diff --git a/README b/README index 9b18a3fe3195..1789fbe67ed2 100644 --- a/README +++ b/README @@ -8,7 +8,6 @@ http://code.google.com/p/dart. Here's a brief guide to what's in here: -compiler/ Dart static analyzer. editor/ Eclipse-based standalone Dart IDE. lib/ Libraries that ship with the Dart runtime (core, html, etc.). pkg/ Packages that are not shipped with the core runtime. diff --git a/README.dart-sdk b/README.dart-sdk index 8a5c750265f6..c0c4b0dc96e0 100644 --- a/README.dart-sdk +++ b/README.dart-sdk @@ -8,7 +8,6 @@ bin/ Binaries/scripts to compile, run, and manage Dart applications. dart Dart virtual machine dart2js Dart-to-JavaScript compiler dartanalyzer Dart static analyzer - dart_analyzer The older, deprecated Dart static analyzer dartdoc Dart documentation generator pub Pub, the Dart package manager diff --git a/compiler/.gitignore b/compiler/.gitignore deleted file mode 100644 index 5a9c6a0cf0ba..000000000000 --- a/compiler/.gitignore +++ /dev/null @@ -1,41 +0,0 @@ -/compiler -/third_party -/compiler_corelib_sources.gypi -/compiler_corelib_sources.xml -/corelib_sources.gypi -/corelib_sources.xml -/domlib_sources.gypi -/domlib_sources.xml -/htmllib_sources.gypi -/htmllib_sources.xml -/isolatelib_sources.gypi -/isolatelib_sources.xml -/jsonlib_sources.gypi -/jsonlib_sources.xml -/sources.gypi -/sources.txt -/sources.xml -/test_sources.gypi -/test_sources.txt -/test_sources.xml -/out -/xcodebuild -/Debug -/DebugARM -/DebugIA32 -/DebugSIMARM -/DebugX64 -/Release -/ReleaseARM -/ReleaseIA32 -/ReleaseSIMARM -/ReleaseX64 -/Makefile -/*.Makefile -/*.sln -/*.target.mk -/*.vcproj -/*.vcxproj -/*.vcxproj.filters -/*.vcxproj.user -/*.xcodeproj diff --git a/compiler/README b/compiler/README deleted file mode 100644 index 4a2c250ba056..000000000000 --- a/compiler/README +++ /dev/null @@ -1,2 +0,0 @@ -This directory is a placeholder for the eventual Dart compiler. -The Dart compiler consists of among others a Dart front-end, a Dart->JS backend, a Dart->Dart backend, tree-shaking tools, minification tools. diff --git a/compiler/api.dart b/compiler/api.dart deleted file mode 100644 index 660dd83650fc..000000000000 --- a/compiler/api.dart +++ /dev/null @@ -1,5 +0,0 @@ -library api; -// dart:core is implicit -import "dart:html"; -import "dart:json"; -import "dart:isolate"; diff --git a/compiler/build.xml b/compiler/build.xml deleted file mode 100644 index 7e77b0e98a20..000000000000 --- a/compiler/build.xml +++ /dev/null @@ -1,185 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/compiler/dart-compiler.gyp b/compiler/dart-compiler.gyp deleted file mode 100644 index 7e589e9e966a..000000000000 --- a/compiler/dart-compiler.gyp +++ /dev/null @@ -1,80 +0,0 @@ -# Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -# for details. All rights reserved. Use of this source code is governed by a -# BSD-style license that can be found in the LICENSE file. - -{ - 'includes': [ - 'sources.gypi', - 'test_sources.gypi', - ], - 'targets': [ - { - 'target_name': 'dart_analyzer', - 'type': 'none', - 'conditions': [ - [ 'OS!="win"', { - 'variables': { - 'script_suffix': '', - }, - }], - [ 'OS=="win"', { - 'variables': { - 'script_suffix': '.bat', - }, - }], - ], - 'actions': [ - { - 'action_name': 'build_dart_analyzer', - 'inputs': [ - 'sources.gypi', - 'test_sources.gypi', - '<@(java_sources)', - '<@(java_resources)', - '<@(javatests_sources)', - '<@(javatests_resources)', - 'dart_analyzer.xml', - 'scripts/dart_analyzer.sh', - 'scripts/dart_analyzer.bat', - 'scripts/analyzer_metrics.sh', - '../third_party/args4j/2.0.12/args4j-2.0.12.jar', - '../third_party/guava/r13/guava-13.0.1.jar', - '../third_party/hamcrest/v1_3/hamcrest-core-1.3.0RC2.jar', - '../third_party/hamcrest/v1_3/hamcrest-generator-1.3.0RC2.jar', - '../third_party/hamcrest/v1_3/hamcrest-integration-1.3.0RC2.jar', - '../third_party/hamcrest/v1_3/hamcrest-library-1.3.0RC2.jar', - ], - 'outputs': [ - '<(INTERMEDIATE_DIR)/<(_target_name)/tests.jar', - '<(PRODUCT_DIR)/analyzer/bin/dart_analyzer', - '<(PRODUCT_DIR)/analyzer/bin/dart_analyzer.bat', - '<(PRODUCT_DIR)/analyzer/util/analyzer/dart_analyzer.jar', - '<(PRODUCT_DIR)/analyzer/util/analyzer/args4j/2.0.12/args4j-2.0.12.jar', - '<(PRODUCT_DIR)/analyzer/util/analyzer/guava/r13/guava-13.0.1.jar', - ], - 'action' : [ - '../third_party/apache_ant/1.8.4/bin/ant<(script_suffix)', - '-f', 'dart_analyzer.xml', - '-Dbuild.dir=<(INTERMEDIATE_DIR)/<(_target_name)', - '-Ddist.dir=<(PRODUCT_DIR)/analyzer', - 'clean', - 'dist', - 'tests.jar', - ], - 'message': 'Building dart_analyzer.', - }, - { - 'action_name': 'copy_tests', - 'inputs': [ '<(INTERMEDIATE_DIR)/<(_target_name)/tests.jar' ], - 'outputs': [ '<(PRODUCT_DIR)/analyzer/dart_analyzer_tests.jar' ], - 'action': [ 'cp', '<@(_inputs)', '<@(_outputs)' ] - }, - ], - }, - { - # GYP won't generate a catch-all target if there's only one target. - 'target_name': 'dummy', - 'type': 'none', - }, - ], -} diff --git a/compiler/dart_analyzer.mf b/compiler/dart_analyzer.mf deleted file mode 100644 index f85084d04a39..000000000000 --- a/compiler/dart_analyzer.mf +++ /dev/null @@ -1,3 +0,0 @@ -Manifest-Version: 1.0 -Main-Class: com.google.dart.compiler.DartCompiler -Class-Path: deploy_deploy.jar diff --git a/compiler/dart_analyzer.xml b/compiler/dart_analyzer.xml deleted file mode 100644 index ff63f2f5b7c2..000000000000 --- a/compiler/dart_analyzer.xml +++ /dev/null @@ -1,190 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/compiler/dartium.gyp b/compiler/dartium.gyp deleted file mode 100644 index 83a32e96fbff..000000000000 --- a/compiler/dartium.gyp +++ /dev/null @@ -1,39 +0,0 @@ -# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -# for details. All rights reserved. Use of this source code is governed by a -# BSD-style license that can be found in the LICENSE file. - -# TODO(vsm): Remove this file and use dart.gyp once that can be pulled -# into the dartium build. -{ - 'includes': [ - # TODO(mmendez): Add the appropriate gypi includes here. - ], - 'targets': [ - { - 'target_name': 'dartc', - 'type': 'none', - 'actions': [ - { - 'action_name': 'Build and test', - 'inputs': [ - ], - 'outputs': [ - 'dummy_target', - ], - 'action' : [ - '../third_party/apache_ant/1.8.4/bin/ant', - '-Dbuild.dir=<(PRODUCT_DIR)/ant-out', - 'clean', - 'dist', - ], - 'message': 'Building dartc.', - }, - ], - }, - { - # GYP won't generate a catch-all target if there's only one target. - 'target_name': 'dummy', - 'type': 'none', - }, - ], -} diff --git a/compiler/eclipse.workspace/README.txt b/compiler/eclipse.workspace/README.txt deleted file mode 100644 index 3f0eaa07bb40..000000000000 --- a/compiler/eclipse.workspace/README.txt +++ /dev/null @@ -1,49 +0,0 @@ -This is an Eclipse workspace for Helios Service Release 2. - -HOW TO - -1. When you open Eclipse the first time, it will ask you to create a - workspace or select an existing one. You can use this directory as - workspace, or you can choose a different one. - -2. If you're already using Eclipse, you can either switch to a new - workspace (File > Switch Workspace) or use your current workspace. - -3. Add the following "Path Variable" to your workspace: - (Open Preferences... > General > Workspace > Linked Resources) - DART_TRUNK: point to the root of your checkout - - -4. Add a "Classpath Variable" to your workspace called DART_TRUNK - that points to the same directory as your DART_TRUNK path variable. - (Open Preferences... > Java > Build Path > Classpath Variables). - -5. Regardless if you're using this directory as a workspace, you have - to import the projects (File > Import... > General > Existing - Projects into Workspace). - -6. Click "Next >" - -7. Select root directory. Browse to: compiler/eclipse.workspace. - -8. It should find and select two projects (dartc and tests). - -9. Click Finish. (At this point Eclipse may get stuck, if so, exit - Eclipse by right-clicking on the dock icon, and restart). - -10. Open Preferences... > Java > Compiler > Errors/Warnings > Potential - programming problems. Change "Serializable class without - serialVersionUID" to "Ignore". - -11. Import the launch configuration (File > Import... > Run/Debug > - Launch Configurations). - -12. Click "Next >" - -13. In SVN, browse to: compiler/eclipse.workspace/tests. - -14. Select "tests". - -15. Click Finish. - -16. Try running the tests: Run > Run History > dartc test suites. diff --git a/compiler/eclipse.workspace/dartc/.classpath b/compiler/eclipse.workspace/dartc/.classpath deleted file mode 100644 index 12f70798c6d7..000000000000 --- a/compiler/eclipse.workspace/dartc/.classpath +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/compiler/eclipse.workspace/dartc/.gitignore b/compiler/eclipse.workspace/dartc/.gitignore deleted file mode 100644 index 1f57b975cdf5..000000000000 --- a/compiler/eclipse.workspace/dartc/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/output diff --git a/compiler/eclipse.workspace/dartc/.project b/compiler/eclipse.workspace/dartc/.project deleted file mode 100644 index 58e595c013dc..000000000000 --- a/compiler/eclipse.workspace/dartc/.project +++ /dev/null @@ -1,24 +0,0 @@ - - - dartc - - - - - - org.eclipse.jdt.core.javabuilder - - - - - - org.eclipse.jdt.core.javanature - - - - src - 2 - DART_TRUNK/compiler/java - - - diff --git a/compiler/eclipse.workspace/tests/.classpath b/compiler/eclipse.workspace/tests/.classpath deleted file mode 100644 index 704cbcde6b99..000000000000 --- a/compiler/eclipse.workspace/tests/.classpath +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/compiler/eclipse.workspace/tests/.gitignore b/compiler/eclipse.workspace/tests/.gitignore deleted file mode 100644 index 4ab5c99ac328..000000000000 --- a/compiler/eclipse.workspace/tests/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/output -/.settings diff --git a/compiler/eclipse.workspace/tests/.project b/compiler/eclipse.workspace/tests/.project deleted file mode 100644 index 980f025facd9..000000000000 --- a/compiler/eclipse.workspace/tests/.project +++ /dev/null @@ -1,118 +0,0 @@ - - - tests - - - - - - org.eclipse.jdt.core.javabuilder - - - - - - org.eclipse.jdt.core.javanature - - - - cases - 2 - DART_TRUNK/compiler/javatests - - - suites - 2 - DART_TRUNK/compiler/javatests - - - test.py - 1 - DART_TRUNK/tools/test.py - - - imported/third_party/java_src/dart/corelib/tests - 2 - DART_TRUNK/corelib/tests - - - imported/third_party/java_src/dart/execution/runtime/tests - 2 - DART_TRUNK/runtime/tests - - - - - 1311331907127 - cases - 22 - - org.eclipse.ui.ide.multiFilter - 1.0-name-matches-false-false-*Tests.java - - - - 1311331781529 - imported - 21 - - org.eclipse.ui.ide.multiFilter - 1.0-name-matches-false-false-*.dart - - - - 1311331571786 - jscomp - 21 - - org.eclipse.ui.ide.multiFilter - 1.0-name-matches-false-false-*OptTests.java - - - - 1311331079908 - suites - 21 - - org.eclipse.ui.ide.multiFilter - 1.0-name-matches-true-false-*Tests.java - - - - 1311331715338 - cases/com/google/dart/compiler - 10 - - org.eclipse.ui.ide.multiFilter - 1.0-name-matches-false-false-vm - - - - 1311331633045 - jscomp/com/google/dart/compiler - 10 - - org.eclipse.ui.ide.multiFilter - 1.0-name-matches-false-false-vm - - - - 1311331190572 - suites/com/google/dart/compiler - 10 - - org.eclipse.ui.ide.multiFilter - 1.0-name-matches-false-false-vm - - - - 1311331455715 - suites/com/google/dart/compiler/end2end - 6 - - org.eclipse.ui.ide.multiFilter - 1.0-name-matches-false-false-*OptTests.java - - - - diff --git a/compiler/eclipse.workspace/tests/SharedTests.launch b/compiler/eclipse.workspace/tests/SharedTests.launch deleted file mode 100644 index 7e43202a0688..000000000000 --- a/compiler/eclipse.workspace/tests/SharedTests.launch +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/compiler/eclipse.workspace/tests/TestSharedTests.launch b/compiler/eclipse.workspace/tests/TestSharedTests.launch deleted file mode 100644 index 6854d4edc4ca..000000000000 --- a/compiler/eclipse.workspace/tests/TestSharedTests.launch +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/compiler/eclipse.workspace/tests/dartc_tests_suites.launch b/compiler/eclipse.workspace/tests/dartc_tests_suites.launch deleted file mode 100644 index 4570ece0d572..000000000000 --- a/compiler/eclipse.workspace/tests/dartc_tests_suites.launch +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/compiler/generate_systemlibrary_list.py b/compiler/generate_systemlibrary_list.py deleted file mode 100644 index 175443629656..000000000000 --- a/compiler/generate_systemlibrary_list.py +++ /dev/null @@ -1,122 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -# for details. All rights reserved. Use of this source code is governed by a -# BSD-style license that can be found in the LICENSE file. - -from __future__ import with_statement -import StringIO -import os -import sys -import re -from collections import deque - -class GenerateError(Exception): - - def __init__(self, value): - self.value = value - - def __str__(self): - return repr(self.value) - - -class Generator: - - def __init__(self, base_directory, name, output, path, *includes): - self.base_directory = base_directory - self.name = name - self.output = output - self.path = path - self.includes = set() - for x in includes: - self.includes.add(x) - self.sources = [] - self.resources = [] - - def _list_files(self): - drain = deque() - drain.extend(self.includes) - while len(drain) > 0: - target = drain.popleft() - # Avoid circular dependencies - if target in self.resources: - continue - if (target.startswith("dart:")): - continue - self.resources.append(target) - if (target.endswith(".dart")): - with open(os.path.join(self.base_directory,self.path,target),"r") as fobj: - text = fobj.read() - file_sources = re.findall(r"#source\(['\"](?P.*)['\"]\);",text) - file_native = re.findall(r"#native\(['\"](?P.*)['\"]\);",text) - file_imports = re.findall(r"#import\(['\"](?P.*)['\"]\);",text) - self.resources.extend(file_sources) - self.resources.extend(file_native) - drain.extend(file_imports) - self.sources.sort() - self.resources.sort() - - def _print_gypi_files(self, out, name, files): - out.write(" '%s': [\n" % name) - for filename in files: - out.write(" '%s/%s',\n" % (self.path, filename)) - out.write(" ],\n") - - def _print_ant_files(self, out, name, files): - out.write(" \n" % (name, self.path)) - for filename in files: - out.write(" \n" % filename) - out.write(" \n") - out.write(" \n" - % (name, name)) - out.write(" \n" % self.path) - out.write(" \n") - - def _make_output(self, file_name): - if os.path.exists(file_name): - return StringIO.StringIO() - else: - return file(file_name, 'w') - - def _close(self, file_name, output): - if not isinstance(output, StringIO.StringIO): - output.close() - return - new_text = output.getvalue() - output.close() - with open(file_name, 'r') as f: - old_text = f.read() - if old_text == new_text: - return - sys.stderr.write('Updating %s\n' % file_name) - with open(file_name, 'w') as f: - f.write(new_text) - - def generate(self): - self._list_files() - file_name = self.output + '.gypi'; - gypi = self._make_output(file_name) - gypi.write("{\n 'variables': {\n") - self._print_gypi_files(gypi, self.name + '_sources', self.sources) - self._print_gypi_files(gypi, self.name + '_resources', self.resources) - gypi.write(" },\n}\n") - self._close(file_name, gypi) - file_name = self.output + '.xml' - ant = self._make_output(file_name) - ant.write("\n") - self._print_ant_files(ant, self.name + '_sources', self.sources) - self._print_ant_files(ant, self.name + '_resources', self.resources) - ant.write("\n") - self._close(file_name, ant) - - -def Main(script_name = None, name = None, output = None, path = None, - *rest): - if not path: - raise GenerateError("usage: %s NAME OUTPUT PATH EXCLUDE_DIR_NAME ..." - % script_name) - base_directory = os.path.dirname(output) - Generator(base_directory, name, output, path, *rest).generate() - - -if __name__ == '__main__': - sys.exit(Main(*sys.argv)) diff --git a/compiler/java/com/google/dart/compiler/CommandLineOptions.java b/compiler/java/com/google/dart/compiler/CommandLineOptions.java deleted file mode 100644 index 0e3ed28b1226..000000000000 --- a/compiler/java/com/google/dart/compiler/CommandLineOptions.java +++ /dev/null @@ -1,347 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import com.google.common.collect.Lists; -import com.google.dart.compiler.CompilerConfiguration.ErrorFormat; -import com.google.dart.compiler.util.apache.StringUtils; - -import org.kohsuke.args4j.Argument; -import org.kohsuke.args4j.CmdLineException; -import org.kohsuke.args4j.CmdLineParser; -import org.kohsuke.args4j.Option; - -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * Options that can be specified on the command line. - */ -public class CommandLineOptions { - - /** - * Command line options accepted by the {@link DartCompiler} entry point. - */ - public static class CompilerOptions { - - @Option(name = "--batch", aliases = { "-batch" }, - usage = "Batch mode (for unit testing)") - private boolean batch = false; - - @Option(name = "--error_format", - usage = "Format errors as normal or machine") - private String errorFormat = ""; - - @Option(name = "--machine", // - usage = "Print errors in a format suitable for parsing") - private boolean machineFormat = false; - - @Option(name = "--extended-exit-code", - usage = "0 - clean; 1 - has warnings; 2 - has errors") - private boolean extendedExitCode = false; - - @Option(name = "--enable_type_checks", - usage = "Generate runtime type checks") - private boolean developerModeChecks = false; - - @Option(name = "--ignore-unrecognized-flags", - usage = "Ignore unrecognized command line flags") - private boolean ignoreUnrecognizedFlags = false; - - @Option(name = "--jvm-metrics-detail", - usage = "Display summary (default) or\n verbose metrics") - private String jvmMetricDetail = "summary"; - - @Option(name = "--jvm-metrics-format", - usage = "Output metrics in tabular (default)\n or pretty format") - private String jvmMetricFormat = "tabular"; - - @Option(name = "--jvm-metrics-type", - usage = "Comma-separated list to display:\n " - + " all: (default) all stat types\n " - + " gc: show garbage collection stats\n " - + " mem: show memory stats\n " - + " jit: show jit stats") - private String jvmMetricType = "all"; - - // leave the command line flag for legacy purposes. - @SuppressWarnings("unused") - @Option(name = "--noincremental", - usage = "Disable incremental compilation (default)") - private boolean noincremental = true; // not used, just a placeholder for arg parsing - - @Option(name = "--incremental", - usage = "Enable incremental compilation") - private boolean incremental = false; - - @Option(name = "--work", aliases = { "-out" }, - usage = "Directory to receive compiler output\n for future incremental builds") - private File workDirectory = new File("out"); - - @Option(name = "--help", aliases = { "-?", "-help" }, - usage = "Prints this help message") - private boolean showHelp = false; - - @Option(name = "--jvm-metrics", - usage = "Print jvm metrics at end of compile") - private boolean showJvmMetrics = false; - - @Option(name = "--metrics", - usage = "Print compilation metrics") - private boolean showMetrics = false; - - @Option(name = "--fatal-type-errors", aliases = { "-fatal-type-errors" }, - usage = "Treat type errors as fatal") - private boolean typeErrorsAreFatal = false; - - @Option(name = "--fatal-warnings", aliases = { "-Werror" }, - usage = "Treat non-type warnings as fatal") - private boolean warningsAreFatal = false; - - @Option(name = "--platform", - usage = "Platform libraries to analyze (e.g. dartium, vm, dart2js, any)") - private String platformName = PackageLibraryManager.DEFAULT_PLATFORM; - - @Option(name = "--dart-sdk", - usage = "Path to dart sdk. (system property com.google.dart.sdk)") - private File dartSdkPath = PackageLibraryManager.DEFAULT_SDK_PATH; - - @Option(name = "--package-root", - usage = "Root directory used for the package: scheme") - private File packageRoot = PackageLibraryManager.DEFAULT_PACKAGE_ROOT; - - @Option(name = "--show-sdk-warnings", usage = "show warnings from SDK source") - private boolean showSdkWarnings = false; - - @Option(name = "--source-from-ast", - usage = "For debugging, reconstitute source code from the parsed AST.") - private boolean showSourceFromAst = false; - - @Option(name = "--resolve-on-parse-error", - usage = "For debugging, continue on with resolution even if there are parse errors.") - private boolean resolveDespiteParseErrors; - - @Option(name = "--type-checks-for-inferred-types", - usage = "[not in spec] Enables 'interface has no method/field' for receivers with inferred types.") - private boolean typeChecksForInferredTypes = false; - - @Option(name = "--version", - usage = "Show analyzer version") - private boolean showVersion = false; - - @Argument - private final List sourceFiles = new ArrayList(); - - public String getJvmMetricOptions() { - if (!showJvmMetrics) { - return null; - } - return jvmMetricDetail + ":" + jvmMetricFormat + ":" + jvmMetricType; - } - - public String getPlatformName() { - return platformName; - } - - /** - * @return the packageRoot - */ - public File getPackageRoot() { - return packageRoot; - } - - public File getDartSdkPath() { - return dartSdkPath; - } - - public boolean extendedExitCode() { - return extendedExitCode; - } - - /** - * Returns whether warnings from SDK files should be suppressed. - */ - public boolean suppressSdkWarnings() { - return !showSdkWarnings; - } - - /** - * Returns whether inferred types should be used for type checks. - */ - public boolean typeChecksForInferredTypes() { - return this.typeChecksForInferredTypes; - } - - /** - * Returns whether "no such member" should be reported for classes which implement - * "noSuchMethod" method. - */ - public boolean reportNoMemberWhenHasInterceptor() { - return true; - } - - /** - * Returns the list of files passed to the compiler. - */ - public List getSourceFiles() { - return sourceFiles; - } - - /** - * Returns the path to receive compiler intermediate output. - */ - public File getWorkDirectory() { - return workDirectory; - } - - public boolean ignoreUnrecognizedFlags() { - return ignoreUnrecognizedFlags; - } - - /** - * Returns whether the compiler should attempt to incrementally recompile. - */ - public boolean buildIncrementally() { - return incremental; - } - - public boolean shouldBatch() { - return batch; - } - - public boolean resolveDespiteParseErrors() { - return resolveDespiteParseErrors; - } - - /** - * Returns true if the compiler should print it's help message. - */ - public boolean showHelp() { - return showHelp; - } - - public boolean showJvmMetrics() { - return showJvmMetrics; - } - - public boolean showMetrics() { - return showMetrics; - } - - public boolean showVersion() { - return showVersion; - } - - /** - * if true, run the AST back through the DartSourceVisitor to create source - * from the parsed AST and print to stdout. - */ - public boolean showSourceFromAst() { - return showSourceFromAst; - } - - /** - * Returns whether type errors are fatal. - */ - public boolean typeErrorsAreFatal() { - return typeErrorsAreFatal; - } - - /** - * Returns whether warnings (excluding type warnings) are fatal. - */ - public boolean warningsAreFatal() { - return warningsAreFatal; - } - - public boolean developerModeChecks() { - return developerModeChecks; - } - - /** - * @return the format to use for printing errors - */ - public ErrorFormat printErrorFormat() { - if (machineFormat) { - return ErrorFormat.MACHINE; - } - - String lowerError = errorFormat.toLowerCase(); - - if ("machine".equals(lowerError)) { - return ErrorFormat.MACHINE; - } - - return ErrorFormat.NORMAL; - } - } - - /** - * Parses command line options, handling the feature to ignore unrecognized - * flags. - * - * If one of the options is 'ignore-unrecognized-flags', then any exceptions - * for 'not a valid option' are suppressed. - * - * @param args Arguments passed from main() - * @param parsedOptions [out parameter] parsed options - * @throws CmdLineException Thrown if there is a problem parsing the options. - */ - public static CmdLineParser parse(String[] args, CompilerOptions parsedOptions) - throws CmdLineException { - // convert new "--name=value" into old "--name value" style - { - List argList = Lists.newArrayList(); - for (String arg : args) { - String[] parts = StringUtils.split(arg, '='); - Collections.addAll(argList, parts); - } - args = argList.toArray(new String[argList.size()]); - } - - boolean ignoreUnrecognized = false; - for (String arg : args) { - if (arg.equals("--ignore-unrecognized-flags")) { - ignoreUnrecognized = true; - break; - } - } - - if (!ignoreUnrecognized) { - CmdLineParser cmdLineParser = new CmdLineParser(parsedOptions); - cmdLineParser.parseArgument(args); - return cmdLineParser; - } - CmdLineParser cmdLineParser = new CmdLineParser(parsedOptions); - for (int i = 0, len = args.length; i < len; i++) { - try { - cmdLineParser.parseArgument(args); - } catch (CmdLineException e) { - String msg = e.getMessage(); - - if (e.getMessage().endsWith(" is not a valid option")) { - String option = msg.substring(1); - int closeQuote = option.indexOf('\"'); - option = option.substring(0, closeQuote); - List newArgs = Lists.newArrayList(); - for (String arg : args) { - if (arg.equals(option)) { - System.out.println("(Ignoring unrecognized flag: " + arg + ")"); - continue; - } - newArgs.add(arg); - } - args = newArgs.toArray(new String[newArgs.size()]); - cmdLineParser = new CmdLineParser(parsedOptions); - continue; - } - } - break; - } - return cmdLineParser; - } -} diff --git a/compiler/java/com/google/dart/compiler/CompilerConfiguration.java b/compiler/java/com/google/dart/compiler/CompilerConfiguration.java deleted file mode 100644 index 7216edb4d5ce..000000000000 --- a/compiler/java/com/google/dart/compiler/CompilerConfiguration.java +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import com.google.dart.compiler.CommandLineOptions.CompilerOptions; -import com.google.dart.compiler.metrics.CompilerMetrics; - -import java.io.File; -import java.util.List; - -/** - * A configuration for the Dart compiler specifying which phases will be executed. - */ -public interface CompilerConfiguration { - - enum ErrorFormat { - NORMAL, // Library/File, line, message - MACHINE, // All information including severity, subsystem, etc - } - - List getPhases(); - - /** - * Indicates whether developer-mode runtime checks are needed. - * @return true if developer-mode checks should be inserted, false if not - */ - boolean developerModeChecks(); - - /** - * Returns the {@link CompilerMetrics} instance or null if metrics should not be - * recorded. - * - * @return the metrics instance, null if metrics should not be recorded - */ - CompilerMetrics getCompilerMetrics(); - - /** - * Returns a comma-separated string list of options for displaying jvm metrics. - * Returns null if jvm metrics are not enabled. - */ - String getJvmMetricOptions(); - - boolean typeErrorsAreFatal(); - - boolean warningsAreFatal(); - - /** - * Returns true if the compiler should try to resolve - * even after having seen parse-errors. - */ - boolean resolveDespiteParseErrors(); - - /** - * Temporary flag to turn on incremental compilation. This will be removed once we're certain - * incremental compilation is correct. - */ - boolean incremental(); - - /** - * The work directory where incremental build output is stored between invocations. - */ - File getOutputDirectory(); - - /** - * Returns the error formatting the compiler should print with - */ - ErrorFormat printErrorFormat(); - - /** - * Return the system library corresponding to the specified "dart:" spec. - */ - LibrarySource getSystemLibraryFor(String importSpec); - - /** - * Return the system library manager - */ - PackageLibraryManager getPackageLibraryManager(); - - /** - * Return {@link CompilerOptions} instance. - * @return command line options passed to the compiler. - */ - CompilerOptions getCompilerOptions(); -} diff --git a/compiler/java/com/google/dart/compiler/DartArtifactProvider.java b/compiler/java/com/google/dart/compiler/DartArtifactProvider.java deleted file mode 100644 index a3b165dce57c..000000000000 --- a/compiler/java/com/google/dart/compiler/DartArtifactProvider.java +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import java.io.IOException; -import java.io.Reader; -import java.io.Writer; -import java.net.URI; - -/** - * Abstract class that {@link DartCompiler} consumers can use to specify where - * generated files are located. - */ -public abstract class DartArtifactProvider { - - /** - * Gets a reader for an artifact associated with the specified source, which - * must have been written to {@link #getArtifactWriter(Source, String, String)}. The - * caller is responsible for closing the reader. Only one artifact may be - * associated with the given extension. - * - * @param source the source file (not null) - * @param part a component of the source file to get a reader for (may be empty). - * @param extension the file extension for this artifact (not - * null, not empty) - * @return the reader, or null if there is no such artifact - */ - public abstract Reader getArtifactReader(Source source, String part, String extension) - throws IOException; - - /** - * Gets the {@link URI} for an artifact associated with this source. - * - * @param source the source file (not null) - * @param part a component of the source file to get a reader for (may be empty). - * @param extension the file extension for this artifact (not - * null, not empty) - */ - public abstract URI getArtifactUri(Source source, String part, String extension); - - /** - * Gets a writer for an artifact associated with this source. The caller is - * responsible for closing the writer. Only one artifact may be associated - * with the given extension. - * - * @param source the source file (not null) - * @param part a component of the source file to get a reader for (may be empty). - * @param extension the file extension for this artifact (not - * null, not empty) - */ - public abstract Writer getArtifactWriter(Source source, String part, String extension) - throws IOException; - - /** - * Determines whether an artifact for the specified source is out of date - * with respect to some other source. - * - * @param source the source file to check (not null) - * @param base the artifact's base source (not null) - * @param extension the file extension for this artifact (not - * null, not empty) - * @return true if out of date - */ - public abstract boolean isOutOfDate(Source source, Source base, String extension); -} diff --git a/compiler/java/com/google/dart/compiler/DartCompilationError.java b/compiler/java/com/google/dart/compiler/DartCompilationError.java deleted file mode 100644 index ddf7e3314718..000000000000 --- a/compiler/java/com/google/dart/compiler/DartCompilationError.java +++ /dev/null @@ -1,191 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import com.google.dart.compiler.common.HasSourceInfo; -import com.google.dart.compiler.common.SourceInfo; -import com.google.dart.compiler.parser.DartScanner.Location; - -/** - * Information about a compilation error. - * - * @see DartCompilerListener - */ -public class DartCompilationError { - - /** - * The character offset from the beginning of the source (zero based) where the error occurred. - */ - private int offset = 0; - - /** - * The number of characters from the startPosition to the end of the source which encompasses the - * compilation error. - */ - private int length = 0; - - /** - * The line number in the source (one based) where the error occurred or -1 if it is undefined. - */ - private int lineNumber = -1; - - /** - * The column number in the source (one based) where the error occurred or -1 if it is undefined. - */ - private int columnNumber = -1; - - /** - * The error code associated with the error. - */ - private ErrorCode errorCode; - - /** - * The compilation error message. - */ - private String message; - - /** - * The source in which the error occurred or null if unknown. - */ - private Source source; - - /** - * Compilation error for the specified {@link Source}, without location. - * - * @param source the {@link Source} for which the exception occurred - * @param errorCode the {@link ErrorCode} to be associated with this error - * @param arguments the arguments used to build the error message - */ - public DartCompilationError(Source source, ErrorCode errorCode, Object... arguments) { - this.source = source; - this.errorCode = errorCode; - this.message = String.format(errorCode.getMessage(), arguments); - } - - /** - * Compilation error at the {@link SourceInfo} from specified {@link HasSourceInfo}. - * - * @param hasSourceInfo the provider of {@link SourceInfo} where the error occurred - * @param errorCode the {@link ErrorCode} to be associated with this error - * @param arguments the arguments used to build the error message - */ - public DartCompilationError(HasSourceInfo hasSourceInfo, ErrorCode errorCode, Object... arguments) { - this(hasSourceInfo.getSourceInfo(), errorCode, arguments); - } - - /** - * Compilation error at the specified {@link SourceInfo}. - * - * @param sourceInfo the {@link SourceInfo} where the error occurred - * @param errorCode the {@link ErrorCode} to be associated with this error - * @param arguments the arguments used to build the error message - */ - public DartCompilationError(SourceInfo sourceInfo, ErrorCode errorCode, Object... arguments) { - this.source = sourceInfo.getSource(); - this.lineNumber = sourceInfo.getLine(); - this.columnNumber = sourceInfo.getColumn(); - this.offset = sourceInfo.getOffset(); - this.length = sourceInfo.getLength(); - this.errorCode = errorCode; - this.message = String.format(errorCode.getMessage(), arguments); - } - - /** - * Instantiate a new instance representing a compilation error at the specified location. - * - * @param source the source reference - * @param location the source range where the error occurred - * @param errorCode the error code to be associated with this error - * @param arguments the arguments used to build the error message - */ - public DartCompilationError(Source source, - Location location, - ErrorCode errorCode, - Object... arguments) { - this.source = source; - this.errorCode = errorCode; - this.message = String.format(errorCode.getMessage(), arguments); - if (location != null) { - offset = location.getBegin(); - SourceInfo sourceInfo = new SourceInfo(source, offset, 0); - lineNumber = sourceInfo.getLine(); - columnNumber = sourceInfo.getColumn(); - length = location.getEnd() - offset; - } - } - - /** - * The column number in the source (one based) where the error occurred. - */ - public int getColumnNumber() { - return columnNumber; - } - - /** - * Return the error code associated with the error. - */ - public ErrorCode getErrorCode() { - return errorCode; - } - - /** - * The line number in the source (one based) where the error occurred. - */ - public int getLineNumber() { - return lineNumber; - } - - /** - * The compilation error message. - */ - public String getMessage() { - return message; - } - - /** - * Return the source in which the error occurred or null if unknown. - */ - public Source getSource() { - return source; - } - - /** - * The character offset from the beginning of the source (zero based) where the error occurred. - */ - public int getStartPosition() { - return offset; - } - - /** - * The length of the error location. - */ - public int getLength() { - return length; - } - - @Override - public int hashCode() { - int hashCode = offset; - hashCode ^= (message != null) ? message.hashCode() : 0; - hashCode ^= (source != null) ? source.getName().hashCode() : 0; - return hashCode; - } - - /** - * Set the source in which the error occurred or null if unknown. - */ - public void setSource(Source source) { - this.source = source; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append((source != null) ? source.getName() : ""); - sb.append("(" + lineNumber + ":" + columnNumber + "): "); - sb.append(message); - return sb.toString(); - } -} diff --git a/compiler/java/com/google/dart/compiler/DartCompilationPhase.java b/compiler/java/com/google/dart/compiler/DartCompilationPhase.java deleted file mode 100644 index 24a034126a02..000000000000 --- a/compiler/java/com/google/dart/compiler/DartCompilationPhase.java +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import com.google.dart.compiler.ast.DartUnit; -import com.google.dart.compiler.resolver.CoreTypeProvider; - -/** - * A compiler phase that processes a unit and possibly transforms it or reports - * compilation errors. - */ -public interface DartCompilationPhase { - - /** - * Execute this phase on a unit. - * - * @param unit the program to process - * @param context context where to report error messages - */ - DartUnit exec(DartUnit unit, DartCompilerContext context, CoreTypeProvider typeProvider); -} diff --git a/compiler/java/com/google/dart/compiler/DartCompiler.java b/compiler/java/com/google/dart/compiler/DartCompiler.java deleted file mode 100644 index b939d6a34fc9..000000000000 --- a/compiler/java/com/google/dart/compiler/DartCompiler.java +++ /dev/null @@ -1,1463 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import com.google.common.base.Objects; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import com.google.common.collect.Sets.SetView; -import com.google.common.io.CharStreams; -import com.google.common.io.Closeables; -import com.google.dart.compiler.CommandLineOptions.CompilerOptions; -import com.google.dart.compiler.LibraryDeps.Dependency; -import com.google.dart.compiler.UnitTestBatchRunner.Invocation; -import com.google.dart.compiler.ast.DartDirective; -import com.google.dart.compiler.ast.DartLibraryDirective; -import com.google.dart.compiler.ast.DartNode; -import com.google.dart.compiler.ast.DartPartOfDirective; -import com.google.dart.compiler.ast.DartToSourceVisitor; -import com.google.dart.compiler.ast.DartUnit; -import com.google.dart.compiler.ast.LibraryExport; -import com.google.dart.compiler.ast.LibraryNode; -import com.google.dart.compiler.ast.LibraryUnit; -import com.google.dart.compiler.ast.Modifiers; -import com.google.dart.compiler.common.SourceInfo; -import com.google.dart.compiler.metrics.CompilerMetrics; -import com.google.dart.compiler.metrics.DartEventType; -import com.google.dart.compiler.metrics.JvmMetrics; -import com.google.dart.compiler.metrics.Tracer; -import com.google.dart.compiler.metrics.Tracer.TraceEvent; -import com.google.dart.compiler.parser.DartParser; -import com.google.dart.compiler.resolver.CompileTimeConstantAnalyzer; -import com.google.dart.compiler.resolver.CoreTypeProvider; -import com.google.dart.compiler.resolver.CoreTypeProviderImplementation; -import com.google.dart.compiler.resolver.Element; -import com.google.dart.compiler.resolver.ElementKind; -import com.google.dart.compiler.resolver.Elements; -import com.google.dart.compiler.resolver.LibraryElement; -import com.google.dart.compiler.resolver.MemberBuilder; -import com.google.dart.compiler.resolver.MethodElement; -import com.google.dart.compiler.resolver.Resolver; -import com.google.dart.compiler.resolver.ResolverErrorCode; -import com.google.dart.compiler.resolver.SupertypeResolver; -import com.google.dart.compiler.resolver.TopLevelElementBuilder; -import com.google.dart.compiler.type.TypeAnalyzer; -import com.google.dart.compiler.util.DefaultTextOutput; -import com.google.dart.compiler.util.apache.StringUtils; - -import org.kohsuke.args4j.CmdLineException; -import org.kohsuke.args4j.CmdLineParser; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.PrintStream; -import java.io.Reader; -import java.io.Writer; -import java.net.URI; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -/** - * Entry point for the Dart compiler. - */ -public class DartCompiler { - - static final int RESULT_OK = 0; - static final int RESULT_WARNINGS = 1; - static final int RESULT_ERRORS = 2; - static final int RESULT_OTHER = 127; - - static class Result { - final int code; - final String message; - public Result(int code, String message) { - this.code = code; - this.message = message; - } - Result merge(Result other) { - if (other.code > code) { - return other; - } - return this; - } - } - - public static final String EXTENSION_DEPS = "deps"; - public static final String EXTENSION_LOG = "log"; - public static final String EXTENSION_TIMESTAMP = "timestamp"; - - public static final String CORELIB_URL_SPEC = "dart:core"; - public static final String MAIN_ENTRY_POINT_NAME = "main"; - - private static class Compiler { - private final LibrarySource app; - private final List embeddedLibraries = new ArrayList(); - private final DartCompilerMainContext context; - private final CompilerConfiguration config; - private final Map libraries = new LinkedHashMap(); - private CoreTypeProvider typeProvider; - private final boolean incremental; - private final List phases; - private final LibrarySource coreLibrarySource; - - private Compiler(LibrarySource app, List embedded, CompilerConfiguration config, - DartCompilerMainContext context) { - this.app = app; - this.config = config; - this.phases = config.getPhases(); - this.context = context; - for (LibrarySource library : embedded) { - if (PackageLibraryManager.isDartSpec(library.getName())) { - LibrarySource foundLibrary = context.getSystemLibraryFor(library.getName()); - assert(foundLibrary != null); - embeddedLibraries.add(foundLibrary); - } else { - embeddedLibraries.add(library); - } - } - coreLibrarySource = context.getSystemLibraryFor(CORELIB_URL_SPEC); - assert(coreLibrarySource != null); - embeddedLibraries.add(coreLibrarySource); - - incremental = config.incremental(); - } - - void addResolvedLibraries(Map resolvedLibraries) { - libraries.putAll(resolvedLibraries); - } - - Map getLibraries() { - return libraries; - } - - private void compile() { - TraceEvent logEvent = Tracer.canTrace() ? Tracer.start(DartEventType.COMPILE) : null; - try { - updateAndResolve(); - if (!config.resolveDespiteParseErrors() && context.getErrorCount() > 0) { - return; - } - compileLibraries(); - } catch (IOException e) { - context.onError(new DartCompilationError(app, DartCompilerErrorCode.IO, e.getMessage())); - } finally { - Tracer.end(logEvent); - } - } - - /** - * Update the current application and any referenced libraries and resolve - * them. - * - * @return a {@link LibraryUnit}, maybe null - * @throws IOException on IO errors - the caller must log this if it cares - */ - private LibraryUnit updateAndResolve() throws IOException { - TraceEvent logEvent = Tracer.canTrace() ? Tracer.start(DartEventType.UPDATE_RESOLVE) : null; - - CompilerMetrics compilerMetrics = context.getCompilerMetrics(); - if (compilerMetrics != null) { - compilerMetrics.startUpdateAndResolveTime(); - } - - try { - LibraryUnit library = updateLibraries(app); - importEmbeddedLibraries(); - parseOutOfDateFiles(); - if (incremental) { - addOutOfDateDeps(); - } - if (!config.resolveDespiteParseErrors() && (context.getErrorCount() > 0)) { - return library; - } - buildLibraryScopes(); - LibraryUnit corelibUnit = updateLibraries(coreLibrarySource); - typeProvider = new CoreTypeProviderImplementation(corelibUnit.getElement().getScope(), - context); - resolveLibraries(); - validateLibraryDirectives(); - return library; - } finally { - if(compilerMetrics != null) { - compilerMetrics.endUpdateAndResolveTime(); - } - - Tracer.end(logEvent); - } - } - - /** - * This method reads all libraries. They will be populated from some combination of fully-parsed - * and diet-parser compilation units. - */ - private void parseOutOfDateFiles() throws IOException { - TraceEvent logEvent = - Tracer.canTrace() ? Tracer.start(DartEventType.PARSE_OUTOFDATE) : null; - CompilerMetrics compilerMetrics = context.getCompilerMetrics(); - long parseStart = compilerMetrics != null ? CompilerMetrics.getCPUTime() : 0; - - try { - final Set topLevelSymbolsDiff = Sets.newHashSet(); - for (LibraryUnit lib : getLibrariesToProcess()) { - LibrarySource libSrc = lib.getSource(); - LibraryNode selfSourcePath = lib.getSelfSourcePath(); - - // Load the existing DEPS, or create an empty one. - LibraryDeps deps = lib.getDeps(context); - Set newUnitPaths = Sets.newHashSet(); - - // Parse each compilation unit. - for (LibraryNode sourcePathNode : lib.getSourcePaths()) { - String relPath = sourcePathNode.getText(); - newUnitPaths.add(relPath); - - // Prepare DartSource for "#source" unit. - final DartSource dartSrc = libSrc.getSourceFor(relPath); - if (dartSrc == null || !dartSrc.exists()) { - continue; - } - - if (!incremental - || PackageLibraryManager.isDartUri(libSrc.getUri()) - || isSourceOutOfDate(dartSrc)) { - DartUnit unit = parse(dartSrc, lib.getPrefixes(), false); - // If we just parsed unit of library, report problems. - if (sourcePathNode == selfSourcePath) { - // report "#import" problems - for (LibraryNode importPathNode : lib.getImportPaths()) { - LibrarySource dep = getImportSource(libSrc, importPathNode); - if (dep == null) { - reportMissingSource(context, libSrc, importPathNode); - } - } - // report "#source" problems - for (LibraryNode checkSourcePathNode : lib.getSourcePaths()) { - String checkRelPath = checkSourcePathNode.getText(); - final DartSource checkSource = libSrc.getSourceFor(checkRelPath); - if (checkSource == null || !checkSource.exists()) { - reportMissingSource(context, libSrc, checkSourcePathNode); - } - } - } - - // Process unit, if exists. - if (unit != null) { - if (sourcePathNode == selfSourcePath) { - lib.setSelfDartUnit(unit); - } - // Replace unit within the library. - lib.putUnit(unit); - context.setFilesHaveChanged(); - // Include into top-level symbols diff from current units, already existed or new. - { - LibraryDeps.Source source = deps.getSource(relPath); - Set newTopSymbols = unit.getTopDeclarationNames(); - if (source != null) { - Set oldTopSymbols = source.getTopSymbols(); - SetView diff0 = Sets.symmetricDifference(oldTopSymbols, newTopSymbols); - topLevelSymbolsDiff.addAll(diff0); - } else { - topLevelSymbolsDiff.addAll(newTopSymbols); - } - } - } - } else { - DartUnit dietUnit = parse(dartSrc, lib.getPrefixes(), true); - if (dietUnit != null) { - if (sourcePathNode == selfSourcePath) { - lib.setSelfDartUnit(dietUnit); - } - lib.putUnit(dietUnit); - } - } - } - - // Include into top-level symbols diff from units which disappeared since last compiling. - { - Set oldUnitPaths = deps.getUnitPaths(); - Set disappearedUnitPaths = Sets.difference(oldUnitPaths, newUnitPaths); - for (String relPath : disappearedUnitPaths) { - LibraryDeps.Source source = deps.getSource(relPath); - if (source != null) { - Set oldTopSymbols = source.getTopSymbols(); - topLevelSymbolsDiff.addAll(oldTopSymbols); - } - } - } - } - - // Parse units, which potentially depend on the difference in top-level symbols. - if (!topLevelSymbolsDiff.isEmpty()) { - context.setFilesHaveChanged(); - for (LibraryUnit lib : getLibrariesToProcess()) { - LibrarySource libSrc = lib.getSource(); - LibraryNode selfSourcePath = lib.getSelfSourcePath(); - LibraryDeps deps = lib.getDeps(context); - for (LibraryNode libNode : lib.getSourcePaths()) { - String relPath = libNode.getText(); - // Prepare source dependency. - LibraryDeps.Source source = deps.getSource(relPath); - if (source == null) { - continue; - } - // Check re-compilation conditions. - if (source.shouldRecompileOnAnyTopLevelChange() - || !Sets.intersection(source.getAllSymbols(), topLevelSymbolsDiff).isEmpty() - || !Sets.intersection(source.getHoles(), topLevelSymbolsDiff).isEmpty()) { - DartSource dartSrc = libSrc.getSourceFor(relPath); - if (dartSrc == null || !dartSrc.exists()) { - continue; - } - DartUnit unit = parse(dartSrc, lib.getPrefixes(), false); - if (unit != null) { - if (libNode == selfSourcePath) { - lib.setSelfDartUnit(unit); - } else { - lib.putUnit(unit); - } - } - } - } - } - } - } finally { - if (compilerMetrics != null) { - compilerMetrics.addParseWallTimeNano(CompilerMetrics.getCPUTime() - parseStart); - } - Tracer.end(logEvent); - } - } - - Collection getLibrariesToProcess() { - return libraries.values(); - } - - /** - * This method reads the embedded library sources, making sure they are added - * to the list of libraries to compile. It then adds the libraries as imports - * of all libraries. The import is without prefix. - */ - private void importEmbeddedLibraries() throws IOException { - TraceEvent importEvent = - Tracer.canTrace() ? Tracer.start(DartEventType.IMPORT_EMBEDDED_LIBRARIES) : null; - try { - for (LibrarySource embedded : embeddedLibraries) { - updateLibraries(embedded); - } - - for (LibraryUnit lib : getLibrariesToProcess()) { - for (LibrarySource embedded : embeddedLibraries) { - LibraryUnit imp = libraries.get(embedded.getUri()); - // Check that the current library is not the embedded library, and - // that the current library does not already import the embedded - // library. - if (lib != imp && !lib.hasImport(imp)) { - lib.addImport(imp, null); - } - } - } - } finally { - Tracer.end(importEvent); - } - } - - /** - * This method reads a library source and sets it up with its imports. When it - * completes, it is guaranteed that {@link Compiler#libraries} will be completely populated. - */ - private LibraryUnit updateLibraries(LibrarySource libSrc) throws IOException { - TraceEvent updateEvent = - Tracer.canTrace() ? Tracer.start(DartEventType.UPDATE_LIBRARIES, "name", - libSrc.getName()) : null; - try { - // Avoid cycles. - LibraryUnit lib = libraries.get(libSrc.getUri()); - if (lib != null) { - return lib; - } - - lib = context.getLibraryUnit(libSrc); - // If we could not find the library, continue. The context will report - // the error at the end. - if (lib == null) { - return null; - } - - libraries.put(libSrc.getUri(), lib); - - // Update dependencies. - for (LibraryNode libNode : lib.getImportPaths()) { - LibrarySource dep = getImportSource(libSrc, libNode); - if (dep != null) { - LibraryUnit importedLib = updateLibraries(dep); - lib.addImport(importedLib, libNode); - if (libNode.isExported()) { - lib.addExport(importedLib, libNode); - } - } - } - for (LibraryNode libNode : lib.getExportPaths()) { - LibrarySource dep = getImportSource(libSrc, libNode); - if (dep != null) { - lib.addExport(updateLibraries(dep), libNode); - } - } - return lib; - } finally { - Tracer.end(updateEvent); - } - } - - /** - * @return the {@link LibrarySource} referenced in the "#import" from "libSrc". May be - * null if invalid URI or not existing library. - */ - private LibrarySource getImportSource(LibrarySource libSrc, LibraryNode libNode) - throws IOException { - String libSpec = libNode.getText(); - LibrarySource dep; - try { - if (PackageLibraryManager.isDartSpec(libSpec)) { - dep = context.getSystemLibraryFor(libSpec); - } else { - dep = libSrc.getImportFor(libSpec); - } - } catch (Throwable e) { - return null; - } - if (dep == null || !dep.exists()) { - return null; - } - return dep; - } - - /** - * Determines whether the given source is out-of-date with respect to its artifacts. - */ - private boolean isSourceOutOfDate(DartSource dartSrc) { - TraceEvent logEvent = - Tracer.canTrace() ? Tracer.start(DartEventType.IS_SOURCE_OUTOFDATE, "src", - dartSrc.getName()) : null; - - try { - // If incremental compilation is disabled, just return true to force all - // units to be recompiled. - if (!incremental) { - return true; - } - - TraceEvent timestampEvent = - Tracer.canTrace() ? Tracer.start( - DartEventType.TIMESTAMP_OUTOFDATE, - "src", - dartSrc.getName()) : null; - try { - return context.isOutOfDate(dartSrc, dartSrc, EXTENSION_TIMESTAMP); - } finally { - Tracer.end(timestampEvent); - } - } finally { - Tracer.end(logEvent); - } - } - - /** - * Build scopes for the given libraries. - */ - private void buildLibraryScopes() { - TraceEvent logEvent = - Tracer.canTrace() ? Tracer.start(DartEventType.BUILD_LIB_SCOPES) : null; - try { - Collection libs = getLibrariesToProcess(); - - // Build the class elements declared in the sources of a library. - // Loop can be parallelized. - for (LibraryUnit lib : libs) { - new TopLevelElementBuilder().exec(lib, context); - } - - // The library scope can then be constructed, containing types declared - // in the library, and types declared in the imports. Loop can be parallelized. - for (LibraryUnit lib : libs) { - new TopLevelElementBuilder().fillInLibraryScope(lib, context); - } - } finally { - Tracer.end(logEvent); - } - } - - /** - * Parses compilation units that are out-of-date with respect to their dependencies. - */ - private void addOutOfDateDeps() throws IOException { - TraceEvent logEvent = Tracer.canTrace() ? Tracer.start(DartEventType.ADD_OUTOFDATE) : null; - try { - boolean filesHaveChanged = false; - for (LibraryUnit lib : getLibrariesToProcess()) { - - // Load the existing DEPS, or create an empty one. - LibraryDeps deps = lib.getDeps(context); - - // Prepare all top-level symbols. - Set oldTopLevelSymbols = Sets.newHashSet(); - for (LibraryDeps.Source source : deps.getSources()) { - oldTopLevelSymbols.addAll(source.getTopSymbols()); - } - - // Parse units that are out-of-date with respect to their dependencies. - for (DartUnit unit : lib.getUnits()) { - if (unit.isDiet()) { - String relPath = ((DartSource) unit.getSourceInfo().getSource()).getRelativePath(); - LibraryDeps.Source source = deps.getSource(relPath); - if (isUnitOutOfDate(lib, source)) { - filesHaveChanged = true; - DartSource dartSrc = lib.getSource().getSourceFor(relPath); - if (dartSrc != null && dartSrc.exists()) { - unit = parse(dartSrc, lib.getPrefixes(), false); - if (unit != null) { - lib.putUnit(unit); - } - } - } - } - } - } - - if (filesHaveChanged) { - context.setFilesHaveChanged(); - } - } finally { - Tracer.end(logEvent); - } - } - - /** - * Determines whether the given dependencies are out-of-date. - */ - private boolean isUnitOutOfDate(LibraryUnit lib, LibraryDeps.Source source) { - // If we don't have dependency information, then we can not be sure that nothing changed. - if (source == null) { - return true; - } - // Check all dependencies. - for (Dependency dep : source.getDeps()) { - LibraryUnit depLib = libraries.get(dep.getLibUri()); - if (depLib == null) { - return true; - } - // Prepare unit. - DartUnit depUnit = depLib.getUnit(dep.getUnitName()); - if (depUnit == null) { - return true; - } - // May be unit modified. - if (depUnit.getSourceInfo().getSource().getLastModified() != dep.getLastModified()) { - return true; - } - } - // No changed dependencies. - return false; - } - - /** - * Resolve all libraries. Assume that all library scopes are already built. - */ - private void resolveLibraries() { - TraceEvent logEvent = - Tracer.canTrace() ? Tracer.start(DartEventType.RESOLVE_LIBRARIES) : null; - try { - // TODO(jgw): Optimization: Skip work for libraries that have nothing to - // compile. - - // Resolve super class chain, and build the member elements. Both passes - // need the library scope to be setup. Each for loop can be - // parallelized. - for (LibraryUnit lib : getLibrariesToProcess()) { - for (DartUnit unit : lib.getUnits()) { - // These two method calls can be parallelized. - new SupertypeResolver().exec(unit, context, getTypeProvider()); - new MemberBuilder().exec(unit, context, getTypeProvider()); - } - } - - } finally { - Tracer.end(logEvent); - } - } - - private void validateLibraryDirectives() { - for (LibraryUnit lib : getLibrariesToProcess()) { - // don't need to validate system libraries - if (PackageLibraryManager.isDartUri(lib.getSource().getUri())) { - continue; - } - - // check for #source uniqueness - { - Set includedSourceUris = Sets.newHashSet(); - for (LibraryNode sourceNode : lib.getSourcePaths()) { - String path = sourceNode.getText(); - DartSource source = lib.getSource().getSourceFor(path); - if (source != null) { - URI uri = source.getUri(); - if (includedSourceUris.contains(uri)) { - context.onError(new DartCompilationError(sourceNode.getSourceInfo(), - DartCompilerErrorCode.UNIT_WAS_ALREADY_INCLUDED, uri)); - } - includedSourceUris.add(uri); - } - } - } - - // Validate imports. - boolean hasIO = false; - boolean hasHTML = false; - for (LibraryNode importNode : lib.getImportPaths()) { - String libSpec = importNode.getText(); - hasIO |= "dart:io".equals(libSpec); - hasHTML |= "dart:html".equals(libSpec); - // "dart:mirrors" are not done yet - if ("dart:mirrors".equals(libSpec)) { - context.onError(new DartCompilationError(importNode, - DartCompilerErrorCode.MIRRORS_NOT_FULLY_IMPLEMENTED)); - } - // validate console/web mix - if (hasIO && hasHTML) { - context.onError(new DartCompilationError(importNode.getSourceInfo(), - DartCompilerErrorCode.CONSOLE_WEB_MIX)); - } - } - - // check that each exported library has a library directive - for (LibraryExport libraryExport : lib.getExports()) { - LibraryUnit exportedLibrary = libraryExport.getLibrary(); - String exportedLibraryName = getLibraryName(exportedLibrary); - // no => error - if (exportedLibraryName == null) { - SourceInfo info = findExportDirective(lib, exportedLibrary); - if (info != null) { - Source expSource = exportedLibrary.getSelfDartUnit().getSourceInfo().getSource(); - context.onError(new DartCompilationError(info, - DartCompilerErrorCode.MISSING_LIBRARY_DIRECTIVE_EXPORT, - ((DartSource) expSource).getRelativePath())); - } - } - } - - // check that each imported library has a library directive - Map nameToImportedLibrary = Maps.newHashMap(); - for (LibraryUnit importedLib : lib.getImportedLibraries()) { - - if (PackageLibraryManager.isDartUri(importedLib.getSource().getUri())) { - // system libraries are always valid - continue; - } - - // get the dart unit corresponding to this library - DartUnit unit = importedLib.getSelfDartUnit(); - if (unit == null || unit.isDiet()) { - // don't need to check a unit that hasn't changed - continue; - } - - // find imported library name - String importedLibraryName = getLibraryName(importedLib); - - // no name => error - if (importedLibraryName == null) { - SourceInfo info = findImportDirective(lib, importedLib); - if (info != null) { - context.onError(new DartCompilationError(info, - DartCompilerErrorCode.MISSING_LIBRARY_DIRECTIVE_IMPORT, - ((DartSource) unit.getSourceInfo().getSource()).getRelativePath())); - } - } - - // has already library with such name => error - if (importedLibraryName != null) { - LibraryUnit prevLibraryWithSameName = nameToImportedLibrary.get(importedLibraryName); - if (prevLibraryWithSameName != null) { - SourceInfo info = findImportDirective(lib, importedLib); - if (info != null) { - Source prevSource = prevLibraryWithSameName.getSelfDartUnit().getSourceInfo().getSource(); - context.onError(new DartCompilationError(info, - DartCompilerErrorCode.DUPLICATE_IMPORTED_LIBRARY_NAME, - importedLibraryName, - ((DartSource) prevSource).getRelativePath())); - } - } else { - nameToImportedLibrary.put(importedLibraryName, importedLib); - } - } - } - - // check that all sourced units have no directives - for (DartUnit unit : lib.getUnits()) { - // don't need to check a unit that hasn't changed - if (unit.isDiet()) { - continue; - } - // ignore library unit - DartSource unitSource = (DartSource) unit.getSourceInfo().getSource(); - if (isLibrarySelfUnit(lib, unitSource)) { - continue; - } - // analyze directives - List directives = unit.getDirectives(); - if (directives.isEmpty()) { - context.onError(new DartCompilationError(unitSource, - DartCompilerErrorCode.MISSING_PART_OF_DIRECTIVE, lib.getName())); - } else if (directives.size() == 1 && directives.get(0) instanceof DartPartOfDirective) { - DartPartOfDirective directive = (DartPartOfDirective) directives.get(0); - String dirName = directive.getLibraryName(); - if (!Objects.equal(dirName, lib.getName())) { - context.onError(new DartCompilationError(directive, - DartCompilerErrorCode.WRONG_PART_OF_NAME, lib.getName(), dirName)); - } - } else { - context.onError(new DartCompilationError(directives.get(0), - DartCompilerErrorCode.ILLEGAL_DIRECTIVES_IN_SOURCED_UNIT, - Elements.getRelativeSourcePath(unitSource, lib.getSource()))); - } - } - } - } - - /** - * @return the name of the given {@link LibraryUnit} specified in {@link DartLibraryDirective}. - */ - private static String getLibraryName(LibraryUnit libraryUnit) { - DartUnit unit = libraryUnit.getSelfDartUnit(); - for (DartDirective directive : unit.getDirectives()) { - if (directive instanceof DartLibraryDirective) { - return ((DartLibraryDirective) directive).getLibraryName(); - } - } - return null; - } - - /** - * @return the {@link SourceInfo} of the import directive in "lib" for "importedLib". - */ - private static SourceInfo findImportDirective(LibraryUnit lib, LibraryUnit importedLib) { - for (LibraryNode importPath : lib.getImportPaths()) { - if (importPath.getText().equals(importedLib.getSelfSourcePath().getText())) { - return importPath.getSourceInfo(); - } - } - return null; - } - - /** - * @return the {@link SourceInfo} of the export directive in "lib" for "importedLib". - */ - private static SourceInfo findExportDirective(LibraryUnit lib, LibraryUnit importedLib) { - for (LibraryNode exportPath : lib.getExportPaths()) { - if (exportPath.getText().equals(importedLib.getSelfSourcePath().getText())) { - return exportPath.getSourceInfo(); - } - } - return null; - } - - private static boolean isLibrarySelfUnit(LibraryUnit lib, DartSource unitSource) { - String unitRelativePath = unitSource.getRelativePath(); - for (LibraryNode sourceNode : lib.getSourcePaths()) { - if (unitRelativePath.equals(sourceNode.getText())) { - if (sourceNode == lib.getSelfSourcePath()) { - return true; - } - return false; - } - } - return false; - } - - private void setEntryPoint() { - LibraryUnit lib = context.getAppLibraryUnit(); - lib.setEntryNode(new LibraryNode(MAIN_ENTRY_POINT_NAME)); - // this ensures that if we find it, it's a top-level static element - Element element = lib.getElement().lookupLocalElement(MAIN_ENTRY_POINT_NAME); - switch (ElementKind.of(element)) { - case NONE: - // this is ok, it might just be a library - break; - - case METHOD: - MethodElement methodElement = (MethodElement) element; - Modifiers modifiers = methodElement.getModifiers(); - if (modifiers.isGetter()) { - context.onError(new DartCompilationError(element, - DartCompilerErrorCode.ENTRY_POINT_METHOD_MAY_NOT_BE_GETTER, MAIN_ENTRY_POINT_NAME)); - } else if (modifiers.isSetter()) { - context.onError(new DartCompilationError(element, - DartCompilerErrorCode.ENTRY_POINT_METHOD_MAY_NOT_BE_SETTER, MAIN_ENTRY_POINT_NAME)); - } else if (methodElement.getParameters().size() > 0) { - context.onError(new DartCompilationError(element, - DartCompilerErrorCode.ENTRY_POINT_METHOD_CANNOT_HAVE_PARAMETERS, - MAIN_ENTRY_POINT_NAME)); - } else { - lib.getElement().setEntryPoint(methodElement); - } - break; - - default: - context.onError(new DartCompilationError(element, - ResolverErrorCode.NOT_A_STATIC_METHOD, MAIN_ENTRY_POINT_NAME)); - break; - } - } - - private void compileLibraries() throws IOException { - TraceEvent logEvent = - Tracer.canTrace() ? Tracer.start(DartEventType.COMPILE_LIBRARIES) : null; - - CompilerMetrics compilerMetrics = context.getCompilerMetrics(); - if (compilerMetrics != null) { - compilerMetrics.startCompileLibrariesTime(); - } - - try { - // Set entry point - setEntryPoint(); - - // The two following for loops can be parallelized. - for (LibraryUnit lib : getLibrariesToProcess()) { - boolean persist = false; - - // Compile all the units in this library. - for (DartCompilationPhase phase : phases) { - - // Run all compiler phases including AST simplification and symbol - // resolution. This must run in serial. - for (DartUnit unit : lib.getUnits()) { - - // Don't compile diet units. - if (unit.isDiet()) { - continue; - } - - unit = phase.exec(unit, context, getTypeProvider()); - if (!config.resolveDespiteParseErrors() && context.getErrorCount() > 0) { - return; - } - } - - } - - for (DartUnit unit : lib.getUnits()) { - if (unit.isDiet()) { - continue; - } - updateAnalysisTimestamp(unit); - // To help support the IDE, notify the listener that this unit is compiled. - context.unitCompiled(unit); - // Update deps. - lib.getDeps(context).update(context, unit); - // We analyzed something, so we need to persist the deps. - persist = true; - } - - // Persist the DEPS file. - if (persist) { - lib.writeDeps(context); - } - } - } finally { - if (compilerMetrics != null) { - compilerMetrics.endCompileLibrariesTime(); - } - Tracer.end(logEvent); - } - } - - private void updateAnalysisTimestamp(DartUnit unit) throws IOException { - // Update timestamp. - Writer writer = - context.getArtifactWriter(unit.getSourceInfo().getSource(), "", EXTENSION_TIMESTAMP); - String timestampData = String.format("%d\n", System.currentTimeMillis()); - writer.write(timestampData); - writer.close(); - } - - DartUnit parse(DartSource dartSrc, Set libraryPrefixes, boolean diet) throws IOException { - TraceEvent parseEvent = - Tracer.canTrace() ? Tracer.start(DartEventType.PARSE, "src", dartSrc.getName()) : null; - CompilerMetrics compilerMetrics = context.getCompilerMetrics(); - long parseStart = compilerMetrics != null ? CompilerMetrics.getThreadTime() : 0; - Reader r = dartSrc.getSourceReader(); - String srcCode; - boolean failed = true; - try { - try { - srcCode = CharStreams.toString(r); - failed = false; - } finally { - Closeables.close(r, failed); - } - - DartParser parser = new DartParser(dartSrc, srcCode, diet, libraryPrefixes, context, - context.getCompilerMetrics()); - DartUnit unit = parser.parseUnit(); - if (compilerMetrics != null) { - compilerMetrics.addParseTimeNano(CompilerMetrics.getThreadTime() - parseStart); - } - - if (!config.resolveDespiteParseErrors() && context.getErrorCount() > 0) { - // We don't return this unit, so no more processing expected for it. - context.unitCompiled(unit); - return null; - } - return unit; - } finally { - Tracer.end(parseEvent); - } - } - - private void reportMissingSource(DartCompilerContext context, - LibrarySource libSrc, - LibraryNode libNode) { - if (libNode != null && StringUtils.startsWith(libNode.getText(), "dart-ext:")) { - return; - } - DartCompilationError event = new DartCompilationError(libNode, - DartCompilerErrorCode.MISSING_SOURCE, - libNode.getText()); - event.setSource(libSrc); - context.onError(event); - } - CoreTypeProvider getTypeProvider() { - typeProvider.getClass(); // Quick null check. - return typeProvider; - } - } - - /** - * Provides cached parse and resolution results during selective compilation - */ - public abstract static class SelectiveCache { - - /** - * Answer the cached resolved libraries - * - * @return a mapping (not null) of library source URI to cached {@link LibraryUnit} - */ - public abstract Map getResolvedLibraries(); - - /** - * Answer the cached unresolved {@link DartUnit} for the specified source - * - * @param dartSrc the source (not null) - * @return the cached unit or null if it is not cached - */ - public abstract DartUnit getUnresolvedDartUnit(DartSource dartSrc); - } - - /** - * Selectively compile a library. Use supplied libraries and ASTs when available. - * This allows programming tools to provide customized ASTs for code that is currently being - * edited, and may not compile correctly. - */ - static class SelectiveCompiler extends Compiler { - private final SelectiveCache selectiveCache; - private Collection librariesToProcess; - - private SelectiveCompiler(LibrarySource app, SelectiveCache selectiveCache, - CompilerConfiguration config, DartCompilerMainContext context) { - super(app, Collections.emptyList(), config, context); - this.selectiveCache = selectiveCache; - addResolvedLibraries(selectiveCache.getResolvedLibraries()); - } - - @Override - Collection getLibrariesToProcess() { - if (librariesToProcess == null) { - librariesToProcess = new ArrayList(); - librariesToProcess.addAll(super.getLibrariesToProcess()); - librariesToProcess.removeAll(selectiveCache.getResolvedLibraries().values()); - } - return librariesToProcess; - } - - @Override - DartUnit parse(DartSource dartSrc, Set prefixes, boolean diet) throws IOException { - DartUnit parsedUnit = selectiveCache.getUnresolvedDartUnit(dartSrc); - if (parsedUnit != null) { - return parsedUnit; - } - return super.parse(dartSrc, prefixes, diet); - } - } - - private static CompilerOptions processCommandLineOptions(String[] args) { - CmdLineParser cmdLineParser = null; - CompilerOptions compilerOptions = null; - try { - compilerOptions = new CompilerOptions(); - cmdLineParser = CommandLineOptions.parse(args, compilerOptions); - if (args.length == 0 || compilerOptions.showHelp()) { - showUsage(cmdLineParser, System.err); - System.exit(1); - } - } catch (CmdLineException e) { - System.err.println(e.getLocalizedMessage()); - showUsage(cmdLineParser, System.err); - System.exit(1); - } - - assert compilerOptions != null; - return compilerOptions; - } - - public static void main(final String[] topArgs) { - Tracer.init(); - - CompilerOptions topCompilerOptions = processCommandLineOptions(topArgs); - Result result = null; - try { - // configure UTF-8 output - System.setOut(new PrintStream(System.out, true, "UTF-8")); - System.setErr(new PrintStream(System.err, true, "UTF-8")); - - if (topCompilerOptions.showVersion()) { - showVersion(topCompilerOptions); - System.exit(RESULT_OK); - } - if (topCompilerOptions.shouldBatch()) { - if (topArgs.length > 1) { - System.err.println("(Extra arguments specified with -batch ignored.)"); - } - result = UnitTestBatchRunner.runAsBatch(topArgs, new Invocation() { - @Override - public Result invoke(String[] lineArgs) throws Throwable { - List allArgs = new ArrayList(); - for (String arg: topArgs) { - if (!arg.equals("-batch")) { - allArgs.add(arg); - } - } - for (String arg: lineArgs) { - allArgs.add(arg); - } - - CompilerOptions compilerOptions = processCommandLineOptions( - allArgs.toArray(new String[allArgs.size()])); - if (compilerOptions.shouldBatch()) { - System.err.println("-batch ignored: Already in batch mode."); - } - return compilerMain(compilerOptions); - } - }); - } else { - System.out.println("WARNING: This command is now deprecated, please use dartanalyzer instead."); - System.out.println("For more info, see www.dartlang.org/tools/analyzer."); - System.out.println(); - - result = compilerMain(topCompilerOptions); - } - } catch (Throwable t) { - t.printStackTrace(); - crash(); - } - // exit - { - int exitCode = result.code; - if (!topCompilerOptions.extendedExitCode()) { - if (exitCode == RESULT_ERRORS) { - exitCode = 1; - } else { - exitCode = 0; - } - } - System.exit(exitCode); - } - } - - /** - * Invoke the compiler to build single application. - * - * @param compilerOptions parsed command line arguments - * @return the result as integer when 0 means clean; 1 there were - * warnings; 2 there were errors; 127 other problems or - * exceptions. - */ - public static Result compilerMain(CompilerOptions compilerOptions) throws IOException { - List sourceFiles = compilerOptions.getSourceFiles(); - if (sourceFiles.size() == 0) { - System.err.println("dart_analyzer: no source files were specified."); - showUsage(null, System.err); - return new Result(RESULT_OTHER, null); - } - - File sourceFile = new File(sourceFiles.get(0)); - if (!sourceFile.exists()) { - System.err.println("dart_analyzer: file not found: " + sourceFile); - showUsage(null, System.err); - return new Result(RESULT_OTHER, null); - } - - CompilerConfiguration config = new DefaultCompilerConfiguration(compilerOptions); - config.getPackageLibraryManager().setPackageRoots(Arrays.asList(new File[]{compilerOptions.getPackageRoot()})); - return compilerMain(sourceFile, config); - } - - /** - * Invoke the compiler to build single application. - * - * @param sourceFile file passed on the command line to build - * @param config compiler configuration built from parsed command line options - */ - public static Result compilerMain(File sourceFile, CompilerConfiguration config) - throws IOException { - Result result = compileApp(sourceFile, config); - String errorMessage = result.message; - if (errorMessage != null) { - System.err.println(errorMessage); - return result; - } - - TraceEvent logEvent = Tracer.canTrace() ? Tracer.start(DartEventType.WRITE_METRICS) : null; - try { - maybeShowMetrics(config); - } finally { - Tracer.end(logEvent); - } - return result; - } - - public static void crash() { - // Our test scripts look for 253 to signal a "crash". - System.exit(253); - } - - private static void showUsage(CmdLineParser cmdLineParser, PrintStream out) { - out.println("Usage: dart_analyzer [] [script-arguments]"); - out.println("Available options:"); - if (cmdLineParser == null) { - cmdLineParser = new CmdLineParser(new CompilerOptions()); - } - cmdLineParser.printUsage(out); - } - - private static void maybeShowMetrics(CompilerConfiguration config) { - CompilerMetrics compilerMetrics = config.getCompilerMetrics(); - if (compilerMetrics != null) { - compilerMetrics.write(System.out); - } - - JvmMetrics.maybeWriteJvmMetrics(System.out, config.getJvmMetricOptions()); - } - - /** - * Treats the sourceFile as the top level library and generates compiled output by - * linking the dart source in this file with all libraries referenced with #import - * statements. - * - * @return the result as integer when 0 means clean; 1 there were - * warnings; 2 there were errors; 127 other problems or - * exceptions. - */ - public static Result compileApp(File sourceFile, CompilerConfiguration config) throws IOException { - TraceEvent logEvent = - Tracer.canTrace() ? Tracer.start(DartEventType.COMPILE_APP, "src", sourceFile.toString()) - : null; - try { - File outputDirectory = config.getOutputDirectory(); - DefaultDartArtifactProvider provider = new DefaultDartArtifactProvider(outputDirectory); - // Compile the Dart application and its dependencies. - PackageLibraryManager libraryManager = config.getPackageLibraryManager(); - final LibrarySource lib = new UrlLibrarySource(sourceFile.toURI(),libraryManager); - DefaultDartCompilerListener listener; - if (config.getCompilerOptions().showSourceFromAst()) { - listener = new DefaultDartCompilerListener(config.printErrorFormat()) { - @Override - public void unitCompiled(DartUnit unit) { - if (unit.getLibrary() != null) { - if (unit.getLibrary().getSource() == lib) { - DefaultTextOutput output = new DefaultTextOutput(false); - unit.accept(new DartToSourceVisitor(output)); - System.out.println(output.toString()); - } - } - } - }; - } else { - listener = new DefaultDartCompilerListener(config.printErrorFormat()); - } - return compileLib(lib, config, provider, listener); - } finally { - Tracer.end(logEvent); - } - } - - /** - * Compiles the given library, translating all its source files, and those - * of its imported libraries, transitively. - * - * @param lib The library to be compiled (not null) - * @param config The compiler configuration specifying the compilation phases - * @param provider A mechanism for specifying where code should be generated - * @param listener An object notified when compilation errors occur - */ - public static Result compileLib(LibrarySource lib, CompilerConfiguration config, - DartArtifactProvider provider, DartCompilerListener listener) throws IOException { - return compileLib(lib, Collections.emptyList(), config, provider, listener); - } - - /** - * Same method as above, but also takes a list of libraries that should be - * implicitly imported by all libraries. These libraries are provided by the embedder. - */ - public static Result compileLib(LibrarySource lib, - List embeddedLibraries, - CompilerConfiguration config, - DartArtifactProvider provider, - DartCompilerListener listener) throws IOException { - DartCompilerMainContext context = new DartCompilerMainContext(lib, provider, listener, - config); - new Compiler(lib, embeddedLibraries, config, context).compile(); - int errorCount = context.getErrorCount(); - if (config.typeErrorsAreFatal()) { - errorCount += context.getTypeErrorCount(); - } - if (config.warningsAreFatal()) { - errorCount += context.getWarningCount(); - } - if (errorCount > 0) { - return new Result(RESULT_ERRORS, "Compilation failed with " + errorCount - + (errorCount == 1 ? " problem." : " problems.")); - } - if (!context.getFilesHaveChanged()) { - return null; - } - // Write checking log. - { - Writer writer = provider.getArtifactWriter(lib, "", EXTENSION_LOG); - boolean threw = true; - try { - writer.write(String.format("Checked %s and found:%n", lib.getName())); - writer.write(String.format(" no load/resolution errors%n")); - writer.write(String.format(" %s type errors%n", context.getTypeErrorCount())); - threw = false; - } finally { - Closeables.close(writer, threw); - } - } - { - int resultCode = RESULT_OK; - if (context.getWarningCount() != 0) { - resultCode = RESULT_WARNINGS; - } - return new Result(resultCode, null); - } - } - - /** - * Analyzes the given library and all its transitive dependencies. - * - * @param lib The library to be analyzed - * @param parsedUnits A collection of unresolved ASTs that should be used - * instead of parsing the associated source from storage. Intended for - * IDE use when modified buffers must be analyzed. AST nodes in the map may be - * ignored if not referenced by {@code lib}. (May be null.) - * @param config The compiler configuration (phases will not be used), but resolution and - * type-analysis will be invoked - * @param provider A mechanism for specifying where code should be generated - * @param listener An object notified when compilation errors occur - * @throws NullPointerException if any of the arguments except {@code parsedUnits} - * are {@code null} - * @throws IOException on IO errors, which are not logged - */ - public static LibraryUnit analyzeLibrary(LibrarySource lib, final Map parsedUnits, - CompilerConfiguration config, DartArtifactProvider provider, DartCompilerListener listener) - throws IOException { - final PackageLibraryManager manager = config.getPackageLibraryManager(); - final HashMap resolvedLibs = new HashMap(); - SelectiveCache selectiveCache = new SelectiveCache() { - @Override - public Map getResolvedLibraries() { - return resolvedLibs; - } - @Override - public DartUnit getUnresolvedDartUnit(DartSource dartSrc) { - if (parsedUnits == null) { - return null; - } - URI srcUri = dartSrc.getUri(); - DartUnit parsedUnit = parsedUnits.remove(srcUri); - if (parsedUnit != null) { - return parsedUnit; - } - URI fileUri = manager.resolveDartUri(srcUri); - return parsedUnits.remove(fileUri); - } - }; - Map libraryUnit = analyzeLibraries(lib, selectiveCache, config, - provider, listener, false); - return libraryUnit != null ? libraryUnit.get(lib.getUri()) : null; - } - - /** - * Analyzes the given library and all its transitive dependencies. - * - * @param lib The library to be analyzed - * @param selectiveCache Provides cached parse and resolution results - * during selective compilation (not null) - * @param config The compiler configuration (phases and backends - * will not be used), but resolution and type-analysis will be invoked - * @param provider A mechanism for specifying where code should be generated - * @param listener An object notified when compilation errors occur - * @param resolveAllNewLibs true if all new libraries should be resolved - * or false if only the library specified by the "lib" parameter should be resolved - * @throws NullPointerException if any of the arguments except {@code parsedUnits} - * are {@code null} - * @throws IOException on IO errors, which are not logged - */ - public static Map analyzeLibraries(LibrarySource lib, - SelectiveCache selectiveCache, CompilerConfiguration config, - DartArtifactProvider provider, DartCompilerListener listener, - boolean resolveAllNewLibs) throws IOException { - lib.getClass(); // Quick null check. - provider.getClass(); // Quick null check. - listener.getClass(); // Quick null check. - Map resolvedLibs = selectiveCache.getResolvedLibraries(); - DartCompilerMainContext context = new DartCompilerMainContext(lib, provider, listener, config); - Compiler compiler = new SelectiveCompiler(lib, selectiveCache, config, context); - - LibraryUnit topLibUnit = compiler.updateAndResolve(); - if (topLibUnit == null) { - return null; - } - - Map librariesToResolve; - librariesToResolve = new HashMap(); - if (resolveAllNewLibs) { - librariesToResolve.putAll(compiler.getLibraries()); - } - librariesToResolve.put(topLibUnit.getSource().getUri(), topLibUnit); - - DartCompilationPhase[] phases = { - new Resolver.Phase(), - new CompileTimeConstantAnalyzer.Phase(), - new TypeAnalyzer()}; - Map newLibraries = Maps.newHashMap(); - for (Entry entry : librariesToResolve.entrySet()) { - URI libUri = entry.getKey(); - LibraryUnit libUnit = entry.getValue(); - if (!resolvedLibs.containsKey(libUri) && libUnit != null) { - newLibraries.put(libUri, libUnit); - for (DartCompilationPhase phase : phases) { - // Run phase on all units, because "const" phase expects to have fully resolved library. - for (DartUnit unit : libUnit.getUnits()) { - if (unit.isDiet()) { - continue; - } - unit = phase.exec(unit, context, compiler.getTypeProvider()); - } - } - // To help support the IDE, notify the listener that these unit were compiled. - for (DartUnit unit : libUnit.getUnits()) { - context.unitCompiled(unit); - } - } - } - - return newLibraries; - } - - /** - * Re-analyzes source code after a modification. The modification is described by a SourceDelta. - * - * @param delta what has changed - * @param enclosingLibrary the library in which the change occurred - * @param interestStart beginning of interest area (as character offset from the beginning of the - * source file after the change. - * @param interestLength length of interest area - * @return a node which covers the entire interest area. - */ - public static DartNode analyzeDelta(SourceDelta delta, - LibraryElement enclosingLibrary, - LibraryElement coreLibrary, - DartNode interestNode, - int interestStart, - int interestLength, - CompilerConfiguration config, - DartCompilerListener listener) throws IOException { - DeltaAnalyzer analyzer = new DeltaAnalyzer(delta, enclosingLibrary, coreLibrary, - interestNode, interestStart, interestLength, - config, listener); - return analyzer.analyze(); - } - - public static LibraryUnit findLibrary(LibraryUnit libraryUnit, String uri, - Set seen) { - if (seen.contains(libraryUnit.getElement())) { - return null; - } - seen.add(libraryUnit.getElement()); - if (uri.equals(libraryUnit.getName())) { - return libraryUnit; - } - for (LibraryNode src : libraryUnit.getSourcePaths()) { - if (src.getText().equals(uri)) { - return libraryUnit; - } - } - for (LibraryUnit importedLibrary : libraryUnit.getImportedLibraries()) { - LibraryUnit unit = findLibrary(importedLibrary, uri, seen); - if (unit != null) { - return unit; - } - } - return null; - } - - public static LibraryUnit getCoreLib(LibraryUnit libraryUnit) { - LibraryUnit coreLib = findLibrary(libraryUnit, "dart.core", new HashSet()); - if (coreLib == null) { - coreLib = findLibrary(libraryUnit, "dart:core", new HashSet()); - } - return coreLib; - } - - private static void showVersion(CompilerOptions options) { - String version = getSdkVersion(options); - if (version == null) { - version = ""; - } - System.out.println("dart_analyzer version " + version); - } - - /** - * @return the numeric revision of SDK, may be null if cannot find. - */ - private static String getSdkVersion(CompilerOptions options) { - try { - File sdkPath = options.getDartSdkPath(); - File revisionFile = new File(sdkPath, "version"); - if (revisionFile.exists() && revisionFile.isFile()) { - BufferedReader br = new BufferedReader(new FileReader(revisionFile)); - try { - return br.readLine(); - } finally { - br.close(); - } - } - } catch (Throwable e) { - } - return null; - } -} diff --git a/compiler/java/com/google/dart/compiler/DartCompilerContext.java b/compiler/java/com/google/dart/compiler/DartCompilerContext.java deleted file mode 100644 index 61e3302150ab..000000000000 --- a/compiler/java/com/google/dart/compiler/DartCompilerContext.java +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import com.google.dart.compiler.ast.LibraryUnit; -import com.google.dart.compiler.metrics.CompilerMetrics; - -import java.io.IOException; -import java.io.Reader; -import java.io.Writer; -import java.net.URI; - -/** - * An interface used internally by the {@link DartCompiler} for determining where an artifact should - * be generated and providing feedback during the compilation process. This is an internal compiler - * construct and as such should not be instantiated or implemented by those outside the compiler - * itself. - */ -public interface DartCompilerContext { - - /** - * Parse the application being compiled and return the result. The "application unit" is a - * library that specifies an entry-point. - * - * This method will be removed in favor of {@link #getAppLibraryUnit()}. - * - * @return the parsed result (not null) - */ - LibraryUnit getApplicationUnit(); - - /** - * Parse the application being compiled and return the result. The "app" library unit is a - * library that specifies an entry-point. - * - * @return the parsed result (not null) - */ - LibraryUnit getAppLibraryUnit(); - - /** - * Parse the specified library and return the result. - * - * @param lib the library to parse (not null) - * @return the parsed result (not null) - */ - LibraryUnit getLibraryUnit(LibrarySource lib); - - /** - * Called by the compiler when a error (fatal or non-fatal) has occurred in a Dart file. - * - * @param event the event information (not null) - */ - void onError(DartCompilationError event); - - /** - * Gets a reader for an artifact associated with the specified source, which - * must have been written to {@link #getArtifactWriter(Source, String, String)}. The - * caller is responsible for closing the reader. Only one artifact may be - * associated with the given extension. - * - * @param source the source file (not null) - * @param part a component of the source file to get a reader for (may be empty). - * @param extension the file extension for this artifact (not - * null, not empty) - * @return the reader, or null if no such artifact exists - */ - Reader getArtifactReader(Source source, String part, String extension) throws IOException; - - /** - * Gets the {@link URI} for an artifact associated with this source. - * - * @param source the source file (not null) - * @param part a component of the source file to get a reader for (may be empty). - * @param extension the file extension for this artifact (not - * null, not empty) - */ - URI getArtifactUri(DartSource source, String part, String extension); - - /** - * Gets a writer for an artifact associated with this source. The caller is - * responsible for closing the writer. Only one artifact may be associated - * with the given extension. - * - * @param source the source file (not null) - * @param part a component of the source file to get a reader for (may be empty). - * @param extension the file extension for this artifact (not - * null, not empty) - */ - Writer getArtifactWriter(Source source, String part, String extension) throws IOException; - - /** - * Determines whether an artifact for the specified source is out of date - * with respect to some other source. - * - * @param source the source file to check (not null) - * @param base the artifact's base source (not null) - * @param extension the file extension for this artifact (not - * null, not empty) - * @return true if out of date - */ - boolean isOutOfDate(Source source, Source base, String extension); - - /** - * Returns the {@link CompilerMetrics} instance or null if we should not record - * metrics. - * - * @return the metrics instance, null if metrics should not be recorded - */ - CompilerMetrics getCompilerMetrics(); - - /** - * Returns the {@link CompilerConfiguration} instance. - * @return the compiler configuration instance. - */ - CompilerConfiguration getCompilerConfiguration(); - - /** - * Return the system library corresponding to the specified "dart:" spec. - */ - LibrarySource getSystemLibraryFor(String importSpec); -} diff --git a/compiler/java/com/google/dart/compiler/DartCompilerErrorCode.java b/compiler/java/com/google/dart/compiler/DartCompilerErrorCode.java deleted file mode 100644 index 5476e2e52c57..000000000000 --- a/compiler/java/com/google/dart/compiler/DartCompilerErrorCode.java +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -/** - * Valid error codes for the errors produced by the Dart compiler. - */ -public enum DartCompilerErrorCode implements ErrorCode { - CONSOLE_WEB_MIX(ErrorSeverity.INFO, - "Libraries 'dart:io' (console apps only) and 'dart:html' (web apps only) cannot be used together"), - DUPLICATE_IMPORTED_LIBRARY_NAME("a library with name '%s' was already imported: %s"), - ENTRY_POINT_METHOD_CANNOT_HAVE_PARAMETERS(ErrorSeverity.WARNING, - "Main entry point method cannot have parameters"), - ENTRY_POINT_METHOD_MAY_NOT_BE_GETTER(ErrorSeverity.WARNING, - "Entry point \"%s\" may not be a getter"), - ENTRY_POINT_METHOD_MAY_NOT_BE_SETTER(ErrorSeverity.WARNING, - "Entry point \"%s\" may not be a setter"), - ILLEGAL_DIRECTIVES_IN_SOURCED_UNIT("This part was included by %s via a " - + "part directive, so cannot itself contain directives other than a 'part of' directive"), - IO("Input/Output error: %s"), - MIRRORS_NOT_FULLY_IMPLEMENTED(ErrorSeverity.WARNING, "dart:mirrors is not fully implemented yet"), - MISSING_LIBRARY_DIRECTIVE_IMPORT("a library which is imported is missing a library directive: %s"), - MISSING_LIBRARY_DIRECTIVE_EXPORT("a library which is exported is missing a library directive: %s"), - MISSING_SOURCE("Cannot find referenced source: %s"), - MISSING_PART_OF_DIRECTIVE("Unit is part of library '%s', but has no 'part of' directive"), - UNIT_WAS_ALREADY_INCLUDED("Unit '%s' was already included"), - WRONG_PART_OF_NAME( - ErrorSeverity.WARNING, - "This part was included by '%s' via a 'part' directive, but uses name '%s' in 'part of' directive"); - private final ErrorSeverity severity; - private final String message; - - /** - * Initialize a newly created error code to have the given message and ERROR severity. - */ - private DartCompilerErrorCode(String message) { - this(ErrorSeverity.ERROR, message); - } - - /** - * Initialize a newly created error code to have the given severity and message. - */ - private DartCompilerErrorCode(ErrorSeverity severity, String message) { - this.severity = severity; - this.message = message; - } - - @Override - public String getMessage() { - return message; - } - - @Override - public ErrorSeverity getErrorSeverity() { - return severity; - } - - @Override - public SubSystem getSubSystem() { - return SubSystem.COMPILER; - } - - @Override - public boolean needsRecompilation() { - return true; - } -} diff --git a/compiler/java/com/google/dart/compiler/DartCompilerListener.java b/compiler/java/com/google/dart/compiler/DartCompilerListener.java deleted file mode 100644 index 9216c5bced2b..000000000000 --- a/compiler/java/com/google/dart/compiler/DartCompilerListener.java +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. -package com.google.dart.compiler; - -import com.google.dart.compiler.ast.DartUnit; - -/** - * Interface that {@link DartCompiler} consumers can use to monitor compilation progress and report - * various problems that occur during compilation. - */ -public interface DartCompilerListener { - /** - * Called by the compiler when a compilation error has occurred in a Dart file. - * - * @param event the event information (not null) - */ - void onError(DartCompilationError event); - - /** - * Called by the compiler before parsing given {@link DartSource}. - */ - void unitAboutToCompile(DartSource source, boolean diet); - - /** - * Called by the compiler after the resolution and type analyzer phase for each unit. - * - * @param unit the {@link DartUnit} having just been compiled (not null) - */ - void unitCompiled(DartUnit unit); - - /** - * Implementation of {@link DartCompilerListener} which does nothing. - */ - public static class Empty implements DartCompilerListener { - @Override - public void onError(DartCompilationError event) { - } - - @Override - public void unitAboutToCompile(DartSource source, boolean diet) { - } - - @Override - public void unitCompiled(DartUnit unit) { - } - } - - /** - * Instance of {@link DartCompilerListener} which does nothing. - */ - public static final DartCompilerListener EMPTY = new Empty(); -} diff --git a/compiler/java/com/google/dart/compiler/DartCompilerMainContext.java b/compiler/java/com/google/dart/compiler/DartCompilerMainContext.java deleted file mode 100644 index ea3ea09122ac..000000000000 --- a/compiler/java/com/google/dart/compiler/DartCompilerMainContext.java +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import com.google.dart.compiler.ast.DartUnit; -import com.google.dart.compiler.ast.LibraryUnit; -import com.google.dart.compiler.metrics.CompilerMetrics; -import com.google.dart.compiler.parser.DartParser; -import com.google.dart.compiler.resolver.Elements; -import com.google.dart.compiler.resolver.ResolverErrorCode; -import com.google.dart.compiler.resolver.TypeErrorCode; - -import java.io.IOException; -import java.io.Reader; -import java.io.Writer; -import java.net.URI; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * An overall context for the Dart compiler providing an adapter and forwarding - * mechanism for to both {@link DartArtifactProvider} and - * {@link DartCompilerListener}. This is an internal compiler construct and as - * such should not be instantiated or subclassed by those outside the compiler - * itself. - */ -final class DartCompilerMainContext implements DartCompilerListener, DartCompilerContext { - - private final LibrarySource lib; - private final DartArtifactProvider provider; - private final DartCompilerListener listener; - private final Map> errors = Maps.newHashMap(); - private final AtomicInteger errorCount = new AtomicInteger(0); - private final AtomicInteger warningCount = new AtomicInteger(0); - private final AtomicInteger typeErrorCount = new AtomicInteger(0); - private final AtomicBoolean filesHaveChanged = new AtomicBoolean(); - // declared volatile for thread-safety - private volatile LibraryUnit appLibraryUnit = null; - - private final CompilerConfiguration compilerConfiguration; - - DartCompilerMainContext(LibrarySource lib, DartArtifactProvider provider, - DartCompilerListener listener, - CompilerConfiguration compilerConfiguration) { - this.lib = lib; - this.provider = provider; - this.listener = listener; - this.compilerConfiguration = compilerConfiguration; - } - - @Override - public void onError(DartCompilationError event) { - // problems in dart:core are not interesting - // http://code.google.com/p/dart/issues/detail?id=7128 - if (Elements.isCoreLibrarySource(event.getSource())) { - ErrorCode ec = event.getErrorCode(); - if (ec == ResolverErrorCode.EXPECTED_CONSTANT_EXPRESSION_NUMBER - || ec == TypeErrorCode.ASSERT_BOOL - || ec == TypeErrorCode.TYPE_NOT_ASSIGNMENT_COMPATIBLE - || ec == TypeErrorCode.FOR_IN_WITH_INVALID_ITERATOR_RETURN_TYPE - || ec == TypeErrorCode.OPERATOR_EQUALS_BOOL_RETURN_TYPE - || ec == TypeErrorCode.CANNOT_OVERRIDE_TYPED_MEMBER - || ec == TypeErrorCode.CANNOT_OVERRIDE_METHOD_NOT_SUBTYPE - || ec == TypeErrorCode.OPERATOR_WRONG_OPERAND_TYPE) { - return; - } - } - - // Remember error. - { - Source source = event.getSource(); - if (source != null) { - List sourceErrors = errors.get(source); - if (sourceErrors == null) { - sourceErrors = Lists.newArrayList(); - errors.put(source, sourceErrors); - } - sourceErrors.add(event); - } - } - // Increment counters. - if (event.getErrorCode().getSubSystem() == SubSystem.STATIC_TYPE) { - incrementTypeErrorCount(); - } - if (event.getErrorCode().getErrorSeverity() == ErrorSeverity.ERROR) { - incrementErrorCount(); - } else if (event.getErrorCode().getErrorSeverity() == ErrorSeverity.WARNING) { - incrementWarningCount(); - } - // Notify listener. - listener.onError(event); - } - - @Override - public LibraryUnit getApplicationUnit() { - return getAppLibraryUnit(); - } - - @Override - public LibraryUnit getAppLibraryUnit() { - // use double-checked looking pattern with use of volatile - if (appLibraryUnit == null) { - synchronized (this) { - if (appLibraryUnit == null) { - try { - appLibraryUnit = new DartParser(lib, DartParser.read(lib), false, - Sets. newHashSet(), DartCompilerListener.EMPTY, null).preProcessLibraryDirectives(lib); - } catch (IOException e) { - onError(new DartCompilationError(lib, DartCompilerErrorCode.IO, e.getMessage())); - return null; - } - } - } - } - return appLibraryUnit; - } - - @Override - public Reader getArtifactReader(Source source, String part, String extension) - throws IOException { - return provider.getArtifactReader(source, part, extension); - } - - @Override - public URI getArtifactUri(DartSource source, String part, String extension) { - return provider.getArtifactUri(source, part, extension); - } - - @Override - public Writer getArtifactWriter(Source source, String part, String extension) - throws IOException { - return provider.getArtifactWriter(source, part, extension); - } - - /** - * @return the {@link DartCompilationError}s found in the given {@link Source}. - */ - public List getSourceErrors(Source source) { - List sourceErrors = errors.get(source); - if (sourceErrors != null) { - return sourceErrors; - } - return Collections.emptyList(); - } - - public int getErrorCount() { - return errorCount.get(); - } - - public int getWarningCount() { - return warningCount.get(); - } - - public int getTypeErrorCount() { - return typeErrorCount.get(); - } - - @Override - public LibraryUnit getLibraryUnit(LibrarySource libSrc) { - if (libSrc == lib) { - return getApplicationUnit(); - } - try { - return new DartParser(libSrc, DartParser.read(libSrc), false, - Sets. newHashSet(), listener, null).preProcessLibraryDirectives(libSrc); - } catch (IOException e) { - onError(new DartCompilationError(libSrc, DartCompilerErrorCode.IO, e.getMessage())); - return null; - } - } - - @Override - public boolean isOutOfDate(Source source, Source base, String extension) { - return provider.isOutOfDate(source, base, extension); - } - - protected void incrementErrorCount() { - errorCount.incrementAndGet(); - } - - protected void incrementWarningCount() { - warningCount.incrementAndGet(); - } - - protected void incrementTypeErrorCount() { - typeErrorCount.incrementAndGet(); - } - - @Override - public CompilerMetrics getCompilerMetrics() { - return compilerConfiguration.getCompilerMetrics(); - } - - public void setFilesHaveChanged() { - filesHaveChanged.set(true); - } - - public boolean getFilesHaveChanged() { - return filesHaveChanged.get(); - } - - @Override - public CompilerConfiguration getCompilerConfiguration() { - return compilerConfiguration; - } - - /** - * Return the system library corresponding to the specified "dart:" spec. - */ - @Override - public LibrarySource getSystemLibraryFor(String importSpec) { - return compilerConfiguration.getSystemLibraryFor(importSpec); - } - - @Override - public void unitAboutToCompile(DartSource source, boolean diet) { - listener.unitAboutToCompile(source, diet); - } - - @Override - public void unitCompiled(DartUnit unit) { - listener.unitCompiled(unit); - } -} diff --git a/compiler/java/com/google/dart/compiler/DartSource.java b/compiler/java/com/google/dart/compiler/DartSource.java deleted file mode 100644 index 2962e17156ae..000000000000 --- a/compiler/java/com/google/dart/compiler/DartSource.java +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -/** - * Abstract interface to Dart source. - */ -public interface DartSource extends Source { - - /** - * Gets the library with which this Dart source is associated. - */ - LibrarySource getLibrary(); - - /** - * Gets the path of this source, relative to its library. - */ - String getRelativePath(); -} diff --git a/compiler/java/com/google/dart/compiler/DefaultCompilerConfiguration.java b/compiler/java/com/google/dart/compiler/DefaultCompilerConfiguration.java deleted file mode 100644 index f66190a8dac7..000000000000 --- a/compiler/java/com/google/dart/compiler/DefaultCompilerConfiguration.java +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import com.google.dart.compiler.CommandLineOptions.CompilerOptions; -import com.google.dart.compiler.metrics.CompilerMetrics; -import com.google.dart.compiler.resolver.CompileTimeConstantAnalyzer; -import com.google.dart.compiler.resolver.Resolver; -import com.google.dart.compiler.type.TypeAnalyzer; - -import java.io.File; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.List; - -/** - * A configuration for the Dart compiler specifying which phases will be executed. - */ -public class DefaultCompilerConfiguration implements CompilerConfiguration { - - private final CompilerOptions compilerOptions; - - private final CompilerMetrics compilerMetrics; - - private final PackageLibraryManager packageLibraryManager; - - - /** - * A default configuration. - */ - public DefaultCompilerConfiguration() { - this(new CompilerOptions()); - } - - /** - * A new instance with the specified {@link CompilerOptions}. - */ - public DefaultCompilerConfiguration(CompilerOptions compilerOptions) { - this(compilerOptions, new PackageLibraryManager(compilerOptions.getDartSdkPath(), - compilerOptions.getPlatformName())); - } - - /** - * A new instance with the specified options and system library manager. - */ - public DefaultCompilerConfiguration(CompilerOptions compilerOptions, - PackageLibraryManager libraryManager) { - this.compilerOptions = compilerOptions; - this.compilerMetrics = compilerOptions.showMetrics() ? new CompilerMetrics() : null; - this.packageLibraryManager = libraryManager; - } - - @Override - public List getPhases() { - List phases = new ArrayList(); - phases.add(new Resolver.Phase()); - phases.add(new CompileTimeConstantAnalyzer.Phase()); - phases.add(new TypeAnalyzer()); - return phases; - } - - @Override - public boolean developerModeChecks() { - return compilerOptions.developerModeChecks(); - } - - @Override - public CompilerMetrics getCompilerMetrics() { - return compilerMetrics; - } - - @Override - public String getJvmMetricOptions() { - return compilerOptions.getJvmMetricOptions(); - } - - @Override - public boolean typeErrorsAreFatal() { - return compilerOptions.typeErrorsAreFatal(); - } - - @Override - public boolean warningsAreFatal() { - return compilerOptions.warningsAreFatal(); - } - - @Override - public boolean resolveDespiteParseErrors() { - return compilerOptions.resolveDespiteParseErrors(); - } - - @Override - public boolean incremental() { - return compilerOptions.buildIncrementally(); - } - - @Override - public File getOutputDirectory() { - return compilerOptions.getWorkDirectory(); - } - - @Override - public LibrarySource getSystemLibraryFor(String importSpec) { - URI systemUri; - try { - systemUri = new URI(importSpec); - } catch (URISyntaxException e) { - throw new RuntimeException(e); - } - - // Verify the dart system library exists - if( null == this.packageLibraryManager.expandRelativeDartUri(systemUri) ) { - return null; - } - - // Ensure we are using the short form if it exists - URI shortUri = packageLibraryManager.getShortUri(systemUri); - if (shortUri != null) { - systemUri = shortUri; - } - - return new UrlLibrarySource(systemUri, this.packageLibraryManager); - } - - @Override - public CompilerOptions getCompilerOptions() { - return compilerOptions; - } - - @Override - public ErrorFormat printErrorFormat() { - return compilerOptions.printErrorFormat(); - } - - @Override - public PackageLibraryManager getPackageLibraryManager() { - return packageLibraryManager; - } -} diff --git a/compiler/java/com/google/dart/compiler/DefaultDartArtifactProvider.java b/compiler/java/com/google/dart/compiler/DefaultDartArtifactProvider.java deleted file mode 100644 index 5874051127d9..000000000000 --- a/compiler/java/com/google/dart/compiler/DefaultDartArtifactProvider.java +++ /dev/null @@ -1,235 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.io.Reader; -import java.io.Writer; -import java.net.URI; -import java.net.URISyntaxException; - -/** - * A default implementation of {@link DartArtifactProvider} specifying - * generated files be placed in the same directory as source files. - */ -public class DefaultDartArtifactProvider extends DartArtifactProvider { - - private final File outputDirectory; - - public DefaultDartArtifactProvider() { - this(new File("out")); - } - - public DefaultDartArtifactProvider(File outputDirectory) { - this.outputDirectory = outputDirectory; - } - - @Override - public Reader getArtifactReader(Source source, String part, String extension) - throws IOException { - if (PackageLibraryManager.isDartUri(source.getUri())) { - DartSource bundledSource = getBundledArtifact(source, source, part, extension); - if (bundledSource != null) { - Reader reader = null; - try { - reader = bundledSource.getSourceReader(); - } catch (FileNotFoundException e) { - /* thrown if file doesn't exist, which is fine */ - } - if (reader != null) { - return new BufferedReader(reader); - } - } - } - File file = getArtifactFile(source, part, extension); - if (!file.exists()) { - return null; - } - return new BufferedReader(new FileReader(file)); - } - - @Override - public URI getArtifactUri(Source source, String part, String extension) { - try { - return new URI("file", getArtifactFile(source, part, extension).getPath(), null); - } catch (URISyntaxException e) { - throw new IllegalArgumentException(e); - } - } - - @Override - public Writer getArtifactWriter(Source source, String part, String extension) throws IOException { - return new BufferedWriter(new FileWriter(makeDirectories(getArtifactFile(source, part, - extension)))); - } - - @Override - public boolean isOutOfDate(Source source, Source base, String extension) { - if (PackageLibraryManager.isDartUri(base.getUri())) { - Source bundledSource = getBundledArtifact(source, base, "", extension); - if (bundledSource != null && bundledSource.exists()) { - // Note: Artifacts bundled with sources are always up to date - return false; - } - } - File artifactFile = getArtifactFile(base, "", extension); - return !artifactFile.exists() || artifactFile.lastModified() < source.getLastModified(); - } - - // TODO(jbrosenberg): remove 'source' argument from this method, it's not used - protected DartSource getBundledArtifact(Source source, Source base, String part, String extension) { - LibrarySource library; - URI relativeUri; - if (base instanceof LibrarySource) { - library = (LibrarySource) base; - relativeUri = library.getUri().resolve(".").normalize().relativize(base.getUri()); - } else if (base instanceof DartSource){ - library = ((DartSource) base).getLibrary(); - String name = base.getName(); - URI nameUri = URI.create(name).normalize(); - relativeUri = library.getUri().resolve(".").normalize().relativize(nameUri); - } else { - throw new AssertionError(base.getClass().getName()); - } - - DartSource bundledSource; - if (!relativeUri.isAbsolute()) { - bundledSource = library.getSourceFor(fullname(relativeUri.getPath(), part, extension)); - } else { - bundledSource = null; - } - return bundledSource; - } - - /** - * Answer the artifact file associated with the specified source. Only one - * artifact may be associated with the given extension. - * - * @param source the source file (not null) - * @param part a component of the source file to get a reader for (may be empty). - * @param extension the file extension for this artifact (not - * null, not empty) - * @return the artifact file (not null) - */ - protected File getArtifactFile(Source source, String part, String extension) { - String name = source.getName(); - name = URI.create(name).normalize().toString(); - name = normalizeArtifactName(name); - File file = new File(outputDirectory, fullname(name, part, extension)); - return file; - } - - /* - * Removes extraneous punctuation and file path syntax. - */ - private String normalizeArtifactName(String name) { - /** - * For efficiency, String operations are replaced with a single pass over - * the character array data. - * - * Note: This is a refactor of a previous version which used repeated calls - * to String.replace(), which turns out to be unnecessarily expensive. This - * particular method has been identified as being called a large number of - * times, thus the need for the micro-optimization here. - * - * This is the original logic being implemented here: - * - * - * name = name.replace("//", File.separator); - * name = name.replace(":", ""); - * name = name.replace("!", ""); - * name = name.replace("..", "_"); - * - * - * Please update the above if the logic being implemented ever changes. - * - * TODO(jbrosenberg): Figure out a better way such that this normalization - * is no longer needed in the first place. Source objects could be built - * from pre-normalized prefixes, etc. Or if it can be called less often, - * then use pre-compiled Patterns and Matchers instead. - */ - boolean lastCharWasSlash = false; - boolean lastCharWasPeriod = false; - boolean madeChanges = false; - int nameLen = name.length(); - char[] newName = new char[nameLen]; - int idx = 0; - for (char ch : name.toCharArray()) { - if (lastCharWasPeriod && ch != '.') { - // didn't get a second period, so append the one we did get - newName[idx++] = '.'; - lastCharWasPeriod = false; - } else if (lastCharWasSlash && ch != '/') { - // didn't get a second slash, so append the one we did get - newName[idx++] = '/'; - lastCharWasSlash = false; - } - - switch (ch) { - case ':': - case '!': - // replace ':'s and '!'s with empty string - madeChanges = true; - break; - case '/': - if (lastCharWasSlash) { - // got a second slash, replace with File.separatorChar - madeChanges = true; - newName[idx++] = File.separatorChar; - lastCharWasSlash = false; - } else { - lastCharWasSlash = true; - } - break; - case '.': - if (lastCharWasPeriod) { - // got a second period, replace with a '_' - madeChanges = true; - newName[idx++] = ('_'); - lastCharWasPeriod = false; - } else { - lastCharWasPeriod = true; - } - break; - default: - newName[idx++] = ch; - lastCharWasSlash = false; - lastCharWasPeriod = false; - } - } - if (lastCharWasPeriod) { - // didn't get a final second period, so append the one we did get - newName[idx++] = '.'; - } else if (lastCharWasSlash) { - // didn't get a final second slash, so append the one we did get - newName[idx++] = '/'; - } - - if (madeChanges) { - name = new String(newName, 0, idx); - } - - return name; - } - - private File makeDirectories(File file) { - file.getParentFile().mkdirs(); - return file; - } - - private String fullname(String name, String part, String extension) { - if (part.isEmpty()) { - return name + "." + extension; - } else { - return name + "$" + part + "." + extension; - } - } -} diff --git a/compiler/java/com/google/dart/compiler/DefaultDartCompilerListener.java b/compiler/java/com/google/dart/compiler/DefaultDartCompilerListener.java deleted file mode 100644 index 7b7be62275a2..000000000000 --- a/compiler/java/com/google/dart/compiler/DefaultDartCompilerListener.java +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import com.google.dart.compiler.CompilerConfiguration.ErrorFormat; -import com.google.dart.compiler.ast.DartUnit; - -import java.io.PrintStream; - -/** - * A default implementation of {@link DartCompilerListener} which counts - * compilation errors. - */ -public class DefaultDartCompilerListener implements DartCompilerListener { - - /** - * The number of (fatal) problems that occurred during compilation. - */ - private int errorCount = 0; - - /** - * The number of (non-fatal) problems that occurred during compilation. - */ - private int warningCount = 0; - - /** - * The number of (non-fatal) problems that occurred during compilation. - */ - private int typeErrorCount = 0; - - /** - * Formatter used to report error messages. Marked protected so that - * subclasses can override it (e.g. for a test server using HTML formatting). - */ - protected final ErrorFormatter formatter; - - public DefaultDartCompilerListener(ErrorFormat errorFormat) { - this(System.err, errorFormat); - } - - /** - * @param outputStream the {@link PrintStream} to use for {@link ErrorFormatter}. - */ - public DefaultDartCompilerListener(PrintStream outputStream, ErrorFormat errorFormat) { - formatter = new PrettyErrorFormatter(outputStream, useColor(), errorFormat); - } - - private boolean useColor() { - return String.valueOf(System.getenv("TERM")).startsWith("xterm") && System.console() != null; - } - - /** - * Answer the number of fatal errors that occurred during compilation. - * - * @return the number of problems - */ - public int getErrorCount() { - return errorCount; - } - - /** - * Answer the number of non-fatal warnings that occurred during compilation. - * - * @return the number of problems - */ - public int getWarningCount() { - return warningCount; - } - - /** - * Answer the number of non-fatal type problems that occurred during compilation. - * - * @return the number of problems - */ - public int getTypeErrorCount() { - return typeErrorCount; - } - - /** - * Increment the {@link #errorCount} by 1 - */ - protected void incrementErrorCount() { - errorCount++; - } - - /** - * Increment the {@link #warningCount} by 1 - */ - protected void incrementWarningCount() { - warningCount++; - } - - /** - * Increment the {@link #typeErrorCount} by 1 - */ - protected void incrementTypeErrorCount() { - typeErrorCount++; - } - - @Override - public void onError(DartCompilationError event) { - formatter.format(event); - if (event.getErrorCode().getSubSystem() == SubSystem.STATIC_TYPE) { - incrementTypeErrorCount(); - } else if (event.getErrorCode().getErrorSeverity() == ErrorSeverity.ERROR) { - incrementErrorCount(); - } else if (event.getErrorCode().getErrorSeverity() == ErrorSeverity.WARNING) { - incrementWarningCount(); - } - } - - @Override - public void unitAboutToCompile(DartSource source, boolean diet) { - } - - @Override - public void unitCompiled(DartUnit unit) { - } -} diff --git a/compiler/java/com/google/dart/compiler/DefaultErrorFormatter.java b/compiler/java/com/google/dart/compiler/DefaultErrorFormatter.java deleted file mode 100644 index a908369d1b6c..000000000000 --- a/compiler/java/com/google/dart/compiler/DefaultErrorFormatter.java +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import com.google.common.base.Objects; -import com.google.dart.compiler.CompilerConfiguration.ErrorFormat; - -import java.io.PrintStream; - -/** - * An error formatter that simply prints the file name with the line and column - * location. - */ -public class DefaultErrorFormatter implements ErrorFormatter { - protected final PrintStream outputStream; - protected final ErrorFormat errorFormat; - - public DefaultErrorFormatter(PrintStream outputStream, ErrorFormat errorFormat) { - this.outputStream = outputStream; - this.errorFormat = errorFormat; - } - - @Override - public void format(DartCompilationError event) { - StringBuilder buf = new StringBuilder(); - appendError(buf, event); - outputStream.print(buf); - outputStream.print("\n"); - } - - protected void appendError(StringBuilder buf, DartCompilationError error) { - Source source = error.getSource(); - String sourceName = getSourceName(source); - int line = error.getLineNumber(); - int col = error.getColumnNumber(); - int length = error.getLength(); - if (errorFormat == ErrorFormat.MACHINE) { - buf.append(String.format( - "%s|%s|%s|%s|%d|%d|%d|%s", - escapePipe(error.getErrorCode().getErrorSeverity().toString()), - escapePipe(error.getErrorCode().getSubSystem().toString()), - escapePipe(error.getErrorCode().toString()), - escapePipe(sourceName), - line, - col, - length, - escapePipe(error.getMessage()))); - } else { - String includeFrom = getImportString(source); - buf.append(String.format( - "%s:%d:%d: %s%s", - sourceName, - line, - col, - error.getMessage(), - includeFrom)); - } - } - - protected static String getImportString(Source sourceFile) { - String includeFrom = ""; - if (sourceFile instanceof DartSource) { - LibrarySource lib = ((DartSource) sourceFile).getLibrary(); - if (lib != null && !Objects.equal(sourceFile.getUri(), lib.getUri())) { - includeFrom = " (sourced from " + lib.getUri() + ")"; - } - } - return includeFrom; - } - - protected static String getSourceName(Source source) { - if (source instanceof UrlDartSource) { - return source.getUri().toString(); - } - if (source != null) { - return source.getName(); - } - return ""; - } - - protected static String escapePipe(String input) { - StringBuilder result = new StringBuilder(); - for (char c : input.toCharArray()) { - if (c == '\\' || c == '|') { - result.append('\\'); - } - result.append(c); - } - return result.toString(); - } -} diff --git a/compiler/java/com/google/dart/compiler/DefaultLibrarySource.java b/compiler/java/com/google/dart/compiler/DefaultLibrarySource.java deleted file mode 100644 index 82a4c1ca3a38..000000000000 --- a/compiler/java/com/google/dart/compiler/DefaultLibrarySource.java +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import com.google.dart.compiler.util.DartSourceString; -import com.google.dart.compiler.util.Lists; -import com.google.dart.compiler.util.Paths; - -import java.io.File; -import java.io.PrintWriter; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Create a default app library specification when compiling a single dart file. - * - * @author johnlenz@google.com (John Lenz) - */ -public class DefaultLibrarySource extends UrlSource implements LibrarySource { - private static final String WRAPPED_NAME_PREFIX = "_DefaultLibrarySource.wrapper."; - private final File sourceFile; - private final Map sources; - private final Map imports; - private String source; - private String wrappedName; - - // TODO: Deprecated - public DefaultLibrarySource(List sources, String entryPoint) { - this(sources.get(0), Paths.toFiles(sources), entryPoint); - } - - // TODO: Deprecated - public DefaultLibrarySource(List sources, List imports, String entryPoint) { - this(sources.get(0), Paths.toFiles(sources), Paths.toFiles(imports), entryPoint); - } - - // TODO: Deprecated - public DefaultLibrarySource(File sourceFile, String entryPoint) { - this(sourceFile.getName(), Lists. create(sourceFile), - Lists. create(), entryPoint); - } - - public DefaultLibrarySource(String appName, List sourceFiles, String entryPoint) { - this(appName, sourceFiles, Lists. create(), entryPoint); - } - - /** - * Answer a new instance representing a {@link LibrarySource} with the - * specified name and that contains the specified imports and source files. - * - * @param appName the application name (not null, not empty) - * @param sourceFiles the source files to be included in the application (not - * null, and must contain at least one file) - * @param importFiles libraries to be imported into the application (e.g. from - * #import directives) - * @param entryPoint The name of the static method to call to invoke the - * library. A synthetic main() method will be generated which wraps a call to - * this method. Pass null to use the default main() method - * lookup. - */ - public DefaultLibrarySource(String appName, List sourceFiles, List importFiles, - String entryPoint) { - this(sourceFiles.get(0)); - - for (File file : sourceFiles) { - String relPath = Paths.relativePathFor(sourceFile, file); - this.sources.put(relPath, new UrlDartSource(file, this)); - } - for (File file : importFiles) { - String relPath = Paths.relativePathFor(sourceFile, file); - this.imports.put(relPath, new UrlLibrarySource(file)); - } - wrappedName = WRAPPED_NAME_PREFIX + appName; - source = generateSource(wrappedName, sourceFile, importFiles, sourceFiles, entryPoint); - this.sources.put(wrappedName, new DartSourceString(wrappedName, source)); - } - - private DefaultLibrarySource(File sourceFile) { - super(sourceFile); - - this.sourceFile = sourceFile; - this.sources = new HashMap(); - this.imports = new HashMap(); - } - - /** - * Generate source declaring a library. An app library will specify a - * non-null entryPoint. - * - * @param name the name of the application or library - * @param imports a collection of relative paths indicating the libraries - * imported by this application or library - * @param sources a collection of relative paths indicating the dart sources - * included in this application or library - * @param entryPoint The name of the static method to call to invoke the - * library. A synthetic main() method will be generated which wraps a call to - * this method. Pass null to use the default main() method - * lookup. - * @return the source (not null) - */ - public static String generateSource(String name, List imports, - List sources, String entryPoint) { - return generateSource(name, new File(name), Paths.toFiles(imports), - Paths.toFiles(sources), entryPoint); - } - - /** - * Generate source declaring a library. If an entryPoint is provided a main() - * method will be synthesized which wraps a call to the provided entryPoint - * method. - * - * @param name the name of the application or library - * @param baseFile the application or library file that will contain this - * source or any file in that same directory (not null, - * but does not need to exist) - * @param importFiles a collection of library files imported by this - * application or library - * @param sourceFiles a collection of dart source files included in this - * application or library - * @param entryPoint The name of the static method to call to invoke the - * library. A synthetic main() method will be generated which wraps a call to - * this method. Pass null to use the default main() method - * lookup. - * @return the source (not null) - */ - public static String generateSource(String name, File baseFile, List importFiles, - List sourceFiles, String entryPoint) { - StringWriter sw = new StringWriter(200); - PrintWriter pw = new PrintWriter(sw); - pw.println("library " + name + ";"); - if (importFiles != null) { - for (File file : importFiles) { - String relPath = file.getPath(); - if (!relPath.startsWith("dart:")) { - relPath = Paths.relativePathFor(baseFile, file); - } - if (relPath != null) { - pw.println("import '" + relPath + "';"); - } - } - } - if (sourceFiles != null) { - for (File file : sourceFiles) { - String relPath = Paths.relativePathFor(baseFile, file); - if (relPath != null) { - pw.println("part '" + relPath + "';"); - } - } - } - if (entryPoint != null) { - // synthesize a main method, which wraps the entryPoint method call - pw.println(); - pw.println(DartCompiler.MAIN_ENTRY_POINT_NAME + "() {"); - pw.println(" " + entryPoint + "();"); - pw.println("}"); - } - return sw.toString(); - } - - @Override - public Reader getSourceReader() { - return new StringReader(source); - } - - @Override - public String getUniqueIdentifier() { - return "string://" + wrappedName; - } - - @Override - public URI getUri() { - try { - // A bogus uri (but which ends with our wrappedName) - return new URI("string://" + wrappedName); - } catch (URISyntaxException e) { - throw new AssertionError(e); - } - } - - @Override - public String getName() { - return wrappedName; - } - - @Override - public LibrarySource getImportFor(String relPath) { - return imports.get(relPath); - } - - @Override - public DartSource getSourceFor(String relPath) { - return sources.get(relPath); - } -} diff --git a/compiler/java/com/google/dart/compiler/DelegatingCompilerConfiguration.java b/compiler/java/com/google/dart/compiler/DelegatingCompilerConfiguration.java deleted file mode 100644 index cf377f298c30..000000000000 --- a/compiler/java/com/google/dart/compiler/DelegatingCompilerConfiguration.java +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import com.google.dart.compiler.CommandLineOptions.CompilerOptions; -import com.google.dart.compiler.metrics.CompilerMetrics; - -import java.io.File; -import java.util.List; - -/** - * Provides a way to override a specific method of an existing instance of a CompilerConfiguration. - * - * @author zundel@google.com (Eric Ayers) - */ -public class DelegatingCompilerConfiguration implements CompilerConfiguration { - - private CompilerConfiguration delegate; - - public DelegatingCompilerConfiguration(CompilerConfiguration delegate) { - this.delegate = delegate; - } - - @Override - public boolean developerModeChecks() { - return delegate.developerModeChecks(); - } - - @Override - public List getPhases() { - return delegate.getPhases(); - } - - @Override - public CompilerMetrics getCompilerMetrics() { - return delegate.getCompilerMetrics(); - } - - @Override - public String getJvmMetricOptions() { - return delegate.getJvmMetricOptions(); - } - - @Override - public boolean typeErrorsAreFatal() { - return delegate.typeErrorsAreFatal(); - } - - @Override - public boolean warningsAreFatal() { - return delegate.warningsAreFatal(); - } - - @Override - public boolean resolveDespiteParseErrors() { - return delegate.resolveDespiteParseErrors(); - } - - @Override - public boolean incremental() { - return delegate.incremental(); - } - - @Override - public File getOutputDirectory() { - return delegate.getOutputDirectory(); - } - - @Override - public LibrarySource getSystemLibraryFor(String importSpec) { - return delegate.getSystemLibraryFor(importSpec); - } - - @Override - public CompilerOptions getCompilerOptions() { - return delegate.getCompilerOptions(); - } - - @Override - public ErrorFormat printErrorFormat() { - return delegate.printErrorFormat(); - } - - @Override - public PackageLibraryManager getPackageLibraryManager() { - return delegate.getPackageLibraryManager(); - } -} diff --git a/compiler/java/com/google/dart/compiler/DeltaAnalyzer.java b/compiler/java/com/google/dart/compiler/DeltaAnalyzer.java deleted file mode 100644 index 2829cd95f202..000000000000 --- a/compiler/java/com/google/dart/compiler/DeltaAnalyzer.java +++ /dev/null @@ -1,225 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import com.google.common.collect.Sets; -import com.google.common.io.CharStreams; -import com.google.common.io.Closeables; -import com.google.dart.compiler.ast.DartNode; -import com.google.dart.compiler.ast.DartUnit; -import com.google.dart.compiler.ast.LibraryNode; -import com.google.dart.compiler.ast.LibraryUnit; -import com.google.dart.compiler.metrics.CompilerMetrics; -import com.google.dart.compiler.parser.DartParser; -import com.google.dart.compiler.resolver.CoreTypeProvider; -import com.google.dart.compiler.resolver.CoreTypeProviderImplementation; -import com.google.dart.compiler.resolver.Element; -import com.google.dart.compiler.resolver.ElementKind; -import com.google.dart.compiler.resolver.LibraryElement; -import com.google.dart.compiler.resolver.MemberBuilder; -import com.google.dart.compiler.resolver.Resolver; -import com.google.dart.compiler.resolver.Scope; -import com.google.dart.compiler.resolver.SupertypeResolver; -import com.google.dart.compiler.resolver.TopLevelElementBuilder; -import com.google.dart.compiler.type.TypeAnalyzer; - -import java.io.IOException; -import java.io.Reader; -import java.io.Writer; -import java.net.URI; - -class DeltaAnalyzer { - private final SourceDelta delta; - private final LibraryElement enclosingLibrary; - private final CompilerConfiguration config; - private final DartCompilerListener listener; - private final CoreTypeProvider typeProvider; - private final DartCompilerContext context; - - public DeltaAnalyzer(SourceDelta delta, - LibraryElement enclosingLibrary, - LibraryElement coreLibrary, - DartNode interestNode, - int interestStart, - int interestLength, - CompilerConfiguration config, - DartCompilerListener listener) { - this.delta = delta; - this.enclosingLibrary = enclosingLibrary; - this.config = config; - this.listener = listener; - typeProvider = new CoreTypeProviderImplementation(coreLibrary.getScope(), listener); - this.context = new Context(); - } - - public DartNode analyze() throws IOException { - Source originalSource = delta.getSourceBefore(); - DartUnit unit = delta.getUnitAfter(); - if (unit == null) { - DartSource source = delta.getSourceAfter(); - unit = getParser(source).parseUnit(); - } - Scope scope = deltaLibraryScope(originalSource, unit); - // We have to create supertypes and member elements for the entire unit. For example, if you're - // doing code-completion, you are only interested in the current expression, but you may be - // code-completing on a type that is defined outside the current class. - new SupertypeResolver().exec(unit, context, typeProvider); - new MemberBuilder().exec(unit, context, typeProvider); - - // The following two phases can be narrowed down to the interest area. We currently ignore the - // interest area, but long term, we will need to narrow down to the interest area to handle - // very large files. - new Resolver(context, scope, typeProvider).exec(unit); - new TypeAnalyzer().exec(unit, context, typeProvider); - return unit; - } - - private Scope deltaLibraryScope(Source originalSource, DartUnit unit) { - // Create a library unit which holds the new unit. - LibraryUnit libraryUnit = new LibraryUnit(makeLibrarySource("delta")); - // Copy all the imports - for (LibraryNode path : enclosingLibrary.getLibraryUnit().getImportPaths()) { - libraryUnit.addImportPath(path); - } - for (LibraryUnit importUnit : enclosingLibrary.getLibraryUnit().getImportedLibraries()) { - libraryUnit.addImport(importUnit, importUnit.getEntryNode()); - } - libraryUnit.putUnit(unit); - - // Create top-level elements for the new unit. - new TopLevelElementBuilder().exec(libraryUnit, context); - new TopLevelElementBuilder().fillInLibraryScope(libraryUnit, listener); - - // Copy all the elements from the old library, except the ones declared in the original source. - Scope scope = libraryUnit.getElement().getScope(); - for (Element member : enclosingLibrary.getMembers()) { - if (member.getSourceInfo().getSource() != originalSource) { - String name = member.getName(); - if (ElementKind.of(member) == ElementKind.LIBRARY) { - name = "__library_" + ((LibraryElement) member).getLibraryUnit().getName(); - } - scope.declareElement(name, member); - } - } - return scope; - } - - private LibrarySource makeLibrarySource(final String name) { - final URI uri = URI.create(name); - return new LibrarySource() { - @Override - public String getUniqueIdentifier() { - return uri.toString(); - } - - @Override - public URI getUri() { - return uri; - } - - @Override - public Reader getSourceReader() { - throw new AssertionError(); - } - - @Override - public String getName() { - return name; - } - - @Override - public long getLastModified() { - throw new AssertionError(); - } - - @Override - public boolean exists() { - throw new AssertionError(); - } - - @Override - public DartSource getSourceFor(String relPath) { - return null; - } - - @Override - public LibrarySource getImportFor(String relPath) { - return null; - } - }; - } - - private DartParser getParser(Source source) throws IOException { - Reader r = source.getSourceReader(); - String sourceString = CharStreams.toString(r); - Closeables.close(r, false); - return new DartParser(source, sourceString, false, Sets.newHashSet(), listener, null); - } - - private class Context implements DartCompilerListener, DartCompilerContext { - @Override - public LibraryUnit getApplicationUnit() { - throw new AssertionError(); - } - - @Override - public LibraryUnit getAppLibraryUnit() { - throw new AssertionError(); - } - - @Override - public LibraryUnit getLibraryUnit(LibrarySource lib) { - throw new AssertionError(); - } - - @Override - public Reader getArtifactReader(Source source, String part, String extension) { - throw new AssertionError(); - } - - @Override - public URI getArtifactUri(DartSource source, String part, String extension) { - throw new AssertionError(); - } - - @Override - public Writer getArtifactWriter(Source source, String part, String extension) { - throw new AssertionError(); - } - - @Override - public boolean isOutOfDate(Source source, Source base, String extension) { - throw new AssertionError(); - } - - @Override - public CompilerMetrics getCompilerMetrics() { - return null; - } - - @Override - public CompilerConfiguration getCompilerConfiguration() { - return config; - } - - @Override - public LibrarySource getSystemLibraryFor(String importSpec) { - throw new AssertionError(); - } - - @Override - public void onError(DartCompilationError event) { - listener.onError(event); - } - - @Override - public void unitAboutToCompile(DartSource source, boolean diet) { - } - - @Override - public void unitCompiled(DartUnit unit) { - } - } -} diff --git a/compiler/java/com/google/dart/compiler/ErrorCode.java b/compiler/java/com/google/dart/compiler/ErrorCode.java deleted file mode 100644 index 395bcaab8ac5..000000000000 --- a/compiler/java/com/google/dart/compiler/ErrorCode.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. -package com.google.dart.compiler; - -import com.google.dart.compiler.util.apache.StringUtils; - -/** - * The behavior common to objects representing error codes associated with - * {@link DartCompilationError Dart compilation errors}. - */ -public interface ErrorCode { - /** - * Return the message template used to create the message to be displayed for this error. - */ - String getMessage(); - - /** - * @return the {@link ErrorSeverity} of this error. - */ - ErrorSeverity getErrorSeverity(); - - /** - * @return the {@link SubSystem} which issued this error. - */ - SubSystem getSubSystem(); - - /** - * @return true if this {@link ErrorCode} should cause recompilation of the source - * during next incremental compilation. - */ - boolean needsRecompilation(); - - public class Helper { - /** - * @return the "qualified name" of the given {@link ErrorCode} enumeration, good for passing it - * to {@link #forQualifiedName(String)}. - */ - public static String toQualifiedName(ErrorCode errorCode) { - return errorCode.getClass().getCanonicalName() + "." + ((Enum) errorCode).name(); - } - - /** - * @return the {@link ErrorCode} enumeration constant for string from - * {@link #toQualifiedName(ErrorCode)}. - */ - public static ErrorCode forQualifiedName(String qualifiedName) { - try { - String className = StringUtils.substringBeforeLast(qualifiedName, "."); - String fieldName = StringUtils.substringAfterLast(qualifiedName, "."); - Class errorCodeClass = Class.forName(className); - return (ErrorCode) errorCodeClass.getField(fieldName).get(null); - } catch (Throwable e) { - return null; - } - } - } -} diff --git a/compiler/java/com/google/dart/compiler/ErrorFormatter.java b/compiler/java/com/google/dart/compiler/ErrorFormatter.java deleted file mode 100644 index b04ed1303910..000000000000 --- a/compiler/java/com/google/dart/compiler/ErrorFormatter.java +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -/** - * A class that that helps presenting error messages in the command line. - * - * @see DefaultErrorFormatter - * @see PrettyErrorFormatter - */ -public interface ErrorFormatter { - - public void format(DartCompilationError event); -} diff --git a/compiler/java/com/google/dart/compiler/ErrorSeverity.java b/compiler/java/com/google/dart/compiler/ErrorSeverity.java deleted file mode 100644 index 49d76882fda2..000000000000 --- a/compiler/java/com/google/dart/compiler/ErrorSeverity.java +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -/** - * The severity of {@link ErrorCode}. - */ -public enum ErrorSeverity { - /** - * Fatal error. - */ - ERROR("E"), - /** - * Warning, may become error with -Werror command line flag. - */ - WARNING("W"), - /** - * Info, not considered an official warning - */ - INFO("I"); - - final String name; - - ErrorSeverity(String name) { - this.name = name; - } - - public String getName() { - return name; - } -} \ No newline at end of file diff --git a/compiler/java/com/google/dart/compiler/FileBasedSystemLibraryProvider.java b/compiler/java/com/google/dart/compiler/FileBasedSystemLibraryProvider.java deleted file mode 100644 index d659f767ee16..000000000000 --- a/compiler/java/com/google/dart/compiler/FileBasedSystemLibraryProvider.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2012, the Dart project authors. - * - * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.eclipse.org/legal/epl-v10.html - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package com.google.dart.compiler; - -import java.io.File; -import java.io.IOException; -import java.net.URI; - -/** - * A file-based {@link SystemLibraryProvider} that reads dart-sdk/lib/_internal/libraries.dart for - * system library information. - */ -public class FileBasedSystemLibraryProvider extends SystemLibraryProvider { - - private File sdkLibPath; - - /** - * Create a {@link FileBasedSystemLibraryProvider} with the given path to the dart SDK. - */ - public FileBasedSystemLibraryProvider(File sdkPath) { - super(new File(sdkPath, "lib").getAbsoluteFile().toURI()); - //TODO(pquitslund): remove this duplicated file creation - sdkLibPath = new File(sdkPath, "lib").getAbsoluteFile(); - } - - @Override - protected SystemLibrariesReader createReader() throws IOException { - return new SystemLibrariesReader(sdkLibPath); - } - - @Override - public SystemLibrary createSystemLibrary(String name, String host, String pathToLib, - String category, boolean documented, boolean implementation) { - - - File dir = new File(sdkLibPath, host); - - File libFile = new File(dir, pathToLib); - if (!libFile.isFile()) { - throw new InternalCompilerException("Error mapping dart:" + host + ", path " - + libFile.getAbsolutePath() + " is not a file."); - } - - return new SystemLibrary( - name, host, pathToLib, dir, category, documented, implementation); - } - - @Override - public boolean exists(URI uri) { - return new File(uri).exists(); - } - - @Override - public URI resolveHost(String host, URI uri) { - return new File(sdkLibPath, host).toURI().resolve("." + uri.getPath()); - } - -} \ No newline at end of file diff --git a/compiler/java/com/google/dart/compiler/InternalCompilerException.java b/compiler/java/com/google/dart/compiler/InternalCompilerException.java deleted file mode 100644 index 2c073c5bd54c..000000000000 --- a/compiler/java/com/google/dart/compiler/InternalCompilerException.java +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -/** - * Exception thrown when the compiler encounters an unexpected internal error. - */ -public class InternalCompilerException extends RuntimeException { - private static final long serialVersionUID = 1L; - - public InternalCompilerException(String message) { - super(message); - } - - public InternalCompilerException(String message, Throwable t) { - super(message, t); - } -} diff --git a/compiler/java/com/google/dart/compiler/LibraryDeps.java b/compiler/java/com/google/dart/compiler/LibraryDeps.java deleted file mode 100644 index bcdf2e46aca1..000000000000 --- a/compiler/java/com/google/dart/compiler/LibraryDeps.java +++ /dev/null @@ -1,313 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. -package com.google.dart.compiler; - -import com.google.common.base.Objects; -import com.google.common.base.Splitter; -import com.google.common.base.Strings; -import com.google.common.collect.Iterables; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import com.google.dart.compiler.ast.DartUnit; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.Reader; -import java.io.Writer; -import java.net.URI; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -/** - * Represents a library's dependencies artifact. - */ -public class LibraryDeps { - private static final String VERSION = "v00001"; - - /** - * Each dependency record contains the library in which it was found, name of the unit in this - * library and last-modified timestamp. Any change in the timestamp of the target dependency will - * force a recompile of the associated compilation unit. - */ - public static class Dependency { - private final URI libUri; - private final String unitName; - private final long lastModified; - - public Dependency(URI libUri, String unitName, long lastModified) { - this.libUri = libUri; - this.unitName = unitName; - this.lastModified = lastModified; - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof Dependency) { - Dependency dep = (Dependency) obj; - return Objects.equal(libUri, dep.libUri) && Objects.equal(unitName, dep.unitName); - } - return false; - } - - @Override - public int hashCode() { - return Objects.hashCode(libUri, unitName); - } - - public URI getLibUri() { - return libUri; - } - - public String getUnitName() { - return unitName; - } - - public long getLastModified() { - return lastModified; - } - } - - public static class Source { - private final Set deps = Sets.newHashSet(); - private final Set topSymbols = Sets.newHashSet(); - private final Set allSymbols = Sets.newHashSet(); - private final Set holes = Sets.newHashSet(); - private boolean shouldRecompileOnAnyTopLevelChange = false; - - /** - * @return the {@link Set} of {@link Dependency}s. - */ - public Set getDeps() { - return deps; - } - - /** - * @return the names of top-level elements, such as methods and classes. - */ - public Set getTopSymbols() { - return topSymbols; - } - - /** - * @return the names of all elements in unit, such as names of local variables, fields, etc. - */ - public Set getAllSymbols() { - return allSymbols; - } - - /** - * @return the names of functions, which are invoked without qualifier. So, declaration or - * removing function with such name on top-level should cause recompiling. - */ - public Set getHoles() { - return holes; - } - - /** - * @return true if this unit should be recompiled on any change in the set of - * top-level symbols. Typically unit has compilation errors, which potentially may be - * fixed, so we should recompile this unit. - */ - public boolean shouldRecompileOnAnyTopLevelChange() { - return shouldRecompileOnAnyTopLevelChange; - } - - /** - * Adds new {@link Dependency}. - */ - public void addDep(Dependency dep) { - deps.add(dep); - } - - /** - * Adds symbol to the {@link Set} of top symbols. - */ - public void addTopSymbol(String symbol) { - if (!Strings.isNullOrEmpty(symbol)) { - topSymbols.add(symbol); - } - } - - /** - * Adds symbol to the {@link Set} of all symbols. - */ - public void addAllSymbol(String symbol) { - allSymbols.add(symbol); - } - - /** - * Adds new hole for {@link #getHoles()}. - */ - public void addHole(String hole) { - holes.add(hole); - } - } - - public static LibraryDeps fromReader(Reader reader) { - try { - return fromReaderEx(reader); - } catch (Throwable e) { - return null; - } - } - - private static LibraryDeps fromReaderEx(Reader reader) throws Exception { - LibraryDeps deps = new LibraryDeps(); - BufferedReader buf = new BufferedReader(reader); - // Check version. - { - String line = buf.readLine(); - if (!Objects.equal(line, VERSION)) { - return deps; - } - } - // Read units dependencies. - String relPath; - while (null != (relPath = buf.readLine())) { - Source source = new Source(); - // Read flags. - source.shouldRecompileOnAnyTopLevelChange = Boolean.parseBoolean(buf.readLine()); - // Read top symbols. - { - String line = buf.readLine(); - Iterable topSymbols = Splitter.on(' ').omitEmptyStrings().split(line); - Iterables.addAll(source.topSymbols, topSymbols); - } - // Read all symbols. - { - String line = buf.readLine(); - Iterable allSymbols = Splitter.on(' ').omitEmptyStrings().split(line); - Iterables.addAll(source.allSymbols, allSymbols); - } - // Read holes. - { - String line = buf.readLine(); - Iterable holes = Splitter.on(' ').omitEmptyStrings().split(line); - Iterables.addAll(source.holes, holes); - } - // Read dependencies. - while (true) { - String line = buf.readLine(); - // Blank line: next unit. - if (line.length() == 0) { - break; - } - // Parse line. - String[] parts = line.split(" "); - source.deps.add(new Dependency(new URI(parts[0]), parts[1], Long.parseLong(parts[2]))); - } - // Remember dependencies for current unit. - deps.sources.put(relPath, source); - } - return deps; - } - - private final Map sources = Maps.newHashMap(); - - public LibraryDeps() { - } - - /** - * @return the relative paths of all units with remembered dependencies. - */ - public Set getUnitPaths() { - return sources.keySet(); - } - - /** - * @return all {@link Source} descriptions for all units in this library. - */ - public Iterable getSources() { - return sources.values(); - } - - /** - * @return the {@link Source} description of the unit with given path. - */ - public Source getSource(String relPath) { - return sources.get(relPath); - } - - /** - * Remembers {@link Dependency}s of the unit with given path. - */ - public void putSource(String relPath, Source source) { - sources.put(relPath, source); - } - - /** - * Update the library dependencies to reflect this unit's classes. - */ - public void update(DartCompilerMainContext context, DartUnit unit) { - Source source = new Source(); - DartSource unitSource = (DartSource) unit.getSourceInfo().getSource(); - String relPath = unitSource.getRelativePath(); - putSource(relPath, source); - // Remember dependencies. - LibraryDepsVisitor.exec(unit, source); - // Fill Source with symbols. - for (String name : unit.getDeclarationNames()) { - source.addAllSymbol(name); - } - for (String name : unit.getTopDeclarationNames()) { - source.addTopSymbol(name); - } - // Analyze errors and see if any of them should force recompilation. - List sourceErrors = context.getSourceErrors(unitSource); - for (DartCompilationError error : sourceErrors) { - if (error.getErrorCode().needsRecompilation()) { - source.shouldRecompileOnAnyTopLevelChange = true; - break; - } - } - } - - public void write(Writer writer) throws IOException { - // Write version. - writer.write(VERSION); - writer.write('\n'); - // Write entries. - for (Entry entry : sources.entrySet()) { - String relPath = entry.getKey(); - Source source = entry.getValue(); - // Unit name. - writer.write(relPath); - writer.write('\n'); - // Flags. - writer.write(Boolean.toString(source.shouldRecompileOnAnyTopLevelChange)); - writer.write('\n'); - // Write top symbols. - for (String symbol : source.topSymbols) { - writer.write(symbol); - writer.write(' '); - } - writer.write('\n'); - // Write all symbols. - for (String symbol : source.allSymbols) { - writer.write(symbol); - writer.write(' '); - } - writer.write('\n'); - // Write holes. - for (String hole : source.holes) { - writer.write(hole); - writer.write(' '); - } - writer.write('\n'); - // Write dependencies. - for (Dependency dep : source.deps) { - writer.write(dep.libUri.toString()); - writer.write(' '); - writer.write(dep.unitName); - writer.write(' '); - writer.write(Long.toString(dep.lastModified)); - writer.write('\n'); - } - // Empty line after each unit. - writer.write('\n'); - } - } -} diff --git a/compiler/java/com/google/dart/compiler/LibraryDepsVisitor.java b/compiler/java/com/google/dart/compiler/LibraryDepsVisitor.java deleted file mode 100644 index d0acd51610ac..000000000000 --- a/compiler/java/com/google/dart/compiler/LibraryDepsVisitor.java +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. -package com.google.dart.compiler; - -import com.google.dart.compiler.ast.ASTVisitor; -import com.google.dart.compiler.ast.DartClass; -import com.google.dart.compiler.ast.DartIdentifier; -import com.google.dart.compiler.ast.DartMethodInvocation; -import com.google.dart.compiler.ast.DartParameterizedTypeNode; -import com.google.dart.compiler.ast.DartPropertyAccess; -import com.google.dart.compiler.ast.DartTypeNode; -import com.google.dart.compiler.ast.DartUnit; -import com.google.dart.compiler.resolver.Element; -import com.google.dart.compiler.resolver.ElementKind; -import com.google.dart.compiler.type.InterfaceType; -import com.google.dart.compiler.type.Type; -import com.google.dart.compiler.type.TypeKind; - -import java.net.URI; - -/** - * A visitor that fills in {@link LibraryDeps} for a compilation unit. - */ -public class LibraryDepsVisitor extends ASTVisitor { - /** - * Fill in {@link LibraryDeps} from a {@link DartUnit}. - */ - static void exec(DartUnit unit, LibraryDeps.Source source) { - LibraryDepsVisitor v = new LibraryDepsVisitor(source); - unit.accept(v); - } - - private final LibraryDeps.Source source; - private Element currentClass; - - private LibraryDepsVisitor(LibraryDeps.Source source) { - this.source = source; - } - - @Override - public Void visitIdentifier(DartIdentifier node) { - Element target = node.getElement(); - ElementKind kind = ElementKind.of(target); - // Add dependency on the field or method. - switch (kind) { - case FIELD: - case METHOD: { - Element enclosing = target.getEnclosingElement(); - addHoleIfUnqualifiedSuper(node, enclosing); - if (enclosing.getKind().equals(ElementKind.LIBRARY)) { - addElementDependency(target); - } - break; - } - } - // Add dependency on the computed type of identifiers. - switch (kind) { - case NONE: - source.addHole(node.getName()); - break; - case DYNAMIC: - break; - default: { - Type type = target.getType(); - if (type != null) { - Element element = type.getElement(); - if (ElementKind.of(element).equals(ElementKind.CLASS)) { - addElementDependency(element); - } - } - break; - } - } - return null; - } - - @Override - public Void visitPropertyAccess(DartPropertyAccess node) { - if (node.getQualifier() instanceof DartIdentifier) { - DartIdentifier qualifier = (DartIdentifier) node.getQualifier(); - Element target = qualifier.getElement(); - if (target != null && target.getKind() == ElementKind.LIBRARY) { - // Handle library prefixes normally. - // The prefix part of the qualifier doesn't contain any resolvable library source info. - return super.visitPropertyAccess(node); - } - } - // Skip rhs of property accesses, so that all identifiers we visit will be unqualified. - if (node.isCascade()) { - return null; - } - return node.getQualifier().accept(this); - } - - @Override - public Void visitClass(DartClass node) { - currentClass = node.getElement(); - node.visitChildren(this); - currentClass = null; - return null; - } - - @Override - public Void visitParameterizedTypeNode(DartParameterizedTypeNode node) { - if (TypeKind.of(node.getType()).equals(TypeKind.INTERFACE)) { - addElementDependency(((InterfaceType) node.getType()).getElement()); - } - node.visitChildren(this); - return null; - } - - @Override - public Void visitTypeNode(DartTypeNode node) { - if (TypeKind.of(node.getType()).equals(TypeKind.INTERFACE)) { - addElementDependency(((InterfaceType) node.getType()).getElement()); - } - node.visitChildren(this); - return null; - } - - /** - * Add a 'hole' for the given identifier, if its declaring class is a superclass of the current - * class. A 'hole' dependency specifies a name that, if filled by something in the library scope, - * would require this unit to be recompiled. - * - * This situation occurs because names in the library scope bind more strongly than unqualified - * superclass members. - */ - private void addHoleIfUnqualifiedSuper(DartIdentifier node, Element holder) { - if (isQualified(node)) { - return; - } - if (ElementKind.of(holder) == ElementKind.CLASS && holder != currentClass) { - source.addHole(node.getName()); - } - } - - /** - * Adds a direct dependency on the unit providing given {@link Element}. - */ - private void addElementDependency(Element element) { - DartSource elementSource = (DartSource) element.getSourceInfo().getSource(); - if (elementSource != null) { - LibrarySource library = elementSource.getLibrary(); - if (library != null) { - URI libUri = library.getUri(); - LibraryDeps.Dependency dep = new LibraryDeps.Dependency(libUri, elementSource.getName(), - elementSource.getLastModified()); - source.addDep(dep); - } - } - } - - /** - * @return true if given {@link DartIdentifier} is "name" part of qualified property - * access or method invocation. - */ - private static boolean isQualified(DartIdentifier node) { - if (node.getParent() instanceof DartPropertyAccess) { - return ((DartPropertyAccess) node.getParent()).getName() == node; - } - if (node.getParent() instanceof DartMethodInvocation) { - return ((DartMethodInvocation) node.getParent()).getFunctionName() == node; - } - return false; - } -} diff --git a/compiler/java/com/google/dart/compiler/LibrarySource.java b/compiler/java/com/google/dart/compiler/LibrarySource.java deleted file mode 100644 index 1d2ab24bbb3e..000000000000 --- a/compiler/java/com/google/dart/compiler/LibrarySource.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import java.io.IOException; - -/** - * Abstract interface to library source. - * - * TODO(jgw): Consider requiring implementors to intern LibrarySource instances so that users can - * depend upon reference equality to avoid cycles (or require them to use .equals()). As it is, - * there are two pieces of code in {@link DartCompiler} that do this manually, and it's a little - * tricky. - */ -public interface LibrarySource extends Source { - - /** - * Answer the {@link LibrarySource} for the path specified in the receiver's - * imports declaration - * - * @param relPath path to the {@link LibrarySource} relative to the receiver - * @return the dart source or null if could not be found - */ - LibrarySource getImportFor(String relPath) throws IOException; - - /** - * Answer the {@link DartSource} for the path specified in the receiver's - * sources declaration - * - * @param relPath the path to the {@link DartSource} relative to the receiver - * @return the dart source or null if could not be found - */ - DartSource getSourceFor(String relPath); -} diff --git a/compiler/java/com/google/dart/compiler/PackageLibraryManager.java b/compiler/java/com/google/dart/compiler/PackageLibraryManager.java deleted file mode 100644 index ddd5d8f64ec5..000000000000 --- a/compiler/java/com/google/dart/compiler/PackageLibraryManager.java +++ /dev/null @@ -1,346 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - - -/** - * Manages the collection of {@link SystemLibrary}s. - */ -public class PackageLibraryManager { - - public static class NotADartShortUriException extends RuntimeException { - private static final long serialVersionUID = 1L; - - public NotADartShortUriException(String uriString) { - super("Expected dart:, got: " + uriString); - } - - public NotADartShortUriException(URI uri) { - super("Expected dart:, got: " + uri.toString()); - } - } - - /** - * The "any" platform is meant to have definitions for all known dart system libraries. - * Other implementations may only contain a subset. - */ - public static final String DEFAULT_PLATFORM = "any"; - public static final File DEFAULT_SDK_PATH = new File(System.getProperty( - "com.google.dart.sdk", "../")); - - public static final File DEFAULT_PACKAGE_ROOT = new File("packages"); - public static final List DEFAULT_PACKAGE_ROOTS = Arrays.asList(new File[] {DEFAULT_PACKAGE_ROOT}); - - public static final String PACKAGE_SCHEME = "package"; - public static final String PACKAGE_SCHEME_SPEC = "package:"; - - public static final String DART_SCHEME = "dart"; - public static final String DART_SCHEME_SPEC = "dart:"; - - - /** - * Answer true if the string is a dart spec - */ - public static boolean isDartSpec(String spec) { - return spec != null && spec.startsWith(DART_SCHEME_SPEC); - } - - /** - * Answer true if the specified URI has a "dart" scheme - */ - public static boolean isDartUri(URI uri) { - return uri != null && DART_SCHEME.equals(uri.getScheme()); - } - - /** - * Answer true if the string is a package spec - */ - public static boolean isPackageSpec(String spec) { - return spec != null && spec.startsWith(PACKAGE_SCHEME_SPEC); - } - - /** - * Answer true if the specified URI has a "package" scheme - */ - public static boolean isPackageUri(URI uri) { - return uri != null && PACKAGE_SCHEME.equals(uri.getScheme()); - } - - private static SystemLibraryManager SDK_LIBRARY_MANAGER; - - private List packageRoots = new ArrayList(); - private List packageRootsUri = new ArrayList(); - - public PackageLibraryManager() { - this(DEFAULT_SDK_PATH, DEFAULT_PLATFORM); - } - - public PackageLibraryManager(File sdkPath, String platformName) { - this(new FileBasedSystemLibraryProvider(sdkPath)); - } - - public PackageLibraryManager(SystemLibraryProvider libraryProvider) { - initLibraryManager(libraryProvider); - setPackageRoots(DEFAULT_PACKAGE_ROOTS); - } - - protected void initLibraryManager(SystemLibraryProvider libraryProvider) { - if (SDK_LIBRARY_MANAGER == null) { - SDK_LIBRARY_MANAGER = new SystemLibraryManager(libraryProvider); - } - } - - - /** - * Expand a relative or short URI (e.g. "dart:html") which is implementation independent to its - * full URI (e.g. "dart://html/com/google/dart/htmllib/html.dart"). - * - * @param uri the relative URI - * @return the expanded URI - * or the original URI if it could not be expanded - * or null if the uri is of the form "dart:" but does not correspond to a system library - */ - public URI expandRelativeDartUri(URI uri) throws AssertionError { - if (isDartUri(uri)) { - return SDK_LIBRARY_MANAGER.expandRelativeDartUri(uri); - } - if (isPackageUri(uri)){ - String host = uri.getHost(); - if (host == null) { - String spec = uri.getSchemeSpecificPart(); - if (!spec.startsWith("//")){ - try { - if (spec.startsWith("/")){ - // TODO(keertip): fix to handle spaces - uri = new URI(PACKAGE_SCHEME + ":/" + spec); - } else { - uri = new URI(PACKAGE_SCHEME + "://" + spec); - } - } catch (URISyntaxException e) { - throw new AssertionError(e); - } - } - } - } - return uri; - } - - - - /** - * Given an absolute file URI (e.g. "file:/some/install/directory/dart-sdk/lib/core/bool.dart"), - * answer the corresponding dart: URI (e.g. "dart://core/bool.dart") for that file URI, - * or null if the file URI does not map to a dart: URI - * @param fileUri the file URI - * @return the dart URI or null - */ - public URI getRelativeUri(URI fileUri) { - // TODO (danrubel): does not convert dart: libraries outside the dart-sdk/lib directory - if (fileUri == null || !fileUri.getScheme().equals("file")) { - return null; - } - - URI relativeUri = SDK_LIBRARY_MANAGER.getRelativeUri(fileUri); - if (relativeUri != null){ - return relativeUri; - } - - for (URI rootUri : packageRootsUri){ - relativeUri = rootUri.relativize(fileUri); - if (relativeUri.getScheme() == null) { - try { - return new URI(null, null, "package://" + relativeUri.getPath(), null, null); - } catch (URISyntaxException e) { - //$FALL-THROUGH$ - } - } - } - return null; - } - - /** - * Given a package URI (package:foo/foo.dart), convert it into a file system URI. - */ - public URI resolvePackageUri(String packageUriRef) { - if (packageUriRef.startsWith(PACKAGE_SCHEME_SPEC)) { - String relPath = packageUriRef.substring(PACKAGE_SCHEME_SPEC.length()); - if (relPath.startsWith("/")){ - relPath = relPath.replaceAll("^\\/+", ""); - } - for (URI rootUri : packageRootsUri){ - URI fileUri = rootUri.resolve(relPath); - File file = new File(fileUri); - if (file.exists()){ - try { - return file.getCanonicalFile().toURI(); - } catch (IOException e) { - file.toURI(); - } - } - } - // don't return null for package scheme - return packageRootsUri.get(0).resolve(relPath); - } - return null; - } - - /** - * Answer the original "dart:" URI for the specified resolved URI or null if - * it does not map to a short URI. - */ - public URI getShortUri(URI uri) { - URI shortUri = SDK_LIBRARY_MANAGER.getShortUri(uri); - if (shortUri != null){ - return shortUri; - } - shortUri = getRelativeUri(uri); - if (shortUri != null){ - try { - if (shortUri.getHost() != null){ - return new URI(null, null, shortUri.getScheme() + ":" + shortUri.getHost() + shortUri.getPath(),null, null); - } - else { - return new URI(null, null, shortUri.getScheme() + ":" + shortUri.getSchemeSpecificPart(), null, null); - } - } catch (URISyntaxException e) { - } - } - return null; - } - - /** - * Expand a relative or short URI (e.g. "dart:html") which is implementation independent to its - * full URI (e.g. "dart://html/com/google/dart/htmllib/html.dart") and then translate that URI to - * a "file:" URI (e.g. - * "file:/some/install/directory/com/google/dart/htmllib/html.dart"). - * - * @param uri the original URI - * @return the expanded and translated URI, which may be null and may not exist - * @exception RuntimeException if the URI is a "dart" scheme, but does not map to a defined system - * library - */ - public URI resolveDartUri(URI uri) { - return translateDartUri(expandRelativeDartUri(uri)); - } - - - public List getPackageRoots(){ - return packageRoots; - } - - - public void setPackageRoots(List roots){ - if (roots == null || roots.isEmpty()){ - roots = DEFAULT_PACKAGE_ROOTS; - } - packageRoots.clear(); - for (File file : roots){ - packageRoots.add(file.getAbsoluteFile()); - } - packageRootsUri.clear(); - for (File file : roots){ - packageRootsUri.add(file.toURI()); - } - } - - /** - * Translate the URI from dart://[host]/[pathToLib] (e.g. dart://html/html.dart) - * to a "file:" URI (e.g. "file:/some/install/directory/html.dart") - * - * @param uri the original URI - * @return the translated URI, which may be null and may not exist - * @exception RuntimeException if the URI is a "dart" scheme, - * but does not map to a defined system library - */ - public URI translateDartUri(URI uri) { - if (isDartUri(uri)) { - return SDK_LIBRARY_MANAGER.translateDartUri(uri); - } - if (isPackageUri(uri)){ - URI fileUri; - for (URI rootUri : packageRootsUri){ - fileUri = getResolvedPackageUri(uri, rootUri); - File file = new File(fileUri); - if (file.exists()){ - try { - return file.getCanonicalFile().toURI(); - } catch (IOException e) { - return file.toURI(); - } - } - } - // resolve against first package root - fileUri = getResolvedPackageUri(uri, packageRootsUri.get(0)); - return fileUri; - } - return uri; - } - - - /** - * Given a uri, resolve against the list of package roots, used to find generated files - * @return uri - resolved uri if file exists, else return given uri - */ - public URI findExistingFileInPackages(URI fileUri){ - - URI resolvedUri = getRelativeUri(fileUri); - if (isPackageUri(resolvedUri)){ - resolvedUri = resolvePackageUri(resolvedUri.toString()); - return resolvedUri; - } - return fileUri; - } - - /** - * Resolves the given uri against the package root uri - */ - private URI getResolvedPackageUri(URI uri, URI packageRootUri) { - URI fileUri; - // TODO(keertip): Investigate further - // if uri.getHost() returns null, then it is resolved right - // so use uri.getAuthority to resolve - // package://third_party/dart_lang/lib/unittest/unittest.dart - if (uri.getHost() != null){ - fileUri = packageRootUri.resolve(uri.getHost() + uri.getPath()); - } else { - fileUri = packageRootUri.resolve(uri.getAuthority() + uri.getPath()); - } - return fileUri; - } - - /** - * Answer a collection of all bundled library URL specs (e.g. "dart:html"). - * - * @return a collection of specs (not null, contains no nulls) - */ - public Collection getAllLibrarySpecs() { - return SDK_LIBRARY_MANAGER.getAllLibrarySpecs(); - } - - protected SystemLibrary[] getDefaultLibraries() { - return SDK_LIBRARY_MANAGER.getDefaultLibraries(); - } - - public Collection getSystemLibraries(){ - return SDK_LIBRARY_MANAGER.getAllSystemLibraries(); - } - - /** - * Check if this URI denotes a patch file. - */ - public static boolean isPatchFile(File file) { - return SDK_LIBRARY_MANAGER.isPatchFile(file.toURI()); - } - -} diff --git a/compiler/java/com/google/dart/compiler/PrettyErrorFormatter.java b/compiler/java/com/google/dart/compiler/PrettyErrorFormatter.java deleted file mode 100644 index 0baa65174e68..000000000000 --- a/compiler/java/com/google/dart/compiler/PrettyErrorFormatter.java +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import com.google.common.io.Closeables; -import com.google.dart.compiler.CompilerConfiguration.ErrorFormat; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.PrintStream; -import java.io.Reader; - -/** - * An error formatter that scans the source file and prints the error line and - * some context around it. This formatter has two modes: with or without color. - * When using colors, it prints the error message in red, and it highlights the - * portion of the line containing the error in red. Without colors, it prints an - * extra line underlying the portion of the line containing the error. - */ -public class PrettyErrorFormatter extends DefaultErrorFormatter { - public static final String ERROR_BOLD_COLOR = "\033[31;1m"; - public static final String ERROR_COLOR = "\033[31m"; - - // Mix ANSI with xterm colors, giving ANSI priority. The terminal should ignore xterm codes - // if it doesn't support them. - public static final String WARNING_BOLD_COLOR = "\033[33;1m\033[38;5;202m"; - public static final String WARNING_COLOR = "\033[33m\033[38;5;208m"; - - public static final String NO_COLOR = "\033[0m"; - - private final boolean useColor; - - public PrettyErrorFormatter(PrintStream outputStream, - boolean useColor, - ErrorFormat errorFormat) { - super(outputStream, errorFormat); - this.useColor = useColor; - } - - @Override - public void format(DartCompilationError event) { - Source sourceFile = event.getSource(); - - // if this is an unknown source type, default to the basic error formatter - if (!(sourceFile instanceof DartSource) && !(sourceFile instanceof LibrarySource)) { - super.format(event); - return; - } - - BufferedReader reader = null; - try { - Reader sourceReader = sourceFile.getSourceReader(); - if (sourceReader != null) { - reader = new BufferedReader(sourceReader); - } - - // get the error line and the line above it (note: line starts at 1) - int line = event.getLineNumber(); - String lineBefore = null; - String lineText = null; - - if (reader != null) { - lineBefore = getLineAt(reader, line - 1); - lineText = getLineAt(reader, 1); - } - - // if there is no line to highlight, default to the basic error formatter - if (lineText == null) { - super.format(event); - return; - } - - // get column/length and ensure they are within the line limits. - int col = event.getColumnNumber() - 1; - int length = event.getLength(); - col = between(col, 0, lineText.length()); - length = between(length, 0, lineText.length() - col); - length = length == 0 ? lineText.length() - col : length; - - // print the error message - StringBuilder buf = new StringBuilder(); - if (useColor) { - buf.append(event.getErrorCode().getErrorSeverity() == ErrorSeverity.WARNING - ? WARNING_BOLD_COLOR : ERROR_BOLD_COLOR); - } - appendError(buf, event); - if (useColor) { - buf.append(NO_COLOR); - } - buf.append("\n"); - // show the previous line for context - if (lineBefore != null) { - buf.append(String.format("%6d: %s\n", line - 1, lineBefore)); - } - - if (useColor) { - // highlight error in red - buf.append(String.format("%6d: %s%s%s%s%s\n", - line, - lineText.substring(0, col), - event.getErrorCode().getErrorSeverity() == ErrorSeverity.WARNING - ? WARNING_COLOR : ERROR_COLOR, - lineText.substring(col, col + length), - NO_COLOR, - lineText.substring(col + length))); - } else { - // print the error line without formatting - buf.append(String.format("%6d: %s\n", line, lineText)); - - // underline error portion - buf.append(" "); - for (int i = 0; i < col; ++i) { - buf.append(' '); - } - buf.append('~'); - if (length > 1) { - for (int i = 0; i < length - 2; ++i) { - buf.append('~'); - } - buf.append('~'); - } - buf.append('\n'); - } - - outputStream.print(buf.toString()); - } catch (IOException ex) { - super.format(event); - } finally { - if (reader != null) { - Closeables.closeQuietly(reader); - } - } - } - - private String getLineAt(BufferedReader reader, int line) throws IOException { - if (line <= 0) { - return null; - } - String currentLine = null; - // TODO(sigmund): do something more efficient - we currently do a linear - // scan of the file every time an error is reported. This will not scale - // when many errors are reported on the same file. - while ((currentLine = reader.readLine()) != null && line-- > 1){} - return currentLine; - } - - /** - * Returns the closest value in {@code [start,end]} to the given value. If - * the given range is entirely empty, then {@code start} is returned. - */ - private static int between(int val, int start, int end) { - return Math.max(start, Math.min(val, end)); - } -} diff --git a/compiler/java/com/google/dart/compiler/Source.java b/compiler/java/com/google/dart/compiler/Source.java deleted file mode 100644 index eb43b653a78b..000000000000 --- a/compiler/java/com/google/dart/compiler/Source.java +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import java.io.IOException; -import java.io.Reader; -import java.net.URI; -import java.util.Date; - -/** - * Abstract interface to a source file. - */ -public interface Source { - - /** - * Determines whether the given source exists. - */ - boolean exists(); - - /** - * Returns the last-modified timestamp for this source, using the same units as - * {@link Date#getTime()}. - */ - long getLastModified(); - - /** - * Gets the name of this source. - */ - String getName(); - - /** - * Gets a reader for the dart file's source code. The caller is responsible for closing the - * returned reader. - */ - Reader getSourceReader() throws IOException; - - /** - * Return an identifier that will uniquely identify this source. - * - * @return the unique identifier for this source. - */ - String getUniqueIdentifier(); - - /** - * Gets the identifier for this source. This is used to uniquely identify the - * source, but should not be used to obtain the source content. Use - * {@link #getSourceReader()} to obtain the source content. - */ - URI getUri(); -} diff --git a/compiler/java/com/google/dart/compiler/SourceDelta.java b/compiler/java/com/google/dart/compiler/SourceDelta.java deleted file mode 100644 index e048c4f9a45f..000000000000 --- a/compiler/java/com/google/dart/compiler/SourceDelta.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import com.google.dart.compiler.ast.DartUnit; - -/** - * Representation of changes to source. - */ -public abstract class SourceDelta { - public abstract Source getSourceBefore(); - - public abstract DartSource getSourceAfter(); - - public abstract DartUnit getUnitAfter(); - - public final SourceDelta after(DartSource sourceAfter) { - return new BeforeAfter(getSourceBefore(), sourceAfter, null); - } - - public final SourceDelta after(DartUnit nodeAfter) { - return new BeforeAfter(getSourceBefore(), null, nodeAfter); - } - - public static SourceDelta before(final DartSource sourceBefore) { - return new BeforeAfter(sourceBefore, sourceBefore, null); - } - - private static class BeforeAfter extends SourceDelta { - private final Source sourceBefore; - private final DartSource sourceAfter; - private final DartUnit nodeAfter; - - BeforeAfter(Source sourceBefore, DartSource sourceAfter, DartUnit nodeAfter) { - this.sourceBefore = sourceBefore; - this.sourceAfter = sourceAfter; - this.nodeAfter = nodeAfter; - } - - @Override - public Source getSourceBefore() { - return sourceBefore; - } - - @Override - public DartSource getSourceAfter() { - return sourceAfter; - } - - @Override - public DartUnit getUnitAfter() { - return nodeAfter; - } - } -} diff --git a/compiler/java/com/google/dart/compiler/SubSystem.java b/compiler/java/com/google/dart/compiler/SubSystem.java deleted file mode 100644 index c85755d0c15f..000000000000 --- a/compiler/java/com/google/dart/compiler/SubSystem.java +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -/** - * Subsystem of compiler. - */ -public enum SubSystem { - COMPILER, PARSER, STATIC_TYPE, RESOLVER -} \ No newline at end of file diff --git a/compiler/java/com/google/dart/compiler/SystemLibrariesReader.java b/compiler/java/com/google/dart/compiler/SystemLibrariesReader.java deleted file mode 100644 index 56d3bbf950ce..000000000000 --- a/compiler/java/com/google/dart/compiler/SystemLibrariesReader.java +++ /dev/null @@ -1,264 +0,0 @@ -/* - * Copyright (c) 2012, the Dart project authors. - * - * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.eclipse.org/legal/epl-v10.html - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package com.google.dart.compiler; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.io.CharStreams; -import com.google.common.io.Closeables; -import com.google.dart.compiler.CompilerConfiguration.ErrorFormat; -import com.google.dart.compiler.ast.ASTVisitor; -import com.google.dart.compiler.ast.DartBooleanLiteral; -import com.google.dart.compiler.ast.DartExpression; -import com.google.dart.compiler.ast.DartFieldDefinition; -import com.google.dart.compiler.ast.DartIdentifier; -import com.google.dart.compiler.ast.DartMapLiteralEntry; -import com.google.dart.compiler.ast.DartNamedExpression; -import com.google.dart.compiler.ast.DartNewExpression; -import com.google.dart.compiler.ast.DartNode; -import com.google.dart.compiler.ast.DartStringLiteral; -import com.google.dart.compiler.ast.DartUnit; -import com.google.dart.compiler.metrics.CompilerMetrics; -import com.google.dart.compiler.parser.DartParser; -import com.google.dart.compiler.util.DartSourceString; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.URI; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; - -/** - * A reader that parses and reads the libraries dart-sdk/lib/_internal/libraries.dart file for - * system library information library information is in the format final Map - * LIBRARIES = const { // Used by VM applications "builtin": const LibraryInfo( - * "builtin/builtin_runtime.dart", category: "Server", platforms: VM_PLATFORM), "compiler": const - * LibraryInfo( "compiler/compiler.dart", category: "Tools", platforms: 0), }; - */ -public class SystemLibrariesReader { - - @VisibleForTesting - public class DartLibrary { - - private String shortName = null; - private String path = null; - private String category = "Shared"; - private boolean documented = true; - private boolean implementation = false; - private int platforms = 0; - - DartLibrary(String name) { - this.shortName = name; - } - - public String getShortName() { - return shortName; - } - - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - public boolean isDocumented() { - return documented; - } - - public void setDocumented(boolean documented) { - this.documented = documented; - } - - public boolean isImplementation() { - return implementation; - } - - public void setImplementation(boolean implementation) { - this.implementation = implementation; - } - - public boolean isDart2JsLibrary() { - return (platforms & DART2JS_PLATFORM) != 0; - } - - public boolean isVmLibrary() { - return (platforms & VM_PLATFORM) != 0; - } - - public void setPlatforms(int platforms) { - this.platforms = platforms; - } - } - - class LibrariesFileAstVistor extends ASTVisitor { - - @Override - public Void visitMapLiteralEntry(DartMapLiteralEntry node) { - - String keyString = null; - DartExpression key = node.getKey(); - if (key instanceof DartStringLiteral) { - keyString = "dart:" + ((DartStringLiteral) key).getValue(); - } - DartExpression value = node.getValue(); - if (value instanceof DartNewExpression) { - DartLibrary library = new DartLibrary(keyString); - List args = ((DartNewExpression) value).getArguments(); - for (DartExpression arg : args) { - if (arg instanceof DartStringLiteral) { - library.setPath(((DartStringLiteral) arg).getValue()); - } - if (arg instanceof DartNamedExpression) { - String name = ((DartNamedExpression) arg).getName().getName(); - DartExpression expression = ((DartNamedExpression) arg).getExpression(); - if (name.equals(CATEGORY)) { - library.setCategory(((DartStringLiteral) expression).getValue()); - } else if (name.equals(IMPLEMENTATION)) { - library.setImplementation(((DartBooleanLiteral) expression).getValue()); - } else if (name.equals(DOCUMENTED)) { - library.setDocumented(((DartBooleanLiteral) expression).getValue()); - } else if (name.equals(PATCH_PATH)) { - String path = ((DartStringLiteral) expression).getValue(); - URI uri = sdkLibPath.resolve(URI.create(path)); - patchPaths.add(uri); - } else if (name.equals(PLATFORMS)) { - if (expression instanceof DartIdentifier) { - String identifier = ((DartIdentifier) expression).getName(); - if (identifier.equals("VM_PLATFORM")) { - library.setPlatforms(VM_PLATFORM); - } else { - library.setPlatforms(DART2JS_PLATFORM); - } - } - } - } - } - librariesMap.put(keyString, library); - } - return null; - } - - } - - public static final String LIBRARIES_FILE = "libraries.dart"; - public static final String INTERNAL_DIR = "_internal"; - - private static final String IMPLEMENTATION = "implementation"; - private static final String DOCUMENTED = "documented"; - private static final String CATEGORY = "category"; - private static final String PATCH_PATH = "dart2jsPatchPath"; - private static final String PLATFORMS = "platforms"; - - private static final int DART2JS_PLATFORM = 1; - private static final int VM_PLATFORM = 2; - - private final URI sdkLibPath; - private final Map librariesMap = new HashMap(); - private final List patchPaths = new ArrayList(); - - public SystemLibrariesReader(URI sdkLibPath, Reader sdkFileReader) { - this.sdkLibPath = sdkLibPath; - loadLibraryInfo(sdkFileReader); - } - - public SystemLibrariesReader(File sdkLibPath) throws IOException { - this(sdkLibPath.getAbsoluteFile().toURI(), new InputStreamReader(new FileInputStream( - getLibrariesFile(sdkLibPath)), Charset.forName("UTF8"))); - } - - public Map getLibrariesMap() { - return librariesMap; - } - - public List getPatchPaths() { - return patchPaths; - } - - private void loadLibraryInfo(Reader sdkFileReader) { - - DartUnit unit = getDartUnit(sdkFileReader); - - List nodes = unit.getTopLevelNodes(); - for (DartNode node : nodes) { - if (node instanceof DartFieldDefinition) { - node.accept(new LibrariesFileAstVistor()); - } - } - } - - /** - * Parse the given dart file and return the AST - * - * @param fileReader the dart file reader - * @return the parsed AST - */ - private DartUnit getDartUnit(Reader fileReader) { - - String srcCode = getSource(fileReader); - DartSourceString dartSource = new DartSourceString(LIBRARIES_FILE, srcCode); - DefaultDartCompilerListener listener = new DefaultDartCompilerListener(ErrorFormat.NORMAL); - DartParser parser = new DartParser( - dartSource, - srcCode, - false, - new HashSet(), - listener, - new CompilerMetrics()); - return parser.parseUnit(); - } - - private String getSource(Reader reader) { - String srcCode = null; - boolean failed = true; - try { - srcCode = CharStreams.toString(reader); - failed = false; - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - Closeables.close(reader, failed); - } catch (IOException e) { - e.printStackTrace(); - } - } - return srcCode; - } - - private static File getLibrariesFile(File sdkLibDir) { - File file = new File(new File(sdkLibDir, INTERNAL_DIR), LIBRARIES_FILE); - if (!file.exists()) { - throw new InternalCompilerException("Failed to find " + file.toString() - + ". Is dart-sdk path correct?"); - } - return file; - } - -} diff --git a/compiler/java/com/google/dart/compiler/SystemLibrary.java b/compiler/java/com/google/dart/compiler/SystemLibrary.java deleted file mode 100644 index a1a472667d8a..000000000000 --- a/compiler/java/com/google/dart/compiler/SystemLibrary.java +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import java.io.File; -import java.net.URI; -import java.net.URISyntaxException; - -/** - * A library accessible via the "dart:.lib" protocol. - */ -public class SystemLibrary { - - private final String shortName; - private final String host; - private final String pathToLib; - private final File dirOrZip; - private String category; - private boolean documented; - private boolean implementation; - - /** - * Define a new system library such that dart:[shortLibName] will automatically be expanded to - * dart://[host]/[pathToLib]. For example this call - * - *
-   *    new SystemLibrary("html.lib", "html", "dart_html.lib");
-   * 
- * - * will define a new system library such that "dart:html.lib" to automatically be expanded to - * "dart://html/dart_html.lib". The dirOrZip argument is either the root directory or a zip file - * containing all files for this library. - */ - public SystemLibrary(String shortName, String host, String pathToLib, File dirOrZip, String category, - boolean documented, boolean implementation) { - this.shortName = shortName; - this.host = host; - this.pathToLib = pathToLib; - this.dirOrZip = dirOrZip; - this.category = category; - this.documented = documented; - this.implementation = implementation; - } - - public String getCategory() { - return category; - } - - public boolean isDocumented() { - return documented; - } - - public boolean isImplementation() { - return implementation; - } - - public boolean isShared(){ - return category.equals("Shared"); - } - - public String getHost() { - return host; - } - - public String getPathToLib() { - return pathToLib; - } - - public String getShortName() { - return shortName; - } - - public File getLibraryDir() { - return dirOrZip; - } - - public URI translateUri(URI dartUri) { - if (!dirOrZip.exists()) { - throw new RuntimeException("System library for " + dartUri + " does not exist: " + dirOrZip.getPath()); - } - try { - URI dirOrZipURI = dirOrZip.toURI(); - if (dirOrZip.isFile()) { - return new URI("jar", "file:" + dirOrZipURI.getPath() + "!" + dartUri.getPath(), null); - } else { - return dirOrZipURI.resolve("." + dartUri.getPath()); - } - } catch (URISyntaxException e) { - throw new AssertionError(); - } - } - - public File getFile() { - return this.dirOrZip; - } -} diff --git a/compiler/java/com/google/dart/compiler/SystemLibraryManager.java b/compiler/java/com/google/dart/compiler/SystemLibraryManager.java deleted file mode 100644 index a86558ef4660..000000000000 --- a/compiler/java/com/google/dart/compiler/SystemLibraryManager.java +++ /dev/null @@ -1,241 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import com.google.dart.compiler.SystemLibrariesReader.DartLibrary; - -import java.io.File; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -/** - * A Library manager that manages system libraries - */ -public class SystemLibraryManager { - - private HashMap expansionMap; - private Map hostMap; - private final URI sdkLibPathUri; - - private Map longToShortUriMap; - - private List libraries; - private final SystemLibraryProvider libraryProvider; - - public SystemLibraryManager(File sdkPath) { - this(new FileBasedSystemLibraryProvider(sdkPath)); - } - - public SystemLibraryManager(SystemLibraryProvider libraryProvider) { - this.libraryProvider = libraryProvider; - this.sdkLibPathUri = libraryProvider.getSdkLibPathUri(); - setLibraries(getDefaultLibraries()); - } - - public URI expandRelativeDartUri(URI uri) throws AssertionError { - String host = uri.getHost(); - if (host == null && uri.getAuthority() == null) { - String spec = uri.getSchemeSpecificPart(); - String replacement = expansionMap.get(spec); - if (replacement != null) { - try { - uri = new URI(PackageLibraryManager.DART_SCHEME + ":" + replacement); - } catch (URISyntaxException e) { - throw new AssertionError(); - } - } else { - return null; - } - } - return uri; - } - - public URI getRelativeUri(URI fileUri) { - - if (fileUri == null || !fileUri.getScheme().equals("file")){ - return null; - } - - URI relativeUri = sdkLibPathUri.relativize(fileUri); - if (relativeUri.getScheme() == null) { - try { - return new URI(null, null, "dart://" + relativeUri.getPath(), null, null); - } catch (URISyntaxException e) { - //$FALL-THROUGH$ - } - } - return null; - } - - public URI getShortUri(URI uri) { - URI shortUri = longToShortUriMap.get(uri); - if (shortUri != null){ - return shortUri; - } - shortUri = getRelativeUri(uri); - if (shortUri != null){ - try { - return new URI(null, null, shortUri.getScheme() + ":" + shortUri.getHost() + shortUri.getPath(),null, null); - } catch (URISyntaxException e) { - } - } - return null; - } - - public URI translateDartUri(URI uri) { - - String host = uri.getHost(); - - SystemLibrary library = hostMap.get(host); - if (library != null) { - return library.translateUri(uri); - } - if (host != null) { - return libraryProvider.resolveHost(host, uri); - } - String authorithy = uri.getAuthority(); - if (authorithy != null){ - return libraryProvider.resolveHost(authorithy, uri); - } - throw new RuntimeException("No system library defined for " + uri); - - } - - - public Collection getAllLibrarySpecs() { - Collection result = new ArrayList(libraries.size()); - for (SystemLibrary lib : libraries) { - result.add("dart:" + lib.getShortName()); - } - return result; - } - - public Collection getAllSystemLibraries(){ - return libraries; - } - - /** - * Load the libraries listed out in the libraries.dart files as read by the {@link SystemLibrariesReader} - */ - protected SystemLibrary[] getDefaultLibraries() { - libraries = new ArrayList(); - longToShortUriMap = new HashMap(); - - // Cycle through the import.config, extracting explicit mappings and searching directories - URI base = this.sdkLibPathUri; - - Map declaredLibraries = libraryProvider.getLibraryMap(); - - HashSet explicitShortNames = new HashSet(); - - for (Entry entry : declaredLibraries.entrySet()) { - if (entry.getValue().getCategory().equals("Internal") - // TODO(8365): the following line allows dart:_collection-dev to - // be imported even though it's a hidden library. - && !entry.getKey().equals("dart:_collection-dev")) { - continue; - } - String shortName = entry.getKey().trim(); - DartLibrary library = entry.getValue(); - String path = library.getPath(); - URI libFileUri; - try { - libFileUri = base.resolve(new URI(null, null, path, null, null)).normalize(); - } catch (URISyntaxException e) { - continue; - } - - if (!libraryProvider.exists(libFileUri)) { - throw new InternalCompilerException("Can't find system library dart:" + shortName - + " at " + libFileUri); - } - - int index = shortName.indexOf(':'); - if (index == -1) { - continue; - } - explicitShortNames.add(shortName); - String scheme = shortName.substring(0, index + 1); - String name = shortName.substring(index + 1); - - String relPath = sdkLibPathUri.relativize(libFileUri).getPath(); - index = relPath.indexOf('/'); - if (index == -1) { - continue; - } - String host = relPath.substring(0, index); - String pathToLib = relPath.substring(index + 1); - - addLib(scheme, - host, - name, - pathToLib, - library.getCategory(), - library.isDocumented(), - library.isImplementation()); - - } - return libraries.toArray(new SystemLibrary[libraries.size()]); - } - - protected boolean addLib(String scheme, String host, String name, String pathToLib, - String category, boolean documented, boolean implementation) - throws AssertionError { - - SystemLibrary lib = libraryProvider.createSystemLibrary(name, host, pathToLib, category, documented, implementation); - libraries.add(lib); - - String libSpec = scheme + name; - URI libUri; - URI expandedUri; - try { - libUri = new URI(libSpec); - expandedUri = new URI("dart:" + "//" + host + "/" + pathToLib); - } catch (URISyntaxException e) { - throw new AssertionError(e); - } - URI resolvedUri = lib.translateUri(expandedUri); - longToShortUriMap.put(resolvedUri, libUri); - longToShortUriMap.put(expandedUri, libUri); - return true; - } - - /** - * Register system libraries for the "dart:" protocol such that dart:[shortLibName] (e.g. - * "dart:html") will automatically be expanded to dart://[host]/[pathToLib] (e.g. - * dart://html/html.dart) - */ - private void setLibraries(SystemLibrary[] newLibraries) { - libraries = new ArrayList(); - hostMap = new HashMap(); - expansionMap = new HashMap(); - for (SystemLibrary library : newLibraries) { - String host = library.getHost(); - SystemLibrary existingLib = hostMap.get(host); - if (existingLib != null) { - libraries.remove(existingLib); - } - libraries.add(library); - hostMap.put(host, library); - expansionMap.put(library.getShortName(), - "//" + host + "/" + library.getPathToLib()); - } - } - - /** - * Check if this URI denotes a patch file. - */ - public boolean isPatchFile(URI uri) { - return libraryProvider.isPatchFile(uri); - } - -} diff --git a/compiler/java/com/google/dart/compiler/SystemLibraryProvider.java b/compiler/java/com/google/dart/compiler/SystemLibraryProvider.java deleted file mode 100644 index af6ab2d2f918..000000000000 --- a/compiler/java/com/google/dart/compiler/SystemLibraryProvider.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (c) 2012, the Dart project authors. - * - * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.eclipse.org/legal/epl-v10.html - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package com.google.dart.compiler; - -import com.google.dart.compiler.SystemLibrariesReader.DartLibrary; - -import java.io.IOException; -import java.net.URI; -import java.util.Map; - -/** - * A provider for System libraries. - */ -public abstract class SystemLibraryProvider { - - private final URI sdkLibPathUri; - private SystemLibrariesReader reader; - - /** - * Create a {@link SystemLibraryProvider} with the given path to the dart SDK. - */ - public SystemLibraryProvider(URI sdkLibPathUri) { - this.sdkLibPathUri = sdkLibPathUri; - } - - /** - * Define a new system library. - * - * @param name the short name of the library - * @param host the host - * @param pathToLib the path to the library - * @param category the library category - * @param documented true if documented, false otherwise - * @param implementation true if an implementation library, false - * otherwise - * @return the resulting {@link SystemLibrary} - */ - public abstract SystemLibrary createSystemLibrary(String name, String host, String pathToLib, - String category, boolean documented, boolean implementation); - - /** - * Tests whether the resource denoted by this abstract URI exists. - * - * @param uri the URI to test - * @return true if and only if the resource denoted by this URI exists; - * false otherwise - */ - public abstract boolean exists(URI uri); - - /** - * Get a URI describing the root of the SDK. - */ - public URI getSdkLibPathUri() { - return sdkLibPathUri; - } - - /** - * Get a mapping of symbolic names (e.g., "dart:html") to {@link DartLibrary}s. - */ - public Map getLibraryMap() { - return getReader().getLibrariesMap(); - } - - /** - * Check if this URI denotes a patch file. - */ - public boolean isPatchFile(URI uri) { - return getReader().getPatchPaths().contains(uri); - } - - /** - * Constructs a new URI by parsing the given host string and then resolving it against this URI. - * - * @param host the host string - * @param uri the uri to resolve against - * @return the resulting URI - */ - public abstract URI resolveHost(String host, URI uri); - - /** - * Create the system libraries reader. - * - * @return a reader for parsing system libraries - */ - protected abstract SystemLibrariesReader createReader() throws IOException; - - private SystemLibrariesReader getReader() { - if (reader == null) { - try { - reader = createReader(); - } catch (IOException e) { - throw new InternalCompilerException("Unable to create system library reader", e); - } - } - return reader; - } - -} diff --git a/compiler/java/com/google/dart/compiler/UnitTestBatchRunner.java b/compiler/java/com/google/dart/compiler/UnitTestBatchRunner.java deleted file mode 100644 index bbabf4a2a35b..000000000000 --- a/compiler/java/com/google/dart/compiler/UnitTestBatchRunner.java +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - - -import com.google.dart.compiler.DartCompiler.Result; - -import java.io.BufferedReader; -import java.io.InputStreamReader; - -/** - * Provides a framework to read command line options from stdin and feed them to - * the {@link DartCompiler}. - * - */ -public class UnitTestBatchRunner { - - public interface Invocation { - public Result invoke (String[] args) throws Throwable; - } - - /** - * Run the tool in 'batch' mode, receiving command lines through stdin and returning - * pass/fail status through stdout. This feature is intended for use in unit testing. - * - * @param batchArgs command line arguments forwarded from main(). - */ - public static Result runAsBatch(String[] batchArgs, Invocation toolInvocation) throws Throwable { - System.out.println(">>> BATCH START"); - - // Read command lines in from stdin and create a new compiler for each one. - BufferedReader cmdlineReader = new BufferedReader(new InputStreamReader( - System.in)); - long startTime = System.currentTimeMillis(); - int testsFailed = 0; - int totalTests = 0; - Result batchResult = new Result(DartCompiler.RESULT_OK, null); - try { - String line; - for (; (line = cmdlineReader.readLine()) != null; totalTests++) { - long testStart = System.currentTimeMillis(); - // TODO(zundel): These are shell script cmdlines: be smarter about quoted strings. - String[] args = line.trim().split("\\s+"); - Result result = toolInvocation.invoke(args); - boolean resultPass = result.code < DartCompiler.RESULT_ERRORS; - if (resultPass) { - testsFailed++; - } - batchResult = batchResult.merge(result); - // Write stderr end token and flush. - System.err.println(">>> EOF STDERR"); - System.err.flush(); - System.out.println(">>> TEST " + (resultPass ? "PASS" : "FAIL") + " " - + (System.currentTimeMillis() - testStart) + "ms"); - System.out.flush(); - } - } catch (Throwable e) { - System.err.println(">>> EOF STDERR"); - System.err.flush(); - System.out.println(">>> TEST CRASH"); - System.out.flush(); - throw e; - } - long elapsed = System.currentTimeMillis() - startTime; - System.out.println(">>> BATCH END (" + (totalTests - testsFailed) + "/" - + totalTests + ") " + elapsed + "ms"); - System.out.flush(); - return batchResult; - } -} diff --git a/compiler/java/com/google/dart/compiler/UrlDartSource.java b/compiler/java/com/google/dart/compiler/UrlDartSource.java deleted file mode 100644 index 2e1389998818..000000000000 --- a/compiler/java/com/google/dart/compiler/UrlDartSource.java +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import java.io.File; -import java.net.URI; -import java.net.URISyntaxException; - -/** - * A {@link DartSource} backed by a URL. - */ -public class UrlDartSource extends UrlSource implements DartSource { - - private final LibrarySource lib; - private final String relPath; - - protected UrlDartSource(URI uri, String relPath, LibrarySource lib, PackageLibraryManager slm) { - super(uri,slm); - this.relPath = relPath; - this.lib = lib; - } - - protected UrlDartSource(URI uri, String relPath, LibrarySource lib) { - this(uri, relPath, lib, null); - } - - public UrlDartSource(File file, LibrarySource lib) { - super(file); - this.relPath = file.getPath(); - this.lib = lib; - } - - @Override - public LibrarySource getLibrary() { - return lib; - } - - @Override - public String getName() { - try { - String uriSafeName = new URI(null, null, relPath, null).toString(); - return lib.getName() + "/" + uriSafeName; - } catch (URISyntaxException e) { - throw new AssertionError(e); - } - } - - @Override - public String getRelativePath() { - return relPath; - } -} diff --git a/compiler/java/com/google/dart/compiler/UrlLibrarySource.java b/compiler/java/com/google/dart/compiler/UrlLibrarySource.java deleted file mode 100644 index 27fce70e9e1b..000000000000 --- a/compiler/java/com/google/dart/compiler/UrlLibrarySource.java +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. -package com.google.dart.compiler; - -import java.io.File; -import java.net.URI; - -/** - * A {@link LibrarySource} backed by a URL. - */ -public class UrlLibrarySource extends UrlSource implements LibrarySource { - - public UrlLibrarySource(URI uri, PackageLibraryManager slm) { - super(uri, slm); - } - - public UrlLibrarySource(URI uri) { - this(uri, null); - } - - public UrlLibrarySource(File file) { - super(file); - } - - @Override - public String getName() { - return getUri().toString(); - } - - @Override - public LibrarySource getImportFor(String relPath) { - if (relPath == null || relPath.isEmpty()) { - return null; - } - try { - // Force the creation of an escaped relative URI to deal with spaces, etc. - URI uri = getUri().resolve(new URI(null, null, relPath, null, null)).normalize(); - String path = uri.getPath(); - // Resolve relative reference out of one system library into another - if (PackageLibraryManager.isDartUri(uri)) { - if (path != null && path.startsWith("/..")) { - URI fileUri = packageLibraryManager.resolveDartUri(uri); - URI shortUri = packageLibraryManager.getShortUri(fileUri); - if (shortUri != null) { - uri = shortUri; - } - } - } else if (PackageLibraryManager.isPackageUri(uri)) { - URI fileUri = packageLibraryManager.resolveDartUri(uri); - if (fileUri != null) { - uri = fileUri; - } - } else if (!resourceExists(uri)) { - // resolve against package root directories to find file - uri = packageLibraryManager.findExistingFileInPackages(uri); - } - - return createLibrarySource(uri, packageLibraryManager); - } catch (Throwable e) { - return null; - } - } - - @Override - public DartSource getSourceFor(final String relPath) { - if (relPath == null || relPath.isEmpty()) { - return null; - } - try { - // Force the creation of an escaped relative URI to deal with spaces, etc. - URI uri = getUri().resolve(new URI(null, null, relPath, null, null)).normalize(); - if (PackageLibraryManager.isPackageUri(uri)) { - URI fileUri = packageLibraryManager.resolveDartUri(uri); - if (fileUri != null) { - uri = fileUri; - } - } - return createDartSource(uri, relPath, this, packageLibraryManager); - } catch (Throwable e) { - return null; - } - } - - /** - * Create a URL library source. - * - * (Clients can override.) - * - * @param uri the URI of the library - * @param relPath relative path to the dart source - * @param libSource the library source - * @param packageManager the package library manager - * @return the resulting dart source - */ - protected UrlDartSource createDartSource(URI uri, String relPath, UrlLibrarySource libSource, PackageLibraryManager packageManager) { - return new UrlDartSource(uri, relPath, libSource, packageManager); - } - - /** - * Create a URL library source. - * - * (Clients can override.) - * - * @param uri the URI of the library - * @return the resulting library source - */ - protected UrlLibrarySource createLibrarySource(URI uri, PackageLibraryManager packageManager) { - return new UrlLibrarySource(uri, packageManager); - } - - /** - * Check if a resource exists at this URI. - * - * (Clients can override.) - * - * @param uri the URI to test - * @return true if a resource exists at this URI, false otherwise - */ - protected boolean resourceExists(URI uri) { - String path = uri.getPath(); - return path == null || new File(path).exists(); - } -} diff --git a/compiler/java/com/google/dart/compiler/UrlSource.java b/compiler/java/com/google/dart/compiler/UrlSource.java deleted file mode 100644 index 890df68bc09d..000000000000 --- a/compiler/java/com/google/dart/compiler/UrlSource.java +++ /dev/null @@ -1,205 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.JarURLConnection; -import java.net.URI; -import java.net.URL; -import java.nio.charset.Charset; -import java.util.jar.JarEntry; - -/** - * A {@link Source} backed by a URL (or optionally by a file). - */ -public abstract class UrlSource implements Source { - - private final static String FILE_PROTOCOL = "file"; - private final static String JAR_PROTOCOL = "jar"; - private final static URI CURRENT_DIR = new File(".").toURI().normalize(); - private final static Charset UTF8 = Charset.forName("UTF8"); - private final static URI BASE_URI = CURRENT_DIR; - - private final URI uri; - private final URI absoluteUri; - private final URI translatedUri; - private final boolean shouldCareAboutLastModified; - private volatile boolean exists = false; - private volatile long lastModified = -1; - private volatile boolean propertiesInitialized = false; - - // generally, one or the other of these will be non-null after properties are initialized - private volatile File sourceFile = null; - private volatile JarURLConnection jarConn = null; - - protected final PackageLibraryManager packageLibraryManager; - - protected UrlSource(URI uri) { - this(uri,null); - } - - protected UrlSource(URI uri, PackageLibraryManager slm) { - URI expanded = slm != null ? slm.expandRelativeDartUri(uri) : uri; - if (expanded == null) { - // import("dart:typo") case - expanded = uri; - } - this.uri = BASE_URI.relativize(expanded.normalize()); - this.absoluteUri = BASE_URI.resolve(expanded); - this.packageLibraryManager = slm; - if (PackageLibraryManager.isDartUri(this.uri) || PackageLibraryManager.isPackageUri(this.uri)) { - assert slm != null; - this.shouldCareAboutLastModified = false; - this.translatedUri = slm.resolveDartUri(this.absoluteUri); - } else { - this.shouldCareAboutLastModified = true; - this.translatedUri = this.absoluteUri; - } - } - - protected UrlSource(File file) { - URI uri = file.toURI().normalize(); - if (!file.exists()) { - // TODO(jgw): This is a bit ugly, but some of the test infrastructure depends upon - // non-existant relative files being looked up as classpath resources. This was - // previously embedded in DartSourceFile.getSourceReader(). - URL url = getClass().getClassLoader().getResource(file.getPath()); - if (url != null) { - uri = URI.create(url.toString()); - } - } - - this.uri = BASE_URI.relativize(uri); - this.translatedUri = this.absoluteUri = BASE_URI.resolve(uri); - this.packageLibraryManager = null; - this.shouldCareAboutLastModified = true; - } - - @Override - public boolean exists() { - initProperties(); - return exists; - } - - @Override - public long getLastModified() { - initProperties(); - return lastModified; - } - - @Override - public Reader getSourceReader() throws IOException { - initProperties(); - if (sourceFile != null) { - return new InputStreamReader(new FileInputStream(sourceFile), UTF8); - } else if (jarConn != null) { - return new InputStreamReader(jarConn.getInputStream(), UTF8); - } - // fall back case - if (translatedUri != null) { - InputStream stream = translatedUri.toURL().openStream(); - if (stream != null) { - return new InputStreamReader(stream, UTF8); - } - } - throw new FileNotFoundException(getName()); - } - - @Override - public String getUniqueIdentifier() { - return absoluteUri.toString(); - } - - /** - * Get the translated URI for this source. - * - * @return the translated URI - */ - public URI getTranslatedUri() { - return translatedUri; - } - - @Override - public URI getUri() { - return absoluteUri; - } - - private void initProperties() { - synchronized (this) { - if (!propertiesInitialized) { - try { - initPropertiesEx(); - } catch (Throwable e) { - } finally { - propertiesInitialized = true; - } - } - } - } - - /** - * Implementation of {@link #initProperties()} which can throw exceptions. - */ - private void initPropertiesEx() throws Exception { - URI resolvedUri = BASE_URI.resolve(translatedUri); - String scheme = resolvedUri.getScheme(); - if (scheme == null || FILE_PROTOCOL.equals(scheme)) { - File file = new File(resolvedUri); - lastModified = file.lastModified(); - exists = file.exists(); - sourceFile = file; - } else { - URL url = translatedUri.toURL(); - if (JAR_PROTOCOL.equals(url.getProtocol())) { - getJarEntryProperties(url); - } else { - /* - * TODO(jbrosenberg): Flesh out the support for other - * protocols, like http, etc. Note, calling - * URLConnection.getLastModified() can be dangerous, some - * URLConnection sub-classes don't have a way to close a - * connection opened by this call. Return 0 for now. - */ - lastModified = 0; - // Default this to true for now. - exists = true; - } - } - } - - private void getJarEntryProperties(URL url) { - try { - jarConn = (JarURLConnection) url.openConnection(); - // useCaches is usually set to true by default, but make sure here - jarConn.setUseCaches(true); - // See if our entry exists - JarEntry jarEntry = jarConn.getJarEntry(); - if (jarEntry != null) { - exists = true; - if (!shouldCareAboutLastModified) { - lastModified = 0; - return; - } - // TODO(jbrosenberg): Note the time field for a jarEntry can be - // unreliable, and is not always required in a jar file. Consider using - // the timestamp on the jar file itself. - lastModified = jarEntry.getTime(); - } - if (!exists) { - lastModified = -1; - return; - } - } catch (IOException e) { - exists = false; - lastModified = -1; - } - } -} \ No newline at end of file diff --git a/compiler/java/com/google/dart/compiler/ast/ASTNodes.java b/compiler/java/com/google/dart/compiler/ast/ASTNodes.java deleted file mode 100644 index 2e3b87f062b1..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/ASTNodes.java +++ /dev/null @@ -1,1448 +0,0 @@ -/* - * Copyright (c) 2012, the Dart project authors. - * - * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.eclipse.org/legal/epl-v10.html - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package com.google.dart.compiler.ast; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.dart.compiler.common.SourceInfo; -import com.google.dart.compiler.parser.Token; -import com.google.dart.compiler.resolver.Element; -import com.google.dart.compiler.resolver.ElementKind; -import com.google.dart.compiler.resolver.FieldElement; -import com.google.dart.compiler.resolver.MethodElement; -import com.google.dart.compiler.resolver.VariableElement; -import com.google.dart.compiler.type.InterfaceType; -import com.google.dart.compiler.type.Type; -import com.google.dart.compiler.type.TypeKind; - -import java.util.Collections; -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Defines utility methods that operate on nodes in a Dart AST structure (instances of - * {@link DartNode} and its subclasses). - */ -public class ASTNodes { - - /** - * @return true if given {@link DartNode} is part of static method, static field or - * top-level function. - */ - public static boolean isStaticContext(DartNode node) { - while (node != null) { - DartNode parent = node.getParent(); - if (node instanceof DartMethodDefinition) { - DartMethodDefinition method = (DartMethodDefinition) node; - if (method.getModifiers().isStatic()) { - return true; - } - return parent instanceof DartUnit; - } - if (node instanceof DartField) { - DartField field = (DartField) node; - if (field.getModifiers().isStatic()) { - return true; - } - return parent != null && parent.getParent() instanceof DartUnit; - } - node = parent; - } - return false; - } - - /** - * @return true if given {@link DartNode} is part of factory method. - */ - public static boolean isFactoryContext(DartNode node) { - while (node != null) { - if (node instanceof DartMethodDefinition) { - DartMethodDefinition method = (DartMethodDefinition) node; - return method.getModifiers().isFactory(); - } - node = node.getParent(); - } - return false; - } - - /** - * @return true if given {@link DartNode} is part of static method or factory. - */ - public static boolean isStaticOrFactoryContext(DartNode node) { - return isFactoryContext(node) || isStaticContext(node); - } - - /** - * Returns complete field access node for given field name. - * - *
-   * node = 1;        => node
-   * obj.node = 1;    => obj.node
-   * 
- * - * Note, that we don't check if given {@link DartNode} is actually field name. - */ - public static DartNode getPropertyAccessNode(DartNode node) { - DartNode parent = node.getParent(); - if (parent instanceof DartPropertyAccess && ((DartPropertyAccess) parent).getName() == node) { - return parent; - } - return node; - } - - public static List findDeepestCommonPath(List nodes) { - List> parents = Lists.newArrayList(); - for (DartNode node : nodes) { - parents.add(getParents(node)); - } - return getLongestListPrefix(parents); - } - - /** - * @return the {@link DartNode} of given {@link Class} which is given {@link DartNode} itself, or - * one of its parents. - */ - @SuppressWarnings("unchecked") - public static E getAncestor(DartNode node, Class enclosingClass) { - while (node != null && !enclosingClass.isInstance(node)) { - node = node.getParent(); - }; - return (E) node; - } - - /** - * Get the element associated with the given AST node. - * - * @param node the target node - * @param includeDeclarations true if elements should be returned for declaration - * sites as well as for reference sites - * @return the associated element (or null if none can be found) - */ - public static Element getElement(DartNode node, boolean includeDeclarations) { - Element targetElement = node.getElement(); - DartNode parent = node.getParent(); - // name of named parameter in invocation - if (node instanceof DartIdentifier && node.getParent() instanceof DartNamedExpression) { - DartNamedExpression namedExpression = (DartNamedExpression) node.getParent(); - if (namedExpression.getName() == node) { - Object parameterId = ((DartIdentifier) node).getInvocationParameterId(); - if (parameterId instanceof VariableElement) { - targetElement = (VariableElement) parameterId; - } - } - } - // target of "new X()" or "new X.a()" is not just a type, it is a constructor - if (parent instanceof DartTypeNode || parent instanceof DartPropertyAccess) { - DartNode grandparent = parent.getParent(); - if (grandparent instanceof DartNewExpression) { - targetElement = ((DartNewExpression) grandparent).getElement(); - } - } else if (parent instanceof DartRedirectConstructorInvocation - || parent instanceof DartSuperConstructorInvocation) { - targetElement = parent.getElement(); - } - return targetElement; - } - - /** - * Return the class definition enclosing the given node, or null if the node is not a - * child of a class definition. - * - * @param node the node enclosed in the class definition to be returned - * @return the class definition enclosing the given node - */ - public static DartClass getEnclosingDartClass(DartNode node) { - return getEnclosingNodeOfType(DartClass.class, node); - } - - /** - * Return the first node of the given class that encloses the given node, or null if - * the node is not a child of a node of the given class. The node itself will not be - * returned, even if it is an instance of the given class. - * - * @param enclosingNodeClass the class of node to be returned - * @param node the child of the node to be returned - * @return the specified parent of the given node - */ - @SuppressWarnings("unchecked") - public static E getEnclosingNodeOfType(Class enclosingNodeClass, - DartNode node) { - DartNode parent = node.getParent(); - while (parent != null && !enclosingNodeClass.isInstance(parent)) { - parent = parent.getParent(); - } - return (E) parent; - } - - public static int getExclusiveEnd(DartNode node) { - SourceInfo sourceInfo = node.getSourceInfo(); - return sourceInfo.getOffset() + sourceInfo.getLength(); - } - - /** - * @return the {@link FieldElement} with {@link ElementKind#VARIABLE} if the given - * {@link DartIdentifier} is the field reference, or null in the other case. - */ - public static FieldElement getFieldElement(DartIdentifier node) { - Element element = node.getElement(); - if (ElementKind.of(element) == ElementKind.FIELD) { - return (FieldElement) element; - } - return null; - } - - public static int getInclusiveEnd(DartNode node) { - SourceInfo sourceInfo = node.getSourceInfo(); - return sourceInfo.getOffset() + sourceInfo.getLength() - 1; - } - - /** - * @return the {@link DartExpression} qualified if given node is name part of - * {@link DartPropertyAccess}. May be null. - */ - public static DartNode getNodeQualifier(DartIdentifier node) { - if (node.getParent() instanceof DartPropertyAccess) { - DartPropertyAccess propertyAccess = (DartPropertyAccess) node.getParent(); - if (propertyAccess.getName() == node) { - return propertyAccess.getQualifier(); - } - } - return null; - } - - /** - * @return the {@link VariableElement} if the given {@link DartIdentifier} is the parameter - * reference, or null in the other case. - */ - public static VariableElement getParameterElement(DartIdentifier node) { - Element element = node.getElement(); - if (ElementKind.of(element) == ElementKind.PARAMETER) { - return (VariableElement) element; - } - return null; - } - - /** - * @return the index of given {@link VariableElement} in parameters, or -1 if not - * parameter. - */ - public static int getParameterIndex(VariableElement variableElement) { - Element enclosingElement = variableElement.getEnclosingElement(); - if (enclosingElement instanceof MethodElement) { - MethodElement methodElement = (MethodElement) enclosingElement; - return methodElement.getParameters().indexOf(variableElement); - } - return -1; - } - - /** - * Returns the closest ancestor of node that is an instance of - * parentClass, or null if none. - *

- * Warning: This method does not stop at any boundaries like parentheses, statements, body - * declarations, etc. The resulting node may be in a totally different scope than the given node. - * Consider using one of the {@link ASTResolving}.find(..) methods instead. - *

- * - * @param node the node - * @param parentClass the class of the sought ancestor node - * @return the closest ancestor of node that is an instance of - * parentClass, or null if none - */ - @SuppressWarnings("unchecked") - public static E getParent(DartNode node, Class parentClass) { - do { - node = node.getParent(); - } while (node != null && !parentClass.isInstance(node)); - return (E) node; - } - -// private static class ChildrenCollector extends ASTVisitor { -// public List result; -// -// @Override -// public Void visitNode(DartNode node) { -// // first visitNode: on the node's parent: do nothing, return true -// if (result == null) { -// result = Lists.newArrayList(); -// return super.visitNode(node); -// } else { -// result.add(node); -// } -// } -// } -// -// public static final int NODE_ONLY = 0; -// public static final int INCLUDE_FIRST_PARENT = 1; -// -// public static final int INCLUDE_ALL_PARENTS = 2; -// public static final int WARNING = 1 << 0; -// public static final int ERROR = 1 << 1; -// -// public static final int PROBLEMS = WARNING | ERROR; -// private static final Message[] EMPTY_MESSAGES = new Message[0]; -// -// private static final IProblem[] EMPTY_PROBLEMS = new IProblem[0]; -// -// private static final int CLEAR_VISIBILITY = -// ~(Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE); -// -// public static String asFormattedString(DartNode node, -// int indent, -// String lineDelim, -// Map options) { -// String unformatted = asString(node); -// TextEdit edit = CodeFormatterUtil.format2(node, unformatted, indent, lineDelim, options); -// if (edit != null) { -// Document document = new Document(unformatted); -// try { -// edit.apply(document, TextEdit.NONE); -// } catch (BadLocationException e) { -// JavaPlugin.log(e); -// } -// return document.get(); -// } -// return unformatted; // unknown node -// } -// -// public static String asString(DartNode node) { -// ASTFlattener flattener = new ASTFlattener(); -// node.accept(flattener); -// return flattener.getResult(); -// } -// -// public static int changeVisibility(int modifiers, int visibility) { -// return modifiers & CLEAR_VISIBILITY | visibility; -// } -// -// public static InfixExpression.Operator convertToInfixOperator(Assignment.Operator operator) { -// if (operator.equals(Assignment.Operator.PLUS_ASSIGN)) { -// return InfixExpression.Operator.PLUS; -// } -// -// if (operator.equals(Assignment.Operator.MINUS_ASSIGN)) { -// return InfixExpression.Operator.MINUS; -// } -// -// if (operator.equals(Assignment.Operator.TIMES_ASSIGN)) { -// return InfixExpression.Operator.TIMES; -// } -// -// if (operator.equals(Assignment.Operator.DIVIDE_ASSIGN)) { -// return InfixExpression.Operator.DIVIDE; -// } -// -// if (operator.equals(Assignment.Operator.BIT_AND_ASSIGN)) { -// return InfixExpression.Operator.AND; -// } -// -// if (operator.equals(Assignment.Operator.BIT_OR_ASSIGN)) { -// return InfixExpression.Operator.OR; -// } -// -// if (operator.equals(Assignment.Operator.BIT_XOR_ASSIGN)) { -// return InfixExpression.Operator.XOR; -// } -// -// if (operator.equals(Assignment.Operator.REMAINDER_ASSIGN)) { -// return InfixExpression.Operator.REMAINDER; -// } -// -// if (operator.equals(Assignment.Operator.LEFT_SHIFT_ASSIGN)) { -// return InfixExpression.Operator.LEFT_SHIFT; -// } -// -// if (operator.equals(Assignment.Operator.RIGHT_SHIFT_SIGNED_ASSIGN)) { -// return InfixExpression.Operator.RIGHT_SHIFT_SIGNED; -// } -// -// if (operator.equals(Assignment.Operator.RIGHT_SHIFT_UNSIGNED_ASSIGN)) { -// return InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED; -// } -// -// Assert.isTrue(false, "Cannot convert assignment operator"); //$NON-NLS-1$ -// return null; -// } -// -// public static DartNode findDeclaration(IBinding binding, DartNode root) { -// root = root.getRoot(); -// if (root instanceof CompilationUnit) { -// return ((CompilationUnit) root).findDeclaringNode(binding); -// } -// return null; -// } -// -// public static Modifier findModifierNode(int flag, List modifiers) { -// for (int i = 0; i < modifiers.size(); i++) { -// Object curr = modifiers.get(i); -// if (curr instanceof Modifier && ((Modifier) curr).getKeyword().toFlagValue() == flag) { -// return (Modifier) curr; -// } -// } -// return null; -// } -// -// public static DartNode findParent(DartNode node, StructuralPropertyDescriptor[][] pathes) { -// for (int p = 0; p < pathes.length; p++) { -// StructuralPropertyDescriptor[] path = pathes[p]; -// DartNode current = node; -// int d = path.length - 1; -// for (; d >= 0 && current != null; d--) { -// StructuralPropertyDescriptor descriptor = path[d]; -// if (!descriptor.equals(current.getLocationInParent())) { -// break; -// } -// current = current.getParent(); -// } -// if (d < 0) { -// return current; -// } -// } -// return null; -// } -// -// public static VariableDeclaration findVariableDeclaration(IVariableBinding binding, DartNode root) { -// if (binding.isField()) { -// return null; -// } -// DartNode result = findDeclaration(binding, root); -// if (result instanceof VariableDeclaration) { -// return (VariableDeclaration) result; -// } -// -// return null; -// } -// -// public static List getBodyDeclarations(DartNode node) { -// if (node instanceof AbstractTypeDeclaration) { -// return ((AbstractTypeDeclaration) node).bodyDeclarations(); -// } else if (node instanceof AnonymousClassDeclaration) { -// return ((AnonymousClassDeclaration) node).bodyDeclarations(); -// } -// // should not happen. -// Assert.isTrue(false); -// return null; -// } -// -// /** -// * Returns the structural property descriptor for the "bodyDeclarations" property of this node -// * (element type: {@link BodyDeclaration}). -// * -// * @param node the node, either an {@link AbstractTypeDeclaration} or an -// * {@link AnonymousClassDeclaration} -// * @return the property descriptor -// */ -// public static ChildListPropertyDescriptor getBodyDeclarationsProperty(DartNode node) { -// if (node instanceof AbstractTypeDeclaration) { -// return ((AbstractTypeDeclaration) node).getBodyDeclarationsProperty(); -// } else if (node instanceof AnonymousClassDeclaration) { -// return AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY; -// } -// // should not happen. -// Assert.isTrue(false); -// return null; -// } -// -// /** -// * Returns a list of the direct children of a node. The siblings are ordered by start offset. -// * -// * @param node the node to get the children for -// * @return the children -// */ -// public static List getChildren(DartNode node) { -// ChildrenCollector visitor = new ChildrenCollector(); -// node.accept(visitor); -// return visitor.result; -// } -// -// /** -// * Returns the list that contains the given DartNode. If the node isn't part of any list, -// * null is returned. -// * -// * @param node the node in question -// * @return the list that contains the node or null -// */ -// public static List getContainingList(DartNode node) { -// StructuralPropertyDescriptor locationInParent = node.getLocationInParent(); -// if (locationInParent != null && locationInParent.isChildListProperty()) { -// return (List) node.getParent().getStructuralProperty(locationInParent); -// } -// return null; -// } -// -// public static int getDimensions(VariableDeclaration declaration) { -// int dim = declaration.getExtraDimensions(); -// Type type = getType(declaration); -// if (type instanceof ArrayType) { -// dim += ((ArrayType) type).getDimensions(); -// } -// return dim; -// } -// -// /** -// * Returns the element type. This is a convenience method that returns its argument if it is a -// * simple type and the element type if the parameter is an array type. -// * -// * @param type The type to get the element type from. -// * @return The element type of the type or the type itself. -// */ -// public static Type getElementType(Type type) { -// if (!type.isArrayType()) { -// return type; -// } -// return ((ArrayType) type).getElementType(); -// } -// -// public static ITypeBinding getEnclosingType(DartNode node) { -// while (node != null) { -// if (node instanceof AbstractTypeDeclaration) { -// return ((AbstractTypeDeclaration) node).resolveBinding(); -// } else if (node instanceof AnonymousClassDeclaration) { -// return ((AnonymousClassDeclaration) node).resolveBinding(); -// } -// node = node.getParent(); -// } -// return null; -// } -// -// public static int getExclusiveEnd(DartNode node) { -// return node.getStartPosition() + node.getLength(); -// } -// -// /** -// * Returns the type to which an inlined variable initializer should be cast, or null -// * if no cast is necessary. -// * -// * @param initializer the initializer expression of the variable to inline -// * @param reference the reference to the variable (which is to be inlined) -// * @return a type binding to which the initializer should be cast, or null iff no -// * cast is necessary -// */ -// public static ITypeBinding getExplicitCast(Expression initializer, Expression reference) { -// ITypeBinding initializerType = initializer.resolveTypeBinding(); -// ITypeBinding referenceType = reference.resolveTypeBinding(); -// if (initializerType == null || referenceType == null) { -// return null; -// } -// -// if (initializerType.isPrimitive() -// && referenceType.isPrimitive() -// && !referenceType.isEqualTo(initializerType)) { -// return referenceType; -// -// } else if (initializerType.isPrimitive() && !referenceType.isPrimitive()) { // initializer is autoboxed -// ITypeBinding unboxedReferenceType = -// Bindings.getUnboxedTypeBinding(referenceType, reference.getAST()); -// if (!unboxedReferenceType.isEqualTo(initializerType)) { -// return unboxedReferenceType; -// } else if (needsExplicitBoxing(reference)) { -// return referenceType; -// } -// -// } else if (!initializerType.isPrimitive() && referenceType.isPrimitive()) { // initializer is autounboxed -// ITypeBinding unboxedInitializerType = -// Bindings.getUnboxedTypeBinding(initializerType, reference.getAST()); -// if (!unboxedInitializerType.isEqualTo(referenceType)) { -// return referenceType; -// } -// -// } else if (initializerType.isRawType() && referenceType.isParameterizedType()) { -// return referenceType; // don't lose the unchecked conversion -// -// } else if (!TypeRules.canAssign(initializerType, referenceType)) { -// if (!Bindings.containsTypeVariables(referenceType)) { -// return referenceType; -// } -// } -// -// return null; -// } -// -// public static IVariableBinding getFieldBinding(Name node) { -// IVariableBinding result = getVariableBinding(node); -// if (result == null || !result.isField()) { -// return null; -// } -// -// return result; -// } -// -// public static int getInclusiveEnd(DartNode node) { -// return node.getStartPosition() + node.getLength() - 1; -// } -// -// /** -// * Computes the insertion index to be used to add the given member to the the list -// * container. -// * -// * @param member the member to add -// * @param container a list containing objects of type BodyDeclaration -// * @return the insertion index to be used -// */ -// public static int getInsertionIndex(BodyDeclaration member, -// List container) { -// int containerSize = container.size(); -// -// MembersOrderPreferenceCache orderStore = -// JavaPlugin.getDefault().getMemberOrderPreferenceCache(); -// -// int orderIndex = getOrderPreference(member, orderStore); -// -// int insertPos = containerSize; -// int insertPosOrderIndex = -1; -// -// for (int i = containerSize - 1; i >= 0; i--) { -// int currOrderIndex = getOrderPreference(container.get(i), orderStore); -// if (orderIndex == currOrderIndex) { -// if (insertPosOrderIndex != orderIndex) { // no perfect match yet -// insertPos = i + 1; // after a same kind -// insertPosOrderIndex = orderIndex; // perfect match -// } -// } else if (insertPosOrderIndex != orderIndex) { // not yet a perfect match -// if (currOrderIndex < orderIndex) { // we are bigger -// if (insertPosOrderIndex == -1) { -// insertPos = i + 1; // after -// insertPosOrderIndex = currOrderIndex; -// } -// } else { -// insertPos = i; // before -// insertPosOrderIndex = currOrderIndex; -// } -// } -// } -// return insertPos; -// } -// -// public static SimpleName getLeftMostSimpleName(Name name) { -// if (name instanceof SimpleName) { -// return (SimpleName) name; -// } else { -// final SimpleName[] result = new SimpleName[1]; -// ASTVisitor visitor = new ASTVisitor() { -// @Override -// public boolean visit(QualifiedName qualifiedName) { -// Name left = qualifiedName.getQualifier(); -// if (left instanceof SimpleName) { -// result[0] = (SimpleName) left; -// } else { -// left.accept(this); -// } -// return false; -// } -// }; -// name.accept(visitor); -// return result[0]; -// } -// } -// -// public static SimpleType getLeftMostSimpleType(QualifiedType type) { -// final SimpleType[] result = new SimpleType[1]; -// ASTVisitor visitor = new ASTVisitor() { -// @Override -// public boolean visit(QualifiedType qualifiedType) { -// Type left = qualifiedType.getQualifier(); -// if (left instanceof SimpleType) { -// result[0] = (SimpleType) left; -// } else { -// left.accept(this); -// } -// return false; -// } -// }; -// type.accept(visitor); -// return result[0]; -// } -// -// public static IVariableBinding getLocalVariableBinding(Name node) { -// IVariableBinding result = getVariableBinding(node); -// if (result == null || result.isField()) { -// return null; -// } -// -// return result; -// } -// -// public static Message[] getMessages(DartNode node, int flags) { -// DartNode root = node.getRoot(); -// if (!(root instanceof CompilationUnit)) { -// return EMPTY_MESSAGES; -// } -// Message[] messages = ((CompilationUnit) root).getMessages(); -// if (root == node) { -// return messages; -// } -// final int iterations = computeIterations(flags); -// List result = new ArrayList(5); -// for (int i = 0; i < messages.length; i++) { -// Message message = messages[i]; -// DartNode temp = node; -// int count = iterations; -// do { -// int nodeOffset = temp.getStartPosition(); -// int messageOffset = message.getStartPosition(); -// if (nodeOffset <= messageOffset && messageOffset < nodeOffset + temp.getLength()) { -// result.add(message); -// count = 0; -// } else { -// count--; -// } -// } while ((temp = temp.getParent()) != null && count > 0); -// } -// return result.toArray(new Message[result.size()]); -// } -// -// public static IMethodBinding getMethodBinding(Name node) { -// IBinding binding = node.resolveBinding(); -// if (binding instanceof IMethodBinding) { -// return (IMethodBinding) binding; -// } -// return null; -// } -// -// public static List getModifiers(VariableDeclaration declaration) { -// Assert.isNotNull(declaration); -// if (declaration instanceof SingleVariableDeclaration) { -// return ((SingleVariableDeclaration) declaration).modifiers(); -// } else if (declaration instanceof VariableDeclarationFragment) { -// DartNode parent = declaration.getParent(); -// if (parent instanceof VariableDeclarationExpression) { -// return ((VariableDeclarationExpression) parent).modifiers(); -// } else if (parent instanceof VariableDeclarationStatement) { -// return ((VariableDeclarationStatement) parent).modifiers(); -// } -// } -// return new ArrayList(0); -// } -// -// /** -// * Returns the source of the given node from the location where it was parsed. -// * -// * @param node the node to get the source from -// * @param extendedRange if set, the extended ranges of the nodes should ne used -// * @param removeIndent if set, the indentation is removed. -// * @return return the source for the given node or null if accessing the source failed. -// */ -// public static String getNodeSource(DartNode node, boolean extendedRange, boolean removeIndent) { -// DartNode root = node.getRoot(); -// if (root instanceof CompilationUnit) { -// CompilationUnit astRoot = (CompilationUnit) root; -// ITypeRoot typeRoot = astRoot.getTypeRoot(); -// try { -// if (typeRoot != null && typeRoot.getBuffer() != null) { -// IBuffer buffer = typeRoot.getBuffer(); -// int offset = -// extendedRange ? astRoot.getExtendedStartPosition(node) : node.getStartPosition(); -// int length = extendedRange ? astRoot.getExtendedLength(node) : node.getLength(); -// String str = buffer.getText(offset, length); -// if (removeIndent) { -// IJavaProject project = typeRoot.getJavaProject(); -// int indent = StubUtility.getIndentUsed(buffer, node.getStartPosition(), project); -// str = -// Strings.changeIndent( -// str, -// indent, -// project, -// new String(), -// typeRoot.findRecommendedLineSeparator()); -// } -// return str; -// } -// } catch (JavaModelException e) { -// // ignore -// } -// } -// return null; -// } -// -// public static DartNode getNormalizedNode(DartNode node) { -// DartNode current = node; -// // normalize name -// if (QualifiedName.NAME_PROPERTY.equals(current.getLocationInParent())) { -// current = current.getParent(); -// } -// // normalize type -// if (QualifiedType.NAME_PROPERTY.equals(current.getLocationInParent()) -// || SimpleType.NAME_PROPERTY.equals(current.getLocationInParent())) { -// current = current.getParent(); -// } -// // normalize parameterized types -// if (ParameterizedType.TYPE_PROPERTY.equals(current.getLocationInParent())) { -// current = current.getParent(); -// } -// return current; -// } - - /** - * @return parent {@link DartNode}s from {@link DartUnit} (at index "0") to the given one. - */ - public static List getParents(DartNode node) { - List parents = Lists.newArrayList(); - DartNode current = node; - do { - parents.add(current.getParent()); - current = current.getParent(); - } while (current.getParent() != null); - Collections.reverse(parents); - return parents; - } - - /** - * @return given {@link DartStatement} if not {@link DartBlock}, first child {@link DartStatement} - * if {@link DartBlock}, or null if more than one child. - */ - public static DartStatement getSingleStatement(DartStatement statement) { - if (statement instanceof DartBlock) { - List blockStatements = ((DartBlock) statement).getStatements(); - if (blockStatements.size() != 1) { - return null; - } - return blockStatements.get(0); - } - return statement; - } - - /** - * @return given {@link DartStatement} if not {@link DartBlock}, all children - * {@link DartStatement}s if {@link DartBlock}. - */ - public static List getStatements(DartStatement statement) { - if (statement instanceof DartBlock) { - return ((DartBlock) statement).getStatements(); - } - return ImmutableList.of(statement); - } - - /** - * @return the {@link DartThisExpression} if given node is name of {@link DartPropertyAccess} with - * {@link DartThisExpression} qualifier. May be null. - */ - public static DartThisExpression getThisQualifier(DartIdentifier node) { - if (node.getParent() instanceof DartPropertyAccess) { - DartPropertyAccess propertyAccess = (DartPropertyAccess) node.getParent(); - if (propertyAccess.getName() == node - && propertyAccess.getQualifier() instanceof DartThisExpression) { - return (DartThisExpression) propertyAccess.getQualifier(); - } - } - return null; - } - - /** - * Return the type associated with the given type node, or null if the type could not - * be determined. - * - * @param typeNode the type node whose type is to be returned - * @return the type associated with the given type node - */ - public static Type getType(DartTypeNode typeNode) { - Type type = typeNode.getType(); - if (type == null) { - DartNode parent = typeNode.getParent(); - if (parent instanceof DartTypeNode) { - Type parentType = getType((DartTypeNode) parent); - if (parentType != null && parentType.getKind() == TypeKind.INTERFACE) { - int index = ((DartTypeNode) parent).getTypeArguments().indexOf(typeNode); - return ((InterfaceType) parentType).getArguments().get(index); - } - } - } - return type; - } - - /** - * @return the {@link VariableElement} with {@link ElementKind#VARIABLE} if the given - * {@link DartIdentifier} is the local variable reference, or null in the - * other case. - */ - public static VariableElement getVariableElement(DartIdentifier node) { - Element element = node.getElement(); - if (ElementKind.of(element) == ElementKind.VARIABLE) { - return (VariableElement) element; - } - return null; - } - - /** - * @return the {@link VariableElement} with {@link ElementKind#VARIABLE} or - * {@link ElementKind#PARAMETER} if the given {@link DartIdentifier} is the reference to - * local variable or parameter, or null in the other case. - */ - public static VariableElement getVariableOrParameterElement(DartIdentifier node) { - Element element = node.getElement(); - if (element instanceof VariableElement) { - return (VariableElement) element; - } - return null; - } - - /** - * Return true if the given method is a constructor. - * - * @param method the method being tested - * @return true if the given method is a constructor - */ - public static boolean isConstructor(DartMethodDefinition method) { - MethodElement methodElement = method.getElement(); - if (methodElement != null) { - return methodElement.isConstructor(); - } - return isConstructor(((DartClass) method.getParent()).getClassName(), method); - } - - /** - * Return true if the given method is a constructor. - * - * @param className the name of the type containing the method definition - * @param method the method being tested - * @return true if the given method is a constructor - */ - public static boolean isConstructor(String className, DartMethodDefinition method) { - if (method.getModifiers().isFactory()) { - return true; - } - DartExpression name = method.getName(); - if (name instanceof DartIdentifier) { - return ((DartIdentifier) name).getName().equals(className); - } else if (name instanceof DartPropertyAccess) { - DartPropertyAccess property = (DartPropertyAccess) name; - DartNode qualifier = property.getQualifier(); - if (qualifier instanceof DartIdentifier) { - return ((DartIdentifier) qualifier).getName().equals(className); - } - } - return false; - } - - /** - * @return true if given {@link DartNode} is the name of some {@link DartDeclaration} - * . - */ - public static boolean isNameOfDeclaration(DartNode node) { - return node.getParent() instanceof DartDeclaration - && ((DartDeclaration) node.getParent()).getName() == node; - } - - /** - * @return true if given {@link List}s are equals at given position. - */ - private static boolean allListsEqual(List> lists, int position) { - T element = lists.get(0).get(position); - for (List list : lists) { - if (list.get(position) != element) { - return false; - } - } - return true; - } - - private static List getLongestListPrefix(List> lists) { - if (lists.isEmpty()) { - return ImmutableList.of(); - } - // prepare minimal length of all arrays - int minLength = lists.get(0).size(); - for (List list : lists) { - minLength = Math.min(minLength, list.size()); - } - // find length of the common prefix - int length = -1; - for (int i = 0; i < minLength; i++) { - if (!allListsEqual(lists, i)) { - break; - } - length++; - } - // done - return lists.get(0).subList(0, length + 1); - } - -// /** -// * Returns the closest ancestor of node whose type is nodeType, or -// * null if none. -// *

-// * Warning: This method does not stop at any boundaries like parentheses, statements, body -// * declarations, etc. The resulting node may be in a totally different scope than the given node. -// * Consider using one of the {@link ASTResolving}.find(..) methods instead. -// *

-// * -// * @param node the node -// * @param nodeType the node type constant from {@link DartNode} -// * @return the closest ancestor of node whose type is nodeType, or -// * null if none -// */ -// public static DartNode getParent(DartNode node, int nodeType) { -// do { -// node = node.getParent(); -// } while (node != null && node.getNodeType() != nodeType); -// return node; -// } -// -// public static IProblem[] getProblems(DartNode node, int scope, int severity) { -// DartNode root = node.getRoot(); -// if (!(root instanceof CompilationUnit)) { -// return EMPTY_PROBLEMS; -// } -// IProblem[] problems = ((CompilationUnit) root).getProblems(); -// if (root == node) { -// return problems; -// } -// final int iterations = computeIterations(scope); -// List result = new ArrayList(5); -// for (int i = 0; i < problems.length; i++) { -// IProblem problem = problems[i]; -// boolean consider = false; -// if ((severity & PROBLEMS) == PROBLEMS) { -// consider = true; -// } else if ((severity & WARNING) != 0) { -// consider = problem.isWarning(); -// } else if ((severity & ERROR) != 0) { -// consider = problem.isError(); -// } -// if (consider) { -// DartNode temp = node; -// int count = iterations; -// do { -// int nodeOffset = temp.getStartPosition(); -// int problemOffset = problem.getSourceStart(); -// if (nodeOffset <= problemOffset && problemOffset < nodeOffset + temp.getLength()) { -// result.add(problem); -// count = 0; -// } else { -// count--; -// } -// } while ((temp = temp.getParent()) != null && count > 0); -// } -// } -// return result.toArray(new IProblem[result.size()]); -// } -// -// public static String getQualifier(Name name) { -// if (name.isQualifiedName()) { -// return ((QualifiedName) name).getQualifier().getFullyQualifiedName(); -// } -// return ""; //$NON-NLS-1$ -// } -// -// /** -// * Returns the receiver's type binding of the given method invocation. -// * -// * @param invocation method invocation to resolve type of -// * @return the type binding of the receiver -// */ -// public static ITypeBinding getReceiverTypeBinding(MethodInvocation invocation) { -// ITypeBinding result = null; -// Expression exp = invocation.getExpression(); -// if (exp != null) { -// return exp.resolveTypeBinding(); -// } else { -// AbstractTypeDeclaration type = -// (AbstractTypeDeclaration) getParent(invocation, AbstractTypeDeclaration.class); -// if (type != null) { -// return type.resolveBinding(); -// } -// } -// return result; -// } -// -// public static String getSimpleNameIdentifier(Name name) { -// if (name.isQualifiedName()) { -// return ((QualifiedName) name).getName().getIdentifier(); -// } else { -// return ((SimpleName) name).getIdentifier(); -// } -// } -// -// public static Name getTopMostName(Name name) { -// Name result = name; -// while (result.getParent() instanceof Name) { -// result = (Name) result.getParent(); -// } -// return result; -// } -// -// public static Type getTopMostType(Type type) { -// Type result = type; -// while (result.getParent() instanceof Type) { -// result = (Type) result.getParent(); -// } -// return result; -// } -// -// /** -// * Returns the type node for the given declaration. -// * -// * @param declaration the declaration -// * @return the type node -// */ -// public static Type getType(VariableDeclaration declaration) { -// if (declaration instanceof SingleVariableDeclaration) { -// return ((SingleVariableDeclaration) declaration).getType(); -// } else if (declaration instanceof VariableDeclarationFragment) { -// DartNode parent = ((VariableDeclarationFragment) declaration).getParent(); -// if (parent instanceof VariableDeclarationExpression) { -// return ((VariableDeclarationExpression) parent).getType(); -// } else if (parent instanceof VariableDeclarationStatement) { -// return ((VariableDeclarationStatement) parent).getType(); -// } else if (parent instanceof FieldDeclaration) { -// return ((FieldDeclaration) parent).getType(); -// } -// } -// Assert.isTrue(false, "Unknown VariableDeclaration"); //$NON-NLS-1$ -// return null; -// } -// -// public static ITypeBinding getTypeBinding(CompilationUnit root, IType type) -// throws JavaModelException { -// if (type.isAnonymous()) { -// final IJavaElement parent = type.getParent(); -// if (parent instanceof IField && Flags.isEnum(((IMember) parent).getFlags())) { -// final EnumConstantDeclaration constant = -// (EnumConstantDeclaration) NodeFinder.perform( -// root, -// ((ISourceReference) parent).getSourceRange()); -// if (constant != null) { -// final AnonymousClassDeclaration declaration = constant.getAnonymousClassDeclaration(); -// if (declaration != null) { -// return declaration.resolveBinding(); -// } -// } -// } else { -// final ClassInstanceCreation creation = -// (ClassInstanceCreation) getParent( -// NodeFinder.perform(root, type.getNameRange()), -// ClassInstanceCreation.class); -// if (creation != null) { -// return creation.resolveTypeBinding(); -// } -// } -// } else { -// final AbstractTypeDeclaration declaration = -// (AbstractTypeDeclaration) getParent( -// NodeFinder.perform(root, type.getNameRange()), -// AbstractTypeDeclaration.class); -// if (declaration != null) { -// return declaration.resolveBinding(); -// } -// } -// return null; -// } -// -// public static ITypeBinding getTypeBinding(Name node) { -// IBinding binding = node.resolveBinding(); -// if (binding instanceof ITypeBinding) { -// return (ITypeBinding) binding; -// } -// return null; -// } -// -// public static String getTypeName(Type type) { -// final StringBuffer buffer = new StringBuffer(); -// ASTVisitor visitor = new ASTVisitor() { -// @Override -// public void endVisit(ArrayType node) { -// buffer.append("[]"); //$NON-NLS-1$ -// } -// -// @Override -// public boolean visit(PrimitiveType node) { -// buffer.append(node.getPrimitiveTypeCode().toString()); -// return false; -// } -// -// @Override -// public boolean visit(QualifiedName node) { -// buffer.append(node.getName().getIdentifier()); -// return false; -// } -// -// @Override -// public boolean visit(SimpleName node) { -// buffer.append(node.getIdentifier()); -// return false; -// } -// }; -// type.accept(visitor); -// return buffer.toString(); -// } -// -// public static IVariableBinding getVariableBinding(Name node) { -// IBinding binding = node.resolveBinding(); -// if (binding instanceof IVariableBinding) { -// return (IVariableBinding) binding; -// } -// return null; -// } -// -// /** -// * Returns true if a node at a given location is a body of a control statement. Such body nodes -// * are interesting as when replacing them, it has to be evaluates if a Block is needed instead. -// * E.g. if (x) do(); -> if (x) { do1(); do2() } -// * -// * @param locationInParent Location of the body node -// * @return Returns true if the location is a body node location of a control statement. -// */ -// public static boolean isControlStatementBody(StructuralPropertyDescriptor locationInParent) { -// return locationInParent == IfStatement.THEN_STATEMENT_PROPERTY -// || locationInParent == IfStatement.ELSE_STATEMENT_PROPERTY -// || locationInParent == ForStatement.BODY_PROPERTY -// || locationInParent == EnhancedForStatement.BODY_PROPERTY -// || locationInParent == WhileStatement.BODY_PROPERTY -// || locationInParent == DoStatement.BODY_PROPERTY; -// } -// -// public static boolean isDeclaration(Name name) { -// if (name.isQualifiedName()) { -// return ((QualifiedName) name).getName().isDeclaration(); -// } else { -// return ((SimpleName) name).isDeclaration(); -// } -// } -// -// /** -// * Returns true if this is an existing node, i.e. it was created as part of a parsing process of a -// * source code file. Returns false if this is a newly created node which has not yet been given a -// * source position. -// * -// * @param node the node to be tested. -// * @return true if this is an existing node, false if not. -// */ -// public static boolean isExistingNode(DartNode node) { -// return node.getStartPosition() != -1; -// } -// -// public static boolean isLabel(SimpleName name) { -// int parentType = name.getParent().getNodeType(); -// return parentType == DartNode.LABELED_STATEMENT -// || parentType == DartNode.BREAK_STATEMENT -// || parentType != DartNode.CONTINUE_STATEMENT; -// } -// -// public static boolean isLiteral(Expression expression) { -// int type = expression.getNodeType(); -// return type == DartNode.BOOLEAN_LITERAL -// || type == DartNode.CHARACTER_LITERAL -// || type == DartNode.NULL_LITERAL -// || type == DartNode.NUMBER_LITERAL -// || type == DartNode.STRING_LITERAL -// || type == DartNode.TYPE_LITERAL; -// } -// -// /** -// * Returns true iff parent is a true ancestor of node (i.e. -// * returns false if parent == node). -// * -// * @param node node to test -// * @param parent assumed parent -// * @return true iff parent is a true ancestor of node -// */ -// public static boolean isParent(DartNode node, DartNode parent) { -// Assert.isNotNull(parent); -// do { -// node = node.getParent(); -// if (node == parent) { -// return true; -// } -// } while (node != null); -// return false; -// } -// -// public static boolean isSingleDeclaration(VariableDeclaration declaration) { -// Assert.isNotNull(declaration); -// if (declaration instanceof SingleVariableDeclaration) { -// return true; -// } else if (declaration instanceof VariableDeclarationFragment) { -// DartNode parent = declaration.getParent(); -// if (parent instanceof VariableDeclarationExpression) { -// return ((VariableDeclarationExpression) parent).fragments().size() == 1; -// } else if (parent instanceof VariableDeclarationStatement) { -// return ((VariableDeclarationStatement) parent).fragments().size() == 1; -// } -// } -// return false; -// } -// -// public static boolean isStatic(BodyDeclaration declaration) { -// return Modifier.isStatic(declaration.getModifiers()); -// } -// -// /** -// * Adds flags to the given node and all its descendants. -// * -// * @param root The root node -// * @param flags The flags to set -// */ -// public static void setFlagsToAST(DartNode root, final int flags) { -// root.accept(new GenericVisitor(true) { -// @Override -// protected boolean visitNode(DartNode node) { -// node.setFlags(node.getFlags() | flags); -// return true; -// } -// }); -// } -// -// private static int computeIterations(int flags) { -// switch (flags) { -// case NODE_ONLY: -// return 1; -// case INCLUDE_ALL_PARENTS: -// return Integer.MAX_VALUE; -// case INCLUDE_FIRST_PARENT: -// return 2; -// default: -// return 1; -// } -// } -// -// private static int getOrderPreference(BodyDeclaration member, MembersOrderPreferenceCache store) { -// int memberType = member.getNodeType(); -// int modifiers = member.getModifiers(); -// -// switch (memberType) { -// case DartNode.TYPE_DECLARATION: -// case DartNode.ENUM_DECLARATION: -// case DartNode.ANNOTATION_TYPE_DECLARATION: -// return store.getCategoryIndex(MembersOrderPreferenceCache.TYPE_INDEX) * 2; -// case DartNode.FIELD_DECLARATION: -// if (Modifier.isStatic(modifiers)) { -// int index = store.getCategoryIndex(MembersOrderPreferenceCache.STATIC_FIELDS_INDEX) * 2; -// if (Modifier.isFinal(modifiers)) { -// return index; // first final static, then static -// } -// return index + 1; -// } -// return store.getCategoryIndex(MembersOrderPreferenceCache.FIELDS_INDEX) * 2; -// case DartNode.INITIALIZER: -// if (Modifier.isStatic(modifiers)) { -// return store.getCategoryIndex(MembersOrderPreferenceCache.STATIC_INIT_INDEX) * 2; -// } -// return store.getCategoryIndex(MembersOrderPreferenceCache.INIT_INDEX) * 2; -// case DartNode.ANNOTATION_TYPE_MEMBER_DECLARATION: -// return store.getCategoryIndex(MembersOrderPreferenceCache.METHOD_INDEX) * 2; -// case DartNode.METHOD_DECLARATION: -// if (Modifier.isStatic(modifiers)) { -// return store.getCategoryIndex(MembersOrderPreferenceCache.STATIC_METHODS_INDEX) * 2; -// } -// if (((MethodDeclaration) member).isConstructor()) { -// return store.getCategoryIndex(MembersOrderPreferenceCache.CONSTRUCTORS_INDEX) * 2; -// } -// return store.getCategoryIndex(MembersOrderPreferenceCache.METHOD_INDEX) * 2; -// default: -// return 100; -// } -// } -// -// /** -// * Returns whether an expression at the given location needs explicit boxing. -// * -// * @param expression the expression -// * @return true iff an expression at the given location needs explicit boxing -// */ -// private static boolean needsExplicitBoxing(Expression expression) { -// StructuralPropertyDescriptor locationInParent = expression.getLocationInParent(); -// if (locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY) { -// return needsExplicitBoxing((ParenthesizedExpression) expression.getParent()); -// } -// -// if (locationInParent == ClassInstanceCreation.EXPRESSION_PROPERTY -// || locationInParent == FieldAccess.EXPRESSION_PROPERTY -// || locationInParent == MethodInvocation.EXPRESSION_PROPERTY) { -// return true; -// } -// -// return false; -// } - - private ASTNodes() { - // no instance; - } - - /** - * Looks to see if the property access requires a getter. - *

- * A property access requires a getter if it is on the right hand side of an assignment, or if it - * is on the left hand side of an assignment and uses one of the assignment operators other than - * plain '='. - *

- * Note, that we don't check if given {@link DartNode} is actually field name. - */ - public static boolean inGetterContext(DartNode node) { - if (node.getParent() instanceof DartBinaryExpression) { - DartBinaryExpression expr = (DartBinaryExpression) node.getParent(); - if (expr.getArg1() == node && expr.getOperator() == Token.ASSIGN) { - return false; - } - } - return true; - } - - /** - * Looks to see if the property access requires a setter. - *

- * Basically, this boils down to any property access on the left hand side of an assignment. - *

- * Keep in mind that an assignment of the form node = is the only kind of write-only - * expression. Other types of assignments also read the value and require a getter access. - *

- * Note, that we don't check if given {@link DartNode} is actually field name. - */ - public static boolean inSetterContext(DartNode node) { - if (node.getParent() instanceof DartUnaryExpression) { - DartUnaryExpression expr = (DartUnaryExpression) node.getParent(); - return expr.getArg() == node && expr.getOperator().isCountOperator(); - } - if (node.getParent() instanceof DartBinaryExpression) { - DartBinaryExpression expr = (DartBinaryExpression) node.getParent(); - return expr.getArg1() == node && expr.getOperator().isAssignmentOperator(); - } - return false; - } - - /** - * @return the {@link DartIdentifier} corresponding to the name of constructor. - */ - public static DartIdentifier getConstructorNameNode(DartNewExpression node) { - DartNode constructor = node.getConstructor(); - return getConstructorNameNode(constructor); - } - - /** - * @return the {@link DartIdentifier} corresponding to the name of constructor. - */ - private static DartIdentifier getConstructorNameNode(DartNode constructor) { - if (constructor instanceof DartPropertyAccess) { - return ((DartPropertyAccess) constructor).getName(); - } else if (constructor instanceof DartTypeNode) { - return getConstructorNameNode(((DartTypeNode) constructor).getIdentifier()); - } else { - return (DartIdentifier) constructor; - } - } - - /** - * @return true if given {@link DartNode} has {@link DartSuperExpression}. - */ - public static boolean hasSuperInvocation(DartNode node) { - final AtomicBoolean result = new AtomicBoolean(); - node.accept(new ASTVisitor() { - @Override - public Void visitSuperExpression(DartSuperExpression node) { - result.set(true); - return null; - } - }); - return result.get(); - } - -} diff --git a/compiler/java/com/google/dart/compiler/ast/ASTVisitor.java b/compiler/java/com/google/dart/compiler/ast/ASTVisitor.java deleted file mode 100644 index 6223fa0c9192..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/ASTVisitor.java +++ /dev/null @@ -1,411 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import java.util.List; - -/** - * A visitor for abstract syntax tree. - * - *

- *
- * public R visitArrayAccess(DartArrayAccess node) {
- *   // Actions before visiting subnodes.
- *   node.visitChildren(this);
- *   // Actions after visiting subnodes.
- *   return node;
- * }
- * 
- * - *

- * In addition, this visitor takes advantage of the AST-node class hierarchy and makes it easy to - * perform an action for, for example, all statements: - * - *

- *
- * public R visitStatement(DartStatement node) {
- *   // Action that must be performed for all statements.
- * }
- * 
- */ -public class ASTVisitor { - - public R visitNode(DartNode node) { - node.visitChildren(this); - return null; - } - - public R visitNodeWithMetadata(DartNodeWithMetadata node) { - return visitNode(node); - } - - public R visitDirective(DartDirective node) { - return visitNodeWithMetadata(node); - } - - public R visitInvocation(DartInvocation node) { - return visitExpression(node); - } - - public R visitExportDirective(DartExportDirective node) { - return visitDirective(node); - } - - public R visitExpression(DartExpression node) { - return visitNode(node); - } - - public R visitStatement(DartStatement node) { - return visitNode(node); - } - - public R visitLiteral(DartLiteral node) { - return visitExpression(node); - } - - public R visitGotoStatement(DartGotoStatement node) { - return visitStatement(node); - } - - public R visitSwitchMember(DartSwitchMember node) { - return visitNode(node); - } - - public R visitDeclaration(DartDeclaration node) { - return visitNodeWithMetadata(node); - } - - public R visitClassMember(DartClassMember node) { - return visitDeclaration(node); - } - - public R visitComment(DartComment node) { - return visitNode(node); - } - - public R visitCommentNewName(DartCommentNewName node) { - return visitNode(node); - } - - public R visitCommentRefName(DartCommentRefName node) { - return visitNode(node); - } - - public R visitAnnotation(DartAnnotation node) { - return visitNode(node); - } - - public R visitArrayAccess(DartArrayAccess node) { - return visitExpression(node); - } - - public R visitArrayLiteral(DartArrayLiteral node) { - return visitTypedLiteral(node); - } - - public R visitBinaryExpression(DartBinaryExpression node) { - return visitExpression(node); - } - - public R visitBlock(DartBlock node) { - return visitStatement(node); - } - - public R visitReturnBlock(DartReturnBlock node) { - return visitBlock(node); - } - - public R visitBooleanLiteral(DartBooleanLiteral node) { - return visitLiteral(node); - } - - public R visitAssertStatement(DartAssertStatement node) { - return visitStatement(node); - } - - public R visitBreakStatement(DartBreakStatement node) { - return visitGotoStatement(node); - } - - public R visitFunctionObjectInvocation(DartFunctionObjectInvocation node) { - return visitInvocation(node); - } - - public R visitMethodInvocation(DartMethodInvocation node) { - return visitInvocation(node); - } - - public R visitUnqualifiedInvocation(DartUnqualifiedInvocation node) { - return visitInvocation(node); - } - - public R visitSuperConstructorInvocation(DartSuperConstructorInvocation node) { - return visitInvocation(node); - } - - public R visitCascadeExpression(DartCascadeExpression node) { - return visitExpression(node); - } - - public R visitCase(DartCase node) { - return visitSwitchMember(node); - } - - public R visitClass(DartClass node) { - return visitDeclaration(node); - } - - public R visitConditional(DartConditional node) { - return visitExpression(node); - } - - public R visitContinueStatement(DartContinueStatement node) { - return visitGotoStatement(node); - } - - public R visitDefault(DartDefault node) { - return visitSwitchMember(node); - } - - public R visitDoubleLiteral(DartDoubleLiteral node) { - return visitLiteral(node); - } - - public R visitDoWhileStatement(DartDoWhileStatement node) { - return visitStatement(node); - } - - public R visitEmptyStatement(DartEmptyStatement node) { - return visitStatement(node); - } - - public R visitExprStmt(DartExprStmt node) { - return visitStatement(node); - } - - public R visitField(DartField node) { - return visitClassMember(node); - } - - public R visitFieldDefinition(DartFieldDefinition node) { - return visitNodeWithMetadata(node); - } - - public R visitForInStatement(DartForInStatement node) { - return visitStatement(node); - } - - public R visitForStatement(DartForStatement node) { - return visitStatement(node); - } - - public R visitFunction(DartFunction node) { - return visitNode(node); - } - - public R visitFunctionExpression(DartFunctionExpression node) { - return visitExpression(node); - } - - public R visitFunctionTypeAlias(DartFunctionTypeAlias node) { - return visitDeclaration(node); - } - - public R visitClassTypeAlias(DartClassTypeAlias node) { - return visitDeclaration(node); - } - - public R visitIdentifier(DartIdentifier node) { - return visitExpression(node); - } - - public R visitIfStatement(DartIfStatement node) { - return visitStatement(node); - } - - public R visitImportCombinator(ImportCombinator node) { - return visitNode(node); - } - - public R visitImportDirective(DartImportDirective node) { - return visitDirective(node); - } - - public R visitImportHideCombinator(ImportHideCombinator node) { - return visitImportCombinator(node); - } - - public R visitImportShowCombinator(ImportShowCombinator node) { - return visitImportCombinator(node); - } - - public R visitInitializer(DartInitializer node) { - return visitNode(node); - } - - public R visitIntegerLiteral(DartIntegerLiteral node) { - return visitLiteral(node); - } - - public R visitLabel(DartLabel node) { - return visitStatement(node); - } - - public R visitLibraryDirective(DartLibraryDirective node) { - return visitDirective(node); - } - - public R visitTypedLiteral(DartTypedLiteral node) { - return visitExpression(node); - } - - public R visitMapLiteral(DartMapLiteral node) { - return visitTypedLiteral(node); - } - - public R visitMapLiteralEntry(DartMapLiteralEntry node) { - return visitNode(node); - } - - public R visitMethodDefinition(DartMethodDefinition node) { - return visitClassMember(node); - } - - public R visitNativeDirective(DartNativeDirective node) { - return visitDirective(node); - } - - public R visitNewExpression(DartNewExpression node) { - return visitInvocation(node); - } - - public R visitNullLiteral(DartNullLiteral node) { - return visitLiteral(node); - } - - public R visitParameter(DartParameter node) { - return visitDeclaration(node); - } - - public R visitParameterizedTypeNode(DartParameterizedTypeNode node) { - return visitExpression(node); - } - - public R visitParenthesizedExpression(DartParenthesizedExpression node) { - return visitExpression(node); - } - - public R visitPartOfDirective(DartPartOfDirective node) { - return visitDirective(node); - } - - public R visitPropertyAccess(DartPropertyAccess node) { - return visitExpression(node); - } - - public R visitTypeNode(DartTypeNode node) { - return visitNode(node); - } - - public R visitReturnStatement(DartReturnStatement node) { - return visitStatement(node); - } - - public R visitSourceDirective(DartSourceDirective node) { - return visitDirective(node); - } - - public R visitStringLiteral(DartStringLiteral node) { - return visitLiteral(node); - } - - public R visitStringInterpolation(DartStringInterpolation node) { - return visitLiteral(node); - } - - public R visitSuperExpression(DartSuperExpression node) { - return visitExpression(node); - } - - public R visitSwitchStatement(DartSwitchStatement node) { - return visitStatement(node); - } - - public R visitSyntheticErrorExpression(DartSyntheticErrorExpression node) { - return visitExpression(node); - } - - public R visitSyntheticErrorIdentifier(DartSyntheticErrorIdentifier node) { - return visitIdentifier(node); - } - - public R visitSyntheticErrorStatement(DartSyntheticErrorStatement node) { - return visitStatement(node); - } - - public R visitThisExpression(DartThisExpression node) { - return visitExpression(node); - } - - public R visitThrowExpression(DartThrowExpression node) { - return visitExpression(node); - } - - public R visitCatchBlock(DartCatchBlock node) { - return visitStatement(node); - } - - public R visitTryStatement(DartTryStatement node) { - return visitStatement(node); - } - - public R visitUnaryExpression(DartUnaryExpression node) { - return visitExpression(node); - } - - public R visitUnit(DartUnit node) { - return visitNode(node); - } - - public R visitVariable(DartVariable node) { - return visitDeclaration(node); - } - - public R visitVariableStatement(DartVariableStatement node) { - return visitStatement(node); - } - - public R visitWhileStatement(DartWhileStatement node) { - return visitStatement(node); - } - - public void visit(List nodes) { - if (nodes != null) { - for (DartNode node : nodes) { - node.accept(this); - } - } - } - - public R visitNamedExpression(DartNamedExpression node) { - return visitExpression(node); - } - - public R visitTypeExpression(DartTypeExpression node) { - return visitExpression(node); - } - - public R visitTypeParameter(DartTypeParameter node) { - return visitDeclaration(node); - } - - public R visitNativeBlock(DartNativeBlock node) { - return visitBlock(node); - } - - public R visitRedirectConstructorInvocation(DartRedirectConstructorInvocation node) { - return visitInvocation(node); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartAnnotation.java b/compiler/java/com/google/dart/compiler/ast/DartAnnotation.java deleted file mode 100644 index ab44015decd2..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartAnnotation.java +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import java.util.List; - - -/** - * Instances of the class {@code DartAnnotation} represent metadata that can be associated with an - * AST node. - * - *
- * metadata ::=
- *     annotation*
- * 
- * annotation ::=
- *     '@' qualified ('.' identifier)? arguments?
- * 
- */ -public class DartAnnotation extends DartNode { - private DartExpression name; - - private NodeList arguments = NodeList.create(this); - - public DartAnnotation(DartExpression name, List arguments) { - this.name = becomeParentOf(name); - if (arguments != null) { - this.arguments.addAll(arguments); - } - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitAnnotation(this); - } - - public DartExpression getName() { - return name; - } - - public NodeList getArguments() { - return arguments; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(name, visitor); - arguments.accept(visitor); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartArrayAccess.java b/compiler/java/com/google/dart/compiler/ast/DartArrayAccess.java deleted file mode 100644 index 959ac36e03a7..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartArrayAccess.java +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.resolver.Element; -import com.google.dart.compiler.resolver.MethodNodeElement; - -/** - * Represents a Dart array access expression (a[b]). - */ -public class DartArrayAccess extends DartExpression { - - private DartExpression target; - private boolean isCascade; - private DartExpression key; - private MethodNodeElement element; - - public DartArrayAccess(DartExpression target, DartExpression key) { - this(target, false, key); - } - - public DartArrayAccess(DartExpression target, boolean isCascade, DartExpression key) { - this.target = becomeParentOf(target); - this.isCascade = isCascade; - this.key = becomeParentOf(key); - } - - @Override - public boolean isAssignable() { - return true; - } - - public boolean isCascade() { - return isCascade; - } - - public DartExpression getKey() { - return key; - } - - public DartExpression getTarget() { - return target; - } - - public DartExpression getRealTarget() { - if (isCascade) { - DartNode ancestor = getParent(); - while (!(ancestor instanceof DartCascadeExpression)) { - if (ancestor == null) { - return target; - } - ancestor = ancestor.getParent(); - } - return ((DartCascadeExpression) ancestor).getTarget(); - } - return target; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(target, visitor); - safelyVisitChild(key, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitArrayAccess(this); - } - - @Override - public MethodNodeElement getElement() { - return element; - } - - @Override - public void setElement(Element element) { - this.element = (MethodNodeElement) element; - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartArrayLiteral.java b/compiler/java/com/google/dart/compiler/ast/DartArrayLiteral.java deleted file mode 100644 index 5c9ad5fb8c21..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartArrayLiteral.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import java.util.List; - -/** - * Represents a Dart array literal value. - */ -public class DartArrayLiteral extends DartTypedLiteral { - - private final NodeList expressions = NodeList.create(this); - - public DartArrayLiteral(boolean isConst, List typeArguments, - List expressions) { - super(isConst, typeArguments); - this.expressions.addAll(expressions); - } - - public List getExpressions() { - return expressions; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - super.visitChildren(visitor); - expressions.accept(visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitArrayLiteral(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartAssertStatement.java b/compiler/java/com/google/dart/compiler/ast/DartAssertStatement.java deleted file mode 100644 index 91572a23109a..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartAssertStatement.java +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Represents a Dart 'assert' statement. - */ -public class DartAssertStatement extends DartStatement { - - private final DartExpression condition; - - public DartAssertStatement(DartExpression condition) { - this.condition = becomeParentOf(condition); - } - - public DartExpression getCondition() { - return condition; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(condition, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitAssertStatement(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartBinaryExpression.java b/compiler/java/com/google/dart/compiler/ast/DartBinaryExpression.java deleted file mode 100644 index 25017d28440d..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartBinaryExpression.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.parser.Token; -import com.google.dart.compiler.resolver.Element; -import com.google.dart.compiler.resolver.MethodNodeElement; - -/** - * Represents a Dart binary expression. - */ -public class DartBinaryExpression extends DartExpression { - - private final Token op; - private final int opOffset; - private DartExpression arg1; - private DartExpression arg2; - private MethodNodeElement element; - - public DartBinaryExpression(Token op, int opOffset, DartExpression arg1, DartExpression arg2) { - this.opOffset = opOffset; - assert op.isBinaryOperator() : op; - - this.op = op; - this.arg1 = becomeParentOf(arg1 != null ? arg1 : new DartSyntheticErrorExpression()); - this.arg2 = becomeParentOf(arg2 != null ? arg2 : new DartSyntheticErrorExpression()); - } - - public DartExpression getArg1() { - return arg1; - } - - public DartExpression getArg2() { - return arg2; - } - - public Token getOperator() { - return op; - } - - /** - * @return the character offset of the {@link #getOperator()} token. - */ - public int getOperatorOffset() { - return opOffset; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(arg1, visitor); - safelyVisitChild(arg2, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitBinaryExpression(this); - } - - @Override - public MethodNodeElement getElement() { - return element; - } - - @Override - public void setElement(Element element) { - this.element = (MethodNodeElement) element; - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartBlock.java b/compiler/java/com/google/dart/compiler/ast/DartBlock.java deleted file mode 100644 index 27d0d0580285..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartBlock.java +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import java.util.List; - -/** - * Represents a Dart statement block. - */ -public class DartBlock extends DartStatement { - - private final NodeList statements = NodeList.create(this); - - public DartBlock(List statements) { - if (statements != null && !statements.isEmpty()) { - this.statements.addAll(statements); - } - } - - public List getStatements() { - return statements; - } - - @Override - public boolean isAbruptCompletingStatement() { - for (DartStatement stmt : statements) { - if (stmt.isAbruptCompletingStatement()) { - return true; - } - } - return false; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - statements.accept(visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitBlock(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartBooleanLiteral.java b/compiler/java/com/google/dart/compiler/ast/DartBooleanLiteral.java deleted file mode 100644 index cdf51600dace..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartBooleanLiteral.java +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Represents a Dart boolean literal value. - */ -public class DartBooleanLiteral extends DartLiteral { - - public static DartBooleanLiteral get(boolean value) { - return new DartBooleanLiteral(value); - } - - private final boolean value; - - private DartBooleanLiteral(boolean value) { - this.value = value; - } - - public boolean getValue() { - return value; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitBooleanLiteral(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartBreakStatement.java b/compiler/java/com/google/dart/compiler/ast/DartBreakStatement.java deleted file mode 100644 index 7d51c330d708..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartBreakStatement.java +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Represents a Dart 'break' statement. - */ -public class DartBreakStatement extends DartGotoStatement { - - public DartBreakStatement(DartIdentifier label) { - super(label); - } - - @Override - public boolean isAbruptCompletingStatement() { - return true; - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitBreakStatement(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartCascadeExpression.java b/compiler/java/com/google/dart/compiler/ast/DartCascadeExpression.java deleted file mode 100644 index 6c9b2b812b5f..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartCascadeExpression.java +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import java.util.List; - -/** - * Instances of the class {@code DartCascadeExpression} represent a sequence of cascaded expressions: - * expressions that share a common target. There are three kinds of expressions that can be used in - * a cascade expression: {@link DartArrayAccess}, {@link DartMethodInvocation} and {@link DartPropertyAccess}. - * - *
- * cascadeExpression ::=
- *     {@link DartExpression conditionalExpression} cascadeSection*
- * 
- * cascadeSection ::=
- *     '..'  (cascadeSelector arguments*) (assignableSelector arguments*)* (assignmentOperator expressionWithoutCascade)?
- * 
- * cascadeSelector ::=
- *     '[ ' expression '] '
- *   | identifier
- * 
- */ -public class DartCascadeExpression extends DartExpression { - /** - * The target of the cascade sections. - */ - private DartExpression target; - - /** - * The cascade sections sharing the common target. - */ - private NodeList cascadeSections = new NodeList(this); - - /** - * Initialize a newly created cascade expression. - * - * @param target the target of the cascade sections - * @param cascadeSections the cascade sections sharing the common target - */ - public DartCascadeExpression(DartExpression target, List cascadeSections) { - this.target = becomeParentOf(target); - this.cascadeSections.addAll(cascadeSections); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitCascadeExpression(this); - } - - /** - * Return the cascade sections sharing the common target. - * - * @return the cascade sections sharing the common target - */ - public NodeList getCascadeSections() { - return cascadeSections; - } - - /** - * Return the target of the cascade sections. - * - * @return the target of the cascade sections - */ - public DartExpression getTarget() { - return target; - } - - /** - * Set the target of the cascade sections to the given expression. - * - * @param target the target of the cascade sections - */ - public void setTarget(DartExpression target) { - this.target = becomeParentOf(target); - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(target, visitor); - cascadeSections.accept(visitor); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartCase.java b/compiler/java/com/google/dart/compiler/ast/DartCase.java deleted file mode 100644 index 5285fd354e3a..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartCase.java +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import java.util.List; - -/** - * Represents a Dart 'case' switch member. - */ -public class DartCase extends DartSwitchMember { - - private DartExpression expr; - - public DartCase(DartExpression expr, List labels, List statements) { - super(labels, statements); - this.expr = becomeParentOf(expr); - } - - public DartExpression getExpr() { - return expr; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(expr, visitor); - super.visitChildren(visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitCase(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartCatchBlock.java b/compiler/java/com/google/dart/compiler/ast/DartCatchBlock.java deleted file mode 100644 index 6ab02f5af492..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartCatchBlock.java +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Represents a Dart 'catch' block. - */ -public class DartCatchBlock extends DartStatement { - private final int onTokenOffset; - private final DartParameter exception; - private final DartParameter stackTrace; - private final DartBlock block; - - public DartCatchBlock(DartBlock block, - int onTokenOffset, - DartParameter exception, - DartParameter stackTrace) { - this.block = becomeParentOf(block); - this.onTokenOffset = onTokenOffset; - this.exception = becomeParentOf(exception); - this.stackTrace = becomeParentOf(stackTrace); - } - - public int getOnTokenOffset() { - return onTokenOffset; - } - - public DartParameter getException() { - return exception; - } - - public DartParameter getStackTrace() { - return stackTrace; - } - - public DartBlock getBlock() { - return block; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(exception, visitor); - safelyVisitChild(stackTrace, visitor); - safelyVisitChild(block, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitCatchBlock(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartClass.java b/compiler/java/com/google/dart/compiler/ast/DartClass.java deleted file mode 100644 index ede1696b6b77..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartClass.java +++ /dev/null @@ -1,204 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.resolver.ClassNodeElement; -import com.google.dart.compiler.resolver.Element; - -import java.util.List; - -/** - * Represents a Dart class. - */ -public class DartClass extends DartDeclaration { - - private ClassNodeElement element; - - private DartTypeNode superclass; - - private final NodeList members = NodeList.create(this); - private final NodeList typeParameters = NodeList.create(this); - private final NodeList interfaces = NodeList.create(this); - private final NodeList mixins = NodeList.create(this); - - private boolean isInterface; - private DartParameterizedTypeNode defaultClass; - private final Modifiers modifiers; - - // If the Dart class is implemented by a native JS class the nativeName - // points to the JS class. Otherwise it is null. - private final DartStringLiteral nativeName; - - private final int tokenOffset; - private final int tokenLength; - private final int defaultTokenOffset; - private final int implementsOffset; - private final int openBraceOffset; - private final int closeBraceOffset; - - public DartClass(int tokenOffset, int tokenLength, DartIdentifier name, - DartStringLiteral nativeName, DartTypeNode superclass, int implementsOffset, - List interfaces, List mixins, int defaultTokenOffset, - int openBraceOffset, int closeBraceOffset, List members, - List typeParameters, DartParameterizedTypeNode defaultClass, - boolean isInterface, Modifiers modifiers) { - super(name); - this.tokenOffset = tokenOffset; - this.tokenLength = tokenLength; - this.nativeName = becomeParentOf(nativeName); - this.superclass = becomeParentOf(superclass); - this.defaultTokenOffset = defaultTokenOffset; - this.openBraceOffset = openBraceOffset; - this.closeBraceOffset = closeBraceOffset; - this.members.addAll(members); - this.typeParameters.addAll(typeParameters); - this.implementsOffset = implementsOffset; - this.interfaces.addAll(interfaces); - this.mixins.addAll(mixins); - this.defaultClass = becomeParentOf(defaultClass); - this.isInterface = isInterface; - this.modifiers = modifiers; - } - - public boolean isInterface() { - return isInterface; - } - - public Modifiers getModifiers() { - return modifiers; - } - - public boolean isAbstract() { - if (modifiers.isAbstract()) { - return true; - } - for (DartNode node : members) { - if (node instanceof DartMethodDefinition) { - DartMethodDefinition methodDefinition = (DartMethodDefinition) node; - if (methodDefinition.getModifiers().isAbstract()) { - return true; - } - } - if (node instanceof DartFieldDefinition) { - DartFieldDefinition fieldDefinition = (DartFieldDefinition) node; - for (DartField field : fieldDefinition.getFields()) { - if (field.getModifiers().isAbstract()) { - return true; - } - } - } - } - return false; - } - - public int getTokenOffset() { - return tokenOffset; - } - - public int getTokenLength() { - return tokenLength; - } - - public int getDefaultTokenOffset() { - return defaultTokenOffset; - } - - public int getOpenBraceOffset() { - return openBraceOffset; - } - - public int getCloseBraceOffset() { - return closeBraceOffset; - } - - public List getMembers() { - return members; - } - - public List getTypeParameters() { - return typeParameters; - } - - public int getImplementsOffset() { - return implementsOffset; - } - - public List getInterfaces() { - return interfaces; - } - - public NodeList getMixins() { - return mixins; - } - - public String getClassName() { - if (getName() == null) { - return null; - } - return getName().getName(); - } - - public DartTypeNode getSuperclass() { - return superclass; - } - - public DartParameterizedTypeNode getDefaultClass() { - return defaultClass; - } - - public Element getDefaultSymbol() { - if (defaultClass != null) { - return defaultClass.getType().getElement(); - } else { - return null; - } - } - - public Element getSuperSymbol() { - if (superclass != null) { - return superclass.getType().getElement(); - } else { - return null; - } - } - - @Override - public ClassNodeElement getElement() { - return element; - } - - public void setDefaultClass(DartParameterizedTypeNode newName) { - defaultClass = becomeParentOf(newName); - } - - public void setSuperclass(DartTypeNode newName) { - superclass = becomeParentOf(newName); - } - - @Override - public void setElement(Element element) { - this.element = (ClassNodeElement) element; - } - - public DartStringLiteral getNativeName() { - return nativeName; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - super.visitChildren(visitor); - typeParameters.accept(visitor); - safelyVisitChild(superclass, visitor); - interfaces.accept(visitor); - mixins.accept(visitor); - safelyVisitChild(defaultClass, visitor); - members.accept(visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitClass(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartClassMember.java b/compiler/java/com/google/dart/compiler/ast/DartClassMember.java deleted file mode 100644 index 2e5a2bfdcd0d..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartClassMember.java +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.resolver.NodeElement; - -/** - * Base class for class members (fields and methods). - */ -public abstract class DartClassMember extends DartDeclaration { - - private final Modifiers modifiers; - - protected DartClassMember(N name, Modifiers modifiers) { - super(name); - this.modifiers = modifiers; - } - - public Modifiers getModifiers() { - return modifiers; - } - - @Override - public abstract NodeElement getElement(); -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartClassTypeAlias.java b/compiler/java/com/google/dart/compiler/ast/DartClassTypeAlias.java deleted file mode 100644 index a5c35c0dac58..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartClassTypeAlias.java +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.resolver.ClassNodeElement; -import com.google.dart.compiler.resolver.Element; - -import java.util.List; - -/** - * Instances of the class {@code DartClassTypeAlias} represent a class type alias. - */ -public class DartClassTypeAlias extends DartDeclaration { - private final NodeList typeParameters = NodeList.create(this); - private final Modifiers modifiers; - private final DartTypeNode superclass; - private final NodeList mixins = NodeList.create(this); - private final NodeList interfaces = NodeList.create(this); - private ClassNodeElement element; - - public DartClassTypeAlias(DartIdentifier name, List typeParameters, - Modifiers modifiers, DartTypeNode superclass, List mixins, - List interfaces) { - super(name); - this.typeParameters.addAll(typeParameters); - this.modifiers = modifiers; - this.superclass = becomeParentOf(superclass); - this.mixins.addAll(mixins); - this.interfaces.addAll(interfaces); - } - - public List getTypeParameters() { - return typeParameters; - } - - public Modifiers getModifiers() { - return modifiers; - } - - public boolean isAbstract() { - return modifiers.isAbstract(); - } - - public DartTypeNode getSuperclass() { - return superclass; - } - - public NodeList getMixins() { - return mixins; - } - - public List getInterfaces() { - return interfaces; - } - - public String getClassName() { - if (getName() == null) { - return null; - } - return getName().getName(); - } - - @Override - public ClassNodeElement getElement() { - return element; - } - - @Override - public void setElement(Element element) { - this.element = (ClassNodeElement) element; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - super.visitChildren(visitor); - typeParameters.accept(visitor); - superclass.accept(visitor); - mixins.accept(visitor); - interfaces.accept(visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitClassTypeAlias(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartComment.java b/compiler/java/com/google/dart/compiler/ast/DartComment.java deleted file mode 100644 index 6f6e7d0dd8e9..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartComment.java +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.Source; -import com.google.dart.compiler.common.SourceInfo; - -import java.util.List; - -public class DartComment extends DartNode { - private final NodeList refNames = NodeList.create(this); - private final NodeList newNames = NodeList.create(this); - - @SuppressWarnings("unused") - private static final long serialVersionUID = 6066713446767517627L; - - public static enum Style { - END_OF_LINE, BLOCK, DART_DOC; - } - - private Style style; - - public DartComment(Source source, int start, int length, Style style) { - setSourceInfo(new SourceInfo(source, start, length)); - this.style = style; - } - - /** - * Return true if this comment is a block comment. - * - * @return true if this comment is a block comment - */ - public boolean isBlock() { - return style == Style.BLOCK; - } - - /** - * Return true if this comment is a DartDoc comment. - * - * @return true if this comment is a DartDoc comment - */ - public boolean isDartDoc() { - return style == Style.DART_DOC; - } - - /** - * Return true if this comment is an end-of-line comment. - * - * @return true if this comment is an end-of-line comment - */ - public boolean isEndOfLine() { - return style == Style.END_OF_LINE; - } - - /** - * Adds [id] reference. - */ - public void addRefName(DartCommentRefName name) { - refNames.add(name); - } - - public NodeList getRefNames() { - return refNames; - } - - /** - * Adds [new Class] or [new Class.name] reference. - */ - public void addNewName(DartCommentNewName name) { - newNames.add(name); - } - - /** - * @return the [new Class] or [new Class.name] references. - */ - public List getNewNames() { - return newNames; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - refNames.accept(visitor); - newNames.accept(visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitComment(this); - } - -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartCommentNewName.java b/compiler/java/com/google/dart/compiler/ast/DartCommentNewName.java deleted file mode 100644 index e1ef173329fb..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartCommentNewName.java +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.resolver.ClassElement; -import com.google.dart.compiler.resolver.ConstructorElement; -import com.google.dart.compiler.util.StringInterner; - -/** - * [new Class.name] in {@link DartComment}. - */ -public final class DartCommentNewName extends DartNode { - private final String className; - private final int classOffset; - private final String constructorName; - private ClassElement classElement; - private final int constructorOffset; - private ConstructorElement constructorElement; - - public DartCommentNewName(String className, int classOffset, String constructorName, - int constructorOffset) { - assert className != null; - assert constructorName != null; - this.className = StringInterner.intern(className); - this.classOffset = classOffset; - this.constructorName = StringInterner.intern(constructorName); - this.constructorOffset = constructorOffset; - } - - @Override - public String toString() { - if (constructorName.isEmpty()) { - return className; - } - return className + "." + constructorName; - } - - public void setElements(ClassElement classElement, ConstructorElement constructorElement) { - this.classElement = classElement; - this.constructorElement = constructorElement; - } - - public String getClassName() { - return className; - } - - public int getClassOffset() { - return classOffset; - } - - public ClassElement getClassElement() { - return classElement; - } - - public String getConstructorName() { - return constructorName; - } - - public int getConstructorOffset() { - return constructorOffset; - } - - public ConstructorElement getConstructorElement() { - return constructorElement; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitCommentNewName(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartCommentRefName.java b/compiler/java/com/google/dart/compiler/ast/DartCommentRefName.java deleted file mode 100644 index 95a1bbd6fb72..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartCommentRefName.java +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.resolver.Element; -import com.google.dart.compiler.util.StringInterner; - -/** - * [name] in {@link DartComment}. - */ -public final class DartCommentRefName extends DartNode { - private final String name; - private Element element; - - public DartCommentRefName(String name) { - assert name != null; - this.name = StringInterner.intern(name); - } - - @Override - public String toString() { - return name; - } - - @Override - public Element getElement() { - return element; - } - - @Override - public void setElement(Element element) { - this.element = element; - } - - public String getName() { - return name; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitCommentRefName(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartConditional.java b/compiler/java/com/google/dart/compiler/ast/DartConditional.java deleted file mode 100644 index 9e8a3d108155..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartConditional.java +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Represents a Dart conditional expression. - */ -public class DartConditional extends DartExpression { - - private DartExpression condition; - private DartExpression elseExpr; - private DartExpression thenExpr; - - public DartConditional(DartExpression condition, DartExpression thenExpr, - DartExpression elseExpr) { - this.condition = becomeParentOf(condition); - this.thenExpr = becomeParentOf(thenExpr); - this.elseExpr = becomeParentOf(elseExpr); - } - - public DartExpression getCondition() { - return condition; - } - - public DartExpression getElseExpression() { - return elseExpr; - } - - public DartExpression getThenExpression() { - return thenExpr; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(condition, visitor); - safelyVisitChild(thenExpr, visitor); - safelyVisitChild(elseExpr, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitConditional(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartContinueStatement.java b/compiler/java/com/google/dart/compiler/ast/DartContinueStatement.java deleted file mode 100644 index afe0816465fe..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartContinueStatement.java +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Represents a Dart 'continue' statement. - */ -public class DartContinueStatement extends DartGotoStatement { - - public DartContinueStatement(DartIdentifier label) { - super(label); - } - - @Override - public boolean isAbruptCompletingStatement() { - return true; - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitContinueStatement(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartDeclaration.java b/compiler/java/com/google/dart/compiler/ast/DartDeclaration.java deleted file mode 100644 index 35f3013d4e0c..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartDeclaration.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Common supertype for most declarations. A declaration introduces a new name in a scope. Certain - * tools, such as the IDE, need to know the location of this name, but the name should otherwise be - * considered a part of the declaration, not an independent node. So the name is not visited when - * traversing the AST. - */ -public abstract class DartDeclaration extends DartNodeWithMetadata - implements HasObsoleteMetadata { - - private N name; // Not visited. - private DartComment dartDoc; - private DartObsoleteMetadata obsoleteMetadata = DartObsoleteMetadata.EMPTY; - - protected DartDeclaration(N name) { - this.name = becomeParentOf(name); - } - - public final N getName() { - return name; - } - - public final void setName(N newName) { - name = becomeParentOf(newName); - } - - public DartComment getDartDoc() { - return dartDoc; - } - - public void setDartDoc(DartComment dartDoc) { - // dartDoc is still parented by the containing DartUnit. - this.dartDoc = dartDoc; - } - - public DartObsoleteMetadata getObsoleteMetadata() { - return obsoleteMetadata; - } - - public void setObsoleteMetadata(DartObsoleteMetadata metadata) { - this.obsoleteMetadata = metadata; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(dartDoc, visitor); - super.visitChildren(visitor); - safelyVisitChild(name, visitor); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartDefault.java b/compiler/java/com/google/dart/compiler/ast/DartDefault.java deleted file mode 100644 index 2ff46a2c3fca..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartDefault.java +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import java.util.List; - -/** - * Represents a Dart 'default' switch member. - */ -public class DartDefault extends DartSwitchMember { - - public DartDefault(List labels, List statements) { - super(labels, statements); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitDefault(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartDirective.java b/compiler/java/com/google/dart/compiler/ast/DartDirective.java deleted file mode 100644 index 7c039c1d51f4..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartDirective.java +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.resolver.NodeElement; - -/** - * Base class for directives. - */ -public abstract class DartDirective extends DartNodeWithMetadata implements HasObsoleteMetadata { - private DartObsoleteMetadata obsoleteMetadata = DartObsoleteMetadata.EMPTY; - - @Override - public NodeElement getElement() { - throw new UnsupportedOperationException(getClass().getSimpleName()); - } - - public DartObsoleteMetadata getObsoleteMetadata() { - return obsoleteMetadata; - } - - public void setObsoleteMetadata(DartObsoleteMetadata metadata) { - this.obsoleteMetadata = metadata; - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartDoWhileStatement.java b/compiler/java/com/google/dart/compiler/ast/DartDoWhileStatement.java deleted file mode 100644 index a2a42695934c..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartDoWhileStatement.java +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Represents a Dart 'do/while' statement. - */ -public class DartDoWhileStatement extends DartStatement { - - private DartExpression condition; - private DartStatement body; - - public DartDoWhileStatement(DartExpression condition, DartStatement body) { - this.condition = becomeParentOf(condition); - this.body = becomeParentOf(body); - } - - public DartStatement getBody() { - return body; - } - - public DartExpression getCondition() { - return condition; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(condition, visitor); - safelyVisitChild(body, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitDoWhileStatement(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartDoubleLiteral.java b/compiler/java/com/google/dart/compiler/ast/DartDoubleLiteral.java deleted file mode 100644 index f4bbcaca7161..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartDoubleLiteral.java +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Represents a Dart double literal value. - */ -public class DartDoubleLiteral extends DartLiteral { - - public static DartDoubleLiteral get(double x) { - return new DartDoubleLiteral(x); - } - - private final double value; - - private DartDoubleLiteral(double value) { - this.value = value; - } - - public double getValue() { - return value; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitDoubleLiteral(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartEmptyStatement.java b/compiler/java/com/google/dart/compiler/ast/DartEmptyStatement.java deleted file mode 100644 index 0adb02f10515..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartEmptyStatement.java +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Represents an empty Dart statement. - */ -public class DartEmptyStatement extends DartStatement { - - @Override - public void visitChildren(ASTVisitor visitor) { - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitEmptyStatement(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartExportDirective.java b/compiler/java/com/google/dart/compiler/ast/DartExportDirective.java deleted file mode 100644 index e659d56165c7..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartExportDirective.java +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import java.util.List; - -/** - * Implements the export directive. - */ -public class DartExportDirective extends DartDirective { - private DartStringLiteral libraryUri; - - private NodeList combinators = new NodeList(this); - - public DartExportDirective(DartStringLiteral libraryUri, List combinators) { - this.libraryUri = becomeParentOf(libraryUri); - this.combinators.addAll(combinators); - } - - public DartStringLiteral getLibraryUri() { - return libraryUri; - } - - public List getCombinators() { - return combinators; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - super.visitChildren(visitor); - safelyVisitChild(libraryUri, visitor); - combinators.accept(visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitExportDirective(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartExprStmt.java b/compiler/java/com/google/dart/compiler/ast/DartExprStmt.java deleted file mode 100644 index 72fcfc712dd4..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartExprStmt.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Represents a Dart expression-as-statement. - */ -public class DartExprStmt extends DartStatement { - - private DartExpression expr; - - public DartExprStmt(DartExpression expr) { - this.expr = becomeParentOf(expr); - } - - public DartExpression getExpression() { - return expr; - } - - @Override - public boolean isAbruptCompletingStatement() { - return expr instanceof DartThrowExpression; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(expr, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitExprStmt(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartExpression.java b/compiler/java/com/google/dart/compiler/ast/DartExpression.java deleted file mode 100644 index 76c712a421d8..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartExpression.java +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - - -/** - * Abstract base class for Dart expressions. - */ -public abstract class DartExpression extends DartNode { - - private Object invocationParameterId; - - public boolean isAssignable() { - // By default you cannot assign to expressions. - return false; - } - - /** - * @return the ID of parameter, {@link Integer} index of positional, {@link String} name if named. - */ - public Object getInvocationParameterId() { - return invocationParameterId; - } - - /** - * @see #getInvocationParameterId() - */ - public void setInvocationParameterId(Object parameterId) { - this.invocationParameterId = parameterId; - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartField.java b/compiler/java/com/google/dart/compiler/ast/DartField.java deleted file mode 100644 index 654b770fc2b3..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartField.java +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.resolver.Element; -import com.google.dart.compiler.resolver.FieldNodeElement; - -/** - * Represents a single field within a field definition. - */ -public class DartField extends DartClassMember { - - private DartExpression value; - private FieldNodeElement element; - private DartMethodDefinition accessor; - - public DartField(DartIdentifier name, Modifiers modifiers, DartMethodDefinition accessor, - DartExpression value) { - super(name, modifiers); - this.accessor = becomeParentOf(accessor); - this.value = becomeParentOf(value); - } - - public void setValue(DartExpression value) { - this.value = becomeParentOf(value); - } - - public DartExpression getValue() { - return value; - } - - public void setAccessor(DartMethodDefinition accessor) { - this.accessor = becomeParentOf(accessor); - } - - public DartMethodDefinition getAccessor() { - return accessor; - } - - @Override - public FieldNodeElement getElement() { - return element; - } - - @Override - public void setElement(Element element) { - this.element = (FieldNodeElement) element; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - super.visitChildren(visitor); - safelyVisitChild(accessor, visitor); - safelyVisitChild(value, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitField(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartFieldDefinition.java b/compiler/java/com/google/dart/compiler/ast/DartFieldDefinition.java deleted file mode 100644 index 08078d8f18a4..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartFieldDefinition.java +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import java.util.List; - -/** - * Represents a Dart field definition. - */ -public class DartFieldDefinition extends DartNodeWithMetadata { - - private DartTypeNode typeNode; - private final NodeList fields = NodeList.create(this); - - public DartFieldDefinition(DartTypeNode typeNode, List fields) { - this.setTypeNode(typeNode); - this.fields.addAll(fields); - } - - public DartTypeNode getTypeNode() { - return typeNode; - } - - public void setTypeNode(DartTypeNode typeNode) { - this.typeNode = becomeParentOf(typeNode); - } - - public List getFields() { - return fields; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - super.visitChildren(visitor); - safelyVisitChild(typeNode, visitor); - fields.accept(visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitFieldDefinition(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartForInStatement.java b/compiler/java/com/google/dart/compiler/ast/DartForInStatement.java deleted file mode 100644 index 7dfb7699f7a5..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartForInStatement.java +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Represents a Dart 'for (.. in ..)' statement. - */ -public class DartForInStatement extends DartStatement { - - private DartStatement setup; - private DartExpression iterable; - private final int closeParenOffset; - private DartStatement body; - - public DartForInStatement(DartStatement setup, - DartExpression iterable, - int closeParenOffset, - DartStatement body) { - this.setup = becomeParentOf(setup); - this.iterable = becomeParentOf(iterable); - this.closeParenOffset = closeParenOffset; - this.body = becomeParentOf(body); - } - - public int getCloseParenOffset() { - return closeParenOffset; - } - - public DartStatement getBody() { - return body; - } - - public DartExpression getIterable() { - return iterable; - } - - public boolean introducesVariable() { - return setup instanceof DartVariableStatement; - } - - public DartIdentifier getIdentifier() { - assert !introducesVariable(); - return (DartIdentifier) ((DartExprStmt) setup).getExpression(); - } - - public DartVariableStatement getVariableStatement() { - assert introducesVariable(); - return (DartVariableStatement) setup; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(setup, visitor); - safelyVisitChild(iterable, visitor); - safelyVisitChild(body, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitForInStatement(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartForStatement.java b/compiler/java/com/google/dart/compiler/ast/DartForStatement.java deleted file mode 100644 index e9b04be52383..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartForStatement.java +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Represents a Dart 'for' statement. - */ -public class DartForStatement extends DartStatement { - - private DartStatement init; - private DartExpression condition; - private DartExpression increment; - private final int closeParenOffset; - private DartStatement body; - - public DartForStatement(DartStatement init, DartExpression condition, DartExpression increment, - int closeParenOffset, DartStatement body) { - this.init = becomeParentOf(init); - this.condition = becomeParentOf(condition); - this.increment = becomeParentOf(increment); - this.closeParenOffset = closeParenOffset; - this.body = becomeParentOf(body); - } - - public int getCloseParenOffset() { - return closeParenOffset; - } - - public DartStatement getBody() { - return body; - } - - public DartExpression getCondition() { - return condition; - } - - public DartExpression getIncrement() { - return increment; - } - - public DartStatement getInit() { - return init; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(init, visitor); - safelyVisitChild(condition, visitor); - safelyVisitChild(increment, visitor); - safelyVisitChild(body, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitForStatement(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartFunction.java b/compiler/java/com/google/dart/compiler/ast/DartFunction.java deleted file mode 100644 index 628e45eda972..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartFunction.java +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import java.util.List; - -/** - * Represents a Dart function. - */ -public class DartFunction extends DartNode { - - private final NodeList parameters = NodeList.create(this); - private final int parametersOpenParen; - private final int parametersOptionalOpen; - private final int parametersOptionalClose; - private final int parametersCloseParen; - private DartBlock body; - private DartTypeNode returnTypeNode; - - public DartFunction(List parameters, int parametersOpenParen, int parametersOptionalOpen, - int parametersOptionalClose, int parametersCloseParen, DartBlock body, - DartTypeNode returnTypeNode) { - this.parametersOpenParen = parametersOpenParen; - this.parametersOptionalOpen = parametersOptionalOpen; - this.parametersOptionalClose = parametersOptionalClose; - if (parameters != null && !parameters.isEmpty()) { - this.parameters.addAll(parameters); - } - this.parametersCloseParen = parametersCloseParen; - this.body = becomeParentOf(body); - this.returnTypeNode = becomeParentOf(returnTypeNode); - } - - public DartBlock getBody() { - return body; - } - - public List getParameters() { - return parameters; - } - - public int getParametersOptionalOpen() { - return parametersOptionalOpen; - } - - public int getParametersOptionalClose() { - return parametersOptionalClose; - } - - public int getParametersOpenParen() { - return parametersOpenParen; - } - - public int getParametersCloseParen() { - return parametersCloseParen; - } - - public DartTypeNode getReturnTypeNode() { - return returnTypeNode; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - parameters.accept(visitor); - safelyVisitChild(body, visitor); - safelyVisitChild(returnTypeNode, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitFunction(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartFunctionExpression.java b/compiler/java/com/google/dart/compiler/ast/DartFunctionExpression.java deleted file mode 100644 index b8e028bf2869..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartFunctionExpression.java +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.resolver.Element; -import com.google.dart.compiler.resolver.MethodElement; - -/** - * Represents a Dart 'function' expression. - */ -public class DartFunctionExpression extends DartExpression { - - // Not visited. Similar to DartDeclaration, but DartDeclaration shouldn't be - // a statement or an expression. - private DartIdentifier name; - - private final boolean isStmt; - private MethodElement element; - private DartFunction function; - - public DartFunctionExpression(DartIdentifier name, DartFunction function, boolean isStmt) { - this.name = becomeParentOf(name); - this.function = becomeParentOf(function); - this.isStmt = isStmt; - } - - public DartFunction getFunction() { - return function; - } - - public String getFunctionName() { - if (name == null) { - return null; - } - return name.getName(); - } - - public DartIdentifier getName() { - return name; - } - - @Override - public MethodElement getElement() { - return element; - } - - public boolean isStatement() { - return isStmt; - } - - public void setName(DartIdentifier newName) { - name = becomeParentOf(newName); - } - - @Override - public void setElement(Element element) { - this.element = (MethodElement) element; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(name, visitor); - safelyVisitChild(function, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitFunctionExpression(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartFunctionObjectInvocation.java b/compiler/java/com/google/dart/compiler/ast/DartFunctionObjectInvocation.java deleted file mode 100644 index 0ef2aaaefc57..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartFunctionObjectInvocation.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import java.util.List; - -/** - * Function-object invocation AST node. - */ -public class DartFunctionObjectInvocation extends DartInvocation { - - private DartExpression target; - - public DartFunctionObjectInvocation(DartExpression target, List args) { - super(args); - this.target = becomeParentOf(target); - } - - @Override - public DartExpression getTarget() { - return target; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(target, visitor); - visitor.visit(getArguments()); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitFunctionObjectInvocation(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartFunctionTypeAlias.java b/compiler/java/com/google/dart/compiler/ast/DartFunctionTypeAlias.java deleted file mode 100644 index e5b242343222..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartFunctionTypeAlias.java +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.resolver.Element; -import com.google.dart.compiler.resolver.FunctionAliasElement; - -import java.util.List; - -/** - * Named function-type alias AST node. - */ -public class DartFunctionTypeAlias extends DartDeclaration { - - private DartTypeNode returnTypeNode; - private final NodeList parameters = NodeList.create(this); - private final NodeList typeParameters = NodeList.create(this); - private FunctionAliasElement element; - - public DartFunctionTypeAlias(DartIdentifier name, DartTypeNode returnTypeNode, - List parameters, - List typeParameters) { - super(name); - this.returnTypeNode = becomeParentOf(returnTypeNode); - this.parameters.addAll(parameters); - this.typeParameters.addAll(typeParameters); - } - - public List getParameters() { - return parameters; - } - - public DartTypeNode getReturnTypeNode() { - return returnTypeNode; - } - - public List getTypeParameters() { - return typeParameters; - } - - @Override - public FunctionAliasElement getElement() { - return element; - } - - public void setReturnTypeNode(DartTypeNode newReturnType) { - returnTypeNode = becomeParentOf(newReturnType); - } - - @Override - public void setElement(Element element) { - this.element = (FunctionAliasElement) element; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - super.visitChildren(visitor); - safelyVisitChild(returnTypeNode, visitor); - parameters.accept(visitor); - typeParameters.accept(visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitFunctionTypeAlias(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartGotoStatement.java b/compiler/java/com/google/dart/compiler/ast/DartGotoStatement.java deleted file mode 100644 index 212af3eadd05..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartGotoStatement.java +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.resolver.Element; -import com.google.dart.compiler.resolver.LabelElement; - -/** - * Base class of {@link DartBreakStatement} and {@link DartContinueStatement}. - */ -public abstract class DartGotoStatement extends DartStatement { - - private DartIdentifier label; - private LabelElement element; - - public DartGotoStatement(DartIdentifier label) { - this.label = becomeParentOf(label); - } - - public DartIdentifier getLabel() { - return label; - } - - public String getTargetName() { - if (label == null) { - return null; - } - return label.getName(); - } - - public void setLabel(DartIdentifier newLabel) { - label = newLabel; - } - - @Override - public LabelElement getElement() { - return element; - } - - @Override - public void setElement(Element element) { - this.element = (LabelElement) element; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(label, visitor); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartIdentifier.java b/compiler/java/com/google/dart/compiler/ast/DartIdentifier.java deleted file mode 100644 index 46ff36fdc389..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartIdentifier.java +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.resolver.Element; -import com.google.dart.compiler.util.StringInterner; - -/** - * Represents a Dart identifier expression. - */ -public class DartIdentifier extends DartExpression { - - private final String name; - private Element element; - private boolean resolutionAlreadyReportedThatTheMethodCouldNotBeFound; - - public DartIdentifier(String name) { - assert name != null; - this.name = StringInterner.intern(name); - } - - public DartIdentifier(DartIdentifier original) { - this.name = StringInterner.intern(original.name); - } - - @Override - public Element getElement() { - return element; - } - - @Override - // Note: final added for performance reasons. - public final String toString() { - return name; - } - - @Override - public boolean isAssignable() { - return true; - } - - public String getName() { - return name; - } - - @Override - public void setElement(Element element) { - this.element = element; - } - - /** - * Specifies that this name was not found it enclosing {@link Element}. - */ - public void markResolutionAlreadyReportedThatTheMethodCouldNotBeFound() { - this.resolutionAlreadyReportedThatTheMethodCouldNotBeFound = true; - } - - /** - * @return true if we know that this name was not found in its enclosing - * {@link Element}, and error was already reported. - */ - public boolean isResolutionAlreadyReportedThatTheMethodCouldNotBeFound() { - return resolutionAlreadyReportedThatTheMethodCouldNotBeFound; - } - - @Override - public final void visitChildren(ASTVisitor visitor) { - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitIdentifier(this); - } - - public static boolean isPrivateName(String name) { - return name.startsWith("_"); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartIfStatement.java b/compiler/java/com/google/dart/compiler/ast/DartIfStatement.java deleted file mode 100644 index e75c659a92f1..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartIfStatement.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Represents a Dart 'if' statement. - */ -public class DartIfStatement extends DartStatement { - - private DartExpression condition; - private DartStatement thenStmt; - private DartStatement elseStmt; - private final int closeParenOffset; - private final int elseTokenOffset; - - public DartIfStatement(DartExpression condition, int closeParenOffset, DartStatement thenStmt, - int elseTokenOffset, DartStatement elseStmt) { - this.condition = becomeParentOf(condition); - this.closeParenOffset = closeParenOffset; - this.thenStmt = becomeParentOf(thenStmt); - this.elseTokenOffset = elseTokenOffset; - this.elseStmt = becomeParentOf(elseStmt); - } - - public DartExpression getCondition() { - return condition; - } - - public int getCloseParenOffset() { - return closeParenOffset; - } - - public DartStatement getThenStatement() { - return thenStmt; - } - - public int getElseTokenOffset() { - return elseTokenOffset; - } - - public DartStatement getElseStatement() { - return elseStmt; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(condition, visitor); - safelyVisitChild(thenStmt, visitor); - safelyVisitChild(elseStmt, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitIfStatement(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartImportDirective.java b/compiler/java/com/google/dart/compiler/ast/DartImportDirective.java deleted file mode 100644 index 5c79e7852650..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartImportDirective.java +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import java.util.List; - -/** - * Implements the import directive. - */ -public class DartImportDirective extends DartDirective { - private boolean obsoleteFormat; - - private DartStringLiteral libraryUri; - - private DartIdentifier prefix; - - private NodeList combinators = new NodeList(this); - - // TODO(brianwilkerson) Remove this field once the obsolete format is no longer supported. - private boolean exported; - - private DartStringLiteral oldPrefix; - - public DartImportDirective(DartStringLiteral libraryUri, DartIdentifier prefix, List combinators) { - obsoleteFormat = false; - this.libraryUri = becomeParentOf(libraryUri); - this.prefix = becomeParentOf(prefix); - this.combinators.addAll(combinators); - this.exported = false; - } - - public DartImportDirective(DartStringLiteral libraryUri, DartBooleanLiteral exported, List combinators, DartStringLiteral prefix) { - obsoleteFormat = true; - this.libraryUri = becomeParentOf(libraryUri); - this.combinators.addAll(combinators); - this.oldPrefix = becomeParentOf(prefix); - this.exported = exported != null; - } - - public DartStringLiteral getLibraryUri() { - return libraryUri; - } - - public boolean isExported() { - // TODO(brianwilkerson) Remove this method once the obsolete format is no longer supported. - return exported; - } - - public boolean isObsoleteFormat() { - // TODO(brianwilkerson) Remove this method once the obsolete format is no longer supported. - return obsoleteFormat; - } - - public List getCombinators() { - return combinators; - } - - public String getPrefixValue() { - if (prefix != null) { - return prefix.getName(); - } - // TODO(brianwilkerson) Remove this part once the obsolete format is no longer supported. - if (oldPrefix != null) { - return oldPrefix.getValue(); - } - return null; - } - - @Deprecated - public DartStringLiteral getOldPrefix() { - // TODO(brianwilkerson) Remove this method once the obsolete format is no longer supported. - return oldPrefix; - } - - public DartIdentifier getPrefix() { - return prefix; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - super.visitChildren(visitor); - safelyVisitChild(libraryUri, visitor); - safelyVisitChild(prefix, visitor); - combinators.accept(visitor); - safelyVisitChild(oldPrefix, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitImportDirective(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartInitializer.java b/compiler/java/com/google/dart/compiler/ast/DartInitializer.java deleted file mode 100644 index c9d324b0033e..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartInitializer.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Represents a constructor initializer expression. - */ -public class DartInitializer extends DartNode { - - private DartIdentifier name; - private DartExpression value; - - public DartInitializer(DartIdentifier name, DartExpression value) { - this.name = becomeParentOf(name); - this.value = becomeParentOf(value); - } - - public String getInitializerName() { - if (name == null) { - return null; - } - return name.getName(); - } - - public DartIdentifier getName() { - return name; - } - - public DartExpression getValue() { - return value; - } - - /** - * Determines if initializer is an invocation. - * @return true if initializer is either super or redirected constructor invocation. - */ - public boolean isInvocation() { - return name == null; - } - - public void setName(DartIdentifier newName) { - name = becomeParentOf(newName); - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(name, visitor); - safelyVisitChild(value, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitInitializer(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartIntegerLiteral.java b/compiler/java/com/google/dart/compiler/ast/DartIntegerLiteral.java deleted file mode 100644 index ac25f822e347..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartIntegerLiteral.java +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import java.math.BigInteger; - -/** - * Represents a Dart integer literal value. - */ -public class DartIntegerLiteral extends DartLiteral { - - public static DartIntegerLiteral get(BigInteger x) { - return new DartIntegerLiteral(x); - } - - public static DartIntegerLiteral one() { - return new DartIntegerLiteral(BigInteger.ONE); - } - - private final BigInteger value; - - private DartIntegerLiteral(BigInteger value) { - this.value = value; - } - - public BigInteger getValue() { - return value; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitIntegerLiteral(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartInvocation.java b/compiler/java/com/google/dart/compiler/ast/DartInvocation.java deleted file mode 100644 index 1a3a0a2fd4cd..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartInvocation.java +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.resolver.Element; - -import java.util.List; - -/** - * Common superclass for all invocation expressions. In - * a Dart program, there are different kinds of invocation: - *
    - *
  • expression.identifier() is a method invocation, where the - * receiver is 'expression' and the method name 'identifier'. - * This invocation is represented as a DartMethodInvocation. - * Examples: A.foo(), this.foo(), super.foo(), bar().foo(). - *
  • - * - *
  • identifier() is an unqualified invocation. After the resolver has - * resolved 'identifier', the normalizer will transform the node to - * either a DartFunctionObjectInvocation or a DartMethodInvocation. - * This invocation is represented as a DartUnqualifiedInvocation. - * Examples: foo(). - *
  • - * - *
  • expression() is a function object invocation. - * This invocation is represented as a DartFunctionObjectInvocation. - * Examples: bar()(), (A.bar)(), bar[0](), (bar)(). - *
  • - *
- * - */ -public abstract class DartInvocation extends DartExpression { - - private final NodeList arguments = NodeList.create(this); - private Element element; - - public DartInvocation(List arguments) { - if (arguments != null && !arguments.isEmpty()) { - this.arguments.addAll(arguments); - } - } - - public DartExpression getTarget() { - return null; - } - - public List getArguments() { - return arguments; - } - - @Override - public Element getElement() { - return element; - } - - @Override - public void setElement(Element element) { - this.element = element; - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartLabel.java b/compiler/java/com/google/dart/compiler/ast/DartLabel.java deleted file mode 100644 index 1efdbe384d4d..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartLabel.java +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.resolver.Element; -import com.google.dart.compiler.resolver.LabelElement; - -/** - * Represents a Dart statement label. - */ -public class DartLabel extends DartStatement { - - // Not visited. Similar to DartDeclaration, but DartDeclaration shouldn't be - // a statement or an expression. - private DartIdentifier label; - - private LabelElement element; - - private DartStatement statement; - - public DartLabel(DartIdentifier label, DartStatement statement) { - this.label = becomeParentOf(label); - this.statement = becomeParentOf(statement); - } - - public DartIdentifier getLabel() { - return label; - } - - public String getName() { - return label.getName(); - } - - public DartStatement getStatement() { - return statement; - } - - @Override - public LabelElement getElement() { - return element; - } - - public void setLabel(DartIdentifier newLabel) { - label = newLabel; - } - - @Override - public void setElement(Element element) { - this.element = (LabelElement) element; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(label, visitor); - safelyVisitChild(statement, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitLabel(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartLibraryDirective.java b/compiler/java/com/google/dart/compiler/ast/DartLibraryDirective.java deleted file mode 100644 index 3a27b6e2d805..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartLibraryDirective.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Implements the library directive. - */ -public class DartLibraryDirective extends DartDirective { - private DartExpression name; - - public DartLibraryDirective(DartExpression name) { - this.name = becomeParentOf(name); - } - - public DartExpression getName() { - return name; - } - - public String getLibraryName() { - if (name == null) { - return null; - } else if (name instanceof DartStringLiteral) { - // TODO(brianwilkerson) Remove this case once the obsolete format is no longer supported. - return ((DartStringLiteral) name).getValue(); - } else { - return name.toSource(); - } - } - - public boolean isObsoleteFormat() { - // TODO(brianwilkerson) Remove this method once the obsolete format is no longer supported. - return name instanceof DartStringLiteral; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - super.visitChildren(visitor); - safelyVisitChild(name, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitLibraryDirective(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartLiteral.java b/compiler/java/com/google/dart/compiler/ast/DartLiteral.java deleted file mode 100644 index 616fe29236e9..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartLiteral.java +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Abstract base class for Dart literal values. - */ -public abstract class DartLiteral extends DartExpression { -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartMapLiteral.java b/compiler/java/com/google/dart/compiler/ast/DartMapLiteral.java deleted file mode 100644 index 40272084f806..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartMapLiteral.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import java.util.List; - -/** - * Represents a Dart map literal value. - */ -public class DartMapLiteral extends DartTypedLiteral { - - private final NodeList entries = NodeList.create(this); - - public DartMapLiteral(boolean isConst, List typeArguments, - List entries) { - super(isConst, typeArguments); - this.entries.addAll(entries); - } - - public List getEntries() { - return entries; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - super.visitChildren(visitor); - entries.accept(visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitMapLiteral(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartMapLiteralEntry.java b/compiler/java/com/google/dart/compiler/ast/DartMapLiteralEntry.java deleted file mode 100644 index f7ced3804436..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartMapLiteralEntry.java +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Represents an entry in a Dart map literal value. - */ -public class DartMapLiteralEntry extends DartNode { - - private DartExpression key; - private DartExpression value; - - public DartMapLiteralEntry(DartExpression key, DartExpression value) { - this.key = becomeParentOf(key); - this.value = becomeParentOf(value); - } - - public DartExpression getKey() { - return key; - } - - public DartExpression getValue() { - return value; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(key, visitor); - safelyVisitChild(value, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitMapLiteralEntry(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartMethodDefinition.java b/compiler/java/com/google/dart/compiler/ast/DartMethodDefinition.java deleted file mode 100644 index c0092de6c700..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartMethodDefinition.java +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.resolver.Element; -import com.google.dart.compiler.resolver.MethodNodeElement; - -import java.util.Collections; -import java.util.List; - -/** - * Represents a Dart method definition. - */ -public class DartMethodDefinition extends DartClassMember { - - protected DartFunction function; - private MethodNodeElement element; - - public static DartMethodDefinition create(DartExpression name, - DartFunction function, - Modifiers modifiers, - List initializers) { - if (initializers == null) { - return new DartMethodDefinition(name, function, modifiers); - } else { - return new DartMethodWithInitializersDefinition(name, function, modifiers, - initializers); - } - } - - public static DartMethodDefinition create(DartExpression name, - DartFunction function, - Modifiers modifiers, - DartTypeNode redirectedTypeName, - DartIdentifier redirectedConstructorName) { - if (redirectedTypeName == null) { - return new DartMethodDefinition(name, function, modifiers); - } else { - return new DartMethodWithRedirectionDefinition(name, function, modifiers, redirectedTypeName, - redirectedConstructorName); - } - } - - private DartMethodDefinition(DartExpression name, DartFunction function, Modifiers modifiers) { - super(name, modifiers); - this.function = becomeParentOf(function); - } - - public DartFunction getFunction() { - return function; - } - - @Override - public MethodNodeElement getElement() { - return element; - } - - @Override - public void setElement(Element element) { - this.element = (MethodNodeElement) element; - } - - public List getInitializers() { - return Collections.emptyList(); - } - - public DartTypeNode getRedirectedTypeName() { - return null; - } - - public DartIdentifier getRedirectedConstructorName() { - return null; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - super.visitChildren(visitor); - safelyVisitChild(function, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitMethodDefinition(this); - } - - private static class DartMethodWithInitializersDefinition extends DartMethodDefinition { - - private final NodeList initializers = NodeList.create(this); - - DartMethodWithInitializersDefinition(DartExpression name, - DartFunction function, - Modifiers modifiers, - List initializers) { - super(name, function, modifiers); - this.initializers.addAll(initializers); - } - - @Override - public List getInitializers() { - return initializers; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - super.visitChildren(visitor); - initializers.accept(visitor); - } - } - - private static class DartMethodWithRedirectionDefinition extends DartMethodDefinition { - private DartTypeNode redirectedTypeName; - private DartIdentifier redirectedConstructorName; - - DartMethodWithRedirectionDefinition(DartExpression name, - DartFunction function, - Modifiers modifiers, - DartTypeNode redirectedTypeName, - DartIdentifier redirectedConstructorName) { - super(name, function, modifiers); - this.redirectedTypeName = becomeParentOf(redirectedTypeName); - this.redirectedConstructorName = becomeParentOf(redirectedConstructorName); - } - - @Override - public DartTypeNode getRedirectedTypeName() { - return redirectedTypeName; - } - - @Override - public DartIdentifier getRedirectedConstructorName() { - return redirectedConstructorName; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - super.visitChildren(visitor); - safelyVisitChild(redirectedTypeName, visitor); - safelyVisitChild(redirectedConstructorName, visitor); - } - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartMethodInvocation.java b/compiler/java/com/google/dart/compiler/ast/DartMethodInvocation.java deleted file mode 100644 index 4f3b0cdc99de..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartMethodInvocation.java +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import java.util.List; - -/** - * Method invocation AST node. The name of the method must not be null. The receiver is an - * expression, super, or a classname. - *

- * {@link DartMethodInvocation} may be created at the parsing time not only for invocation of actual - * method, but also for invocation of function object in some object. For example: - * - *

- *  class A {
- *    Function run;
- *  }
- *  test(A a) {
- *    a.run();
- *  }
- * 
- */ -public class DartMethodInvocation extends DartInvocation { - - private DartExpression target; - private boolean isCascade; - private DartIdentifier functionName; - - public DartMethodInvocation(DartExpression target, - boolean isCascade, - DartIdentifier functionName, - List args) { - super(args); - functionName.getClass(); // Quick null-check. - this.target = becomeParentOf(target); - this.isCascade = isCascade; - this.functionName = becomeParentOf(functionName); - } - - @Override - public DartExpression getTarget() { - return target; - } - - public DartExpression getRealTarget() { - if (isCascade) { - DartNode ancestor = getParent(); - while (!(ancestor instanceof DartCascadeExpression)) { - if (ancestor == null) { - return target; - } - ancestor = ancestor.getParent(); - } - return ((DartCascadeExpression) ancestor).getTarget(); - } - return target; - } - - public String getFunctionNameString() { - return functionName.getName(); - } - - public boolean isCascade() { - return isCascade; - } - - public DartIdentifier getFunctionName() { - return functionName; - } - - public void setFunctionName(DartIdentifier newName) { - newName.getClass(); // Quick null-check. - functionName = becomeParentOf(newName); - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(target, visitor); - safelyVisitChild(functionName, visitor); - visitor.visit(getArguments()); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitMethodInvocation(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartNamedExpression.java b/compiler/java/com/google/dart/compiler/ast/DartNamedExpression.java deleted file mode 100644 index 434348caa7b7..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartNamedExpression.java +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Represents a labeled expression (used in named method arguments). - */ -public class DartNamedExpression extends DartExpression { - - private DartIdentifier name; - private DartExpression expression; - - public DartNamedExpression(DartIdentifier ident, DartExpression expression) { - this.name = becomeParentOf(ident); - this.expression = becomeParentOf(expression); - } - - public DartIdentifier getName() { - return name; - } - - public DartExpression getExpression() { - return expression; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(name, visitor); - safelyVisitChild(expression, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitNamedExpression(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartNativeBlock.java b/compiler/java/com/google/dart/compiler/ast/DartNativeBlock.java deleted file mode 100644 index 100a956a0e56..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartNativeBlock.java +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - - -/** - * Unofficial Dart native block for built in native invocations. - */ -public class DartNativeBlock extends DartBlock { - - private final DartExpression body; - - public DartNativeBlock(DartExpression body) { - super(null); - this.body = body; - } - - public DartExpression getBody() { - return body; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(body, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitNativeBlock(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartNativeDirective.java b/compiler/java/com/google/dart/compiler/ast/DartNativeDirective.java deleted file mode 100644 index fb4d998397fa..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartNativeDirective.java +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Implements the #native directive. - */ -public class DartNativeDirective extends DartDirective { - private DartStringLiteral nativeUri; - - public DartNativeDirective(DartStringLiteral nativeUri) { - this.nativeUri = becomeParentOf(nativeUri); - } - - public DartStringLiteral getNativeUri() { - return nativeUri; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - super.visitChildren(visitor); - safelyVisitChild(nativeUri, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitNativeDirective(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartNewExpression.java b/compiler/java/com/google/dart/compiler/ast/DartNewExpression.java deleted file mode 100644 index c2b2a2dcca53..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartNewExpression.java +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.resolver.ConstructorNodeElement; -import com.google.dart.compiler.resolver.Element; -import com.google.dart.compiler.type.Type; - -import java.util.List; - -/** - * Represents a Dart 'new' expression. - */ -public class DartNewExpression extends DartInvocation { - - private DartNode constructor; - private ConstructorNodeElement element; - private final boolean isConst; - - public DartNewExpression(DartNode constructor, List args, boolean isConst) { - super(args); - this.constructor = becomeParentOf(constructor); - this.isConst = isConst; - } - - public DartNode getConstructor() { - return constructor; - } - - @Override - public Type getType() { - return constructor.getType(); - } - - public boolean isConst() { - return isConst; - } - - @Override - public ConstructorNodeElement getElement() { - return element; - } - - public void setConstructor(DartExpression newConstructor) { - constructor = becomeParentOf(newConstructor); - } - - @Override - public void setElement(Element element) { - this.element = (ConstructorNodeElement) element; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(constructor, visitor); - visitor.visit(getArguments()); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitNewExpression(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartNode.java b/compiler/java/com/google/dart/compiler/ast/DartNode.java deleted file mode 100644 index 5079d1bc0611..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartNode.java +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.common.AbstractNode; -import com.google.dart.compiler.resolver.Element; -import com.google.dart.compiler.type.Type; -import com.google.dart.compiler.util.DefaultTextOutput; - -import java.util.List; - -/** - * Base class for all Dart AST nodes. - */ -public abstract class DartNode extends AbstractNode { - private DartNode parent; - private Type type; - - public final String toSource() { - DefaultTextOutput out = new DefaultTextOutput(false); - accept(new DartToSourceVisitor(out)); - return out.toString(); - } - - public Element getElement() { - return null; - } - - public void setElement(Element element) { - throw new UnsupportedOperationException(getClass().getSimpleName()); - } - - public void setType(Type type) { - this.type = type; - } - - public Type getType() { - return type; - } - - @Override - public String toString() { - return this.toSource(); - } - - /** - * Returns this node's parent node, or null if this is the - * root node. - *

- * Note that the relationship between an AST node and its parent node - * may change over the lifetime of a node. - * - * @return the parent of this node, or null if none - */ - public final DartNode getParent() { - return parent; - } - - /** - * Return the node at the root of this node's AST structure. Note that this - * method's performance is linear with respect to the depth of the node in - * the AST structure (O(depth)). - * - * @return the node at the root of this node's AST structure - */ - public final DartNode getRoot() { - DartNode root = this; - DartNode parent = getParent(); - while (parent != null) { - root = parent; - parent = root.getParent(); - } - return root; - } - - protected T becomeParentOf(T child) { - if (child != null) { - DartNode node = child; // Java 7 access rules require a temp of a concrete type. - node.setParent(this); - } - return child; - } - - protected > L becomeParentOf(L children) { - if (children != null) { - for (DartNode child : children) { - child.setParent(this); - } - } - return children; - } - - private void setParent(DartNode newParent) { - parent = newParent; - } - - public abstract void visitChildren(ASTVisitor visitor); - - public abstract R accept(ASTVisitor visitor); - - @Override - public DartNode clone() { - // TODO (fabiomfv) - Implement proper cloning when strictly needed. - return this; - } - - public String getObjectIdentifier(){ - return super.toString(); - } - - /** - * If the given child is not null, use the given visitor to visit it. - * - * @param child the child to be visited - * @param visitor the visitor that will be used to visit the child - */ - protected void safelyVisitChild(DartNode child, ASTVisitor visitor) { - if (child != null) { - child.accept(visitor); - } - } - -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartNodeWithMetadata.java b/compiler/java/com/google/dart/compiler/ast/DartNodeWithMetadata.java deleted file mode 100644 index 995a0aeb788c..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartNodeWithMetadata.java +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import java.util.List; - -/** - * The abstract class {@code DartNodeWithMetadata} defines the behavior of nodes that can have - * metadata associated with them. - */ -public abstract class DartNodeWithMetadata extends DartNode { - private NodeList metadata = NodeList.create(this); - - protected DartNodeWithMetadata() { - super(); - } - - public NodeList getMetadata() { - return metadata; - } - - public void setMetadata(List metadata) { - this.metadata.addAll(metadata); - } - - @Override - public void visitChildren(ASTVisitor visitor) { - metadata.accept(visitor); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartNullLiteral.java b/compiler/java/com/google/dart/compiler/ast/DartNullLiteral.java deleted file mode 100644 index 0a6486b0637f..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartNullLiteral.java +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Represents a Dart 'null' literal value. - */ -public class DartNullLiteral extends DartLiteral { - - public static DartNullLiteral get() { - return new DartNullLiteral(); - } - - private DartNullLiteral() { - } - - @Override - public void visitChildren(ASTVisitor visitor) { - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitNullLiteral(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartObsoleteMetadata.java b/compiler/java/com/google/dart/compiler/ast/DartObsoleteMetadata.java deleted file mode 100644 index 45eeed99ced2..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartObsoleteMetadata.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Some metadata information attached to the {@link DartDeclaration}. This has been superseded by - * the metadata defined in the specification and will be removed in the near future. - */ -public class DartObsoleteMetadata { - public static final DartObsoleteMetadata EMPTY = new DartObsoleteMetadata(false, false); - private boolean deprecated; - private boolean override; - - private DartObsoleteMetadata(boolean deprecated, boolean override) { - this.deprecated = deprecated; - this.override = override; - } - - public DartObsoleteMetadata makeDeprecated() { - return new DartObsoleteMetadata(true, override); - } - - public DartObsoleteMetadata makeOverride() { - return new DartObsoleteMetadata(deprecated, true); - } - - public boolean isDeprecated() { - return deprecated; - } - - public boolean isOverride() { - return override; - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartParameter.java b/compiler/java/com/google/dart/compiler/ast/DartParameter.java deleted file mode 100644 index a620a2da3df9..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartParameter.java +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.common.base.Preconditions; -import com.google.dart.compiler.resolver.Element; -import com.google.dart.compiler.resolver.VariableElement; - -import java.util.List; - -/** - * Represents a Dart function parameter. - */ -public class DartParameter extends DartDeclaration { - - private VariableElement element; - private DartTypeNode typeNode; - private final NodeList functionParameters; - private DartExpression defaultExpr; - private final Modifiers modifiers; - - public DartParameter(DartExpression name, - DartTypeNode typeNode, - List functionParameters, - DartExpression defaultExpr, - Modifiers modifiers) { - super(name); - Preconditions.checkArgument(name instanceof DartIdentifier - || name instanceof DartPropertyAccess, "name"); - this.typeNode = becomeParentOf(typeNode); - if (functionParameters != null) { - this.functionParameters = NodeList.create(this); - this.functionParameters.addAll(functionParameters); - } else { - this.functionParameters = null; - } - this.defaultExpr = becomeParentOf(defaultExpr); - this.modifiers = modifiers; - } - - public DartExpression getDefaultExpr() { - return defaultExpr; - } - - public String getParameterName() { - // TODO(fabiomfv) remove instanceof (http://b/issue?id=4729144) - if (getName() instanceof DartIdentifier) { - return ((DartIdentifier)getName()).getName(); - } - return ((DartPropertyAccess)getName()).getPropertyName(); - } - - @Override - public VariableElement getElement() { - return element; - } - - public List getFunctionParameters() { - return functionParameters; - } - - public DartTypeNode getTypeNode() { - return typeNode; - } - - public Modifiers getModifiers() { - return modifiers; - } - - public DartNode getQualifier() { - if (getName() instanceof DartPropertyAccess) { - return ((DartPropertyAccess)getName()).getQualifier(); - } - return null; - } - - @Override - public void setElement(Element element) { - this.element = (VariableElement) element; - } - - public void setTypeNode(DartTypeNode typeNode) { - this.typeNode = becomeParentOf(typeNode); - } - - @Override - public void visitChildren(ASTVisitor visitor) { - super.visitChildren(visitor); - safelyVisitChild(typeNode, visitor); - safelyVisitChild(defaultExpr, visitor); - if (functionParameters != null) { - functionParameters.accept(visitor); - } - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitParameter(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartParameterizedTypeNode.java b/compiler/java/com/google/dart/compiler/ast/DartParameterizedTypeNode.java deleted file mode 100644 index 60ecdf24558b..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartParameterizedTypeNode.java +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import java.util.List; - -public class DartParameterizedTypeNode extends DartExpression { - private DartExpression expression; - private final NodeList typeParameters = NodeList.create(this); - - public DartParameterizedTypeNode(DartExpression expression, List typeParameters) { - setExpression(expression); - this.typeParameters.addAll(typeParameters); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitParameterizedTypeNode(this); - } - - public DartExpression getExpression() { - return expression; - } - - public List getTypeParameters() { - return typeParameters; - } - - public void setExpression(DartExpression expression) { - this.expression = expression; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(expression, visitor); - typeParameters.accept(visitor); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartParenthesizedExpression.java b/compiler/java/com/google/dart/compiler/ast/DartParenthesizedExpression.java deleted file mode 100644 index 2a1a157647aa..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartParenthesizedExpression.java +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Represents a Dart parenthesized expression. - */ -public class DartParenthesizedExpression extends DartExpression { - - private DartExpression expression; - - public DartParenthesizedExpression(DartExpression expression) { - this.expression = becomeParentOf(expression); - } - - public DartExpression getExpression() { - return expression; - } - - public void setExpression(DartExpression newExpression) { - expression = newExpression; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(expression, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitParenthesizedExpression(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartPartOfDirective.java b/compiler/java/com/google/dart/compiler/ast/DartPartOfDirective.java deleted file mode 100644 index 9d55581301a7..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartPartOfDirective.java +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Implements the "part of" directive. - */ -public class DartPartOfDirective extends DartDirective { - private final int ofOffset; - private final DartExpression name; - - public DartPartOfDirective(int ofOffset, DartExpression name) { - this.ofOffset = ofOffset; - this.name = becomeParentOf(name); - } - - public int getOfOffset() { - return ofOffset; - } - - public DartExpression getName() { - return name; - } - - public String getLibraryName() { - return name == null ? null : name.toSource(); - } - - @Override - public void visitChildren(ASTVisitor visitor) { - super.visitChildren(visitor); - safelyVisitChild(name, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitPartOfDirective(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartPlainVisitor.java b/compiler/java/com/google/dart/compiler/ast/DartPlainVisitor.java deleted file mode 100644 index 3d68e630fdfa..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartPlainVisitor.java +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import java.util.List; - -public interface DartPlainVisitor { - - void visit(List nodes); - - R visitArrayAccess(DartArrayAccess node); - - R visitArrayLiteral(DartArrayLiteral node); - - R visitBinaryExpression(DartBinaryExpression node); - - R visitBlock(DartBlock node); - - R visitBooleanLiteral(DartBooleanLiteral node); - - R visitBreakStatement(DartBreakStatement node); - - R visitFunctionObjectInvocation(DartFunctionObjectInvocation node); - - R visitMethodInvocation(DartMethodInvocation node); - - R visitSuperConstructorInvocation(DartSuperConstructorInvocation node); - - R visitCase(DartCase node); - - R visitClass(DartClass node); - - R visitConditional(DartConditional node); - - R visitContinueStatement(DartContinueStatement node); - - R visitDefault(DartDefault node); - - R visitDoubleLiteral(DartDoubleLiteral node); - - R visitDoWhileStatement(DartDoWhileStatement node); - - R visitEmptyStatement(DartEmptyStatement node); - - R visitExprStmt(DartExprStmt node); - - R visitField(DartField node); - - R visitFieldDefinition(DartFieldDefinition node); - - R visitForInStatement(DartForInStatement node); - - R visitForStatement(DartForStatement node); - - R visitFunction(DartFunction node); - - R visitFunctionExpression(DartFunctionExpression node); - - R visitFunctionTypeAlias(DartFunctionTypeAlias node); - - R visitIdentifier(DartIdentifier node); - - R visitIfStatement(DartIfStatement node); - - R visitImportDirective(DartImportDirective node); - - R visitInitializer(DartInitializer node); - - R visitIntegerLiteral(DartIntegerLiteral node); - - R visitLabel(DartLabel node); - - R visitLibraryDirective(DartLibraryDirective node); - - R visitMapLiteral(DartMapLiteral node); - - R visitMapLiteralEntry(DartMapLiteralEntry node); - - R visitMethodDefinition(DartMethodDefinition node); - - R visitNativeDirective(DartNativeDirective node); - - R visitNewExpression(DartNewExpression node); - - R visitNullLiteral(DartNullLiteral node); - - R visitParameter(DartParameter node); - - R visitParameterizedTypeNode(DartParameterizedTypeNode node); - - R visitParenthesizedExpression(DartParenthesizedExpression node); - - R visitPropertyAccess(DartPropertyAccess node); - - R visitTypeNode(DartTypeNode node); - - R visitReturnStatement(DartReturnStatement node); - - R visitSourceDirective(DartSourceDirective node); - - R visitStringLiteral(DartStringLiteral node); - - R visitStringInterpolation(DartStringInterpolation node); - - R visitSuperExpression(DartSuperExpression node); - - R visitSwitchStatement(DartSwitchStatement node); - - R visitSyntheticErrorExpression(DartSyntheticErrorExpression node); - - R visitSyntheticErrorStatement(DartSyntheticErrorStatement node); - - R visitThisExpression(DartThisExpression node); - - R visitThrowExpression(DartThrowExpression node); - - R visitCatchBlock(DartCatchBlock node); - - R visitTryStatement(DartTryStatement node); - - R visitUnaryExpression(DartUnaryExpression node); - - R visitUnit(DartUnit node); - - R visitUnqualifiedInvocation(DartUnqualifiedInvocation node); - - R visitVariable(DartVariable node); - - R visitVariableStatement(DartVariableStatement node); - - R visitWhileStatement(DartWhileStatement node); - - R visitNamedExpression(DartNamedExpression node); - - R visitTypeExpression(DartTypeExpression node); - - R visitTypeParameter(DartTypeParameter node); - - R visitNativeBlock(DartNativeBlock node); - - R visitRedirectConstructorInvocation(DartRedirectConstructorInvocation node); -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartPropertyAccess.java b/compiler/java/com/google/dart/compiler/ast/DartPropertyAccess.java deleted file mode 100644 index 9c1c903f7ff9..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartPropertyAccess.java +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.resolver.Element; - -/** - * Represents a Dart property access expression (a.b). - */ -public class DartPropertyAccess extends DartExpression { - - private DartNode qualifier; - private boolean isCascade; - private DartIdentifier name; - - public DartPropertyAccess(DartNode qualifier, DartIdentifier name) { - this(qualifier, false, name); - } - - public DartPropertyAccess(DartNode qualifier, boolean isCascade, DartIdentifier name) { - this.qualifier = becomeParentOf(qualifier); - this.isCascade = isCascade; - this.name = becomeParentOf(name); - } - - @Override - public boolean isAssignable() { - return true; - } - - public boolean isCascade() { - return isCascade; - } - - public String getPropertyName() { - return name.getName(); - } - - public DartIdentifier getName() { - return name; - } - - public DartNode getQualifier() { - return qualifier; - } - - public DartNode getRealTarget() { - if (isCascade) { - DartNode ancestor = getParent(); - while (!(ancestor instanceof DartCascadeExpression)) { - if (ancestor == null) { - return qualifier; - } - ancestor = ancestor.getParent(); - } - return ((DartCascadeExpression) ancestor).getTarget(); - } - return qualifier; - } - - public void setName(DartIdentifier newName) { - name = becomeParentOf(newName); - } - - @Override - public void setElement(Element element) { - name.setElement(element); - } - - @Override - public Element getElement() { - return name.getElement(); - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(qualifier, visitor); - safelyVisitChild(name, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitPropertyAccess(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartRedirectConstructorInvocation.java b/compiler/java/com/google/dart/compiler/ast/DartRedirectConstructorInvocation.java deleted file mode 100644 index 3697326cd283..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartRedirectConstructorInvocation.java +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.resolver.ConstructorNodeElement; -import com.google.dart.compiler.resolver.Element; - -import java.util.List; - -/** - * Redirected constructor invocation AST node. - */ -public class DartRedirectConstructorInvocation extends DartInvocation { - - private DartIdentifier name; - private ConstructorNodeElement element; - - public DartRedirectConstructorInvocation(DartIdentifier name, List args) { - super(args); - this.name = becomeParentOf(name); - } - - public DartIdentifier getName() { - return name; - } - - @Override - public void setElement(Element element) { - this.element = (ConstructorNodeElement) element; - } - - @Override - public ConstructorNodeElement getElement() { - return element; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(name, visitor); - visitor.visit(getArguments()); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitRedirectConstructorInvocation(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartReturnBlock.java b/compiler/java/com/google/dart/compiler/ast/DartReturnBlock.java deleted file mode 100644 index 2ab69ce540bf..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartReturnBlock.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. -package com.google.dart.compiler.ast; - -import com.google.common.collect.Lists; - -/** - * Represents a Dart block containing a single return statement. - */ -public class DartReturnBlock extends DartBlock { - private final DartExpression value; - - public DartReturnBlock(DartExpression value) { - super(Lists. newArrayList(new DartReturnStatement(value))); - this.value = value; - // Set the source information for the synthesized node. - getStatements().get(0).setSourceInfo(value.getSourceInfo()); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitReturnBlock(this); - } - - public DartExpression getValue() { - return value; - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartReturnStatement.java b/compiler/java/com/google/dart/compiler/ast/DartReturnStatement.java deleted file mode 100644 index 8148fcc964f4..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartReturnStatement.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Represents a Dart 'return' statement. - */ -public class DartReturnStatement extends DartStatement { - - private DartExpression value; - - public DartReturnStatement(DartExpression value) { - this.value = becomeParentOf(value); - } - - public DartExpression getValue() { - return value; - } - - @Override - public boolean isAbruptCompletingStatement() { - return true; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(value, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitReturnStatement(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartSourceDirective.java b/compiler/java/com/google/dart/compiler/ast/DartSourceDirective.java deleted file mode 100644 index 427f0065e0a3..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartSourceDirective.java +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Implements the #source directive. - */ -public class DartSourceDirective extends DartDirective { - private DartStringLiteral sourceUri; - - public DartSourceDirective(DartStringLiteral sourceUri) { - this.sourceUri = becomeParentOf(sourceUri); - } - - public DartStringLiteral getSourceUri() { - return sourceUri; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - super.visitChildren(visitor); - safelyVisitChild(sourceUri, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitSourceDirective(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartStatement.java b/compiler/java/com/google/dart/compiler/ast/DartStatement.java deleted file mode 100644 index e06941532663..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartStatement.java +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Abstract base class for Dart statement objects. - */ -public abstract class DartStatement extends DartNode { - public boolean isAbruptCompletingStatement() { - return false; - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartStringInterpolation.java b/compiler/java/com/google/dart/compiler/ast/DartStringInterpolation.java deleted file mode 100644 index 143f156699cc..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartStringInterpolation.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.common.base.Preconditions; - -import java.util.List; - -/** - * Represents a Dart string interpolation of the form: "1 ${a} 2 ${b} 3". - */ -public class DartStringInterpolation extends DartLiteral { - - /** - * Literal string portions. The interpolation alternates between strings and - * expressions. We preserve the invariant that {@code string.size() = - * expressions.size() + 1}. Empty string constants are used to represent - * adjacent expressions (e.g. $"${a} ${b}${c}" is represented by 4 strings - * ("", " ", "", "") and 3 expressions (#(){a}, #(){b}, #(){c}). - */ - private final NodeList strings = NodeList.create(this);; - - /** Embedded expressions (see {@link strings} for details). */ - private final NodeList expressions = NodeList.create(this); - - public DartStringInterpolation(List strings, - List expressions) { - Preconditions.checkNotNull(strings); - Preconditions.checkNotNull(expressions); - Preconditions.checkArgument(strings.size() == expressions.size() + 1); - this.strings.addAll(strings); - this.expressions.addAll(expressions); - } - - public List getStrings() { - return strings; - } - - public List getExpressions() { - return expressions; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - strings.accept(visitor); - expressions.accept(visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitStringInterpolation(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartStringLiteral.java b/compiler/java/com/google/dart/compiler/ast/DartStringLiteral.java deleted file mode 100644 index 9aacf4e41503..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartStringLiteral.java +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.common.collect.ImmutableList; -import com.google.dart.compiler.resolver.Element; -import com.google.dart.compiler.util.StringInterner; - -import java.util.List; - -/** - * Represents a Dart string literal value. - */ -public class DartStringLiteral extends DartLiteral { - - private Element element; - - public static DartStringLiteral get(String x) { - return new DartStringLiteral(x, null); - } - - public static DartStringLiteral get(String x, List parts) { - return new DartStringLiteral(x, parts); - } - - private final String value; - private final List parts; - - private DartStringLiteral(String value, List parts) { - this.value = StringInterner.intern(value); - this.parts = parts; - } - - public String getValue() { - return value; - } - - /** - * @return the adjacent literals (separated only by whitespace) which consist this - * {@link DartStringLiteral}. - */ - public List getParts() { - if (parts == null) { - return ImmutableList.of(this); - } - return parts; - } - - @Override - public void setElement(Element element) { - this.element = element; - } - - @Override - public Element getElement() { - return element; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitStringLiteral(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartSuperConstructorInvocation.java b/compiler/java/com/google/dart/compiler/ast/DartSuperConstructorInvocation.java deleted file mode 100644 index ddf3a0e870f1..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartSuperConstructorInvocation.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.resolver.ConstructorNodeElement; -import com.google.dart.compiler.resolver.Element; - -import java.util.List; - -/** - * Super constructor invocation AST node. - */ -public class DartSuperConstructorInvocation extends DartInvocation { - - private DartIdentifier name; - private ConstructorNodeElement element; - - public DartSuperConstructorInvocation(DartIdentifier name, List args) { - super(args); - this.name = becomeParentOf(name); - } - - public String getConstructorName() { - if (name == null) { - return null; - } - return name.getName(); - } - - public DartIdentifier getName() { - return name; - } - - public void setName(DartIdentifier newName) { - name = becomeParentOf(newName); - } - - @Override - public void setElement(Element element) { - this.element = (ConstructorNodeElement) element; - } - - @Override - public ConstructorNodeElement getElement() { - return element; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(name, visitor); - visitor.visit(getArguments()); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitSuperConstructorInvocation(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartSuperExpression.java b/compiler/java/com/google/dart/compiler/ast/DartSuperExpression.java deleted file mode 100644 index aa30b0e530e1..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartSuperExpression.java +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.resolver.Element; -import com.google.dart.compiler.resolver.SuperElement; - -/** - * Represents a Dart 'super' expression. - */ -public class DartSuperExpression extends DartExpression { - - private SuperElement element; - - public static DartSuperExpression get() { - return new DartSuperExpression(); - } - - private DartSuperExpression() { - } - - @Override - public void setElement(Element element) { - this.element = (SuperElement) element; - } - - @Override - public SuperElement getElement() { - return element; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitSuperExpression(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartSwitchMember.java b/compiler/java/com/google/dart/compiler/ast/DartSwitchMember.java deleted file mode 100644 index 6bc889dedb5b..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartSwitchMember.java +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import java.util.List; - -/** - * Represents a Dart 'switch' member ('case' or 'default'). - */ -public abstract class DartSwitchMember extends DartNode { - - private final NodeList statements = NodeList.create(this); - private final NodeList labels = NodeList.create(this); - - public DartSwitchMember(List labels, List statements) { - this.labels.addAll(labels); - this.statements.addAll(statements); - } - - public List getStatements() { - return statements; - } - - public List getLabels() { - return labels; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - labels.accept(visitor); - statements.accept(visitor); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartSwitchStatement.java b/compiler/java/com/google/dart/compiler/ast/DartSwitchStatement.java deleted file mode 100644 index 985ec00d4748..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartSwitchStatement.java +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import java.util.List; - -/** - * Represents a Dart 'switch' statement. - */ -public class DartSwitchStatement extends DartStatement { - - private DartExpression expression; - private final NodeList members = NodeList.create(this); - - public DartSwitchStatement(DartExpression expression, List members) { - this.expression = becomeParentOf(expression); - this.members.addAll(members); - } - - public DartExpression getExpression() { - return expression; - } - - public List getMembers() { - return members; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(expression, visitor); - members.accept(visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitSwitchStatement(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartSyntheticErrorExpression.java b/compiler/java/com/google/dart/compiler/ast/DartSyntheticErrorExpression.java deleted file mode 100644 index d2d31b9df079..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartSyntheticErrorExpression.java +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. -package com.google.dart.compiler.ast; - -/** - * An expression node representing an unparseable expression. - */ -public class DartSyntheticErrorExpression extends DartExpression { - - private final String tokenString; - - public DartSyntheticErrorExpression() { - this(null); - } - - public DartSyntheticErrorExpression(String tokenString) { - this.tokenString = tokenString; - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitSyntheticErrorExpression(this); - } - - public String getTokenString() { - return tokenString; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartSyntheticErrorIdentifier.java b/compiler/java/com/google/dart/compiler/ast/DartSyntheticErrorIdentifier.java deleted file mode 100644 index 55f780f7f1f5..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartSyntheticErrorIdentifier.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file -package com.google.dart.compiler.ast; - -/** - * This node is created by the parser when it cannot find a proper identifier token in the input - * stream. The token might not have been consumed, or was a reserved word, so the name of the - * identifier is left blank. - */ -public class DartSyntheticErrorIdentifier extends DartIdentifier { - - private final String tokenString; - - public DartSyntheticErrorIdentifier() { - super(""); - this.tokenString = ""; - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitSyntheticErrorIdentifier(this); - } - - public String getTokenString() { - return tokenString; - } - -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartSyntheticErrorStatement.java b/compiler/java/com/google/dart/compiler/ast/DartSyntheticErrorStatement.java deleted file mode 100644 index 5b7c5c4b131b..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartSyntheticErrorStatement.java +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. -package com.google.dart.compiler.ast; - -/** - * A statement node representing an unparseable statement. - */ -public class DartSyntheticErrorStatement extends DartStatement { - - private final String tokenString; - - public DartSyntheticErrorStatement() { - this(null); - } - - public DartSyntheticErrorStatement(String tokenString) { - this.tokenString = tokenString; - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitSyntheticErrorStatement(this); - } - - public String getTokenString() { - return tokenString; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartThisExpression.java b/compiler/java/com/google/dart/compiler/ast/DartThisExpression.java deleted file mode 100644 index 07097bf39ec7..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartThisExpression.java +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Represents a Dart 'this' expression. - */ -public class DartThisExpression extends DartExpression { - - public static DartThisExpression get() { - return new DartThisExpression(); - } - - private DartThisExpression() { - } - - @Override - public void visitChildren(ASTVisitor visitor) { - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitThisExpression(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartThrowExpression.java b/compiler/java/com/google/dart/compiler/ast/DartThrowExpression.java deleted file mode 100644 index 7904d41a395c..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartThrowExpression.java +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Represents a Dart 'throw' expression. - */ -public class DartThrowExpression extends DartExpression { - - private DartExpression exception; - - public DartThrowExpression(DartExpression exception) { - this.exception = becomeParentOf(exception); - } - - public DartExpression getException() { - return exception; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(exception, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitThrowExpression(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartToSourceVisitor.java b/compiler/java/com/google/dart/compiler/ast/DartToSourceVisitor.java deleted file mode 100644 index d7c259763e4e..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartToSourceVisitor.java +++ /dev/null @@ -1,1050 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.util.TextOutput; - -import java.util.Iterator; -import java.util.List; - -/** - * Used by {@link DartNode} to generate Dart source from an AST subtree. - */ -public class DartToSourceVisitor extends ASTVisitor { - - private final TextOutput out; - - public DartToSourceVisitor(TextOutput out) { - this.out = out; - } - - @Override - public Void visitUnit(DartUnit x) { - p("// unit " + x.getSourceName()); - nl(); - return super.visitUnit(x); - } - - @Override - public Void visitComment(DartComment node) { - return null; - } - - @Override - public Void visitNativeBlock(DartNativeBlock x) { - p("native;"); - return null; - } - - private void accept(DartNode x) { - x.accept(this); - } - - private void acceptList(List xs) { - for (DartNode x : xs) { - x.accept(this); - } - } - - private void pTypeParameters(List typeParameters) { - if (typeParameters != null && !typeParameters.isEmpty()) { - p("<"); - boolean first = true; - for (DartNode node : typeParameters) { - if (!first) { - p(", "); - } - accept(node); - first = false; - } - p(">"); - } - } - - @Override - public Void visitLibraryDirective(DartLibraryDirective node) { - if (node.isObsoleteFormat()) { - p("#library("); - accept(node.getName()); - p(");"); - nl(); - } else { - p("library "); - accept(node.getName()); - p(";"); - nl(); - } - return null; - } - - @SuppressWarnings("deprecation") - @Override - public Void visitImportDirective(DartImportDirective node) { - if (node.isObsoleteFormat()) { - p("#import("); - accept(node.getLibraryUri()); - if (node.getOldPrefix() != null) { - p(", prefix : "); - accept(node.getOldPrefix()); - } - p(");"); - nl(); - } else { - p("import "); - accept(node.getLibraryUri()); - if (node.getPrefix() != null) { - p(" as "); - accept(node.getPrefix()); - } - for (ImportCombinator combinator : node.getCombinators()) { - accept(combinator); - } - if (node.isExported()) { - p(" & export"); - } - p(";"); - nl(); - } - return null; - } - - @Override - public Void visitFunctionTypeAlias(DartFunctionTypeAlias x) { - p("typedef "); - - if (x.getReturnTypeNode() != null) { - accept(x.getReturnTypeNode()); - } - - p(" "); - accept(x.getName()); - pTypeParameters(x.getTypeParameters()); - - p("("); - printSeparatedByComma(x.getParameters()); - p(")"); - - p(";"); - nl(); - nl(); - return null; - } - - @Override - public Void visitClass(DartClass x) { - if (x.isInterface()) { - p("interface "); - } else { - p("class "); - } - accept(x.getName()); - pTypeParameters(x.getTypeParameters()); - - if (x.getSuperclass() != null) { - p(" extends "); - accept(x.getSuperclass()); - } - - List interfaces = x.getInterfaces(); - if (interfaces != null && !interfaces.isEmpty()) { - if (x.isInterface()) { - p(" extends "); - } else { - p(" implements "); - } - boolean first = true; - for (DartTypeNode cls : interfaces) { - if (!first) { - p(", "); - } - accept(cls); - first = false; - } - } - - if (x.getNativeName() != null) { - p(" native "); - accept(x.getNativeName()); - } - - if (x.getDefaultClass() != null) { - p(" default "); - accept(x.getDefaultClass()); - } - - p(" {"); - nl(); - indent(); - - acceptList(x.getMembers()); - - outdent(); - p("}"); - nl(); - nl(); - return null; - } - - @Override - public Void visitTypeNode(DartTypeNode x) { - accept(x.getIdentifier()); - List arguments = x.getTypeArguments(); - if (arguments != null && !arguments.isEmpty()) { - p("<"); - printSeparatedByComma(arguments); - p(">"); - } - return null; - } - - @Override - public Void visitTypeParameter(DartTypeParameter x) { - accept(x.getName()); - DartTypeNode bound = x.getBound(); - if (bound != null) { - p(" extends "); - accept(bound); - } - return null; - } - - @Override - public Void visitFieldDefinition(DartFieldDefinition x) { - Modifiers modifiers = x.getFields().get(0).getModifiers(); - if (modifiers.isAbstractField()) { - pAbstractField(x); - } else { - pFieldModifiers(x); - if (x.getTypeNode() != null) { - accept(x.getTypeNode()); - p(" "); - } else { - if (!modifiers.isFinal()) { - p("var "); - } - } - printSeparatedByComma(x.getFields()); - p(";"); - } - - nl(); - - return null; - } - - @Override - public Void visitField(DartField x) { - accept(x.getName()); - if (x.getValue() != null) { - p(" = "); - accept(x.getValue()); - } - return null; - } - - @Override - public Void visitParameter(DartParameter x) { - if (x.getModifiers().isFinal()) { - p("final "); - } - if (x.getTypeNode() != null) { - accept(x.getTypeNode()); - p(" "); - } - accept(x.getName()); - if (x.getFunctionParameters() != null) { - p("("); - printSeparatedByComma(x.getFunctionParameters()); - p(")"); - } - if (x.getDefaultExpr() != null) { - if (x.getModifiers().isOptional()) { - p(" = "); - } - if (x.getModifiers().isNamed()) { - p(" : "); - } - accept(x.getDefaultExpr()); - } - return null; - } - - @Override - public Void visitMethodDefinition(DartMethodDefinition x) { - nl(); - pMethodModifiers(x); - // return type - DartFunction func = x.getFunction(); - if (func.getReturnTypeNode() != null) { - accept(func.getReturnTypeNode()); - p(" "); - } - // special methods - if (x.getModifiers().isOperator()) { - p("operator "); - } else if (x.getModifiers().isGetter()) { - p("get "); - } else if (x.getModifiers().isSetter()) { - p("set "); - } - // name - pFunctionDeclaration(x.getName(), func, !x.getModifiers().isGetter()); - p(" "); - // initializers - List inits = x.getInitializers(); - if (!inits.isEmpty()) { - p(": "); - for (int i = 0; i < inits.size(); ++i) { - accept(inits.get(i)); - if (i < inits.size() - 1) { - p(", "); - } - } - } - // body - if (x.getFunction().getBody() != null) { - accept(x.getFunction().getBody()); - } else if (x.getRedirectedTypeName() != null) { - p(" = "); - accept(x.getRedirectedTypeName()); - if (x.getRedirectedConstructorName() != null) { - p("."); - accept(x.getRedirectedConstructorName()); - } - p(";"); - nl(); - } else { - p(";"); - nl(); - } - // done - return null; - } - - @Override - public Void visitInitializer(DartInitializer x) { - if (!x.isInvocation()) { - p("this."); - p(x.getInitializerName()); - p(" = "); - } - accept(x.getValue()); - return null; - } - - private void pBlock(DartBlock x, boolean newline) { - p("{"); - nl(); - - indent(); - acceptList(x.getStatements()); - outdent(); - - p("}"); - if (newline) { - nl(); - } - } - - private void pFunctionDeclaration(DartNode name, DartFunction x, boolean includeParameters) { - if (name != null) { - accept(name); - } - if (includeParameters) { - p("("); - pFormalParameters(x.getParameters()); - p(")"); - } - } - - private void pFormalParameters(List params) { - boolean first = true, hasPositional = false, hasNamed = false; - for (DartParameter param : params) { - if (!first) { - p(", "); - } - if (!hasPositional && param.getModifiers().isOptional()) { - hasPositional = true; - p("["); - } - if (!hasNamed && param.getModifiers().isNamed()) { - hasNamed = true; - p("{"); - } - accept(param); - first = false; - } - if (hasPositional) { - p("]"); - } - if (hasNamed) { - p("}"); - } - } - - @Override - public Void visitAssertStatement(DartAssertStatement x) { - p("assert("); - accept(x.getCondition()); - p(");"); - return null; - } - - @Override - public Void visitBlock(DartBlock x) { - pBlock(x, true); - return null; - } - - @Override - public Void visitIfStatement(DartIfStatement x) { - p("if ("); - accept(x.getCondition()); - p(") "); - pIfBlock(x.getThenStatement(), x.getElseStatement() == null); - if (x.getElseStatement() != null) { - p(" else "); - pIfBlock(x.getElseStatement(), true); - } - return null; - } - - @Override - public Void visitSwitchStatement(DartSwitchStatement x) { - p("switch ("); - accept(x.getExpression()); - p(") {"); - nl(); - - indent(); - acceptList(x.getMembers()); - outdent(); - - p("}"); - nl(); - return null; - } - - @Override - public Void visitCase(DartCase x) { - p("case "); - accept(x.getExpr()); - p(":"); - nl(); - indent(); - acceptList(x.getStatements()); - outdent(); - return null; - } - - @Override - public Void visitDefault(DartDefault x) { - p("default:"); - nl(); - indent(); - acceptList(x.getStatements()); - outdent(); - return null; - } - - @Override - public Void visitWhileStatement(DartWhileStatement x) { - p("while ("); - accept(x.getCondition()); - p(") "); - pIfBlock(x.getBody(), true); - return null; - } - - @Override - public Void visitDoWhileStatement(DartDoWhileStatement x) { - p("do "); - pIfBlock(x.getBody(), false); - p(" while ("); - accept(x.getCondition()); - p(");"); - nl(); - return null; - } - - @Override - public Void visitForStatement(DartForStatement x) { - p("for ("); - - // Setup - DartStatement setup = x.getInit(); - if (setup != null) { - if (setup instanceof DartVariableStatement) { - // Special case to avoid an extra semicolon & newline after the var - // statement. - p("var "); - printSeparatedByComma(((DartVariableStatement) setup).getVariables()); - } else { - // Plain old expression. - assert setup instanceof DartExprStmt; - accept(((DartExprStmt) setup).getExpression()); - } - } - p("; "); - - // Condition - if (x.getCondition() != null) { - accept(x.getCondition()); - } - p("; "); - - // Next - if (x.getIncrement() != null) { - accept(x.getIncrement()); - } - p(") "); - - // Body - accept(x.getBody()); - nl(); - return null; - } - - @Override - public Void visitForInStatement(DartForInStatement x) { - p("for ("); - if (x.introducesVariable()) { - DartTypeNode type = x.getVariableStatement().getTypeNode(); - if (type != null) { - accept(type); - p(" "); - } else { - p("var "); - } - printSeparatedByComma(x.getVariableStatement().getVariables()); - } else { - accept(x.getIdentifier()); - } - - p(" in "); - - // iterable - accept(x.getIterable()); - p(") "); - - // Body - accept(x.getBody()); - nl(); - return null; - } - - @Override - public Void visitContinueStatement(DartContinueStatement x) { - p("continue"); - if (x.getTargetName() != null) { - p(" " + x.getTargetName()); - } - p(";"); - nl(); - return null; - } - - @Override - public Void visitBreakStatement(DartBreakStatement x) { - p("break"); - if (x.getTargetName() != null) { - p(" " + x.getTargetName()); - } - p(";"); - nl(); - return null; - } - - @Override - public Void visitReturnStatement(DartReturnStatement x) { - p("return"); - if (x.getValue() != null) { - p(" "); - accept(x.getValue()); - } - p(";"); - nl(); - return null; - } - - @Override - public Void visitTryStatement(DartTryStatement x) { - p("try "); - accept(x.getTryBlock()); - acceptList(x.getCatchBlocks()); - if (x.getFinallyBlock() != null) { - p("finally "); - accept(x.getFinallyBlock()); - } - return null; - } - - @Override - public Void visitCatchBlock(DartCatchBlock x) { - DartParameter catchParameter = x.getException(); - DartTypeNode type = catchParameter.getTypeNode(); - if (type != null) { - p("on "); - accept(type); - p(" "); - } - p("catch ("); - accept(catchParameter.getName()); - if (x.getStackTrace() != null) { - p(", "); - accept(x.getStackTrace()); - } - p(") "); - accept(x.getBlock()); - return null; - } - - @Override - public Void visitThrowExpression(DartThrowExpression x) { - p("throw"); - if (x.getException() != null) { - p(" "); - accept(x.getException()); - } - return null; - } - - @Override - public Void visitVariableStatement(DartVariableStatement x) { - if (x.getTypeNode() != null) { - accept(x.getTypeNode()); - p(" "); - } else { - p("var "); - } - printSeparatedByComma(x.getVariables()); - p(";"); - nl(); - return null; - } - - @Override - public Void visitVariable(DartVariable x) { - accept(x.getName()); - if (x.getValue() != null) { - p(" = "); - accept(x.getValue()); - } - return null; - } - - @Override - public Void visitEmptyStatement(DartEmptyStatement x) { - p(";"); - nl(); - return null; - } - - @Override - public Void visitLabel(DartLabel x) { - p(x.getName()); - p(": "); - accept(x.getStatement()); - return null; - } - - @Override - public Void visitExprStmt(DartExprStmt x) { - accept(x.getExpression()); - p(";"); - nl(); - return null; - } - - @Override - public Void visitBinaryExpression(DartBinaryExpression x) { - accept(x.getArg1()); - p(" "); - p(x.getOperator().getSyntax()); - p(" "); - accept(x.getArg2()); - return null; - } - - @Override - public Void visitConditional(DartConditional x) { - accept(x.getCondition()); - p(" ? "); - accept(x.getThenExpression()); - p(" : "); - accept(x.getElseExpression()); - return null; - } - - @Override - public Void visitUnaryExpression(DartUnaryExpression x) { - if (x.isPrefix()) { - p(x.getOperator().getSyntax()); - } - accept(x.getArg()); - if (!x.isPrefix()) { - p(x.getOperator().getSyntax()); - } - return null; - } - - @Override - public Void visitPropertyAccess(DartPropertyAccess x) { - if (x.getQualifier() != null) { - accept(x.getQualifier()); - } - if (x.isCascade()) { - p(".."); - } else { - p("."); - } - p(x.getPropertyName()); - return null; - } - - @Override - public Void visitCascadeExpression(DartCascadeExpression x) { - accept(x.getTarget()); - acceptList(x.getCascadeSections()); - return null; - } - - @Override - public Void visitArrayAccess(DartArrayAccess x) { - if (x.isCascade()) { - p(".."); - } else { - accept(x.getTarget()); - } - p("["); - accept(x.getKey()); - p("]"); - return null; - } - - private void pArgs(List args) { - p("("); - printSeparatedByComma(args); - p(")"); - } - - @Override - public Void visitUnqualifiedInvocation(DartUnqualifiedInvocation x) { - accept(x.getTarget()); - pArgs(x.getArguments()); - return null; - } - - @Override - public Void visitFunctionObjectInvocation(DartFunctionObjectInvocation x) { - accept(x.getTarget()); - pArgs(x.getArguments()); - return null; - } - - @Override - public Void visitMethodInvocation(DartMethodInvocation x) { - if (x.isCascade()) { - p(".."); - } else { - accept(x.getTarget()); - p("."); - } - accept(x.getFunctionName()); - pArgs(x.getArguments()); - return null; - } - - @Override - public Void visitSyntheticErrorExpression(DartSyntheticErrorExpression node) { - p("[error: " + node.getTokenString() + "]"); - return null; - } - - @Override - public Void visitSyntheticErrorStatement(DartSyntheticErrorStatement node) { - p("[error: " + node.getTokenString() + "]"); - return null; - } - - @Override - public Void visitThisExpression(DartThisExpression x) { - p("this"); - return null; - } - - @Override - public Void visitSuperExpression(DartSuperExpression x) { - p("super"); - return null; - } - - @Override - public Void visitSuperConstructorInvocation(DartSuperConstructorInvocation x) { - p("super"); - if (x.getName() != null) { - p("."); - accept(x.getName()); - } - pArgs(x.getArguments()); - return null; - } - - @Override - public Void visitNewExpression(DartNewExpression x) { - if (x.isConst()) { - p("const "); - } else { - p("new "); - } - accept(x.getConstructor()); - pArgs(x.getArguments()); - return null; - } - - @Override - public Void visitFunctionExpression(DartFunctionExpression x) { - DartFunction func = x.getFunction(); - if (func.getReturnTypeNode() != null) { - accept(func.getReturnTypeNode()); - p(" "); - } - DartIdentifier name = x.getName(); - pFunctionDeclaration(name, x.getFunction(), true); - p(" "); - if (x.getFunction().getBody() != null) { - pBlock(x.getFunction().getBody(), false); - } - return null; - } - - @Override - public Void visitIdentifier(DartIdentifier x) { - p(x.getName()); - return null; - } - - @Override - public Void visitNullLiteral(DartNullLiteral x) { - p("null"); - return null; - } - - @Override - public Void visitRedirectConstructorInvocation(DartRedirectConstructorInvocation x) { - p("this"); - if (x.getName() != null) { - p("."); - accept(x.getName()); - } - pArgs(x.getArguments()); - return null; - } - - @Override - public Void visitStringLiteral(DartStringLiteral x) { - if (x.getValue() == null) { - return null; - } - p("\""); - // 'replaceAll' takes regular expressions as first argument and parses the second argument - // for captured groups. We must escape backslashes twice: once to escape them in the source - // code and once for the regular expression parser. - String escaped = x.getValue().replaceAll("\\\\", "\\\\\\\\"); - escaped = escaped.replaceAll("\"", "\\\\\""); - escaped = escaped.replaceAll("'", "\\\\'"); - escaped = escaped.replaceAll("\\n", "\\\\n"); - // In the replacement string '$' is used to refer to captured groups. We have to escape the - // dollar. - escaped = escaped.replaceAll("\\$", "\\\\\\$"); - p(escaped); - p("\""); - return null; - } - - @Override - public Void visitStringInterpolation(DartStringInterpolation x) { - p("\""); - // do not use the default visitor recursion, instead alternate strings and - // expressions: - Iterator eIter = x.getExpressions().iterator(); - boolean first = true; - for (DartStringLiteral lit : x.getStrings()) { - if (first) { - first = false; - } else { - p("${"); - assert eIter.hasNext() : "DartStringInterpolation invariant broken."; - accept(eIter.next()); - p("}"); - } - p(lit.getValue().replaceAll("\"", "\\\"")); - } - p("\""); - return null; - } - - @Override - public Void visitBooleanLiteral(DartBooleanLiteral x) { - p(Boolean.toString(x.getValue())); - return null; - } - - @Override - public Void visitIntegerLiteral(DartIntegerLiteral x) { - p(x.getValue().toString()); - return null; - } - - @Override - public Void visitDoubleLiteral(DartDoubleLiteral x) { - p(Double.toString(x.getValue())); - return null; - } - - @Override - public Void visitArrayLiteral(DartArrayLiteral x) { - List typeArguments = x.getTypeArguments(); - if (typeArguments != null && typeArguments.size() > 0) { - p("<"); - printSeparatedByComma(typeArguments); - p(">"); - } - p("["); - printSeparatedByComma(x.getExpressions()); - p("]"); - return null; - } - - @Override - public Void visitMapLiteral(DartMapLiteral x) { - List typeArguments = x.getTypeArguments(); - if (typeArguments != null && typeArguments.size() > 0) { - p("<"); - printSeparatedByComma(typeArguments); - p(">"); - } - p("{"); - List entries = x.getEntries(); - for (int i = 0; i < entries.size(); ++i) { - DartMapLiteralEntry entry = entries.get(i); - accept(entry); - if (i < entries.size() - 1) { - p(", "); - } - } - p("}"); - return null; - } - - @Override - public Void visitMapLiteralEntry(DartMapLiteralEntry x) { - // Always quote keys just to be safe. This could be optimized to only quote - // unsafe identifiers. - accept(x.getKey()); - p(" : "); - accept(x.getValue()); - return null; - } - - @Override - public Void visitParameterizedTypeNode(DartParameterizedTypeNode x) { - accept(x.getExpression()); - if (!x.getTypeParameters().isEmpty()) { - p("<"); - printSeparatedByComma(x.getTypeParameters()); - p(">"); - } - return null; - } - - @Override - public Void visitParenthesizedExpression(DartParenthesizedExpression x) { - p("("); - accept(x.getExpression()); - p(")"); - return null; - } - - @Override - public Void visitNamedExpression(DartNamedExpression x) { - accept(x.getName()); - p(":"); - accept(x.getExpression()); - return null; - } - - private void pAbstractField(DartFieldDefinition x) { - accept(x.getFields().get(0).getAccessor()); - } - - private void pIfBlock(DartStatement stmt, boolean newline) { - if (stmt instanceof DartBlock) { - pBlock((DartBlock) stmt, newline); - } else { - p("{"); - nl(); - indent(); - accept(stmt); - outdent(); - p("}"); - if (newline) { - nl(); - } - } - } - - private void printSeparatedByComma(List nodes) { - boolean first = true; - for (DartNode node : nodes) { - if (!first) { - p(", "); - } - accept(node); - first = false; - } - } - - private void pFieldModifiers(DartFieldDefinition field) { - Modifiers modifiers = field.getFields().get(0).getModifiers(); - if (modifiers.isStatic()) { - p("static "); - } - if (modifiers.isFinal()) { - p("final "); - } - } - - private void pMethodModifiers(DartMethodDefinition method) { - if (method.getModifiers().isConstant()) { - p("const "); - } - if (method.getModifiers().isStatic()) { - p("static "); - } - if (method.getModifiers().isAbstract()) { - p("abstract "); - } - if (method.getModifiers().isFactory()) { - p("factory "); - } - } - - private void p(String x) { - out.print(x); - } - - private void nl() { - out.newline(); - } - - private void indent() { - out.indentIn(); - } - - private void outdent() { - out.indentOut(); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartTryStatement.java b/compiler/java/com/google/dart/compiler/ast/DartTryStatement.java deleted file mode 100644 index 14f542f74895..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartTryStatement.java +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import java.util.List; - -/** - * Represents a Dart 'try/catch' statement. - */ -public class DartTryStatement extends DartStatement { - - private DartBlock tryBlock; - private final NodeList catchBlocks = NodeList.create(this); - private DartBlock finallyBlock; - - public DartTryStatement(DartBlock tryBlock, List catchBlocks, - DartBlock finallyBlock) { - this.tryBlock = becomeParentOf(tryBlock); - this.catchBlocks.addAll(catchBlocks); - this.finallyBlock = becomeParentOf(finallyBlock); - } - - public List getCatchBlocks() { - return catchBlocks; - } - - public DartBlock getFinallyBlock() { - return finallyBlock; - } - - public DartBlock getTryBlock() { - return tryBlock; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(tryBlock, visitor); - catchBlocks.accept(visitor); - safelyVisitChild(finallyBlock, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitTryStatement(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartTypeExpression.java b/compiler/java/com/google/dart/compiler/ast/DartTypeExpression.java deleted file mode 100644 index 9d2a22a2d95b..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartTypeExpression.java +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Represents a type expression at the right hand side of an 'is'. - */ -public class DartTypeExpression extends DartExpression { - - private DartTypeNode typeNode; - - public DartTypeExpression(DartTypeNode type) { - this.typeNode = becomeParentOf(type); - } - - public DartTypeNode getTypeNode() { - return typeNode; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(typeNode, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitTypeExpression(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartTypeNode.java b/compiler/java/com/google/dart/compiler/ast/DartTypeNode.java deleted file mode 100644 index 6c3db0db0cc1..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartTypeNode.java +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import java.util.List; - -/** - * Representation of a Dart type name. - */ -public class DartTypeNode extends DartNode { - - private DartNode identifier; - private NodeList typeArguments = NodeList.create(this); - - public DartTypeNode(DartNode identifier) { - this(identifier, null); - } - - public DartTypeNode(DartNode identifier, List typeArguments) { - this.identifier = becomeParentOf(identifier); - this.typeArguments.addAll(typeArguments); - } - - public DartNode getIdentifier() { - return identifier; - } - - public List getTypeArguments() { - return typeArguments; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(identifier, visitor); - typeArguments.accept(visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitTypeNode(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartTypeParameter.java b/compiler/java/com/google/dart/compiler/ast/DartTypeParameter.java deleted file mode 100644 index 38ff64187a57..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartTypeParameter.java +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.resolver.Element; - -/** - * Represents a type parameter in a class or interface declaration. - */ -public class DartTypeParameter extends DartDeclaration { - - private DartTypeNode bound; - - public DartTypeParameter(DartIdentifier name, DartTypeNode bound) { - super(name); - this.bound = becomeParentOf(bound); - } - - public DartTypeNode getBound() { - return bound; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - super.visitChildren(visitor); - safelyVisitChild(bound, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitTypeParameter(this); - } - - @Override - public Element getElement() { - return getName().getElement(); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartTypedLiteral.java b/compiler/java/com/google/dart/compiler/ast/DartTypedLiteral.java deleted file mode 100644 index 28015cd8228c..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartTypedLiteral.java +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.type.InterfaceType; - -import java.util.List; - -public abstract class DartTypedLiteral extends DartExpression { - private final boolean isConst; - private final NodeList typeArguments = NodeList.create(this); - - DartTypedLiteral(boolean isConst, List typeArguments) { - this.isConst = isConst; - this.typeArguments.addAll(typeArguments); - } - - public boolean isConst() { - return isConst; - } - - public List getTypeArguments() { - return typeArguments; - } - - @Override - public InterfaceType getType() { - return (InterfaceType) super.getType(); - } - - @Override - public void visitChildren(ASTVisitor visitor) { - typeArguments.accept(visitor); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartUnaryExpression.java b/compiler/java/com/google/dart/compiler/ast/DartUnaryExpression.java deleted file mode 100644 index 0356f6451137..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartUnaryExpression.java +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.parser.Token; -import com.google.dart.compiler.resolver.Element; -import com.google.dart.compiler.resolver.MethodNodeElement; - -/** - * Represents a Dart unary expression. - */ -public class DartUnaryExpression extends DartExpression { - - private final Token operator; - private final int operatorOffset; - private DartExpression arg; - private final boolean isPrefix; - private MethodNodeElement element; - - public DartUnaryExpression(Token operator, int operatorOffset, DartExpression arg, boolean isPrefix) { - assert operator.isUnaryOperator() || operator == Token.SUB || operator == Token.CONDITIONAL; - this.operator = operator; - this.operatorOffset = operatorOffset; - this.arg = becomeParentOf(arg); - this.isPrefix = isPrefix; - } - - public DartExpression getArg() { - return arg; - } - - public Token getOperator() { - return operator; - } - - public int getOperatorOffset() { - return operatorOffset; - } - - public boolean isPrefix() { - return isPrefix; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(arg, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitUnaryExpression(this); - } - - @Override - public MethodNodeElement getElement() { - return element; - } - - @Override - public void setElement(Element element) { - this.element = (MethodNodeElement) element; - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartUnit.java b/compiler/java/com/google/dart/compiler/ast/DartUnit.java deleted file mode 100644 index 8959f525ef46..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartUnit.java +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.common.collect.Sets; -import com.google.dart.compiler.DartSource; - -import java.util.List; -import java.util.Set; - -/** - * Represents a Dart compilation unit. - */ -public class DartUnit extends DartNode { - - @SuppressWarnings("unused") - private static final long serialVersionUID = -3407637869012712127L; - - private LibraryUnit library; - private final NodeList directives = NodeList.create(this); - private final NodeList topLevelNodes = NodeList.create(this); - private final NodeList comments = NodeList.create(this); - private final DartSource source; - private final boolean isDiet; - - private boolean hasParseErrors; - - public DartUnit(DartSource source, boolean isDiet) { - this.source = source; - this.isDiet = isDiet; - } - - public String getSourceName() { - return source.getName(); - } - - public List getComments() { - return comments; - } - - public void setLibrary(LibraryUnit library) { - this.library = library; - } - - public LibraryUnit getLibrary() { - return library; - } - - public List getTopLevelNodes() { - return topLevelNodes; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - directives.accept(visitor); - topLevelNodes.accept(visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitUnit(this); - } - - /** - * Whether this is an diet unit, meaning it contains no method bodies. - */ - public boolean isDiet() { - return isDiet; - } - - public void setHasParseErrors(boolean hasParseErrors) { - this.hasParseErrors = hasParseErrors; - } - - public boolean hasParseErrors() { - return hasParseErrors; - } - - /** - * Answer the receiver's directives, not null. - */ - public List getDirectives() { - return directives; - } - - /** - * @return the names of top-level declarations. - */ - public Set getTopDeclarationNames() { - Set topLevelSymbols = Sets.newHashSet(); - for (DartNode node : getTopLevelNodes()) { - if (node instanceof DartClass) { - DartIdentifier name = ((DartClass) node).getName(); - topLevelSymbols.add(name.getName()); - } - if (node instanceof DartFunctionTypeAlias) { - DartIdentifier name = ((DartFunctionTypeAlias) node).getName(); - topLevelSymbols.add(name.getName()); - } - if (node instanceof DartMethodDefinition) { - DartExpression name = ((DartMethodDefinition) node).getName(); - if (name instanceof DartIdentifier) { - topLevelSymbols.add(((DartIdentifier) name).getName()); - } - } - if (node instanceof DartFieldDefinition) { - DartFieldDefinition fieldDefinition = (DartFieldDefinition) node; - List fields = fieldDefinition.getFields(); - for (DartField variable : fields) { - topLevelSymbols.add(variable.getName().getName()); - } - } - } - return topLevelSymbols; - } - - /** - * @return the {@link Set} of names of all declarations. - */ - public Set getDeclarationNames() { - final Set symbols = Sets.newHashSet(); - accept(new ASTVisitor() { - @Override - public Void visitFunctionTypeAlias(DartFunctionTypeAlias node) { - symbols.add(node.getName().getName()); - return super.visitFunctionTypeAlias(node); - } - - @Override - public Void visitClass(DartClass node) { - symbols.add(node.getClassName()); - return super.visitClass(node); - } - - @Override - public Void visitTypeParameter(DartTypeParameter node) { - symbols.add(node.getName().getName()); - return super.visitTypeParameter(node); - } - - @Override - public Void visitField(DartField node) { - symbols.add(node.getName().getName()); - return super.visitField(node); - } - - @Override - public Void visitMethodDefinition(DartMethodDefinition node) { - if (node.getName() instanceof DartIdentifier) { - symbols.add(((DartIdentifier) node.getName()).getName()); - } - return super.visitMethodDefinition(node); - } - - @Override - public Void visitParameter(DartParameter node) { - symbols.add(node.getParameterName()); - return super.visitParameter(node); - } - - @Override - public Void visitVariable(DartVariable node) { - symbols.add(node.getVariableName()); - return super.visitVariable(node); - } - }); - return symbols; - } -} \ No newline at end of file diff --git a/compiler/java/com/google/dart/compiler/ast/DartUnqualifiedInvocation.java b/compiler/java/com/google/dart/compiler/ast/DartUnqualifiedInvocation.java deleted file mode 100644 index 54db3f2d46ec..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartUnqualifiedInvocation.java +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.resolver.Element; -import com.google.dart.compiler.resolver.FieldElement; -import com.google.dart.compiler.resolver.MethodElement; -import com.google.dart.compiler.resolver.VariableElement; - -import java.util.List; - -/** - * Unqualified function invocation AST node. - *

- * {@link DartUnqualifiedInvocation} may be invocation of real method, or invocation of function - * object in field, or invocation of function object in variable. So, its {@link Element} may be - * {@link MethodElement}, or {@link FieldElement}, or {@link VariableElement}. - */ -public class DartUnqualifiedInvocation extends DartInvocation { - - private DartIdentifier target; - - public DartUnqualifiedInvocation(DartIdentifier target, List args) { - super(args); - this.target = becomeParentOf(target); - } - - @Override - public DartIdentifier getTarget() { - return target; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(target, visitor); - visitor.visit(getArguments()); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitUnqualifiedInvocation(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartVariable.java b/compiler/java/com/google/dart/compiler/ast/DartVariable.java deleted file mode 100644 index 491dd273c490..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartVariable.java +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.dart.compiler.resolver.Element; -import com.google.dart.compiler.resolver.VariableElement; - -/** - * Represents a single variable declaration in a {@link DartVariableStatement}. - */ -public class DartVariable extends DartDeclaration { - - private VariableElement element; - - private DartExpression value; - - public DartVariable(DartIdentifier name, DartExpression value) { - super(name); - this.value = becomeParentOf(value); - } - - public String getVariableName() { - return getName().getName(); - } - - @Override - public VariableElement getElement() { - return element; - } - - public DartExpression getValue() { - return value; - } - - @Override - public void setElement(Element element) { - this.element = (VariableElement) element; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - super.visitChildren(visitor); - safelyVisitChild(value, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitVariable(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartVariableStatement.java b/compiler/java/com/google/dart/compiler/ast/DartVariableStatement.java deleted file mode 100644 index a0f322c28506..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartVariableStatement.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import java.util.List; - -/** - * Represents a Dart 'var' statement. - */ -public class DartVariableStatement extends DartStatement { - - private final NodeList vars = NodeList.create(this); - private DartTypeNode typeNode; - private final Modifiers modifiers; - - public DartVariableStatement(List vars, DartTypeNode type) { - this(vars, type, Modifiers.NONE); - } - - public DartVariableStatement(List vars, DartTypeNode type, Modifiers modifiers) { - this.vars.addAll(vars); - this.typeNode = becomeParentOf(type); - this.modifiers = modifiers; - } - - public List getVariables() { - return vars; - } - - public DartTypeNode getTypeNode() { - return typeNode; - } - - public Modifiers getModifiers() { - return modifiers; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(typeNode, visitor); - vars.accept(visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitVariableStatement(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/DartWhileStatement.java b/compiler/java/com/google/dart/compiler/ast/DartWhileStatement.java deleted file mode 100644 index aaa975e300f9..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/DartWhileStatement.java +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Represents a Dart 'while' statement. - */ -public class DartWhileStatement extends DartStatement { - - private DartExpression condition; - private final int closeParenOffset; - private DartStatement body; - - public DartWhileStatement(DartExpression condition, int closeParenOffset, DartStatement body) { - this.condition = becomeParentOf(condition); - this.closeParenOffset = closeParenOffset; - this.body = becomeParentOf(body); - } - - public DartStatement getBody() { - return body; - } - - public DartExpression getCondition() { - return condition; - } - - public int getCloseParenOffset() { - return closeParenOffset; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - safelyVisitChild(condition, visitor); - safelyVisitChild(body, visitor); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitWhileStatement(this); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/HasObsoleteMetadata.java b/compiler/java/com/google/dart/compiler/ast/HasObsoleteMetadata.java deleted file mode 100644 index b1648aa22e5c..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/HasObsoleteMetadata.java +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -public interface HasObsoleteMetadata { - - DartObsoleteMetadata getObsoleteMetadata(); - - void setObsoleteMetadata(DartObsoleteMetadata metadata); -} diff --git a/compiler/java/com/google/dart/compiler/ast/ImportCombinator.java b/compiler/java/com/google/dart/compiler/ast/ImportCombinator.java deleted file mode 100644 index 3836e18b2ae4..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/ImportCombinator.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2012, the Dart project authors. - * - * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.eclipse.org/legal/epl-v10.html - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package com.google.dart.compiler.ast; - -/** - * Instances of the class ImportCombinator represent a combinator associated with an - * import directive. - * - *

- * importCombinator ::=
- *     {@link ImportHideCombinator importHideCombinator}
- *   | {@link ImportShowCombinator importShowCombinator}
- * 
- */ -public abstract class ImportCombinator extends DartNode { - /** - * Initialize a newly created import combinator. - */ - public ImportCombinator() { - super(); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/ImportHideCombinator.java b/compiler/java/com/google/dart/compiler/ast/ImportHideCombinator.java deleted file mode 100644 index 5742b59f0c75..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/ImportHideCombinator.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2012, the Dart project authors. - * - * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.eclipse.org/legal/epl-v10.html - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package com.google.dart.compiler.ast; - -import java.util.List; - -/** - * Instances of the class ImportHideCombinator represent a combinator that restricts - * the names being imported to those that are not in a given list. - * - *
- * importHideCombinator ::=
- *     'hide:' {@link DartArrayLiteral listLiteral}
- * 
- */ -public class ImportHideCombinator extends ImportCombinator { - /** - * The list of names from the library that are hidden by this combinator. - */ - private NodeList hiddenNames = new NodeList(this); - - /** - * Initialize a newly created import show combinator. - */ - public ImportHideCombinator() { - super(); - } - - /** - * Initialize a newly created import show combinator. - * - * @param hiddenNames the list of names from the library that are hidden by this combinator - */ - public ImportHideCombinator(List hiddenNames) { - this.hiddenNames.addAll(hiddenNames); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitImportHideCombinator(this); - } - - /** - * Return the list of names from the library that are hidden by this combinator. - * - * @return the list of names from the library that are hidden by this combinator - */ - public NodeList getHiddenNames() { - return hiddenNames; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - if (hiddenNames != null) { - hiddenNames.accept(visitor); - } - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/ImportShowCombinator.java b/compiler/java/com/google/dart/compiler/ast/ImportShowCombinator.java deleted file mode 100644 index cb6920e330b9..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/ImportShowCombinator.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2012, the Dart project authors. - * - * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.eclipse.org/legal/epl-v10.html - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package com.google.dart.compiler.ast; - -import java.util.List; - -/** - * Instances of the class ImportShowCombinator represent a combinator that restricts - * the names being imported to those in a given list. - * - *
- * importShowCombinator ::=
- *     'show:' {@link DartArrayLiteral listLiteral}
- * 
- */ -public class ImportShowCombinator extends ImportCombinator { - /** - * The list of names from the library that are made visible by this combinator. - */ - private NodeList shownNames = new NodeList(this); - - /** - * Initialize a newly created import show combinator. - */ - public ImportShowCombinator() { - super(); - } - - /** - * Initialize a newly created import show combinator. - * - * @param shownNames the list of names from the library that are made visible by this combinator - */ - public ImportShowCombinator(List shownNames) { - this.shownNames.addAll(shownNames); - } - - @Override - public R accept(ASTVisitor visitor) { - return visitor.visitImportShowCombinator(this); - } - - /** - * Return the list of names from the library that are made visible by this combinator. - * - * @return the list of names from the library that are made visible by this combinator - */ - public NodeList getShownNames() { - return shownNames; - } - - @Override - public void visitChildren(ASTVisitor visitor) { - if (shownNames != null) { - shownNames.accept(visitor); - } - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/LibraryExport.java b/compiler/java/com/google/dart/compiler/ast/LibraryExport.java deleted file mode 100644 index 98c2ffd992b9..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/LibraryExport.java +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.common.collect.Sets; -import com.google.dart.compiler.common.SourceInfo; - -import java.util.List; -import java.util.Set; - -/** - * Information about export - {@link LibraryUnit} and show/hide names. - */ -public class LibraryExport { - private final SourceInfo sourceInfo; - private final LibraryUnit library; - private final Set showNames; - private final Set hideNames; - - public LibraryExport(SourceInfo sourceInfo, LibraryUnit library, - List combinators) { - this.sourceInfo = sourceInfo; - this.library = library; - this.showNames = createCombinatorsSet(combinators, true); - this.hideNames = createCombinatorsSet(combinators, false); - } - - public SourceInfo getSourceInfo() { - return sourceInfo; - } - - public LibraryUnit getLibrary() { - return library; - } - - public boolean isVisible(String name) { - if (hideNames.contains(name)) { - return false; - } - if (!showNames.isEmpty()) { - return showNames.contains(name); - } - return true; - } - - private static Set createCombinatorsSet(List combinators, boolean show) { - Set result = Sets.newHashSet(); - for (ImportCombinator combinator : combinators) { - // show - if (show && combinator instanceof ImportShowCombinator) { - ImportShowCombinator showCombinator = (ImportShowCombinator) combinator; - for (DartIdentifier showName : showCombinator.getShownNames()) { - if (showName != null) { - result.add(showName.getName()); - } - } - } - // hide - if (!show && combinator instanceof ImportHideCombinator) { - ImportHideCombinator hideCombinator = (ImportHideCombinator) combinator; - for (DartIdentifier hideName : hideCombinator.getHiddenNames()) { - if (hideName != null) { - result.add(hideName.getName()); - } - } - } - } - return result; - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/LibraryImport.java b/compiler/java/com/google/dart/compiler/ast/LibraryImport.java deleted file mode 100644 index 300093d138a3..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/LibraryImport.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.common.collect.Sets; - -import java.util.List; -import java.util.Set; - -/** - * Information about import - prefix and {@link LibraryUnit}. - */ -public class LibraryImport { - private final LibraryUnit library; - private final String prefix; - private final Set showNames; - private final Set hideNames; - - public LibraryImport(LibraryUnit library, String prefix, List combinators) { - this.library = library; - this.prefix = prefix; - this.showNames = createCombinatorsSet(combinators, true); - this.hideNames = createCombinatorsSet(combinators, false); - } - - public LibraryUnit getLibrary() { - return library; - } - - public String getPrefix() { - return prefix; - } - - public boolean isVisible(String name) { - if (hideNames.contains(name)) { - return false; - } - if (!showNames.isEmpty()) { - return showNames.contains(name); - } - return true; - } - - private static Set createCombinatorsSet(List combinators, boolean show) { - Set result = Sets.newHashSet(); - for (ImportCombinator combinator : combinators) { - // show - if (show && combinator instanceof ImportShowCombinator) { - ImportShowCombinator showCombinator = (ImportShowCombinator) combinator; - for (DartIdentifier showName : showCombinator.getShownNames()) { - if (showName != null) { - result.add(showName.getName()); - } - } - } - // hide - if (!show && combinator instanceof ImportHideCombinator) { - ImportHideCombinator hideCombinator = (ImportHideCombinator) combinator; - for (DartIdentifier hideName : hideCombinator.getHiddenNames()) { - if (hideName != null) { - result.add(hideName.getName()); - } - } - } - } - return result; - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/LibraryNode.java b/compiler/java/com/google/dart/compiler/ast/LibraryNode.java deleted file mode 100644 index c9ce360b7d71..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/LibraryNode.java +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.common.collect.ImmutableList; -import com.google.dart.compiler.common.AbstractNode; -import com.google.dart.compiler.util.apache.StringUtils; - -import java.util.List; - -/** - * An element in a library. - */ -public class LibraryNode extends AbstractNode { - - private final String text; - private final String prefix; - private final List combinators; - private final boolean exported; - - /** - * Construct a new library node instance - * - * @param manifest the library manifest declaration (not null) - * @param text the text comprising the node (not null) - */ - public LibraryNode(String text) { - this.text = StringUtils.trim(text); - this.prefix = null; - this.combinators = ImmutableList.of(); - this.exported = false; - } - - public LibraryNode(DartImportDirective importDirective) { - setSourceInfo(importDirective.getSourceInfo()); - this.text = StringUtils.trim(importDirective.getLibraryUri().getValue()); - this.prefix = importDirective.getPrefixValue(); - this.combinators = importDirective.getCombinators(); - this.exported = importDirective.isExported(); - } - - public LibraryNode(DartExportDirective exportDirective) { - setSourceInfo(exportDirective.getSourceInfo()); - this.text = StringUtils.trim(exportDirective.getLibraryUri().getValue()); - this.prefix = null; - this.combinators = exportDirective.getCombinators(); - this.exported = false; - } - - public String getText() { - return text; - } - - public String getPrefix() { - return prefix; - } - - public List getCombinators() { - return combinators; - } - - public boolean isExported() { - return exported; - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/LibraryUnit.java b/compiler/java/com/google/dart/compiler/ast/LibraryUnit.java deleted file mode 100644 index 9700c84059ee..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/LibraryUnit.java +++ /dev/null @@ -1,314 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.common.base.Objects; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import com.google.dart.compiler.DartCompiler; -import com.google.dart.compiler.DartCompilerContext; -import com.google.dart.compiler.DartSource; -import com.google.dart.compiler.LibraryDeps; -import com.google.dart.compiler.LibrarySource; -import com.google.dart.compiler.resolver.Elements; -import com.google.dart.compiler.resolver.LibraryElement; - -import java.io.IOException; -import java.io.Reader; -import java.io.Writer; -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentSkipListMap; - -/** - * Represents the parsed source from a {@link LibrarySource}. - */ -public class LibraryUnit { - private final LibrarySource libSource; - private final LibraryNode selfSourcePath; - private final List importPaths = Lists.newArrayList(); - private final List exportPaths = Lists.newArrayList(); - private final List sourcePaths = Lists.newArrayList(); - private final List nativePaths = Lists.newArrayList(); - - private final Map units = new ConcurrentSkipListMap(); - private final List imports = Lists.newArrayList(); - private final List exports = Lists.newArrayList(); - - private final LibraryElement element; - - private LibraryDeps deps; - - private LibraryNode entryNode; - private DartUnit selfDartUnit; - - private String name; - - private DartExpression entryPoint; - - private int sourceCount; - - public void setName(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public LibraryUnit(LibrarySource libSource) { - assert libSource != null; - this.libSource = libSource; - element = Elements.libraryElement(this); - - // get the name part of the path, since it needs to be relative - // TODO(jbrosenberg): change this to use lazy init - // Note: We don't want an encoded relative path. - String self = libSource.getUri().getSchemeSpecificPart(); - int lastSlash; - if ((lastSlash = self.lastIndexOf('/')) > -1) { - self = self.substring(lastSlash + 1); - } - selfSourcePath = new LibraryNode(self); - } - - public void addImportPath(LibraryNode path) { - assert path != null; - importPaths.add(path); - } - - public void addExportPath(LibraryNode path) { - assert path != null; - exportPaths.add(path); - } - - public void addSourcePath(LibraryNode path) { - assert path != null; - sourcePaths.add(path); - sourceCount++; - } - - public int getSourceCount() { - return sourceCount; - } - - public void addNativePath(LibraryNode path) { - assert path != null; - nativePaths.add(path); - } - - public void putUnit(DartUnit unit) { - unit.setLibrary(this); - units.put(unit.getSourceName(), unit); - } - - public DartUnit getUnit(String sourceName) { - return units.get(sourceName); - } - - public void addImport(LibraryUnit unit, LibraryNode node) { - if (unit != null) { - if (node != null) { - imports.add(new LibraryImport(unit, node.getPrefix(), node.getCombinators())); - } else { - imports.add(new LibraryImport(unit, null, ImmutableList. of())); - } - } - } - - public void addExport(LibraryUnit unit, LibraryNode node) { - if (unit != null) { - if (node != null) { - exports.add(new LibraryExport(node.getSourceInfo(), unit, node.getCombinators())); - } - } - } - - public Collection getLibrariesWithPrefix(String prefixToMatch) { - List result = Lists.newArrayList(); - for (LibraryImport libraryImport : imports) { - if (Objects.equal(libraryImport.getPrefix(), prefixToMatch)) { - result.add(libraryImport.getLibrary()); - } - } - return result; - } - - public LibraryElement getElement() { - return element; - } - - public Iterable getUnits() { - return units.values(); - } - - public Iterable getImports() { - return imports; - } - - public List getExports() { - return exports; - } - - public Iterable getImportedLibraries() { - LinkedHashSet libraries = Sets.newLinkedHashSet(); - for (LibraryImport libraryImport : imports) { - libraries.add(libraryImport.getLibrary()); - } - return libraries; - } - - public boolean hasImport(LibraryUnit unit) { - for (LibraryImport libraryImport : imports) { - if (libraryImport.getPrefix() == null && Objects.equal(libraryImport.getLibrary(), unit)) { - return true; - } - } - return false; -// return imports.contains(new LibraryImport(unit, null, ImmutableList. of())); - } - - public DartExpression getEntryPoint() { - return entryPoint; - } - - public void setEntryPoint(DartExpression entry) { - this.entryPoint = entry; - } - - public DartUnit getSelfDartUnit() { - return this.selfDartUnit; - } - - public void setSelfDartUnit(DartUnit unit) { - this.selfDartUnit = unit; - // set DartObsoleteMetadata for LibraryElement - if (unit != null) { - List directives = unit.getDirectives(); - if (!directives.isEmpty() && directives.get(0) instanceof DartLibraryDirective) { - DartLibraryDirective libraryDirective = (DartLibraryDirective) directives.get(0); - Elements.setLibraryMetadata(element, libraryDirective.getObsoleteMetadata()); - } - } - } - - /** - * Return a collection of paths to {@link LibrarySource}s upon which this library or application - * depends. - * - * @return the paths (not null, contains no null) - */ - public Iterable getImportPaths() { - return importPaths; - } - - public Iterable getExportPaths() { - return exportPaths; - } - - /** - * Return all prefixes used by this library. - */ - public Set getPrefixes() { - Set result = Sets.newTreeSet(); - for (LibraryImport libraryImport : imports) { - String prefix = libraryImport.getPrefix(); - if (prefix != null) { - result.add(prefix); - } - } - return result; - } - - /** - * Return the path for dart source that corresponds to the same dart file as this library unit. - * This is added to the set of sourcePaths for this unit. - * - * @return the self source path for this unit. - */ - public LibraryNode getSelfSourcePath() { - return selfSourcePath; - } - - /** - * Answer the source associated with this unit - * - * @return the library source (not null) - */ - public LibrarySource getSource() { - return libSource; - } - - /** - * Return a collection of paths to {@link DartSource}s that are included in this library or - * application. - * - * @return the paths (not null, contains no null) - */ - public Iterable getSourcePaths() { - return sourcePaths; - } - - /** - * Returns a collection of paths to native {@link DartSource}s that are included in this library. - * - * @return the paths (not null, contains no null) - */ - public Iterable getNativePaths() { - return nativePaths; - } - - /** - * Return the declared entry method, if any - * - * @return the entry method or null if not defined - */ - public LibraryNode getEntryNode() { - return entryNode; - } - - /** - * Set the declared entry method. - * - * @param libraryNode the entry method or null if none - */ - public void setEntryNode(LibraryNode libraryNode) { - this.entryNode = libraryNode; - } - - /** - * Gets the dependencies associated with this library. If no dependencies artifact exists, or the - * file is invalid, it will return an empty deps object. - */ - public LibraryDeps getDeps(DartCompilerContext context) throws IOException { - if (deps != null) { - return deps; - } - - Reader reader = context.getArtifactReader(libSource, "", DartCompiler.EXTENSION_DEPS); - if (reader != null) { - deps = LibraryDeps.fromReader(reader); - reader.close(); - } - - if (deps == null) { - deps = new LibraryDeps(); - } - return deps; - } - - /** - * Writes this library's associated dependencies. - */ - public void writeDeps(DartCompilerContext context) throws IOException { - Writer writer = context.getArtifactWriter(libSource, "", DartCompiler.EXTENSION_DEPS); - deps.write(writer); - writer.close(); - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/Modifiers.java b/compiler/java/com/google/dart/compiler/ast/Modifiers.java deleted file mode 100644 index 4d9dea91774c..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/Modifiers.java +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -/** - * Methods for working with modifier bits on various nodes. - */ -public class Modifiers { - - public static final Modifiers NONE = new Modifiers(); - - // Sorting this list would be confusing when adding new modifiers, - // as each one depends on the previously declared one. - // TODO(ngeoffray): Make this an enum. - private static final int FLAG_STATIC = 1; - private static final int FLAG_CONSTANT = FLAG_STATIC << 1; - private static final int FLAG_FACTORY = FLAG_CONSTANT << 1; - private static final int FLAG_ABSTRACT = FLAG_FACTORY << 1; - private static final int FLAG_GETTER = FLAG_ABSTRACT << 1; - private static final int FLAG_SETTER = FLAG_GETTER << 1; - private static final int FLAG_OPERATOR = FLAG_SETTER << 1; - private static final int FLAG_NATIVE = FLAG_OPERATOR << 1; - private static final int FLAG_INLINABLE = FLAG_NATIVE << 1; - private static final int FLAG_ABSTRACTFIELD = FLAG_INLINABLE << 1; - private static final int FLAG_REDIRECTEDCONSTRUCTOR = FLAG_ABSTRACTFIELD << 1; - private static final int FLAG_FINAL = FLAG_REDIRECTEDCONSTRUCTOR << 1; - private static final int FLAG_OPTIONAL = FLAG_FINAL << 1; - private static final int FLAG_NAMED = FLAG_OPTIONAL << 1; - private static final int FLAG_INITIALIZED = FLAG_NAMED << 1; - private static final int FLAG_EXTERNAL = FLAG_INITIALIZED << 1; - - private final int value; - - public boolean isStatic() { return is(FLAG_STATIC); } - public boolean isConstant() { return is(FLAG_CONSTANT); } - public boolean isFactory() { return is(FLAG_FACTORY); } - public boolean isAbstract() { return is(FLAG_ABSTRACT); } - public boolean isGetter() { return is(FLAG_GETTER); } - public boolean isSetter() { return is(FLAG_SETTER); } - public boolean isOperator() { return is(FLAG_OPERATOR); } - public boolean isNative() { return is(FLAG_NATIVE); } - public boolean isInlinable() { return is(FLAG_INLINABLE); } - public boolean isAbstractField() { return is(FLAG_ABSTRACTFIELD); } - public boolean isRedirectedConstructor() { return is(FLAG_REDIRECTEDCONSTRUCTOR); } - public boolean isFinal() { return is(FLAG_FINAL); } - public boolean isOptional() { return is(FLAG_OPTIONAL); } - public boolean isNamed() { return is(FLAG_NAMED); } - public boolean isInitialized() { return is(FLAG_INITIALIZED); } - public boolean isExternal() { return is(FLAG_EXTERNAL); } - - public Modifiers makeStatic() { return make(FLAG_STATIC); } - public Modifiers makeConstant() { return make(FLAG_CONSTANT); } - public Modifiers makeFactory() { return make(FLAG_FACTORY); } - public Modifiers makeAbstract() { return make(FLAG_ABSTRACT); } - public Modifiers makeGetter() { return make(FLAG_GETTER); } - public Modifiers makeSetter() { return make(FLAG_SETTER); } - public Modifiers makeOperator() { return make(FLAG_OPERATOR); } - public Modifiers makeNative() { return make(FLAG_NATIVE); } - public Modifiers makeInlinable() { return make(FLAG_INLINABLE); } - public Modifiers makeAbstractField() { return make(FLAG_ABSTRACTFIELD); } - public Modifiers makeRedirectedConstructor() { return make(FLAG_REDIRECTEDCONSTRUCTOR); } - public Modifiers makeFinal() { return make(FLAG_FINAL); } - public Modifiers makeOptional() { return make(FLAG_OPTIONAL); } - public Modifiers makeNamed() { return make(FLAG_NAMED); } - public Modifiers makeInitialized() { return make(FLAG_INITIALIZED); } - public Modifiers makeExternal() { return make(FLAG_EXTERNAL); } - - public Modifiers removeStatic() { return remove(FLAG_STATIC); } - public Modifiers removeConstant() { return remove(FLAG_CONSTANT); } - public Modifiers removeFactory() { return remove(FLAG_FACTORY); } - public Modifiers removeAbstract() { return remove(FLAG_ABSTRACT); } - public Modifiers removeGetter() { return remove(FLAG_GETTER); } - public Modifiers removeSetter() { return remove(FLAG_SETTER); } - public Modifiers removeOperator() { return remove(FLAG_OPERATOR); } - public Modifiers removeNative() { return remove(FLAG_NATIVE); } - public Modifiers removeInlinable() { return remove(FLAG_INLINABLE); } - public Modifiers removeAbstractField() { return remove(FLAG_ABSTRACTFIELD); } - public Modifiers removeRedirectedConstructor() { return remove(FLAG_REDIRECTEDCONSTRUCTOR); } - public Modifiers removeFinal() { return remove(FLAG_FINAL); } - public Modifiers removeOptional() { return remove(FLAG_OPTIONAL); } - public Modifiers removeNamed() { return remove(FLAG_NAMED); } - public Modifiers removeIniitalized() { return remove(FLAG_INITIALIZED); } - public Modifiers removeExternal() { return remove(FLAG_EXTERNAL); } - - public boolean is(int flag) { - return (value & flag) != 0; - } - - public boolean is(Modifiers modifier) { - return is(modifier.value); - } - - public Modifiers make(int flag) { - return new Modifiers(value | flag); - } - - public Modifiers remove(int flag) { - return new Modifiers(value & ~flag); - } - - private Modifiers() { - this.value = 0; - } - - private Modifiers(int value) { - this.value = value; - } -} diff --git a/compiler/java/com/google/dart/compiler/ast/NodeList.java b/compiler/java/com/google/dart/compiler/ast/NodeList.java deleted file mode 100644 index 8eda6ba9a819..000000000000 --- a/compiler/java/com/google/dart/compiler/ast/NodeList.java +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.ast; - -import com.google.common.collect.Lists; - -import java.util.AbstractList; -import java.util.Collection; -import java.util.List; - -/** - * Instances of the class NodeList represent a list of AST nodes that have a common - * parent. - */ -public class NodeList extends AbstractList { - /** - * @return the new instance of {@link NodeList} with correct type argument. - */ - public static NodeList create(DartNode owner) { - return new NodeList(owner); - } - - /** - * The underlying list in which the nodes of this list are stored. - */ - private List elements = null; - - /** - * The node that is the parent of each of the elements in the list. - */ - private final DartNode owner; - - /** - * Initialize a newly created list of nodes to be empty. - * - * @param owner the node that is the parent of each of the elements in the list - */ - public NodeList(DartNode owner) { - this.owner = owner; - } - - /** - * Use the given visitor to visit each of the nodes in this list. - * - * @param visitor the visitor to be used to visit the elements of this list - */ - public void accept(ASTVisitor visitor) { - if (elements != null) { - for (int i = 0, size = elements.size(); i < size; i++) { - elements.get(i).accept(visitor); - } - } - } - - @Override - public void add(int index, E element) { - if (elements == null) { - elements = Lists.newArrayListWithCapacity(2); - } - elements.add(element); - owner.becomeParentOf(element); - } - - @Override - public boolean addAll(Collection c) { - if (c != null) { - return super.addAll(c); - } - return false; - } - - @Override - public E get(int index) { - if (elements == null) { - throw new IndexOutOfBoundsException(Integer.toString(index)); - } - return elements.get(index); - } - - @Override - public E set(int index, E element) { - if (elements == null) { - elements = Lists.newArrayListWithCapacity(index + 1); - } - E result = elements.set(index, element); - owner.becomeParentOf(element); - return result; - } - - @Override - public int size() { - if (elements == null) { - return 0; - } - return elements.size(); - } -} diff --git a/compiler/java/com/google/dart/compiler/common/AbstractNode.java b/compiler/java/com/google/dart/compiler/common/AbstractNode.java deleted file mode 100644 index 43ebdaf6a1df..000000000000 --- a/compiler/java/com/google/dart/compiler/common/AbstractNode.java +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.common; - -/** - * Abstract base class for nodes that carry source information. - */ -public class AbstractNode implements HasSourceInfo, HasSourceInfoSetter { - - private SourceInfo sourceInfo = SourceInfo.UNKNOWN; - - @Override - public final SourceInfo getSourceInfo() { - return sourceInfo; - } - - @Override - public final void setSourceInfo(SourceInfo sourceInfo) { - this.sourceInfo = sourceInfo; - } -} diff --git a/compiler/java/com/google/dart/compiler/common/HasSourceInfo.java b/compiler/java/com/google/dart/compiler/common/HasSourceInfo.java deleted file mode 100644 index a09552c7e05b..000000000000 --- a/compiler/java/com/google/dart/compiler/common/HasSourceInfo.java +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.common; - -/** - * Abstract view of a class that has source info. - */ -public interface HasSourceInfo { - - /** - * @return the {@link SourceInfo} associated with this object. May be {@link SourceInfo#UNKNOWN} - * but not null. - */ - SourceInfo getSourceInfo(); -} diff --git a/compiler/java/com/google/dart/compiler/common/HasSourceInfoSetter.java b/compiler/java/com/google/dart/compiler/common/HasSourceInfoSetter.java deleted file mode 100644 index 6d419429aa7e..000000000000 --- a/compiler/java/com/google/dart/compiler/common/HasSourceInfoSetter.java +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.common; - -/** - * Object for which you can set new {@link SourceInfo}. - */ -public interface HasSourceInfoSetter { - - /** - * Set the {@link SourceInfo} associated with this object. May only be called only once. - */ - void setSourceInfo(SourceInfo sourceInfo); -} diff --git a/compiler/java/com/google/dart/compiler/common/SourceInfo.java b/compiler/java/com/google/dart/compiler/common/SourceInfo.java deleted file mode 100644 index e3c74283c279..000000000000 --- a/compiler/java/com/google/dart/compiler/common/SourceInfo.java +++ /dev/null @@ -1,184 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.common; - -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.common.collect.MapMaker; -import com.google.dart.compiler.Source; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.Serializable; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -/** - * Contains {@link Source} and location information for AST nodes. - *

- * Each node in the subtree (other than the contrived nodes) carries source range(s) information - * relating back to positions in the given source (the given source itself is not remembered with - * the AST). The source range usually begins at the first character of the first token corresponding - * to the node; leading whitespace and comments are not included. The source range usually - * extends through the last character of the last token corresponding to the node; trailing - * whitespace and comments are not included. There are a handful of exceptions (including the - * various body declarations). Source ranges nest properly: the source range for a child is always - * within the source range of its parent, and the source ranges of sibling nodes never overlap. - */ -public final class SourceInfo implements Serializable { - private static final long serialVersionUID = 1L; - - /** - * The unknown {@link SourceInfo}. - */ - public static final SourceInfo UNKNOWN = new SourceInfo(null, 0, 0); - - private static final Map lines = new MapMaker().weakKeys().makeMap(); - - private final Source source; - private final int offset; - private final int length; - - public SourceInfo(Source source, int offset, int length) { - Preconditions.checkArgument(offset != -1 && length >= 0 || offset == -1 && length == 0); - this.source = source; - this.offset = offset; - this.length = length; - } - - /** - * @return the {@link LinesInfo}, may be empty if some {@link Exception} happens, but not - * null. - */ - private static LinesInfo getLinesInfo(Source source) { - LinesInfo linesInfo = lines.get(source); - if (linesInfo == null) { - linesInfo = createLinesInfo(source); - lines.put(source, linesInfo); - } - return linesInfo; - } - - /** - * @return the new {@link LinesInfo}, may be empty if some {@link Exception} happens, but not - * null. - */ - private static LinesInfo createLinesInfo(Source source) { - BufferedReader reader = null; - try { - reader = new BufferedReader(source.getSourceReader()); - int offset = 0; - List lineOffsets = Lists.newArrayList(0); - while (true) { - int charValue = reader.read(); - if (charValue == -1) { - break; - } - offset++; - char c = (char) charValue; - if (c == '\n') { - lineOffsets.add(offset); - } - } - return new LinesInfo(lineOffsets); - } catch (Throwable e) { - return new LinesInfo(ImmutableList.of(0)); - } finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException e) { - // Ignored - } - } - } - } - - /** - * @return the {@link Source}. - */ - public Source getSource() { - return source; - } - - /** - * @return the 0-based character index in the {@link Source}, may -1 if no source - * information is recorded. - */ - public int getOffset() { - return offset; - } - - /** - * @return a (possibly 0) length of this node in the {@link Source}, may 0 if no - * source position information is recorded. - */ - public int getLength() { - return length; - } - - /** - * @return the 0-based character index in the {@link Source}, result of {@link #getOffset()} plus - * {@link #getLength()}. - */ - public int getEnd() { - return offset + length; - } - - /** - * @return a 1-based line number in the {@link Source} indicating where the source fragment - * begins. May be 0 if line not found. - */ - public int getLine() { - if (source == null) { - return 0; - } - return 1 + getLinesInfo(source).getLineOfOffset(offset); - } - - /** - * @return a 1-based column number in the {@link Source} indicating where the source fragment - * begins. May be 0 if column not found. - */ - public int getColumn() { - if (source == null) { - return 0; - } - return 1 + getLinesInfo(source).getColumnOfOffset(offset); - } - - /** - * Container for information about lines in some {@link Source}. - */ - private static class LinesInfo { - private final List lineOffsets; - - public LinesInfo(List lineOffsets) { - this.lineOffsets = lineOffsets; - } - - int getLineOffset(int line) { - if (line < 0) { - return 0; - } - return lineOffsets.get(line); - } - - int getLineOfOffset(int offset) { - int index = Collections.binarySearch(lineOffsets, offset); - if (index >= 0) { - return index; - } - return -(2 + index); - } - - int getColumnOfOffset(int offset) { - int line = getLineOfOffset(offset); - return offset - getLineOffset(line); - } - } -} diff --git a/compiler/java/com/google/dart/compiler/metrics/CompilerMetrics.java b/compiler/java/com/google/dart/compiler/metrics/CompilerMetrics.java deleted file mode 100644 index 3f7d9380f6c6..000000000000 --- a/compiler/java/com/google/dart/compiler/metrics/CompilerMetrics.java +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.metrics; - -import java.io.PrintStream; -import java.lang.management.ManagementFactory; -import java.lang.management.ThreadMXBean; -import java.util.concurrent.atomic.AtomicLong; - -/** - * Collection of compiler metrics. - */ -public final class CompilerMetrics { - // TODO: Consider refactoring this class so each subsystem has it own metrics class. - - public static long getCPUTime() { - return System.currentTimeMillis() * 1000000; - } - /** - * Returns the current thread's CPU time or -1 if this is not supported. - */ - public static long getThreadTime() { - ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); - if (threadMXBean.isThreadCpuTimeSupported()) { - return threadMXBean.getCurrentThreadCpuTime(); - } - - return -1; - } - - private static double nanoToMillis(long nanoTime) { - return nanoTime / 1000000.0d; - } - private AtomicLong charactersParsed = new AtomicLong(); - private AtomicLong charactersParsedExcludingComments = new AtomicLong(); - private long compileLibrariesTime = 0L; - private long compileLibrariesTimeStart = 0L; - private AtomicLong linesParsed = new AtomicLong(); - private AtomicLong linesParsedExcludingComments = new AtomicLong(); - - private long milliEndTime = -1; - private final long milliStartTime; - - private long nanoParseWallTime = 0; - private AtomicLong nanoTotalParseTime = new AtomicLong(); - private long nativeLibCharCount; - - // Parser metrics - private AtomicLong unitsParsed = new AtomicLong(); - - private long updateAndResolveTime = 0L; - - // Timing metrics for complete stages - private long updateAndResolveTimeStart = 0L; - - public CompilerMetrics() { - this.milliStartTime = System.currentTimeMillis(); - } - - /** - * Accumulate more parsing time. TODO: Once the parser gets cleaned up we should be able to - * integrate this with unit parsed. - */ - public void addParseTimeNano(long nanoTotalParseTime) { - this.nanoTotalParseTime.addAndGet(nanoTotalParseTime); - } - - public void addParseWallTimeNano( long nanoWallParseTime) { - this.nanoParseWallTime = nanoWallParseTime; - } - - public void done() { - if (milliEndTime == -1) { - milliEndTime = System.currentTimeMillis(); - } - } - - public void endCompileLibrariesTime() { - compileLibrariesTime = System.currentTimeMillis() - compileLibrariesTimeStart; - } - - public void endUpdateAndResolveTime() { - updateAndResolveTime = System.currentTimeMillis() - updateAndResolveTimeStart; - } - - public long getCompileLibrariesTime() { - return compileLibrariesTime; - } - - public long getJSNativeLibCharSize() { - return nativeLibCharCount; - } - - public double getLinesPerMS() { - return getNumLinesParsed() / getTotalCompilationTime(); - } - - public double getNonCommentLinesPerMS() { - return getNumNonCommentLines() / getTotalCompilationTime(); - } - - public long getNumCharsParsed() { - return charactersParsed.get(); - } - - public long getNumLinesParsed() { - return linesParsed.get(); - } - - public long getNumNonCommentChars() { - return charactersParsedExcludingComments.get(); - } - - public long getNumNonCommentLines() { - return linesParsedExcludingComments.get(); - } - - public double getNumUnitsParsed() { - return unitsParsed.get(); - } - - public double getParseTime() { - return nanoToMillis(nanoTotalParseTime.get()); - } - - public double getParseWallTime() { - return nanoToMillis(nanoParseWallTime); - } - - public double getPercentCharsConsumedByNativeLibraries() { - return (getJSNativeLibCharSize() / getNumCharsParsed()) * 100d; - } - - public double getPercentTimeParsing() { - return getParseTime() / getTotalCompilationTime(); - } - - public double getTimeSpentPerUnit() { - if (getNumUnitsParsed() == 0) { - return 0; - } - return getTotalCompilationTime() / getNumUnitsParsed(); - } - - public double getTotalCompilationTime() { - return milliEndTime - milliStartTime; - } - - public long getUpdateAndResolveTime() { - return updateAndResolveTime; - } - - public void startCompileLibrariesTime() { - compileLibrariesTimeStart = System.currentTimeMillis(); - } - - public void startUpdateAndResolveTime() { - updateAndResolveTimeStart = System.currentTimeMillis(); - } - - public void unitParsed(int charactersParsed, int charactersParsedExcludingComments, - int linesParsed, int linesParsedExcludingComments) { - this.unitsParsed.incrementAndGet(); - this.charactersParsed.addAndGet(charactersParsed); - this.charactersParsedExcludingComments.addAndGet(charactersParsedExcludingComments); - this.linesParsed.addAndGet(linesParsed); - this.linesParsedExcludingComments.addAndGet(linesParsedExcludingComments); - } - - /** - * Writes the metrics to the {@link PrintStream}. - */ - public void write(PrintStream out) { - /* This is mainly for the metrics system. Units should be encoded in - * the label name and end up as the benchmark names. - */ - done(); - out.format("Compile-time-total-ms : %1$.2f%n", getTotalCompilationTime()); - out.format("# Update-and-resolve-time-ms : %d\n", getUpdateAndResolveTime()); - out.format("# Compile-libraries-time-ms : %d\n", getCompileLibrariesTime()); - out.println("# Compile-time-unit-average-ms : " + getTimeSpentPerUnit()); - out.format("# Parse-wall-time-ms : %1$.2f%n", getParseWallTime()); - out.format("# Parse-time-ms : %1$.2f%n", getParseTime()); - out.println("# Parsed-units : " + getNumUnitsParsed()); - out.println("# Parsed-src-chars : " + getNumCharsParsed()); - out.println("# Parsed-src-lines : " + getNumLinesParsed()); - out.println("# Parsed-code-chars : " + getNumNonCommentChars()); - out.println("# Parsed-code-lines : " + getNumNonCommentLines()); - double jsNativeLibCharSize = (getJSNativeLibCharSize() == -1) ? 0 : getJSNativeLibCharSize(); - out.println("# Output-js-native-lib-chars : " + jsNativeLibCharSize ); - out.println("# Processed-total-lines-ms : " + getLinesPerMS()); - out.println("# Processed-code-lines-ms : " + getNonCommentLinesPerMS()); - out.println("# Ratio-parsing-compile-percent : " + getPercentTimeParsing() * 100); - } -} diff --git a/compiler/java/com/google/dart/compiler/metrics/DartEventType.java b/compiler/java/com/google/dart/compiler/metrics/DartEventType.java deleted file mode 100644 index c6b2ec306dad..000000000000 --- a/compiler/java/com/google/dart/compiler/metrics/DartEventType.java +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.metrics; - -import com.google.dart.compiler.metrics.Tracer.EventType; - -/** - * Dart events for SpeedTracer. - */ -public enum DartEventType implements EventType { - ADD_OUTOFDATE("MistyRose"), - BUILD_LIB_SCOPES("violet"), - COMPILE("green"), - COMPILE_APP("gray"), - COMPILE_LIBRARIES("brown"), - EXEC_PHASE("blue"), - IMPORT_EMBEDDED_LIBRARIES("purple"), - IS_SOURCE_OUTOFDATE("Chartreuse"), - SCANNER("GoldenRod"), - PARSE("red"), - PARSE_OUTOFDATE("LightCoral"), - RESOLVE_LIBRARIES("black"), - TIMESTAMP_OUTOFDATE("LightSteelBlue"), - UPDATE_LIBRARIES("yellow"), - UPDATE_RESOLVE("orange"), - WRITE_METRICS("LightChiffon"); - - final String cssColor; - final String name; - - DartEventType(String cssColor) { - this(null, cssColor); - } - - DartEventType(String name, String cssColor) { - this.name = name; - this.cssColor = cssColor; - } - - @Override - public String getColor() { - return cssColor; - } - - @Override - public String getName() { - return name == null ? toString() : name; - } -} diff --git a/compiler/java/com/google/dart/compiler/metrics/JvmMetrics.java b/compiler/java/com/google/dart/compiler/metrics/JvmMetrics.java deleted file mode 100644 index 5123ed66cd88..000000000000 --- a/compiler/java/com/google/dart/compiler/metrics/JvmMetrics.java +++ /dev/null @@ -1,249 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.metrics; - -import java.io.PrintStream; -import java.lang.management.CompilationMXBean; -import java.lang.management.GarbageCollectorMXBean; -import java.lang.management.ManagementFactory; -import java.lang.management.MemoryMXBean; -import java.lang.management.MemoryPoolMXBean; -import java.lang.management.MemoryUsage; -import java.util.List; -import java.util.StringTokenizer; - -/** - * A class to report jvm/jmx statistics - */ -public class JvmMetrics { - - private static int TABULAR_COLON_POS = 40; - private static long ONE_KILO_BYTE = 1L << 10L; - private static long ONE_MEGA_BYTE = 1L << 20L; - private static long ONE_GIGA_BYTE = 1L << 30L; - - public static void maybeWriteJvmMetrics(PrintStream out, String options) { - if (options == null) { - return; - } - - boolean verboseMode = false; - boolean prettyMode = false; - StringTokenizer st = new StringTokenizer(options,":"); - // options are grouped in order 'detail:format:types' - if (st.hasMoreTokens()) { - String mode = st.nextToken(); - if (mode.equalsIgnoreCase("verbose")) { - verboseMode = true; - } - } - - if (st.hasMoreTokens()) { - String mode = st.nextToken(); - if (mode.equalsIgnoreCase("pretty")) { - prettyMode = true; - } - } - - if (st.hasMoreTokens()) { - while (st.hasMoreTokens()) { - String types = st.nextToken(); - StringTokenizer typeSt = new StringTokenizer(types,","); - while (typeSt.hasMoreElements()) { - String type = typeSt.nextToken(); - writeMetrics(out, type, verboseMode, prettyMode); - } - } - } else { - // the default - writeMetrics(out, "all", verboseMode, prettyMode); - } - } - - private static void writeMetrics(PrintStream out, String type, boolean verbose, boolean pretty) { - - if (type.equals("gc") || type.equalsIgnoreCase("all")) { - writeGarbageCollectionStats(out, verbose, pretty); - } - if (type.equals("mem") || type.equalsIgnoreCase("all")) { - writeMemoryMetrics(out, verbose, pretty); - } - if (type.equals("jit") || type.equalsIgnoreCase("all")) { - writeJitMetrics(out, verbose, pretty); - } - } - - private static void writeJitMetrics(PrintStream out, boolean verbose, boolean pretty) { - - CompilationMXBean cBean = ManagementFactory.getCompilationMXBean(); - - String name; - if (verbose) { - name = cBean.getName(); - } else { - name = "total"; - } - - if (pretty) { - out.println("\nJIT Stats"); - out.println(String.format("\t%s jit time: %d ms", name, cBean.getTotalCompilationTime())); - } else { - out.println(normalizeTabularColonPos(String.format("%s-jit-time-ms : %d", normalizeName(name), - cBean.getTotalCompilationTime()))); - } - } - - private static void writeOverallMemoryUsage(PrintStream out, MemoryUsage usage, - String prefix, boolean pretty) { - if (pretty) { - out.format("\t%s\n", prefix); - out.format("\t\tavailable : %s\n", formatBytes(usage.getMax())); - out.format("\t\tcurrent : %s\n", formatBytes(usage.getUsed())); - } else { - prefix = normalizeName(prefix); - out.println(normalizeTabularColonPos(String.format(prefix + "-available-bytes : %d", - usage.getMax()))); - out.println(normalizeTabularColonPos(String.format(prefix + "-current-bytes : %d", - usage.getUsed()))); - } - } - - private static void writePoolMemoryUsage(PrintStream out, MemoryUsage usage, - MemoryUsage peakUsage, String prefix, boolean pretty) { - if (pretty) { - out.format("\t\tavailable : %s\n", formatBytes(usage.getMax())); - out.format("\t\tpeak : %s\n", formatBytes(peakUsage.getUsed())); - out.format("\t\tcurrent : %s\n", formatBytes(usage.getUsed())); - } else { - out.println(normalizeTabularColonPos(String.format(prefix + "-available-bytes : %d", - usage.getMax()))); - out.println(normalizeTabularColonPos(String.format(prefix + "-peak-bytes : %d", - peakUsage.getUsed()))); - out.println(normalizeTabularColonPos(String.format(prefix + "-current-bytes : %d", - usage.getUsed()))); - } - } - - private static void writeMemoryMetrics(PrintStream out, boolean verbose, boolean pretty) { - if (pretty) { - out.println("\nMemory usage"); - } - - // only show overall stats in verbose mode - if (verbose) { - MemoryMXBean overallMemBean = ManagementFactory.getMemoryMXBean(); - MemoryUsage usage = overallMemBean.getHeapMemoryUsage(); - writeOverallMemoryUsage(out, usage, "Heap", pretty); - - usage = overallMemBean.getNonHeapMemoryUsage(); - writeOverallMemoryUsage(out, usage, "Non-heap", pretty); - } - - if (verbose) { - List mpBeans = ManagementFactory.getMemoryPoolMXBeans(); - for (MemoryPoolMXBean mpBean : mpBeans) { - MemoryUsage currentUsage = mpBean.getUsage(); - MemoryUsage peakUsage = mpBean.getPeakUsage(); - if (pretty) { - out.println("\tPool " + mpBean.getName()); - writePoolMemoryUsage(out, currentUsage, peakUsage, null, true); - } else { - writePoolMemoryUsage(out, currentUsage, peakUsage, - "mem-pool-" + normalizeName(mpBean.getName()), false); - } - } - } else { - long available = 0; - long current = 0; - long peak = 0; - List mpBeans = ManagementFactory.getMemoryPoolMXBeans(); - for (MemoryPoolMXBean mpBean : mpBeans) { - MemoryUsage currentUsage = mpBean.getUsage(); - available += currentUsage.getMax(); - current += currentUsage.getUsed(); - MemoryUsage peakUsage = mpBean.getPeakUsage(); - peak += peakUsage.getUsed(); - } - MemoryUsage summaryUsage = new MemoryUsage(0, current, current, available); - MemoryUsage summaryPeakUsage = new MemoryUsage(0, peak, peak, peak); - if (pretty) { - out.format("\tAggregate of %d memory pools\n", mpBeans.size()); - writePoolMemoryUsage(out, summaryUsage, summaryPeakUsage, null, true); - } else { - writePoolMemoryUsage(out, summaryUsage, summaryPeakUsage, - "mem", false); - } - } - } - - private static void writeGarbageCollectionStats(PrintStream out, boolean verbose, boolean pretty) { - List gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); - - if (verbose) { - if (pretty) { - out.println("\nGarbage collection stats"); - for (GarbageCollectorMXBean gcBean : gcBeans) { - out.println("\tCollector " + gcBean.getName()); - out.format("\t\tcollection count : %d\n", gcBean.getCollectionCount()); - out.format("\t\tcollection time : %d ms\n", gcBean.getCollectionTime()); - } - } else { - for (GarbageCollectorMXBean gcBean : gcBeans) { - String name = normalizeName(gcBean.getName()); - out.println(normalizeTabularColonPos(String.format("gc-" + name + "-collection-count : %d", - gcBean.getCollectionCount()))); - out.println(normalizeTabularColonPos(String.format("gc-" + name + "-collection-time-ms : %d", - gcBean.getCollectionTime()))); - } - } - } else { - long collectionCount = 0; - long collectionTime = 0; - int collectorCount = gcBeans.size(); - for (GarbageCollectorMXBean gcBean : gcBeans) { - collectionCount += gcBean.getCollectionCount(); - collectionTime += gcBean.getCollectionTime(); - } - if (pretty) { - out.println("\nGarbage collection stats"); - out.format("\tAggregate of %d collectors\n", collectorCount); - out.format("\t\tcollection count : %d\n", collectionCount); - out.format("\t\tcollection time : %d ms\n", collectionTime); - } else { - String name = normalizeName("aggregate"); - out.println(normalizeTabularColonPos(String.format("gc-" + name + "-collection-count : %d", - collectionCount))); - out.println(normalizeTabularColonPos(String.format("gc-" + name + "-collection-time-ms : %d", - collectionTime))); - } - } - } - - private static String normalizeName(String name) { - return name.replace(" ","_").toLowerCase(); - } - - private static String normalizeTabularColonPos(String string) { - StringBuilder sb = new StringBuilder(string); - int index = sb.indexOf(":"); - for (;index < TABULAR_COLON_POS;++index) { - sb.insert(index, ' '); - } - return sb.toString(); - } - - private static String formatBytes(long numBytes) { - if (numBytes < ONE_KILO_BYTE) { - return String.format("%d B", numBytes); - } else if (numBytes < ONE_MEGA_BYTE) { - return String.format("%d KB", numBytes / ONE_KILO_BYTE); - } else if (numBytes < ONE_GIGA_BYTE) { - return String.format("%d MB", numBytes / ONE_MEGA_BYTE); - } else { - return String.format("%d GB", numBytes / ONE_GIGA_BYTE); - } - } - -} diff --git a/compiler/java/com/google/dart/compiler/metrics/SpeedTracerEventType.java b/compiler/java/com/google/dart/compiler/metrics/SpeedTracerEventType.java deleted file mode 100644 index 6c84f1b7c7fa..000000000000 --- a/compiler/java/com/google/dart/compiler/metrics/SpeedTracerEventType.java +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.metrics; - -import com.google.dart.compiler.metrics.Tracer.EventType; - -/** - * Represents a type of event whose performance is tracked while running. - */ -public enum SpeedTracerEventType implements EventType { - GC("Garbage Collection", "Plum"), - OVERHEAD("Speedtracer Overhead","Black"); - - final String cssColor; - final String name; - - SpeedTracerEventType(String name, String cssColor) { - this.name = name; - this.cssColor = cssColor; - } - - @Override - public String getColor() { - return cssColor; - } - - @Override - public String getName() { - return name; - } -} diff --git a/compiler/java/com/google/dart/compiler/metrics/Tracer.java b/compiler/java/com/google/dart/compiler/metrics/Tracer.java deleted file mode 100644 index 9103026b0b7e..000000000000 --- a/compiler/java/com/google/dart/compiler/metrics/Tracer.java +++ /dev/null @@ -1,959 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.metrics; - -import org.json.JSONException; -import org.json.JSONObject; -import org.json.JSONArray; - -import java.io.BufferedWriter; -import java.io.FileWriter; -import java.io.IOException; -import java.io.Writer; -import java.lang.management.GarbageCollectorMXBean; -import java.lang.management.ManagementFactory; -import java.lang.management.OperatingSystemMXBean; -import java.lang.management.ThreadMXBean; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Stack; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; - -/** - * Logs performance metrics for internal development purposes. The output is - * formatted so it can be opened directly in the SpeedTracer Chrome extension. - * This class formats events using SpeedTracer's custom event feature. The html - * file output can be viewed by using Chrome to open the file on a Chrome - * browser that has the SpeedTracer extension installed. - * - *

- * Enable logging by setting the system property {@code dart.speedtracerlog} to - * the output file path. - *

- * - * NB: This class has been copied almost verbatim from the gwt source tree - */ -public final class Tracer { - - // Log file name (logging is enabled if this is non-null) - private static final String logFile = System.getProperty("dart.speedtracerlog"); - - // Allow a system property to override the default output format - private static final String defaultFormatString = System.getProperty("dart.speedtracerformat"); - - // Use cumulative multi-threaded process cpu time instead of wall time - private static final boolean logProcessCpuTime = - getBooleanProperty("dart.speedtracer.logProcessCpuTime"); - - // Use per thread cpu time instead of wall time. If logProcessCpuTime is set, - // then this can remain false - we only need one or the other. - private static final boolean logThreadCpuTime = - getBooleanProperty("dart.speedtracer.logThreadCpuTime"); - - // Turn on logging summarizing gc time during an event - private static final boolean logGcTime = getBooleanProperty("dart.speedtracer.logGcTime"); - - // Turn on logging estimating overhead used for speedtracer logging. - private static final boolean logOverheadTime = - getBooleanProperty("dart.speedtracer.logOverheadTime"); - - static { - // verify configuration - if (logProcessCpuTime && logThreadCpuTime) { - throw new RuntimeException("System properties are misconfigured: " - + "Specify one or the other of 'dart.speedtracer.logProcessCpuTime' " - + "or 'dart.speedtracer.logThreadCpuTime', not both."); - } - } - - /** - * Represents a node in a tree of SpeedTracer events. - */ - public class TraceEvent { - protected final EventType type; - List children; - List data; - - long elapsedDurationNanos; - long elapsedStartTimeNanos; - - long processCpuDurationNanos; - long processCpuStartTimeNanos; - - long threadCpuDurationNanos; - long threadCpuStartTimeNanos; - - TraceEvent() { - if (enabled) { - threadCpuTimeKeeper.resetTimeBase(); - recordStartTime(); - this.data = new ArrayList(); - this.children = new ArrayList(); - } else { - this.processCpuStartTimeNanos = 0L; - this.threadCpuStartTimeNanos = 0L; - this.elapsedStartTimeNanos = 0L; - this.data = null; - this.children = null; - } - this.type = null; - } - - TraceEvent(TraceEvent parent, EventType type, String... data) { - - if (parent != null) { - parent.children.add(this); - } - this.type = type; - assert (data.length % 2 == 0); - recordStartTime(); - this.data = new ArrayList(); - this.data.addAll(Arrays.asList(data)); - this.children = new ArrayList(); - } - - /** - * @param data key/value pairs to add to JSON object. - */ - public void addData(String... data) { - if (data != null) { - assert (data.length % 2 == 0); - this.data.addAll(Arrays.asList(data)); - } - } - - /** - * Signals the end of the current event. - */ - public void end(String... data) { - endImpl(this, data); - } - - /** - * Returns the event duration, in nanoseconds, for the log file. Depending - * on system properties, this will measured in elapsed time, process CPU - * time, or thread CPU time. - */ - public long getDurationNanos() { - return logProcessCpuTime ? processCpuDurationNanos : (logThreadCpuTime - ? threadCpuDurationNanos : elapsedDurationNanos); - } - - public long getElapsedDurationNanos() { - return this.elapsedDurationNanos; - } - - public long getElapsedStartTimeNanos() { - return this.elapsedStartTimeNanos; - } - - /** - * Returns the event start time, normalized in nanoseconds, for the log - * file. Depending on system properties, this will be normalized based on - * elapsed time, process CPU time, or thread CPU time. - */ - public long getStartTimeNanos() { - return logProcessCpuTime ? processCpuStartTimeNanos : (logThreadCpuTime - ? threadCpuStartTimeNanos : elapsedStartTimeNanos); - } - - public EventType getType() { - return type; - } - - @Override - public String toString() { - return type.getName(); - } - - /** - * Extends the durations of the current event by the durations of the - * specified event. - */ - void extendDuration(TraceEvent refEvent) { - elapsedDurationNanos += refEvent.elapsedDurationNanos; - processCpuDurationNanos += refEvent.processCpuDurationNanos; - threadCpuDurationNanos += refEvent.threadCpuDurationNanos; - } - - /** - * Sets the start time of this event to start immediately after the - * specified event ends. - */ - void setStartsAfter(TraceEvent refEvent) { - elapsedStartTimeNanos = refEvent.elapsedStartTimeNanos + refEvent.elapsedDurationNanos; - processCpuStartTimeNanos = - refEvent.processCpuStartTimeNanos + refEvent.processCpuDurationNanos; - threadCpuStartTimeNanos = refEvent.threadCpuStartTimeNanos + refEvent.threadCpuDurationNanos; - } - - JSONObject toJson() throws JSONException { - JSONObject json = new JSONObject(); - json.put("type", -2); - json.put("typeName", type.getName()); - json.put("color", type.getColor()); - double startMs = convertToMilliseconds(getStartTimeNanos()); - json.put("time", startMs); - double durationMs = convertToMilliseconds(getDurationNanos()); - json.put("duration", durationMs); - - JSONObject jsonData = new JSONObject(); - for (int i = 0; i < data.size(); i += 2) { - jsonData.put(data.get(i), data.get(i + 1)); - } - json.put("data", jsonData); - - JSONArray jsonChildren = new JSONArray(); - for (TraceEvent child : children) { - jsonChildren.put(child.toJson()); - } - json.put("children", jsonChildren); - - return json; - } - - /** - * Records the duration of this event based on the current time and the - * event's recorded start time. - */ - void updateDuration() { - long elapsedEndTimeNanos = elapsedTimeKeeper.normalizedTimeNanos(); - assert (elapsedEndTimeNanos >= elapsedStartTimeNanos); - elapsedDurationNanos = elapsedEndTimeNanos - elapsedStartTimeNanos; - - // don't bother making expensive time keeping method calls unless - // necessary - if (logProcessCpuTime) { - long processCpuEndTimeNanos = processCpuTimeKeeper.normalizedTimeNanos(); - assert (processCpuEndTimeNanos >= processCpuStartTimeNanos); - processCpuDurationNanos = processCpuEndTimeNanos - processCpuStartTimeNanos; - } else if (logThreadCpuTime) { - long threadCpuEndTimeNanos = threadCpuTimeKeeper.normalizedTimeNanos(); - assert (threadCpuEndTimeNanos >= threadCpuStartTimeNanos); - threadCpuDurationNanos = threadCpuEndTimeNanos - threadCpuStartTimeNanos; - } - } - - /** - * Marks the start time for this event. Three different time measurements - * are used: - *
    - *
  1. Elapsed (wall-clock) time
  2. - *
  3. Process CPU time
  4. - *
  5. Thread CPU time
  6. - *
- */ - private void recordStartTime() { - elapsedStartTimeNanos = elapsedTimeKeeper.normalizedTimeNanos(); - - // don't bother making expensive time keeping method calls unless - // necessary - if (logProcessCpuTime) { - processCpuStartTimeNanos = processCpuTimeKeeper.normalizedTimeNanos(); - } else if (logThreadCpuTime) { - threadCpuStartTimeNanos = threadCpuTimeKeeper.normalizedTimeNanos(); - } - } - } - - /** - * Enumerated types for logging events implement this interface. - */ - public interface EventType { - String getColor(); - - String getName(); - } - - static enum Format { - /** - * Standard SpeedTracer log that includes JSON wrapped in HTML that will - * launch a SpeedTracer monitor session. - */ - HTML, - - /** - * Only the JSON data without any HTML wrappers. - */ - RAW - } - - /** - * A dummy implementation to do nothing if logging has not been turned on. - */ - private class DummyEvent extends TraceEvent { - @Override - public void addData(String... data) { - // do nothing - } - - @Override - public void end(String... data) { - // do nothing - } - - @Override - public String toString() { - return "Dummy"; - } - } - - /** - * Provides functionality specific to garbage collection events. - */ - private class GcEvent extends TraceEvent { - private TraceEvent refEvent; - - /** - * Constructs an event that represents garbage collection metrics. - * - * @param refEvent the event during which the garbage collections took place - * @param gcType the garbage collector type - * @param collectionCount the total number of collections for this garbage - * collector type - * @param durationNanos the total elapsed time spent in garbage collection - * during the span of {@code refEvent} - */ - GcEvent(TraceEvent refEvent, String gcType, long collectionCount, long durationNanos) { - super(null, SpeedTracerEventType.GC, "Collector Type", gcType, "Cumulative Collection Count", - Long.toString(collectionCount)); - - this.refEvent = refEvent; - // GarbageCollectorMXBean can only provide elapsed time, so that's all we - // record - this.elapsedDurationNanos = durationNanos; - } - - /** - * Returns elapsed duration since that is the only duration we can measure - * for garbage collection events. - */ - @Override - public long getDurationNanos() { - return getElapsedDurationNanos(); - } - - /** - * Returns a start time so that this event ends with its {@code refEvent}. - */ - @Override - public long getElapsedStartTimeNanos() { - return refEvent.getElapsedStartTimeNanos() + refEvent.getElapsedDurationNanos() - - getElapsedDurationNanos(); - } - - /** - * Returns a start time so that this event ends with its {@code refEvent}. - */ - @Override - public long getStartTimeNanos() { - return refEvent.getStartTimeNanos() + refEvent.getDurationNanos() - getDurationNanos(); - } - } - - /** - * Time keeper which uses wall time. - */ - private class ElapsedNormalizedTimeKeeper { - - private final long zeroTimeMillis; - - public ElapsedNormalizedTimeKeeper() { - zeroTimeMillis = System.currentTimeMillis(); - } - - public long normalizedTimeNanos() { - return (System.currentTimeMillis() - zeroTimeMillis) * 1000000L; - } - - public long zeroTimeMillis() { - return zeroTimeMillis; - } - } - - /** - * Time keeper which uses process cpu time. This can be greater than wall - * time, since it is cumulative over the multiple threads of a process. - */ - private class ProcessNormalizedTimeKeeper { - private final OperatingSystemMXBean osMXBean; - private final Method getProcessCpuTimeMethod; - private final long zeroTimeNanos; - private final long zeroTimeMillis; - - public ProcessNormalizedTimeKeeper() { - try { - osMXBean = ManagementFactory.getOperatingSystemMXBean(); - /* - * Find this method by reflection, since it's part of the Sun - * implementation for OperatingSystemMXBean, and we can't always assume - * that com.sun.management.OperatingSystemMXBean will be available. - */ - getProcessCpuTimeMethod = osMXBean.getClass().getMethod("getProcessCpuTime"); - getProcessCpuTimeMethod.setAccessible(true); - zeroTimeNanos = (Long) getProcessCpuTimeMethod.invoke(osMXBean); - zeroTimeMillis = (long) convertToMilliseconds(zeroTimeNanos); - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } - - public long normalizedTimeNanos() { - try { - return (Long) getProcessCpuTimeMethod.invoke(osMXBean) - zeroTimeNanos; - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } - - public long zeroTimeMillis() { - return zeroTimeMillis; - } - } - - /** - * Time keeper which uses per thread cpu time. It is assumed that individual - * events logged will be single threaded, and that top-level events will call - * {@link #resetTimeBase()} prior to logging time. The resettable time base is - * needed since each individual thread starts its timing at 0, regardless of - * when the thread is created. So we reset the time base at the beginning of - * an event, so that we can generate a chronologically representative output, - * although the relation to wall time is actually compressed within a logged - * event (thread cpu time does not include wait time, etc.). - */ - private class ThreadNormalizedTimeKeeper { - - private final ThreadMXBean threadMXBean; - private final ThreadLocal resettableTimeBase = new ThreadLocal(); - private final long zeroTimeNanos; - private final long zeroTimeMillis; - - public ThreadNormalizedTimeKeeper() { - threadMXBean = ManagementFactory.getThreadMXBean(); - if (!threadMXBean.isCurrentThreadCpuTimeSupported()) { - throw new RuntimeException("Current thread cpu time not supported"); - } - zeroTimeNanos = System.nanoTime(); - zeroTimeMillis = (long) convertToMilliseconds(zeroTimeNanos); - } - - public long normalizedTimeNanos() { - return threadMXBean.getCurrentThreadCpuTime() + resettableTimeBase.get(); - } - - public void resetTimeBase() { - /* - * Since all threads start individually at time 0L, we use this to offset - * each event's time so we can generate chronological output. - */ - resettableTimeBase.set(System.nanoTime() - zeroTimeNanos - - threadMXBean.getCurrentThreadCpuTime()); - } - - public long zeroTimeMillis() { - return zeroTimeMillis; - } - } - - /** - * Initializes the singleton on demand. - */ - private static class LazySpeedTracerLoggerHolder { - public static Tracer singleton = new Tracer(); - } - - /** - * Thread that converts log requests to JSON in the background. - */ - private class LogWriterThread extends Thread { - private static final int FLUSH_TIMER_MSECS = 10000; - private final String fileName; - private final BlockingQueue threadEventQueue; - private final Writer writer; - - public LogWriterThread(Writer writer, String fileName, final BlockingQueue eventQueue) { - super(); - this.writer = writer; - this.fileName = fileName; - this.threadEventQueue = eventQueue; - } - - @Override - public void run() { - long nextFlush = System.currentTimeMillis() + FLUSH_TIMER_MSECS; - try { - while (true) { - TraceEvent event = - threadEventQueue.poll(nextFlush - System.currentTimeMillis(), TimeUnit.MILLISECONDS); - if (event == null) { - // ignore. - } else if (event == shutDownSentinel) { - break; - } else if (event == flushSentinel) { - writer.flush(); - flushLatch.countDown(); - } else { - JSONObject json = event.toJson(); - json.write(writer); - writer.write('\n'); - } - if (System.currentTimeMillis() >= nextFlush) { - writer.flush(); - nextFlush = System.currentTimeMillis() + FLUSH_TIMER_MSECS; - } - } - // All queued events have been written. - if (outputFormat.equals(Format.HTML)) { - writer.write("\n"); - } - writer.close(); - } catch (InterruptedException ignored) { - } catch (IOException e) { - System.err.println("Unable to write to dart.speedtracerlog '" - + (fileName == null ? "" : fileName) + "'"); - e.printStackTrace(); - } catch (JSONException e) { - // TODO(jat): Auto-generated catch block - e.printStackTrace(); - } finally { - shutDownLatch.countDown(); - } - } - } - - /** - * Records a LOG_MESSAGE type of SpeedTracer event. - */ - private class MarkTimelineEvent extends TraceEvent { - public MarkTimelineEvent(TraceEvent parent) { - super(); - if (parent != null) { - parent.children.add(this); - } - } - - @Override - JSONObject toJson() throws JSONException { - JSONObject json = new JSONObject(); - json.put("type", 11); - double startMs = convertToMilliseconds(getStartTimeNanos()); - json.put("time", startMs); - json.put("duration", 0.0); - JSONObject jsonData = new JSONObject(); - for (int i = 0; i < data.size(); i += 2) { - jsonData.put(data.get(i), data.get(i + 1)); - } - json.put("data", jsonData); - return json; - } - } - - /** - * Annotate the current event on the top of the stack with more information. - * The method expects key, value pairs, so there must be an even number of - * parameters. - * - * @param data JSON property, value pair to add to current event. - */ - public static void addData(String... data) { - Tracer.get().addDataImpl(data); - } - - /** - * Create a new global instance. Force the zero time to be recorded and the - * log to be opened if the default logging is turned on with the - * -Ddart.speedtracerlog VM property. - * - * This method is only intended to be called once. - */ - public static void init() { - get(); - } - - /** - * Returns true if the trace output file is configured. This is intended to be - * the quickest possible check, statically determined. - */ - public static boolean canTrace() { - return logFile != null; - } - - /** - * Adds a LOG_MESSAGE SpeedTracer event to the log. This represents a single - * point in time and has a special representation in the SpeedTracer UI. - */ - public static void markTimeline(String message) { - Tracer.get().markTimelineImpl(message); - } - - /** - * Signals that a new event has started. You must end each event for each - * corresponding call to {@code start}. You may nest timing calls. - * - * @param type the type of event - * @param data a set of key-value pairs (each key is followed by its value) - * that contain additional information about the event - * @return an Event object to be ended by the caller - */ - public static TraceEvent start(EventType type, String... data) { - return Tracer.get().startImpl(type, data); - } - - private static double convertToMilliseconds(long nanos) { - return nanos / 1000000.0d; - } - - /** - * Convenience method for ending event, which might possibly be null. - */ - public static void end(TraceEvent event, String... data) { - if (event != null) { - event.end(data); - } - } - - /** - * For accessing the logger as a singleton, you can retrieve the global - * instance. It is prudent, but not necessary to first initialize the - * singleton with a call to {@link #init()} to set the base time. - * - * @return the current global {@link Tracer} instance. - */ - private static Tracer get() { - return LazySpeedTracerLoggerHolder.singleton; - } - - private static boolean getBooleanProperty(String propName) { - try { - return System.getProperty(propName) != null; - } catch (RuntimeException ruEx) { - return false; - } - } - - private final boolean enabled; - - private final DummyEvent dummyEvent = new DummyEvent(); - - private BlockingQueue eventsToWrite; - - private final boolean fileLoggingEnabled; - - private CountDownLatch flushLatch; - - private TraceEvent flushSentinel; - - private Format outputFormat; - - private ThreadLocal> pendingEvents; - - private CountDownLatch shutDownLatch; - - private TraceEvent shutDownSentinel; - - private List gcMXBeans; - - private Map lastGcTimes; - - private final ElapsedNormalizedTimeKeeper elapsedTimeKeeper; - - private final ProcessNormalizedTimeKeeper processCpuTimeKeeper; - - private final ThreadNormalizedTimeKeeper threadCpuTimeKeeper; - - /** - * Constructor intended for unit testing. - * - * @param writer alternative {@link Writer} to send speed tracer output. - */ - Tracer(Writer writer, Format format) { - enabled = true; - fileLoggingEnabled = true; - outputFormat = format; - eventsToWrite = openLogWriter(writer, ""); - pendingEvents = initPendingEvents(); - elapsedTimeKeeper = new ElapsedNormalizedTimeKeeper(); - processCpuTimeKeeper = new ProcessNormalizedTimeKeeper(); - threadCpuTimeKeeper = new ThreadNormalizedTimeKeeper(); - shutDownSentinel = new DummyEvent(); - flushSentinel = new DummyEvent(); - shutDownLatch = new CountDownLatch(1); - } - - private Tracer() { - fileLoggingEnabled = logFile != null; - enabled = fileLoggingEnabled; - - if (enabled) { - elapsedTimeKeeper = new ElapsedNormalizedTimeKeeper(); - processCpuTimeKeeper = new ProcessNormalizedTimeKeeper(); - threadCpuTimeKeeper = new ThreadNormalizedTimeKeeper(); - - if (fileLoggingEnabled) { - // Allow a system property to override the default output format - Format format = Format.HTML; - if (defaultFormatString != null) { - for (Format value : Format.values()) { - if (value.name().toLowerCase().equals(defaultFormatString.toLowerCase())) { - format = value; - break; - } - } - } - outputFormat = format; - eventsToWrite = openDefaultLogWriter(); - - shutDownSentinel = new TraceEvent(); - flushSentinel = new TraceEvent(); - shutDownLatch = new CountDownLatch(1); - } - - if (logGcTime) { - gcMXBeans = ManagementFactory.getGarbageCollectorMXBeans(); - lastGcTimes = new ConcurrentHashMap(); - } - - pendingEvents = initPendingEvents(); - } else { - elapsedTimeKeeper = null; - processCpuTimeKeeper = null; - threadCpuTimeKeeper = null; - } - } - - public void addDataImpl(String... data) { - Stack threadPendingEvents = pendingEvents.get(); - if (threadPendingEvents.isEmpty()) { - throw new IllegalStateException("Tried to add data to an event that never started!"); - } - - TraceEvent currentEvent = threadPendingEvents.peek(); - currentEvent.addData(data); - } - - public void markTimelineImpl(String message) { - Stack threadPendingEvents = pendingEvents.get(); - TraceEvent parent = null; - if (!threadPendingEvents.isEmpty()) { - parent = threadPendingEvents.peek(); - } - TraceEvent newEvent = new MarkTimelineEvent(parent); - threadPendingEvents.push(newEvent); - newEvent.end("message", message); - } - - void addGcEvents(TraceEvent refEvent) { - // we're not sending GC events to the dartboard, so we only record them - // to file - if (!fileLoggingEnabled) { - return; - } - - for (GarbageCollectorMXBean gcMXBean : gcMXBeans) { - String gcName = gcMXBean.getName(); - Long lastGcTime = lastGcTimes.get(gcName); - long currGcTime = gcMXBean.getCollectionTime(); - if (lastGcTime == null) { - lastGcTime = 0L; - } - if (currGcTime > lastGcTime) { - // create a new event - long gcDurationNanos = (currGcTime - lastGcTime) * 1000000L; - TraceEvent gcEvent = - new GcEvent(refEvent, gcName, gcMXBean.getCollectionCount(), gcDurationNanos); - - eventsToWrite.add(gcEvent); - lastGcTimes.put(gcName, currGcTime); - } - } - } - - void addOverheadEvent(TraceEvent refEvent) { - TraceEvent overheadEvent = new TraceEvent(refEvent, SpeedTracerEventType.OVERHEAD); - // measure the time between the end of refEvent and now - overheadEvent.setStartsAfter(refEvent); - overheadEvent.updateDuration(); - - refEvent.extendDuration(overheadEvent); - } - - void endImpl(TraceEvent event, String... data) { - if (!enabled) { - return; - } - - if (data.length % 2 == 1) { - throw new IllegalArgumentException("Unmatched data argument"); - } - - Stack threadPendingEvents = pendingEvents.get(); - if (threadPendingEvents.isEmpty()) { - throw new IllegalStateException("Tried to end an event that never started!"); - } - TraceEvent currentEvent = threadPendingEvents.pop(); - currentEvent.updateDuration(); - - while (currentEvent != event && !threadPendingEvents.isEmpty()) { - // Missed a closing end for one or more frames! Try to sync back up. - currentEvent.addData("Missed", - "This event was closed without an explicit call to Event.end()"); - currentEvent = threadPendingEvents.pop(); - currentEvent.updateDuration(); - } - - if (threadPendingEvents.isEmpty() && currentEvent != event) { - currentEvent.addData("Missed", "Fell off the end of the threadPending events"); - } - - if (logGcTime) { - addGcEvents(currentEvent); - } - - currentEvent.addData(data); - - if (logOverheadTime) { - addOverheadEvent(currentEvent); - } - - if (threadPendingEvents.isEmpty()) { - if (fileLoggingEnabled) { - eventsToWrite.add(currentEvent); - } - } - } - - /** - * Notifies the background thread to finish processing all data in the queue. - * Blocks the current thread until the data is flushed in the Log Writer - * thread. - */ - void flush() { - if (!fileLoggingEnabled) { - return; - } - - try { - // Wait for the other thread to drain the queue. - flushLatch = new CountDownLatch(1); - eventsToWrite.add(flushSentinel); - flushLatch.await(); - } catch (InterruptedException e) { - // Ignored - } - } - - TraceEvent startImpl(EventType type, String... data) { - if (!enabled) { - return dummyEvent; - } - - if (data.length % 2 == 1) { - throw new IllegalArgumentException("Unmatched data argument"); - } - - Stack threadPendingEvents = pendingEvents.get(); - TraceEvent parent = null; - if (!threadPendingEvents.isEmpty()) { - parent = threadPendingEvents.peek(); - } else { - // reset the thread CPU time base for top-level events (so events can be - // properly sequenced chronologically) - threadCpuTimeKeeper.resetTimeBase(); - } - - TraceEvent newEvent = new TraceEvent(parent, type, data); - // Add a field to the top level event in order to track the base time - // so we can re-normalize the data - if (threadPendingEvents.size() == 0) { - long baseTime = - logProcessCpuTime ? processCpuTimeKeeper.zeroTimeMillis() : (logThreadCpuTime - ? threadCpuTimeKeeper.zeroTimeMillis() : elapsedTimeKeeper.zeroTimeMillis()); - newEvent.addData("baseTime", "" + baseTime); - } - threadPendingEvents.push(newEvent); - return newEvent; - } - - private ThreadLocal> initPendingEvents() { - return new ThreadLocal>() { - @Override - protected Stack initialValue() { - return new Stack(); - } - }; - } - - private BlockingQueue openDefaultLogWriter() { - Writer writer = null; - if (enabled) { - try { - writer = new BufferedWriter(new FileWriter(logFile)); - return openLogWriter(writer, logFile); - } catch (IOException e) { - System.err.println("Unable to open dart.speedtracerlog '" + logFile + "'"); - e.printStackTrace(); - } - } - return null; - } - - private BlockingQueue openLogWriter(final Writer writer, final String fileName) { - try { - if (outputFormat.equals(Format.HTML)) { - writer.write("" - + "" - + "

Performance dump from GWT

" - + "
This file contains data that can be viewed with the " - + "SpeedTracer " - + "extension under the " - + "Chrome browser.

" - + "(You must install the SpeedTracer extension to open this file)

" - + "
\n"); - } - } catch (IOException e) { - System.err.println("Unable to write to dart.speedtracerlog '" - + (fileName == null ? "" : fileName) + "'"); - e.printStackTrace(); - return null; - } - - final BlockingQueue eventQueue = new LinkedBlockingQueue(); - - Runtime.getRuntime().addShutdownHook(new Thread() { - @Override - public void run() { - try { - // Wait for the other thread to drain the queue. - eventQueue.add(shutDownSentinel); - shutDownLatch.await(); - } catch (InterruptedException e) { - // Ignored - } - } - }); - - // Background thread to write SpeedTracer events to log - Thread logWriterWorker = new LogWriterThread(writer, fileName, eventQueue); - - // Lower than normal priority. - logWriterWorker.setPriority((Thread.MIN_PRIORITY + Thread.NORM_PRIORITY) / 2); - - /* - * This thread must be daemon, otherwise shutdown hooks would never begin to - * run, and an app wouldn't finish. - */ - logWriterWorker.setDaemon(true); - logWriterWorker.setName("SpeedTracerLogger writer"); - logWriterWorker.start(); - return eventQueue; - } -} diff --git a/compiler/java/com/google/dart/compiler/parser/AbstractParser.java b/compiler/java/com/google/dart/compiler/parser/AbstractParser.java deleted file mode 100644 index 6295eb197414..000000000000 --- a/compiler/java/com/google/dart/compiler/parser/AbstractParser.java +++ /dev/null @@ -1,257 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.parser; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import com.google.dart.compiler.DartCompilationError; -import com.google.dart.compiler.ErrorCode; -import com.google.dart.compiler.parser.DartScanner.Location; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Abstract base class for sharing common utility methods between implementation - * classes, like {@link DartParser}. - */ -abstract class AbstractParser { - - private final TerminalAnnotationsCache terminalAnnotationsCache = new TerminalAnnotationsCache(); - protected final ParserContext ctx; - private int lastErrorPosition = Integer.MIN_VALUE; - - protected AbstractParser(ParserContext ctx) { - this.ctx = ctx; - } - - protected boolean EOS() { - return match(Token.EOS) || match(Token.ILLEGAL); - } - - private static class TerminalAnnotationsCache { - private Map> classes; - private Map> methods; - - private void init(StackTraceElement[] stackTrace) { - // This method, she is slow. - if (classes == null) { - classes = Maps.newHashMap(); - methods = Maps.newHashMap(); - } - - for (StackTraceElement frame : stackTrace) { - Class thisClass = classes.get(frame.getClassName()); - if (thisClass == null) { - try { - thisClass = Class.forName(frame.getClassName()); - - for (java.lang.reflect.Method method : thisClass - .getDeclaredMethods()) { - List tokens = methods.get(method.getName()); - if (tokens == null) { - tokens = Lists.newArrayList(); - methods.put(thisClass.getName() + "." + method.getName(), tokens); - } - // look for annotations - Terminals terminalsAnnotation = method - .getAnnotation(Terminals.class); - if (terminalsAnnotation != null) { - for (Token token : terminalsAnnotation.tokens()) { - tokens.add(token); - } - } - } - } catch (ClassNotFoundException e) { - // ignored - } - classes.put(frame.getClassName(), null); - } - } - } - - public Set terminalsForStack(StackTraceElement[] stackTrace) { - Set results = Sets.newHashSet(); - for (StackTraceElement frame: stackTrace) { - List found = methods.get(frame.getClassName() + "." + frame.getMethodName()); - if (found != null) { - results.addAll(found); - } - } - return results; - } - } - - /** - * Uses reflection to walk up the stack and look for @Terminals method - * annotations. It gathers up the tokens in these annotations and returns them - * to the caller. This is intended for use in parser recovery, so that we - * don't accidentally consume a token that could be used to complete a - * non-terminal higher up in the stack. - */ - protected Set collectTerminalAnnotations() { - StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); - // Get methods for every class and associated Terminals annotations & stick them in a hash - terminalAnnotationsCache.init(stackTrace); - // Create the set of terminals to return - return terminalAnnotationsCache.terminalsForStack(stackTrace); - } - - /** - * If the expectedToken is encountered it is consumed and true is returned. - * If the expectedToken is not found, an error is reported. - * The token will only be consumed if it is not among the set of tokens that can be handled - * by a method currently on the stack. See the {@link Terminals annotation} - * - * @param expectedToken The token to expect next in the stream. - */ - protected boolean expect(Token expectedToken) { - if (!optional(expectedToken)) { - - /* - * Save the current token, then advance to make sure that we have the - * right position. - */ - Token actualToken = peek(0); - - Set possibleTerminals = collectTerminalAnnotations(); - - ctx.begin(); - ctx.advance(); - reportUnexpectedToken(position(), expectedToken, actualToken); - // Don't consume tokens someone else could use to cleanly terminate the - // statement. - if (possibleTerminals.contains(actualToken)) { - ctx.rollback(); - return false; - } - ctx.done(null); - - // Recover from the middle of string interpolation - if (actualToken.equals(Token.STRING_EMBED_EXP_START) - || actualToken.equals(Token.STRING_EMBED_EXP_END)) { - while (!EOS()) { - Token nextToken = next(); - if (nextToken.equals(Token.STRING_LAST_SEGMENT)) { - break; - } - next(); - } - } - return false; - } - return true; - } - - protected Location peekTokenLocation(int n) { - assert (n >= 0); - return ctx.peekTokenLocation(n); - } - - protected String getPeekTokenValue(int n) { - assert (n >= 0); - String value = ctx.peekTokenString(n); - return value; - } - - protected boolean match(Token token) { - return peek(0) == token; - } - - protected Token next() { - ctx.advance(); - return ctx.getCurrentToken(); - } - - protected boolean optionalPseudoKeyword(String keyword) { - if (!peekPseudoKeyword(0, keyword)) { - return false; - } - next(); - return true; - } - - protected boolean optional(Token token) { - if (peek(0) != token) { - return false; - } - next(); - return true; - } - - protected Token peek(int n) { - return ctx.peek(n); - } - - protected boolean peekPseudoKeyword(int n, String keyword) { - return (peek(n) == Token.IDENTIFIER) - && keyword.equals(getPeekTokenValue(n)); - } - - protected int position() { - DartScanner.Location tokenLocation = ctx.getTokenLocation(); - return tokenLocation != null ? tokenLocation.getBegin() : 0; - } - - /** - * Report a syntax error, unless an error has already been reported at the - * given or a later position. - */ - protected void reportError(int position, - ErrorCode errorCode, Object... arguments) { - DartScanner.Location location = ctx.getTokenLocation(); - if (location.getBegin() <= lastErrorPosition) { - return; - } - DartCompilationError dartError = new DartCompilationError(ctx.getSource(), - location, errorCode, arguments); - lastErrorPosition = position; - ctx.error(dartError); - } - - /** - * Even though you pass a 'Position' to {@link #reportError} above, it only - * uses that to prevent logging more than one error at that position. This - * method actually uses the passed position to create the error event. - */ - protected void reportErrorAtPosition(int startPosition, - int endPosition, - ErrorCode errorCode, Object... arguments) { - DartScanner.Location location = ctx.getTokenLocation(); - if (location.getBegin() <= lastErrorPosition) { - return; - } - DartCompilationError dartError = new DartCompilationError(ctx.getSource(), - new Location(startPosition, endPosition), errorCode, arguments); - ctx.error(dartError); - } - - protected void reportUnexpectedToken(int position, - Token expected, Token actual) { - if (expected == Token.EOS) { - reportError(position, ParserErrorCode.EXPECTED_EOS, actual); - } else if (expected == Token.IDENTIFIER) { - reportError(position, ParserErrorCode.INVALID_IDENTIFIER, actual); - } else if (expected == null) { - reportError(position, ParserErrorCode.UNEXPECTED_TOKEN, actual); - } else { - reportError(position, ParserErrorCode.EXPECTED_TOKEN, actual, expected); - } - } - - protected void setPeek(int n, Token token) { - assert n == 0; // so far, n is always zero - ctx.replaceNextToken(token); - } - - protected boolean consume(Token token) { - boolean result = (peek(0) == token); - assert (result); - next(); - return result; - } -} diff --git a/compiler/java/com/google/dart/compiler/parser/CompletionHooksParserBase.java b/compiler/java/com/google/dart/compiler/parser/CompletionHooksParserBase.java deleted file mode 100644 index 0c52488ffcae..000000000000 --- a/compiler/java/com/google/dart/compiler/parser/CompletionHooksParserBase.java +++ /dev/null @@ -1,482 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.parser; - -import com.google.dart.compiler.common.HasSourceInfo; - -/** - * This class exists to enforce constraints on begin calls so code - * completion works. - *

- * In particular, it prevents {@link #begin()} from being called directly, - * ensuring that callers must use appropriate {@code beginFoo} methods. - *

- * These hooks serve two purposes: - *

    - *
  1. remember start positions to set source location information on AST - * nodes - *
  2. provide an event mechanism that is useful for an IDE operating on code - * being edited - for example, for error recovery or code completion - *
- *

- * Every call to {@code beginFoo} must be balanced with exactly one call - * to either {@link #rollback()} or {@link #done(Object)}. Between those - * calls, there may be an arbitrary number of calls to - * {@link #doneWithoutConsuming(Object)} to set AST node positions based on - * the current position on the stack. - */ -public abstract class CompletionHooksParserBase extends AbstractParser { - - /* - * Guards the parser from infinite loops and recursion. - * THIS CLASS IS FOR DEBUG/INTERNAL USE ONLY. - * TODO (fabiomfv) - remove before release. - */ - private class TerminationGuard { - - /* - * Loosely, determines the maximum number of non-terminals 'visited' without - * advancing on input. It does not need to be a precise number, just to have - * an upper bound on the 'space' the parser can consume before declaring - * it is not making progress. - */ - private static final int THRESHOLD = 1000; - - private int maxPositionRange = Integer.MIN_VALUE; - private int minPositionRange = Integer.MAX_VALUE; - private int threshold = THRESHOLD; - - /* - * Guard against parser termination bugs. Called from begin(). - * If the parser does not consume tokens it is an indication that it is not - * making progress. Look at the stack in the exception for hints of - * productions at fault. Called from begin() - */ - public boolean assertProgress() { - int currentPosition = position(); - if (currentPosition > maxPositionRange) { - minPositionRange = maxPositionRange; - maxPositionRange = currentPosition; - threshold = THRESHOLD; - } else if (currentPosition < minPositionRange) { - minPositionRange = currentPosition; - threshold = THRESHOLD; - } - if (threshold-- <= 0) { - StringBuilder sb = new StringBuilder(); - sb.append("Parser failed to make progress after many tries. File a " + - "bug and attach this callstack and error output.\n"); - sb.append("Scanner State: "); - sb.append(ctx.toString()); - sb.append("\n"); - sb.append("Input range ["); - sb.append(minPositionRange); - sb.append(","); - sb.append(maxPositionRange); - sb.append("]\n"); - throw new AssertionError(sb.toString()); - } - return true; - } - } - - /** - * Guards against termination bugs. For debugging purposes only. - * See {@link TerminationGuard} for details. - */ - private TerminationGuard guard = new TerminationGuard(); - - /** - * Set the context the parser will use. - * - * @param ctx the {@link ParserContext} to use - */ - public CompletionHooksParserBase(ParserContext ctx) { - super(ctx); - } - - protected void beginArgumentDefinitionTest() { - begin(); - } - - protected void beginArrayLiteral() { - begin(); - } - - protected void beginAssertStatement() { - begin(); - } - - protected void beginBinaryExpression() { - begin(); - } - - protected void beginBlock() { - begin(); - } - - protected void beginBreakStatement() { - begin(); - } - - protected void beginCatchClause() { - begin(); - } - - protected void beginCatchParameter() { - begin(); - } - - protected void beginClassBody() { - begin(); - } - - protected void beginClassMember() { - begin(); - } - - protected void beginCompilationUnit() { - begin(); - } - - protected void beginConditionalExpression() { - begin(); - } - - protected void beginConstExpression() { - begin(); - } - - protected void beginConstructor() { - begin(); - } - - protected void beginConstructorNamePart() { - begin(); - } - - protected void beginContinueStatement() { - begin(); - } - - protected void beginDoStatement() { - begin(); - } - - protected void beginEmptyStatement() { - begin(); - } - - protected void beginEntryPoint() { - begin(); - } - - protected void beginExportDirective() { - begin(); - } - - protected void beginExpression() { - begin(); - } - - protected void beginExpressionList() { - begin(); - } - - protected void beginExpressionStatement() { - begin(); - } - - protected void beginFieldInitializerOrRedirectedConstructor() { - begin(); - } - - protected void beginFinalDeclaration() { - begin(); - } - - protected void beginForInitialization() { - begin(); - } - - protected void beginFormalParameter() { - begin(); - } - - protected void beginFormalParameterList() { - begin(); - } - - protected void beginForStatement() { - begin(); - } - - protected void beginFunctionDeclaration() { - begin(); - } - - protected void beginFunctionLiteral() { - begin(); - } - - protected void beginFunctionStatementBody() { - begin(); - } - - protected void beginClassTypeInterface() { - begin(); - } - - protected void beginFunctionTypeInterface() { - begin(); - } - - protected void beginIdentifier() { - begin(); - } - - protected void beginIfStatement() { - begin(); - } - - protected void beginImportDirective() { - begin(); - } - - protected void beginImportCombinator() { - begin(); - } - - protected void beginInitializer() { - begin(); - } - - protected void beginTypeExpression() { - begin(); - } - - protected void beginLabel() { - begin(); - } - - protected void beginLibraryDirective() { - begin(); - } - - protected void beginLiteral() { - begin(); - } - - protected void beginMapLiteral() { - begin(); - } - - protected void beginMapLiteralEntry() { - begin(); - } - - protected void beginMetadata() { - begin(); - } - - protected void beginMethodName() { - begin(); - } - - protected void beginNativeBody() { - begin(); - } - - protected void beginNativeDirective() { - begin(); - } - - protected void beginNewExpression() { - begin(); - } - - protected void beginOperatorName() { - begin(); - } - - protected void beginParameter() { - begin(); - } - - protected void beginParameterName() { - begin(); - } - - protected void beginParenthesizedExpression() { - begin(); - } - - protected void beginPartDirective() { - begin(); - } - - protected void beginPartOfDirective() { - begin(); - } - - protected void beginPostfixExpression() { - begin(); - } - - protected void beginQualifiedIdentifier() { - begin(); - } - - protected void beginReturnStatement() { - begin(); - } - - protected void beginReturnType() { - begin(); - } - - protected void beginSelectorExpression() { - begin(); - } - - protected void beginSourceDirective() { - begin(); - } - - protected void beginSpreadExpression() { - begin(); - } - - protected void beginStringInterpolation() { - begin(); - } - - protected void beginStringSegment() { - begin(); - } - - protected void beginSuperExpression() { - begin(); - } - - protected void beginSuperInitializer() { - begin(); - } - - protected void beginSwitchMember() { - begin(); - } - - protected void beginSwitchStatement() { - begin(); - } - - protected void beginThisExpression() { - begin(); - } - - protected void beginThrowExpression() { - begin(); - } - - protected void beginTopLevelElement() { - begin(); - } - - protected void beginTryStatement() { - begin(); - } - - protected void beginTypeAnnotation() { - begin(); - } - - protected void beginTypeArguments() { - begin(); - } - - protected void beginTypeFunctionOrVariable() { - begin(); - } - - protected void beginTypeParameter() { - begin(); - } - - protected void beginUnaryExpression() { - begin(); - } - - protected void beginVarDeclaration() { - begin(); - } - - protected void beginVariableDeclaration() { - begin(); - } - - protected void beginWhileStatement() { - begin(); - } - - /** - * Terminates a grammatical structure, saving the source location in the - * supplied AST node. - * - * @param type of the AST node - * @param result the AST node to return, if any - if it implements - * {@link HasSourceInfo}, the source location is set based on the - * current position and the start of this grammatical structure - * @return the supplied AST node (may be null) - */ - protected T done(T result) { - return ctx.done(result); - } - - /** - * Saves the current source location in the supplied AST node, used for - * subcomponents of the AST. This may only be called within an active - * {@link #begin()} call, which must still be terminated with either - * {@link #done(Object)} or {@link #rollback()}. - * - * @param type of the AST node - * @param result the AST node to return - if it implements - * {@link HasSourceInfo}, the source location is set based on the - * current position and the start of this grammatical structure - * @return the supplied AST node - */ - protected T doneWithoutConsuming(T result) { - return ctx.doneWithoutConsuming(result); - } - - /** - * Terminates an attempt to parse a grammatical structure, rolling back to the - * state as of the previous {@link #begin()} call and removing the saved - * state. - */ - protected void rollback() { - ctx.rollback(); - } - - /** - * This should only be called when the parser is looking ahead to decide how - * to parse something, and this will always be rolled back without any other {@link #begin()} - * statements being called. - */ - protected void startLookahead() { - begin(); - } - - /** - * Begin a grammatical structure, saving the current location to later set in - * an AST node. This may be followed by zero or more - * {@link #doneWithoutConsuming(Object)} calls, and is terminated by exactly - * one {@link #done(Object)} or {@link #rollback()} call. - */ - private void begin() { - assert guard.assertProgress(); - ctx.begin(); - } -} diff --git a/compiler/java/com/google/dart/compiler/parser/DartParser.java b/compiler/java/com/google/dart/compiler/parser/DartParser.java deleted file mode 100644 index cd5728ae4c43..000000000000 --- a/compiler/java/com/google/dart/compiler/parser/DartParser.java +++ /dev/null @@ -1,5688 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.parser; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.ImmutableSet; -import com.google.common.io.CharStreams; -import com.google.dart.compiler.DartCompilationError; -import com.google.dart.compiler.DartCompilerListener; -import com.google.dart.compiler.DartSource; -import com.google.dart.compiler.ErrorCode; -import com.google.dart.compiler.ErrorSeverity; -import com.google.dart.compiler.InternalCompilerException; -import com.google.dart.compiler.LibrarySource; -import com.google.dart.compiler.PackageLibraryManager; -import com.google.dart.compiler.Source; -import com.google.dart.compiler.ast.DartAnnotation; -import com.google.dart.compiler.ast.DartArrayAccess; -import com.google.dart.compiler.ast.DartArrayLiteral; -import com.google.dart.compiler.ast.DartAssertStatement; -import com.google.dart.compiler.ast.DartBinaryExpression; -import com.google.dart.compiler.ast.DartBlock; -import com.google.dart.compiler.ast.DartBooleanLiteral; -import com.google.dart.compiler.ast.DartBreakStatement; -import com.google.dart.compiler.ast.DartCascadeExpression; -import com.google.dart.compiler.ast.DartCase; -import com.google.dart.compiler.ast.DartCatchBlock; -import com.google.dart.compiler.ast.DartClass; -import com.google.dart.compiler.ast.DartClassTypeAlias; -import com.google.dart.compiler.ast.DartConditional; -import com.google.dart.compiler.ast.DartContinueStatement; -import com.google.dart.compiler.ast.DartDeclaration; -import com.google.dart.compiler.ast.DartDefault; -import com.google.dart.compiler.ast.DartDirective; -import com.google.dart.compiler.ast.DartDoWhileStatement; -import com.google.dart.compiler.ast.DartDoubleLiteral; -import com.google.dart.compiler.ast.DartEmptyStatement; -import com.google.dart.compiler.ast.DartExportDirective; -import com.google.dart.compiler.ast.DartExprStmt; -import com.google.dart.compiler.ast.DartExpression; -import com.google.dart.compiler.ast.DartField; -import com.google.dart.compiler.ast.DartFieldDefinition; -import com.google.dart.compiler.ast.DartForInStatement; -import com.google.dart.compiler.ast.DartForStatement; -import com.google.dart.compiler.ast.DartFunction; -import com.google.dart.compiler.ast.DartFunctionExpression; -import com.google.dart.compiler.ast.DartFunctionObjectInvocation; -import com.google.dart.compiler.ast.DartFunctionTypeAlias; -import com.google.dart.compiler.ast.DartIdentifier; -import com.google.dart.compiler.ast.DartIfStatement; -import com.google.dart.compiler.ast.DartImportDirective; -import com.google.dart.compiler.ast.DartInitializer; -import com.google.dart.compiler.ast.DartIntegerLiteral; -import com.google.dart.compiler.ast.DartLabel; -import com.google.dart.compiler.ast.DartLibraryDirective; -import com.google.dart.compiler.ast.DartMapLiteral; -import com.google.dart.compiler.ast.DartMapLiteralEntry; -import com.google.dart.compiler.ast.DartMethodDefinition; -import com.google.dart.compiler.ast.DartMethodInvocation; -import com.google.dart.compiler.ast.DartNamedExpression; -import com.google.dart.compiler.ast.DartNativeBlock; -import com.google.dart.compiler.ast.DartNativeDirective; -import com.google.dart.compiler.ast.DartNewExpression; -import com.google.dart.compiler.ast.DartNode; -import com.google.dart.compiler.ast.DartNodeWithMetadata; -import com.google.dart.compiler.ast.DartNullLiteral; -import com.google.dart.compiler.ast.DartParameter; -import com.google.dart.compiler.ast.DartParameterizedTypeNode; -import com.google.dart.compiler.ast.DartParenthesizedExpression; -import com.google.dart.compiler.ast.DartPartOfDirective; -import com.google.dart.compiler.ast.DartPropertyAccess; -import com.google.dart.compiler.ast.DartRedirectConstructorInvocation; -import com.google.dart.compiler.ast.DartReturnBlock; -import com.google.dart.compiler.ast.DartReturnStatement; -import com.google.dart.compiler.ast.DartSourceDirective; -import com.google.dart.compiler.ast.DartStatement; -import com.google.dart.compiler.ast.DartStringInterpolation; -import com.google.dart.compiler.ast.DartStringLiteral; -import com.google.dart.compiler.ast.DartSuperConstructorInvocation; -import com.google.dart.compiler.ast.DartSuperExpression; -import com.google.dart.compiler.ast.DartSwitchMember; -import com.google.dart.compiler.ast.DartSwitchStatement; -import com.google.dart.compiler.ast.DartSyntheticErrorExpression; -import com.google.dart.compiler.ast.DartSyntheticErrorIdentifier; -import com.google.dart.compiler.ast.DartSyntheticErrorStatement; -import com.google.dart.compiler.ast.DartThisExpression; -import com.google.dart.compiler.ast.DartThrowExpression; -import com.google.dart.compiler.ast.DartTryStatement; -import com.google.dart.compiler.ast.DartTypeExpression; -import com.google.dart.compiler.ast.DartTypeNode; -import com.google.dart.compiler.ast.DartTypeParameter; -import com.google.dart.compiler.ast.DartUnaryExpression; -import com.google.dart.compiler.ast.DartUnit; -import com.google.dart.compiler.ast.DartUnqualifiedInvocation; -import com.google.dart.compiler.ast.DartVariable; -import com.google.dart.compiler.ast.DartVariableStatement; -import com.google.dart.compiler.ast.DartWhileStatement; -import com.google.dart.compiler.ast.HasObsoleteMetadata; -import com.google.dart.compiler.ast.ImportCombinator; -import com.google.dart.compiler.ast.ImportHideCombinator; -import com.google.dart.compiler.ast.ImportShowCombinator; -import com.google.dart.compiler.ast.LibraryNode; -import com.google.dart.compiler.ast.LibraryUnit; -import com.google.dart.compiler.ast.Modifiers; -import com.google.dart.compiler.metrics.CompilerMetrics; -import com.google.dart.compiler.parser.DartScanner.Location; -import com.google.dart.compiler.resolver.Elements; -import com.google.dart.compiler.util.Lists; -import com.google.dart.compiler.util.apache.StringUtils; - -import java.io.IOException; -import java.io.Reader; -import java.math.BigInteger; -import java.text.Normalizer; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * The Dart parser. Parses a single compilation unit and produces a {@link DartUnit}. - * The grammar rules are taken from Dart.g revision 557. - */ -public class DartParser extends CompletionHooksParserBase { - - private final Source source; - private final String sourceCode; - private final boolean isDietParse; - private final Set prefixes; - private boolean allowNativeKeyword; - private final Set errorHistory = new HashSet(); - private boolean isParsingInterface; - private boolean isTopLevelAbstract; - private int topLevelAbstractModifierPosition; - private boolean isParsingClass; - private int errorCount = 0; - - /** - * Determines the maximum number of errors before terminating the parser. See - * {@link #reportError(int, ErrorCode, Object...)}. - */ - final int MAX_DEFAULT_ERRORS = Short.MAX_VALUE; - - // Pseudo-keywords that should also be valid identifiers. - private static final String ABSTRACT_KEYWORD = "abstract"; - private static final String AS_KEYWORD = "as"; - private static final String CALL_KEYWORD = "call"; - public static final String DYNAMIC_KEYWORD = "dynamic"; - private static final String EXPORT_KEYWORD = "export"; - private static final String EXTERNAL_KEYWORD = "external"; - private static final String FACTORY_KEYWORD = "factory"; - private static final String GETTER_KEYWORD = "get"; - private static final String HIDE_KEYWORD = "hide"; - private static final String IMPLEMENTS_KEYWORD = "implements"; - private static final String IMPORT_KEYWORD = "import"; - private static final String INTERFACE_KEYWORD = "interface"; - private static final String LIBRARY_KEYWORD = "library"; - private static final String NATIVE_KEYWORD = "native"; - private static final String OF_KEYWORD = "of"; - private static final String ON_KEYWORD = "on"; - private static final String OPERATOR_KEYWORD = "operator"; - private static final String PART_KEYWORD = "part"; - private static final String PREFIX_KEYWORD = "prefix"; - private static final String SETTER_KEYWORD = "set"; - private static final String SHOW_KEYWORD = "show"; - private static final String STATIC_KEYWORD = "static"; - private static final String TYPEDEF_KEYWORD = "typedef"; - // does not exist in specification - private static final String PATCH_KEYWORD = "patch"; - - - public static final String[] PSEUDO_KEYWORDS = { - ABSTRACT_KEYWORD, - AS_KEYWORD, - DYNAMIC_KEYWORD, - EXPORT_KEYWORD, - EXTERNAL_KEYWORD, - FACTORY_KEYWORD, - GETTER_KEYWORD, - IMPLEMENTS_KEYWORD, - IMPORT_KEYWORD, - LIBRARY_KEYWORD, - OPERATOR_KEYWORD, - PART_KEYWORD, - SETTER_KEYWORD, - STATIC_KEYWORD, - TYPEDEF_KEYWORD - }; - public static final Set PSEUDO_KEYWORDS_SET = ImmutableSet.copyOf(PSEUDO_KEYWORDS); - - public static final String[] RESERVED_WORDS = { - "break", - "case", - "catch", - "class", - "const", - "continue", - "default", - "do", - "else", - "extends", - "false", - "final", - "finally", - "for", - "if", - "in", - "is", - "new", - "null", - "return", - "rethrow", - "super", - "switch", - "this", - "throw", - "true", - "try", - "var", - "void", - "while"}; - public static final Set RESERVED_WORDS_SET = ImmutableSet.copyOf(RESERVED_WORDS); - - public DartParser(Source source, - String sourceCode, - boolean isDietParse, - Set prefixes, - DartCompilerListener listener, - CompilerMetrics compilerMetrics) { - super(new DartParserCommentsHelper.CommentParserContext(source, sourceCode, listener, compilerMetrics)); - this.source = source; - this.sourceCode = sourceCode; - this.isDietParse = isDietParse; - this.prefixes = prefixes; - this.allowNativeKeyword = source != null && PackageLibraryManager.isDartUri(source.getUri()); - // check Unicode normalization - { - int indexOfDifference = StringUtils.indexOfDifference(sourceCode, - Normalizer.normalize(sourceCode, Normalizer.Form.NFC)); - if (indexOfDifference != -1) { - DartCompilationError error = new DartCompilationError(source, new Location( - indexOfDifference, indexOfDifference + 1), - ParserErrorCode.INVALID_UNICODE_NORMALIZATION); - ctx.error(error); - } - } - } - - public static String read(Source source) throws IOException { - return read(source.getSourceReader()); - } - - public static String read(Reader reader) throws IOException { - try { - return CharStreams.toString(reader); - } finally { - reader.close(); - } - } - - /** - * A flag indicating whether function expressions are allowed. See - * {@link #setAllowFunctionExpression(boolean)}. - */ - private boolean allowFunctionExpression = true; - - /** - * 'break' (with no labels) and 'continue' stmts are not valid - * just anywhere, they must be inside a loop or a case stmt. - * - * A break with a label may be valid and is allowed through and - * checked in the resolver. - */ - private boolean inLoopStatement = false; - private boolean inCaseStatement = false; - - /** - * Set the {@link #allowFunctionExpression} flag indicating whether function expressions are - * allowed, returning the old value. This is required to avoid ambiguity in a few places in the - * grammar. - * - * @param allow true if function expressions are allowed, false if not - * @return previous value of the flag, which should be restored - */ - private boolean setAllowFunctionExpression(boolean allow) { - boolean old = allowFunctionExpression; - allowFunctionExpression = allow; - return old; - } - - /** - *

-   * compilationUnit
-   *     : libraryDeclaration? topLevelDefinition* EOF
-   *     ;
-   *
-   * libraryDeclaration
-   *     : libraryDirective? importDirective* sourceDirective* resourceDirective* nativeDirective*
-   *
-   * topLevelDefinition
-   *     : classDefinition
-   *     | interfaceDefinition
-   *     | functionTypeAlias
-   *     | methodOrConstructorDeclaration functionStatementBody
-   *     | type? getOrSet identifier formalParameterList functionStatementBody
-   *     | CONST type? staticConstDeclarationList ';'
-   *     | variableDeclaration ';'
-   *     ;
-   * 
- */ - @Terminals(tokens={Token.EOS, Token.CLASS, Token.LIBRARY, Token.IMPORT, Token.SOURCE, - Token.RESOURCE, Token.NATIVE}) - public DartUnit parseUnit() { - DartSource dartSource = (DartSource) source; - - errorCount = 0; - - try { - beginCompilationUnit(); - ctx.unitAboutToCompile(dartSource, isDietParse); - DartUnit unit = new DartUnit(dartSource, isDietParse); - List metadata = parseMetadata(); - - // parse any directives at the beginning of the source - metadata = parseDirectives(unit, metadata); - - while (!EOS()) { - DartNodeWithMetadata node = null; - beginTopLevelElement(); - isParsingClass = isParsingInterface = false; - // Check for ABSTRACT_KEYWORD. - isTopLevelAbstract = false; - topLevelAbstractModifierPosition = 0; - if (isBuiltInSpecial() && optionalPseudoKeyword(ABSTRACT_KEYWORD)) { - isTopLevelAbstract = true; - topLevelAbstractModifierPosition = position(); - } - // skip "patch" before "class" - if (peek(1) == Token.CLASS && optionalPseudoKeyword(PATCH_KEYWORD)) { - } - // Parse top level element. - if (optional(Token.CLASS)) { - isParsingClass = true; - node = done(parseClass()); - } else if (peekPseudoKeyword(0, INTERFACE_KEYWORD) && peek(1).equals(Token.IDENTIFIER)) { - consume(Token.IDENTIFIER); - isParsingInterface = true; - reportError(position(), ParserErrorCode.DEPRECATED_INTERFACE); - node = done(parseClass()); - } else if (peekPseudoKeyword(0, TYPEDEF_KEYWORD) - && (peek(1).equals(Token.IDENTIFIER) || peek(1).equals(Token.VOID))) { - consume(Token.IDENTIFIER); - node = done(parseTypeAlias()); - } else if (looksLikeDirective()) { - reportErrorWithoutAdvancing(ParserErrorCode.DIRECTIVE_OUT_OF_ORDER); - metadata = parseDirectives(unit, metadata); - } else { - node = done(parseFieldOrMethod(false)); - } - // Parsing was successful, add node. - if (node != null) { - unit.getTopLevelNodes().add(node); - setMetadata(node, metadata); - metadata = parseMetadata(); - // Only "class" can be top-level abstract element. - if (isTopLevelAbstract && !isParsingClass) { - int abstractPositionEnd = topLevelAbstractModifierPosition + ABSTRACT_KEYWORD.length(); - Location location = new Location(topLevelAbstractModifierPosition, abstractPositionEnd); - reportError(new DartCompilationError(source, location, - ParserErrorCode.ABSTRACT_TOP_LEVEL_ELEMENT)); - } - } - } - expect(Token.EOS); - // add comments - { - List commentLocs = ((DartParserCommentsHelper.CommentParserContext) ctx).getCommentLocs(); - DartParserCommentsHelper.addComments(unit, source, sourceCode, commentLocs); - } - // done - unit.setHasParseErrors(errorCount != 0); - return done(unit); - } catch (StringInterpolationParseError exception) { - throw new InternalCompilerException("Failed to parse " + source.getUri(), exception); - } - } - - /** - * Set the metadata associated with the given node to the given annotations. - * - * @param node the node with which the metadata is to be associated - * @param metadata the metadata to be associated with the node - */ - private void setMetadata(DartNodeWithMetadata node, List annotations) { - if (node instanceof DartFieldDefinition) { - DartFieldDefinition fieldDefinition = (DartFieldDefinition) node; - List fields = fieldDefinition.getFields(); - for (DartField field : fields) { - setMetadata(field, annotations); - } - return; - } - if (annotations != null && !annotations.isEmpty()) { - node.setMetadata(annotations); - if (node instanceof HasObsoleteMetadata) { - HasObsoleteMetadata declaration = (HasObsoleteMetadata) node; - for (int i = 0, size = annotations.size(); i < size; i++) { - DartAnnotation annotation = annotations.get(i); - DartExpression nameNode = annotation.getName(); - if (nameNode instanceof DartIdentifier) { - String name = ((DartIdentifier) nameNode).getName(); - if (name.equals("deprecated")) { - declaration.setObsoleteMetadata(declaration.getObsoleteMetadata().makeDeprecated()); - } else if (name.equals("override")) { - declaration.setObsoleteMetadata(declaration.getObsoleteMetadata().makeOverride()); - } - } - } - } - } - } - - private boolean looksLikeDirective() { - if (!isBuiltInSpecial()) { - return false; - } - switch(peek(0)) { - case LIBRARY: - case IMPORT: - case SOURCE: - case RESOURCE: - case NATIVE: - return true; - } - return peekPseudoKeyword(0, LIBRARY_KEYWORD) || peekPseudoKeyword(0, IMPORT_KEYWORD) || peekPseudoKeyword(0, PART_KEYWORD); - } - - /** - * 'interface' and 'typedef' are valid to use as names of fields and methods, so you can't - * just blindly recover when you see them in any context. This does a further test to make - * sure they are followed by another identifier. This would be illegal as a field or method - * definition, as you cannot use 'interface' or 'typedef' as a type name. - */ - private boolean looksLikeTopLevelKeyword() { - if (peek(0).equals(Token.CLASS)) { - return true; - } - if (peekPseudoKeyword(0, INTERFACE_KEYWORD) - && peek(1).equals(Token.IDENTIFIER)) { - return true; - } else if (peekPseudoKeyword(0, TYPEDEF_KEYWORD) - && (peek(1).equals(Token.IDENTIFIER) || peek(1).equals(Token.VOID))) { - return true; - } - return false; - } - - /** - * A version of the parser which only parses the directives of a library. - * - * TODO(jbrosenberg): consider parsing the whole file here, in order to avoid - * duplicate work. Probably requires removing use of LibraryUnit's, etc. - * Also, this minimal parse does have benefit in the incremental compilation - * case. - */ - @SuppressWarnings("deprecation") - public LibraryUnit preProcessLibraryDirectives(LibrarySource source) { - beginCompilationUnit(); - LibraryUnit libUnit = new LibraryUnit(source); - parseMetadata(); - if (peekPseudoKeyword(0, LIBRARY_KEYWORD)) { - DartLibraryDirective libraryDirective = parseLibraryDirective(); - libUnit.setName(libraryDirective.getLibraryName()); - parseMetadata(); - } - while (peekPseudoKeyword(0, IMPORT_KEYWORD) || peekPseudoKeyword(0, EXPORT_KEYWORD)) { - if (peekPseudoKeyword(0, IMPORT_KEYWORD)) { - DartImportDirective importDirective = parseImportDirective(); - LibraryNode importPath = new LibraryNode(importDirective); - importPath.setSourceInfo(importDirective.getSourceInfo()); - libUnit.addImportPath(importPath); - } - if (peekPseudoKeyword(0, EXPORT_KEYWORD)) { - DartExportDirective exportDirective = parseExportDirective(); - LibraryNode importPath = new LibraryNode(exportDirective); - importPath.setSourceInfo(exportDirective.getSourceInfo()); - libUnit.addExportPath(importPath); - } - parseMetadata(); - } - while (peekPseudoKeyword(0, PART_KEYWORD)) { - if (peekPseudoKeyword(1, OF_KEYWORD)) { - parsePartOfDirective(); - } else { - DartSourceDirective sourceDirective = parsePartDirective(); - LibraryNode sourcePath = new LibraryNode(sourceDirective.getSourceUri().getValue()); - sourcePath.setSourceInfo(sourceDirective.getSourceInfo()); - libUnit.addSourcePath(sourcePath); - } - parseMetadata(); - } - // - // The code below is obsolete. We do not make any effort to find duplications between the old - // and the new syntax because support for the old syntax will be removed very soon. - // - if (peek(0) == Token.LIBRARY) { - beginLibraryDirective(); - DartLibraryDirective libDirective = done(parseObsoleteLibraryDirective()); - libUnit.setName(libDirective.getLibraryName()); - parseMetadata(); - } - while (peek(0) == Token.IMPORT) { - beginImportDirective(); - DartImportDirective importDirective = done(parseObsoleteImportDirective()); - LibraryNode importPath; - if (importDirective.getOldPrefix() != null) { - importPath = - new LibraryNode(importDirective); - } else { - importPath = new LibraryNode(importDirective.getLibraryUri().getValue()); - } - importPath.setSourceInfo(importDirective.getSourceInfo()); - libUnit.addImportPath(importPath); - parseMetadata(); - } - while (peek(0) == Token.SOURCE) { - beginSourceDirective(); - DartSourceDirective sourceDirective = done(parseSourceDirective()); - LibraryNode sourcePath = new LibraryNode(sourceDirective.getSourceUri().getValue()); - sourcePath.setSourceInfo(sourceDirective.getSourceInfo()); - libUnit.addSourcePath(sourcePath); - parseMetadata(); - } - while (peek(0) == Token.RESOURCE) { - parseResourceDirective(); - parseMetadata(); - } - while (peek(0) == Token.NATIVE) { - beginNativeDirective(); - DartNativeDirective nativeDirective = done(parseNativeDirective()); - LibraryNode nativePath = new LibraryNode(nativeDirective.getNativeUri().getValue()); - nativePath.setSourceInfo(nativeDirective.getSourceInfo()); - libUnit.addNativePath(nativePath); - parseMetadata(); - } - - // add ourselves to the list of sources, so inline dart code will be parsed - libUnit.addSourcePath(libUnit.getSelfSourcePath()); - return done(libUnit); - } - - private List parseDirectives(DartUnit unit, List metadata) { - boolean hasLibraryDirective = false; - if (peekPseudoKeyword(0, LIBRARY_KEYWORD)) { - DartLibraryDirective libraryDirective = parseLibraryDirective(); - for (DartDirective directive : unit.getDirectives()) { - if (directive instanceof DartLibraryDirective) { - reportError(position(), ParserErrorCode.ONLY_ONE_LIBRARY_DIRECTIVE); - break; - } - } - unit.getDirectives().add(libraryDirective); - hasLibraryDirective = true; - setMetadata(libraryDirective, metadata); - metadata = parseMetadata(); - } - while (peekPseudoKeyword(0, IMPORT_KEYWORD) || peekPseudoKeyword(0, EXPORT_KEYWORD)) { - if (peekPseudoKeyword(0, IMPORT_KEYWORD)) { - DartImportDirective importDirective = parseImportDirective(); - unit.getDirectives().add(importDirective); - setMetadata(importDirective, metadata); - metadata = parseMetadata(); - } else { - DartExportDirective exportDirective = parseExportDirective(); - unit.getDirectives().add(exportDirective); - if (!hasLibraryDirective) { - reportError(exportDirective, ParserErrorCode.EXPORT_WITHOUT_LIBRARY_DIRECTIVE); - } - setMetadata(exportDirective, metadata); - metadata = parseMetadata(); - } - } - while (peekPseudoKeyword(0, PART_KEYWORD)) { - if (peekPseudoKeyword(1, OF_KEYWORD)) { - DartPartOfDirective partOfDirective = parsePartOfDirective(); - unit.getDirectives().add(partOfDirective); - setMetadata(partOfDirective, metadata); - metadata = parseMetadata(); - } else { - DartSourceDirective partDirective = parsePartDirective(); - unit.getDirectives().add(partDirective); - setMetadata(partDirective, metadata); - metadata = parseMetadata(); - } - } - // - // The code below is obsolete. We do not make any effort to find duplications between the old - // and the new syntax because support for the old syntax will be removed very soon. - // - if (peek(0) == Token.LIBRARY) { - beginLibraryDirective(); - DartLibraryDirective libraryDirective = parseObsoleteLibraryDirective(); - for (DartDirective directive : unit.getDirectives()) { - if (directive instanceof DartLibraryDirective) { - reportError(position(), ParserErrorCode.ONLY_ONE_LIBRARY_DIRECTIVE); - break; - } - } - unit.getDirectives().add(libraryDirective); - done(libraryDirective); - setMetadata(libraryDirective, metadata); - metadata = parseMetadata(); - } - while (peek(0) == Token.IMPORT) { - beginImportDirective(); - DartImportDirective importDirective = parseObsoleteImportDirective(); - unit.getDirectives().add(done(importDirective)); - setMetadata(importDirective, metadata); - metadata = parseMetadata(); - } - while (peek(0) == Token.SOURCE) { - beginSourceDirective(); - DartSourceDirective sourceDirective = parseSourceDirective(); - unit.getDirectives().add(done(sourceDirective)); - setMetadata(sourceDirective, metadata); - metadata = parseMetadata(); - } - while (peek(0) == Token.RESOURCE) { - parseResourceDirective(); - } - while (peek(0) == Token.NATIVE) { - beginNativeDirective(); - DartNativeDirective nativeDirective = parseNativeDirective(); - unit.getDirectives().add(done(nativeDirective)); - setMetadata(nativeDirective, metadata); - metadata = parseMetadata(); - } - return metadata; - } - - private DartLibraryDirective parseLibraryDirective() { - beginLibraryDirective(); - next(); // "library" - DartExpression libraryName = parseLibraryName(); - expect(Token.SEMICOLON); - return done(new DartLibraryDirective(libraryName)); - } - - private DartExpression parseLibraryName() { - beginQualifiedIdentifier(); - DartExpression libraryName = parseIdentifier(); - while (optional(Token.PERIOD)) { - beginQualifiedIdentifier(); - DartIdentifier identifier = parseIdentifier(); - libraryName = done(new DartPropertyAccess(libraryName, identifier)); - } - return done(libraryName); - } - - private DartLibraryDirective parseObsoleteLibraryDirective() { - expect(Token.LIBRARY); - reportDeprecatedError(position(), ParserErrorCode.DEPRECATED_LIBRARY_DIRECTIVE); - expect(Token.LPAREN); - beginLiteral(); - expect(Token.STRING); - DartStringLiteral libname = done(DartStringLiteral.get(ctx.getTokenString())); - expectCloseParen(); - expect(Token.SEMICOLON); - return new DartLibraryDirective(libname); - } - - protected DartExportDirective parseExportDirective() { - beginExportDirective(); - next(); // "export" - DartStringLiteral libUri = parseUri(); - - List combinators = new ArrayList(); - while (peekPseudoKeyword(0, HIDE_KEYWORD) || peekPseudoKeyword(0, SHOW_KEYWORD)) { - beginImportCombinator(); - if (optionalPseudoKeyword(HIDE_KEYWORD)) { - List hiddenNames = parseIdentifierList(); - combinators.add(done(new ImportHideCombinator(hiddenNames))); - } else if (optionalPseudoKeyword(SHOW_KEYWORD)) { - List shownNames = parseIdentifierList(); - combinators.add(done(new ImportShowCombinator(shownNames))); - } - } - - if (!optional(Token.SEMICOLON)) { - // If there is no semicolon, then we probably don't want to consume the next token. It might - // make sense to advance to the next valid token for a directive or top-level declaration, but - // our recovery mechanism isn't quite sophisticated enough for that. - reportUnexpectedToken(position(), Token.SEMICOLON, peek(0)); - } - return done(new DartExportDirective(libUri, combinators)); - } - - protected DartImportDirective parseImportDirective() { - beginImportDirective(); - next(); // "import" - DartStringLiteral libUri = parseUri(); - // allow "native" if we have "dart-ext:" import - if (StringUtils.startsWith(libUri.getValue(), "dart-ext:")) { - allowNativeKeyword = true; - } - - DartIdentifier prefix = null; - if (peek(0) == Token.IDENTIFIER && "as".equals(ctx.peekTokenString(0))) { - ctx.advance(); - prefix = parseIdentifier(); - if (prefix instanceof DartSyntheticErrorIdentifier) { - if (peekPseudoKeyword(1, HIDE_KEYWORD) || peekPseudoKeyword(1, SHOW_KEYWORD) - || peek(1) == Token.BIT_AND || peek(1) == Token.COLON) { - next(); - } - } - } - - List combinators = new ArrayList(); - while (peekPseudoKeyword(0, HIDE_KEYWORD) || peekPseudoKeyword(0, SHOW_KEYWORD)) { - if (optionalPseudoKeyword(HIDE_KEYWORD)) { - List hiddenNames = parseIdentifierList(); - combinators.add(new ImportHideCombinator(hiddenNames)); - } else if (optionalPseudoKeyword(SHOW_KEYWORD)) { - List shownNames = parseIdentifierList(); - combinators.add(new ImportShowCombinator(shownNames)); - } - } - - if (!optional(Token.SEMICOLON)) { - // If there is no semicolon, then we probably don't want to consume the next token. It might - // make sense to advance to the next valid token for a directive or top-level declaration, but - // our recovery mechanism isn't quite sophisticated enough for that. - reportUnexpectedToken(position(), Token.SEMICOLON, peek(0)); - } - return done(new DartImportDirective(libUri, prefix, combinators)); - } - - /** - * Parse a comma-separated list of identifiers. - * - * @return the identifiers that were parsed - */ - private List parseIdentifierList() { - ArrayList identifiers = new ArrayList(); - identifiers.add(parseIdentifier()); - while (optional(Token.COMMA)) { - identifiers.add(parseIdentifier()); - } - return identifiers; - } - - protected DartImportDirective parseObsoleteImportDirective() { - expect(Token.IMPORT); - reportDeprecatedError(position(), ParserErrorCode.DEPRECATED_IMPORT_DIRECTIVE); - expect(Token.LPAREN); - - DartStringLiteral libUri = parseUri(); - - // allow "native" if we have "dart-ext:" import - if (StringUtils.startsWith(libUri.getValue(), "dart-ext:")) { - allowNativeKeyword = true; - } - - DartBooleanLiteral export = null; - List combinators = new ArrayList(); - DartStringLiteral prefix = null; - if (optional(Token.COMMA)) { - if (optionalPseudoKeyword(PREFIX_KEYWORD)) { - expect(Token.COLON); - beginLiteral(); - expect(Token.STRING); - String id = ctx.getTokenString(); - // The specification requires the value of this string be a valid identifier - if(id == null || !id.matches("[_a-zA-Z]([_A-Za-z0-9]*)")) { - reportError(position(), ParserErrorCode.EXPECTED_PREFIX_IDENTIFIER); - } - prefix = done(DartStringLiteral.get(ctx.getTokenString())); - } else { - reportError(position(), ParserErrorCode.EXPECTED_PREFIX_KEYWORD); - } - } - expectCloseParen(); - expect(Token.SEMICOLON); - return new DartImportDirective(libUri, export, combinators, prefix); - } - - private DartSourceDirective parsePartDirective() { - beginPartDirective(); - next(); // "part" - beginLiteral(); - expect(Token.STRING); - DartStringLiteral partUri = done(DartStringLiteral.get(ctx.getTokenString())); - expect(Token.SEMICOLON); - return done(new DartSourceDirective(partUri)); - } - - private DartSourceDirective parseSourceDirective() { - expect(Token.SOURCE); - reportDeprecatedError(position(), ParserErrorCode.DEPRECATED_SOURCE_DIRECTIVE); - expect(Token.LPAREN); - DartStringLiteral sourceUri = parseUri(); - expectCloseParen(); - expect(Token.SEMICOLON); - return new DartSourceDirective(sourceUri); - } - - private DartPartOfDirective parsePartOfDirective() { - beginPartOfDirective(); - next(); // "part" - next(); // "of" - int ofOffset= position(); - DartExpression libraryName = parseLibraryName(); - expect(Token.SEMICOLON); - return done(new DartPartOfDirective(ofOffset, libraryName)); - } - - private void parseResourceDirective() { - expect(Token.RESOURCE); - reportError(position(), ParserErrorCode.DEPRECATED_RESOURCE_DIRECTIVE); - expect(Token.LPAREN); - @SuppressWarnings("unused") - DartStringLiteral sourceUri = parseUri(); - expectCloseParen(); - expect(Token.SEMICOLON); - } - - private DartNativeDirective parseNativeDirective() { - expect(Token.NATIVE); - expect(Token.LPAREN); - DartStringLiteral nativeUri = parseUri(); - expect(Token.RPAREN); - expect(Token.SEMICOLON); - return new DartNativeDirective(nativeUri); - } - - private List parseMetadata() { - List metadata = new ArrayList(); - while (match(Token.AT)) { - beginMetadata(); - next(); - beginQualifiedIdentifier(); - DartExpression name = parseQualified(true); - if (optional(Token.PERIOD)) { - name = new DartPropertyAccess(name, parseIdentifier()); - } - done(name); - List arguments = null; - if (match(Token.LPAREN)) { - arguments = parseArguments(); - } - metadata.add(done(new DartAnnotation(name, arguments))); - } - return metadata; - } - - /** - *
-   * typeParameter
-   *     : identifier (EXTENDS type)?
-   *     ;
-   *
-   * typeParameters
-   *     : '<' typeParameter (',' typeParameter)* '>'
-   *     ;
-   * 
- */ - @Terminals(tokens={Token.GT, Token.COMMA}) - private List parseTypeParameters() { - List types = new ArrayList(); - expect(Token.LT); - do { - DartTypeParameter typeParameter = parseTypeParameter(); - types.add(typeParameter); - - } while (optional(Token.COMMA)); - expect(Token.GT); - return types; - } - - /** - * Parses single {@link DartTypeParameter} for {@link #parseTypeParameters()}. - */ - private DartTypeParameter parseTypeParameter() { - beginTypeParameter(); - List metadata = parseMetadata(); - DartIdentifier name = parseIdentifier(); - if (PSEUDO_KEYWORDS_SET.contains(name.getName())) { - reportError(name, ParserErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE_VARIABLE_NAME); - } - // Try to parse bound. - DartTypeNode bound = null; - if (peek(0) != Token.EOS && peek(0) != Token.COMMA && peek(0) != Token.GT) { - if (optional(Token.EXTENDS)) { - // OK, this is EXTENDS, parse type. - bound = parseTypeAnnotation(); - } else if (looksLikeTopLevelKeyword()) { - return done(new DartTypeParameter(name, bound)); - } else if (peek(0) == Token.IDENTIFIER && (peek(1) == Token.COMMA || peek(1) == Token.GT)) { - // - // User tries to type "extends", but it is not finished yet. - // Report problem and try to continue. - next(); - reportError(position(), ParserErrorCode.EXPECTED_EXTENDS); - } else if (peek(0) == Token.IDENTIFIER - && peek(1) == Token.IDENTIFIER - && (peek(2) == Token.COMMA || peek(2) == Token.GT)) { - // - // User mistyped word "extends" or it is not finished yet. - // Report problem and try to continue. - next(); - reportError(position(), ParserErrorCode.EXPECTED_EXTENDS); - bound = parseTypeAnnotation(); - } else { - // Something else, restart parsing from next top level element. - next(); - reportError(position(), ParserErrorCode.EXPECTED_EXTENDS); - } - } - // Ready to create DartTypeParameter. - DartTypeParameter parameter = new DartTypeParameter(name, bound); - parameter.setMetadata(metadata); - return done(parameter); - } - - private List parseTypeParametersOpt() { - return (peek(0) == Token.LT) - ? parseTypeParameters() - : Collections.emptyList(); - } - - /** - *
-   * classDefinition
-   *     : CLASS identifier typeParameters? superclass? interfaces?
-   *       '{' classMemberDefinition* '}'
-   *     ;
-   *
-   * superclass
-   *     : EXTENDS type
-   *     ;
-   *
-   * interfaces
-   *     : IMPLEMENTS typeList
-   *     ;
-   *
-   * superinterfaces
-   *     : EXTENDS typeList
-   *     ;
-   *
-   * classMemberDefinition
-   *     : declaration ';'
-   *     | methodDeclaration blockOrNative
-   *
-   * interfaceDefinition
-   *     : INTERFACE identifier typeParameters? superinterfaces?
-   *       (DEFAULT type)? '{' (interfaceMemberDefinition)* '}'
-   *     ;
-   * 
- */ - private DartDeclaration parseClass() { - beginClassBody(); - - int tokenOffset = ctx.getTokenLocation().getBegin(); - int tokenLength = ctx.getTokenLocation().getEnd() - tokenOffset; - - // Parse modifiers. - Modifiers modifiers = Modifiers.NONE; - if (isTopLevelAbstract) { - modifiers = modifiers.makeAbstract(); - } - - DartIdentifier name = parseIdentifier(); - if (name.getName().equals("")) { - // something went horribly wrong. - if (peek(0).equals(Token.LBRACE)) { - parseBlock(); - } - return done(null); - } - if (PSEUDO_KEYWORDS_SET.contains(name.getName())) { - reportError(name, ParserErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE_NAME); - } - List typeParameters = parseTypeParametersOpt(); - - // Parse the extends and implements clauses. - DartTypeNode superType = null; - int withOffset = -1; - int implementsOffset = -1; - List mixins = null; - List interfaces = null; - if (isParsingInterface) { - if (optional(Token.EXTENDS)) { - interfaces = parseTypeAnnotationList(); - } - } else { - boolean foundClause = true; - while (foundClause) { - if (optional(Token.EXTENDS)) { - if (mixins != null) { - reportErrorAtPosition(withOffset, withOffset + "with".length(), - ParserErrorCode.WITH_BEFORE_EXTENDS); - } - if (interfaces != null) { - reportErrorAtPosition(implementsOffset, implementsOffset + "implements".length(), - ParserErrorCode.IMPLEMENTS_BEFORE_EXTENDS); - } - if (superType == null) { - superType = parseTypeAnnotation(); - } else { - reportError(position(), ParserErrorCode.MULTIPLE_EXTENDS_CLAUSES); - parseTypeAnnotation(); - } - } else if (optional(Token.WITH)) { - if (mixins == null) { - withOffset = position(); - mixins = parseTypeAnnotationList(); - if (interfaces != null) { - reportErrorAtPosition(implementsOffset, implementsOffset + "implements".length(), - ParserErrorCode.IMPLEMENTS_BEFORE_WITH); - } - } else { - reportError(position(), ParserErrorCode.MULTIPLE_WITH_CLAUSES); - parseTypeAnnotationList(); - } - } else if (optionalPseudoKeyword(IMPLEMENTS_KEYWORD)) { - if (interfaces == null) { - implementsOffset = position(); - interfaces = parseTypeAnnotationList(); - } else { - reportError(position(), ParserErrorCode.MULTIPLE_IMPLEMENTS_CLAUSES); - parseTypeAnnotationList(); - } - } else { - foundClause = false; - } - } - if (mixins != null && superType == null) { - reportErrorAtPosition(withOffset, withOffset + "with".length(), - ParserErrorCode.WITH_WITHOUT_EXTENDS); - } - } - - // Deal with factory clause for interfaces. - DartParameterizedTypeNode defaultClass = null; - int defaultTokenOffset = -1; - if (isParsingInterface && - (optionalDeprecatedFactory() || optional(Token.DEFAULT))) { - defaultTokenOffset = position(); - beginTypeAnnotation(); - DartExpression qualified = parseQualified(false); - List defaultTypeParameters = parseTypeParametersOpt(); - defaultClass = doneWithoutConsuming(new DartParameterizedTypeNode(qualified, - defaultTypeParameters)); - } - - // Deal with native clause for classes. - DartStringLiteral nativeName = null; - if (optionalPseudoKeyword(NATIVE_KEYWORD)) { - if (isParsingInterface) { - reportError(position(), ParserErrorCode.NATIVE_ONLY_CLASS); - } - if (!allowNativeKeyword) { - reportError(position(), ParserErrorCode.NATIVE_ONLY_CORE_LIB); - } - beginLiteral(); - if (expect(Token.STRING)) { - nativeName = done(DartStringLiteral.get(ctx.getTokenString())); - } - modifiers = modifiers.makeNative(); - } - - // Parse the members. - int openBraceOffset = -1; - int closeBraceOffset = -1; - List members = new ArrayList(); - if (optional(Token.LBRACE)) { - openBraceOffset = ctx.getTokenLocation().getBegin(); - parseClassOrInterfaceBody(members); - expectCloseBrace(true); - closeBraceOffset = ctx.getTokenLocation().getBegin(); - } else { - reportErrorWithoutAdvancing(ParserErrorCode.EXPECTED_CLASS_DECLARATION_LBRACE); - } - - if (isParsingInterface) { - return done(new DartClass(tokenOffset, tokenLength, name, null, superType, implementsOffset, - interfaces, mixins, defaultTokenOffset, openBraceOffset, closeBraceOffset, members, - typeParameters, defaultClass, true, Modifiers.NONE)); - } else { - return done(new DartClass(tokenOffset, tokenLength, name, nativeName, superType, - implementsOffset, interfaces, mixins, defaultTokenOffset, openBraceOffset, - closeBraceOffset, members, typeParameters, null, false, modifiers)); - } - } - - /** - * Helper for {@link #parseClass()}. - * - * classMemberDefinition* - */ - @Terminals(tokens={Token.RBRACE, Token.SEMICOLON}) - private void parseClassOrInterfaceBody(List members) { - while (!match(Token.RBRACE) && !EOS() && !looksLikeTopLevelKeyword()) { - List metadata = parseMetadata(); - DartNodeWithMetadata member = parseFieldOrMethod(true); - if (member != null) { - setMetadata(member, metadata); - members.add(member); - } - // Recover at a semicolon - if (optional(Token.SEMICOLON)) { - reportUnexpectedToken(position(), null, Token.SEMICOLON); - } - } - } - - private boolean optionalDeprecatedFactory() { - if (optionalPseudoKeyword(FACTORY_KEYWORD)) { - reportError(position(), ParserErrorCode.DEPRECATED_USE_OF_FACTORY_KEYWORD); - return true; - } - return false; - } - - private List parseTypeAnnotationList() { - List result = new ArrayList(); - do { - result.add(parseTypeAnnotation()); - } while (optional(Token.COMMA)); - return result; - } - - /** - * Look ahead to detect if we are seeing ident [ TypeParameters ] "(". - * We need this lookahead to distinguish between the optional return type - * and the alias name of a function type alias. - * Token position remains unchanged. - * - * @return true if the next tokens should be parsed as a type - */ - private boolean isFunctionTypeAliasName() { - beginFunctionTypeInterface(); - try { - if (peek(0) == Token.IDENTIFIER && peek(1) == Token.LPAREN) { - return true; - } - if (peek(0) == Token.IDENTIFIER && peek(1) == Token.LT) { - consume(Token.IDENTIFIER); - // isTypeParameter leaves the position advanced if it matches - if (isTypeParameter() && peek(0) == Token.LPAREN) { - return true; - } - } - return false; - } finally { - rollback(); - } - } - - /** - * Returns true if the current and next tokens can be parsed as type - * parameters. Current token position is not saved and restored. - */ - private boolean isTypeParameter() { - if (peek(0) == Token.LT) { - // We are possibly looking at type parameters. Find closing ">". - consume(Token.LT); - int nestingLevel = 1; - while (nestingLevel > 0) { - switch (peek(0)) { - case LT: - nestingLevel++; - break; - case GT: - nestingLevel--; - break; - case SAR: // >> - nestingLevel -= 2; - break; - case COMMA: - case EXTENDS: - case IDENTIFIER: - break; - default: - // We are looking at something other than type parameters. - return false; - } - next(); - if (nestingLevel < 0) { - return false; - } - } - } - return true; - } - - /** - * Parse a type alias. - * - *
-   * typeAlias ::=
-   *     'typedef' typeAliasBody
-   * 
-   * typeAliasBody ::=
-   *     classTypeAlias
-   *   | functionTypeAlias
-   *
-   * classTypeAlias ::=
-   *     identifier typeParameters? '=' 'abstract'? mixinApplication
-   * 
-   * mixinApplication ::=
-   *     qualified withClause implementsClause? ';'
-   *
-   * functionTypeAlias ::=
-   *     functionPrefix typeParameterList? formalParameterList ';'
-   *
-   * functionPrefix ::=
-   *     returnType? name
-   * 
- * - * @return the type alias that was parsed - */ - private DartNodeWithMetadata parseTypeAlias() { - if (match(Token.IDENTIFIER)) { - Token next = peek(1); - if (next == Token.LT) { - int offset = skipTypeArguments(1, new DepthCounter()); - next = peek(offset); - if (next != null && next == Token.ASSIGN) { - return parseClassTypeAlias(); - } - } else if (next == Token.ASSIGN) { - return parseClassTypeAlias(); - } - } - return parseFunctionTypeAlias(); - } - - /** - * Parse a class type alias. - * - *
-   * classTypeAlias ::=
-   *     identifier typeParameters? '=' 'abstract'? mixinApplication
-   * 
-   * mixinApplication ::=
-   *     type withClause implementsClause? ';'
-   * 
- * - * @return the class type alias that was parsed - */ - private DartClassTypeAlias parseClassTypeAlias() { - beginClassTypeInterface(); - - DartIdentifier name = parseIdentifier(); - if (PSEUDO_KEYWORDS_SET.contains(name.getName())) { - reportError(name, ParserErrorCode.BUILT_IN_IDENTIFIER_AS_TYPEDEF_NAME); - } - List typeParameters = parseTypeParametersOpt(); - - expect(Token.ASSIGN); - - Modifiers modifiers = Modifiers.NONE; - if (optionalPseudoKeyword(ABSTRACT_KEYWORD)) { - modifiers = modifiers.makeAbstract(); - } - - DartTypeNode superType = parseTypeAnnotation(); - - List mixins = null; - if (optional(Token.WITH)) { - mixins = parseTypeAnnotationList(); - } - - List interfaces = null; - if (optionalPseudoKeyword(IMPLEMENTS_KEYWORD)) { - interfaces = parseTypeAnnotationList(); - } - - expect(Token.SEMICOLON); - return done(new DartClassTypeAlias(name, typeParameters, modifiers, superType, mixins, - interfaces)); - } - - /** - * Parse a function type alias. - * - *
-   * functionTypeAlias ::=
-   *     functionPrefix typeParameterList? formalParameterList ';'
-   *
-   * functionPrefix ::=
-   *     returnType? name
-   * 
- * - * @return the function type alias that was parsed - */ - private DartFunctionTypeAlias parseFunctionTypeAlias() { - beginFunctionTypeInterface(); - - DartTypeNode returnType = null; - if (peek(0) == Token.VOID) { - returnType = parseVoidType(); - } else if (!isFunctionTypeAliasName()) { - returnType = parseTypeAnnotation(); - } - - DartIdentifier name = parseIdentifier(); - if (PSEUDO_KEYWORDS_SET.contains(name.getName())) { - reportError(name, ParserErrorCode.BUILT_IN_IDENTIFIER_AS_TYPEDEF_NAME); - } - - List typeParameters = parseTypeParametersOpt(); - FormalParameters params = parseFormalParameterList(); - expect(Token.SEMICOLON); - validateNoDefaultParameterValues( - params.val, - ParserErrorCode.DEFAULT_VALUE_CAN_NOT_BE_SPECIFIED_IN_TYPEDEF); - - return done(new DartFunctionTypeAlias(name, returnType, params.val, typeParameters)); - } - - /** - * Parse a field or method, which may be inside a class or at the top level. - * - *
-   * // This rule is organized in a way that may not be most readable, but
-   * // gives the best error messages.
-   * classMemberDefinition
-   *     : declaration ';'
-   *     | methodDeclaration bodyOrNative
-   *     ;
-   *
-   * // Note: this syntax is not official, but used in dart_interpreter. It
-   * // is unlikely that Dart will support numbered natives.
-   * bodyOrNative
-   *     : error=NATIVE (':' (STRING | RATIONAL_NUMBER))? ';'
-   *       { legacy($error, "native not supported (yet)"); }
-   *     | functionStatementBody
-   *     ;
-   *
-   * // A method, operator, or constructor (which all should be followed by
-   * // a function body).
-   * methodDeclaration
-   *     : factoryConstructorDeclaration
-   *     | STATIC methodOrConstructorDeclaration
-   *     | specialSignatureDefinition
-   *     | methodOrConstructorDeclaration initializers?
-   *     | namedConstructorDeclaration initializers?
-   *     ;
-   *
-   *
-   * // An abstract method/operator, a field, or const constructor (which
-   * // all should be followed by a semicolon).
-   * declaration
-   *     : constantConstructorDeclaration initializers?
-   *     | ABSTRACT specialSignatureDefinition
-   *     | ABSTRACT methodOrConstructorDeclaration
-   *     | STATIC CONST type? staticConstDeclarationList
-   *     | STATIC? variableDeclaration
-   *     ;
-   *
-   * interfaceMemberDefinition
-   *     : STATIC CONST type? initializedIdentifierList ';'
-   *     | methodOrConstructorDeclaration ';'
-   *     | constantConstructorDeclaration ';'
-   *     | namedConstructorDeclaration ';'
-   *     | specialSignatureDefinition ';'
-   *     | variableDeclaration ';'
-   *     ;
-   *
-   * variableDeclaration
-   *     : constVarOrType identifierList
-   *     ;
-   *
-   * methodOrConstructorDeclaration
-   *     : typeOrFunction? identifier formalParameterList
-   *     ;
-   *
-   * factoryConstructorDeclaration
-   *     : FACTORY qualified ('.' identifier)? formalParameterList
-   *     ;
-   *
-   * namedConstructorDeclaration
-   *     : identifier typeArguments? '.' identifier formalParameterList
-   *     ;
-   *
-   * constructorDeclaration
-   *     : identifier typeArguments? formalParameterList
-   *     | namedConstructorDeclaration
-   *     ;
-   *
-   * constantConstructorDeclaration
-   *     : CONST qualified formalParameterList
-   *     ;
-   *
-   * specialSignatureDefinition
-   *     : STATIC? type? getOrSet identifier formalParameterList
-   *     | type? OPERATOR operator formalParameterList
-   *     ;
-   *
-   * getOrSet
-   *     : GET
-   *     | SET
-   *     ;
-   *
-   * operator
-   *     : unaryOperator
-   *     | binaryOperator
-   *     | '[' ']' { "[]".equals($text) }?
-   *     | '[' ']' '=' { "[]=".equals($text) }?
-   *     | NEGATE
-   *     | CALL
-   *     ;
-   * 
- * - * @param allowStatic true if the static modifier is allowed - * @return a {@link DartNode} representing the grammar fragment above - */ - @Terminals(tokens={Token.SEMICOLON}) - private DartNodeWithMetadata parseFieldOrMethod(boolean allowStatic) { - beginClassMember(); - Modifiers modifiers = Modifiers.NONE; - if (isBuiltInSpecial() && optionalPseudoKeyword(EXTERNAL_KEYWORD)) { - modifiers = modifiers.makeExternal(); - } - if (isBuiltInSpecial() && optionalPseudoKeyword(STATIC_KEYWORD)) { - if (!allowStatic) { - reportError(position(), ParserErrorCode.TOP_LEVEL_CANNOT_BE_STATIC); - } else { - if (isParsingInterface - && peek(0) != Token.FINAL && peek(0) != Token.CONST) { - reportError(position(), ParserErrorCode.NON_FINAL_STATIC_MEMBER_IN_INTERFACE); - } - modifiers = modifiers.makeStatic(); - } - } - if (isBuiltInSpecial() && optionalPseudoKeyword(ABSTRACT_KEYWORD)) { - if (modifiers.isStatic()) { - reportError(position(), ParserErrorCode.STATIC_MEMBERS_CANNOT_BE_ABSTRACT); - } - if (modifiers.isExternal()) { - reportError(position(), ParserErrorCode.EXTERNAL_ABSTRACT); - } - modifiers = modifiers.makeAbstract(); - } - if (isBuiltInSpecial() && optionalPseudoKeyword(FACTORY_KEYWORD)) { - if (isParsingInterface) { - reportError(position(), ParserErrorCode.FACTORY_MEMBER_IN_INTERFACE); - } - if (modifiers.isStatic()) { - reportError(position(), ParserErrorCode.FACTORY_CANNOT_BE_STATIC); - } - if (modifiers.isAbstract()) { - reportError(position(), ParserErrorCode.FACTORY_CANNOT_BE_ABSTRACT); - } - - modifiers = modifiers.makeFactory(); - } - - if (match(Token.VAR) || match(Token.FINAL)) { - if (modifiers.isAbstract()) { - reportError(position(), ParserErrorCode.DISALLOWED_ABSTRACT_KEYWORD); - } - if (modifiers.isFactory()) { - reportError(position(), ParserErrorCode.DISALLOWED_FACTORY_KEYWORD); - } - } - - // report "abstract" warning after all other checks to don't hide error with warning - // we ignore problems if there was already reported problem after given position - if (modifiers.isAbstract()) { - reportError(position(), ParserErrorCode.DEPRECATED_ABSTRACT_METHOD); - } - - if (modifiers.isFactory()) { - if (!isParsingClass) { - reportError(position(), ParserErrorCode.FACTORY_CANNOT_BE_TOP_LEVEL); - } - // Do parse factory. - DartMethodDefinition factoryNode = parseFactory(modifiers); - // If factory is not allowed, ensure that it is valid as method. - DartExpression actualName = factoryNode.getName(); - if (!allowStatic && !(actualName instanceof DartIdentifier)) { - DartExpression replacementName = new DartIdentifier(actualName.toString()); - factoryNode.setName(replacementName); - } - // Done. - return done(factoryNode); - } - - final DartNodeWithMetadata member; - - switch (peek(0)) { - case VAR: { - consume(Token.VAR); - // Check for malformed method starting with 'var' : var ^ foo() { } - if (peek(0).equals(Token.IDENTIFIER) && looksLikeMethodOrAccessorDefinition()) { - reportError(position(), ParserErrorCode.VAR_IS_NOT_ALLOWED_ON_A_METHOD_DEFINITION); - member = parseMethodOrAccessor(modifiers, null); - break; - } - - member = parseFieldDeclaration(modifiers, null); - expectStatmentTerminator(); - break; - } - - case CONST: { - consume(Token.CONST); - modifiers = modifiers.makeConstant(); - // Allow "const factory ... native" constructors for core libraries only - if (optionalPseudoKeyword(FACTORY_KEYWORD)) { - modifiers = modifiers.makeFactory(); - } - if (peek(0).equals(Token.IDENTIFIER) && looksLikeMethodOrAccessorDefinition()) { - return done(parseMethod(modifiers, null)); - } - // Try to find type, may be "const ^ Type field". - DartTypeNode type = null; - if (peek(1) != Token.COMMA - && peek(1) != Token.ASSIGN - && peek(1) != Token.SEMICOLON) { - type = parseTypeAnnotation(); - } - // Parse field. - modifiers = modifiers.makeFinal(); - member = parseFieldDeclaration(modifiers, type); - expectStatmentTerminator(); - break; - } - - case FINAL: { - consume(Token.FINAL); - modifiers = modifiers.makeFinal(); - - // Check for malformed method starting with 'final': final ^ foo() { } - if (peek(0).equals(Token.IDENTIFIER) && looksLikeMethodOrAccessorDefinition()) { - reportError(position(), ParserErrorCode.FINAL_IS_NOT_ALLOWED_ON_A_METHOD_DEFINITION); - member = parseMethodOrAccessor(modifiers, null); - break; - } - DartTypeNode type = null; - if (peek(1) != Token.COMMA - && peek(1) != Token.ASSIGN - && peek(1) != Token.SEMICOLON) { - type = parseTypeAnnotation(); - - // Check again for malformed method starting with 'final': final String ^ foo() { } - if (peek(0).equals(Token.IDENTIFIER) && looksLikeMethodOrAccessorDefinition()) { - reportError(position(), ParserErrorCode.FINAL_IS_NOT_ALLOWED_ON_A_METHOD_DEFINITION); - member = parseMethodOrAccessor(modifiers, null); - break; - } - } - member = parseFieldDeclaration(modifiers, type); - expectStatmentTerminator(); - break; - } - - case IDENTIFIER: { - - // Check to see if it looks like the start of a method definition (sans type). - if (looksLikeMethodOrAccessorDefinition()) { - member = parseMethodOrAccessor(modifiers, null); - break; - } - } - //$FALL-THROUGH$ - - case VOID: { - - // The next token may be a type specification or parameterized constructor: either a method or field. - boolean isVoidType = peek(0) == Token.VOID; - DartTypeNode type; - if (isVoidType) { - type = parseVoidType(); - } else { - int nameIndex = skipTypeName(0); - if (nameIndex < 0 || peek(nameIndex) != Token.IDENTIFIER) { - // There was no type name. - type = null; - } else { - type = parseTypeAnnotation(); - } - } - if (peek(1) == Token.SEMICOLON - || peek(1) == Token.COMMA - || peek(1) == Token.ASSIGN) { - if (modifiers.isAbstract()) { - reportError(position(), ParserErrorCode.INVALID_FIELD_DECLARATION); - } - member = parseFieldDeclaration(modifiers, type); - if (isVoidType) { - reportError(type, ParserErrorCode.VOID_FIELD); - } else if (!modifiers.isFinal() && type == null) { - reportError(position(), ParserErrorCode.INVALID_FIELD_DECLARATION); - } - expectStatmentTerminator(); - } else { - member = parseMethodOrAccessor(modifiers, type); - } - break; - } - - case SEMICOLON: - default: { - done(null); - reportUnexpectedToken(position(), null, next()); - member = null; - break; - } - } - return member; - } - - /** - * Returns true if the beginning of a method definition follows. - * - * This test is needed to disambiguate between a method that returns a type - * and a plain method. - * - * Assumes the next token has already been determined to be an identifier. - * - * The following constructs will match: - * - * : get ( - * | get identifier ( - * | set ( - * | set identifier ( - * | operator ( - * | operator ( - * | identifier ( - * | identifier DOT identifier ( - * | identifier DOT identifier DOT identifier ( - * - * @return true if the signature of a method has been found. No tokens are consumed. - */ - private boolean looksLikeMethodOrAccessorDefinition() { - assert (peek(0) == Token.IDENTIFIER ); - beginMethodName(); // begin() equivalent - try { - if (isBuiltInSpecial() && peekPseudoKeyword(0, OPERATOR_KEYWORD)) { - next(); - // Using 'operator' as a field name is valid - if (peek(0).equals(Token.SEMICOLON) || peek(0).equals(Token.ASSIGN)) { - return false; - } - // Using 'operator' as a method name is valid (but discouraged) - if (peek(0).equals(Token.LPAREN)) { - return true; - } - // operator call ( - if (peekPseudoKeyword(0, CALL_KEYWORD) && peek(1).equals(Token.LPAREN)) { - return true; - } - // TODO(zundel): Look for valid operator overload tokens. For now just assuming - // non-idents are good enough - // operator ??? ( - if (!(peek(0).equals(Token.IDENTIFIER) && peek(1).equals(Token.LPAREN))) { - return true; - } - if (peek(0).equals(Token.LBRACK) && peek(1).equals(Token.RBRACK)) { - // operator [] ( - if (peek(2).equals(Token.LPAREN)) { - return true; - } - // operator []= ( - if (peek(2).equals(Token.ASSIGN) && peek(3).equals(Token.LPAREN)) { - return true; - } - } - return false; - } - - if (peekPseudoKeyword(0, GETTER_KEYWORD) - || peekPseudoKeyword(0, SETTER_KEYWORD)) { - boolean isGetter = peekPseudoKeyword(0, GETTER_KEYWORD); - next(); - // Using 'get' or 'set' as a field name is valid - if (peek(0).equals(Token.SEMICOLON) || peek(0).equals(Token.ASSIGN)) { - return false; - } - // Using 'get' or 'set' as a method name is valid (but discouraged) - if (peek(0).equals(Token.LPAREN)) { - return true; - } - // normal case: get foo ( - if (peek(0).equals(Token.IDENTIFIER) && (isGetter || peek(1).equals(Token.LPAREN))) { - return true; - } - return false; - } - - consume(Token.IDENTIFIER); - - if (peek(0).equals(Token.PERIOD) && peek(1).equals(Token.IDENTIFIER)) { - consume(Token.PERIOD); - consume(Token.IDENTIFIER); - - if (peek(0).equals(Token.PERIOD) && peek(1).equals(Token.IDENTIFIER)) { - consume(Token.PERIOD); - consume(Token.IDENTIFIER); - } - } - - // next token should be LPAREN - return (peek(0).equals(Token.LPAREN)); - } finally { - rollback(); - } - } - - /** - *
-   * factoryConstructorDeclaration
-   *     : FACTORY qualified ('.' identifier)? formalParameterList
-   *     ;
-   * 
- */ - private DartMethodDefinition parseFactory(Modifiers modifiers) { - beginMethodName(); - DartExpression name = parseQualified(true); - if (optional(Token.PERIOD)) { - name = doneWithoutConsuming(new DartPropertyAccess(name, parseIdentifier())); - } - done(name); - FormalParameters formals = parseFormalParameterList(); - int parametersCloseParen = ctx.getTokenLocation().getBegin(); - - // Parse redirecting factory - if (match(Token.ASSIGN)) { - next(); - if (!modifiers.isFactory()) { - reportError(position(), ParserErrorCode.ONLY_FACTORIES_CAN_REDIRECT); - } - modifiers = modifiers.makeRedirectedConstructor(); - DartTypeNode redirectedTypeName = parseTypeAnnotationPossiblyFollowedByName(); - DartIdentifier redirectedConstructorName = null; - if (optional(Token.PERIOD)) { - redirectedConstructorName = parseIdentifier(); - } - expect(Token.SEMICOLON); - DartFunction function = doneWithoutConsuming(new DartFunction(formals.val, formals.openParen, - formals.optionalOpenOffset, formals.optionalCloseOffset, parametersCloseParen, null, null)); - return DartMethodDefinition.create(name, function, modifiers, redirectedTypeName, - redirectedConstructorName); - } - - DartFunction function; - if (peekPseudoKeyword(0, NATIVE_KEYWORD)) { - modifiers = modifiers.makeNative(); - function = new DartFunction(formals.val, formals.optionalOpenOffset, - formals.optionalOpenOffset, formals.optionalCloseOffset, parametersCloseParen, - parseNativeBlock(modifiers), null); - } else { - function = new DartFunction(formals.val, formals.optionalOpenOffset, - formals.optionalOpenOffset, formals.optionalCloseOffset, parametersCloseParen, - parseFunctionStatementBody(!modifiers.isExternal(), true), null); - } - doneWithoutConsuming(function); - return DartMethodDefinition.create(name, function, modifiers, null); - } - - private DartIdentifier parseVoidIdentifier() { - beginIdentifier(); - expect(Token.VOID); - return done(new DartIdentifier(Token.VOID.getSyntax())); - } - - private DartTypeNode parseVoidType() { - beginTypeAnnotation(); - return done(new DartTypeNode(parseVoidIdentifier())); - } - - private DartMethodDefinition parseMethod(Modifiers modifiers, DartTypeNode returnType) { - DartExpression name = new DartIdentifier(""); - - if (modifiers.isFactory()) { - if (modifiers.isAbstract()) { - reportError(position(), ParserErrorCode.FACTORY_CANNOT_BE_ABSTRACT); - } - if (modifiers.isStatic()) { - reportError(position(), ParserErrorCode.FACTORY_CANNOT_BE_STATIC); - } - } - - int arity = -1; - Token operation = null; - if (isBuiltInSpecial() && optionalPseudoKeyword(OPERATOR_KEYWORD)) { - // Overloaded operator. - if (modifiers.isStatic()) { - reportError(position(), ParserErrorCode.OPERATOR_CANNOT_BE_STATIC); - } - modifiers = modifiers.makeOperator(); - - beginOperatorName(); - operation = next(); - if (operation.isUserDefinableOperator()) { - name = done(new DartIdentifier(operation.getSyntax())); - if (operation == Token.ASSIGN_INDEX) { - arity = 2; - } else if (operation == Token.SUB) { - arity = -1; - } else if (operation.isBinaryOperator()) { - arity = 1; - } else if (operation == Token.INDEX) { - arity = 1; - } else { - assert operation.isUnaryOperator(); - arity = 0; - } - } else if (operation == Token.IDENTIFIER - && ctx.getTokenString().equals(CALL_KEYWORD)) { - name = done(new DartIdentifier(CALL_KEYWORD)); - arity = -1; - } else if (operation == Token.IDENTIFIER - && ctx.getTokenString().equals(CALL_KEYWORD)) { - name = done(new DartIdentifier(CALL_KEYWORD)); - } else { - // Not a valid operator. Try to recover. - boolean found = false; - for (int i = 0; i < 4; ++i) { - if (peek(i).equals(Token.LPAREN)) { - found = true; - break; - } - } - StringBuilder buf = new StringBuilder(); - buf.append(operation.getSyntax()); - if (found) { - reportError(position(), ParserErrorCode.OPERATOR_IS_NOT_USER_DEFINABLE); - while(true) { - Token token = peek(0); - if (token.equals(Token.LPAREN)) { - break; - } - buf.append(next().getSyntax()); - } - name = done(new DartIdentifier(buf.toString())); - } else { - reportUnexpectedToken(position(), Token.COMMENT, operation); - done(null); - } - } - } else { - beginMethodName(); - // Check for getters and setters. - if (peek(1) != Token.LPAREN && optionalPseudoKeyword(GETTER_KEYWORD)) { - name = parseIdentifier(); - modifiers = modifiers.makeGetter(); - arity = 0; - } else if (peek(1) != Token.LPAREN && optionalPseudoKeyword(SETTER_KEYWORD)) { - name = parseIdentifier(); - modifiers = modifiers.makeSetter(); - arity = 1; - } else { - // Normal method or property. - name = parseIdentifier(); - } - - // Check for named constructor. - if (optional(Token.PERIOD)) { - name = doneWithoutConsuming(new DartPropertyAccess(name, parseIdentifier())); - if(currentlyParsingToplevel()) { - // TODO: Error recovery could find a missing brace and treat this as an expression - reportError(name, ParserErrorCode.FUNCTION_NAME_EXPECTED_IDENTIFIER); - } - if (optional(Token.PERIOD)) { - name = doneWithoutConsuming(new DartPropertyAccess(name, parseIdentifier())); - } - } - done(null); - } - - // Parse the parameters definitions. - FormalParameters parametersInfo; - if (modifiers.isGetter()) { - parametersInfo = new FormalParameters(new ArrayList(), -1, -1, -1); - if (peek(0) == Token.LPAREN) { - reportError(position(), ParserErrorCode.DEPRECATED_GETTER); - parametersInfo = parseFormalParameterList(); - } - } else { - parametersInfo = parseFormalParameterList(); - } - List parameters = parametersInfo.val; - int parametersCloseParen = ctx.getTokenLocation().getBegin(); - - if (arity != -1) { - if (parameters.size() != arity) { - reportError(position(), ParserErrorCode.ILLEGAL_NUMBER_OF_PARAMETERS); - } - // In methods with required arity each parameter is required. - for (int i = 0, size = parameters.size(); i < size; i++) { - DartParameter parameter = parameters.get(i); - if (parameter.getModifiers().isOptional()) { - reportError(parameter, ParserErrorCode.OPTIONAL_POSITIONAL_PARAMETER_NOT_ALLOWED); - } - if (parameter.getModifiers().isNamed()) { - reportError(parameter, ParserErrorCode.NAMED_PARAMETER_NOT_ALLOWED); - } - } - } else if (operation == Token.SUB) { - if (parameters.size() != 0 && parameters.size() != 1) { - reportError(position(), ParserErrorCode.ILLEGAL_NUMBER_OF_PARAMETERS); - } - // In methods with required arity each parameter is required. - for (int i = 0, size = parameters.size(); i < size; i++) { - DartParameter parameter = parameters.get(i); - if (parameter.getModifiers().isNamed()) { - reportError(parameter, ParserErrorCode.NAMED_PARAMETER_NOT_ALLOWED); - } - } - } - - // Parse redirecting factory - DartTypeNode redirectedTypeName = null; - DartIdentifier redirectedConstructorName = null; - if (match(Token.ASSIGN)) { - next(); - if (!modifiers.isFactory()) { - reportError(position(), ParserErrorCode.ONLY_FACTORIES_CAN_REDIRECT); - } - modifiers = modifiers.makeRedirectedConstructor(); - redirectedTypeName = parseTypeAnnotationPossiblyFollowedByName(); - if (optional(Token.PERIOD)) { - redirectedConstructorName = parseIdentifier(); - } - expect(Token.SEMICOLON); - DartFunction function = doneWithoutConsuming(new DartFunction(parameters, - parametersInfo.openParen, parametersInfo.optionalOpenOffset, - parametersInfo.optionalCloseOffset, parametersCloseParen, null, returnType)); - return DartMethodDefinition.create(name, function, modifiers, redirectedTypeName, - redirectedConstructorName); - } - - // Parse initializer expressions for constructors. - List initializers = new ArrayList(); - if (match(Token.COLON) && !(isParsingInterface || modifiers.isFactory())) { - parseInitializers(initializers); - boolean isRedirectedConstructor = validateInitializers(parameters, initializers); - if (isRedirectedConstructor) { - modifiers = modifiers.makeRedirectedConstructor(); - } - } - - // Parse the body. - DartBlock body = null; - if (!optional(Token.SEMICOLON)) { - if (peekPseudoKeyword(0, NATIVE_KEYWORD)) { - modifiers = modifiers.makeNative(); - body = parseNativeBlock(modifiers); - } else { - body = parseFunctionStatementBody(!modifiers.isExternal(), true); - } - if (body != null && modifiers.isRedirectedConstructor()) { - reportError(position(), ParserErrorCode.REDIRECTING_CONSTRUCTOR_CANNOT_HAVE_A_BODY); - } - } - - DartFunction function = doneWithoutConsuming(new DartFunction(parameters, - parametersInfo.openParen, parametersInfo.optionalOpenOffset, - parametersInfo.optionalCloseOffset, parametersCloseParen, body, returnType)); - return DartMethodDefinition.create(name, function, modifiers, initializers); - } - - private DartBlock parseNativeBlock(Modifiers modifiers) { - beginNativeBody(); - if (!optionalPseudoKeyword(NATIVE_KEYWORD)) { - throw new AssertionError(); - } - if (!allowNativeKeyword) { - reportError(position(), ParserErrorCode.NATIVE_ONLY_CORE_LIB); - } - DartExpression body = null; - if (match(Token.STRING)) { - body = parseStringWithPasting(); - } - if (match(Token.LBRACE) || match(Token.ARROW)) { - return done(parseFunctionStatementBody(!modifiers.isExternal(), true)); - } else { - expect(Token.SEMICOLON); - return done(new DartNativeBlock(body)); - } - } - - private DartNodeWithMetadata parseMethodOrAccessor(Modifiers modifiers, DartTypeNode returnType) { - DartMethodDefinition method = done(parseMethod(modifiers, returnType)); - // Abstract method can not have a body. - if (method.getFunction().getBody() != null) { - if (isParsingInterface) { - reportError(method.getName(), ParserErrorCode.INTERFACE_METHOD_WITH_BODY); - } - if (method.getModifiers().isAbstract()) { - reportError(method.getName(), ParserErrorCode.ABSTRACT_METHOD_WITH_BODY); - } - } - // If getter or setter, generate DartFieldDefinition instead. - if (method.getModifiers().isGetter() || method.getModifiers().isSetter()) { - DartField field = new DartField((DartIdentifier) method.getName(), - method.getModifiers().makeAbstractField(), method, null); - field.setSourceInfo(method.getSourceInfo()); - DartFieldDefinition fieldDefinition = - new DartFieldDefinition(null, Lists.create(field)); - fieldDefinition.setSourceInfo(field.getSourceInfo()); - return fieldDefinition; - } - // OK, use method as method. - return method; - } - - /** - *
-   * initializers
-   *            : ':' superCallOrFirstFieldInitializer (',' fieldInitializer)*
-   *            | THIS ('.' identifier) formalParameterList
-   *            ;
-   *
-   * fieldInitializer
-   *            : (THIS '.')? identifier '=' conditionalExpression
-   *            ;
-   *
-   * superCallOrFirstFieldInitializer
-   *            : SUPER arguments | SUPER '.' identifier arguments
-   *            | fieldInitializer
-   *            ;
-   *
-   * fieldInitializer
-   *            : (THIS '.')? identifier '=' conditionalExpression
-   *            | THIS ('.' identifier)? arguments
-   *            ;
-   * 
- */ - private void parseInitializers(List initializers) { - expect(Token.COLON); - do { - beginInitializer(); - if (match(Token.SUPER)) { - beginSuperInitializer(); - expect(Token.SUPER); - DartIdentifier constructor = null; - if (optional(Token.PERIOD)) { - constructor = parseIdentifier(); - } - DartSuperConstructorInvocation superInvocation = - new DartSuperConstructorInvocation(constructor, parseArguments()); - initializers.add(done(new DartInitializer(null, done(superInvocation)))); - } else { - boolean hasThisPrefix = optional(Token.THIS); - if (hasThisPrefix) { - if (match(Token.LPAREN)) { - parseRedirectedConstructorInvocation(null, initializers); - continue; - } - expect(Token.PERIOD); - } - DartIdentifier name = parseIdentifier(); - if (hasThisPrefix && match(Token.LPAREN)) { - parseRedirectedConstructorInvocation(name, initializers); - continue; - } else { - expect(Token.ASSIGN); - boolean save = setAllowFunctionExpression(false); - DartExpression initExpr = parseExpression(); - setAllowFunctionExpression(save); - initializers.add(done(new DartInitializer(name, initExpr))); - } - } - } while (optional(Token.COMMA)); - } - - private void parseRedirectedConstructorInvocation(DartIdentifier name, - List initializers) { - DartRedirectConstructorInvocation redirConstructor = - new DartRedirectConstructorInvocation(name, parseArguments()); - initializers.add(done(new DartInitializer(null, doneWithoutConsuming(redirConstructor)))); - } - - private boolean validateInitializers(List parameters, - List initializers) { - // Try to find DartRedirectConstructorInvocation, check for multiple invocations. - // Check for DartSuperConstructorInvocation multiple invocations. - DartInitializer redirectInitializer = null; - boolean firstMultipleRedirectReported = false; - { - DartInitializer superInitializer = null; - boolean firstMultipleSuperReported = false; - for (DartInitializer initializer : initializers) { - if (initializer.isInvocation()) { - // DartSuperConstructorInvocation - DartExpression initializerInvocation = initializer.getValue(); - if (initializerInvocation instanceof DartSuperConstructorInvocation) { - if (superInitializer != null) { - if (!firstMultipleSuperReported) { - reportError(superInitializer, ParserErrorCode.SUPER_CONSTRUCTOR_MULTIPLE); - firstMultipleSuperReported = true; - } - reportError(initializer, ParserErrorCode.SUPER_CONSTRUCTOR_MULTIPLE); - } else { - superInitializer = initializer; - } - } - // DartRedirectConstructorInvocation - if (initializerInvocation instanceof DartRedirectConstructorInvocation) { - if (redirectInitializer != null) { - if (!firstMultipleRedirectReported) { - reportError(redirectInitializer, ParserErrorCode.REDIRECTING_CONSTRUCTOR_MULTIPLE); - firstMultipleRedirectReported = true; - } - reportError(initializer, ParserErrorCode.REDIRECTING_CONSTRUCTOR_MULTIPLE); - } else { - redirectInitializer = initializer; - } - } - } - } - } - // If there is redirecting constructor, then there should be no other initializers. - if (redirectInitializer != null) { - boolean shouldRedirectInvocationReported = false; - // Implicit initializer in form of "this.id" parameter. - for (DartParameter parameter : parameters) { - if (parameter.getName() instanceof DartPropertyAccess) { - DartPropertyAccess propertyAccess = (DartPropertyAccess) parameter.getName(); - if (propertyAccess.getQualifier() instanceof DartThisExpression) { - shouldRedirectInvocationReported = true; - reportError( - parameter, - ParserErrorCode.REDIRECTING_CONSTRUCTOR_PARAM); - } - } - } - // Iterate all initializers and mark all except of DartRedirectConstructorInvocation - for (DartInitializer initializer : initializers) { - if (!(initializer.getValue() instanceof DartRedirectConstructorInvocation)) { - shouldRedirectInvocationReported = true; - reportError( - initializer, - ParserErrorCode.REDIRECTING_CONSTRUCTOR_OTHER); - } - } - // Mark DartRedirectConstructorInvocation if needed. - if (shouldRedirectInvocationReported) { - reportError( - redirectInitializer, - ParserErrorCode.REDIRECTING_CONSTRUCTOR_ITSELF); - } - } - // Done. - return redirectInitializer != null; - } - - /** - *
-   * variableDeclaration
-   *    : constVarOrType identifierList
-   *    ;
-   * identifierList
-   *    : identifier (',' identifier)*
-   *    ;
-   *
-   * staticConstDeclarationList
-   *    : staticConstDeclaration (',' staticConstDeclaration)*
-   *    ;
-   *
-   * staticConstDeclaration
-   *    : identifier '=' constantExpression
-   *    ;
-   *
-   * // The compile-time expression production is used to mark certain expressions
-   * // as only being allowed to hold a compile-time constant. The grammar cannot
-   * // express these restrictions, so this will have to be enforced by a separate
-   * // analysis phase.
-   * constantExpression
-   *    : expression
-   *    ;
-   * 
- */ - private DartFieldDefinition parseFieldDeclaration(Modifiers modifiers, DartTypeNode type) { - List fields = new ArrayList(); - List metadata = parseMetadata(); - do { - beginVariableDeclaration(); - DartIdentifier name = parseIdentifier(); - DartExpression value = null; - if (optional(Token.ASSIGN)) { - value = parseExpression(); - if (value != null) { - modifiers = modifiers.makeInitialized(); - } - } - if (modifiers.isExternal()) { - reportError(name, ParserErrorCode.EXTERNAL_ONLY_METHOD); - } - DartField field = done(new DartField(name, modifiers, null, value)); - setMetadata(field, metadata); - fields.add(field); - } while (optional(Token.COMMA)); - DartFieldDefinition definition = new DartFieldDefinition(type, fields); - setMetadata(definition, metadata); - return done(definition); - } - - private static class FormalParameters { - private final List val; - private final int openParen; - private final int optionalOpenOffset; - private final int optionalCloseOffset; - public FormalParameters(List parameters, int openParen, int optionalOpenOffset, - int optionalCloseOffset) { - this.val = parameters; - this.openParen = openParen; - this.optionalOpenOffset = optionalOpenOffset; - this.optionalCloseOffset = optionalCloseOffset; - } - } - - /** - *
-   * formalParameterList
-   *     : '(' ')'
-   *     | '(' normalFormalParameters (',' optionalFormalParameters)? ')'
-   *     | '(' optionalFormalParameters ')'
-   *     ;
-   *
-   * normalFormalParameters
-   *     : normalFormalParameter (',' normalFormalParameter)*
-   *     ;
-   *
-   * optionalFormalParameters
-   *     : optionalPositionalFormalParameters
-   *     | namedFormalParameters
-   *     ;
-   *
-   * optionalPositionalFormalParameters
-   *     : '[' defaultFormalParameter (',' defaultFormalParameter)* ']'
-   *     ;
-   *
-   * namedFormalParameters
-   *     : '{' defaultNamedParameter (',' defaultNamedParameter)* '}'
-   *     ;
-   * 
- */ - @Terminals(tokens = {Token.COMMA, Token.RPAREN}) - private FormalParameters parseFormalParameterList() { - beginFormalParameterList(); - List params = new ArrayList(); - int optionalOpenOffset = -1; - int optionalCloseOffset = -1; - expect(Token.LPAREN); - boolean done = optional(Token.RPAREN); - int openParen = ctx.getTokenLocation().getBegin(); - boolean isOptional = false; - boolean isNamed = false; - while (!done) { - if (!isOptional && optional(Token.LBRACK)) { - if (isNamed) { - reportErrorWithoutAdvancing(ParserErrorCode.CANNOT_MIX_OPTIONAL_AND_NAMED_PARAMETERS); - } - isOptional = true; - optionalOpenOffset = ctx.getTokenLocation().getBegin(); - } - if (!isNamed && optional(Token.LBRACE)) { - if (isOptional) { - reportErrorWithoutAdvancing(ParserErrorCode.CANNOT_MIX_OPTIONAL_AND_NAMED_PARAMETERS); - } - isNamed = true; - optionalOpenOffset = ctx.getTokenLocation().getBegin(); - } - - DartParameter param = parseFormalParameter(isOptional, isNamed); - params.add(param); - - if (isOptional && optional(Token.RBRACK)) { - optionalCloseOffset = ctx.getTokenLocation().getBegin(); - expectCloseParen(); - break; - } - if (isNamed && optional(Token.RBRACE)) { - optionalCloseOffset = ctx.getTokenLocation().getBegin(); - expectCloseParen(); - break; - } - - // Ensure termination if token is anything other than COMMA. - // Must keep Token.COMMA in sync with @Terminals above - if (!optional(Token.COMMA)) { - if (isOptional && !optional(Token.RBRACE)) { - reportErrorWithoutAdvancing(ParserErrorCode.MISSING_OPTIONAL_PARAMETER_END); - } - if (isNamed && !optional(Token.RBRACK)) { - reportErrorWithoutAdvancing(ParserErrorCode.MISSING_NAMED_PARAMETER_END); - } - // Must keep Token.RPAREN in sync with @Terminals above - expectCloseParen(); - done = true; - } - } - - return new FormalParameters(done(params), openParen, optionalOpenOffset, optionalCloseOffset); - } - - /** - *
-   * normalFormalParameter
-   *     : functionDeclaration
-   *     | fieldFormalParameter
-   *     | simpleFormalParameter
-   *     ;
-   *
-   * defaultFormalParameter
-   *     : normalFormalParameter ('=' constantExpression)?
-   *     ;
-   * 
-   * defaultNamedParameter
-   *     : normalFormalParameter (':' constantExpression)?
-   *     ;
-   * 
- */ - private DartParameter parseFormalParameter(boolean isOptional, boolean isNamed) { - beginFormalParameter(); - List metadata = parseMetadata(); - DartExpression paramName = null; - DartTypeNode type = null; - DartExpression defaultExpr = null; - List functionParams = null; - boolean hasVar = false; - Modifiers modifiers = Modifiers.NONE; - - if (isOptional) { - modifiers = modifiers.makeOptional(); - } - if (isNamed) { - modifiers = modifiers.makeNamed(); - } - - if (optional(Token.FINAL)) { - modifiers = modifiers.makeFinal(); - } else if (optional(Token.CONST)) { - reportError(position(), ParserErrorCode.FORMAL_PARAMETER_IS_CONST); - } else if (optional(Token.VAR)) { - hasVar = true; - } - - boolean isVoidType = false; - if (!hasVar) { - isVoidType = (peek(0) == Token.VOID); - if (isVoidType) { - type = parseVoidType(); - } else if ((peek(0) != Token.ELLIPSIS) - && (peek(1) != Token.COMMA) - && (peek(1) != Token.RPAREN) - && (peek(1) != Token.RBRACE) - && (peek(1) != Token.RBRACK) - && (peek(1) != Token.ASSIGN) - && (peek(1) != Token.COLON) - && (peek(1) != Token.LPAREN) - && (peek(0) != Token.THIS)) { - // Must be a type specification. - type = parseTypeAnnotation(); - } - } - - paramName = parseParameterName(); - - if (peek(0) == Token.LPAREN) { - // Function parameter. - if (modifiers.isFinal()) { - reportError(position(), ParserErrorCode.FUNCTION_TYPED_PARAMETER_IS_FINAL); - } - if (hasVar) { - reportError(position(), ParserErrorCode.FUNCTION_TYPED_PARAMETER_IS_VAR); - } - functionParams = parseFormalParameterList().val; - validateNoDefaultParameterValues( - functionParams, - ParserErrorCode.DEFAULT_VALUE_CAN_NOT_BE_SPECIFIED_IN_CLOSURE); - } else { - // Not a function parameter. - if (isVoidType) { - reportError(type, ParserErrorCode.VOID_PARAMETER); - } - } - - // Look for an initialization expression - switch (peek(0)) { - case COMMA: - case RPAREN: - case RBRACE: - case RBRACK: - // It is a simple parameter. - break; - - case ASSIGN: - // Default parameter -- only allowed for optional parameters. - if (isOptional) { - consume(Token.ASSIGN); - defaultExpr = parseExpression(); - } else if (isNamed) { - reportError(position(), ParserErrorCode.INVALID_SEPARATOR_FOR_NAMED); - consume(Token.ASSIGN); - defaultExpr = parseExpression(); - } else { - reportError(position(), ParserErrorCode.DEFAULT_POSITIONAL_PARAMETER); - } - break; - - case COLON: - // Default parameter -- only allowed for named parameters. - if (isNamed) { - consume(Token.COLON); - defaultExpr = parseExpression(); - } else if (isOptional) { - reportError(position(), ParserErrorCode.INVALID_SEPARATOR_FOR_OPTIONAL); - consume(Token.COLON); - defaultExpr = parseExpression(); - } else { - reportError(position(), ParserErrorCode.DEFAULT_POSITIONAL_PARAMETER); - } - break; - - default: - reportUnexpectedToken(position(), null, peek(0)); - break; - } - - DartParameter parameter = new DartParameter(paramName, type, functionParams, defaultExpr, - modifiers); - setMetadata(parameter, metadata); - return done(parameter); - } - - /** - *
-   * simpleFormalParameter
-   *     : declaredIdentifier
-   *     | identifier
-   *     ;
-   *
-   * fieldFormalParameter
-   *    : finalVarOrType? THIS '.' identifier
-   *    ;
-   * 
- */ - private DartExpression parseParameterName() { - beginParameterName(); - if (match(Token.THIS)) { - beginThisExpression(); - expect(Token.THIS); - DartThisExpression thisExpression = done(DartThisExpression.get()); - expect(Token.PERIOD); - return done(new DartPropertyAccess(thisExpression, parseIdentifier())); - } - return done(parseIdentifier()); - } - - /** - * Validates that given {@link DartParameter}s have no default values, or marks existing default - * values with given {@link ErrorCode}. - */ - private void validateNoDefaultParameterValues(List parameters, - ErrorCode errorCode) { - for (int i = 0, size = parameters.size(); i < size; i++) { - DartParameter parameter = parameters.get(i); - DartExpression defaultExpr = parameter.getDefaultExpr(); - if (defaultExpr != null) { - reportError(defaultExpr, errorCode); - } - } - } - - /** - * Parse an expression. - * - *
-   * expression
-   *     : assignableExpression assignmentOperator expression
-   *     | conditionalExpression cascadeSection*
-   *     | throwExpression
-   *     ;
-   *
-   * assignableExpression
-   *     : primary (arguments* assignableSelector)+
-   *     | SUPER assignableSelector
-   *     | identifier
-   *     ;
-   * 
- * - * @return an expression matching the {@code expression} production above - */ - @VisibleForTesting - public DartExpression parseExpression() { - if (peek(0) == Token.THROW) { - return parseThrowExpression(true); - } - beginExpression(); - if (looksLikeTopLevelKeyword() || peek(0).equals(Token.RBRACE)) { - // Allow recovery back to the top level. - reportErrorWithoutAdvancing(ParserErrorCode.UNEXPECTED_TOKEN); - return done(null); - } - DartExpression result = parseConditionalExpression(); - Token token = peek(0); - if (token == Token.CASCADE) { - List cascadeSections = new ArrayList(); - while (token == Token.CASCADE) { - beginExpression(); - DartExpression section = parseCascadeSection(); - done(section); - if (section != null) { - cascadeSections.add(section); - } - token = peek(0); - } - result = done(new DartCascadeExpression(result, cascadeSections)); - } else if (token.isAssignmentOperator()) { - ensureAssignable(result); - consume(token); - int tokenOffset = ctx.getTokenLocation().getBegin(); - result = done(new DartBinaryExpression(token, tokenOffset, result, parseExpression())); - } else { - done(null); - } - return result; - } - - /** - * Parse an expression without a cascade. - * - *
-   * expressionWithoutCascade
-   *     : assignableExpression assignmentOperator expressionWithoutCascade
-   *     | conditionalExpression
-   *     ;
-   * 
- * - * @return an expression matching the {@code expression} production above - */ - private DartExpression parseExpressionWithoutCascade() { - if (peek(0) == Token.THROW) { - return parseThrowExpression(false); - } - beginExpression(); - if (looksLikeTopLevelKeyword() || peek(0).equals(Token.RBRACE)) { - // Allow recovery back to the top level. - reportErrorWithoutAdvancing(ParserErrorCode.UNEXPECTED_TOKEN); - return done(null); - } - DartExpression result = parseConditionalExpression(); - Token token = peek(0); - if (token.isAssignmentOperator()) { - ensureAssignable(result); - consume(token); - int tokenOffset = ctx.getTokenLocation().getBegin(); - result = done(new DartBinaryExpression(token, tokenOffset, result, parseExpressionWithoutCascade())); - } else { - done(null); - } - return result; - } - - /** - * Parse a cascade section. - *
-   * cascadeSection
-   *     : CASCADE (cascadeSelector arguments*) (assignableSelector arguments*)* (assignmentOperator
-   * expressionWithoutCascade)?
-   *     ;
-   *
-   * cascadeSelector
-   *     : LBRACK expression RBRACK
-   *     | identifier
-   *     ;
-   * 
- * - * @return the expression representing the cascaded method invocation - */ - private DartExpression parseCascadeSection() { - expect(Token.CASCADE); - DartExpression result = null; - DartIdentifier functionName = null; - if (peek(0) == Token.IDENTIFIER) { - functionName = parseIdentifier(); - } else if (peek(0) == Token.LBRACK) { - consume(Token.LBRACK); - result = doneWithoutConsuming(new DartArrayAccess(result, true, parseExpression())); - expect(Token.RBRACK); - } else { - reportUnexpectedToken(position(), null, next()); - return result; - } - if (peek(0) == Token.LPAREN) { - while (peek(0) == Token.LPAREN) { - if (functionName != null) { - result = doneWithoutConsuming(new DartMethodInvocation(result, result == null, functionName, parseArguments())); - functionName = null; - } else if (result == null) { - return null; - } else { - result = doneWithoutConsuming(new DartFunctionObjectInvocation(result, parseArguments())); - } - } - } else if (functionName != null) { - result = doneWithoutConsuming(new DartPropertyAccess(result, result == null, functionName)); - } - boolean progress = true; - while (progress) { - progress = false; - DartExpression selector = tryParseAssignableSelector(result); - if (selector != null) { - result = selector; - progress = true; - while (peek(0) == Token.LPAREN) { - result = doneWithoutConsuming(new DartFunctionObjectInvocation(result, parseArguments())); - } - } - } - Token token = peek(0); - if (token.isAssignmentOperator()) { - ensureAssignable(result); - consume(token); - int tokenOffset = ctx.getTokenLocation().getBegin(); - result = doneWithoutConsuming(new DartBinaryExpression(token, tokenOffset, result, parseExpressionWithoutCascade())); - } - return result; - } - - /** - * expressionList - * : expression (',' expression)* - * ; - */ - @Terminals(tokens={Token.COMMA}) - private DartExpression parseExpressionList() { - beginExpressionList(); - DartExpression result = parseExpression(); - // Must keep in sync with @Terminals above - while (optional(Token.COMMA)) { - int tokenOffset = ctx.getTokenLocation().getBegin(); - result = new DartBinaryExpression(Token.COMMA, tokenOffset, result, parseExpression()); - if (match(Token.COMMA)) { - result = doneWithoutConsuming(result); - } - } - return done(result); - } - - - /** - * Parse a binary expression. - * - *
-   * logicalOrExpression
-   *     : logicalAndExpression ('||' logicalAndExpression)*
-   *     ;
-   *
-   * logicalAndExpression
-   *     : bitwiseOrExpression ('&&' bitwiseOrExpression)*
-   *     ;
-   *
-   * bitwiseOrExpression
-   *     : bitwiseXorExpression ('|' bitwiseXorExpression)*
-   *     ;
-   *
-   * bitwiseXorExpression
-   *     : bitwiseAndExpression ('^' bitwiseAndExpression)*
-   *     ;
-   *
-   * bitwiseAndExpression
-   *     : equalityExpression ('&' equalityExpression)*
-   *     ;
-   *
-   * equalityExpression
-   *     : relationalExpression (equalityOperator relationalExpression)?
-   *     ;
-   *
-   * relationalExpression
-   *     : shiftExpression (isOperator type | relationalOperator shiftExpression)?
-   *     ;
-   *
-   * shiftExpression
-   *     : additiveExpression (shiftOperator additiveExpression)*
-   *     ;
-   *
-   * additiveExpression
-   *     : multiplicativeExpression (additiveOperator multiplicativeExpression)*
-   *     ;
-   *
-   * multiplicativeExpression
-   *     : unaryExpression (multiplicativeOperator unaryExpression)*
-   *     ;
-   * 
- * - * @return an expression matching one of the productions above - */ - private DartExpression parseBinaryExpression(int precedence) { - assert (precedence >= 4); - beginBinaryExpression(); - DartExpression lastResult = parseUnaryExpression(); - DartExpression result = lastResult; - for (int level = peekMaybeAS(0).getPrecedence(); level >= precedence; level--) { - while (peekMaybeAS(0).getPrecedence() == level) { - int prevPositionStart = ctx.getTokenLocation().getBegin(); - int prevPositionEnd = ctx.getTokenLocation().getEnd(); - Token token = nextMaybeAS(); - int tokenOffset = ctx.getTokenLocation().getBegin(); - if (lastResult instanceof DartSuperExpression - && (token == Token.AND || token == Token.OR)) { - reportErrorAtPosition(prevPositionStart, prevPositionEnd, - ParserErrorCode.SUPER_IS_NOT_VALID_AS_A_BOOLEAN_OPERAND); - } - if (token == Token.EQ_STRICT) { - reportError(tokenOffset, ParserErrorCode.DEPRECATED_STRICT_EQ); - } - if (token == Token.NE_STRICT) { - reportError(tokenOffset, ParserErrorCode.DEPRECATED_STRICT_NE); - } - DartExpression right; - if (token == Token.IS) { - beginTypeExpression(); - if (optional(Token.NOT)) { - int notOffset = ctx.getTokenLocation().getBegin(); - beginTypeExpression(); - DartTypeExpression typeExpression = done(new DartTypeExpression(parseTypeAnnotation())); - right = done(new DartUnaryExpression(Token.NOT, notOffset, typeExpression, true)); - } else { - right = done(new DartTypeExpression(parseTypeAnnotation())); - } - } else if (token == Token.AS) { - beginTypeExpression(); - right = done(new DartTypeExpression(parseTypeAnnotation())); - } else { - right = parseBinaryExpression(level + 1); - } - if (right instanceof DartSuperExpression) { - reportError(position(), ParserErrorCode.SUPER_CANNOT_BE_USED_AS_THE_SECOND_OPERAND); - } - - lastResult = right; - result = doneWithoutConsuming(new DartBinaryExpression(token, tokenOffset, result, right)); - if (token == Token.IS - || token == Token.AS - || token.isRelationalOperator() - || token.isEqualityOperator()) { - // The operations cannot be chained. - if (peekMaybeAS(0) == token) { - reportError(position(), ParserErrorCode.INVALID_OPERATOR_CHAINING, - token.toString().toLowerCase()); - } - break; - } - } - } - done(null); - return result; - } - - /** - * Use this method where token "as" is expected to be used as built-in identifier. - * - * @return the {@link Token} at given position or {@link Token#AS}. - */ - private Token peekMaybeAS(int n) { - Token token = ctx.peek(n); - String tokenString = ctx.peekTokenString(n); - if (token == Token.IDENTIFIER && "as".equals(tokenString)) { - return Token.AS; - } - return token; - } - - /** - * Use this method where token "as" is expected to be used as built-in identifier. - * - * @return the current {@link Token} or {@link Token#AS}. - */ - private Token nextMaybeAS() { - ctx.advance(); - Token token = ctx.getCurrentToken(); - String tokenString = ctx.getTokenString(); - if (token == Token.IDENTIFIER && "as".equals(tokenString)) { - return Token.AS; - } - return token; - } - - /** - * Parse the arguments passed to a function or method invocation. - * - *
-   * arguments
-   *    : '(' argumentList? ')'
-   *    ;
-   *
-   * argumentList
-   *    : expression (',' expression)* (',' spreadArgument)?
-   *    | spreadArgument
-   *    ;
-   *
-   * spreadArgument
-   *    : '...' expression
-   *    ;
-   * 
- * - * @return a list of expressions containing the arguments to be passed - */ - @Terminals(tokens={Token.RPAREN, Token.COMMA}) - public List parseArguments() { - List arguments = new ArrayList(); - expect(Token.LPAREN); - // SEMICOLON is for error recovery - boolean namedArgumentParsed = false; - outer: while (!match(Token.RPAREN) && !match(Token.EOS) && !match(Token.SEMICOLON)) { - beginParameter(); - // parse argument, may be named - DartExpression expression; - if (peek(1) == Token.COLON) { - DartIdentifier name = parseIdentifier(); - expect(Token.COLON); - expression = new DartNamedExpression(name, parseExpression()); - namedArgumentParsed = true; - } else { - expression = parseExpression(); - if (namedArgumentParsed) { - reportError(expression, ParserErrorCode.POSITIONAL_AFTER_NAMED_ARGUMENT); - } - } - done(expression); - // add argument, if parsed successfully - if (expression != null) { - arguments.add(expression); - } - // do we have more arguments? - switch(peek(0)) { - // Must keep in sync with @Terminals above - case COMMA: - if (peek(-1) == Token.COMMA) { - reportErrorWithoutAdvancing(ParserErrorCode.EXPECTED_EXPRESSION_AFTER_COMMA); - } - consume(Token.COMMA); - break; - // Must keep in sync with @Terminals above - case RPAREN: - break; - default: - Token actual = peek(0); - Set terminals = collectTerminalAnnotations(); - if (terminals.contains(actual) || looksLikeTopLevelKeyword()) { - // Looks like a method already on the stack could use this token. - reportErrorWithoutAdvancing(ParserErrorCode.EXPECTED_COMMA_OR_RIGHT_PAREN); - break outer; - } else { - // Advance the parser state if no other method on the stack can use this token. - ctx.advance(); - } - reportError(ctx.getTokenLocation().getEnd(), - ParserErrorCode.EXPECTED_COMMA_OR_RIGHT_PAREN, actual); - break; - } - } - if (peek(-1) == Token.COMMA) { - reportErrorWithoutAdvancing(ParserErrorCode.EXPECTED_EXPRESSION_AFTER_COMMA); - } - expectCloseParen(); - return arguments; - } - - /** - * Parse a conditional expression. - * - *
-   * conditionalExpression
-   *     : logicalOrExpression ('?' expression ':' expression)?
-   *     ;
-   * 
- * - * @return an expression matching the {@code conditionalExpression} production - */ - private DartExpression parseConditionalExpression() { - beginConditionalExpression(); - DartExpression result = parseBinaryExpression(4); - if (result instanceof DartSuperExpression) { - reportError(position(), ParserErrorCode.SUPER_IS_NOT_VALID_ALONE_OR_AS_A_BOOLEAN_OPERAND); - } - if (peek(0) != Token.CONDITIONAL) { - return done(result); - } - consume(Token.CONDITIONAL); - DartExpression yes = parseExpressionWithoutCascade(); - expect(Token.COLON); - DartExpression no = parseExpressionWithoutCascade(); - return done(new DartConditional(result, yes, no)); - } - - private boolean looksLikeStringInterpolation() { - int peekAhead = 0; - while (true) { - switch (peek(peekAhead++)) { - case STRING: - break; - case STRING_SEGMENT: - case STRING_LAST_SEGMENT: - case STRING_EMBED_EXP_START: - case STRING_EMBED_EXP_END: - return true; - default: - return false; - } - } - } - /** - * Pastes together adjacent strings. Re-uses the StringInterpolation - * node if there is more than one adjacent string. - */ - private DartExpression parseStringWithPasting() { - List expressions = new ArrayList(); - if (looksLikeStringInterpolation()) { - beginStringInterpolation(); - } else { - beginLiteral(); - } - DartExpression result = null; - boolean foundStringInterpolation = false; - do { - result = null; - switch(peek(0)) { - case STRING: - case STRING_SEGMENT: - case STRING_EMBED_EXP_START: - // another string is coming, glue it together. - result = parseString(); - if (result != null) { - expressions.add(result); - } - if (result instanceof DartStringInterpolation) { - foundStringInterpolation = true; - } - break; - } - } while (result != null); - - if (expressions.size() == 0) { - return doneWithoutConsuming(null); - } else if (expressions.size() == 1) { - return done(expressions.get(0)); - } - - if (foundStringInterpolation) { - DartStringInterpolationBuilder builder = new DartStringInterpolationBuilder(); - // Create a new DartStringInterpolation object from the expressions. - boolean first = true; - for (DartExpression expr : expressions) { - if (!first) { - // pad between interpolations with a dummy expression - builder.addExpression(DartStringLiteral.get("")); - } - if (expr instanceof DartStringInterpolation) { - builder.addInterpolation((DartStringInterpolation)expr); - } else if (expr instanceof DartStringLiteral) { - builder.addString((DartStringLiteral)expr); - } else { - throw new InternalCompilerException("Expected String or StringInterpolation"); - } - first = false; - } - return done(builder.buildInterpolation()); - } - - // Synthesize a single String literal - List stringParts = new ArrayList(); - StringBuilder builder = new StringBuilder(); - for (DartExpression expr : expressions) { - DartStringLiteral stringPart = (DartStringLiteral)expr; - stringParts.add(stringPart); - builder.append(stringPart.getValue()); - } - return done(DartStringLiteral.get(builder.toString(), stringParts)); - } - - private DartExpression parseString() { - switch(peek(0)) { - case STRING: { - beginLiteral(); - consume(Token.STRING); - return done(DartStringLiteral.get(ctx.getTokenString())); - } - - case STRING_SEGMENT: - case STRING_EMBED_EXP_START: - return parseStringInterpolation(); - - default: - DartExpression expression = parseExpression(); - reportError(position(), ParserErrorCode.EXPECTED_STRING_LITERAL); - return expression; - } - } - - private int skipStringLiteral(int offset) { - Token token = peek(offset); - while (token == Token.STRING || token == Token.STRING_SEGMENT || token == Token.STRING_EMBED_EXP_START) { - switch(token) { - case STRING: - offset = offset + 1; - - case STRING_SEGMENT: - case STRING_EMBED_EXP_START: - offset = skipStringInterpolation(offset); - } - token = peek(offset); - } - return offset; - } - - private int skipStringInterpolation(int offset) { - Token token = peek(offset); - if (token == Token.STRING_LAST_SEGMENT) { - return -1; - } - boolean inString = true; - while (inString) { // Iterate until we find the last string segment. - switch (token) { - case STRING_SEGMENT: - offset = offset + 1; - token = peek(offset); - break; - case STRING_LAST_SEGMENT: - offset = offset + 1; - token = peek(offset); - inString = false; - break; - case STRING_EMBED_EXP_START: { - offset = offset + 1; - token = peek(offset); - while (token != Token.EOS && token != Token.STRING_EMBED_EXP_END && token != Token.STRING_LAST_SEGMENT) { - if (token == Token.STRING || token == Token.STRING_SEGMENT || token == Token.STRING_EMBED_EXP_START) { - offset = skipStringLiteral(offset); - } else { - offset = offset + 1; - } - token = peek(offset); - } - if (token != Token.STRING_EMBED_EXP_END) { - inString = Token.STRING_LAST_SEGMENT != token; - } - break; - } - default: - inString = false; - break; - } - } - return offset; - } - - private DartStringLiteral parseUri() { - DartExpression str = parseStringWithPasting(); - if (str instanceof DartStringLiteral) { - return (DartStringLiteral) str; - } else if (str != null) { - reportError(str, ParserErrorCode.URI_CANNOT_USE_INTERPOLATION); - DartStringLiteral result = DartStringLiteral.get(""); - result.setSourceInfo(str.getSourceInfo()); - return result; - } else { - expect(Token.STRING); - return DartStringLiteral.get(null); - } - } - - /** - * Instances of the class {@code DepthCounter} represent the number of less than tokens that have - * not yet been matched. - */ - private static class DepthCounter { - /** - * The number of less than tokens that have not yet been matched. - */ - private int count = 0; - - /** - * Increment the number of less than tokens that have not yet been matched by the given amount - * (or decrement the count if the argument is negative). - * - * @param value the amount by which the count should be changed - * @return the count after it has been modified - */ - public int add(int value) { - count += value; - return count; - } - - /** - * Return the number of less than tokens that have not yet been matched. - * - * @return the number of less than tokens that have not yet been matched - */ - public int getCount() { - return count; - } - } - - /** - * Return the offset of the first token after a type name, or {@code -1} if the token at the given - * offset is not the start of a type name. - * - * @param offset the offset of the first token of the type name - * @return the offset of the first token after a type name - */ - private int skipTypeName(int offset) { - return skipTypeName(offset, new DepthCounter()); - } - - /** - * Return the offset of the first token after a type name, or {@code -1} if the token at the given - * offset is not the start of a type name. - * - * @param offset the offset of the first token of the type name - * @param depth the number of less-thans that have been encountered since the outer-most type name - * @return the offset of the first token after a type name - */ - private int skipTypeArguments(int offset, DepthCounter depth) { - if (peek(offset) != Token.LT) { - return -1; - } - int oldDepth = depth.add(1); - offset = skipTypeName(offset + 1, depth); - if (offset < 0) { - return offset; - } - while (peek(offset) == Token.COMMA) { - offset = skipTypeName(offset + 1, depth); - if (offset < 0) { - return offset; - } - } - if (depth.getCount() < oldDepth) { - // We already passed the closing '>' for this list of type arguments - return offset; - } - if (peek(offset) == Token.GT) { - depth.add(-1); - return offset + 1; - } else if (peek(offset) == Token.SAR) { - depth.add(-2); - return offset + 1; - } - return -1; - } - - /** - * Return the offset of the first token after a type name, or {@code -1} if the token at the given - * offset is not the start of a type name. - * - * @param offset the offset of the first token of the type name - * @param depth the number of less-thans that have been encountered since the outer-most type name - * @return the offset of the first token after a type name - */ - private int skipTypeName(int offset, DepthCounter depth) { - if (peek(offset) != Token.IDENTIFIER) { - return -1; - } - offset++; - if (peek(offset) == Token.PERIOD) { - offset++; - if (peek(offset) == Token.IDENTIFIER) { - // We tolerate a missing identifier in order to recover better - offset++; - } - } - if (peek(offset) == Token.LT) { - offset = skipTypeArguments(offset, depth); - } - return offset; - } - - /** - * Parse any literal that is not a function literal (those have already been - * handled before this method is called, so we don't need to handle them - * here). - * - *
-   * nonFunctionLiteral
-   *   : NULL
-   *   | TRUE
-   *   | FALSE
-   *   | HEX_NUMBER
-   *   | RATIONAL_NUMBER
-   *   | DOUBLE_NUMBER
-   *   | STRING
-   *   | mapLiteral
-   *   | arrayLiteral
-   *   ;
-   * 
- * - * @return an expression matching the {@code literal} production above - */ - private DartExpression parseLiteral() { - beginLiteral(); - if (PSEUDO_KEYWORDS_SET.contains(peek(0).getSyntax())) { - return done(parseIdentifier()); - } - switch (peek(0)) { - case NULL_LITERAL: { - consume(Token.NULL_LITERAL); - return done(DartNullLiteral.get()); - } - - case TRUE_LITERAL: { - consume(Token.TRUE_LITERAL); - return done(DartBooleanLiteral.get(true)); - } - - case FALSE_LITERAL: { - consume(Token.FALSE_LITERAL); - return done(DartBooleanLiteral.get(false)); - } - - case INTEGER_LITERAL: { - consume(Token.INTEGER_LITERAL); - String number = ctx.getTokenString(); - return done(DartIntegerLiteral.get(new BigInteger(number))); - } - - case DOUBLE_LITERAL: { - consume(Token.DOUBLE_LITERAL); - String number = ctx.getTokenString(); - return done(DartDoubleLiteral.get(Double.parseDouble(number))); - } - - case HEX_LITERAL: { - consume(Token.HEX_LITERAL); - String number = ctx.getTokenString(); - return done(DartIntegerLiteral.get(new BigInteger(number, 16))); - } - - case LBRACE: { - return done(parseMapLiteral(false, null)); - } - - case INDEX: { - expect(peek(0)); - return done(new DartArrayLiteral(false, null, new ArrayList())); - } - - case LBRACK: { - return done(parseArrayLiteral(false, null)); - } - - case VOID: - // For better error recovery / code completion in the IDE, treat "void" as an identifier - // here and let it get reported as a resolution error. - case IDENTIFIER: { - return done(parseIdentifier()); - } - - case SEMICOLON: { - // this is separate from the default case for better error recovery, - // leaving the semicolon for the caller to use for a statement boundary - - // we have to advance to get the proper position, but we want to leave - // the semicolon - startLookahead(); - next(); - reportUnexpectedToken(position(), null, Token.SEMICOLON); - rollback(); - return done(new DartSyntheticErrorExpression("")); - } - - default: { - Token unexpected = peek(0); - String unexpectedString = ctx.getTokenString(); - if (unexpectedString == null && unexpected != Token.EOS) { - unexpectedString = unexpected.getSyntax(); - } - - // Don't eat tokens that could be used to successfully terminate a non-terminal - // further up the stack. - Set terminals = collectTerminalAnnotations(); - if (!looksLikeTopLevelKeyword() && !terminals.contains(unexpected)) { - next(); - } - reportUnexpectedToken(position(), null, unexpected); - StringBuilder tokenStr = new StringBuilder(); - if (unexpectedString != null) { - tokenStr.append(unexpectedString); - } - // TODO(jat): should we eat additional tokens here for error recovery? - return done(new DartSyntheticErrorExpression(tokenStr.toString())); - } - } - } - - /** - * mapLiteralEntry - * : STRING ':' expression - * ; - */ - private DartMapLiteralEntry parseMapLiteralEntry() { - beginMapLiteralEntry(); - // Parse the key. - DartExpression keyExpr = parseStringWithPasting(); - if (keyExpr == null) { - return done(null); - } - // Parse the value. - DartExpression value; - if (expect(Token.COLON)) { - value = parseExpression(); - } else { - value = doneWithoutConsuming(new DartSyntheticErrorExpression()); - } - return done(new DartMapLiteralEntry(keyExpr, value)); - } - private boolean looksLikeString() { - switch(peek(0)) { - case STRING: - case STRING_SEGMENT: - case STRING_EMBED_EXP_START: - return true; - } - return false; - } - - /** - *
 mapLiteral : '{' (mapLiteralEntry (',' mapLiteralEntry)* ','?)? '}' ;
-   * 
- */ - @Terminals(tokens={Token.RBRACE, Token.COMMA}) - private DartExpression parseMapLiteral(boolean isConst, List typeArguments) { - beginMapLiteral(); - boolean foundOpenBrace = expect(Token.LBRACE); - boolean save = setAllowFunctionExpression(true); - List entries = new ArrayList(); - - while (!match(Token.RBRACE) && !match(Token.EOS)) { - if (!looksLikeString()) { - ctx.advance(); - reportError(position(), ParserErrorCode.EXPECTED_STRING_LITERAL_MAP_ENTRY_KEY); - if (peek(0) == Token.COMMA) { - // a common error is to put an empty entry in the list, allow it to - // recover. - continue; - } else { - break; - } - } - DartMapLiteralEntry entry = parseMapLiteralEntry(); - if (entry != null) { - entries.add(entry); - } - Token nextToken = peek(0); - switch (nextToken) { - // Must keep in sync with @Terminals above - case COMMA: - consume(Token.COMMA); - break; - // Must keep in sync with @Terminals above - case RBRACE: - break; - default: - if (entry == null) { - Set terminals = collectTerminalAnnotations(); - if (!terminals.contains(nextToken) && !looksLikeTopLevelKeyword()) { - if (entry == null) { - // Ensure the parser makes progress. - ctx.advance(); - } - } - } - reportError(position(), ParserErrorCode.EXPECTED_COMMA_OR_RIGHT_BRACE); - break; - } - } - - expectCloseBrace(foundOpenBrace); - setAllowFunctionExpression(save); - return done(new DartMapLiteral(isConst, typeArguments, entries)); - } - - /** - * // The array literal syntax doesn't allow elided elements, unlike - * // in ECMAScript. - * - *
-   * arrayLiteral
-   *     : '[' expressionList? ']'
-   *     ;
-   * 
- */ - @Terminals(tokens={Token.RBRACK, Token.COMMA}) - private DartExpression parseArrayLiteral(boolean isConst, List typeArguments) { - beginArrayLiteral(); - expect(Token.LBRACK); - boolean save = setAllowFunctionExpression(true); - List exprs = new ArrayList(); - while (!match(Token.RBRACK) && !EOS()) { - exprs.add(parseExpression()); - // Must keep in sync with @Terminals above - if (!optional(Token.COMMA)) { - break; - } - } - // Must keep in sync with @Terminals above - expect(Token.RBRACK); - setAllowFunctionExpression(save); - return done(new DartArrayLiteral(isConst, typeArguments, exprs)); - } - - /** - * Parse a postfix expression. - * - *
-   * postfixExpression
-   *     | assignableExpression postfixOperator
-   *     : primary selector*
-   *     ;
-   * 
- * - * @return an expression matching the {@code postfixExpression} production above - */ - private DartExpression parsePostfixExpression() { - beginPostfixExpression(); - DartExpression receiver = doneWithoutConsuming(parsePrimaryExpression()); - DartExpression result = receiver; - do { - receiver = result; - result = doneWithoutConsuming(parseSelectorExpression(receiver)); - } while (receiver != result); - - Token token = peek(0); - if (token.isCountOperator()) { - ensureAssignable(result); - consume(token); - int tokenOffset = ctx.getTokenLocation().getBegin(); - result = doneWithoutConsuming(new DartUnaryExpression(token, tokenOffset, result, false)); - } - - return done(result); - } - - /** - *
-   * typeParameters? (arrayLiteral | mapLiteral)
-   * 
- * - * @param isConst true if a CONST expression - * - */ - private DartExpression tryParseTypedCompoundLiteral(boolean isConst) { - beginLiteral(); - List typeArguments = parseTypeArgumentsOpt(); - switch (peek(0)) { - case INDEX: - beginArrayLiteral(); - consume(Token.INDEX); - return done(done(new DartArrayLiteral(isConst, typeArguments, new ArrayList()))); - case LBRACK: - return done(parseArrayLiteral(isConst, typeArguments)); - case LBRACE: - return done(parseMapLiteral(isConst, typeArguments)); - default: - if (typeArguments != null) { - rollback(); - return null; - } - - } - // Doesn't look like a typed compound literal and no tokens consumed. - return done(null); - } - - private enum LastSeenNode { - NONE, - STRING, - EXPRESSION; - } - - private class DartStringInterpolationBuilder { - - private final List strings = new ArrayList(); - private final List expressions = new ArrayList(); - private LastSeenNode lastSeen = LastSeenNode.NONE; - - DartStringInterpolationBuilder() { - } - - void addString(DartStringLiteral string) { - if (lastSeen == LastSeenNode.STRING) { - expressions.add(new DartSyntheticErrorExpression()); - } - strings.add(string); - lastSeen = LastSeenNode.STRING; - } - - void addExpression(DartExpression expression) { - switch (lastSeen) { - case EXPRESSION: - case NONE: - strings.add(DartStringLiteral.get("")); - break; - default: - break; - } - expressions.add(expression); - lastSeen = LastSeenNode.EXPRESSION; - } - - void addInterpolation(DartStringInterpolation interpolation) { - strings.addAll(interpolation.getStrings()); - expressions.addAll(interpolation.getExpressions()); - lastSeen = LastSeenNode.STRING; - } - - DartStringInterpolation buildInterpolation() { - if (strings.size() == expressions.size()) { - strings.add(DartStringLiteral.get("")); - } - return new DartStringInterpolation(strings, expressions); - } - } - - /** - * Instances of the class {@code StringInterpolationParseError} represent the detection of an - * error that needs to be handled in an enclosing context. - */ - private static class StringInterpolationParseError extends RuntimeException { - private static final long serialVersionUID = 1L; - - public StringInterpolationParseError() { - super(); - } - } - - /** - *
-   * string-interpolation
-   *   : (STRING_SEGMENT? embedded-exp?)* STRING_LAST_SEGMENT
-   *
-   * embedded-exp
-   *   : STRING_EMBED_EXP_START expression STRING_EMBED_EXP_END
-   * 
- */ - private DartExpression parseStringInterpolation() { - // TODO(sigmund): generalize to parse string templates as well. - if (peek(0) == Token.STRING_LAST_SEGMENT) { - throw new InternalCompilerException("Invariant broken"); - } - beginStringInterpolation(); - DartStringInterpolationBuilder builder = new DartStringInterpolationBuilder(); - boolean inString = true; - while (inString) { // Iterate until we find the last string segment. - switch (peek(0)) { - case STRING_SEGMENT: { - beginStringSegment(); - consume(Token.STRING_SEGMENT); - builder.addString(done(DartStringLiteral.get(ctx.getTokenString()))); - break; - } - case STRING_LAST_SEGMENT: { - beginStringSegment(); - consume(Token.STRING_LAST_SEGMENT); - builder.addString(done(DartStringLiteral.get(ctx.getTokenString()))); - inString = false; - break; - } - case STRING_EMBED_EXP_START: { - consume(Token.STRING_EMBED_EXP_START); - /* - * We check for ILLEGAL specifically here to give nicer error - * messages, and because the scanner doesn't generate a - * STRING_EMBED_EXP_END to match the START in the case of an ILLEGAL - * token. - */ - if (peek(0) == Token.ILLEGAL) { - reportError(position(), ParserErrorCode.UNEXPECTED_TOKEN_IN_STRING_INTERPOLATION, - next()); - builder.addExpression(new DartSyntheticErrorExpression("")); - break; - } else { - try { - builder.addExpression(parseExpression()); - } catch (StringInterpolationParseError exception) { - if (peek(0) == Token.STRING_LAST_SEGMENT) { - break; - } - throw new InternalCompilerException("Invalid expression found in string interpolation"); - } - } - Token lookAhead = peek(0); - String lookAheadString = getPeekTokenValue(0); - if (!expect(Token.STRING_EMBED_EXP_END)) { - String errorText = null; - if (lookAheadString != null && lookAheadString.length() > 0) { - errorText = lookAheadString; - } else if (lookAhead.getSyntax() != null && lookAhead.getSyntax().length() > 0) { - errorText = lookAhead.getSyntax(); - } - if (errorText != null) { - builder.addExpression(new DartSyntheticErrorExpression(errorText)); - } - inString = !(Token.STRING_LAST_SEGMENT == lookAhead); - } - break; - } - case EOS: { - reportError(position(), ParserErrorCode.INCOMPLETE_STRING_LITERAL); - inString = false; - break; - } - default: { - String errorText = getPeekTokenValue(0) != null && getPeekTokenValue(0).length() > 0 - ? getPeekTokenValue(0) : null; - if(errorText != null) { - builder.addExpression(new DartSyntheticErrorExpression(getPeekTokenValue(0))); - } - reportError(position(), ParserErrorCode.UNEXPECTED_TOKEN_IN_STRING_INTERPOLATION, - next()); - break; - } - } - } - return done(builder.buildInterpolation()); - } - - /** - * Parse a return type, giving an error if the . - * - * @return a return type or null if the current text is not a return type - */ - private DartTypeNode parseReturnType() { - if (peek(0) == Token.VOID) { - return parseVoidType(); - } else { - return parseTypeAnnotation(); - } - } - - /** - * Check if the current text could be a return type, and advance past it if so. The current - * position is unchanged if it is not a return type. - * - * NOTE: if the grammar is changed for what constitutes an acceptable return type, this method - * must be updated to match {@link #parseReturnType()}/etc. - * - * @return true if current text could be a return type, false otherwise - */ - private boolean isReturnType() { - beginReturnType(); - if (optional(Token.VOID)) { - done(null); - return true; - } - if (!optional(Token.IDENTIFIER)) { - rollback(); - return false; - } - // handle prefixed identifiers - if (optional(Token.PERIOD)) { - if (!optional(Token.IDENTIFIER)) { - rollback(); - return false; - } - } - // skip over type arguments if they are present - if (optional(Token.LT)) { - int count = 1; - while (count > 0) { - switch (next()) { - case EOS: - rollback(); - return false; - case LT: - count++; - break; - case GT: - count--; - break; - case SHL: - count += 2; - break; - case SAR: // >> - count -= 2; - break; - case COMMA: - case IDENTIFIER: - // extends is a pseudokeyword, so shows up as IDENTIFIER - break; - default: - rollback(); - return false; - } - } - if (count < 0) { - // if we had too many > (which can only be >> or >>>), can't be a return type - rollback(); - return false; - } - } - done(null); - return true; - } - - /** - * Checks to see if the current text looks like a function expression: - * - *
-   *   FUNCTION name? ( args ) < => | { >
-   *   returnType name? ( args ) < => | { >
-   *   name? ( args ) < => | { >
-   * 
- * - * The current position is unchanged on return. - * - * NOTE: if the grammar for function expressions changes, this method must be - * adapted to match the actual parsing code. It is acceptable for this method - * to return true when the source text does not actually represent a function - * expression (which would result in error messages assuming it was a function - * expression, but it must not do so when the source text would be correct if - * parsed as a non-function expression. - * - * @return true if the current text looks like a function expression, false - * otherwise - */ - @VisibleForTesting - boolean looksLikeFunctionExpression() { - if (!allowFunctionExpression) { - return false; - } - return looksLikeFunctionDeclarationOrExpression(); - } - - /** - * Check to see if the following tokens could be a function expression, and if so try and parse - * it as one. - * - * @return a function expression if found, or null (with no tokens consumed) if not - */ - private DartExpression parseFunctionExpressionWithReturnType() { - beginFunctionLiteral(); - DartIdentifier[] namePtr = new DartIdentifier[1]; - DartFunction function = parseFunctionDeclarationOrExpression(namePtr, false); - if (function == null) { - rollback(); - return null; - } - if (function != null && function.getReturnTypeNode() != null) { - reportError(function.getReturnTypeNode(), ParserErrorCode.DEPRECATED_FUNCTION_LITERAL); - } else if (namePtr[0] != null) { - reportError(namePtr[0], ParserErrorCode.DEPRECATED_FUNCTION_LITERAL); - } - return done(new DartFunctionExpression(namePtr[0], doneWithoutConsuming(function), false)); - } - - /** - * Parse a function declaration or expression, including the body. - *
-   *     ... | functionDeclaration functionBody
-   *
-   * functionDeclaration
-   *    : returnType? identifier formalParameterList
-   *    ;
-   *
-   * functionExpression
-   *    : (returnType? identifier)? formalParameterList functionExpressionBody
-   *    ;
-   *
-   * functionBody
-   *    : '=>' expression ';'
-   *    | block
-   *    ;
-   *
-   * functionExpressionBody
-   *    : '=>' expression
-   *    | block
-   *    ;
-   * 
- * - * @param namePtr out parameter - parsed function name stored in namePtr[0] - * @param isDeclaration true if this is a declaration (i.e. a name is required and a trailing - * semicolon is needed for arrow syntax - * @return a {@link DartFunction} containing the body of the function, or null - * if the next tokens cannot be parsed as a function declaration or expression - */ - private DartFunction parseFunctionDeclarationOrExpression(DartIdentifier[] namePtr, - boolean isDeclaration) { - DartTypeNode returnType = null; - namePtr[0] = null; - if (optionalPseudoKeyword(STATIC_KEYWORD)) { - reportError(position(), ParserErrorCode.LOCAL_CANNOT_BE_STATIC); - } - switch (peek(0)) { - case LPAREN: - // no type or name, just the formal parameter list - break; - case IDENTIFIER: - if (peek(1) == Token.LPAREN) { - // if there is only one identifier, it must be the name - namePtr[0] = parseIdentifier(); - break; - } - //$FALL-THROUGH$ - case VOID: - returnType = parseReturnType(); - if (peek(0) == Token.IDENTIFIER) { - namePtr[0] = parseIdentifier(); - } - break; - default: - return null; - } - FormalParameters params = parseFormalParameterList(); - int parametersCloseParen = ctx.getTokenLocation().getBegin(); - DartBlock body = parseFunctionStatementBody(true, isDeclaration); - DartFunction function = new DartFunction(params.val, params.openParen, - params.optionalOpenOffset, params.optionalCloseOffset, parametersCloseParen, body, - returnType); - doneWithoutConsuming(function); - return function; - } - - /** - * Parse a primary expression. - * - *
-   * primary
-   *   : THIS
-   *   | SUPER assignableSelector
-   *   | literal
-   *   | identifier
-   *   | NEW type ('.' identifier)? arguments
-   *   | typeArguments? (arrayLiteral | mapLiteral)
-   *   | CONST typeArguments? (arrayLiteral | mapLiteral)
-   *   | CONST typeArguments? (arrayLiteral | mapLiteral)
-   *   | CONST type ('.' identifier)? arguments
-   *   | '(' expression ')'
-   *   | string-interpolation
-   *   | functionExpression
-   *   ;
-   * 
- * - * @return an expression matching the {@code primary} production above - */ - private DartExpression parsePrimaryExpression() { - if (looksLikeFunctionExpression()) { - return parseFunctionExpressionWithReturnType(); - } - switch (peek(0)) { - case THIS: { - beginThisExpression(); - consume(Token.THIS); - return done(DartThisExpression.get()); - } - - case SUPER: { - beginSuperExpression(); - consume(Token.SUPER); - return done(DartSuperExpression.get()); - } - - case NEW: { - beginNewExpression(); // DartNewExpression - consume(Token.NEW); - return done(parseConstructorInvocation(false)); - } - - case CONST: { - beginConstExpression(); - consume(Token.CONST); - - DartExpression literal = tryParseTypedCompoundLiteral(true); - if (literal != null) { - return done(literal); - } - return done(parseConstructorInvocation(true)); - } - - case LPAREN: { - beginParenthesizedExpression(); - consume(Token.LPAREN); - beginExpression(); - // inside parens, function blocks are allowed again - boolean save = setAllowFunctionExpression(true); - DartExpression expression = done(parseExpression()); - setAllowFunctionExpression(save); - expectCloseParen(); - return done(new DartParenthesizedExpression(expression)); - } - - case LT: { - beginLiteral(); - DartExpression literal = tryParseTypedCompoundLiteral(false); - if (literal == null) { - reportError(position(), ParserErrorCode.EXPECTED_ARRAY_OR_MAP_LITERAL); - } - return done(literal); - } - - case STRING: - case STRING_SEGMENT: - case STRING_EMBED_EXP_START: { - return parseStringWithPasting(); - } - - case STRING_LAST_SEGMENT: - throw new StringInterpolationParseError(); - - case CONDITIONAL: - return parseArgumentDefinitionTest(); - - default: { - return parseLiteral(); - } - } - } - - private DartExpression parseArgumentDefinitionTest() { - beginArgumentDefinitionTest(); - int operatorOffset = position(); - expect(Token.CONDITIONAL); - return done(new DartUnaryExpression(Token.CONDITIONAL, operatorOffset, parseIdentifier(), true)); - } - - private DartExpression parseConstructorInvocation(boolean isConst) { - List parts = new ArrayList(); - beginConstructor(); - do { - beginConstructorNamePart(); - parts.add(done(new DartTypeNode(parseIdentifier(), parseTypeArgumentsOpt()))); - } while (optional(Token.PERIOD)); - assert parts.size() > 0; - - DartNode constructor; - switch (parts.size()) { - case 1: - constructor = doneWithoutConsuming(parts.get(0)); - break; - - case 2: { - // This case is ambiguous. It can either be prefix.Type or - // Type.namedConstructor. - boolean hasPrefix = false; - DartTypeNode part1 = parts.get(0); - DartTypeNode part2 = parts.get(1); - if (prefixes.contains(((DartIdentifier) part1.getIdentifier()).getName())) { - hasPrefix = true; - } - if (!part2.getTypeArguments().isEmpty()) { - // If the second part has type arguments, the first part must be a prefix. - // If it isn't a prefix, the resolver will complain. - hasPrefix = true; - } - if (hasPrefix) { - constructor = doneWithoutConsuming(toPrefixedType(parts)); - } else { - // Named constructor. - DartIdentifier identifier = (DartIdentifier) part2.getIdentifier(); - constructor = doneWithoutConsuming(new DartPropertyAccess(part1, identifier)); - } - break; - } - default: { - // This case is unambiguous. It must be prefix.Type.namedConstructor. - if (parts.size() > 3) { - reportError(parts.get(3), ParserErrorCode.EXPECTED_LEFT_PAREN); - } - DartTypeNode typeNode = doneWithoutConsuming(toPrefixedType(parts)); - DartIdentifier identifier = (DartIdentifier)parts.get(2).getIdentifier(); - constructor = doneWithoutConsuming(new DartPropertyAccess(typeNode, identifier)); - break; - } - } - - boolean save = setAllowFunctionExpression(true); - try { - List args = parseArguments(); - return done(new DartNewExpression(constructor, args, isConst)); - } finally { - setAllowFunctionExpression(save); - } - } - - private DartTypeNode toPrefixedType(List parts) { - DartIdentifier part1 = (DartIdentifier)parts.get(0).getIdentifier(); - DartTypeNode part2 = parts.get(1); - DartIdentifier identifier = (DartIdentifier) part2.getIdentifier(); - DartPropertyAccess access = doneWithoutConsuming(new DartPropertyAccess(part1, identifier)); - return new DartTypeNode(access, part2.getTypeArguments()); - } - - /** - * Parse a selector expression. - * - *
-   * selector
-   *    : assignableSelector
-   *    | arguments
-   *    ;
-   * 
- * - * @return an expression matching the {@code selector} production above - */ - private DartExpression parseSelectorExpression(DartExpression receiver) { - DartExpression expression = tryParseAssignableSelector(receiver); - if (expression != null) { - return expression; - } - - if (peek(0) == Token.LPAREN) { - beginSelectorExpression(); - boolean save = setAllowFunctionExpression(true); - List args = parseArguments(); - setAllowFunctionExpression(save); - if (receiver instanceof DartIdentifier) { - return(done(new DartUnqualifiedInvocation((DartIdentifier) receiver, args))); - } else { - return(done(new DartFunctionObjectInvocation(receiver, args))); - } - } - - return receiver; - } - - /** - *
-   * assignableSelector
-   *    : '[' expression ']'
-   *    | '.' identifier
-   *    ;
-   * 
- */ - private DartExpression tryParseAssignableSelector(DartExpression receiver) { - switch (peek(0)) { - case PERIOD: - consume(Token.PERIOD); - switch (peek(0)) { - case SEMICOLON: - case RBRACE: - reportError(position(), ParserErrorCode.EXPECTED_IDENTIFIER); - DartIdentifier error = doneWithoutConsuming(new DartIdentifier("")); - return doneWithoutConsuming(new DartPropertyAccess(receiver, error)); - } - // receiver.() = missing name - if (peek(0) == Token.LPAREN) { - reportUnexpectedToken(position(), Token.IDENTIFIER, peek(0)); - DartIdentifier name; - { - beginIdentifier(); - name = done(new DartSyntheticErrorIdentifier()); - } - boolean save = setAllowFunctionExpression(true); - DartMethodInvocation expr = doneWithoutConsuming(new DartMethodInvocation(receiver, - false, name, parseArguments())); - setAllowFunctionExpression(save); - return expr; - } - // expect name - DartIdentifier name = parseIdentifier(); - if (peek(0) == Token.LPAREN) { - boolean save = setAllowFunctionExpression(true); - DartMethodInvocation expr = doneWithoutConsuming(new DartMethodInvocation(receiver, false, - name, parseArguments())); - setAllowFunctionExpression(save); - return expr; - } else { - return doneWithoutConsuming(new DartPropertyAccess(receiver, name)); - } - - case LBRACK: - consume(Token.LBRACK); - DartExpression key = parseExpression(); - expect(Token.RBRACK); - return doneWithoutConsuming(new DartArrayAccess(receiver, key)); - - default: - return null; - } - } - - /** - *
-   * block
-   *     : '{' statements deadCode* '}'
-   *     ;
-   *
-   * statements
-   *     : statement*
-   *     ;
-   *
-   * deadCode
-   *     : (normalCompletingStatement | abruptCompletingStatement)
-   *     ;
-   * 
- */ - @Terminals(tokens={Token.RBRACE}) - private DartBlock parseBlock() { - if (isDietParse) { - expect(Token.LBRACE); - DartBlock emptyBlock = new DartBlock(new ArrayList()); - int nesting = 1; - while (nesting > 0) { - Token token = next(); - switch (token) { - case LBRACE: - ++nesting; - break; - case RBRACE: - --nesting; - break; - case EOS: - return emptyBlock; - } - } - // Return an empty block so we don't generate unparseable code. - return emptyBlock; - } else { - Token nextToken = peek(0); - if (!nextToken.equals(Token.LBRACE) - && (looksLikeTopLevelKeyword() || nextToken.equals(Token.RBRACE))) { - beginBlock(); - // Allow recovery back to the top level. - reportErrorWithoutAdvancing(ParserErrorCode.UNEXPECTED_TOKEN); - return done(new DartBlock(new ArrayList())); - } - beginBlock(); - List statements = new ArrayList(); - boolean foundOpenBrace = expect(Token.LBRACE); - - while (!match(Token.RBRACE) && !EOS()) { - if (looksLikeTopLevelKeyword()) { - reportErrorWithoutAdvancing(ParserErrorCode.UNEXPECTED_TOKEN); - break; - } - int startPosition = position(); - DartStatement newStatement = parseStatement(); - if (newStatement == null) { - break; - } - if (startPosition == position()) { - // The parser is not making progress. - Set terminals = this.collectTerminalAnnotations(); - if (terminals.contains(peek(0))) { - // bail out of the block - break; - } - reportUnexpectedToken(position(), null, next()); - } - statements.add(newStatement); - } - expectCloseBrace(foundOpenBrace); - return done(new DartBlock(statements)); - } - } - - /** - * Parse a function statement body. - * - *
-   * functionStatementBody
-   *    : '=>' expression ';'
-   *    | block
-   * 
- * - * @param requireSemicolonForArrow true if a semicolon is required after an arrow expression - * @return {@link DartBlock} instance containing function body - */ - private DartBlock parseFunctionStatementBody(boolean allowBody, boolean requireSemicolonForArrow) { - // A break inside a function body should have nothing to do with a loop in - // the code surrounding the definition. - boolean oldInLoopStatement = inLoopStatement; - boolean oldInCaseStatement = inCaseStatement; - inLoopStatement = inCaseStatement = false; - try { - DartBlock result; - if (isDietParse) { - result = dietParseFunctionStatementBody(); - } else { - beginFunctionStatementBody(); - if (optional(Token.SEMICOLON)) { - if (allowBody) { - reportError(position(), ParserErrorCode.EXPECTED_FUNCTION_STATEMENT_BODY); - } - result = done(null); - } else if (optional(Token.ARROW)) { - DartExpression expr = parseExpression(); - if (expr == null) { - expr = new DartSyntheticErrorExpression(); - } - if (requireSemicolonForArrow) { - expect(Token.SEMICOLON); - } - result = done(makeReturnBlock(expr)); - } else { - result = done(parseBlock()); - } - } - if (!allowBody && result != null) { - reportError(result, ParserErrorCode.EXTERNAL_METHOD_BODY); - } - return result; - } finally { - inLoopStatement = oldInLoopStatement; - inCaseStatement = oldInCaseStatement; - } - } - - private DartBlock dietParseFunctionStatementBody() { - DartBlock emptyBlock = new DartBlock(new ArrayList()); - if (optional(Token.ARROW)) { - while (true) { - Token token = next(); - if (token == Token.SEMICOLON) { - break; - } - } - } else { - if (!peek(0).equals(Token.LBRACE) && looksLikeTopLevelKeyword()) { - // Allow recovery back to the top level. - reportErrorWithoutAdvancing(ParserErrorCode.UNEXPECTED_TOKEN); - return done(emptyBlock); - } - expect(Token.LBRACE); - int nesting = 1; - while (nesting > 0) { - Token token = next(); - switch (token) { - case LBRACE: - ++nesting; - break; - case RBRACE: - --nesting; - break; - case EOS: - return emptyBlock; - } - } - } - // Return an empty block so we don't generate unparseable code. - return emptyBlock; - } - - /** - * Create a block containing a single return statement. - * - * @param returnVal return value expression - * @return block containing a single return statement - */ - private DartBlock makeReturnBlock(DartExpression returnVal) { - return new DartReturnBlock(returnVal); - } - - /** - *
-   * initializedVariableDeclaration
-   *     : constVarOrType initializedIdentifierList
-   *     ;
-   *
-   * initializedIdentifierList
-   *     : initializedIdentifier (',' initializedIdentifier)*
-   *     ;
-   *
-   * initializedIdentifier
-   *     : IDENTIFIER ('=' assignmentExpression)?
-   *     ;
-   *  
- */ - private List parseInitializedVariableList() { - List idents = new ArrayList(); - do { - beginVariableDeclaration(); - List metadata = parseMetadata(); - DartIdentifier name = parseIdentifier(); - DartExpression value = null; - if (isParsingInterface) { - expect(Token.ASSIGN); - value = parseExpression(); - } else if (optional(Token.ASSIGN)) { - value = parseExpression(); - } - DartVariable variable = done(new DartVariable(name, value)); - setMetadata(variable, metadata); - idents.add(variable); - } while (optional(Token.COMMA)); - - return idents; - } - - private DartAssertStatement parseAssertStatement() { - beginAssertStatement(); - expect(Token.ASSERT); - expect(Token.LPAREN); - DartExpression condition = parseExpression(); - expectCloseParen(); - expectStatmentTerminator(); - return done(new DartAssertStatement(condition)); - } - - /** - *
-   * abruptCompletingStatement
-   *     : BREAK identifier? ';'
-   *     | CONTINUE identifier? ';'
-   *     | RETURN expression? ';'
-   *     | THROW expression? ';'
-   *     ;
-   *  
- */ - private DartBreakStatement parseBreakStatement() { - beginBreakStatement(); - expect(Token.BREAK); - DartIdentifier label = null; - if (match(Token.IDENTIFIER)) { - label = parseIdentifier(); - } else if (!inLoopStatement && !inCaseStatement) { - // The validation of matching of labels to break statements is done later. - reportErrorWithoutAdvancing(ParserErrorCode.BREAK_OUTSIDE_OF_LOOP); - } - expectStatmentTerminator(); - return done(new DartBreakStatement(label)); - } - - private DartContinueStatement parseContinueStatement() { - beginContinueStatement(); - expect(Token.CONTINUE); - DartIdentifier label = null; - if (!inLoopStatement && !inCaseStatement) { - reportErrorWithoutAdvancing(ParserErrorCode.CONTINUE_OUTSIDE_OF_LOOP); - } - if (peek(0) == Token.IDENTIFIER) { - label = parseIdentifier(); - } else if (!inLoopStatement && inCaseStatement) { - reportErrorWithoutAdvancing(ParserErrorCode.CONTINUE_IN_CASE_MUST_HAVE_LABEL); - } - expectStatmentTerminator(); - return done(new DartContinueStatement(label)); - } - - private DartReturnStatement parseReturnStatement() { - beginReturnStatement(); - expect(Token.RETURN); - DartExpression value = null; - if (peek(0) != Token.SEMICOLON) { - value = parseExpression(); - } - expectStatmentTerminator(); - return done(new DartReturnStatement(value)); - } - - private DartThrowExpression parseThrowExpression(boolean allowCascade) { - beginThrowExpression(); - expect(Token.THROW); - DartExpression exception = null; - if (peek(0) != Token.SEMICOLON && peek(0) != Token.RPAREN) { - if (allowCascade) { - exception = parseExpression(); - } else { - exception = parseExpressionWithoutCascade(); - } - } - return done(new DartThrowExpression(exception)); - } - - /** - *
-   * statement
-   *     : label* nonLabelledStatement
-   *     ;
-   *
-   * label
-   *     : identifier ':'
-   *     ;
-   * 
- * - * @return a {@link DartStatement} - */ - @VisibleForTesting - public DartStatement parseStatement() { - List labels = new ArrayList(); - while (peek(0) == Token.IDENTIFIER && peek(1) == Token.COLON) { - beginLabel(); - labels.add(parseIdentifier()); - expect(Token.COLON); - } - List metadata = parseMetadata(); - DartStatement statement = parseNonLabelledStatement(); - if (!metadata.isEmpty() && statement instanceof DartVariableStatement) { - DartVariableStatement variableStatement = (DartVariableStatement) statement; - if (!variableStatement.getVariables().isEmpty()) { - setMetadata(variableStatement.getVariables().get(0), metadata); - } - } - for (int i = labels.size() - 1; i >= 0; i--) { - statement = done(new DartLabel(labels.get(i), statement)); - } - return statement; - } - - private boolean isFunctionExpression(DartStatement statement) { - if (!(statement instanceof DartExprStmt)) { - return false; - } - DartExpression expression = ((DartExprStmt) statement).getExpression(); - if (!(expression instanceof DartFunctionExpression)) { - return false; - } - return ((DartFunctionExpression) expression).getName() == null; - } - - /** - *
-   * normalCompletingStatement
-   *     : functionStatement
-   *     | initializedVariableDeclaration ';'
-   *     | simpleStatement
-   *     ;
-   *
-   * functionStatement
-   *     : typeOrFunction identifier formalParameterList block
-   *     ;
-   *     ;
-   *
-   * simpleStatement
-   *     : ('{')=> block // Guard to break tie with map literal.
-   *     | expression? ';'
-   *     | tryStatement
-   *     | ASSERT '(' conditionalExpression ')' ';'
-   *     | abruptCompletingStatement
-   *     ;
-   * 
- */ - // TODO(zundel): Possibly we could use Token.IDENTIFIER too, but it is used - // in so many places, it might make recovery worse rather than better. - @Terminals(tokens={Token.IF, Token.SWITCH, Token.WHILE, Token.DO, Token.FOR, - Token.VAR, Token.FINAL, Token.CONTINUE, Token.BREAK, Token.RETHROW, - Token.RETURN, Token.THROW, Token.TRY, Token.SEMICOLON }) - private DartStatement parseNonLabelledStatement() { - // Try to parse as function declaration. - if (looksLikeFunctionDeclarationOrExpression()) { - ctx.begin(); - DartStatement functionDeclaration = parseFunctionDeclaration(); - // If "null", then we tried to parse, but found that this is not function declaration. - // So, parsing was rolled back and we can try to parse it as expression. - if (functionDeclaration != null) { - if (!isFunctionExpression(functionDeclaration)) { - ctx.done(null); - return functionDeclaration; - } - ctx.rollback(); - } else { - ctx.done(null); - } - } - // Check possible statement kind. - switch (peek(0)) { - case ASSERT: - return parseAssertStatement(); - - case IF: - return parseIfStatement(); - - case SWITCH: - return parseSwitchStatement(); - - case WHILE: - return parseWhileStatement(); - - case DO: - return parseDoWhileStatement(); - - case FOR: - return parseForStatement(); - - case VAR: { - beginVarDeclaration(); - consume(Token.VAR); - List vars = parseInitializedVariableList(); - expectStatmentTerminator(); - return done(new DartVariableStatement(vars, null)); - } - - case FINAL: { - beginFinalDeclaration(); - consume(peek(0)); - DartTypeNode type = null; - if (peek(1) == Token.IDENTIFIER || peek(1) == Token.LT || peek(1) == Token.PERIOD) { - // We know we have a type. - type = parseTypeAnnotation(); - } - List vars = parseInitializedVariableList(); - expectStatmentTerminator(); - return done(new DartVariableStatement(vars, type, Modifiers.NONE.makeFinal())); - } - - case LBRACE: - Token token = peek(1); - if (token == Token.STRING || token == Token.STRING_SEGMENT || token == Token.STRING_EMBED_EXP_START) { - int offset = skipStringLiteral(1); - if (peek(offset) == Token.COLON) { - DartStatement statement = parseExpressionStatement(); - if (statement instanceof DartExprStmt - && ((DartExprStmt) statement).getExpression() instanceof DartMapLiteral) { - reportError( - ((DartExprStmt) statement).getExpression(), - ParserErrorCode.NON_CONST_MAP_LITERAL_STATEMENT); - } - return statement; - } - } - return parseBlock(); - - case CONTINUE: - return parseContinueStatement(); - - case BREAK: - return parseBreakStatement(); - - case RETURN: - return parseReturnStatement(); - - case THROW: - return parseExpressionStatement(); - - case RETHROW: - consume(Token.RETHROW); - beginExpressionStatement(); - return done(new DartExprStmt(new DartThrowExpression(null))); - - case TRY: - return parseTryStatement(); - - case SEMICOLON: - beginEmptyStatement(); - consume(Token.SEMICOLON); - return done(new DartEmptyStatement()); - - case CONST: - // Check to see whether this is a variable declaration. If not, then default to parsing an - // expression statement. - int offset = skipTypeName(1); - if (offset > 1 && (peek(offset) == Token.IDENTIFIER || (offset == 2 - && (peek(offset) == Token.ASSIGN || peek(offset) == Token.COMMA || peek(offset) == Token.SEMICOLON)))) { - boolean hasType = peek(offset) == Token.IDENTIFIER; - beginVariableDeclaration(); - next(); - DartTypeNode type = null; - if (hasType) { - type = parseTypeAnnotation(); - } - List vars = parseInitializedVariableList(); - expect(Token.SEMICOLON); - return done(new DartVariableStatement(vars, type, Modifiers.NONE.makeConstant().makeFinal())); - } - break; - - case IDENTIFIER: - // We have already eliminated function declarations earlier, so check for: - // a) variable declarations; - // b) beginning of function literal invocation. - if (peek(1) == Token.LT || peekMaybeAS(1) == Token.IDENTIFIER - || (peek(1) == Token.PERIOD && peek(2) == Token.IDENTIFIER)) { - beginTypeFunctionOrVariable(); - DartTypeNode type = tryTypeAnnotation(); - if (type != null && peekMaybeAS(0) == Token.IDENTIFIER) { - List vars = parseInitializedVariableList(); - if (optional(Token.SEMICOLON)) { - return done(new DartVariableStatement(vars, type)); - } else if (peek(0) == Token.LPAREN) { - // Probably a function object invocation. - rollback(); - } else { - //reportError(position(), ParserErrorCode.EXPECTED_SEMICOLON); - expectStatmentTerminator(); - return done(new DartVariableStatement(vars, type)); - } - } else { - rollback(); - } - } - break; - } - return parseExpressionStatement(); - } - - /** - * Check if succeeding tokens look like a function declaration - the parser state is unchanged - * upon return. - * - * See {@link #parseFunctionDeclaration()}. - * - * @return true if the following tokens should be parsed as a function definition - */ - private boolean looksLikeFunctionDeclarationOrExpression() { - beginMethodName(); - try { - optionalPseudoKeyword(STATIC_KEYWORD); - if (peek(0) == Token.IDENTIFIER && peek(1) == Token.LPAREN) { - // just a name, no return type - consume(Token.IDENTIFIER); - } else if (isReturnType()) { - if (!optional(Token.IDENTIFIER)) { - // return types must be followed by a function name - return false; - } - } - // start of parameter list - if (!optional(Token.LPAREN)) { - return false; - } - // if it looks as "(Type name, ....)" then it may be function expression - boolean hasTwoIdentifiersComma; - { - int nameOffset = skipTypeName(0); - hasTwoIdentifiersComma = nameOffset != -1 && peek(nameOffset + 0) == Token.IDENTIFIER - && peek(nameOffset + 1) == Token.COMMA; - } - // find matching parenthesis - int count = 1; - while (count != 0) { - switch (next()) { - case EOS: - return false; - case LPAREN: - count++; - break; - case RPAREN: - count--; - break; - } - } - return (peek(0) == Token.ARROW || peek(0) == Token.LBRACE) || hasTwoIdentifiersComma; - } finally { - rollback(); - } - } - - /** - * Parse a function declaration. - * - *
-   * nonLabelledStatement : ...
-   *     | functionDeclaration functionBody
-   *
-   * functionDeclaration
-   *    : FUNCTION identifier formalParameterList
-   *      { legacy($start, "deprecated 'function' keyword"); }
-   *    | returnType error=FUNCTION identifier? formalParameterList
-   *      { legacy($error, "deprecated 'function' keyword"); }
-   *    | returnType? identifier formalParameterList
-   *    ;
-   * 
- * - * @return a {@link DartStatement} representing the function declaration or null if - * code ends with function invocation, so this is not function declaration. - */ - private DartStatement parseFunctionDeclaration() { - beginFunctionDeclaration(); - DartIdentifier[] namePtr = new DartIdentifier[1]; - DartFunction function = parseFunctionDeclarationOrExpression(namePtr, true); - if (function.getBody() instanceof DartReturnBlock || peek(0) != Token.LPAREN) { - return done(new DartExprStmt(doneWithoutConsuming(new DartFunctionExpression(namePtr[0], - doneWithoutConsuming(function), - true)))); - } else { - rollback(); - return null; - } - } - - private DartStatement parseExpressionStatement() { - beginExpressionStatement(); - DartExpression expression = parseExpression(); - expectStatmentTerminator(); - - return done(new DartExprStmt(expression)); - } - - /** - * Expect a close paren, reporting an error and consuming tokens until a - * plausible continuation is found if it isn't present. - */ - private void expectCloseParen() { - int parenCount = 1; - Token nextToken = peek(0); - switch (nextToken) { - case RPAREN: - expect(Token.RPAREN); - return; - - case EOS: - case LBRACE: - case SEMICOLON: - reportError(position(), ParserErrorCode.EXPECTED_TOKEN, Token.RPAREN.getSyntax(), - nextToken.getSyntax()); - return; - - case LPAREN: - ++parenCount; - //$FALL-THROUGH$ - default: - reportError(position(), ParserErrorCode.EXPECTED_TOKEN, Token.RPAREN.getSyntax(), - nextToken.getSyntax()); - Set terminals = this.collectTerminalAnnotations(); - if (terminals.contains(nextToken) || looksLikeTopLevelKeyword()) { - return; - } - break; - } - - // eat tokens until we get a close paren or a plausible terminator (which - // is not consumed) - while (parenCount > 0) { - switch (peek(0)) { - case RPAREN: - expect(Token.RPAREN); - --parenCount; - break; - - case LPAREN: - expect(Token.LPAREN); - ++parenCount; - break; - - case EOS: - reportErrorWithoutAdvancing(ParserErrorCode.UNEXPECTED_TOKEN); - return; - - case LBRACE: - case SEMICOLON: - return; - - default: - next(); - break; - } - } - } - - /** - * Expect a close brace, reporting an error and consuming tokens until a - * plausible continuation is found if it isn't present. - */ - private void expectCloseBrace(boolean foundOpenBrace) { - // If a top level keyword is seen, bail out to recover. - if (looksLikeTopLevelKeyword()) { - reportUnexpectedToken(position(), Token.RBRACE, peek(0)); - return; - } - - int braceCount = 0; - if (foundOpenBrace) { - braceCount++; - } - Token nextToken = peek(0); - if (expect(Token.RBRACE)) { - return; - } - if (nextToken == Token.LBRACE) { - braceCount++; - } - - // eat tokens until we get a matching close brace or end of stream - while (braceCount > 0) { - if (looksLikeTopLevelKeyword()) { - return; - } - switch (next()) { - case RBRACE: - braceCount--; - break; - - case LBRACE: - braceCount++; - break; - - case EOS: - return; - } - } - } - - /** - * Collect plausible statement tokens and return a synthetic error statement - * containing them. - *

- * Note that this is a crude heuristic that needs to be improved for better - * error recovery. - * - * @return a {@link DartSyntheticErrorStatement} - */ - private DartStatement parseErrorStatement() { - StringBuilder buf = new StringBuilder(); - boolean done = false; - int braceCount = 1; - while (!done) { - buf.append(getPeekTokenValue(0)); - next(); - switch (peek(0)) { - case RBRACE: - if (--braceCount == 0) { - done = true; - } - break; - case LBRACE: - braceCount++; - break; - case EOS: - case SEMICOLON: - done = true; - break; - } - } - return new DartSyntheticErrorStatement(buf.toString()); - } - - - /** - * Look for a statement terminator, giving error messages and consuming tokens - * for error recovery. - */ - protected void expectStatmentTerminator() { - Token token = peek(0); - if (expect(Token.SEMICOLON)) { - return; - } - Set terminals = collectTerminalAnnotations(); - assert(terminals.contains(Token.SEMICOLON)); - - if (peek(0) == token) { - reportErrorWithoutAdvancing(ParserErrorCode.EXPECTED_SEMICOLON); - } else { - reportError(position(), ParserErrorCode.EXPECTED_SEMICOLON); - token = peek(0); - } - - // Consume tokens until we see something that could terminate or start a new statement - while (token != Token.SEMICOLON) { - if (looksLikeTopLevelKeyword() || terminals.contains(token)) { - return; - } - token = next(); - } - } - - /** - * Report an error without advancing past the next token. - * - * @param errCode the error code to report, which may take a string parameter - * containing the actual token found - */ - private void reportErrorWithoutAdvancing(ErrorCode errCode) { - startLookahead(); - Token actual = peek(0); - next(); - reportError(position(), errCode, actual); - rollback(); - } - - /** - *

-   * iterationStatement
-   *     : WHILE '(' expression ')' statement
-   *     | DO statement WHILE '(' expression ')' ';'
-   *     | FOR '(' forLoopParts ')' statement
-   *     ;
-   *  
- */ - private DartWhileStatement parseWhileStatement() { - beginWhileStatement(); - expect(Token.WHILE); - expect(Token.LPAREN); - DartExpression condition = parseExpression(); - expectCloseParen(); - int closeParenOffset = ctx.getTokenLocation().getBegin(); - DartStatement body = parseLoopStatement(); - return done(new DartWhileStatement(condition, closeParenOffset, body)); - } - - /** - *
-   * iterationStatement
-   *     : WHILE '(' expression ')' statement
-   *     | DO statement WHILE '(' expression ')' ';'
-   *     | FOR '(' forLoopParts ')' statement
-   *     ;
-   *  
- */ - private DartDoWhileStatement parseDoWhileStatement() { - beginDoStatement(); - expect(Token.DO); - DartStatement body = parseLoopStatement(); - expect(Token.WHILE); - expect(Token.LPAREN); - DartExpression condition = parseExpression(); - expectCloseParen(); - expectStatmentTerminator(); - return done(new DartDoWhileStatement(condition, body)); - } - - /** - * Use this wrapper to parse the body of a loop - * - * Sets up flag variables to make sure continue and break are properly - * marked as errors when in wrong context. - */ - private DartStatement parseLoopStatement() { - boolean oldInLoop = inLoopStatement; - inLoopStatement = true; - try { - return parseStatement(); - } finally { - inLoopStatement = oldInLoop; - } - } - - /** - *
-   * iterationStatement
-   *     : WHILE '(' expression ')' statement
-   *     | DO statement WHILE '(' expression ')' ';'
-   *     | FOR '(' forLoopParts ')' statement
-   *     ;
-   *
-   * forLoopParts
-   *     : forInitializerStatement expression? ';' expressionList?
-   *     | constVarOrType? identifier IN expression
-   *     ;
-   *
-   * forInitializerStatement
-   *     : initializedVariableDeclaration ';'
-   *     | expression? ';'
-   *     ;
-   * 
- */ - private DartStatement parseForStatement() { - beginForStatement(); - expect(Token.FOR); - expect(Token.LPAREN); - - // Setup - DartStatement setup = null; - if (peek(0) != Token.SEMICOLON) { - // Found a setup expression/statement - beginForInitialization(); - Modifiers modifiers = Modifiers.NONE; - if (optional(Token.VAR)) { - setup = done(new DartVariableStatement(parseInitializedVariableList(), null, modifiers)); - } else { - if (optional(Token.CONST)) { - modifiers = modifiers.makeConstant(); - } - if (optional(Token.FINAL)) { - modifiers = modifiers.makeFinal(); - } - DartTypeNode type = (peek(1) == Token.IDENTIFIER || peek(1) == Token.LT || peek(1) == Token.PERIOD) - ? tryTypeAnnotation() : null; - if (modifiers.isFinal() || type != null) { - setup = done(new DartVariableStatement(parseInitializedVariableList(), type, modifiers)); - } else { - setup = done(new DartExprStmt(parseExpression())); - } - } - } - - if (optional(Token.IN)) { - if (setup instanceof DartVariableStatement) { - DartVariableStatement variableStatement = (DartVariableStatement) setup; - List variables = variableStatement.getVariables(); - if (variables.size() != 1) { - reportError(variables.get(1), ParserErrorCode.FOR_IN_WITH_MULTIPLE_VARIABLES); - } - DartExpression initializer = variables.get(0).getValue(); - if (initializer != null) { - reportError(initializer, ParserErrorCode.FOR_IN_WITH_VARIABLE_INITIALIZER); - } - } else { - DartExpression expression = ((DartExprStmt) setup).getExpression(); - if (!(expression instanceof DartIdentifier)) { - reportError(setup, ParserErrorCode.FOR_IN_WITH_COMPLEX_VARIABLE); - } - } - - DartExpression iterable = parseExpression(); - expectCloseParen(); - int closeParenOffset = ctx.getTokenLocation().getBegin(); - - DartStatement body = parseLoopStatement(); - return done(new DartForInStatement(setup, iterable, closeParenOffset, body)); - - } else if (optional(Token.SEMICOLON)) { - - // Condition - DartExpression condition = null; - if (peek(0) != Token.SEMICOLON) { - condition = parseExpression(); - } - expect(Token.SEMICOLON); - - // Next - DartExpression next = null; - if (peek(0) != Token.RPAREN) { - next = parseExpressionList(); - } - expectCloseParen(); - int closeParenOffset = ctx.getTokenLocation().getBegin(); - - DartStatement body = parseLoopStatement(); - return done(new DartForStatement(setup, condition, next, closeParenOffset, body)); - } else { - reportUnexpectedToken(position(), null, peek(0)); - return done(parseErrorStatement()); - } - } - - /** - *
-   * selectionStatement
-   *    : IF '(' expression ')' statement ((ELSE)=> ELSE statement)?
-   *    | SWITCH '(' expression ')' '{' switchCase* defaultCase? '}'
-   *    ;
-   * 
- */ - private DartIfStatement parseIfStatement() { - beginIfStatement(); - expect(Token.IF); - expect(Token.LPAREN); - DartExpression condition = parseExpression(); - expectCloseParen(); - int closeParenOffset = ctx.getTokenLocation().getBegin(); - DartStatement yes = parseStatement(); - DartStatement no = null; - int elseTokenOffset = 0; - if (optional(Token.ELSE)) { - elseTokenOffset = ctx.getTokenLocation().getBegin(); - no = parseStatement(); - } - return done(new DartIfStatement(condition, closeParenOffset, yes, elseTokenOffset, no)); - } - - /** - *
-   * caseStatements
-   *    : normalCompletingStatement* abruptCompletingStatement
-   *    ;
-   * 
- */ - private List parseCaseStatements() { - List statements = new ArrayList(); - DartStatement statement = null; - boolean endOfCaseFound = false; - boolean warnedUnreachable = false; - while (true) { - switch (peek(0)) { - case CLASS: - // exit loop to report error condition - case CASE: - case DEFAULT: - case RBRACE: - case EOS: - return statements; - case IDENTIFIER: - // Handle consecutively labeled case statements - if (isCaseOrDefault()) { - return statements; - } - default: - boolean oldInCaseStatement = inCaseStatement; - inCaseStatement = true; - try { - if (endOfCaseFound && !warnedUnreachable) { - reportErrorWithoutAdvancing(ParserErrorCode.UNREACHABLE_CODE_IN_CASE); - warnedUnreachable = true; - } - statement = parseStatement(); - } finally { - inCaseStatement = oldInCaseStatement; - } - if (statement == null) { - return statements; - } - - // Don't add unreachable code to the list of statements. - if (!endOfCaseFound) { - statements.add(statement); - if (statement.isAbruptCompletingStatement()) { - endOfCaseFound = true; - } - } - } - } - } - - private boolean isCaseOrDefault() { - int index = 0; - while (peek(index) == Token.IDENTIFIER && peek(index + 1) == Token.COLON) { - index += 2; - } - Token next = peek(index); - return next == Token.CASE || next == Token.DEFAULT; - } - - /** - *
-   * switchCase
-   *    : label? (CASE expression ':')+ caseStatements
-   *    ;
-   * 
- */ - private DartSwitchMember parseCaseMember(List labels) { - // The begin() associated with the done() in this method is in the method - // parseSwitchStatement(), called by beginSwitchMember(). - expect(Token.CASE); - DartExpression caseExpr = parseExpression(); - expect(Token.COLON); - return done(new DartCase(caseExpr, labels, parseCaseStatements())); - } - - /** - *
-   * defaultCase
-   *    : label? (CASE expression ':')* DEFAULT ':' caseStatements
-   *    ;
-   * 
- */ - private DartSwitchMember parseDefaultMember(List labels) { - // The begin() associated with the done() in this method is in the method - // parseSwitchStatement(), called by beginSwitchMember(). - expect(Token.DEFAULT); - expect(Token.COLON); - return done(new DartDefault(labels, parseCaseStatements())); - } - - - /** - *
-   * selectionStatement
-   *    : IF '(' expression ')' statement ((ELSE)=> ELSE statement)?
-   *    | SWITCH '(' expression ')' '{' switchCase* defaultCase? '}'
-   *    ;
-   * 
- */ - private DartStatement parseSwitchStatement() { - beginSwitchStatement(); - expect(Token.SWITCH); - - expect(Token.LPAREN); - DartExpression expr = parseExpression(); - expectCloseParen(); - - List members = new ArrayList(); - if (peek(0) != Token.LBRACE) { - reportUnexpectedToken(position(), Token.LBRACE, peek(0)); - return done(new DartSwitchStatement(expr, members)); - } - boolean foundOpenBrace = expect(Token.LBRACE); - - boolean done = optional(Token.RBRACE); - while (!done) { - List labels = new ArrayList(); - beginSwitchMember(); // switch member - while (peek(0) == Token.IDENTIFIER && peek(1) == Token.COLON) { - beginLabel(); - DartIdentifier identifier = parseIdentifier(); - expect(Token.COLON); - labels.add(done(new DartLabel(identifier, null))); - if (peek(0) == Token.RBRACE) { - reportError(position(), ParserErrorCode.LABEL_NOT_FOLLOWED_BY_CASE_OR_DEFAULT); - expectCloseBrace(foundOpenBrace); - return done(new DartSwitchStatement(expr, members)); - } - } - if (peek(0) == Token.CASE) { - members.add(parseCaseMember(labels)); - } else if (optional(Token.RBRACE)) { - if (!labels.isEmpty()) { - reportError(position(), ParserErrorCode.EXPECTED_CASE_OR_DEFAULT); - } - done = true; - done(null); - } else { - if (peek(0) == Token.DEFAULT) { - members.add(parseDefaultMember(labels)); - } - expectCloseBrace(foundOpenBrace); - done = true; // Ensure termination. - } - } - return done(new DartSwitchStatement(expr, members)); - } - - /** - *
-   * catchParameter
-   *    : FINAL type? identifier
-   *    | VAR identifier
-   *    | type identifier
-   *    ;
-   *  
- */ - private DartParameter parseCatchParameter() { - beginCatchParameter(); - List metadata = parseMetadata(); - DartTypeNode type = null; - Modifiers modifiers = Modifiers.NONE; - boolean isDeclared = false; - if (optional(Token.VAR)) { - isDeclared = true; - } else { - if (optional(Token.FINAL)) { - modifiers = modifiers.makeFinal(); - isDeclared = true; - } - if (peek(1) != Token.COMMA && peek(1) != Token.RPAREN) { - type = parseTypeAnnotation(); - isDeclared = true; - } - } - DartIdentifier name = parseIdentifier(); - if (!isDeclared) { - reportError(name, ParserErrorCode.EXPECTED_VAR_FINAL_OR_TYPE); - } - DartParameter parameter = done(new DartParameter(name, type, null, null, modifiers)); - setMetadata(parameter, metadata); - return parameter; - } - - /** - * Parse either the old try statement syntax: - *
-   * tryStatement
-   *     : TRY block (catchPart+ finallyPart? | finallyPart)
-   *     ;
-   *
-   * catchPart
-   *     : CATCH '(' declaredIdentifier (',' declaredIdentifier)? ')' block
-   *     ;
-   *
-   * finallyPart
-   *     : FINALLY block
-   *     ;
-   * 
- * or the new syntax: - *
-   * tryStatement
-   *     : TRY block (onPart+ finallyPart? | finallyPart)
-   *     ;
-   *
-   * onPart
-   *     : catchPart block
-   *     | ON qualified catchPart? block
-   *
-   * catchPart
-   *     : CATCH '(' identifier (',' identifier)? ')'
-   *     ;
-   *
-   * finallyPart
-   *     : FINALLY block
-   *     ;
-   * 
- */ - private DartTryStatement parseTryStatement() { - beginTryStatement(); - // Try. - expect(Token.TRY); - // TODO(zundel): It would be nice here to setup 'ON', 'CATCH' and 'FINALLY' as tokens for recovery - DartBlock tryBlock = parseBlock(); - - List catches = new ArrayList(); - while (peekPseudoKeyword(0, ON_KEYWORD) || match(Token.CATCH)) { - // TODO(zundel): It would be nice here to setup 'FINALLY' as token for recovery - if (peekPseudoKeyword(0, ON_KEYWORD)) { - beginCatchClause(); - next(); - int onTokenOffset = position(); - DartTypeNode exceptionType = parseTypeAnnotation(); - DartParameter exception = null; - DartParameter stackTrace = null; - if (optional(Token.CATCH)) { - expect(Token.LPAREN); - beginCatchParameter(); - List metadata = parseMetadata(); - DartIdentifier exceptionName = parseIdentifier(); - exception = done(new DartParameter(exceptionName, exceptionType, null, null, Modifiers.NONE)); - setMetadata(exception, metadata); - if (optional(Token.COMMA)) { - beginCatchParameter(); - DartIdentifier stackName = parseIdentifier(); - stackTrace = done(new DartParameter(stackName, null, null, null, Modifiers.NONE)); - } - expectCloseParen(); - } else { - // Create a dummy identifier that the user cannot reliably reference. - beginCatchParameter(); - List metadata = parseMetadata(); - beginIdentifier(); - DartIdentifier exceptionName = done(new DartIdentifier("e" + Long.toHexString(System.currentTimeMillis()))); - exception = done(new DartParameter(exceptionName, exceptionType, null, null, Modifiers.NONE)); - setMetadata(exception, metadata); - } - DartBlock block = parseBlock(); - catches.add(done(new DartCatchBlock(block, onTokenOffset, exception, stackTrace))); - } else { - beginCatchClause(); - next(); - expect(Token.LPAREN); - DartParameter exception; - if (match(Token.IDENTIFIER) && (peek(1) == Token.COMMA || peek(1) == Token.RPAREN)) { - beginCatchParameter(); - List metadata = parseMetadata(); - DartIdentifier exceptionName = parseIdentifier(); - exception = done(new DartParameter(exceptionName, null , null, null, Modifiers.NONE)); - setMetadata(exception, metadata); - } else { - // Old-style parameter - reportError(position(), ParserErrorCode.DEPRECATED_CATCH); - exception = parseCatchParameter(); - } - DartParameter stackTrace = null; - if (optional(Token.COMMA)) { - if (match(Token.IDENTIFIER) && peek(1) == Token.RPAREN) { - beginCatchParameter(); - List metadata = parseMetadata(); - DartIdentifier stackName = parseIdentifier(); - stackTrace = done(new DartParameter(stackName, null, null, null, Modifiers.NONE)); - setMetadata(stackTrace, metadata); - } else { - // Old-style parameter - reportError(position(), ParserErrorCode.DEPRECATED_CATCH); - stackTrace = parseCatchParameter(); - } - } - expectCloseParen(); - DartBlock block = parseBlock(); - catches.add(done(new DartCatchBlock(block, -1, exception, stackTrace))); - } - } - - // Finally. - DartBlock finallyBlock = null; - if (optional(Token.FINALLY)) { - finallyBlock = parseBlock(); - } - - if ( catches.size() == 0 && finallyBlock == null) { - reportError(new DartCompilationError(tryBlock.getSourceInfo().getSource(), new Location(position()), - ParserErrorCode.CATCH_OR_FINALLY_EXPECTED)); - } - - return done(new DartTryStatement(tryBlock, catches, finallyBlock)); - } - - /** - *
-   * unaryExpression
-   *     : postfixExpression
-   *     | prefixOperator unaryExpression
-   *     | incrementOperator assignableExpression
-   *     ;
-   *
-   *  @return an expression or null if noFail is true and the next tokens could not be parsed as an
-   *      expression, leaving the state unchanged.
-   *  
- */ - private DartExpression parseUnaryExpression() { - // There is no unary plus operator in Dart. - // However, we allow a leading plus in decimal numeric literals. - if (optional(Token.ADD)) { - if (peek(0) != Token.INTEGER_LITERAL && peek(0) != Token.DOUBLE_LITERAL) { - reportError(position(), ParserErrorCode.NO_UNARY_PLUS_OPERATOR); - } else if (position() + 1 != peekTokenLocation(0).getBegin()) { - reportError(position(), ParserErrorCode.NO_SPACE_AFTER_PLUS); - } - } - // Check for unary minus operator. - Token token = peek(0); - if (token.isUnaryOperator() || token == Token.SUB) { - if (token == Token.DEC && peek(1) == Token.SUPER) { - beginUnaryExpression(); - beginUnaryExpression(); - consume(token); - int tokenOffset = ctx.getTokenLocation().getBegin(); - DartExpression unary = parseUnaryExpression(); - DartUnaryExpression unary2 = new DartUnaryExpression(Token.SUB, tokenOffset, unary, true); - return done(new DartUnaryExpression(Token.SUB, tokenOffset, done(unary2), true)); - } else { - beginUnaryExpression(); - consume(token); - int tokenOffset = ctx.getTokenLocation().getBegin(); - DartExpression unary = parseUnaryExpression(); - if (token.isCountOperator()) { - ensureAssignable(unary); - } - return done(new DartUnaryExpression(token, tokenOffset, unary, true)); - } - } else { - return parsePostfixExpression(); - } - } - - /** - *
-   * type
-   *     : qualified typeArguments?
-   *     ;
-   * 
- */ - private DartTypeNode parseTypeAnnotation() { - beginTypeAnnotation(); - return done(new DartTypeNode(parseQualified(false), parseTypeArgumentsOpt())); - } - - /** - *
-   * type
-   *     : qualified typeArguments? ('.' identifier)?
-   *     ;
-   * 
- */ - private DartTypeNode parseTypeAnnotationPossiblyFollowedByName() { - beginTypeAnnotation(); - boolean canBeFollowedByPeriod = true; - if (peek(Token.IDENTIFIER, Token.LT) || peek(Token.IDENTIFIER, Token.PERIOD, Token.IDENTIFIER, Token.LT)) { - canBeFollowedByPeriod = false; - } - return done(new DartTypeNode(parseQualified(canBeFollowedByPeriod), parseTypeArgumentsOpt())); - } - - private boolean peek(Token... tokens) { - int index = 0; - for (Token token : tokens) { - if (peek(index++) != token) { - return false; - } - } - return true; - } - - /** - *
-   * typeArguments
-   *     : '<' typeList '>'
-   *     ;
-   *
-   * typeList
-   *     : type (',' type)*
-   *     ;
-   * 
- */ - @Terminals(tokens={Token.GT, Token.COMMA}) - private List parseTypeArguments() { - consume(Token.LT); - List arguments = new ArrayList(); - do { - arguments.add(parseTypeAnnotation()); - } while (optional(Token.COMMA)); - if (!tryParameterizedTypeEnd()) { - expect(Token.GT); - } - return arguments; - } - - /** - *
-   * typeArguments?
-   * 
- */ - private List parseTypeArgumentsOpt() { - return (peek(0) == Token.LT) - ? parseTypeArguments() - : Collections.emptyList(); - } - - /** - *
-   * qualified
-   *     : identifier ('.' identifier)?
-   *     ;
-   * 
- */ - private DartExpression parseQualified(boolean canBeFollowedByPeriod) { - beginQualifiedIdentifier(); - DartIdentifier identifier = parseIdentifier(); - if (!prefixes.contains(identifier.getName())) { - if (canBeFollowedByPeriod && !(peek(0) == Token.PERIOD && peek(1) == Token.IDENTIFIER && peek(2) == Token.PERIOD)) { - return done(identifier); - } - } - DartExpression qualified = identifier; - if (optional(Token.PERIOD)) { - // The previous identifier was a prefix. - qualified = new DartPropertyAccess(qualified, parseIdentifier()); - } - return done(qualified); - } - - private boolean tryParameterizedTypeEnd() { - switch (peek(0)) { - case GT: - consume(Token.GT); - return true; - case SAR: - setPeek(0, Token.GT); - return true; - default: - return false; - } - } - - private DartTypeNode tryTypeAnnotation() { - if (peek(0) != Token.IDENTIFIER) { - return null; - } - List typeArguments = new ArrayList(); - beginTypeAnnotation(); // to allow roll-back in case we're not at a type - - DartNode qualified = parseQualified(false); - - if (optional(Token.LT)) { - if (peek(0) != Token.IDENTIFIER) { - rollback(); - return null; - } - beginTypeArguments(); - DartNode qualified2 = parseQualified(false); - DartTypeNode argument; - switch (peek(0)) { - case LT: - // qualified < qualified2 < - argument = done(new DartTypeNode(qualified2, parseTypeArguments())); - break; - - case GT: - case SAR: - // qualified < qualified2 > - case COMMA: - // qualified < qualified2 , - argument = done(new DartTypeNode(qualified2, Collections.emptyList())); - break; - - default: - done(null); - rollback(); - return null; - } - typeArguments.add(argument); - - while (optional(Token.COMMA)) { - typeArguments.add(parseTypeAnnotation()); - } - if (!tryParameterizedTypeEnd()) { - expect(Token.GT); - } - } - - return done(new DartTypeNode(qualified, typeArguments)); - } - - private DartIdentifier parseIdentifier() { - beginIdentifier(); - if (looksLikeTopLevelKeyword()) { - reportErrorWithoutAdvancing(ParserErrorCode.EXPECTED_IDENTIFIER); - return done(new DartSyntheticErrorIdentifier()); - } - DartIdentifier identifier; - if (expect(Token.IDENTIFIER) && ctx.getTokenString() != null) { - identifier = new DartIdentifier(new String(ctx.getTokenString())); - } else { - identifier = new DartSyntheticErrorIdentifier(); - } - return done(identifier); - } - - public DartExpression parseEntryPoint() { - beginEntryPoint(); - DartExpression entry = parseIdentifier(); - while (!EOS()) { - expect(Token.PERIOD); - entry = doneWithoutConsuming(new DartPropertyAccess(entry, parseIdentifier())); - } - return done(entry); - } - - private void ensureAssignable(DartExpression expression) { - if (expression != null && !expression.isAssignable()) { - reportError(position(), ParserErrorCode.ILLEGAL_ASSIGNMENT_TO_NON_ASSIGNABLE); - } - } - - /** - * Increment the number of errors encountered while parsing this compilation unit. Returns whether - * the current error should be reported. - * - * @return whether the current error should be reported - */ - private boolean incErrorCount(ErrorCode errorCode) { - // count only errors, but not warnings (such as "abstract") - if (errorCode.getErrorSeverity() == ErrorSeverity.ERROR) { - errorCount++; - } - - if (errorCount >= MAX_DEFAULT_ERRORS) { - if (errorCount == MAX_DEFAULT_ERRORS) { - // Create a 'too many errors' error. - DartCompilationError dartError = new DartCompilationError(ctx.getSource(), - ctx.getTokenLocation(), ParserErrorCode.NO_SOUP_FOR_YOU); - ctx.error(dartError); - } - - // Consume the rest of the input stream. Throwing an exception - as suggested elsewhere in - // this file - is not ideal. - Token next = next(); - - while (next != null && next != Token.EOS) { - next = next(); - } - } - - return errorCount < MAX_DEFAULT_ERRORS; - } - - private void reportDeprecatedError(int position, ErrorCode errorCode) { - // TODO(scheglov) remove after http://code.google.com/p/dart/issues/detail?id=6508 - if ( - true - && !Elements.isCoreLibrarySource(source) - && !Elements.isLibrarySource(source, "/isolate/isolate.dart") - && !Elements.isLibrarySource(source, "/json/json.dart") - && !Elements.isLibrarySource(source, "/math/math.dart") - && !Elements.isLibrarySource(source, "/io/io.dart") - && !Elements.isLibrarySource(source, "/crypto/crypto.dart") - && !Elements.isLibrarySource(source, "/uri/uri.dart") - && !Elements.isLibrarySource(source, "/utf/utf.dart") - && !Elements.isLibrarySource(source, "/typed_data/typed_data.dart") - ) { - super.reportError(position, errorCode); - } - } - - @Override - protected void reportError(int position, ErrorCode errorCode, Object... arguments) { - // TODO(devoncarew): we're not correctly identifying dart:html as a core library - if (incErrorCount(errorCode)) { - super.reportError(position, errorCode, arguments); - } - } - - @Override - protected void reportErrorAtPosition(int startPosition, int endPosition, - ErrorCode errorCode, Object... arguments) { - if (incErrorCount(errorCode)) { - super.reportErrorAtPosition(startPosition, endPosition, errorCode, arguments); - } - } - - private void reportError(DartCompilationError dartError) { - if (incErrorCount(dartError.getErrorCode())) { - ctx.error(dartError); - errorHistory.add(dartError.hashCode()); - } - } - - private void reportError(DartNode node, ErrorCode errorCode, Object... arguments) { - if (node != null) { - reportError(new DartCompilationError(node, errorCode, arguments)); - } - } - - private boolean currentlyParsingToplevel() { - return !(isParsingInterface || isTopLevelAbstract || isParsingClass); - } - - /** - * @return true if current token is built-in identifier which can have special - * meaning. For example if it is used as import prefix, this is not special meaning, this is just - * normal identifier. - */ - private boolean isBuiltInSpecial() { - Token nextToken = peek(1); - if (nextToken == Token.LT) { - return peek(2) != Token.IDENTIFIER; - } - return nextToken != Token.PERIOD && nextToken != Token.LPAREN; - } -} diff --git a/compiler/java/com/google/dart/compiler/parser/DartParserCommentsHelper.java b/compiler/java/com/google/dart/compiler/parser/DartParserCommentsHelper.java deleted file mode 100644 index 46654c3a76a7..000000000000 --- a/compiler/java/com/google/dart/compiler/parser/DartParserCommentsHelper.java +++ /dev/null @@ -1,289 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.parser; - -import com.google.common.collect.Lists; -import com.google.dart.compiler.DartCompilerListener; -import com.google.dart.compiler.Source; -import com.google.dart.compiler.ast.ASTVisitor; -import com.google.dart.compiler.ast.DartComment; -import com.google.dart.compiler.ast.DartCommentNewName; -import com.google.dart.compiler.ast.DartCommentRefName; -import com.google.dart.compiler.ast.DartDeclaration; -import com.google.dart.compiler.ast.DartField; -import com.google.dart.compiler.ast.DartMethodDefinition; -import com.google.dart.compiler.ast.DartNode; -import com.google.dart.compiler.ast.DartUnit; -import com.google.dart.compiler.common.SourceInfo; -import com.google.dart.compiler.metrics.CompilerMetrics; -import com.google.dart.compiler.util.apache.StringUtils; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -/** - * A parser for Dart that records comment positions. - */ -public class DartParserCommentsHelper { - - static class CommentParserContext extends DartScannerParserContext { - - private List commentLocs; - - CommentParserContext(Source source, String code, DartCompilerListener listener, - CompilerMetrics metrics) { - super(source, code, listener, metrics); - } - - List getCommentLocs() { - return commentLocs; - } - - @Override - protected DartScanner createScanner(String sourceCode, Source source, - DartCompilerListener listener) { - commentLocs = Lists.newArrayList(); - return new CommentScanner(sourceCode, 0, source, listener); - } - - private class CommentScanner extends DartScanner { - - CommentScanner(String sourceCode, int start, Source sourceReference, - DartCompilerListener listener) { - super(sourceCode, start, sourceReference, listener); - } - - @Override - protected void recordCommentLocation(int start, int stop) { - int size = commentLocs.size(); - if (size > 0) { - // the parser may re-scan lookahead tokens - // fortunately, comments are always scanned as comments - int[] loc = commentLocs.get(size - 1); - if (start <= loc[0] && stop <= loc[1]) { - return; - } - } - commentLocs.add(new int[] {start, stop}); - } - } - } - - static void addComments(DartUnit unit, Source source, String sourceCode, List commentLocs) { - for (int[] loc : commentLocs) { - int start = loc[0]; - int length = loc[1] - start; - DartComment.Style style = getCommentStyle(sourceCode, start); - unit.getComments().add(new DartComment(source, start, length, style)); - } - List comments = unit.getComments(); - if (comments != null) { - assignDartComments(unit, sourceCode, comments); - } - } - - private static void assignDartComments(DartUnit unit, String sourceCode, - List comments) { - // Collect the AST nodes in a list. - final List astNodes = new ArrayList(); - unit.accept(new ASTVisitor() { - @Override - public DartNode visitDeclaration(DartDeclaration node) { - astNodes.add(node); - // Avoid NPE in visitors because of missing part. - try { - super.visitDeclaration(node); - } catch (NullPointerException e) { - } - // No result. - return null; - } - }); - - // Collect all the nodes in one list. - List nodes = new ArrayList(); - - nodes.addAll(comments); - nodes.addAll(astNodes); - - // Sort the nodes by their position in the source file. - Collections.sort(nodes, new Comparator() { - @Override - public int compare(DartNode node1, DartNode node2) { - return node1.getSourceInfo().getOffset() - node2.getSourceInfo().getOffset(); - } - }); - - // Assign dart docs to their associated DartDeclarations. - for (int i = 0; i < nodes.size(); i++) { - DartNode node = nodes.get(i); - if (node instanceof DartComment) { - DartComment comment = (DartComment) node; - // prepare next declaration - DartDeclaration decl = null; - { - int delta = 1; - while (i + delta < nodes.size()) { - DartNode next = nodes.get(i + delta); - // skip all comments - if (next instanceof DartComment) { - delta++; - continue; - } - // declaration found - if (next instanceof DartDeclaration) { - decl = (DartDeclaration) next; - if (!commentContainedBySibling(comment, decl)) { - if (i + 2 < nodes.size()) { - decl = adjustDartdocTarget(next, nodes.get(i + 2)); - } - } - break; - } - // something other than declaration - break; - } - } - // apply comment to declaration - if (decl != null) { - String commentStr = sourceCode.substring(comment.getSourceInfo().getOffset(), - comment.getSourceInfo().getEnd()); - tokenizeComment(comment, commentStr); - // DartDoc - if (comment.isDartDoc()) { - decl.setDartDoc(comment); - } - } - } - } - } - - private static void tokenizeComment(DartComment comment, String src) { - int lastIndex = 0; - while (true) { - int openIndex = src.indexOf('[', lastIndex); - if (openIndex == -1) { - break; - } - int closeIndex = src.indexOf(']', openIndex); - if (closeIndex == -1) { - break; - } - lastIndex = closeIndex; - String tokenSrc = src.substring(openIndex + 1, closeIndex); - if (tokenSrc.startsWith(":") && tokenSrc.endsWith(":")) { - // TODO(scheglov) [:code:] and 'code' - } else if (tokenSrc.startsWith("new ")) { - SourceInfo sourceInfo = comment.getSourceInfo(); - int offset = sourceInfo.getOffset() + openIndex; - int classOffset = offset + "[".length(); - // remove leading "new " - String name = StringUtils.remove(tokenSrc, "new "); - classOffset += "new ".length(); - // remove spaces - { - String stripName = StringUtils.stripStart(name, null); - classOffset += name.length() - stripName.length(); - name = stripName; - } - name = name.trim(); - // - String className = StringUtils.substringBefore(name, "."); - String constructorName = StringUtils.substringAfter(name, "."); - int constructorOffset = classOffset + className.length() + ".".length(); - DartCommentNewName newNode = new DartCommentNewName(className, classOffset, - constructorName, constructorOffset); - { - Source source = sourceInfo.getSource(); - int length = tokenSrc.length() + "[]".length(); - newNode.setSourceInfo(new SourceInfo(source, offset, length)); - } - // add node - comment.addNewName(newNode); - } else { - String name = tokenSrc.trim(); - DartCommentRefName refNode = new DartCommentRefName(name); - { - SourceInfo sourceInfo = comment.getSourceInfo(); - Source source = sourceInfo.getSource(); - int offset = sourceInfo.getOffset() + openIndex; - int length = name.length() + "[]".length(); - refNode.setSourceInfo(new SourceInfo(source, offset, length)); - } - comment.addRefName(refNode); - } - } - } - - private static DartDeclaration adjustDartdocTarget(DartNode currentNode, DartNode nextNode) { - if (currentNode instanceof DartField && nextNode instanceof DartMethodDefinition) { - if (currentNode.getSourceInfo().equals(nextNode.getSourceInfo())) { - return (DartDeclaration) nextNode; - } - } - - return (DartDeclaration) currentNode; - } - - /** - * DartC creates both a {@link DartField} and a {@link DartMethodDefinition} for getters and - * setters. They have the same source location; we want to assign the DartDoc to the method - * definition and not the field. - */ - private static boolean commentContainedBySibling(DartComment comment, DartDeclaration node) { - if (node instanceof DartField) { - for (DartNode child : getChildren(node.getParent())) { - if (child != node && !(child instanceof DartComment)) { - if (isContainedBy(comment, child)) { - return true; - } - } - } - } - return false; - } - - private static List getChildren(DartNode parent) { - final List children = new ArrayList(); - - parent.visitChildren(new ASTVisitor() { - @Override - public DartNode visitNode(DartNode node) { - children.add(node); - return null; - } - }); - - return children; - } - - private static boolean isContainedBy(DartNode node, DartNode containedByNode) { - SourceInfo nodeSource = node.getSourceInfo(); - SourceInfo containedBySource = containedByNode.getSourceInfo(); - int nodeEnd = nodeSource.getOffset() + nodeSource.getLength(); - int containedByEnd = containedBySource.getOffset() + containedBySource.getLength(); - return nodeSource.getOffset() >= containedBySource.getOffset() && nodeEnd <= containedByEnd; - } - - /** - * Return the style of the comment in the given string. - * - * @param sourceString the source containing the comment - * @param commentStart the location of the comment in the source - * @return the style of the comment in the given string - */ - private static DartComment.Style getCommentStyle(String sourceString, int commentStart) { - boolean hasMore1 = commentStart + 1 < sourceString.length(); - boolean hasMore2 = commentStart + 2 < sourceString.length(); - if (hasMore1 && sourceString.charAt(commentStart + 1) == '/') { - return DartComment.Style.END_OF_LINE; - } else if (hasMore2 && sourceString.charAt(commentStart + 2) == '*') { - return DartComment.Style.DART_DOC; - } - return DartComment.Style.BLOCK; - } -} diff --git a/compiler/java/com/google/dart/compiler/parser/DartPrefixParser.java b/compiler/java/com/google/dart/compiler/parser/DartPrefixParser.java deleted file mode 100644 index 50686f97d55d..000000000000 --- a/compiler/java/com/google/dart/compiler/parser/DartPrefixParser.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2012 Dart project authors. - * - * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.eclipse.org/legal/epl-v10.html - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package com.google.dart.compiler.parser; - -import com.google.dart.compiler.DartCompilerListener; -import com.google.dart.compiler.Source; -import com.google.dart.compiler.ast.DartIdentifier; -import com.google.dart.compiler.ast.DartImportDirective; -import com.google.dart.compiler.ast.DartStringLiteral; -import com.google.dart.compiler.metrics.CompilerMetrics; - -import java.util.Set; - -/** - * An extension of {@link DartParser} that updates the prefixes collection - */ -public class DartPrefixParser extends DartParser { - - private final Set prefixes; - - public DartPrefixParser( - Source source, - String sourceCode, - boolean isDietParse, - Set prefixes, - DartCompilerListener listener, - CompilerMetrics compilerMetrics) { - super(source, sourceCode, isDietParse, prefixes, listener, compilerMetrics); - this.prefixes = prefixes; - } - - @Override - protected DartImportDirective parseImportDirective() { - DartImportDirective directive = super.parseImportDirective(); - DartIdentifier prefix = directive.getPrefix(); - if (prefix != null) { - prefixes.add(prefix.getName()); - } - return directive; - } - - @SuppressWarnings("deprecation") - @Override - protected DartImportDirective parseObsoleteImportDirective() { - DartImportDirective directive = super.parseObsoleteImportDirective(); - DartStringLiteral oldPrefix = directive.getOldPrefix(); - if (oldPrefix != null) { - prefixes.add(oldPrefix.getValue()); - } - return directive; - } -} - \ No newline at end of file diff --git a/compiler/java/com/google/dart/compiler/parser/DartScanner.java b/compiler/java/com/google/dart/compiler/parser/DartScanner.java deleted file mode 100644 index a019d93eb191..000000000000 --- a/compiler/java/com/google/dart/compiler/parser/DartScanner.java +++ /dev/null @@ -1,1361 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.parser; - -import com.google.dart.compiler.DartCompilationError; -import com.google.dart.compiler.DartCompilerListener; -import com.google.dart.compiler.Source; -import com.google.dart.compiler.common.SourceInfo; -import com.google.dart.compiler.metrics.DartEventType; -import com.google.dart.compiler.metrics.Tracer; -import com.google.dart.compiler.metrics.Tracer.TraceEvent; -import com.google.dart.compiler.parser.DartScanner.InternalState.Mode; - -import java.util.ArrayList; -import java.util.List; -import java.util.Stack; - -/** - * The Dart scanner. Should normally be used only by {@link DartParser}. - */ -public class DartScanner { - - /** - * Represents a span of characters in a source file. - */ - public static class Location { - public static final Location NONE = null; - private int begin; - private int end; - - public Location(int begin, int end) { - this.begin = begin; - this.end = end; - } - - public Location(int begin) { - this.begin = this.end = begin; - } - - public int getBegin() { - return begin; - } - - public int getEnd() { - return end; - } - - @Override - public String toString() { - return begin + "::" + end; - } - } - - public static class State { - State(int baseOffset) { - this.baseOffset = baseOffset; - } - - static class RollbackToken { - public final int absoluteOffset; - final Token replacedToken; - - public RollbackToken(int tokenOffset, Token token) { - absoluteOffset = tokenOffset; - replacedToken = token; - } - } - - /* Stack of tokens present before setPeek() */ - Stack rollbackTokens = null; - final int baseOffset; - - @Override - public String toString() { - return "ofs=" + baseOffset; - } - } - - /** - * Stores the entire state for the scanner. - */ - protected static class InternalState { - enum Mode { - DEFAULT, - - IN_STRING, - - /** - * Inside a string, scanning a string-interpolation expression. - * Ex: "${foo}". - */ - IN_STRING_EMBEDDED_EXPRESSION, - - /** - * Inside a string, scanning a string-interpolation identifier. - *
-       * Ex: "$foo bc".
-       *        ^
-       * 
- */ - IN_STRING_EMBEDDED_EXPRESSION_IDENTIFIER, - - /** - * Inside a string, just after having scanned a string-interpolation identifier. - *
-       * Ex: "$foo bc".
-       *          ^
-       * 
- */ - IN_STRING_EMBEDDED_EXPRESSION_END - } - - /** - * Maintains the state of scanning strings, including interpolated - * expressions/identifiers, nested braces for terminating an interpolated - * expression, the quote character used to start/end the string, and whether - * it is a multiline string. - */ - public static class StringState { - private int bracesCount; - private Mode mode; - private final boolean multiLine; - private final int quote; - - /** - * Push a new mode on state stack. If the new mode is - * {@link Mode#IN_STRING_EMBEDDED_EXPRESSION}, mark that we have seen an - * opening brace. - * - * @param mode - * @param quote - * @param multiLine - */ - public StringState(Mode mode, int quote, boolean multiLine) { - this.bracesCount = mode == Mode.IN_STRING_EMBEDDED_EXPRESSION ? 1 : 0; - this.mode = mode; - this.quote = quote; - this.multiLine = multiLine; - } - - /** - * Mark that we have seen an opening brace. - */ - public void openBrace() { - if (mode == Mode.IN_STRING_EMBEDDED_EXPRESSION) { - bracesCount++; - } - } - - /** - * Mark that we have seen a closing brace. - * - * @return true if the current mode is now complete and should be popped - * off the stack - */ - public boolean closeBrace() { - if (mode == Mode.IN_STRING_EMBEDDED_EXPRESSION) { - return --bracesCount == 0; - } - return false; - } - - /** - * @return the string scanning mode. - */ - public Mode getMode() { - return mode; - } - - /** - * @return the codepoint of the quote character used to bound the current - * string. - */ - public int getQuote() { - return quote; - } - - /** - * @return true if the current string is a multi-line string. - */ - public boolean isMultiLine() { - return multiLine; - } - - /** - * @param mode the string scanning mode. - */ - public void setMode(Mode mode) { - this.mode = mode; - } - - @Override - public String toString() { - StringBuilder buf = new StringBuilder(); - buf.append(mode).append("/quote=").appendCodePoint(quote); - if (multiLine) { - buf.append("/multiline"); - } - return buf.toString(); - } - } - - private int lookahead[] = new int[NUM_LOOKAHEAD]; - private int lookaheadPos[] = new int[NUM_LOOKAHEAD]; - private int nextLookaheadPos; - private ArrayList tokens; - private TokenData lastToken; - - // Current offset in the token list - int currentOffset; - - // The following fields store data used for parsing string interpolation. - // The scanner splits the interpolated string in segments, alternating - // strings and expressions so that the parser can construct the embedded - // expressions as it goes. The following information is used to ensure that - // the string is closed with matching quotes, and to deal with parsing - // ambiguity of "}" (which closes both embedded expressions and braces - // within embedded expressions). - - /** The string scanning state stack. */ - private List stringStateStack = new ArrayList(); - - public InternalState() { - currentOffset = 0; - } - - @Override - public String toString() { - StringBuilder ret = new StringBuilder(); - - ret.append("currentOffset("); - ret.append(currentOffset); - ret.append(")"); - if ( currentOffset > -1 ) { - TokenData tok = tokens.get(currentOffset); - ret.append(" = ["); - ret.append(tok.token); - if (tok.value != null) { - ret.append(" (" + tok.value + ")"); - } - ret.append("], "); - } - - ret.append("["); - for (int i = 0; i < tokens.size(); i++) { - TokenData tok = tokens.get(i); - ret.append(tok.token); - if (tok.value != null) { - ret.append(" (" + tok.value + ")"); - } - if (i < tokens.size() - 1) { - ret.append(", "); - } - } - ret.append("]"); - if (getMode() != InternalState.Mode.DEFAULT) { - ret.append("(within string starting with "); - ret.appendCodePoint(getQuote()); - if (isMultiLine()) { - ret.appendCodePoint(getQuote()); - ret.appendCodePoint(getQuote()); - } - ret.append(')'); - } - return ret.toString(); - } - - /** - * @return the current scanning mode - */ - protected Mode getMode() { - return stringStateStack.isEmpty() ? Mode.DEFAULT : getCurrentState().getMode(); - } - - /** - * Mark that we have seen an open brace. - */ - protected void openBrace() { - if (!stringStateStack.isEmpty()) { - getCurrentState().openBrace(); - } - } - - /** - * Mark that we have seen a close brace. - * - * @return true if the current mode is now complete and should be popped - */ - protected boolean closeBrace() { - if (!stringStateStack.isEmpty()) { - return getCurrentState().closeBrace(); - } - return false; - } - - /** - * Pop the current mode. - */ - protected void popMode() { - if (!stringStateStack.isEmpty()) { - stringStateStack.remove(stringStateStack.size() - 1); - } - } - - /** - * @param mode the mode to push - */ - protected void pushMode(Mode mode, int quote, boolean multiLine) { - stringStateStack.add(new StringState(mode, quote, multiLine)); - } - - /** - * @param mode the mode to push - */ - protected void replaceMode(Mode mode) { - getCurrentState().setMode(mode); - } - - /** - * Remove all modes, returning to the default state. - */ - public void resetModes() { - stringStateStack.clear(); - } - - /** - * @return the quote - */ - private int getQuote() { - return getCurrentState().getQuote(); - } - - /** - * @return the current string scanning state - */ - private StringState getCurrentState() { - assert !stringStateStack.isEmpty() : "called with empty state stack"; - return stringStateStack.get(stringStateStack.size() - 1); - } - - /** - * @return the multiLine - */ - private boolean isMultiLine() { - return getCurrentState().isMultiLine(); - } - } - - private static class TokenData { - Token token; - Location location; - String value; - - @Override - public String toString() { - String str = token.toString(); - return (value != null) ? str + "(" + value + ")" : str; - } - } - - private static final int NUM_LOOKAHEAD = 2; - - private static boolean isDecimalDigit(int c) { - return c >= '0' && c <= '9'; - } - - private static boolean isHexDigit(int c) { - return isDecimalDigit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); - } - - private static boolean isIdentifierPart(int c) { - return isIdentifierStart(c) || isDecimalDigit(c); - } - - private static boolean isIdentifierStart(int c) { - return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c == '_') || (c == '$'); - } - - private static boolean isLineTerminator(int c) { - return c == '\r' || c == '\n'; - } - - private static boolean isWhiteSpace(int c) { - return c == ' ' || c == '\t'; - } - - private int commentCharCount; - private int lastCommentStart; - private int lastCommentStop; - private String source; - private InternalState internalState; - private Source sourceReference; - private DartCompilerListener listener; - - public DartScanner(String source) { - this(source, 0, null, null); - } - - public DartScanner(String source, int start) { - this(source, 0, null, null); - } - - public DartScanner(String source, int start, Source sourceReference, DartCompilerListener listener) { - final TraceEvent logEvent = Tracer.canTrace() ? Tracer.start(DartEventType.SCANNER) : null; - try { - this.source = source; - this.sourceReference = sourceReference; - this.listener = listener; - internalState = new InternalState(); - internalState.tokens = new ArrayList(source.length()/2); - - // Initialize lookahead positions. - // TODO Determine if line & column should be relative to 0 or 'start' - internalState.nextLookaheadPos = start; - for (int i = 0; i < internalState.lookaheadPos.length; ++i) { - internalState.lookaheadPos[i] = start; - } - - // Fill all the characters in the look-ahead and all the peek - // elements in the tokens buffer. - for (int i = 0; i < NUM_LOOKAHEAD; i++) { - advance(); - } - - // Scan all the tokens up front - scanFile(); - } finally { - Tracer.end(logEvent); - } - } - - /** - * Returns the number of characters of source code that were scanned. - */ - public int getCharCount() { - return internalState.nextLookaheadPos; - } - - /** - * Returns the number of characters of source code that were scanned excluding the number of - * characters consumed by comments. - */ - public int getNonCommentCharCount() { - return getCharCount() - commentCharCount; - } - - /** - * Get the token value for one of the look-ahead tokens. - */ - public String getPeekTokenValue(int n) { - assert (0 <= n && (internalState.currentOffset + n + 1) < internalState.tokens.size()); - return internalState.tokens.get(internalState.currentOffset + n + 1).value; - } - - /** - * Gets a copy of the current scanner state. This state can be passed to {@link - * #restoreState(State)}. - */ - public State getState() { -// System.out.println("get state: " + internalState.currentOffset + " hash: 0x" + Integer.toHexString(this.hashCode())); - return new State(internalState.currentOffset); - } - - /** - * Gets the current offset of the scanner. - */ - public int getOffset() { - return internalState.currentOffset; - } - - /** - * Gets the current token. - */ - public Token getToken() { - return internalState.tokens.get(internalState.currentOffset).token; - } - - /** - * Gets the location of the current token. - */ - public Location getTokenLocation() { - return internalState.tokens.get(internalState.currentOffset).location; - } - - public Location peekTokenLocation(int n) { - if ((internalState.currentOffset + n + 1) < internalState.tokens.size()) { - return internalState.tokens.get(internalState.currentOffset + n + 1).location; - } else { - // It is not valid to read beyond the end of the token stream, so we - // return the Location of the EOS token. - return internalState.tokens.get(internalState.tokens.size() - 1).location; - } - - } - - /** - * Get the token value or location for the current token previously returned - * by a call to next(). - */ - public String getTokenValue() { - return internalState.tokens.get(internalState.currentOffset).value; - } - - public String peekTokenValue(int n) { - if ((internalState.currentOffset + n + 1) < internalState.tokens.size()) { - return internalState.tokens.get(internalState.currentOffset + n + 1).value; - } else { - // It is not valid to read beyond the end of the token stream, so we - // return the null, the default value of an EOS token. - return null; - } - } - - /** - * Returns the next token. - */ - public Token next() { - // Do not advance the current offset beyond the end of the stoken stream - if (internalState.currentOffset + 1 < internalState.tokens.size()) { - internalState.currentOffset++; - } - return getToken(); - } - - /** - * Token look-ahead - past the token returned by next(). - */ - public Token peek(int n) { - if ((internalState.currentOffset + n + 1) < internalState.tokens.size()) { - return internalState.tokens.get(internalState.currentOffset + n + 1).token; - } else { - // It is not valid to read beyond the end of the token stream, so we - // return the EOS token - return Token.EOS; - } - } - - /** - * Sets the scanner's state, using a state object returned from {@link #getState()}. - */ - public void restoreState(State oldState) { -// System.out.println("restore state " + oldState.baseOffset + " hash: 0x" + Integer.toHexString(this.hashCode())); - // reset offset - internalState.currentOffset = oldState.baseOffset; - } - - /** - * Sets the token at the specified slot in the lookahead buffer. - */ - public void setPeek(int n, Token token) { - assert (0 <= n && (internalState.currentOffset + n + 1) < internalState.tokens.size()); - internalState.tokens.get(internalState.currentOffset + n + 1).token = token; - } - - /** - * Sets the token at the specified slot in the lookahead buffer. - */ - public void setAbsolutePeek(int n, Token token) { - assert (0 <= n && n < internalState.tokens.size()); - internalState.tokens.get(n).token = token; - } - - @Override - public String toString() { - if (internalState == null) { - return super.toString(); - } - return internalState.toString(); - } - - /** - * A hook into low-level scanning machinery. Use with care and only as directed.

- * Record the location of a comment. Given a source string source, - * the actual comment string is source.substring(start - 1, stop) - * because the comment cannot be recognized until its second character is - * scanned.

- * Note: A single comment may be scanned multiple times. If the scanner has - * to backtrack it will re-scan comments until it no longer has to backtrack. - * Clients are responsible for filtering duplicate comment locations.

- * Warning: This method may be called during initialization of the scanner in - * the DartScanner constructor. Fields defined in the subclass - * that implements this method may not have been initialized before the first - * invocation. - * @param start the character position of the second character in the comment - * @param stop the character position of the final character in the comment - */ - protected void recordCommentLocation(int start, int stop) { - } - - private void advance() { - for (int i = 0; i < NUM_LOOKAHEAD - 1; ++i) { - internalState.lookahead[i] = internalState.lookahead[i + 1]; - internalState.lookaheadPos[i] = internalState.lookaheadPos[i + 1]; - } - if (internalState.nextLookaheadPos < source.length()) { - int ch = source.codePointAt(internalState.nextLookaheadPos); - internalState.lookahead[NUM_LOOKAHEAD - 1] = ch; - internalState.lookaheadPos[NUM_LOOKAHEAD - 1] = internalState.nextLookaheadPos; - internalState.nextLookaheadPos = source.offsetByCodePoints(internalState.nextLookaheadPos, 1); - } else { - // Let the last look-ahead position be past the source. This makes - // the position information for the last token correct. - internalState.lookahead[NUM_LOOKAHEAD - 1] = -1; - internalState.lookaheadPos[NUM_LOOKAHEAD - 1] = source.length(); - - // Leave the nextLookahead position pointing to the line after the last line - internalState.nextLookaheadPos = source.length(); - } - } - - /** - * Called when comments are identified to aggregate the total number of comment lines and comment - * characters then delegate to {@link #recordCommentLocation(int, int)}. This provides - * a light weight way to track how much of the code is made up of comments without having to keep - * all comments. - * - * @param start the character position of the second character in the comment - * @param stop the character position of the final character in the comment - */ - private void commentLocation(int start, int stop) { - if (start <= lastCommentStart && stop <= lastCommentStop) { - return; - } - - lastCommentStart = start; - lastCommentStop = stop; - commentCharCount += stop - start + 1; - - recordCommentLocation(start, stop); - } - - private boolean is(int c) { - return internalState.lookahead[0] == c; - } - - private boolean isEos() { - return internalState.lookahead[0] < 0; - } - - private int lookahead(int n) { - assert (0 <= n && n < NUM_LOOKAHEAD); - return internalState.lookahead[n]; - } - - // Get the current source code position. - private int position() { - return internalState.lookaheadPos[0]; - } - - private void scanFile() { - // First node inserted as a dummy. - internalState.lastToken = new TokenData(); - internalState.tokens.add(internalState.lastToken); - - while (true) { - internalState.lastToken = new TokenData(); - Token token; - int begin, end; - do { - skipWhiteSpace(); - begin = position(); - token = scanToken(); - } while (token == Token.COMMENT); - end = position(); - - internalState.lastToken.token = token; - internalState.lastToken.location = new Location(begin, end); - internalState.tokens.add(internalState.lastToken); - if (token == Token.EOS) { -// System.out.print("tokens: "); -// for(TokenData t : internalState.tokens) { -// if (t != null) { -// if (t.token != null) { -// System.out.print(t + ", "); -// } else { -// System.out.print("Null, "); -// } -// } -// } -// System.out.println(); - return; - } - } - } - - private Token scanIdentifier(boolean allowDollars) { - assert (isIdentifierStart(lookahead(0))); - int begin = position(); - while (true) { - int nextChar = lookahead(0); - if (!isIdentifierPart(nextChar) || (!allowDollars && nextChar == '$')) { - break; - } - advance(); - } - int size = position() - begin; - - // Use a substring of the source string instead of copying all the - // characters to the token value buffer. - String result = source.substring(begin, begin + size); - internalState.lastToken.value = result; - return Token.lookup(result); - } - - private Token scanNumber() { - boolean isDouble = false; - assert (isDecimalDigit(lookahead(0)) || is('.')); - int begin = position(); - while (isDecimalDigit(lookahead(0))) - advance(); - if (is('.') && isDecimalDigit(lookahead(1))) { - isDouble = true; - advance(); // Consume . - while (isDecimalDigit(lookahead(0))) - advance(); - } - if (isE()) { - isDouble = true; - advance(); - if (is('+') || is('-')) { - advance(); - } - if (!isDecimalDigit(lookahead(0))) { - return Token.ILLEGAL; - } - while (isDecimalDigit(lookahead(0))) - advance(); - } else if (isIdentifierStart(lookahead(0))) { - // Number literals must not be followed directly by an identifier. - return Token.ILLEGAL; - } - int size = position() - begin; - internalState.lastToken.value = source.substring(begin, begin + size); - return isDouble ? Token.DOUBLE_LITERAL : Token.INTEGER_LITERAL; - } - - private boolean isE() { - return is('e') || is('E'); - } - - private Token scanHexNumber() { - assert (isDecimalDigit(lookahead(0)) && (lookahead(1) == 'x' || lookahead(1) == 'X')); - // Skip 0x/0X. - advance(); - advance(); - - int begin = position(); - if (!isHexDigit(lookahead(0))) { - return Token.ILLEGAL; - } - advance(); - while (isHexDigit(lookahead(0))) { - advance(); - } - if (isIdentifierStart(lookahead(0))) { - return Token.ILLEGAL; - } - internalState.lastToken.value = source.substring(begin, position()); - return Token.HEX_LITERAL; - } - - private Token scanString(boolean isRaw) { - int quote = lookahead(0); - assert (is('\'') || is('"')); - boolean multiLine = false; - advance(); - - // detect whether this is a multi-line string: - if (lookahead(0) == quote && lookahead(1) == quote) { - multiLine = true; - advance(); - advance(); - // according to the dart guide, when multi-line strings start immediately - // with a \n, the \n is not part of the string: - if (is('\n')) { - advance(); - } - } - internalState.pushMode(InternalState.Mode.IN_STRING, quote, multiLine); - if (isRaw) { - return scanRawString(); - } else { - return scanWithinString(true); - } - } - - private Token scanRawString() { - assert (internalState.getMode() == InternalState.Mode.IN_STRING); - int quote = internalState.getQuote(); - boolean multiLine = internalState.isMultiLine(); - // TODO(floitsch): Do we really need a StringBuffer to accumulate the characters? - StringBuilder tokenValueBuffer = new StringBuilder(); - while (true) { - if (isEos()) { - // Unterminated string (either multi-line or not). - internalState.popMode(); - return Token.ILLEGAL; - } - int c = lookahead(0); - advance(); - if (c == quote) { - if (!multiLine) { - // Done parsing the string literal. - break; - } else if (lookahead(0) == quote && lookahead(1) == quote) { - // Done parsing the multi-line string literal. - advance(); - advance(); - break; - } - } else if (c == '\n' && !multiLine) { - advance(); - internalState.popMode(); - // unterminated (non multi-line) string - return Token.ILLEGAL; - } - tokenValueBuffer.appendCodePoint(c); - } - internalState.lastToken.value = tokenValueBuffer.toString(); - internalState.popMode(); - return Token.STRING; - } - - /** - * Scan within a string watching for embedded expressions (string - * interpolation). This function returns 4 kinds of tokens: - *

    - *
  • {@link Token#STRING} when {@code start} is true and no embedded - * expressions are found (default to string literals when no interpolation - * was used). - *
  • {@link Token#STRING_SEGMENT} when the string is interrupted with an - * embedded expression. - *
  • {@link Token#STRING_EMBED_EXP_START} when an embedded expression is - * found right away (the lookahead is "${"). - *
  • {@link Token#STRING_LAST_SEGMENT} when {@code start} is false and no - * more embedded expressions are found. - *
- */ - private Token scanWithinString(boolean start) { - assert (internalState.getMode() == InternalState.Mode.IN_STRING); - int quote = internalState.getQuote(); - boolean multiLine = internalState.isMultiLine(); - StringBuffer tokenValueBuffer = new StringBuffer(); - while (true) { - if (isEos()) { - // Unterminated string (either multi-line or not). - internalState.resetModes(); - return Token.EOS; - } - int c = lookahead(0); - if (c == quote) { - advance(); - if (!multiLine) { - // Done parsing string constant. - break; - } else if (lookahead(0) == quote && lookahead(1) == quote) { - // Done parsing multi-line string constant. - advance(); - advance(); - break; - } - } else if (c == '\n' && !multiLine) { - advance(); - internalState.popMode(); - // unterminated (non multi-line) string - return Token.ILLEGAL; - } else if (c == '\\') { - advance(); - if (isEos()) { - // Unterminated string (either multi-line or not). - internalState.resetModes(); - return Token.EOS; - } - c = lookahead(0); - advance(); - switch (c) { - case '\n': - reportError(position() - 1, ParserErrorCode.ESCAPED_NEWLINE); - c = '\n'; - break; - case 'b': - c = 0x08; - break; - case 'f': - c = 0x0C; - break; - case 'n': - c = '\n'; - break; - case 'r': - c = '\r'; - break; - case 't': - c = '\t'; - break; - case 'v': - c = 0x0B; - break; - case 'x': - case 'u': - // Parse Unicode escape sequences, which are of the form (backslash) xXX, (backslash) - // uXXXX or (backslash) u{X*} where X is a hexadecimal digit - the delimited form must - // be between 1 and 6 digits. - int len = (c == 'u') ? 4 : 2; - if (isEos()) { - // Unterminated string (either multi-line or not). - internalState.resetModes(); - return Token.EOS; - } - c = lookahead(0); - int unicodeCodePoint = 0; - // count of characters remaining or negative if delimited - if (c == '{') { - len = -1; - advance(); - if (isEos()) { - // Unterminated string (either multi-line or not). - internalState.resetModes(); - return Token.EOS; - } - c = lookahead(0); - } - while (len != 0) { - advance(); - int digit = Character.getNumericValue(c); - if (digit < 0 || digit > 15) { - // TODO(jat): how to handle an error? We would prefer to give a better error - // message about an invalid Unicode escape sequence - return Token.ILLEGAL; - } - unicodeCodePoint = unicodeCodePoint * 16 + digit; - c = lookahead(0); - if (len-- < 0 && c == '}') { - advance(); - break; - } - if (isEos()) { - // Unterminated string (either multi-line or not). - internalState.resetModes(); - return Token.EOS; - } - if (len < -6) { - // TODO(jat): better way to indicate error - // too many characters for a delimited character - return Token.ILLEGAL; - } - } - c = unicodeCodePoint; - // Unicode escapes must specify a valid Unicode scalar value, and may not specify - // UTF16 surrogates. - if (!Character.isValidCodePoint(c) || (c < 0x10000 - && (Character.isHighSurrogate((char) c) || Character.isLowSurrogate((char) c)))) { - // TODO(jat): better way to indicate error - return Token.ILLEGAL; - } - // TODO(jat): any other checks? We could use Character.isDefined, but then we risk - // version skew with the JRE's Unicode data. For now, assume anything in the Unicode - // range besides surrogates are fine. - break; - - default: - // any other character following a backslash is just itself - // see Dart guide 3.3 - break; - } - } else if (c == '$') { - // TODO(sigmund): add support for named embedded expressions and - // function embedded expressions for string templates. - if (tokenValueBuffer.length() == 0) { - advance(); - int nextChar = lookahead(0); - if (nextChar == '{') { - advance(); - internalState.pushMode(InternalState.Mode.IN_STRING_EMBEDDED_EXPRESSION, quote, - multiLine); - } else { - internalState.pushMode(InternalState.Mode.IN_STRING_EMBEDDED_EXPRESSION_IDENTIFIER, - quote, multiLine); - } - return Token.STRING_EMBED_EXP_START; - } else { - // Encountered the beginning of an embedded expression (string - // interpolation), return the current segment, and keep the "$" for - // the next token. - internalState.lastToken.value = tokenValueBuffer.toString(); - return Token.STRING_SEGMENT; - } - } else { - advance(); - } - tokenValueBuffer.appendCodePoint(c); - } - - internalState.lastToken.value = tokenValueBuffer.toString(); - internalState.popMode(); - if (start) { - return Token.STRING; - } else { - return Token.STRING_LAST_SEGMENT; - } - } - - private Token scanToken() { - switch (internalState.getMode()) { - case IN_STRING: - return scanWithinString(false); - case IN_STRING_EMBEDDED_EXPRESSION_IDENTIFIER: - // We are inside a string looking for an identifier. Ex: "$foo". - internalState.replaceMode(InternalState.Mode.IN_STRING_EMBEDDED_EXPRESSION_END); - int c = lookahead(0); - if (isIdentifierStart(c) && c != '$') { - boolean allowDollars = false; - return scanIdentifier(allowDollars); - } else { - internalState.popMode(); - if (!isEos()) { - internalState.lastToken.value = String.valueOf(c); - } - return Token.ILLEGAL; - } - case IN_STRING_EMBEDDED_EXPRESSION_END: - // We scanned the identifier of a string-interpolation. New we return the - // end-of-embedded-expression token. - internalState.popMode(); - return Token.STRING_EMBED_EXP_END; - default: - // fall through - } - - switch (lookahead(0)) { - case '"': - case '\'': { - boolean isRaw = false; - return scanString(isRaw); - } - - case '<': - // < <= << <<= - advance(); - if (is('=')) - return select(Token.LTE); - if (is('<')) - return select('=', Token.ASSIGN_SHL, Token.SHL); - return Token.LT; - - case '>': - // > >= >> >>= - advance(); - if (is('=')) - return select(Token.GTE); - if (is('>')) { - // >> >>= - advance(); - if (is('=')) - return select(Token.ASSIGN_SAR); - return Token.SAR; - } - return Token.GT; - - case '=': - // = == === => - advance(); - if (is('>')) { - return select(Token.ARROW); - } - if (is('=')) - return select('=', Token.EQ_STRICT, Token.EQ); - return Token.ASSIGN; - - case '!': - // ! != !== - advance(); - if (is('=')) - return select('=', Token.NE_STRICT, Token.NE); - return Token.NOT; - - case '+': - // + ++ += - advance(); - if (is('+')) - return select(Token.INC); - if (is('=')) - return select(Token.ASSIGN_ADD); - return Token.ADD; - - case '-': - // - -- -= - advance(); - if (is('-')) - return select(Token.DEC); - if (is('=')) - return select(Token.ASSIGN_SUB); - return Token.SUB; - - case '*': - // * *= - return select('=', Token.ASSIGN_MUL, Token.MUL); - - case '%': - // % %= - return select('=', Token.ASSIGN_MOD, Token.MOD); - - case '/': - // / // /* /= - advance(); - if (is('/')) - return skipSingleLineComment(); - if (is('*')) - return skipMultiLineComment(); - if (is('=')) - return select(Token.ASSIGN_DIV); - return Token.DIV; - - case '&': - // & && &= - advance(); - if (is('&')) - return select(Token.AND); - if (is('=')) - return select(Token.ASSIGN_BIT_AND); - return Token.BIT_AND; - - case '|': - // | || |= - advance(); - if (is('|')) - return select(Token.OR); - if (is('=')) - return select(Token.ASSIGN_BIT_OR); - return Token.BIT_OR; - - case '^': - // ^ ^= - return select('=', Token.ASSIGN_BIT_XOR, Token.BIT_XOR); - - case '.': - // . - if (isDecimalDigit(lookahead(1))) { - return scanNumber(); - } else { - advance(); - if (lookahead(0) == '.') { - if (lookahead(1) == '.') { - advance(); - advance(); - return Token.ELLIPSIS; - } - advance(); - return Token.CASCADE; - } - return Token.PERIOD; - } - - case ':': - return select(Token.COLON); - - case ';': - return select(Token.SEMICOLON); - - case ',': - return select(Token.COMMA); - - case '(': - return select(Token.LPAREN); - - case ')': - return select(Token.RPAREN); - - case '[': - advance(); - if (is(']')) { - return select('=', Token.ASSIGN_INDEX, Token.INDEX); - } - return Token.LBRACK; - - case ']': - return select(Token.RBRACK); - - case '{': - internalState.openBrace(); - return select(Token.LBRACE); - - case '}': - if (internalState.closeBrace()) { - internalState.popMode(); - return select(Token.STRING_EMBED_EXP_END); - } - return select(Token.RBRACE); - - case '?': - return select(Token.CONDITIONAL); - - case '~': - // ~ ~/ ~/= - advance(); - if (is('/')) { - if (lookahead(1) == '=') { - advance(); - return select(Token.ASSIGN_TRUNC); - } else { - return select(Token.TRUNC); - } - } else { - return Token.BIT_NOT; - } - - case '@': - // Raw strings. - advance(); - if (is('\'') || is('"')) { - reportError(position() - 1, ParserErrorCode.DEPRECATED_RAW_STRING); - Token token = scanString(true); - return token; - } else { - return Token.AT; - } - - case '#': - return scanDirective(); - - case 'r': - if (lookahead(1) == '\'' || lookahead(1) == '"') { - advance(); - return scanString(true); - } - return scanIdentifier(true); - - default: - if (isIdentifierStart(lookahead(0))) { - boolean allowDollars = true; - return scanIdentifier(allowDollars); - } - if (isDecimalDigit(lookahead(0))) { - if (lookahead(0) == '0' && (lookahead(1) == 'x' || lookahead(1) == 'X')) { - return scanHexNumber(); - } else { - return scanNumber(); - } - } - if (isEos()) - return Token.EOS; - return select(Token.ILLEGAL); - } - } - - private void reportError(int offset, ParserErrorCode errorCode) { - if (listener != null) { - listener.onError(new DartCompilationError( - new SourceInfo(sourceReference, offset, position() - offset), - errorCode)); - } - } - - /** - * Scan for #library, #import, #source, and #resource directives - */ - private Token scanDirective() { - assert (is('#')); - int currPos = position(); - int start = currPos; - - // Skip over the #! if it exists and consider it a comment - if (start == 0) { - if (lookahead(1) == '!') { - while (!isEos() && !isLineTerminator(lookahead(0))) - advance(); - int stop = internalState.lookaheadPos[0]; - commentLocation(start, stop); - return Token.COMMENT; - } - } - - // Directives must start at the beginning of a line - if (start > 0 && !isLineTerminator(source.codePointBefore(start))) - return select(Token.ILLEGAL); - - // Determine which directive is being specified - advance(); - while (true) { - int ch = lookahead(0); - if (ch < 'a' || ch > 'z') { - break; - } - advance(); - } - String syntax = source.substring(start, position()); - Token token = Token.lookup(syntax); - return token == Token.IDENTIFIER ? Token.ILLEGAL : token; - } - - private Token select(int next, Token yes, Token no) { - advance(); - if (lookahead(0) != next) - return no; - advance(); - return yes; - } - - private Token select(Token token) { - advance(); - return token; - } - - private Token skipMultiLineComment() { - assert (is('*')); - int currPos = internalState.lookaheadPos[0]; - int start = currPos - 1; - int commentDepth = 1; - advance(); - while (!isEos()) { - int first = lookahead(0); - advance(); - if (first == '*' && is('/')) { - if(--commentDepth == 0) { - Token result = select(Token.COMMENT); - int stop = internalState.lookaheadPos[0]; - commentLocation(start, stop); - return result; - } - advance(); - } else if (first == '/' && is('*')) { - commentDepth++; - advance(); - } - } - int stop = internalState.lookaheadPos[0]; - commentLocation(start, stop); - // Unterminated multi-line comment. - return Token.ILLEGAL; - } - - private Token skipSingleLineComment() { - assert (is('/')); - int currPos = internalState.lookaheadPos[0]; - int start = currPos - 1; - advance(); - while (!isEos() && !isLineTerminator(lookahead(0))) - advance(); - int stop = internalState.lookaheadPos[0]; - commentLocation(start, stop); - return Token.COMMENT; - } - - private void skipWhiteSpace() { - Mode mode = internalState.getMode(); - if ((mode != InternalState.Mode.DEFAULT) - && (mode != InternalState.Mode.IN_STRING_EMBEDDED_EXPRESSION)) { - return; - } - while (true) { - int c = lookahead(0); - if (isLineTerminator(c)) { - } else if (!isWhiteSpace(c)) { - break; - } - advance(); - } - } -} diff --git a/compiler/java/com/google/dart/compiler/parser/DartScannerParserContext.java b/compiler/java/com/google/dart/compiler/parser/DartScannerParserContext.java deleted file mode 100644 index e40bb4c2d089..000000000000 --- a/compiler/java/com/google/dart/compiler/parser/DartScannerParserContext.java +++ /dev/null @@ -1,201 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.parser; - -import com.google.dart.compiler.DartCompilationError; -import com.google.dart.compiler.DartCompilerListener; -import com.google.dart.compiler.DartSource; -import com.google.dart.compiler.Source; -import com.google.dart.compiler.ast.DartUnit; -import com.google.dart.compiler.common.HasSourceInfo; -import com.google.dart.compiler.common.HasSourceInfoSetter; -import com.google.dart.compiler.common.SourceInfo; -import com.google.dart.compiler.metrics.CompilerMetrics; -import com.google.dart.compiler.parser.DartScanner.Location; -import com.google.dart.compiler.parser.DartScanner.State; - -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.Stack; - -/** - * A ParserContext backed by a DartScanner. - */ -class DartScannerParserContext implements ParserContext { - private DartScanner scanner; - private Deque stateStack = new ArrayDeque(); - private Deque positionStack = new ArrayDeque(); - private Source source; - private DartCompilerListener listener; - private final CompilerMetrics compilerMetrics; - - public DartScannerParserContext(Source source, String sourceCode, - DartCompilerListener listener) { - this(source, sourceCode, listener, null); - } - - public DartScannerParserContext(Source source, String sourceCode, - DartCompilerListener listener, CompilerMetrics compilerMetrics) { - this.source = source; - this.scanner = createScanner(sourceCode, source, listener); - this.listener = listener; - this.compilerMetrics = compilerMetrics; - } - - @Override - public void begin() { - stateStack.push(scanner.getState()); - positionStack.push(getBeginLocation(0)); - } - - private int getBeginLocation(int n) { - DartScanner.Location tokenLocation = scanner.peekTokenLocation(n); - return tokenLocation != null ? tokenLocation.getBegin() : 0; - } - - private int getEndLocation() { - DartScanner.Location tokenLocation = scanner.getTokenLocation(); - return tokenLocation != null ? tokenLocation.getEnd() : 0; - } - - @Override - public T done(T result) { - DartScanner.State oldState = stateStack.pop(); - DartScanner.State newState = stateStack.peek(); - - // If there is more state left, push the newer token changes to them. - if (newState != null) { - if (oldState.rollbackTokens != null) { - if (newState.rollbackTokens != null) { - oldState.rollbackTokens.addAll(newState.rollbackTokens); - } - newState.rollbackTokens = oldState.rollbackTokens; - } - } - - setSourcePosition(result, positionStack.pop()); - - if (result instanceof DartUnit) { - if (compilerMetrics != null) { - compilerMetrics.unitParsed(scanner.getCharCount(), scanner.getNonCommentCharCount(), - 0, 0); - } - } - - // want next begin() call to seek to the next token and skip whitespace after previous done() - return result; - } - - /** - * Set the source position on a result, if it is a {@link HasSourceInfo}. - * - * @param result type - * @param result - * @param startPos - */ - private void setSourcePosition(T result, int startPos) { - if (result instanceof HasSourceInfoSetter) { - HasSourceInfoSetter hasSourceInfoSetter = (HasSourceInfoSetter) result; - int start = startPos; - int end = getEndLocation(); - if (start != -1 && end < start) { - // handle 0-length tokens, including where there is trailing whitespace - end = start; - } - hasSourceInfoSetter.setSourceInfo(new SourceInfo(source, start, end - start)); - } - } - - @Override - public T doneWithoutConsuming(T result) { - // do not throw away state - setSourcePosition(result, positionStack.peek()); - - // want next begin() call to seek to the next token and skip whitespace after previous done() - return result; - } - - @Override - public void error(DartCompilationError dartError) { - listener.onError(dartError); - } - - @Override - public void unitAboutToCompile(DartSource source, boolean diet) { - listener.unitAboutToCompile(source, diet); - } - - @Override - public void advance() { - scanner.next(); - } - - @Override - public Token getCurrentToken() { - return scanner.getToken(); - } - - @Override - public Token peek(int steps) { - return scanner.peek(steps); - } - - @Override - public void rollback() { - // undo changes made to scanner tokens - DartScanner.State oldState = stateStack.pop(); - scanner.restoreState(oldState); - - // Restore the replaced tokens to their state. - if (oldState.rollbackTokens != null) { - while (!oldState.rollbackTokens.isEmpty()) { - State.RollbackToken token = oldState.rollbackTokens.pop(); - scanner.setAbsolutePeek(token.absoluteOffset, token.replacedToken); - } - } - positionStack.pop(); - } - - @Override - public String getTokenString() { - return scanner.getTokenValue(); - } - - @Override - public Location peekTokenLocation(int n) { - return scanner.peekTokenLocation(n); - } - - @Override - public String peekTokenString(int steps) { - return scanner.peekTokenValue(steps); - } - - @Override - public void replaceNextToken(Token token) { - DartScanner.State state = stateStack.peek(); - DartScanner.State.RollbackToken oldToken - = new DartScanner.State.RollbackToken(scanner.getOffset() + 1, scanner.peek(0)); - if (state.rollbackTokens == null) { - state.rollbackTokens = new Stack(); - } - state.rollbackTokens.push(oldToken); - scanner.setPeek(0, token); - } - - @Override - public DartScanner.Location getTokenLocation() { - return scanner.getTokenLocation(); - } - - protected DartScanner createScanner(String sourceCode, Source source, DartCompilerListener listener) { - return new DartScanner(sourceCode, 0, source, listener); - } - - @Override - public Source getSource() { - return source; - } -} diff --git a/compiler/java/com/google/dart/compiler/parser/ParserContext.java b/compiler/java/com/google/dart/compiler/parser/ParserContext.java deleted file mode 100644 index f56efdeba4d1..000000000000 --- a/compiler/java/com/google/dart/compiler/parser/ParserContext.java +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.parser; - -import com.google.dart.compiler.DartCompilationError; -import com.google.dart.compiler.DartSource; -import com.google.dart.compiler.Source; -import com.google.dart.compiler.parser.DartScanner.Location; - -/** - * Abstracts parser and permits marking lexical ranges via event driven methods. Certain IDEs need - * more location information than just the source line/column/position of an AST node, such as the - * complete set of lexemes that encompass a given node, e.g. function foo() {}} => - * [FUNCTION, SPACE, IDENTIFIER, LPAREN, RPAREN, SPACE, LBRACE, RBRACE].This interface allows a - * parser to mark the begin and end of each non-terminal AST node in a lexical stream. - */ -public interface ParserContext { - - /** - * Consume the current token, and advance to the next one, skipping whitespace and comment - * tokens. - */ - void advance(); - - /** - * Called at the beginning of a non-terminal rule. The purpose for this method - * is to record any information that might be needed at the end of the rule - * (such as the current source position) as well as any state necessary to be - * able to roll back to the state just prior to the invocation of this method. - * - * @see #done(T) - * @see #doneWithoutConsuming(T) - * @see #rollback() - */ - void begin(); - - /** - * Called at the end of a non-terminal rule to mark the end of the non-terminal - * node. This method consumes any information saved by the {@link #begin()} - * method, updating the node with any saved information (such as its position - * in the source) as appropriate. - * - * @param result the non-terminal node being ended - * - * @return the non-terminal node that should be included in the AST structure, - * which is typically the same as the argument - * - * @see #begin() - * @see #doneWithoutConsuming(T) - * @see #rollback() - */ - T done(T result); - - /** - * Called at the end of a non-terminal rule to mark the end of the non-terminal - * node. Unlike {@link #done()}, this method does not consume any information - * saved by the {@link #begin()} method, but does update the node with any - * saved information (such as its position in the source) as appropriate. - * - * @param result the non-terminal node being ended - * - * @return the non-terminal node that should be included in the AST structure, - * which is typically the same as the argument - * - * @see #begin() - * @see #doneWithoutConsuming(T) - * @see #rollback() - */ - T doneWithoutConsuming(T result); - - /** - * Log a parse error for the current lexical range. - * @param dartError helpful error messaging describing what the expected tokens were - */ - void error(DartCompilationError dartError); - - /** - * Called by the {@link DartParser} before parsing given {@link DartSource}. - */ - void unitAboutToCompile(DartSource source, boolean diet); - - /** - * Return the current token. - */ - Token getCurrentToken(); - - /** - * Return Source if present. - */ - Source getSource(); - - /** - * Return location information for the current token. - */ - DartScanner.Location getTokenLocation(); - - /** - * Return the string value, if any, of the current token (e.g. IDENTIFIER) - */ - String getTokenString(); - - /** - * Peek ahead without advancing the lexer. - */ - Token peek(int steps); - - /** - * Return location information for the token that is 'n' tokens ahead of the current token. - */ - Location peekTokenLocation(int n); - - /** - * Set the next token to be returned. - */ - void replaceNextToken(Token token); - - /** - * Rolls back the current token to the position when {@link begin()} was - * called. - * - * @see #begin() - * @see #done(T) - * @see #doneWithoutConsuming(T) - */ - void rollback(); - - /** - * Peek ahead, for the value, without advancing the lexer. - */ - String peekTokenString(int steps); - -} diff --git a/compiler/java/com/google/dart/compiler/parser/ParserErrorCode.java b/compiler/java/com/google/dart/compiler/parser/ParserErrorCode.java deleted file mode 100644 index 5fb33c989743..000000000000 --- a/compiler/java/com/google/dart/compiler/parser/ParserErrorCode.java +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.parser; - -import com.google.dart.compiler.ErrorCode; -import com.google.dart.compiler.ErrorSeverity; -import com.google.dart.compiler.SubSystem; - -/** - * {@link ErrorCode}s for parser. - *

- * The convention in this file (with some exceptions) is that the enumeration name matches at least - * the beginning default English translation of the message. - */ -public enum ParserErrorCode implements ErrorCode { - ABSTRACT_MEMBER_IN_INTERFACE("Abstract members are not allowed in interfaces"), - ABSTRACT_METHOD_WITH_BODY("Abstract method cannot have a body"), - ABSTRACT_TOP_LEVEL_ELEMENT("Only class can be abstract top-level element"), - BREAK_OUTSIDE_OF_LOOP("'break' used outside of loop, case statement"), - BUILT_IN_IDENTIFIER_AS_TYPE_NAME("Built-in identifier cannot be used as type name"), - BUILT_IN_IDENTIFIER_AS_TYPEDEF_NAME("Built-in identifier can not be used as type alias name"), - BUILT_IN_IDENTIFIER_AS_TYPE_VARIABLE_NAME("Built-in identifier can not be used as type variable name"), - CANNOT_MIX_OPTIONAL_AND_NAMED_PARAMETERS("Cannot mix both optional and named parameters in the same function"), - CATCH_OR_FINALLY_EXPECTED("catch or finally clause expected."), - CONTINUE_IN_CASE_MUST_HAVE_LABEL("'continue' in case statement must have a label as a target."), - CONTINUE_OUTSIDE_OF_LOOP("'continue' used outside of loop or case statement"), - DEFAULT_VALUE_CAN_NOT_BE_SPECIFIED_IN_CLOSURE( - "Default values cannot be specified in closure parameter"), - DEFAULT_VALUE_CAN_NOT_BE_SPECIFIED_IN_TYPEDEF( - "Default values cannot be specified in closure type definition"), - DEFAULT_POSITIONAL_PARAMETER("Positional parameters cannot have default values"), - DEPRECATED_CATCH("This style of catch clause has been deprecated. Please use the 'on' " + - "'catch' '(' (',' )? ')' form."), - DEPRECATED_ABSTRACT_METHOD(ErrorSeverity.WARNING, "Modifier 'abstract' is deprecated for methods without body. Remove it."), - DEPRECATED_FUNCTION_LITERAL("Deprecated function literal syntax, remove return type and name"), - DEPRECATED_GETTER("The presence of parentheses after the name of the getter " - + "has been deprecated and will soon be disallowed. Please remove the parentheses."), - DEPRECATED_INTERFACE("Deprecated declaration of the 'interface', use abstract 'class' instead"), - DEPRECATED_USE_OF_FACTORY_KEYWORD("Deprecated use of the 'factory' keyword: use 'default' instead"), - DEPRECATED_RAW_STRING("The use of '@' to prefix a raw string has been deprecated; use 'r' instead"), - DEPRECATED_RESOURCE_DIRECTIVE("The #resource directive has been deprecated and will soon be disallowed"), - DEPRECATED_STRICT_EQ("Deprecated use of '===', use 'identical()' or '==' instead."), - DEPRECATED_STRICT_NE("Deprecated use of '!==', use '!identical()' or '!=' instead."), - DEPRECATED_LIBRARY_DIRECTIVE("The '#library(url)' directive has been deprecated, use 'library name' instead"), - DEPRECATED_IMPORT_DIRECTIVE("The '#import(url)' directive has been deprecated, use 'import url' instead"), - DEPRECATED_SOURCE_DIRECTIVE("The '#source(url)' directive has been deprecated, use 'part url' instead"), - DIRECTIVE_OUT_OF_ORDER("Directive out of order"), - DISALLOWED_ABSTRACT_KEYWORD("Abstract keyword not allowed here"), - // TODO(zundel): error message needs JUnit test (unreachable code?) - DISALLOWED_FACTORY_KEYWORD("Factory keyword not allowed here"), - DISALLOWED_STATIC_KEYWORD("Static keyword not allowed here"), - ESCAPED_NEWLINE("Escaped new-line characters are not allowed in string literals"), - EXPECTED_ARRAY_OR_MAP_LITERAL("Expected array or map literal"), - // TODO(zundel): error message needs JUnit test (unreachable code?) - EXPECTED_CASE_OR_DEFAULT("Expected 'case' or 'default'"), - EXPECTED_CLASS_DECLARATION_LBRACE("Expected '{' in class or interface declaration"), - // TODO(zundel): error message needs JUnit test - EXPECTED_COMMA_OR_RIGHT_BRACE("Expected ',' or '}'"), - EXPECTED_COMMA_OR_RIGHT_PAREN("Expected ',' or ')', but got '%s'"), - // TODO(zundel): error message needs JUnit test - EXPECTED_EOS("Unexpected token '%s' (expected end of file)"), - EXPECTED_EXPORT("Expected 'export'"), - // TODO(zundel): error message needs JUnit test - EXPECTED_EXPRESSION_AFTER_COMMA("Expected expression after comma"), - EXPECTED_EXTENDS("Expected 'extends'"), - EXPECTED_FUNCTION_STATEMENT_BODY("Expected function statement body"), - // TODO(zundel): error message needs JUnit test - EXPECTED_IDENTIFIER("Expected identifier"), - // TODO(zundel): error message needs JUnit test - EXPECTED_LEFT_PAREN("'(' expected"), - EXPECTED_PREFIX_KEYWORD("Expected 'prefix' after comma"), - EXPECTED_PREFIX_IDENTIFIER("Prefix string can only contain valid identifier characters"), - // TODO(zundel): error message needs JUnit test - EXPECTED_SEMICOLON("Expected ';'"), - // TODO(zundel): error message needs JUnit test - EXPECTED_STRING_LITERAL("Expected string literal"), - // TODO(zundel): error message needs JUnit test (unreachable code?) - EXPECTED_STRING_LITERAL_MAP_ENTRY_KEY("Expected string literal for map entry key"), - EXPECTED_TOKEN("Unexpected token '%s' (expected '%s')"), - // TODO(zundel): error message needs JUnit test - EXPECTED_VAR_FINAL_OR_TYPE("Expected 'var', 'final' or type"), - EXPORT_WITHOUT_LIBRARY_DIRECTIVE("Only library can use 'export' directive"), - EXTERNAL_ABSTRACT("External methods cannot be abstract"), - EXTERNAL_ONLY_METHOD("Only a top-level function, a method, a getter, a setter or an non-redirecting constructor can be specified as external"), - EXTERNAL_METHOD_BODY("External methods cannot have body"), - INVALID_SEPARATOR_FOR_NAMED("Use ':' between a named parameter and its value"), - INVALID_SEPARATOR_FOR_OPTIONAL("Use '=' between an optional parameter and its value"), - INVALID_UNICODE_NORMALIZATION("Source code should be normalized to Unicode Normalization Form C"), - // TODO(zundel): this error message is out of date - NATIVE_ONLY_CLASS("Native keyword can be specified only for classes"), - NATIVE_ONLY_CORE_LIB("Native keyword can be used only in corelib"), - FACTORY_CANNOT_BE_ABSTRACT("A factory cannot be abstract"), - FACTORY_CANNOT_BE_STATIC("A factory cannot be static"), - FACTORY_CANNOT_BE_TOP_LEVEL("A factory cannot be top level, it must be a member of a class"), - FACTORY_MEMBER_IN_INTERFACE("Factory members are not allowed in interfaces"), - FINAL_IS_NOT_ALLOWED_ON_A_METHOD_DEFINITION("'final' is not allowed on a method definition"), - FOR_IN_WITH_COMPLEX_VARIABLE("Only simple variables can be assigned to in a for-in construct"), - FOR_IN_WITH_MULTIPLE_VARIABLES("Too many variable declarations in a for-in construct"), - FOR_IN_WITH_VARIABLE_INITIALIZER("Cannot initialize for-in variables"), - FORMAL_PARAMETER_IS_CONST("Formal parameters cannot be declared 'const'"), - FUNCTION_TYPED_PARAMETER_IS_FINAL("Formal parameter with a function type cannot be const"), - FUNCTION_TYPED_PARAMETER_IS_VAR("Formal parameter with a function type cannot be var"), - FUNCTION_NAME_EXPECTED_IDENTIFIER("Function name expected to be an identifier"), - ILLEGAL_ASSIGNMENT_TO_NON_ASSIGNABLE("Illegal assignment to non-assignable expression"), - // TODO(zundel): error message needs JUnit test - ILLEGAL_NUMBER_OF_PARAMETERS("Illegal number of parameters"), - IMPLEMENTS_BEFORE_EXTENDS("The extends clause must be before the implements clause"), - IMPLEMENTS_BEFORE_WITH("The with clause must be before the implements clause"), - INCOMPLETE_STRING_LITERAL("Incomplete string literal"), - INTERFACE_METHOD_WITH_BODY("Interface method cannot have a body"), - // TODO(zundel): error message needs JUnit test - INVALID_FIELD_DECLARATION("Wrong syntax for field declaration"), - INVALID_IDENTIFIER("The token '%s' cannot be used as an identifier"), - INVALID_OPERATOR_CHAINING("Cannot chain '%s'"), - LABEL_NOT_FOLLOWED_BY_CASE_OR_DEFAULT("Label not followed by 'case', 'default', or statement"), - LOCAL_CANNOT_BE_STATIC("Local function cannot be static"), - MISSING_FUNCTION_NAME(ErrorSeverity.WARNING, "a function name is required for a declaration"), - MISSING_NAMED_PARAMETER_END("Expected '}' to close the list of named parameters"), - MISSING_OPTIONAL_PARAMETER_END("Expected ']' to close the list of optional parameters"), - MULTIPLE_EXTENDS_CLAUSES("Each class definition can have at most one extends clause"), - MULTIPLE_IMPLEMENTS_CLAUSES("Each class definition can have at most one implements clause"), - MULTIPLE_WITH_CLAUSES("Each class definition can have at most one with clause"), - NAMED_PARAMETER_NOT_ALLOWED("Named parameter is not allowed for operator or setter method"), - NO_SPACE_AFTER_PLUS("Cannot have space between plus and numeric literal"), - NO_SOUP_FOR_YOU("Too many errors"), - NO_UNARY_PLUS_OPERATOR("No unary plus operator in Dart"), - NON_CONST_MAP_LITERAL_STATEMENT("Map literals appearing as a statement must be 'const'"), - NON_FINAL_STATIC_MEMBER_IN_INTERFACE("Non-final/const static members are not allowed in interfaces"), - ONLY_FACTORIES_CAN_REDIRECT("Only factory constructors can redirect to another constructor"), - ONLY_ONE_LIBRARY_DIRECTIVE("Only one library directive may be declared in a file"), - OPERATOR_CANNOT_BE_STATIC("Operators cannot be static"), - OPERATOR_IS_NOT_USER_DEFINABLE("Operator is not user definable"), - OPTIONAL_POSITIONAL_PARAMETER_NOT_ALLOWED("Optional positional parameter is not allowed for operator or setter method"), - POSITIONAL_AFTER_NAMED_ARGUMENT("Positional argument after named argument"), - REDIRECTING_CONSTRUCTOR_CANNOT_HAVE_A_BODY("Redirecting constructor cannot have a body"), - REDIRECTING_CONSTRUCTOR_PARAM("Redirecting constructor cannot have initializers"), - REDIRECTING_CONSTRUCTOR_ITSELF("Redirecting constructor cannot have initializers"), - REDIRECTING_CONSTRUCTOR_MULTIPLE("Multiple redirecting constructor invocations"), - REDIRECTING_CONSTRUCTOR_OTHER("Redirecting constructor cannot have initializers"), - STATIC_MEMBERS_CANNOT_BE_ABSTRACT("Static members cannot be abstract"), - SUPER_CONSTRUCTOR_MULTIPLE("'super' must be called only once in the initialization list"), - SUPER_CANNOT_BE_USED_AS_THE_SECOND_OPERAND( - "'super' cannot be used as the second operand in a binary expression."), - SUPER_IS_NOT_VALID_AS_A_BOOLEAN_OPERAND("'super' is not valid as a boolean operand"), - SUPER_IS_NOT_VALID_ALONE_OR_AS_A_BOOLEAN_OPERAND( - "'super' is not valid alone or as a boolean operand"), - TOP_LEVEL_CANNOT_BE_STATIC("Top-level field or method cannot be static"), - UNREACHABLE_CODE_IN_CASE(ErrorSeverity.WARNING, "Unreachable code in case statement"), - UNEXPECTED_TOKEN("Unexpected token '%s'"), - UNEXPECTED_TOKEN_IN_STRING_INTERPOLATION("Unexpected token in string interpolation: %s"), - URI_CANNOT_USE_INTERPOLATION("URIs cannot use string interpolation"), - VAR_IS_NOT_ALLOWED_ON_A_METHOD_DEFINITION("'var' is not allowed on a method definition"), - VOID_FIELD("Field cannot be of type void"), - VOID_PARAMETER("Parameter cannot be of type void"), - WITH_BEFORE_EXTENDS("The extends clause must be before the with clause"), - WITH_WITHOUT_EXTENDS("The with clause cannot be used without an extends clause"); - - private final ErrorSeverity severity; - private final String message; - - /** - * Initialize a newly created error code to have the given message and ERROR severity. - */ - private ParserErrorCode(String message) { - this(ErrorSeverity.ERROR, message); - } - - /** - * Initialize a newly created error code to have the given severity and message. - */ - private ParserErrorCode(ErrorSeverity severity, String message) { - this.severity = severity; - this.message = message; - } - - @Override - public String getMessage() { - return message; - } - - @Override - public ErrorSeverity getErrorSeverity() { - return severity; - } - - @Override - public SubSystem getSubSystem() { - return SubSystem.PARSER; - } - - @Override - public boolean needsRecompilation() { - return true; - } -} \ No newline at end of file diff --git a/compiler/java/com/google/dart/compiler/parser/Terminals.java b/compiler/java/com/google/dart/compiler/parser/Terminals.java deleted file mode 100644 index 85c8e67775ce..000000000000 --- a/compiler/java/com/google/dart/compiler/parser/Terminals.java +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. -package com.google.dart.compiler.parser; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Put this annotation on a method in {@link DartParser} so that code will not consume any tokens - * that a method further up on the stack can use to properly terminate a statement. - */ -@Retention(value=RetentionPolicy.RUNTIME) -@Target(value=ElementType.METHOD) -public @interface Terminals { - public Token[] tokens() default {}; -} diff --git a/compiler/java/com/google/dart/compiler/parser/Token.java b/compiler/java/com/google/dart/compiler/parser/Token.java deleted file mode 100644 index 53b3dde4802a..000000000000 --- a/compiler/java/com/google/dart/compiler/parser/Token.java +++ /dev/null @@ -1,268 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.parser; - -import java.util.HashMap; -import java.util.Map; - -/** - * Dart tokens and associated data. - * - * Note: Token ordinals matter for some accessors, so don't change the order of these without - * knowing what you're doing. - */ -public enum Token { - /* End-of-stream. */ - EOS(null, 0), - - /* Punctuators. */ - AT("@", 0), - LPAREN("(", 0), - RPAREN(")", 0), - LBRACK("[", 0), - RBRACK("]", 0), - LBRACE("{", 0), - RBRACE("}", 0), - COLON(":", 0), - SEMICOLON(";", 0), - PERIOD(".", 0), - CASCADE("..", 2), - ELLIPSIS("...", 0), - COMMA(",", 0), - CONDITIONAL("?", 3), - ARROW("=>", 0), - - /* Assignment operators. */ - ASSIGN("=", 1), - ASSIGN_BIT_OR("|=", 1), - ASSIGN_BIT_XOR("^=", 1), - ASSIGN_BIT_AND("&=", 1), - ASSIGN_SHL("<<=", 1), - ASSIGN_SAR(">>=", 1), - ASSIGN_ADD("+=", 1), - ASSIGN_SUB("-=", 1), - ASSIGN_MUL("*=", 1), - ASSIGN_DIV("/=", 1), - ASSIGN_MOD("%=", 1), - ASSIGN_TRUNC("~/=", 1), - - /* Binary operators sorted by precedence. */ - OR("||", 4), - AND("&&", 5), - BIT_OR("|", 6), - BIT_XOR("^", 7), - BIT_AND("&", 8), - SHL("<<", 11), - SAR(">>", 11), - ADD("+", 12), - SUB("-", 12), - MUL("*", 13), - DIV("/", 13), - TRUNC("~/", 13), - MOD("%", 13), - - /* Compare operators sorted by precedence. */ - EQ("==", 9), - NE("!=", 9), - EQ_STRICT("===", 9), - NE_STRICT("!==", 9), - LT("<", 10), - GT(">", 10), - LTE("<=", 10), - GTE(">=", 10), - AS("as", 10), - IS("is", 10), - - /* Unary operators. */ - NOT("!", 0), - BIT_NOT("~", 0), - - /* Count operators (also unary). */ - INC("++", 0), - DEC("--", 0), - - /* [] operator overloading. */ - INDEX("[]", 0), - ASSIGN_INDEX("[]=", 0), - - /* Keywords. */ - ASSERT("assert", 0), - BREAK("break", 0), - CASE("case", 0), - CATCH("catch", 0), - CLASS("class",0), - CONST("const", 0), - CONTINUE("continue", 0), - DEFAULT("default", 0), - DO("do", 0), - ELSE("else", 0), - EXTENDS("extends", 0), - FINAL("final", 0), - FINALLY("finally", 0), - FOR("for", 0), - IF("if", 0), - IN("in", 0), - NEW("new", 0), - RETHROW("rethrow", 0), - RETURN("return", 0), - SUPER("super", 0), - SWITCH("switch", 0), - THIS("this", 0), - THROW("throw", 0), - TRY("try", 0), - VAR("var", 0), - VOID("void", 0), - WHILE("while", 0), - WITH("with", 0), - - /* Literals. */ - NULL_LITERAL("null", 0), - TRUE_LITERAL("true", 0), - FALSE_LITERAL("false", 0), - HEX_LITERAL(null, 0), - INTEGER_LITERAL(null, 0), - DOUBLE_LITERAL(null, 0), - STRING(null, 0), - - /** String interpolation and string templates. */ - STRING_SEGMENT(null, 0), - STRING_LAST_SEGMENT(null, 0), - // STRING_EMBED_EXP_START does not have a unique string representation in the code: - // "$id" yields the token STRING_EMBED_EXP_START after the '$', and similarly - // "${id}" yield the same token for '${'. - STRING_EMBED_EXP_START(null, 0), - STRING_EMBED_EXP_END(null, 0), - - // Note: STRING_EMBED_EXP_END uses the same symbol as RBRACE, but it is - // recognized by the scanner when closing embedded expressions in string - // interpolation and string templates. - - /* Directives */ - LIBRARY("#library", 0), - IMPORT("#import", 0), - SOURCE("#source", 0), - RESOURCE("#resource", 0), - NATIVE("#native", 0), - - /* Identifiers (not keywords). */ - IDENTIFIER(null, 0), - WHITESPACE(null, 0), - - /* Pseudo tokens. */ - // If you add another pseudo token, don't forget to update the predicate below. - ILLEGAL(null, 0), - COMMENT(null, 0), - - /** - * Non-token to be used by tools where a value outside the range of anything - * returned by the scanner is needed. This is the equivalent of -1 in a C - * tokenizer. - * - * This token is never returned by the scanner. It must have an ordinal - * value outside the range of all tokens returned by the scanner. - */ - NON_TOKEN(null, 0); - - private static Map tokens = new HashMap(); - - static { - for (Token tok : Token.values()) { - if (tok.syntax_ != null) { - tokens.put(tok.syntax_, tok); - } - } - } - - /** - * Given a string finds the corresponding token. Pseudo tokens (EOS, ILLEGAL and COMMENT) are - * ignored. - */ - public static Token lookup(String syntax) { - Token token = tokens.get(syntax); - if ("as".equals(syntax)) { - return IDENTIFIER; - } - if (token == null) { - return IDENTIFIER; - } - return token; - } - - private final String syntax_; - private final int precedence_; - - /** - * The syntax parameter serves two purposes: 1. map tokens that - * look like identifiers ("null", "true", etc.) to their correct token. - * 2. Find the string-representation of operators.
- * When it is null then the token either doesn't have a unique - * representation, or it is a pseudo token (which doesn't physically appear - * in the source). - */ - Token(String syntax, int precedence) { - syntax_ = syntax; - precedence_ = precedence; - } - - public Token asBinaryOperator() { - int ordinal = ordinal() - ASSIGN_BIT_OR.ordinal() + BIT_OR.ordinal(); - return values()[ordinal]; - } - - public int getPrecedence() { - return precedence_; - } - - public String getSyntax() { - return syntax_; - } - - public boolean isEqualityOperator() { - int ordinal = ordinal(); - return EQ.ordinal() <= ordinal && ordinal <= NE_STRICT.ordinal(); - } - - public boolean isRelationalOperator() { - int ordinal = ordinal(); - return LT.ordinal() <= ordinal && ordinal <= GTE.ordinal(); - } - - public boolean isAssignmentOperator() { - int ordinal = ordinal(); - return ASSIGN.ordinal() <= ordinal && ordinal <= ASSIGN_TRUNC.ordinal(); - } - - public boolean isBinaryOperator() { - int ordinal = ordinal(); - return (ASSIGN.ordinal() <= ordinal && ordinal <= IS.ordinal()) - || (ordinal == COMMA.ordinal()); - } - - public boolean isCountOperator() { - int ordinal = ordinal(); - return INC.ordinal() <= ordinal && ordinal <= DEC.ordinal(); - } - - public boolean isUnaryOperator() { - int ordinal = ordinal(); - return NOT.ordinal() <= ordinal && ordinal <= DEC.ordinal(); - } - - public boolean isUserDefinableOperator() { - int ordinal = ordinal(); - return ((BIT_OR.ordinal() <= ordinal && ordinal <= GTE.ordinal()) - || this == BIT_NOT || this == INDEX || this == ASSIGN_INDEX) - && this != NE && this != EQ_STRICT && this != NE_STRICT; - } - - @Override - public String toString() { - String result = getSyntax(); - if (result == null) { - return name(); - } - return result; - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/AbstractNodeElement.java b/compiler/java/com/google/dart/compiler/resolver/AbstractNodeElement.java deleted file mode 100644 index 2c5a703d15f6..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/AbstractNodeElement.java +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.dart.compiler.ast.DartNode; -import com.google.dart.compiler.ast.DartObsoleteMetadata; -import com.google.dart.compiler.ast.Modifiers; -import com.google.dart.compiler.common.SourceInfo; -import com.google.dart.compiler.type.Type; -import com.google.dart.compiler.type.Types; -import com.google.dart.compiler.util.StringInterner; - -abstract class AbstractNodeElement implements Element, NodeElement { - private final DartNode node; - private final String name; - private SourceInfo sourceInfo; - - AbstractNodeElement(DartNode node, String name) { - // TODO(scheglov) in the future we will not use ASTNode and remove null check - this.sourceInfo = node != null ? node.getSourceInfo() : SourceInfo.UNKNOWN; - this.node = node; - this.name = StringInterner.intern(name); - } - - @Override - public DartNode getNode() { - return node; - } - - @Override - public String getName() { - return name; - } - - @Override - public String getOriginalName() { - return name; - } - - @Override - public abstract ElementKind getKind(); - - @Override - public final String toString() { - return getKind() + " " + getName(); - } - - @Override - public Type getType() { - return Types.newDynamicType(); - } - - void setType(Type type) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isDynamic() { - return false; - } - - @Override - public DartObsoleteMetadata getMetadata() { - return DartObsoleteMetadata.EMPTY; - } - - @Override - public Modifiers getModifiers() { - return Modifiers.NONE; - } - - @Override - public EnclosingElement getEnclosingElement() { - return null; - } - - @Override - public SourceInfo getNameLocation() { - return sourceInfo; - } - - @Override - public final SourceInfo getSourceInfo() { - return sourceInfo; - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/ClassAliasElement.java b/compiler/java/com/google/dart/compiler/resolver/ClassAliasElement.java deleted file mode 100644 index c392fbdd7878..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/ClassAliasElement.java +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -/** - * A class type alias. - */ -public interface ClassAliasElement extends ClassElement { -} diff --git a/compiler/java/com/google/dart/compiler/resolver/ClassElement.java b/compiler/java/com/google/dart/compiler/resolver/ClassElement.java deleted file mode 100644 index e2195363d763..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/ClassElement.java +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.dart.compiler.type.InterfaceType; -import com.google.dart.compiler.type.Type; - -import java.util.List; - -public interface ClassElement extends EnclosingElement { - void setType(InterfaceType type); - - @Override - InterfaceType getType(); - - List getTypeParameters(); - - InterfaceType getSupertype(); - - InterfaceType getDefaultClass(); - - void setSupertype(InterfaceType element); - - List getConstructors(); - - LibraryElement getLibrary(); - - List getInterfaces(); - - List getMixins(); - - List getAllSupertypes() throws CyclicDeclarationException; - - String getNativeName(); - - /** - * FIXME(scheglov) We use this in {@link Resolver} to check that "factory" clause is exactly - * same as declaration of factory class. - */ - String getDeclarationNameWithTypeParameters(); - - boolean isObject(); - - boolean isObjectChild(); - - ConstructorElement lookupConstructor(String name); - - /** - * @return the {@link Element}s which are declared in superclass or interfaces, but not - * implemented in this class. May be null if this {@link ClassElement} is - * {@link ClassNodeElement} and was not analyzed yet. - */ - List getUnimplementedMembers(); - - int getOpenBraceOffset(); - - int getCloseBraceOffset(); - - boolean hasSuperInvocation(); -} diff --git a/compiler/java/com/google/dart/compiler/resolver/ClassElementImplementation.java b/compiler/java/com/google/dart/compiler/resolver/ClassElementImplementation.java deleted file mode 100644 index 83b6631f65b0..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/ClassElementImplementation.java +++ /dev/null @@ -1,463 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.common.collect.Lists; -import com.google.dart.compiler.ast.ASTNodes; -import com.google.dart.compiler.ast.DartClass; -import com.google.dart.compiler.ast.DartClassTypeAlias; -import com.google.dart.compiler.ast.DartDeclaration; -import com.google.dart.compiler.ast.DartIdentifier; -import com.google.dart.compiler.ast.DartObsoleteMetadata; -import com.google.dart.compiler.ast.DartStringLiteral; -import com.google.dart.compiler.ast.DartTypeParameter; -import com.google.dart.compiler.ast.Modifiers; -import com.google.dart.compiler.common.SourceInfo; -import com.google.dart.compiler.type.InterfaceType; -import com.google.dart.compiler.type.Type; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.atomic.AtomicReference; - -class ClassElementImplementation extends AbstractNodeElement implements ClassNodeElement { - private InterfaceType type; - private InterfaceType supertype; - private InterfaceType defaultClass; - private final List interfaces = Lists.newArrayList(); - private final List mixins = Lists.newArrayList(); - private final boolean isInterface; - private final String nativeName; - private final DartObsoleteMetadata metadata; - private final Modifiers modifiers; - private final AtomicReference> allSupertypes = - new AtomicReference>(); - private final SourceInfo nameLocation; - private final String declarationNameWithTypeParameter; - private List unimplementedMembers; - private final int openBraceOffset; - private final int closeBraceOffset; - private final boolean hasSuperInvocation; - - // declared volatile for thread-safety - @SuppressWarnings("unused") - private volatile Set subtypes; - - private final List constructors = Lists.newArrayList(); - private final ElementMap members = new ElementMap(); - - private final LibraryElement library; - - private static ThreadLocal> seenSupertypes = new ThreadLocal>() { - @Override - protected Set initialValue() { - return new HashSet(); - } - }; - - ClassElementImplementation(DartClass node, String name, String nativeName, - LibraryElement library) { - super(node, name); - this.nativeName = nativeName; - this.library = library; - if (node != null) { - isInterface = node.isInterface(); - metadata = node.getObsoleteMetadata(); - modifiers = node.getModifiers(); - nameLocation = node.getName().getSourceInfo(); - declarationNameWithTypeParameter = createDeclarationName(node.getName(), node.getTypeParameters()); - openBraceOffset = node.getOpenBraceOffset(); - closeBraceOffset = node.getCloseBraceOffset(); - hasSuperInvocation = ASTNodes.hasSuperInvocation(node); - } else { - isInterface = false; - metadata = DartObsoleteMetadata.EMPTY; - modifiers = Modifiers.NONE; - nameLocation = SourceInfo.UNKNOWN; - declarationNameWithTypeParameter = ""; - openBraceOffset = -1; - closeBraceOffset = -1; - hasSuperInvocation = false; - } - } - - ClassElementImplementation(DartClassTypeAlias node, String name, - LibraryElement library) { - super(node, name); - this.nativeName = null; - this.library = library; - if (node != null) { - isInterface = false; - metadata = node.getObsoleteMetadata(); - modifiers = node.getModifiers(); - nameLocation = node.getName().getSourceInfo(); - declarationNameWithTypeParameter = createDeclarationName(node.getName(), node.getTypeParameters()); - openBraceOffset = -1; - closeBraceOffset = -1; - hasSuperInvocation = false; - } else { - isInterface = false; - metadata = DartObsoleteMetadata.EMPTY; - modifiers = Modifiers.NONE; - nameLocation = SourceInfo.UNKNOWN; - declarationNameWithTypeParameter = ""; - openBraceOffset = -1; - closeBraceOffset = -1; - hasSuperInvocation = false; - } - } - - @Override - public DartDeclaration getNode() { - return (DartDeclaration) super.getNode(); - } - - @Override - public SourceInfo getNameLocation() { - return nameLocation; - } - - @Override - public void setType(InterfaceType type) { - this.type = type; - } - - @Override - public InterfaceType getType() { - return type; - } - - @Override - public List getTypeParameters() { - return getType().getArguments(); - } - - @Override - public InterfaceType getSupertype() { - return supertype; - } - - @Override - public InterfaceType getDefaultClass() { - return defaultClass; - } - - @Override - public void setSupertype(InterfaceType supertype) { - if (this.supertype != null) { - this.supertype.unregisterSubClass(this); - } - this.supertype = supertype; - if (this.supertype != null) { - this.supertype.registerSubClass(this); - } - } - - void setDefaultClass(InterfaceType element) { - defaultClass = element; - } - - @Override - public Iterable getMembers() { - return new Iterable() { - // The only use case for calling getMembers() is for iterating through the - // members. You should not be able to add or remove members through the - // object returned by this method. Returning members or members.value() - // would allow such direct manipulation which might be problematic for - // keeping the element model consistent. - // - // On the other hand, we don't want to make a defensive copy of the list - // because that makes this method expensive. This method should not be - // expensive because the IDE may be using it in interactive scenarios. - // Strictly speaking, we should also wrap the iterator as we don't want - // the method Iterator.remove to be used either. - @Override - public Iterator iterator() { - return members.values().iterator(); - } - }; - } - - @Override - public List getConstructors() { - return constructors; - } - - @Override - public List getInterfaces() { - return interfaces; - } - - @Override - public List getMixins() { - return mixins; - } - - @Override - public ElementKind getKind() { - return ElementKind.CLASS; - } - - @Override - public boolean isInterface() { - return isInterface; - } - - @Override - public DartObsoleteMetadata getMetadata() { - return metadata; - } - - @Override - public Modifiers getModifiers() { - return modifiers; - } - - @Override - public LibraryElement getLibrary() { - return library; - } - - @Override - public String getNativeName() { - return nativeName; - } - - @Override - public String getDeclarationNameWithTypeParameters() { - return declarationNameWithTypeParameter; - } - - void addMethod(MethodNodeElement member) { - String name = member.getName(); - if (member.getModifiers().isOperator()) { - name = "operator " + name; - } - members.add(name, member); - } - - void addConstructor(ConstructorNodeElement member) { - constructors.add(member); - } - - void addField(FieldNodeElement member) { - members.add(member.getName(), member); - } - - void addInterface(InterfaceType type) { - interfaces.add(type); - type.registerSubClass(this); - } - - void addMixin(InterfaceType type) { - mixins.add(type); - } - - Element findElement(String name) { - // Temporary find all strategy to get things working. - // Match resolve order in Resolver.visitMethodInvocation - Element element = lookupLocalMethod(name); - if (element != null) { - return element; - } - element = lookupLocalField(name); - if (element != null) { - return element; - } - if (type != null) { - for (Type arg : type.getArguments()) { - if (arg.getElement().getName().equals(name)) { - return arg.getElement(); - } - } - } - // Don't look for constructors, they are in a different namespace. - return null; - } - - /** - * Lookup a constructor declared in this class. Note that a class may define - * constructors for interfaces in case the class is a default implementation. - * - * @param type The type of the object this constructor is creating. - * @param name The constructor name ("" if unnamed). - * - * @return The constructor found in the class, or null if not found. - */ - ConstructorElement lookupConstructor(ClassElement type, String name) { - for (ConstructorElement element : constructors) { - if (element.getConstructorType().equals(type) && element.getName().equals(name)) { - return element; - } - } - return null; - } - - @Override - public ConstructorElement lookupConstructor(String name) { - // Lookup a constructor that creates instances of this class. - return lookupConstructor(this, name); - } - - @Override - public Element lookupLocalElement(String name) { - return members.get(name); - } - - FieldElement lookupLocalField(String name) { - return (FieldElement) members.get(name, ElementKind.FIELD); - } - - MethodElement lookupLocalMethod(String name) { - return (MethodElement) members.get(name, ElementKind.METHOD); - } - - public static ClassElementImplementation fromNode(DartClass node, LibraryElement library) { - DartStringLiteral nativeName = node.getNativeName(); - String nativeNameString = (nativeName == null ? null : nativeName.getValue()); - return new ClassElementImplementation(node, node.getClassName(), nativeNameString, library); - } - - static class ClassAliasElementImplementation extends ClassElementImplementation implements ClassAliasElement { - ClassAliasElementImplementation(DartClassTypeAlias node, String name, LibraryElement library) { - super(node, name, library); - } - } - public static ClassAliasElement fromNode(DartClassTypeAlias node, LibraryElement library) { - return new ClassAliasElementImplementation(node, node.getClassName(), library); - } - - public static ClassElementImplementation named(String name) { - return new ClassElementImplementation(null, name, null, null); - } - - @Override - public boolean isObject() { - return supertype == null; - } - - @Override - public boolean isObjectChild() { - return supertype != null && supertype.getElement().isObject(); - } - - @Override - public EnclosingElement getEnclosingElement() { - return library; - } - - @Override - public List getAllSupertypes() - throws CyclicDeclarationException { - List list = allSupertypes.get(); - if (list == null) { - allSupertypes.compareAndSet(null, computeAllSupertypes()); - list = allSupertypes.get(); - } - return list; - } - - private List computeAllSupertypes() - throws CyclicDeclarationException { - Map interfaces = new HashMap(); - if (!seenSupertypes.get().add(this)) { - throw new CyclicDeclarationException(this); - } - ArrayList supertypes = new ArrayList(); - try { - for (InterfaceType intf : getInterfaces()) { - addInterfaceToSupertypes(interfaces, supertypes, intf); - } - for (InterfaceType mix : getMixins()) { - addInterfaceToSupertypes(interfaces, supertypes, mix); - } - for (InterfaceType intf : getInterfaces()) { - for (InterfaceType t : intf.getElement().getAllSupertypes()) { - if (!t.getElement().isObject()) { - addInterfaceToSupertypes(interfaces, supertypes, - t.subst(intf.getArguments(), - intf.getElement().getTypeParameters())); - } - } - } - if (supertype != null) { - for (InterfaceType t : supertype.getElement().getAllSupertypes()) { - if (t.getElement().isInterface()) { - addInterfaceToSupertypes(interfaces, supertypes, - t.subst(supertype.getArguments(), - supertype.getElement().getTypeParameters())); - } - } - supertypes.add(supertype); - for (InterfaceType t : supertype.getElement().getAllSupertypes()) { - if (!t.getElement().isInterface()) { - supertypes.add(t.subst(supertype.getArguments(), - supertype.getElement().getTypeParameters())); - } - } - } - } finally { - seenSupertypes.get().remove(this); - } - return supertypes; - } - - private String createDeclarationName( - DartIdentifier name, List typeParameters) { - StringBuilder builder = new StringBuilder(); - builder.append(name.toSource()); - int count = typeParameters.size(); - if (count > 0) { - builder.append("<"); - for (int i = 0; i < count; i++) { - if (i > 0) { - builder.append(", "); - } - builder.append(typeParameters.get(i).toSource()); - } - builder.append(">"); - } - return builder.toString(); - } - - private void addInterfaceToSupertypes(Map interfaces, - ArrayList supertypes, - InterfaceType intf) { - InterfaceType existing = interfaces.put(intf.getElement(), intf); - if (existing == null || !(existing.equals(intf))){ - supertypes.add(intf); - } - } - - @Override - public List getUnimplementedMembers() { - return unimplementedMembers; - } - - @Override - public void setUnimplementedMembers(List members) { - this.unimplementedMembers = members; - } - - @Override - public int getOpenBraceOffset() { - return openBraceOffset; - } - - @Override - public int getCloseBraceOffset() { - return closeBraceOffset; - } - - @Override - public boolean hasSuperInvocation() { - return hasSuperInvocation; - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/ClassElementUnion.java b/compiler/java/com/google/dart/compiler/resolver/ClassElementUnion.java deleted file mode 100644 index 59e5fad0524c..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/ClassElementUnion.java +++ /dev/null @@ -1,211 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.dart.compiler.ast.DartObsoleteMetadata; -import com.google.dart.compiler.ast.Modifiers; -import com.google.dart.compiler.common.SourceInfo; -import com.google.dart.compiler.type.InterfaceType; -import com.google.dart.compiler.type.Type; - -import java.util.List; - -public class ClassElementUnion implements ClassElement { - - private final InterfaceType unionType; - private final List types; - private final InterfaceType lastType; - private final ClassElement lastElement; - - public ClassElementUnion(InterfaceType unionType, List types) { - this.unionType = unionType; - this.types = types; - this.lastType = types.get(types.size() - 1); - this.lastElement = lastType.getElement(); - } - - @Override - public void setType(InterfaceType type) { - throw new UnsupportedOperationException(); - } - - @Override - public InterfaceType getType() { - return unionType; - } - - @Override - public List getTypeParameters() { - return ImmutableList.of(); - } - - @Override - public InterfaceType getSupertype() { - return lastElement.getSupertype(); - } - - @Override - public InterfaceType getDefaultClass() { - throw new UnsupportedOperationException(); - } - - @Override - public void setSupertype(InterfaceType element) { - throw new UnsupportedOperationException(); - } - - @Override - public LibraryElement getLibrary() { - return null; - } - - @Override - public List getInterfaces() { - List interfaces = Lists.newArrayList(); - for (InterfaceType type : types) { - if (type.getElement().isInterface()) { - interfaces.add(type); - } - } - return interfaces; - } - - @Override - public List getMixins() { - return ImmutableList.of(); - } - - @Override - public List getAllSupertypes() throws CyclicDeclarationException { - List superTypes = Lists.newArrayList(); - for (InterfaceType type : types) { - superTypes.addAll(type.getElement().getAllSupertypes()); - } - return superTypes; - } - - @Override - public String getNativeName() { - return lastElement.getNativeName(); - } - - @Override - public String getDeclarationNameWithTypeParameters() { - return lastElement.getDeclarationNameWithTypeParameters(); - } - - @Override - public boolean isObject() { - return lastElement.isObject(); - } - - @Override - public boolean isObjectChild() { - return lastElement.isObjectChild(); - } - - @Override - public ConstructorElement lookupConstructor(String name) { - throw new UnsupportedOperationException(); - } - - @Override - public List getUnimplementedMembers() { - throw new UnsupportedOperationException(); - } - - @Override - public Element lookupLocalElement(String name) { - for (InterfaceType type : types) { - Element localElement = type.getElement().lookupLocalElement(name); - if (localElement != null) { - return localElement; - } - } - return null; - } - - @Override - public boolean isInterface() { - return lastElement.isInterface(); - } - - @Override - public String getOriginalName() { - return lastElement.getOriginalName(); - } - - @Override - public String getName() { - return lastElement.getName(); - } - - @Override - public ElementKind getKind() { - return ElementKind.CLASS; - } - - @Override - public boolean isDynamic() { - return false; - } - - @Override - public Modifiers getModifiers() { - return Modifiers.NONE; - } - - @Override - public DartObsoleteMetadata getMetadata() { - return null; - } - - @Override - public EnclosingElement getEnclosingElement() { - return lastElement.getEnclosingElement(); - } - - @Override - public SourceInfo getNameLocation() { - return lastElement.getNameLocation(); - } - - @Override - public SourceInfo getSourceInfo() { - return lastElement.getSourceInfo(); - } - - @Override - public Iterable getMembers() { - List> typeMembers = Lists.newArrayList(); - for (InterfaceType type : types) { - typeMembers.add(type.getElement().getMembers()); - } - return Iterables.concat(typeMembers); - } - - @Override - public List getConstructors() { - throw new UnsupportedOperationException(); - } - - @Override - public int getOpenBraceOffset() { - return -1; - } - - @Override - public int getCloseBraceOffset() { - return -1; - } - - @Override - public boolean hasSuperInvocation() { - return false; - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/ClassNodeElement.java b/compiler/java/com/google/dart/compiler/resolver/ClassNodeElement.java deleted file mode 100644 index ba10ff6be699..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/ClassNodeElement.java +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. -package com.google.dart.compiler.resolver; - -import com.google.dart.compiler.ast.DartNode; - -import java.util.List; - -/** - * Extension of {@link ClassElement} which is based on {@link DartNode}. - */ -public interface ClassNodeElement extends ClassElement, NodeElement { - Iterable getMembers(); - - List getConstructors(); - - /** - * Sets {@link Element}s which as not implemented in this {@link ClassElement}. - */ - void setUnimplementedMembers(List members); -} diff --git a/compiler/java/com/google/dart/compiler/resolver/ClassScope.java b/compiler/java/com/google/dart/compiler/resolver/ClassScope.java deleted file mode 100644 index e5c393ffdc3e..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/ClassScope.java +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.dart.compiler.type.InterfaceType; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * Lexical scope corresponding to a class body. - */ -class ClassScope extends Scope { - private final ClassElement classElement; - - ClassScope(ClassElement classElement, Scope parent) { - super(classElement.getName(), parent.getLibrary(), parent); - this.classElement = classElement; - } - - @Override - public Element declareElement(String name, Element element) { - throw new AssertionError("not supported yet"); - } - - @Override - public Element findElement(LibraryElement inLibrary, String name) { - return findElement(inLibrary, name, new HashSet()); - } - - protected Element findElement(LibraryElement inLibrary, String name, Set examinedTypes) { - Element element = super.findElement(inLibrary, name); - if (element != null) { - return element; - } - examinedTypes.add(classElement); - InterfaceType superclass = classElement.getSupertype(); - if (superclass != null) { - Element enclosing = superclass.getElement().getEnclosingElement(); - ClassElement superclassElement = superclass.getElement(); - if (!examinedTypes.contains(superclassElement)) { - ClassScope scope = new ClassScope(superclassElement, - new Scope("library", (LibraryElement) enclosing)); - element = scope.findElement(inLibrary, name, examinedTypes); - switch (ElementKind.of(element)) { - case TYPE_VARIABLE: - return null; - case NONE: - break; - default: - return element; - } - } - } - - List interfaces = classElement.getInterfaces(); - for (int i = 0, size = interfaces.size(); i < size; i++) { - InterfaceType intf = interfaces.get(i); - ClassElement intfElement = intf.getElement(); - if (!examinedTypes.contains(intfElement)) { - Element enclosing = intf.getElement().getEnclosingElement(); - ClassScope scope = new ClassScope(intfElement, - new Scope("library", (LibraryElement) enclosing)); - element = scope.findElement(inLibrary, name, examinedTypes); - if (element != null) { - return element; - } - } - } - - List mixins = classElement.getMixins(); - for (int i = 0, size = mixins.size(); i < size; i++) { - InterfaceType mixin = mixins.get(i); - ClassElement mixinElement = mixin.getElement(); - if (!examinedTypes.contains(mixinElement)) { - MixinScope scope = new MixinScope(mixinElement); - element = scope.findElement(inLibrary, name); - if (element != null) { - return element; - } - } - } - return null; - } - - @Override - public Element findLocalElement(String name) { - return Elements.findElement(classElement, name); - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/CompileTimeConstantAnalyzer.java b/compiler/java/com/google/dart/compiler/resolver/CompileTimeConstantAnalyzer.java deleted file mode 100644 index f0dc59914774..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/CompileTimeConstantAnalyzer.java +++ /dev/null @@ -1,822 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import com.google.dart.compiler.DartCompilationError; -import com.google.dart.compiler.DartCompilationPhase; -import com.google.dart.compiler.DartCompilerContext; -import com.google.dart.compiler.ast.ASTVisitor; -import com.google.dart.compiler.ast.DartArrayLiteral; -import com.google.dart.compiler.ast.DartBinaryExpression; -import com.google.dart.compiler.ast.DartBooleanLiteral; -import com.google.dart.compiler.ast.DartCase; -import com.google.dart.compiler.ast.DartClass; -import com.google.dart.compiler.ast.DartConditional; -import com.google.dart.compiler.ast.DartDeclaration; -import com.google.dart.compiler.ast.DartDoubleLiteral; -import com.google.dart.compiler.ast.DartExpression; -import com.google.dart.compiler.ast.DartField; -import com.google.dart.compiler.ast.DartFunction; -import com.google.dart.compiler.ast.DartFunctionObjectInvocation; -import com.google.dart.compiler.ast.DartIdentifier; -import com.google.dart.compiler.ast.DartInitializer; -import com.google.dart.compiler.ast.DartIntegerLiteral; -import com.google.dart.compiler.ast.DartInvocation; -import com.google.dart.compiler.ast.DartMapLiteral; -import com.google.dart.compiler.ast.DartMapLiteralEntry; -import com.google.dart.compiler.ast.DartMethodDefinition; -import com.google.dart.compiler.ast.DartMethodInvocation; -import com.google.dart.compiler.ast.DartNamedExpression; -import com.google.dart.compiler.ast.DartNewExpression; -import com.google.dart.compiler.ast.DartNode; -import com.google.dart.compiler.ast.DartNullLiteral; -import com.google.dart.compiler.ast.DartParameter; -import com.google.dart.compiler.ast.DartParenthesizedExpression; -import com.google.dart.compiler.ast.DartPropertyAccess; -import com.google.dart.compiler.ast.DartRedirectConstructorInvocation; -import com.google.dart.compiler.ast.DartStringInterpolation; -import com.google.dart.compiler.ast.DartStringLiteral; -import com.google.dart.compiler.ast.DartSuperConstructorInvocation; -import com.google.dart.compiler.ast.DartSuperExpression; -import com.google.dart.compiler.ast.DartThisExpression; -import com.google.dart.compiler.ast.DartUnaryExpression; -import com.google.dart.compiler.ast.DartUnit; -import com.google.dart.compiler.ast.DartUnqualifiedInvocation; -import com.google.dart.compiler.ast.DartVariable; -import com.google.dart.compiler.ast.DartVariableStatement; -import com.google.dart.compiler.ast.Modifiers; -import com.google.dart.compiler.common.HasSourceInfo; -import com.google.dart.compiler.type.Type; -import com.google.dart.compiler.type.TypeKind; - -import java.math.BigInteger; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Given an tree, finds all compile-time constant expressions, and determines if - * each expression matches all the rules for a compile-time constant. Emits a - * resolution error if not. - * - * This script doesn't just resolve expressions, it also sets types to the - * extent needed to validate compile-time constant expressions (boolean, int, - * double, and string types might be set) - */ -public class CompileTimeConstantAnalyzer { - - private class ExpressionVisitor extends ASTVisitor { - private boolean checkBoolean(DartNode x, Type type) { - // Spec 0.11 allows using "null" literal in place of bool. - if (x instanceof DartNullLiteral) { - return true; - } - // check actual type - if (!type.equals(boolType)) { - context.onError(new DartCompilationError(x, - ResolverErrorCode.EXPECTED_CONSTANT_EXPRESSION_BOOLEAN, type - .toString())); - return false; - } - return true; - } - - private boolean checkInt(DartNode x, Type type) { - // Spec 0.11 allows using "null" literal in place of num. - if (x instanceof DartNullLiteral) { - return true; - } - // check actual type - if (!type.equals(intType)) { - context - .onError(new DartCompilationError(x, - ResolverErrorCode.EXPECTED_CONSTANT_EXPRESSION_INT, type - .toString())); - return false; - } - return true; - } - - private boolean checkString(DartNode x, Type type) { - if (!type.equals(stringType)) { - context - .onError(new DartCompilationError(x, - ResolverErrorCode.EXPECTED_CONSTANT_EXPRESSION_STRING, type - .toString())); - return false; - } - return true; - } - - private boolean checkNumber(DartNode x, Type type) { - // for "const" constructor we check "potentially constant expression", - // so suppose that parameters have correct type - if (TypeKind.of(type) == TypeKind.DYNAMIC && x.getElement() != null - && x.getElement().getEnclosingElement() instanceof MethodElement) { - return true; - } - // Spec 0.11 allows using "null" literal in place of num. - if (x instanceof DartNullLiteral) { - return true; - } - // check actual type - if (!(type.equals(numType) || type.equals(intType) || type - .equals(doubleType))) { - context.onError(new DartCompilationError(x, - ResolverErrorCode.EXPECTED_CONSTANT_EXPRESSION_NUMBER, type - .toString())); - - return false; - } - return true; - } - - private boolean checkNumberBooleanOrStringType(DartNode x, Type type) { - if (type.equals(intType) || type.equals(boolType) - || type.equals(numType) || type.equals(doubleType) - || type.equals(stringType) || (x instanceof DartNullLiteral)) { - return true; - } else if (x instanceof DartStringInterpolation) { - DartStringInterpolation interpolation = (DartStringInterpolation) x; - for (DartExpression expression : interpolation.getExpressions()) { - Type expressionType = getMostSpecificType(expression); - if (!checkNumberBooleanOrStringType(expression, expressionType)) { - return false; - } - } - return true; - } - context.onError(new DartCompilationError(x, - ResolverErrorCode.EXPECTED_CONSTANT_EXPRESSION_STRING_NUMBER_BOOL, - type.toString())); - return false; - } - - /** - * Logs a general message "expected a constant expression" error. Use a more - * specific error message when possible. - */ - private void expectedConstant(HasSourceInfo x) { - context.onError(new DartCompilationError(x, ResolverErrorCode.EXPECTED_CONSTANT_EXPRESSION)); - } - - /** - * Determine the most specific type assigned to an expression node. Prefer - * the setting in the expression's element if present. Otherwise, use a type - * tagged in the expression node itself. - * - * @return a non null type value. Dynamic if none other can be - * determined. - */ - private Type getMostSpecificType(DartNode node) { - if (node != null) { - Type type = inferredTypes.get(node); - if (type != null) { - return type; - } - Element element = node.getElement(); - if (Elements.isFunctionIdentical(element)) { - return boolType; - } - if (element != null) { - type = element.getType(); - if (type != null && TypeKind.of(type) != TypeKind.DYNAMIC) { - return type; - } - if (element instanceof VariableElement) { - VariableElement variable = (VariableElement) element; - if (variable.getModifiers().isConstant()) { - DartExpression value = variable.getDefaultValue(); - if (value != null) { - type = getMostSpecificType(value); - } - } - } else if (element instanceof FieldElement) { - FieldElement field = (FieldElement) element; - if (field.getModifiers().isConstant()) { - type = field.getConstantType(); - } - } - if (type != null) { - return type; - } - } - } - return dynamicType; - } - - private void rememberInferredType(DartNode x, Type type) { - if (type != null && ! type.equals(dynamicType)) { - inferredTypes.put(x, type); - } - } - - @Override - public Void visitArrayLiteral(DartArrayLiteral x) { - if (!x.isConst()) { - expectedConstant(x); - } else { - for (DartExpression expr : x.getExpressions()) { - expr.accept(this); - } - } - return null; - } - - @Override - public Void visitBinaryExpression(DartBinaryExpression x) { - x.visitChildren(this); - - DartExpression lhs = x.getArg1(); - DartExpression rhs = x.getArg2(); - Type lhsType = getMostSpecificType(lhs); - Type rhsType = getMostSpecificType(rhs); - - switch (x.getOperator()) { - case NE: - case EQ: - case NE_STRICT: - case EQ_STRICT: - if (checkNumberBooleanOrStringType(lhs, lhsType) - && checkNumberBooleanOrStringType(rhs, rhsType)) { - rememberInferredType(x, boolType); - } - break; - - case AND: - case OR: - if (checkBoolean(lhs, lhsType) && checkBoolean(rhs, rhsType)) { - rememberInferredType(x, boolType); - } - break; - - case BIT_XOR: - case BIT_AND: - case BIT_OR: - case SAR: - case SHL: - if (checkInt(lhs, lhsType) && checkInt(rhs, rhsType)) { - rememberInferredType(x, intType); - } - break; - - case ADD: - if (lhsType.equals(stringType)) { - // TODO(zundel): remove this when + no longer acceptable as string concat operator - if (checkString(rhs, rhsType)) { - rememberInferredType(x, stringType); - } - } else { - checkMathExpression(x, lhs, rhs, lhsType, rhsType); - } - break; - case SUB: - case MUL: - case DIV: - checkMathExpression(x, lhs, rhs, lhsType, rhsType); - break; - case TRUNC: - case MOD: - reportExceptionIfZeroLiteral(x, rhs); - if (checkNumber(lhs, lhsType) && checkNumber(rhs, rhsType)) { - rememberInferredType(x, intType); - } - break; - case LT: - case GT: - case LTE: - case GTE: - if (checkNumber(lhs, lhsType) && checkNumber(rhs, rhsType)) { - rememberInferredType(x, boolType); - } - break; - - default: - // all other operators... - expectedConstant(x); - } - return null; - } - - private void reportExceptionIfZeroLiteral(HasSourceInfo target, DartExpression e) { - if (e instanceof DartIntegerLiteral) { - DartIntegerLiteral literal = (DartIntegerLiteral) e; - if (literal.getValue().equals(BigInteger.ZERO)) { - context.onError(new DartCompilationError(target, - ResolverErrorCode.CONSTANTS_EVALUATION_EXCEPTION)); - } - } - } - - private void checkMathExpression(DartBinaryExpression x, - DartExpression lhs, DartExpression rhs, - Type lhsType, Type rhsType) { - if (checkNumber(lhs, lhsType) && checkNumber(rhs, rhsType)) { - if (lhsType.equals(intType) && rhsType.equals(intType)) { - rememberInferredType(x, intType); - } else if (lhsType.equals(doubleType) && rhsType.equals(doubleType)) { - rememberInferredType(x, doubleType); - } else if (lhsType.equals(doubleType) && rhsType.equals(intType) - || lhsType.equals(intType) && rhsType.equals(doubleType)) { - rememberInferredType(x, doubleType); - } else { - rememberInferredType(x, numType); - } - } - } - - @Override - public Void visitBooleanLiteral(DartBooleanLiteral x) { - rememberInferredType(x, boolType); - return null; - } - - @Override - public Void visitDoubleLiteral(DartDoubleLiteral x) { - rememberInferredType(x, doubleType); - return null; - } - - @Override - public Void visitConditional(DartConditional node) { - expectedConstant(node); - return null; - } - - @Override - public Void visitField(DartField x) { - x.visitChildren(this); - if (x.getType() == null || x.getType().equals(dynamicType)) { - Type type = getMostSpecificType(x.getValue()); - rememberInferredType(x, type); - } - return null; - } - - @Override - public Void visitFunction(DartFunction x) { - // No need to traverse, functions are always disallowed. - expectedConstant(x); - return null; - } - - @Override - public Void visitFunctionObjectInvocation(DartFunctionObjectInvocation x) { - // No need to traverse, function object invocations are always disallowed. - expectedConstant(x); - return null; - } - - @Override - public Void visitNamedExpression(DartNamedExpression node) { - return node.getExpression().accept(this); - } - - @Override - public Void visitIdentifier(DartIdentifier x) { - x.visitChildren(this); - - if (x.getParent() instanceof DartDeclaration - && ((DartDeclaration) x.getParent()).getName() == x) { - return null; - } - - Element element = x.getElement(); - boolean elementIsStatic = element != null - && (element.getModifiers().isStatic() || Elements.isTopLevel(element)); - switch (ElementKind.of(element)) { - case CLASS: - case PARAMETER: - case LIBRARY_PREFIX: - break; - - case FIELD: - FieldElement fieldElement = (FieldElement) element; - - // Check for circular references. - if (element != null && visitedElements.contains(element)) { - context.onError(new DartCompilationError(x, ResolverErrorCode.CIRCULAR_REFERENCE)); - rememberInferredType(x, getMostSpecificType(x)); - return null; - } - visitedElements.add(element); - - // Should be declared as constant. - if (!element.getModifiers().isConstant()) { - expectedConstant(x); - } - - // Infer type by visiting node or cached from Element. - final Type inferredType; - if (element instanceof FieldNodeElement) { - FieldNodeElement fieldNodeElement = (FieldNodeElement) element; - DartNode fieldNode = fieldNodeElement.getNode(); - fieldNode.accept(this); - inferredType = getMostSpecificType(fieldNode); - fieldNodeElement.setConstantType(inferredType); - } else if (fieldElement.getType() != null - && !fieldElement.getType().equals(dynamicType)) { - inferredType = fieldElement.getType(); - } else { - inferredType = fieldElement.getConstantType(); - } - - // Done with this element. - visitedElements.remove(element); - - rememberInferredType(x, inferredType); - break; - - case VARIABLE: - if (!element.getModifiers().isConstant()) { - expectedConstant(x); - } - return null; - - case METHOD: - if (!elementIsStatic) { - expectedConstant(x); - } - return null; - - case NONE: - default: - expectedConstant(x); - return null; - } - return null; - } - - - @Override - public Void visitIntegerLiteral(DartIntegerLiteral x) { - rememberInferredType(x, intType); - return null; - } - - @Override - public Void visitInvocation(DartInvocation x) { - // No need to traverse, invocations are always disallowed. - expectedConstant(x); - return null; - } - - @Override - public Void visitMapLiteral(DartMapLiteral x) { - if (!x.isConst()) { - expectedConstant(x); - } else { - for (DartMapLiteralEntry entry : x.getEntries()) { - entry.accept(this); - } - } - return null; - } - - @Override - public Void visitMethodInvocation(DartMethodInvocation x) { - // No need to traverse, method invocations are always disallowed. - expectedConstant(x); - return null; - } - - @Override - public Void visitNewExpression(DartNewExpression x) { - if (!x.isConst()) { - expectedConstant(x); - } else { - for (DartExpression arg : x.getArguments()) { - arg.accept(this); - } - } - rememberInferredType(x, x.getConstructor().getType()); - return null; - } - - @Override - public Void visitParenthesizedExpression(DartParenthesizedExpression x) { - x.visitChildren(this); - Type type = getMostSpecificType(x.getExpression()); - rememberInferredType(x, type); - return null; - } - - @Override - public Void visitPropertyAccess(DartPropertyAccess x) { - switch (ElementKind.of(x.getRealTarget().getElement())) { - case CLASS: - case LIBRARY_PREFIX: - case LIBRARY: - case NONE: - // OK. - break; - default: - expectedConstant(x); - return null; - } - - Type type = getMostSpecificType(x.getName()); - rememberInferredType(x, type); - - Element element = x.getName().getElement(); - if (element != null) { - // OK. Static method reference. - if (ElementKind.of(element) == ElementKind.METHOD && element.getModifiers().isStatic()) { - return null; - } - // OK. Constant field. - if (element.getModifiers().isConstant()) { - return null; - } - // Fail. - expectedConstant(x); - } - return null; - } - - @Override - public Void visitRedirectConstructorInvocation(DartRedirectConstructorInvocation x) { - Element element = x.getElement(); - if (element != null) { - if (!element.getModifiers().isConstant()) { - expectedConstant(x); - } - } - x.visitChildren(this); - return null; - } - - @Override - public Void visitStringInterpolation(DartStringInterpolation x) { - x.visitChildren(this); - for (DartExpression expression : x.getExpressions()) { - Type expressionType = getMostSpecificType(expression); - checkNumberBooleanOrStringType(expression, expressionType); - } - return null; - } - - @Override - public Void visitStringLiteral(DartStringLiteral x) { - rememberInferredType(x, stringType); - return null; - } - - @Override - public Void visitSuperExpression(DartSuperExpression x) { - if (!x.getElement().getModifiers().isConstant()) { - expectedConstant(x); - } - return null; - } - - @Override - public Void visitThisExpression(DartThisExpression x) { - // No need to traverse, this expressions are never constant - expectedConstant(x); - return null; - } - - @Override - public Void visitUnaryExpression(DartUnaryExpression x) { - x.visitChildren(this); - - Type type = getMostSpecificType(x.getArg()); - switch (x.getOperator()) { - case NOT: - if (checkBoolean(x.getArg(), type)) { - rememberInferredType(x, boolType); - } - break; - case SUB: - if (intType.equals(type)) { - rememberInferredType(x, intType); - } else if (checkNumber(x.getArg(), type)) { - rememberInferredType(x, numType); - } - break; - case BIT_NOT: - if (checkInt(x.getArg(), type)) { - rememberInferredType(x, intType); - } - break; - default: - expectedConstant(x); - } - return null; - } - - @Override - public Void visitSuperConstructorInvocation(DartSuperConstructorInvocation x) { - x.visitChildren(this); - return null; - } - - @Override - public Void visitUnqualifiedInvocation(DartUnqualifiedInvocation x) { - Element element = x.getElement(); - // "identical" - if (Elements.isFunctionIdentical(element)) { - x.visitChildren(this); - return null; - } - // No need to traverse, always disallowed. - expectedConstant(x); - return null; - } - } - - private class FindCompileTimeConstantExpressionsVisitor extends ASTVisitor { - private ClassElement currentClass; - private boolean inConstConstructor; - - @Override - public Void visitArrayLiteral(DartArrayLiteral node) { - if (node.isConst()) { - for (DartExpression expr : node.getExpressions()) { - checkConstantExpression(expr); - } - return null; - } - return super.visitArrayLiteral(node); - } - - @Override - public Void visitField(DartField node) { - if (node.getParent() != null) { - if (node.getModifiers().isConstant()) { - Type type = checkConstantExpression(node.getValue()); - if (node.getElement().getType().equals(dynamicType)) { - node.getElement().setConstantType(type); - } - return null; - } - } - return super.visitField(node); - } - - @Override - public Void visitClass(DartClass node) { - ClassElement oldClassElement = currentClass; - currentClass = node.getElement(); - try { - return super.visitClass(node); - } finally { - currentClass = oldClassElement; - } - } - - @Override - public Void visitMethodDefinition(DartMethodDefinition node) { - inConstConstructor = node.getModifiers().isConstant(); - return super.visitMethodDefinition(node); - } - - @Override - public Void visitInitializer(DartInitializer node) { - if (inConstConstructor) { - String name = node.getInitializerName(); - if (name != null) { - Element member = currentClass.lookupLocalElement(name); - if (member instanceof FieldElement) { - if (member.getModifiers().isFinal()) { - checkConstantExpression(node.getValue()); - } - } - } else { - DartExpression value = node.getValue(); - if (value instanceof DartSuperConstructorInvocation - || value instanceof DartRedirectConstructorInvocation) { - List arguments = ((DartInvocation) value).getArguments(); - for (DartExpression argument : arguments) { - checkConstantExpression(argument); - } - } - } - } - return super.visitInitializer(node); - } - - @Override - public Void visitCase(DartCase node) { - checkConstantExpression(node.getExpr()); - return super.visitCase(node); - } - - @Override - public Void visitMapLiteral(DartMapLiteral node) { - if (node.isConst()) { - for (DartMapLiteralEntry entry : node.getEntries()) { - checkConstantExpression(entry.getKey()); - checkConstantExpression(entry.getValue()); - } - return null; - } - return super.visitMapLiteral(node); - } - - @Override - public Void visitNewExpression(DartNewExpression node) { - if (node.isConst()) { - for (DartExpression arg : node.getArguments()) { - checkConstantExpression(arg); - } - return null; - } - return super.visitNewExpression(node); - } - - @Override - public Void visitParameter(DartParameter node) { - checkConstantExpression(node.getDefaultExpr()); - List parameters = node.getFunctionParameters(); - if (parameters != null) { - for (DartParameter parameter : parameters) { - visitParameter(parameter); - } - } - return null; - } - - @Override - public Void visitVariableStatement(DartVariableStatement node) { - Modifiers modifiers = node.getModifiers(); - if (modifiers.isConstant()) { - for (DartVariable variable : node.getVariables()) { - if (variable.getValue() != null) { - checkConstantExpression(variable.getValue()); - } - } - return null; - } - return super.visitVariableStatement(node); - } - - @Override - public Void visitRedirectConstructorInvocation(DartRedirectConstructorInvocation node) { - // Don't evaluate now, wait until it is referenced and evaluate as part of the expression - return null; - } - - @Override - public Void visitSuperConstructorInvocation(DartSuperConstructorInvocation node) { - // Don't evaluate now, wait until it is referenced and evaluate as part of the expression - return null; - } - } - - public static class Phase implements DartCompilationPhase { - /** - * Executes element resolution on the given compilation unit. - * - * @param context The listener through which compilation errors are reported - * (not null) - */ - @Override - public DartUnit exec(DartUnit unit, DartCompilerContext context, - CoreTypeProvider typeProvider) { - new CompileTimeConstantAnalyzer(typeProvider, context).exec(unit); - return unit; - } - } - - public Set visitedElements = Sets.newHashSet(); - - public Map inferredTypes = Maps.newHashMap(); - - private final DartCompilerContext context; - private final Type boolType; - private final Type doubleType; - private final Type intType; - private final Type numType; - private final Type stringType; - private final Type dynamicType; - - public CompileTimeConstantAnalyzer(CoreTypeProvider typeProvider, - DartCompilerContext context) { - this.context = context; - this.boolType = typeProvider.getBoolType(); - this.doubleType = typeProvider.getDoubleType(); - this.intType = typeProvider.getIntType(); - this.numType = typeProvider.getNumType(); - this.stringType = typeProvider.getStringType(); - this.dynamicType = typeProvider.getDynamicType(); - } - - private Type checkConstantExpression(DartExpression expression) { - if (expression != null) { - ExpressionVisitor visitor = new ExpressionVisitor(); - expression.accept(visitor); - return visitor.getMostSpecificType(expression); - } - return null; - } - - public void exec(DartUnit unit) { - unit.accept(new FindCompileTimeConstantExpressionsVisitor()); - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/ConstructorElement.java b/compiler/java/com/google/dart/compiler/resolver/ConstructorElement.java deleted file mode 100644 index 7db795dd3d78..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/ConstructorElement.java +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. -package com.google.dart.compiler.resolver; - -public interface ConstructorElement extends MethodElement { - /** - * Returns the type of the instances created by this constructor. Note that a constructor in a - * class may be a default implementation of an interface's constructor. - */ - ClassElement getConstructorType(); - - /** - * @return the {@link ConstructorElement} in default factory class, may be null. - */ - ConstructorElement getDefaultConstructor(); - - boolean isSynthetic(); - - String getRawName(); - - /** - * Sets {@link ConstructorElement} in default factory class, may be null. - */ - void setDefaultConstructor(ConstructorElement defaultConstructor); - - ConstructorElement getRedirectingFactoryConstructor(); -} diff --git a/compiler/java/com/google/dart/compiler/resolver/ConstructorElementImplementation.java b/compiler/java/com/google/dart/compiler/resolver/ConstructorElementImplementation.java deleted file mode 100644 index 227daaee45ff..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/ConstructorElementImplementation.java +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.dart.compiler.ast.DartIdentifier; -import com.google.dart.compiler.ast.DartMethodDefinition; -import com.google.dart.compiler.ast.DartNode; -import com.google.dart.compiler.ast.DartParameterizedTypeNode; -import com.google.dart.compiler.ast.DartPropertyAccess; - -class ConstructorElementImplementation extends MethodElementImplementation - implements ConstructorNodeElement { - private final ClassElement constructorType; - private final String rawName; - private ConstructorElement defaultConstructor; - private ConstructorElement redirectingFactoryConstructor; - - private ConstructorElementImplementation(DartMethodDefinition node, - String name, - ClassElement declaringClass, - ClassElement constructorType) { - super(node, name, declaringClass); - this.constructorType = constructorType; - this.rawName = getRawName(node.getName()); - } - - private static String getRawName(DartNode name) { - if (name instanceof DartIdentifier) { - return ((DartIdentifier) name).getName(); - } else if (name instanceof DartParameterizedTypeNode) { - return getRawName(((DartParameterizedTypeNode) name).getExpression()); - } else { - DartPropertyAccess propertyAccess = (DartPropertyAccess) name; - DartNode qualifier = propertyAccess.getQualifier(); - if (ElementKind.of(qualifier.getElement()) == ElementKind.CLASS) { - return getRawName(qualifier) + "." + getRawName(propertyAccess.getName()); - } else { - return getRawName(propertyAccess.getName()); - } - } - } - - public ClassElement getConstructorType() { - return constructorType; - } - - @Override - public String getRawName() { - return rawName; - } - - @Override - public ElementKind getKind() { - return ElementKind.CONSTRUCTOR; - } - - @Override - public boolean isConstructor() { - return true; - } - - @Override - public boolean isSynthetic() { - return false; - } - - @Override - public ConstructorElement getDefaultConstructor() { - return defaultConstructor; - } - - @Override - public void setDefaultConstructor(ConstructorElement defaultConstructor) { - this.defaultConstructor = defaultConstructor; - } - - @Override - public ConstructorElement getRedirectingFactoryConstructor() { - return redirectingFactoryConstructor; - } - - public void setRedirectingFactoryConstructor(ConstructorElement redirectingFactoryConstructor) { - this.redirectingFactoryConstructor = redirectingFactoryConstructor; - } - - public static ConstructorElementImplementation fromMethodNode(DartMethodDefinition node, - String name, - ClassElement declaringClass, - ClassElement constructorType) { - return new ConstructorElementImplementation(node, name, declaringClass, constructorType); - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/ConstructorNodeElement.java b/compiler/java/com/google/dart/compiler/resolver/ConstructorNodeElement.java deleted file mode 100644 index 35b5c2fc0de7..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/ConstructorNodeElement.java +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. -package com.google.dart.compiler.resolver; - -import com.google.dart.compiler.ast.DartNode; - -/** - * Extension of {@link ConstructorElement} which is based on {@link DartNode}. - */ -public interface ConstructorNodeElement extends ConstructorElement, MethodNodeElement { -} diff --git a/compiler/java/com/google/dart/compiler/resolver/CoreTypeProvider.java b/compiler/java/com/google/dart/compiler/resolver/CoreTypeProvider.java deleted file mode 100644 index 5d319a60c4c4..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/CoreTypeProvider.java +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.dart.compiler.type.DynamicType; -import com.google.dart.compiler.type.InterfaceType; -import com.google.dart.compiler.type.Type; - -public interface CoreTypeProvider { - - InterfaceType getIntType(); - - InterfaceType getDoubleType(); - - InterfaceType getBoolType(); - - InterfaceType getStringType(); - - InterfaceType getFunctionType(); - - Type getNullType(); - - Type getVoidType(); - - DynamicType getDynamicType(); - - InterfaceType getArrayType(Type elementType); - - InterfaceType getIteratorType(Type elementType); - - InterfaceType getMapType(Type key, Type value); - - InterfaceType getObjectType(); - - InterfaceType getNumType(); - - InterfaceType getTypeType(); -} diff --git a/compiler/java/com/google/dart/compiler/resolver/CoreTypeProviderImplementation.java b/compiler/java/com/google/dart/compiler/resolver/CoreTypeProviderImplementation.java deleted file mode 100644 index 337eb3a25092..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/CoreTypeProviderImplementation.java +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.dart.compiler.DartCompilationError; -import com.google.dart.compiler.DartCompilerListener; -import com.google.dart.compiler.parser.DartScanner.Location; -import com.google.dart.compiler.type.DynamicType; -import com.google.dart.compiler.type.InterfaceType; -import com.google.dart.compiler.type.Type; -import com.google.dart.compiler.type.Types; - -import java.util.Arrays; - -public class CoreTypeProviderImplementation implements CoreTypeProvider { - private final InterfaceType intType; - private final InterfaceType doubleType; - private final InterfaceType numType; - private final InterfaceType boolType; - private final InterfaceType stringType; - private final InterfaceType functionType; - private final InterfaceType arrayType; - private final DynamicType dynamicType; - private final Type voidType; - private final Type nullType; - private final InterfaceType mapType; - private final InterfaceType objectType; - private final InterfaceType iteratorType; - private final InterfaceType typeType; - - public CoreTypeProviderImplementation(Scope scope, DartCompilerListener listener) { - this.intType = getType("int", scope, listener); - this.doubleType = getType("double", scope, listener); - this.boolType = getType("bool", scope, listener); - this.numType = getType("num", scope, listener); - this.stringType = getType("String", scope, listener); - this.functionType = getType("Function", scope, listener); - this.arrayType = getType("List", scope, listener); - this.dynamicType = Types.newDynamicType(); - this.voidType = Types.newVoidType(); - // Currently, there is no need for a special null type. - this.nullType = dynamicType; - this.mapType = getType("Map", scope, listener); - this.objectType = getType("Object", scope, listener); - this.iteratorType = getType("Iterator", scope, listener); - this.typeType = getType("Type", scope, listener); - } - - private static InterfaceType getType(String name, Scope scope, DartCompilerListener listener) { - ClassElement element = (ClassElement) scope.findElement(scope.getLibrary(), name); - if (element == null) { - DartCompilationError error = - new DartCompilationError(null, Location.NONE, - ResolverErrorCode.CANNOT_RESOLVE_SDK_TYPE, name); - listener.onError(error); - return Types.newDynamicType(); - } - return element.getType(); - } - - @Override - public InterfaceType getIntType() { - return intType; - } - - @Override - public InterfaceType getDoubleType() { - return doubleType; - } - - @Override - public InterfaceType getBoolType() { - return boolType; - } - - @Override - public InterfaceType getStringType() { - return stringType; - } - - @Override - public InterfaceType getFunctionType() { - return functionType; - } - - @Override - public InterfaceType getArrayType(Type elementType) { - return arrayType.subst(Arrays.asList(elementType), arrayType.getElement().getTypeParameters()); - } - - @Override - public DynamicType getDynamicType() { - return dynamicType; - } - - @Override - public Type getVoidType() { - return voidType; - } - - @Override - public Type getNullType() { - return nullType; - } - - @Override - public InterfaceType getMapType(Type key, Type value) { - return mapType.subst(Arrays.asList(key, value), mapType.getElement().getTypeParameters()); - } - - @Override - public InterfaceType getObjectType() { - return objectType; - } - - @Override - public InterfaceType getNumType() { - return numType; - } - - @Override - public InterfaceType getIteratorType(Type elementType) { - return iteratorType.subst(Arrays.asList(elementType), - iteratorType.getElement().getTypeParameters()); - } - - @Override - public InterfaceType getTypeType() { - return typeType; - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/CyclicDeclarationException.java b/compiler/java/com/google/dart/compiler/resolver/CyclicDeclarationException.java deleted file mode 100644 index 90e673a3cb4f..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/CyclicDeclarationException.java +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -/** - * Exception thrown if a cycle is detected in the supertype graph of a class or interface. - */ -public class CyclicDeclarationException extends Exception { - private static final long serialVersionUID = 1L; - - private final ClassElement element; - - public CyclicDeclarationException(ClassElement element) { - super(element.getName()); - this.element = element; - } - - public ClassElement getElement() { - return element; - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/DuplicateElement.java b/compiler/java/com/google/dart/compiler/resolver/DuplicateElement.java deleted file mode 100644 index ed526db9af21..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/DuplicateElement.java +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import java.util.List; - -/** - * {@link Element} for duplicate import. - */ -public interface DuplicateElement extends Element { - List getLocations(); -} diff --git a/compiler/java/com/google/dart/compiler/resolver/DuplicateElementImplementation.java b/compiler/java/com/google/dart/compiler/resolver/DuplicateElementImplementation.java deleted file mode 100644 index 3faaff36b5b3..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/DuplicateElementImplementation.java +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.dart.compiler.ast.DartObsoleteMetadata; -import com.google.dart.compiler.ast.Modifiers; -import com.google.dart.compiler.common.SourceInfo; -import com.google.dart.compiler.type.Type; - -import java.util.List; - -class DuplicateElementImplementation implements DuplicateElement { - private final String name; - private final List locations = Lists.newArrayList(); - - public DuplicateElementImplementation(Element oldElement, Element newElement) { - name = oldElement.getName(); - locations.addAll(getLocations(oldElement)); - locations.addAll(getLocations(newElement)); - } - - @Override - public String getOriginalName() { - return name; - } - - @Override - public String getName() { - return name; - } - - @Override - public ElementKind getKind() { - return ElementKind.DUPLICATE; - } - - @Override - public Type getType() { - return null; - } - - @Override - public boolean isDynamic() { - return false; - } - - @Override - public Modifiers getModifiers() { - return Modifiers.NONE; - } - - @Override - public DartObsoleteMetadata getMetadata() { - return null; - } - - @Override - public EnclosingElement getEnclosingElement() { - return null; - } - - @Override - public SourceInfo getNameLocation() { - return null; - } - - @Override - public SourceInfo getSourceInfo() { - return null; - } - - @Override - public List getLocations() { - return locations; - } - - private static List getLocations(Element element) { - if (element instanceof DuplicateElement) { - return ((DuplicateElement) element).getLocations(); - } else { - return ImmutableList.of(Elements.getLibraryUnitLocation(element)); - } - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/DynamicElement.java b/compiler/java/com/google/dart/compiler/resolver/DynamicElement.java deleted file mode 100644 index b971ce293125..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/DynamicElement.java +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.dart.compiler.type.DynamicType; - -/** - * Dummy element corresponding to {@link DynamicType}. - */ -public interface DynamicElement extends FunctionAliasElement, LibraryElement, FieldElement, - LabelElement, SuperElement, VariableElement, - TypeVariableElement, ConstructorElement { - @Override - DynamicType getType(); -} diff --git a/compiler/java/com/google/dart/compiler/resolver/DynamicElementImplementation.java b/compiler/java/com/google/dart/compiler/resolver/DynamicElementImplementation.java deleted file mode 100644 index 3950e8580a1e..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/DynamicElementImplementation.java +++ /dev/null @@ -1,330 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.common.collect.ImmutableSet; -import com.google.dart.compiler.ast.DartExpression; -import com.google.dart.compiler.ast.LibraryUnit; -import com.google.dart.compiler.type.DynamicType; -import com.google.dart.compiler.type.FunctionType; -import com.google.dart.compiler.type.InterfaceType; -import com.google.dart.compiler.type.Type; -import com.google.dart.compiler.type.Types; - -import java.util.Collections; -import java.util.List; -import java.util.Set; - -/** - * Dummy element corresponding to {@link DynamicType}. - */ -class DynamicElementImplementation extends AbstractNodeElement implements DynamicElement, MethodNodeElement { - - private DynamicElementImplementation() { - super(null, "dynamic"); - } - - @Override - public ElementKind getKind() { - return ElementKind.DYNAMIC; - } - - public static DynamicElementImplementation getInstance() { - return new DynamicElementImplementation(); - } - - @Override - public void setType(InterfaceType type) { - throw new UnsupportedOperationException(); - } - - @Override - public List getTypeParameters() { - return Collections.emptyList(); - } - - @Override - public InterfaceType getSupertype() { - return null; - } - - @Override - public InterfaceType getDefaultClass() { - return null; - } - - @Override - public void setSupertype(InterfaceType element) { - throw new UnsupportedOperationException(); - } - - @Override - public List getMembers() { - return Collections.emptyList(); - } - - @Override - public List getConstructors() { - return Collections.emptyList(); - } - - @Override - public Scope getImportScope() { - return null; - } - - @Override - public List getInterfaces() { - return Collections.emptyList(); - } - - @Override - public List getMixins() { - return Collections.emptyList(); - } - - @Override - public DynamicType getType() { - return Types.newDynamicType(); - } - - @Override - public DynamicType getTypeVariable() { - return getType(); - } - - @Override - public ClassElement getEnclosingElement() { - return this; - } - - @Override - public boolean isConstructor() { - return false; - } - - @Override - public boolean isSynthetic() { - return true; - } - - @Override - public ConstructorElement getDefaultConstructor() { - throw new UnsupportedOperationException(); - } - - @Override - public ConstructorElement getRedirectingFactoryConstructor() { - throw new UnsupportedOperationException(); - } - - @Override - public void setDefaultConstructor(ConstructorElement defaultConstructor) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isStatic() { - return false; - } - - @Override - public boolean hasBody() { - return false; - } - - @Override - public boolean isInterface() { - return false; - } - - @Override - public String getNativeName() { - return null; - } - - @Override - public List getParameters() { - return Collections.emptyList(); - } - - @Override - public Type getReturnType() { - return getType(); - } - - @Override - public boolean isDynamic() { - return true; - } - - @Override - public boolean isObject() { - return false; - } - - @Override - public String getDeclarationNameWithTypeParameters() { - return "dynamic"; - } - - @Override - public boolean isObjectChild() { - return false; - } - - @Override - public Element lookupLocalElement(String name) { - return this; - } - - @Override - public LibraryElement getLibrary() { - return null; - } - - @Override - public Type getBound() { - return getType(); - } - - @Override - public Element getDeclaringElement() { - return this; - } - - @Override - public ConstructorElement lookupConstructor(String name) { - return null; - } - - @Override - public FunctionType getFunctionType() { - return null; - } - - @Override - public void setFunctionType(FunctionType functionType) { - } - - @Override - public List getAllSupertypes() { - return Collections.emptyList(); - } - - @Override - public Scope getScope() { - return null; - } - - @Override - public List getExportedElements() { - return null; - } - - @Override - public LibraryUnit getLibraryUnit() { - return null; - } - - @Override - public void setEntryPoint(MethodElement element) { - throw new AssertionError(); - } - - @Override - public MethodElement getEntryPoint() { - return null; - } - - @Override - public MethodElement getGetter() { - return null; - } - - @Override - public MethodElement getSetter() { - return null; - } - - @Override - public MethodElement getEnclosingFunction() { - return this; - } - - @Override - public ClassElement getClassElement() { - return this; - } - - @Override - public FieldElement getParameterInitializerElement() { - return this; - } - - @Override - public boolean isOptional() { - return false; - } - - @Override - public boolean isNamed() { - return false; - } - - @Override - public DartExpression getDefaultValue() { - return null; - } - - @Override - public ClassElement getConstructorType() { - return this; - } - - @Override - public String getRawName() { - return getName(); - } - - @Override - public void setType(Type type) { - super.setType(type); - } - - @Override - public Type getConstantType() { - return null; - } - @Override - public List getUnimplementedMembers() { - return null; - } - - @Override - public Set getOverridden() { - return ImmutableSet.of(); - } - - @Override - public LabeledStatementType getStatementType() { - return LabeledStatementType.STATEMENT; - } - - @Override - public int getOpenBraceOffset() { - return -1; - } - - @Override - public int getCloseBraceOffset() { - return -1; - } - - @Override - public boolean hasSuperInvocation() { - return false; - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/Element.java b/compiler/java/com/google/dart/compiler/resolver/Element.java deleted file mode 100644 index 5dd5fb6b214c..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/Element.java +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.dart.compiler.ast.DartObsoleteMetadata; -import com.google.dart.compiler.ast.Modifiers; -import com.google.dart.compiler.common.HasSourceInfo; -import com.google.dart.compiler.common.SourceInfo; -import com.google.dart.compiler.type.Type; - -public interface Element extends HasSourceInfo { - String getOriginalName(); - - String getName(); - - ElementKind getKind(); - - Type getType(); - - boolean isDynamic(); - - Modifiers getModifiers(); - - DartObsoleteMetadata getMetadata(); - - /** - * @return the innermost {@link EnclosingElement} which encloses this {@link Element}. - */ - EnclosingElement getEnclosingElement(); - - /** - * @return location of the name in the declaration of this {@link Element}. - */ - SourceInfo getNameLocation(); -} diff --git a/compiler/java/com/google/dart/compiler/resolver/ElementKind.java b/compiler/java/com/google/dart/compiler/resolver/ElementKind.java deleted file mode 100644 index 65d1cfd5ddfc..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/ElementKind.java +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - - -/** - * Kinds of elements. Use kinds instead of instanceof for maximum flexibility - * and sharing of similar implementation classes. - */ -public enum ElementKind { - CLASS, - CONSTRUCTOR, - DUPLICATE, - FIELD, - FUNCTION_OBJECT, - LABEL, - METHOD, - PARAMETER, - TYPE_VARIABLE, - VARIABLE, - FUNCTION_TYPE_ALIAS, - DYNAMIC, - LIBRARY, - LIBRARY_PREFIX, - SUPER, - NONE, - VOID; - - public static ElementKind of(Element element) { - if (element != null) { - return element.getKind(); - } else { - return NONE; - } - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/ElementMap.java b/compiler/java/com/google/dart/compiler/resolver/ElementMap.java deleted file mode 100644 index 5a186a6e43e1..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/ElementMap.java +++ /dev/null @@ -1,268 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.common.annotations.VisibleForTesting; -import com.google.dart.compiler.ast.DartNode; -import com.google.dart.compiler.ast.DartObsoleteMetadata; -import com.google.dart.compiler.ast.Modifiers; -import com.google.dart.compiler.common.SourceInfo; -import com.google.dart.compiler.type.Type; - -import java.util.ArrayList; -import java.util.List; - -/** - * A more efficient version of {@link com.google.common.collect.Multimap} specifically for - * {@link NodeElement} - */ -@VisibleForTesting -public class ElementMap { - - /** - * A synthetic place holder for an element where the name given to the element map does not match - * the value returned by {@link NodeElement#getName()} or where there are multiple elements associated - * with the same name. - */ - static class ElementHolder implements NodeElement { - private static final String INTERNAL_ONLY_ERROR = - "ElementHolder should not be accessed outside this class"; - - final String name; - final NodeElement element; - ElementHolder nextHolder; - - ElementHolder(String name, NodeElement element) { - this.name = name; - this.element = element; - } - - @Override - public SourceInfo getNameLocation() { - throw new AssertionError(INTERNAL_ONLY_ERROR); - } - - @Override - public EnclosingElement getEnclosingElement() { - throw new AssertionError(INTERNAL_ONLY_ERROR); - } - - @Override - public ElementKind getKind() { - throw new AssertionError(INTERNAL_ONLY_ERROR); - } - - @Override - public DartObsoleteMetadata getMetadata() { - throw new AssertionError(INTERNAL_ONLY_ERROR); - } - - @Override - public Modifiers getModifiers() { - throw new AssertionError(INTERNAL_ONLY_ERROR); - } - - @Override - public String getName() { - return name; - } - - @Override - public DartNode getNode() { - throw new AssertionError(INTERNAL_ONLY_ERROR); - } - - @Override - public String getOriginalName() { - throw new AssertionError(INTERNAL_ONLY_ERROR); - } - - @Override - public Type getType() { - throw new AssertionError(INTERNAL_ONLY_ERROR); - } - - @Override - public boolean isDynamic() { - throw new AssertionError(INTERNAL_ONLY_ERROR); - } - - @Override - public SourceInfo getSourceInfo() { - throw new AssertionError(INTERNAL_ONLY_ERROR); - } - - } - - // Array indexed by hashed name ... length is always power of 2 - private NodeElement[] elements; - private List ordered = new ArrayList(); - - @VisibleForTesting - public ElementMap() { - clear(); - } - - /** - * Associate the specified element with the specified name. If the element is already associated - * with that name, do not associate it again. - */ - @VisibleForTesting - public void add(String name, NodeElement element) { - - // Most of the time name equals getName() thus holder == element - NodeElement newHolder; - if (name.equals(element.getName())) { - newHolder = element; - } else { - newHolder = new ElementHolder(name, element); - } - - // 75% fill rate which anecdotal evidence claims is a good threshold for growing - if ((elements.length >> 2) * 3 <= size()) { - grow(); - } - int index = internalAdd(newHolder); - if (index == -1) { - ordered.add(element); - return; - } - - // Handle existing element with the same name - NodeElement existingHolder = elements[index]; - if (existingHolder == element) { - return; - } - if (!(existingHolder instanceof ElementHolder)) { - existingHolder = new ElementHolder(name, existingHolder); - elements[index] = existingHolder; - } - - // Check the list for a duplicate element entry, and append if none found - ElementHolder holder = (ElementHolder) existingHolder; - while (true) { - if (holder.element == element) { - return; - } - if (holder.nextHolder == null) { - holder.nextHolder = new ElementHolder(name, element); - ordered.add(element); - return; - } - holder = holder.nextHolder; - } - } - - void clear() { - elements = new NodeElement[16]; - ordered.clear(); - } - - /** - * Answer the element last associated with the specified name. - * - * @return the element or null if none - */ - @VisibleForTesting - public NodeElement get(String name) { - NodeElement element = internalGet(name); - if (element instanceof ElementHolder) { - return ((ElementHolder) element).element; - } else { - return element; - } - } - - /** - * Answer the element associated with the specified name and kind - * - * @return the element of that kind or null if none - */ - @VisibleForTesting - public NodeElement get(String name, ElementKind kind) { - NodeElement element = internalGet(name); - if (element instanceof ElementHolder) { - ElementHolder holder = (ElementHolder) element; - while (true) { - element = holder.element; - if (ElementKind.of(element).equals(kind)) { - return element; - } - holder = holder.nextHolder; - if (holder == null) { - break; - } - } - } else { - if (ElementKind.of(element).equals(kind)) { - return element; - } - } - return null; - } - - @VisibleForTesting - public boolean isEmpty() { - return ordered.isEmpty(); - } - - @VisibleForTesting - public int size() { - return ordered.size(); - } - - @VisibleForTesting - public List values() { - return ordered; - } - - private void grow() { - NodeElement[] old = elements; - elements = new NodeElement[elements.length << 2]; - for (NodeElement element : old) { - if (element != null) { - if (internalAdd(element) != -1) { - // Every element in the array should have a unique name, so there should not be any collision - throw new RuntimeException("Failed to grow: " + element.getName()); - } - } - } - } - - /** - * If an element with the given name does not exist in the array, then add the element and return - * -1 otherwise nothing is added and the index of the existing element returned. - */ - private int internalAdd(NodeElement element) { - String name = element.getName(); - int mask = elements.length - 1; - int probe = name.hashCode() & mask; - for (int i = probe; i < probe + mask + 1; i++) { - int index = i & mask; - NodeElement current = elements[index]; - if (current == null) { - elements[index] = element; - return -1; - } - if (current.getName().equals(name)) { - return index; - } - } - throw new AssertionError("overfilled array"); - } - - private NodeElement internalGet(String name) { - NodeElement element; - int mask = elements.length - 1; - int probe = name.hashCode() & mask; - for (int i = probe; i < probe + mask + 1; i++) { - element = elements[i & mask]; - if (element == null || element.getName().equals(name)) { - return element; - } - } - throw new AssertionError("overfilled array"); - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/Elements.java b/compiler/java/com/google/dart/compiler/resolver/Elements.java deleted file mode 100644 index 36d41c688799..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/Elements.java +++ /dev/null @@ -1,989 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Objects; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import com.google.dart.compiler.DartSource; -import com.google.dart.compiler.LibrarySource; -import com.google.dart.compiler.Source; -import com.google.dart.compiler.ast.DartClass; -import com.google.dart.compiler.ast.DartClassMember; -import com.google.dart.compiler.ast.DartClassTypeAlias; -import com.google.dart.compiler.ast.DartField; -import com.google.dart.compiler.ast.DartFunctionExpression; -import com.google.dart.compiler.ast.DartFunctionTypeAlias; -import com.google.dart.compiler.ast.DartIdentifier; -import com.google.dart.compiler.ast.DartLabel; -import com.google.dart.compiler.ast.DartMethodDefinition; -import com.google.dart.compiler.ast.DartNativeBlock; -import com.google.dart.compiler.ast.DartNode; -import com.google.dart.compiler.ast.DartObsoleteMetadata; -import com.google.dart.compiler.ast.DartParameter; -import com.google.dart.compiler.ast.DartSuperExpression; -import com.google.dart.compiler.ast.DartTypeNode; -import com.google.dart.compiler.ast.DartTypeParameter; -import com.google.dart.compiler.ast.DartVariable; -import com.google.dart.compiler.ast.LibraryUnit; -import com.google.dart.compiler.ast.Modifiers; -import com.google.dart.compiler.common.SourceInfo; -import com.google.dart.compiler.resolver.LabelElement.LabeledStatementType; -import com.google.dart.compiler.type.InterfaceType; -import com.google.dart.compiler.type.InterfaceType.Member; -import com.google.dart.compiler.type.Type; -import com.google.dart.compiler.type.TypeVariable; -import com.google.dart.compiler.util.Paths; -import com.google.dart.compiler.util.apache.StringUtils; - -import java.io.File; -import java.net.URI; -import java.text.MessageFormat; -import java.util.Arrays; -import java.util.List; -import java.util.Set; - -/** - * Utility and factory methods for elements. - */ -public class Elements { - - private Elements() {} // Prevent subclassing and instantiation. - - static void setParameterInitializerElement(VariableElement varElement, FieldElement element) { - ((VariableElementImplementation) varElement).setParameterInitializerElement(element); - } - - static void setDefaultClass(ClassElement classElement, InterfaceType defaultClass) { - ((ClassElementImplementation) classElement).setDefaultClass(defaultClass); - } - - static void addInterface(ClassElement classElement, InterfaceType type) { - ((ClassElementImplementation) classElement).addInterface(type); - } - - static void addMixin(ClassElement classElement, InterfaceType type) { - ((ClassElementImplementation) classElement).addMixin(type); - } - - static LabelElement statementLabelElement(DartLabel node, String name, - MethodElement enclosingFunction) { - return new LabelElementImplementation(node, name, enclosingFunction, - LabeledStatementType.STATEMENT); - } - - static LabelElement switchMemberLabelElement(DartLabel node, String name, - MethodElement enclosingFunction) { - return new LabelElementImplementation(node, name, enclosingFunction, - LabeledStatementType.SWITCH_MEMBER_STATEMENT); - } - - static LabelElement switchLabelElement(DartLabel node, String name, - MethodElement enclosingFunction) { - return new LabelElementImplementation(node, name, enclosingFunction, - LabeledStatementType.SWITCH_STATEMENT); - } - - public static LibraryElement libraryElement(LibraryUnit libraryUnit) { - return new LibraryElementImplementation(libraryUnit); - } - - public static void setLibraryMetadata(LibraryElement element, DartObsoleteMetadata metadata) { - ((LibraryElementImplementation) element).setMetadata(metadata); - } - - public static Element addExportedElement(LibraryElement libraryElement, Element element) { - return ((LibraryElementImplementation) libraryElement).addExportedElements(element); - } - - public static LibraryElement getLibraryElement(Element element) { - while (element != null) { - if (ElementKind.of(element) == ElementKind.LIBRARY) { - return (LibraryElement) element; - } - EnclosingElement enclosingElement = element.getEnclosingElement(); - if (enclosingElement == element) { - return null; - } - element = enclosingElement; - }; - return null; - } - - /** - * @return true if "a" and "b" are declared in the same {@link LibraryElement}. - */ - public static boolean areSameLibrary(Element a, Element b) { - LibraryElement aLibrary = getLibraryElement(a); - LibraryElement bLibrary = getLibraryElement(b); - return Objects.equal(aLibrary, bLibrary); - } - - @VisibleForTesting - public static MethodElement methodElement(DartFunctionExpression node, String name) { - return new MethodElementImplementation(node, name, Modifiers.NONE); - } - - public static TypeVariableElement typeVariableElement(String name, Type bound) { - return new TypeVariableElementImplementation(name, bound); - } - - public static VariableElement variableElement(EnclosingElement owner, - DartVariable node, - String name, - Modifiers modifiers) { - return new VariableElementImplementation(owner, - node, - node.getName().getSourceInfo(), - name, - ElementKind.VARIABLE, - modifiers, - false, - null); - } - - public static VariableElement parameterElement(EnclosingElement owner, - DartParameter node, - String name, - Modifiers modifiers) { - return new VariableElementImplementation(owner, - node, - node.getName().getSourceInfo(), - name, - ElementKind.PARAMETER, - modifiers, - node.getModifiers().isNamed(), - node.getDefaultExpr()); - } - - public static SuperElement superElement(DartSuperExpression node, ClassElement cls) { - return new SuperElementImplementation(node, cls); - } - - static void addConstructor(ClassElement cls, ConstructorNodeElement constructor) { - ((ClassElementImplementation) cls).addConstructor(constructor); - } - - static void addField(EnclosingElement holder, FieldNodeElement field) { - if (ElementKind.of(holder).equals(ElementKind.CLASS)) { - ((ClassElementImplementation) holder).addField(field); - } else if (ElementKind.of(holder).equals(ElementKind.LIBRARY)) { - ((LibraryElementImplementation) holder).addField(field); - } else { - throw new IllegalArgumentException(); - } - } - - @VisibleForTesting - public static void addMethod(EnclosingElement holder, MethodNodeElement method) { - if (ElementKind.of(holder).equals(ElementKind.CLASS)) { - ((ClassElementImplementation) holder).addMethod(method); - } else if (ElementKind.of(holder).equals(ElementKind.LIBRARY)) { - ((LibraryElementImplementation) holder).addMethod(method); - } else { - throw new IllegalArgumentException(); - } - } - - public static void addParameter(MethodElement method, VariableElement parameter) { - ((MethodElementImplementation) method).addParameter(parameter); - } - - static Element findElement(EnclosingElement cls, String name) { - if (cls instanceof ClassElementImplementation) { - return ((ClassElementImplementation) cls).findElement(name); - } - return null; - } - - public static MethodElement methodFromFunctionExpression(DartFunctionExpression node, - Modifiers modifiers) { - return MethodElementImplementation.fromFunctionExpression(node, modifiers); - } - - public static MethodNodeElement methodFromMethodNode(DartMethodDefinition node, - EnclosingElement holder) { - return MethodElementImplementation.fromMethodNode(node, holder); - } - - static ConstructorNodeElement constructorFromMethodNode(DartMethodDefinition node, - String name, - ClassElement declaringClass, - ClassElement constructorType) { - return ConstructorElementImplementation.fromMethodNode(node, name, declaringClass, - constructorType); - } - - public static void setType(Element element, Type type) { - ((AbstractNodeElement) element).setType(type); - } - - public static void setOverridden(Element element, Set overridden) { - if (element instanceof MethodElementImplementation) { - ((MethodElementImplementation) element).setOverridden(overridden); - } - if (element instanceof FieldElementImplementation) { - ((FieldElementImplementation) element).setOverridden(overridden); - } - } - -static FieldElementImplementation fieldFromNode(DartField node, - EnclosingElement holder, - DartObsoleteMetadata metadata, - Modifiers modifiers) { - return FieldElementImplementation.fromNode(node, holder, metadata, modifiers); - } - - static ClassElement classFromNode(DartClass node, LibraryElement library) { - return ClassElementImplementation.fromNode(node, library); - } - - static ClassAliasElement classFromNode(DartClassTypeAlias node, LibraryElement library) { - return ClassElementImplementation.fromNode(node, library); - } - - public static ClassElement classNamed(String name) { - return ClassElementImplementation.named(name); - } - - static TypeVariableElement typeVariableFromNode(DartTypeParameter node, EnclosingElement element) { - return TypeVariableElementImplementation.fromNode(node, element); - } - - public static DynamicElement dynamicElement() { - return DynamicElementImplementation.getInstance(); - } - - static ConstructorElement lookupConstructor(ClassElement cls, ClassElement type, String name) { - return ((ClassElementImplementation) cls).lookupConstructor(type, name); - } - - static ConstructorElement lookupConstructor(ClassElement cls, String name) { - if (cls instanceof ClassElementImplementation) { - return ((ClassElementImplementation) cls).lookupConstructor(name); - } - return null; - } - - public static MethodElement lookupLocalMethod(ClassElement cls, String name) { - return ((ClassElementImplementation) cls).lookupLocalMethod(name); - } - - public static FieldElement lookupLocalField(ClassElement cls, String name) { - return ((ClassElementImplementation) cls).lookupLocalField(name); - } - - public static FunctionAliasElement functionTypeAliasFromNode(DartFunctionTypeAlias node, - LibraryElement library) { - return FunctionAliasElementImplementation.fromNode(node, library); - } - - /** - * @return true if given {@link Element} represents {@link VariableElement} for - * parameter in {@link DartMethodDefinition}. - */ - public static boolean isConstructorParameter(Element element) { - Element parent = element.getEnclosingElement(); - if (parent instanceof MethodElement) { - return ((MethodElement) parent).isConstructor(); - } - return false; - } - - /** - * @return true if given {@link Element} represents {@link VariableElement} for - * parameter in {@link DartMethodDefinition} without body, or with {@link DartNativeBlock} - * as body. - */ - public static boolean isParameterOfMethodWithoutBody(Element element) { - if (element instanceof VariableElement) { - Element parent = element.getEnclosingElement(); - if (parent instanceof MethodElement) { - MethodElement parentMethod = (MethodElement) parent; - return !parentMethod.hasBody(); - } - } - return false; - } - - /** - * @return not-null {@link MethodElement} if "holder", or one of its interfaces, or - * its superclass has {@link FieldElement} with getter. - */ - public static MethodElement lookupFieldElementGetter(EnclosingElement holder, String name) { - MethodElement result = lookupFieldElementGetter0(holder, name); - if (result != null) { - return result; - } - if (holder instanceof ClassElement) { - ClassElement classHolder = (ClassElement) holder; - for (InterfaceType interfaceType : classHolder.getInterfaces()) { - result = lookupFieldElementGetter(interfaceType.getElement(), name); - if (result != null) { - return result; - } - } - for (InterfaceType mixinType : classHolder.getMixins()) { - result = lookupFieldElementGetter0(mixinType.getElement(), name); - if (result != null) { - return result; - } - } - if (classHolder.getSupertype() != null) { - result = lookupFieldElementGetter(classHolder.getSupertype().getElement(), name); - if (result != null) { - return result; - } - } - } - - return null; - } - - /** - * @return the {@link MethodElement} if "holder" has {@link FieldElement} with getter. - */ - private static MethodElement lookupFieldElementGetter0(EnclosingElement holder, String name) { - Element element = holder.lookupLocalElement(name); - if (element instanceof FieldElement) { - FieldElement fieldElement = (FieldElement) element; - MethodElement result = fieldElement.getGetter(); - if (result != null) { - return fieldElement.getGetter(); - } - } - return null; - } - - /** - * @return non-null {@link MethodElement} if "holder", or one of its interfaces, or - * its superclass has {@link FieldElement} with setter. - */ - public static MethodElement lookupFieldElementSetter(EnclosingElement holder, String name) { - MethodElement result = lookupFieldElementSetter0(holder, name); - if (result != null) { - return result; - } - if (holder instanceof ClassElement) { - ClassElement classHolder = (ClassElement) holder; - for (InterfaceType interfaceType : classHolder.getInterfaces()) { - result = lookupFieldElementSetter(interfaceType.getElement(), name); - if (result != null) { - return result; - } - } - for (InterfaceType mixinType : classHolder.getMixins()) { - result = lookupFieldElementSetter0(mixinType.getElement(), name); - if (result != null) { - return result; - } - } - if (classHolder.getSupertype() != null) { - result = lookupFieldElementSetter(classHolder.getSupertype().getElement(), name); - if (result != null) { - return result; - } - } - } - return null; - } - - /** - * @return the {@link MethodElement} if "holder" has {@link FieldElement} with setter. - */ - private static MethodElement lookupFieldElementSetter0(EnclosingElement holder, String name) { - Element element = holder.lookupLocalElement(name); - if (element instanceof FieldElement) { - FieldElement fieldElement = (FieldElement) element; - MethodElement result = fieldElement.getSetter(); - if (result != null) { - return result; - } - } - return null; - } - - /** - * @return true if {@link DartNode} of given {@link Element} if part of static - * {@link DartClassMember} or part of top level declaration. - */ - public static boolean isStaticContext(Element element) { - if (element instanceof ClassElement) { - return true; - } - while (element != null) { - if (element instanceof MethodElement) { - MethodElement methodElement = (MethodElement) element; - return methodElement.isStatic() || methodElement.getEnclosingElement() instanceof LibraryElement; - } - if (element instanceof FieldElement) { - FieldElement fieldElement = (FieldElement) element; - return fieldElement.isStatic() - || fieldElement.getEnclosingElement() instanceof LibraryElement; - } - if (element instanceof ClassElement) { - return false; - } - element = element.getEnclosingElement(); - } - return true; - } - - public static boolean isNonFactoryConstructor(Element method) { - return !method.getModifiers().isFactory() - && ElementKind.of(method) == ElementKind.CONSTRUCTOR; - } - - public static boolean isTopLevel(Element element) { - return ElementKind.of(element.getEnclosingElement()) == ElementKind.LIBRARY; - } - - static List makeTypeVariables(List parameterNodes, - EnclosingElement enclosingElement) { - if (parameterNodes == null) { - return Arrays.asList(); - } - TypeVariable[] typeVariables = new TypeVariable[parameterNodes.size()]; - int i = 0; - for (DartTypeParameter parameterNode : parameterNodes) { - TypeVariable typeVariable = - Elements.typeVariableFromNode(parameterNode, enclosingElement).getTypeVariable(); - typeVariables[i++] = typeVariable; - parameterNode.getName().setElement(typeVariable.getElement()); - } - return Arrays.asList(typeVariables); - } - - public static Element voidElement() { - return VoidElement.getInstance(); - } - - /** - * Returns true if the class needs an implicit default constructor. - */ - public static boolean needsImplicitDefaultConstructor(ClassElement classElement) { - return classElement.getConstructors().isEmpty() - && (!classElement.isInterface() || classElement.getDefaultClass() != null); - } - - /** - * @return true if {@link #classElement} implements {@link #interfaceElement}. - */ - public static boolean implementsType(ClassElement classElement, ClassElement interfaceElement) { - try { - for (InterfaceType supertype : classElement.getAllSupertypes()) { - if (supertype.getElement().equals(interfaceElement)) { - return true; - } - } - } catch (Throwable e) { - } - return false; - } - - /** - * @return the "name" or "qualifier.name" raw name of {@link DartMethodDefinition} which - * corresponds the given {@link MethodElement}. - */ - public static String getRawMethodName(MethodElement methodElement) { - if (methodElement instanceof ConstructorElement) { - ConstructorElement constructorElement = (ConstructorElement) methodElement; - return constructorElement.getRawName(); - } - return methodElement.getName(); - } - - /** - * @return the number of required (not optional/named) parameters in given {@link MethodElement}. - */ - public static int getNumberOfRequiredParameters(MethodElement method) { - int num = 0; - List parameters = method.getParameters(); - for (VariableElement parameter : parameters) { - if (!parameter.isOptional() && !parameter.isNamed()) { - num++; - } - } - return num; - } - - /** - * @return the number of optional positional parameters in given {@link MethodElement}. - */ - public static int getNumberOfOptionalPositionalParameters(MethodElement method) { - int num = 0; - List parameters = method.getParameters(); - for (VariableElement parameter : parameters) { - if (parameter.isOptional()) { - num++; - } - } - return num; - } - - /** - * @return the names for named parameters in given {@link MethodElement}. - */ - public static List getNamedParameters(MethodElement method) { - List names = Lists.newArrayList(); - List parameters = method.getParameters(); - for (VariableElement parameter : parameters) { - if (parameter.isNamed()) { - names.add(parameter.getName()); - } - } - return names; - } - - /** - * @return the names for parameters types in given {@link MethodElement}. - */ - public static List getParameterTypeNames(MethodElement method) { - List names = Lists.newArrayList(); - List parameters = method.getParameters(); - for (VariableElement parameter : parameters) { - String typeName = parameter.getType().getElement().getName(); - names.add(typeName); - } - return names; - } - - /** - * Prepares title for {@link TypeErrorCode#DEPRECATED_ELEMENT}. - */ - public static String getDeprecatedElementTitle(Element element) { - String title = getUserElementTitle(element); - return StringUtils.capitalize(title); - } - - /** - * @return the user readable title of the given {@link Element}, a little different than - * "technical" title returned from {@link Element#toString()}. - */ - public static String getUserElementTitle(Element element) { - return MessageFormat.format("{0} ''{1}''", getUserElementKindTitle(element), element.getName()); - } - - /** - * @return the user readable title of the given {@link Element}'s {@link ElementKind}, a little - * different than "technical" title returned from {@link Element#toString()}. - */ - private static String getUserElementKindTitle(Element element) { - ElementKind kind = element.getKind(); - switch (kind) { - case CLASS: - if (((ClassElement) element).isInterface()) { - return "interface"; - } - break; - case METHOD: - if (isTopLevel(element)) { - return "top-level function"; - } - break; - case FIELD: - if (isTopLevel(element)) { - return "top-level variable"; - } - break; - } - String title = kind.toString(); - title = StringUtils.replace(title, "_", " "); - title = title.toLowerCase(); - return title; - } - - /** - * @return the {@link String} which contains user-readable description of "target" {@link Element} - * location relative to "source". - */ - public static String getRelativeElementLocation(Element source, Element target) { - // Prepare "target" SourceInfo. - SourceInfo targetInfo; - { - targetInfo = target.getNameLocation(); - if (targetInfo == null) { - return "unknown"; - } - } - // Prepare path to the target unit from source unit. - String targetPath; - { - SourceInfo sourceInfo = source.getSourceInfo(); - targetPath = getRelativeSourcePath(sourceInfo, targetInfo); - } - // Prepare (may be empty) target class name. - String targetClassName; - { - EnclosingElement targetEnclosing = target.getEnclosingElement(); - ClassElement targetClass = getEnclosingClassElement(targetEnclosing); - targetClassName = targetClass != null ? targetClass.getName() : ""; - } - // Format location string. - if (StringUtils.isEmpty(targetClassName)) { - return MessageFormat.format("{0} line:{1} col:{2}", targetPath, targetInfo.getLine(), - targetInfo.getColumn()); - } else { - return MessageFormat.format("{0} class:{1} line:{2} col:{3}", targetPath, targetClassName, - targetInfo.getLine(), targetInfo.getColumn()); - } - } - - /** - * @return the relative or absolute path from "source" to "target". - */ - private static String getRelativeSourcePath(SourceInfo source, SourceInfo target) { - Source sourceSource = source.getSource(); - Source targetSource = target.getSource(); - return getRelativeSourcePath(sourceSource, targetSource); - } - - /** - * @return the relative or absolute path from "source" to "target". - */ - public static String getRelativeSourcePath(Source sourceSource, Source targetSource) { - // If both source are from file, prepare relative path. - if (sourceSource != null && targetSource != null) { - URI sourceUri = sourceSource.getUri(); - URI targetUri = targetSource.getUri(); - if (Objects.equal(sourceUri.getScheme(), "file") - && Objects.equal(targetUri.getScheme(), "file")) { - return Paths.relativePathFor(new File(sourceUri.getPath()), new File(targetUri.getPath())); - } - } - // Else return absolute path (including dart:// protocol). - if (targetSource != null) { - URI targetUri = targetSource.getUri(); - return targetUri.toString(); - } - // No source for target. - return ""; - } - - /** - * @return the full location of the given {@link Element} - library and unit. - */ - public static String getLibraryUnitLocation(Element element) { - try { - StringBuilder sb = new StringBuilder(); - // library URI - String libraryUri; - { - LibraryUnit libraryUnit = getDeclaringLibrary(element).getLibraryUnit(); - libraryUri = libraryUnit.getSource().getUri().toString(); - sb.append(libraryUri); - } - // unit URI - SourceInfo sourceInfo = element.getSourceInfo(); - { - String unitUri = sourceInfo.getSource().getUri().toString(); - if (!unitUri.equals(libraryUri)) { - sb.append(" "); - sb.append(unitUri); - } - } - // line - sb.append(":"); - sb.append(sourceInfo.getLine()); - // done - return sb.toString(); - } catch (Throwable e) { - return ""; - } - } - - /** - * @return the enclosing {@link ClassElement} (may be same if already given {@link ClassElement}), - * may be null if top level element. - */ - public static ClassElement getEnclosingClassElement(Element element) { - while (element != null) { - if (element instanceof ClassElement) { - return (ClassElement) element; - } - element = element.getEnclosingElement(); - } - return null; - } - - /** - * @return true if the given {@link DartTypeNode} is type with one of the given - * names. - */ - public static boolean isTypeNode(DartTypeNode typeNode, Set names) { - if (typeNode != null) { - DartNode identifier = typeNode.getIdentifier(); - String typeName = getIdentifierName(identifier); - return names.contains(typeName); - } - return false; - } - - /** - * @return true if the given {@link DartTypeNode} is type with given name. - */ - public static boolean isTypeNode(DartTypeNode typeNode, String name) { - return typeNode != null && isIdentifierName(typeNode.getIdentifier(), name); - } - - /** - * @return true if the given {@link DartNode} is type identifier with given name. - */ - public static boolean isIdentifierName(DartNode identifier, String name) { - String identifierName = getIdentifierName(identifier); - return Objects.equal(identifierName, name); - } - - /** - * @return true if the given {@link ConstructorElement} is a synthetic default - * constructor. - */ - public static boolean isSyntheticConstructor(ConstructorElement element) { - return element != null && element.isSynthetic(); - } - - /** - * @return true if the given {@link ConstructorElement} is a default constructor. - */ - public static boolean isDefaultConstructor(ConstructorElement element) { - return element != null - && element.getParameters().isEmpty() - && getRawMethodName(element).equals(element.getEnclosingElement().getName()); - } - - public static void setRedirectingFactoryConstructor(ConstructorElement source, - ConstructorElement target) { - ((ConstructorElementImplementation) source).setRedirectingFactoryConstructor(target); - } - - /** - * @return the name of given {@link DartNode} if it is {@link DartIdentifier}, or - * null otherwise. - */ - private static String getIdentifierName(DartNode identifier) { - if (identifier != null && identifier instanceof DartIdentifier) { - return ((DartIdentifier) identifier).getName(); - } - return null; - } - - /** - * @return true if given {@link Source} represents library with given name. - */ - public static boolean isLibrarySource(Source source, String name) { - LibrarySource library = null; - if (source instanceof LibrarySource) { - library = (LibrarySource) source; - } - if (source instanceof DartSource) { - DartSource dartSource = (DartSource) source; - library = dartSource.getLibrary(); - } - if (library != null) { - String libraryName = library.getName(); - return libraryName.endsWith(name); - } - return false; - } - - /** - * @return true if given {@link Source} represents code library declaration or - * implementation. - */ - public static boolean isCoreLibrarySource(Source source) { - if (source != null && source.getUri() != null - && source.getUri().toString().equals("libraries.dart")) { - return true; - } - // TODO (danrubel) remove these when dartc libraries are removed - // Old core library file names - return Elements.isLibrarySource(source, "/core/corelib.dart") - || Elements.isLibrarySource(source, "/core/corelib_impl.dart") - // New core library file names - || Elements.isLibrarySource(source, "/core/core.dart"); - } - - public static boolean isCollectionLibrarySource(Source source) { - return Elements.isLibrarySource(source, "/collection/collection.dart"); - } - - public static boolean isHtmlLibrarySource(Source source) { - return Elements.isLibrarySource(source, "/html/dartium/html_dartium.dart"); - } - - public static boolean isSourceName(Source source, String requiredName) { - return source.getName().equals(requiredName); - } - - /** - * @return the {@link LibraryElement} which declares given {@link Element}. - */ - public static LibraryElement getDeclaringLibrary(Element element) { - while (element != null) { - if (element instanceof LibraryElement) { - return (LibraryElement) element; - } - element = element.getEnclosingElement(); - } - return null; - } - - /** - * @return true if "element" is accessible in "scopeLibrary". - */ - public static boolean isAccessible(LibraryElement scopeLibrary, Element element) { - if (element != null && StringUtils.startsWith(element.getName(), "_")) { - return Objects.equal(scopeLibrary, getDeclaringLibrary(element)); - } - return true; - } - - /** - * @return true if given {@link Element} if {@link MethodElement} for - * function "identical". - */ - public static boolean isFunctionIdentical(Element element) { - if (element instanceof MethodElement) { - MethodElement methodElement = (MethodElement) element; - return Objects.equal(methodElement.getName(), "identical") - && methodElement.getEnclosingElement() instanceof LibraryElement - && methodElement.getEnclosingElement().getName().equals("dart://core/core.dart"); - } - return false; - } - - /** - * @return true if normal field or abstract field with getter. - */ - public static boolean isFieldWithGetter(FieldElement fieldElement) { - if (fieldElement.getModifiers().isAbstractField()) { - return fieldElement.getGetter() != null; - } - return true; - } - - public static boolean isAbstractFieldWithoutGetter(Element element) { - if (element instanceof FieldElement) { - FieldElement fieldElement = (FieldElement) element; - return fieldElement.getModifiers().isAbstractField() && fieldElement.getGetter() == null; - } - return false; - } - - public static boolean hasClassMember(ClassElement clazz, String name) { - if (clazz.lookupLocalElement(name) != null) { - return true; - } - for (InterfaceType interfaceType : clazz.getInterfaces()) { - if (hasClassMember(interfaceType.getElement(), name)) { - return true; - } - } - for (InterfaceType mixinType : clazz.getMixins()) { - if (mixinType.getElement().lookupLocalElement(name) != null) { - return true; - } - } - if (clazz.getSupertype() != null) { - if (hasClassMember(clazz.getSupertype().getElement(), name)) { - return true; - } - } - return false; - } - - /** - * @return true if given {@link FieldElement} is explicitly declared static, or is - * static implicitly. - */ - public static boolean isStaticField(FieldElement field) { - Modifiers modifiers = field.getModifiers(); - return modifiers.isStatic(); - } - - /** - * @return true if given {@link InterfaceType} overrides "noSuchMethod". - */ - public static boolean handlesNoSuchMethod(InterfaceType type) { - Member member = type.lookupMember("noSuchMethod"); - if (member == null) { - return false; - } - Source source = member.getElement().getSourceInfo().getSource(); - return !isCoreLibrarySource(source); - } - - public static DuplicateElement createDuplicateElement(Element oldElement, Element newElement) { - return new DuplicateElementImplementation(oldElement, newElement); - } - - - public static List getAllMembers(ClassElement classElement) { - List allMembers = Lists.newArrayList(); - Set visited = Sets.newHashSet(); - addAllMembers(visited, allMembers, classElement); - return allMembers; - } - - private static void addAllMembers(Set visited, List allMembers, ClassElement classElement) { - if (classElement == null) { - return; - } - if (visited.contains(classElement)) { - return; - } - visited.add(classElement); - Iterables.addAll(allMembers, classElement.getMembers()); - { - InterfaceType superType = classElement.getSupertype(); - if (superType != null) - addAllMembers(visited, allMembers, superType.getElement()); - } - for (InterfaceType intf : classElement.getInterfaces()) { - addAllMembers(visited, allMembers, intf.getElement()); - } - for (InterfaceType mix : classElement.getMixins()) { - Iterables.addAll(allMembers, mix.getElement().getMembers()); - } - } - - public static boolean isAbstractElement(Element element) { - if (element == null) { - return false; - } - if (element.getModifiers().isAbstract()) { - return true; - } - if (element.getModifiers().isExternal()) { - return false; - } - if (element.getModifiers().isNative()) { - return false; - } - if (element.getModifiers().isStatic()) { - return false; - } - if (ElementKind.of(element) == ElementKind.METHOD) { - MethodElement method = (MethodElement) element; - return !method.hasBody(); - } - return false; - } - - public static boolean isFieldOfSameClassAsEnclosingConstructor(Element maybeField, - Element maybeConstructor) { - if (ElementKind.of(maybeField) == ElementKind.FIELD - && ElementKind.of(maybeConstructor) == ElementKind.CONSTRUCTOR) { - FieldElement field = (FieldElement) maybeField; - ConstructorElement constructor = (ConstructorElement) maybeConstructor; - if (field.getEnclosingElement() == constructor.getEnclosingElement()) { - return true; - } - } - return false; - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/EnclosingElement.java b/compiler/java/com/google/dart/compiler/resolver/EnclosingElement.java deleted file mode 100644 index 0a96beae2e70..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/EnclosingElement.java +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -public interface EnclosingElement extends Element { - Iterable getMembers(); - - Element lookupLocalElement(String name); - - boolean isInterface(); -} diff --git a/compiler/java/com/google/dart/compiler/resolver/FieldElement.java b/compiler/java/com/google/dart/compiler/resolver/FieldElement.java deleted file mode 100644 index a2fb975cfb33..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/FieldElement.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.dart.compiler.type.Type; - -import java.util.Set; - -public interface FieldElement extends Element { - boolean isStatic(); - - void setType(Type type); - - MethodElement getGetter(); - - MethodElement getSetter(); - - /** - * @return the inferred {@link Type} of this constant, may be null if not set yet. - */ - Type getConstantType(); - - /** - * @return {@link Element}s overridden by this {@link MethodElement}. - */ - Set getOverridden(); -} diff --git a/compiler/java/com/google/dart/compiler/resolver/FieldElementImplementation.java b/compiler/java/com/google/dart/compiler/resolver/FieldElementImplementation.java deleted file mode 100644 index d60a14425044..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/FieldElementImplementation.java +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.common.collect.ImmutableSet; -import com.google.dart.compiler.ast.DartField; -import com.google.dart.compiler.ast.DartNode; -import com.google.dart.compiler.ast.DartObsoleteMetadata; -import com.google.dart.compiler.ast.Modifiers; -import com.google.dart.compiler.common.SourceInfo; -import com.google.dart.compiler.type.Type; - -import java.util.Set; - -class FieldElementImplementation extends AbstractNodeElement implements FieldElement, FieldNodeElement { - private final EnclosingElement holder; - private final SourceInfo nameLocation; - private DartObsoleteMetadata metadata; - private Modifiers modifiers; - private Type type; - private MethodNodeElement getter; - private MethodNodeElement setter; - private Type constantType; - private Set overridden = ImmutableSet.of(); - - FieldElementImplementation(DartNode node, - SourceInfo nameLocation, - String name, - EnclosingElement holder, - DartObsoleteMetadata metadata, - Modifiers modifiers) { - super(node, name); - this.holder = holder; - this.metadata = metadata; - this.modifiers = modifiers; - this.nameLocation = nameLocation; - } - - @Override - public Type getType() { - return type; - } - - @Override - public void setType(Type type) { - this.type = type; - } - - @Override - public ElementKind getKind() { - return ElementKind.FIELD; - } - - @Override - public SourceInfo getNameLocation() { - return nameLocation; - } - - @Override - public EnclosingElement getEnclosingElement() { - return holder; - } - - @Override - public DartObsoleteMetadata getMetadata() { - return metadata; - } - - @Override - public Modifiers getModifiers() { - return modifiers; - } - - @Override - public boolean isStatic() { - return modifiers.isStatic(); - } - - public static FieldElementImplementation fromNode(DartField node, - EnclosingElement holder, - DartObsoleteMetadata metadata, - Modifiers modifiers) { - return new FieldElementImplementation(node, - node.getName().getSourceInfo(), - (node.getAccessor() != null && node.getAccessor().getModifiers().isSetter() ? "setter " : "") + node.getName().getName(), - holder, - metadata, - modifiers); - } - - @Override - public MethodNodeElement getGetter() { - return getter; - } - - @Override - public MethodNodeElement getSetter() { - return setter; - } - - void setGetter(MethodNodeElement getter) { - this.getter = getter; - } - - void setSetter(MethodNodeElement setter) { - this.setter = setter; - } - - @Override - public Type getConstantType() { - return constantType; - } - - @Override - public void setConstantType(Type type) { - constantType = type; - } - - public void setOverridden(Set overridden) { - this.overridden = overridden; - } - - public Set getOverridden() { - return overridden; - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/FieldNodeElement.java b/compiler/java/com/google/dart/compiler/resolver/FieldNodeElement.java deleted file mode 100644 index 6b059653b82a..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/FieldNodeElement.java +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. -package com.google.dart.compiler.resolver; - -import com.google.dart.compiler.ast.DartNode; -import com.google.dart.compiler.type.Type; - -/** - * Extension of {@link FieldElement} which is based on {@link DartNode} and is modifiable. - */ -public interface FieldNodeElement extends FieldElement, NodeElement { - /** - * Sets the inferred type of this constant. - * - * @param type the {@link Type} to set, not null. - */ - void setConstantType(Type type); - - MethodNodeElement getGetter(); - - MethodNodeElement getSetter(); -} diff --git a/compiler/java/com/google/dart/compiler/resolver/FunctionAliasElement.java b/compiler/java/com/google/dart/compiler/resolver/FunctionAliasElement.java deleted file mode 100644 index 982677ee4737..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/FunctionAliasElement.java +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.dart.compiler.type.FunctionAliasType; -import com.google.dart.compiler.type.FunctionType; - -/** - * A function type alias. - */ -public interface FunctionAliasElement extends ClassElement { - @Override - FunctionAliasType getType(); - - FunctionType getFunctionType(); - - void setFunctionType(FunctionType functionType); -} diff --git a/compiler/java/com/google/dart/compiler/resolver/FunctionAliasElementImplementation.java b/compiler/java/com/google/dart/compiler/resolver/FunctionAliasElementImplementation.java deleted file mode 100644 index e6f243912c02..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/FunctionAliasElementImplementation.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.dart.compiler.ast.DartFunctionTypeAlias; -import com.google.dart.compiler.type.FunctionAliasType; -import com.google.dart.compiler.type.FunctionType; -import com.google.dart.compiler.type.InterfaceType; - -// Could be a direct subclass of AbstractElement. -public class FunctionAliasElementImplementation extends ClassElementImplementation - implements FunctionAliasElement { - - private FunctionType functionType; - private final DartFunctionTypeAlias node; - - FunctionAliasElementImplementation(DartFunctionTypeAlias node, String name, LibraryElement library) { - super(null, name, null, library); - this.node = node; - } - - @Override - public DartFunctionTypeAlias getNode() { - return node; - } - - @Override - public ElementKind getKind() { - return ElementKind.FUNCTION_TYPE_ALIAS; - } - - @Override - public FunctionAliasType getType() { - return (FunctionAliasType) super.getType(); - } - - @Override - public FunctionType getFunctionType() { - return functionType; - } - - @Override - public void setType(InterfaceType type) { - FunctionAliasType ftype = (FunctionAliasType) type; - super.setType(ftype); - } - - @Override - public void setFunctionType(FunctionType functionType) { - this.functionType = functionType; - } - - public static FunctionAliasElement fromNode(DartFunctionTypeAlias node, - LibraryElement library) { - return new FunctionAliasElementImplementation( - node, node.getName().getName(), library); - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/LabelElement.java b/compiler/java/com/google/dart/compiler/resolver/LabelElement.java deleted file mode 100644 index 8fb58d91c00d..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/LabelElement.java +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -public interface LabelElement extends Element { - - public enum LabeledStatementType { - STATEMENT, - SWITCH_MEMBER_STATEMENT, - SWITCH_STATEMENT, - } - - /** - * Returns the innermost function where this label is defined. - */ - public MethodElement getEnclosingFunction(); - - public LabeledStatementType getStatementType(); -} diff --git a/compiler/java/com/google/dart/compiler/resolver/LabelElementImplementation.java b/compiler/java/com/google/dart/compiler/resolver/LabelElementImplementation.java deleted file mode 100644 index f61c03db82ef..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/LabelElementImplementation.java +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.dart.compiler.ast.DartLabel; - -class LabelElementImplementation extends AbstractNodeElement implements LabelElement { - - private MethodElement enclosingFunction; - private final LabeledStatementType statementType; - - LabelElementImplementation(DartLabel node, String name, MethodElement enclosingFunction, - LabeledStatementType statementType) { - super(node, name); - this.enclosingFunction = enclosingFunction; - this.statementType = statementType; - } - - @Override - public ElementKind getKind() { - return ElementKind.LABEL; - } - - @Override - public MethodElement getEnclosingFunction() { - return enclosingFunction; - } - - @Override - public LabeledStatementType getStatementType() { - return statementType; - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/LibraryElement.java b/compiler/java/com/google/dart/compiler/resolver/LibraryElement.java deleted file mode 100644 index 529ad646a031..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/LibraryElement.java +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.dart.compiler.ast.LibraryUnit; - -import java.util.Collection; - -public interface LibraryElement extends EnclosingElement { - Scope getImportScope(); - - Scope getScope(); - - Collection getExportedElements(); - - LibraryUnit getLibraryUnit(); - - void setEntryPoint(MethodElement element); - - MethodElement getEntryPoint(); -} diff --git a/compiler/java/com/google/dart/compiler/resolver/LibraryElementImplementation.java b/compiler/java/com/google/dart/compiler/resolver/LibraryElementImplementation.java deleted file mode 100644 index 3e2c49c13971..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/LibraryElementImplementation.java +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.common.collect.Maps; -import com.google.dart.compiler.ast.DartObsoleteMetadata; -import com.google.dart.compiler.ast.LibraryUnit; - -import java.util.Collection; -import java.util.Map; - -class LibraryElementImplementation extends AbstractNodeElement implements LibraryElement { - - private final Scope importScope = new Scope("import", this); - private final Scope scope = new Scope("library", this, importScope); - private final Map exportedElements = Maps.newHashMap(); - private LibraryUnit libraryUnit; - private MethodElement entryPoint; - private DartObsoleteMetadata metadata = DartObsoleteMetadata.EMPTY; - - public LibraryElementImplementation(LibraryUnit libraryUnit) { - // TODO(ngeoffray): What should we pass the super? Should a LibraryUnit be a node? - super(null, libraryUnit.getSource().getName()); - this.libraryUnit = libraryUnit; - } - - @Override - public boolean isInterface() { - return false; - } - - @Override - public Scope getImportScope() { - return importScope; - } - - @Override - public Scope getScope() { - return scope; - } - - public Element addExportedElements(Element element) { - String name = element.getName(); - return exportedElements.put(name, element); - } - - public Collection getExportedElements() { - return exportedElements.values(); - } - - @Override - public ElementKind getKind() { - return ElementKind.LIBRARY; - } - - @Override - public LibraryUnit getLibraryUnit() { - return libraryUnit; - } - - @Override - public void setEntryPoint(MethodElement element) { - this.entryPoint = element; - } - - @Override - public MethodElement getEntryPoint() { - return entryPoint; - } - - @Override - public Collection getMembers() { - // TODO(ngeoffray): have a proper way to get all the declared top level elements. - return scope.getElements().values(); - } - - @Override - public Element lookupLocalElement(String name) { - return scope.findLocalElement(name); - } - - void addField(FieldElement field) { - scope.declareElement(field.getName(), field); - } - - void addMethod(MethodElement method) { - scope.declareElement(method.getName(), method); - } - - @Override - public DartObsoleteMetadata getMetadata() { - return metadata; - } - - public void setMetadata(DartObsoleteMetadata metadata) { - this.metadata = metadata; - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/LibraryPrefixElement.java b/compiler/java/com/google/dart/compiler/resolver/LibraryPrefixElement.java deleted file mode 100644 index 96486174bc46..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/LibraryPrefixElement.java +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import java.util.List; - -public interface LibraryPrefixElement extends EnclosingElement { - Scope getScope(); - void addLibrary(LibraryElement library); - List getLibraries(); -} diff --git a/compiler/java/com/google/dart/compiler/resolver/LibraryPrefixElementImplementation.java b/compiler/java/com/google/dart/compiler/resolver/LibraryPrefixElementImplementation.java deleted file mode 100644 index e54c625bfce4..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/LibraryPrefixElementImplementation.java +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.common.collect.Lists; - -import java.util.Collection; -import java.util.List; - -class LibraryPrefixElementImplementation extends AbstractNodeElement implements - LibraryPrefixElement { - - private final List libraries = Lists.newArrayList(); - private final Scope scope; - - public LibraryPrefixElementImplementation(String name, Scope parent) { - super(null, name); - scope = new Scope("prefix:" + name, parent.getLibrary()); - } - - @Override - public boolean isInterface() { - return false; - } - - @Override - public Scope getScope() { - return scope; - } - - @Override - public ElementKind getKind() { - return ElementKind.LIBRARY_PREFIX; - } - - @Override - public Collection getMembers() { - return scope.getElements().values(); - } - - @Override - public Element lookupLocalElement(String name) { - return scope.findLocalElement(name); - } - - public void addLibrary(LibraryElement library) { - libraries.add(library); - } - - @Override - public List getLibraries() { - return libraries; - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/MemberBuilder.java b/compiler/java/com/google/dart/compiler/resolver/MemberBuilder.java deleted file mode 100644 index a46aa61d2adf..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/MemberBuilder.java +++ /dev/null @@ -1,736 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Objects; -import com.google.dart.compiler.DartCompilerContext; -import com.google.dart.compiler.ErrorCode; -import com.google.dart.compiler.ast.ASTVisitor; -import com.google.dart.compiler.ast.DartBlock; -import com.google.dart.compiler.ast.DartClass; -import com.google.dart.compiler.ast.DartExpression; -import com.google.dart.compiler.ast.DartField; -import com.google.dart.compiler.ast.DartFieldDefinition; -import com.google.dart.compiler.ast.DartFunction; -import com.google.dart.compiler.ast.DartFunctionTypeAlias; -import com.google.dart.compiler.ast.DartIdentifier; -import com.google.dart.compiler.ast.DartMethodDefinition; -import com.google.dart.compiler.ast.DartNativeBlock; -import com.google.dart.compiler.ast.DartNode; -import com.google.dart.compiler.ast.DartParameter; -import com.google.dart.compiler.ast.DartParameterizedTypeNode; -import com.google.dart.compiler.ast.DartPropertyAccess; -import com.google.dart.compiler.ast.DartThisExpression; -import com.google.dart.compiler.ast.DartUnit; -import com.google.dart.compiler.ast.Modifiers; -import com.google.dart.compiler.common.HasSourceInfo; -import com.google.dart.compiler.common.SourceInfo; -import com.google.dart.compiler.type.Type; -import com.google.dart.compiler.type.Types; -import com.google.dart.compiler.util.apache.StringUtils; - -import java.util.ArrayList; -import java.util.List; - -/** - * Builds the method, field and constructor elements of classes and the library in a DartUnit. - */ -public class MemberBuilder { - private ResolutionContext topLevelContext; - private LibraryElement libraryElement; - - public void exec(DartUnit unit, DartCompilerContext context, CoreTypeProvider typeProvider) { - Scope scope = unit.getLibrary().getElement().getScope(); - exec(unit, context, scope, typeProvider); - } - - @VisibleForTesting - public void exec(DartUnit unit, DartCompilerContext compilerContext, Scope scope, - CoreTypeProvider typeProvider) { - libraryElement = unit.getLibrary().getElement(); - topLevelContext = new ResolutionContext(scope, compilerContext, typeProvider); - unit.accept(new MemberElementBuilder(typeProvider)); - } - - /** - * Creates elements for the fields, methods and constructors of a class. The - * elements are added to the ClassElement. - * - * TODO(ngeoffray): Errors reported: - * - Duplicate member names in the same class. - * - Unresolved types. - */ - private class MemberElementBuilder extends ResolveVisitor { - EnclosingElement currentHolder; - private EnclosingElement enclosingElement; - private ResolutionContext context; - private boolean isStatic; - private boolean isFactory; - - MemberElementBuilder(CoreTypeProvider typeProvider) { - super(typeProvider); - context = topLevelContext; - currentHolder = libraryElement; - } - - @Override - ResolutionContext getContext() { - return context; - } - - @Override - protected EnclosingElement getEnclosingElement() { - return enclosingElement; - } - - @Override - public Element visitClass(DartClass node) { - assert !ElementKind.of(currentHolder).equals(ElementKind.CLASS) : "nested class?"; - beginClassContext(node); - ClassElement classElement = node.getElement(); - EnclosingElement previousEnclosingElement = enclosingElement; - enclosingElement = classElement; - // visit fields, to make their Elements ready for constructor parameters - for (DartNode member : node.getMembers()) { - if (member instanceof DartFieldDefinition) { - member.accept(this); - } - } - // visit all other members - for (DartNode member : node.getMembers()) { - if (!(member instanceof DartFieldDefinition)) { - member.accept(this); - } - } - // check constructor names - for (ConstructorElement constructor : classElement.getConstructors()) { - String name = constructor.getName(); - SourceInfo nameLocation = constructor.getNameLocation(); - // should be name of immediately enclosing class - if (constructor.getModifiers().isFactory()) { - String rawName = constructor.getRawName(); - String consClassName = StringUtils.substringBefore(rawName, "."); - String consUserName = StringUtils.substringAfter(rawName, "."); - if (!StringUtils.equals(consClassName, classElement.getName())) { - // report error for for M part of M.id or pure M - SourceInfo consClassLocation = new SourceInfo(nameLocation.getSource(), - nameLocation.getOffset(), consClassName.length()); - resolutionError(consClassLocation, - ResolverErrorCode.CONSTRUCTOR_NAME_NOT_ENCLOSING_CLASS); - // in addition also report warning for whole constructor name - if (!StringUtils.isEmpty(consUserName)) { - resolutionError(nameLocation, - ResolverErrorCode.CONSTRUCTOR_NAME_NOT_ENCLOSING_CLASS_ID); - } - } - } - // should not conflict with member names - { - Element member = classElement.lookupLocalElement(name); - if (member != null) { - resolutionError(nameLocation, - ResolverErrorCode.CONSTRUCTOR_WITH_NAME_OF_MEMBER); - } - } - } - // done with this class - enclosingElement = previousEnclosingElement; - endClassContext(); - return null; - } - - private void checkParameterInitializer(DartMethodDefinition method, DartParameter parameter) { - if (Elements.isNonFactoryConstructor(method.getElement())) { - if (method.getModifiers().isRedirectedConstructor()) { - resolutionError(parameter.getName(), - ResolverErrorCode.PARAMETER_INIT_WITH_REDIR_CONSTRUCTOR); - } - - FieldElement element = - Elements.lookupLocalField((ClassElement) currentHolder, parameter.getParameterName()); - if (element == null) { - resolutionError(parameter, ResolverErrorCode.PARAMETER_NOT_MATCH_FIELD, - parameter.getName()); - } else if (element.isStatic()) { - resolutionError(parameter, - ResolverErrorCode.PARAMETER_INIT_STATIC_FIELD, - parameter.getName()); - } - - // Field parameters are not visible as parameters, so we do not declare them - // in the context. Instead we record the resolved field element. - Elements.setParameterInitializerElement(parameter.getElement(), element); - - // The editor expects the referenced elements to be non-null - DartPropertyAccess prop = (DartPropertyAccess)parameter.getName(); - prop.setElement(element); - prop.getName().setElement(element); - - // If no type specified, use type of field. - if (parameter.getTypeNode() == null && element != null) { - Elements.setType(parameter.getElement(), element.getType()); - } - } else { - resolutionError(parameter.getName(), - ResolverErrorCode.PARAMETER_INIT_OUTSIDE_CONSTRUCTOR); - } - } - - @Override - public Element visitFunctionTypeAlias(DartFunctionTypeAlias node) { - isStatic = false; - isFactory = false; - assert !ElementKind.of(currentHolder).equals(ElementKind.CLASS) : "nested class?"; - FunctionAliasElement element = node.getElement(); - currentHolder = element; - context = context.extend((ClassElement) currentHolder); // Put type variables in scope. - visit(node.getTypeParameters()); - List parameters = new ArrayList(); - for (DartParameter parameter : node.getParameters()) { - parameters.add((VariableElement) parameter.accept(this)); - } - Type returnType = resolveType(node.getReturnTypeNode(), false, false, true, - TypeErrorCode.NO_SUCH_TYPE, TypeErrorCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS); - ClassElement functionElement = getTypeProvider().getFunctionType().getElement(); - element.setFunctionType(Types.makeFunctionType(getContext(), functionElement, - parameters, returnType)); - currentHolder = libraryElement; - context = topLevelContext; - return null; - } - - @Override - public Element visitMethodDefinition(final DartMethodDefinition method) { - isFactory = method.getModifiers().isFactory(); - isStatic = method.getModifiers().isStatic() || isFactory; - MethodNodeElement element = method.getElement(); - if (element == null) { - switch (getMethodKind(method)) { - case NONE: - case CONSTRUCTOR: - element = buildConstructor(method); - checkConstructor(element, method); - addConstructor((ClassElement) currentHolder, (ConstructorNodeElement) element); - break; - - case METHOD: - element = Elements.methodFromMethodNode(method, currentHolder); - addMethod(currentHolder, element); - break; - } - } else { - // This is a top-level element, and an element was already created in - // TopLevelElementBuilder. - Elements.addMethod(currentHolder, element); - assertTopLevel(method); - } - if (element != null) { - checkTopLevelMainFunction(method); - checkModifiers(element, method); - recordElement(method, element); - recordElement(method.getName(), element); - ResolutionContext previous = context; - context = context.extend(element.getName()); - EnclosingElement previousEnclosingElement = enclosingElement; - enclosingElement = element; - resolveFunction(method.getFunction(), element); - enclosingElement = previousEnclosingElement; - context = previous; - } - return null; - } - - @Override - protected void resolveFunctionWithParameters(DartFunction node, MethodElement element) { - super.resolveFunctionWithParameters(node, element); - // Bind "formal initializers" to fields. - if (node.getParent() instanceof DartMethodDefinition) { - DartMethodDefinition method = (DartMethodDefinition) node.getParent(); - for (DartParameter parameter : node.getParameters()) { - if (parameter.getQualifier() instanceof DartThisExpression) { - checkParameterInitializer(method, parameter); - } - } - } - } - - @Override - public Element visitFieldDefinition(DartFieldDefinition node) { - isStatic = false; - isFactory = false; - for (DartField fieldNode : node.getFields()) { - if (fieldNode.getModifiers().isStatic()) { - isStatic = true; - } - } - Type type = resolveType(node.getTypeNode(), isStatic, false, true, TypeErrorCode.NO_SUCH_TYPE, - TypeErrorCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS); - for (DartField fieldNode : node.getFields()) { - if (fieldNode.getModifiers().isAbstractField()) { - buildAbstractField(fieldNode); - } else { - buildField(fieldNode, type); - } - } - return null; - } - - private void beginClassContext(final DartClass node) { - assert !ElementKind.of(currentHolder).equals(ElementKind.CLASS) : "nested class?"; - currentHolder = node.getElement(); - context = context.extend((ClassElement) currentHolder); - } - - private void endClassContext() { - currentHolder = libraryElement; - context = topLevelContext; - } - - private Element resolveConstructorName(final DartMethodDefinition method) { - return method.getName().accept(new ASTVisitor() { - @Override - public Element visitPropertyAccess(DartPropertyAccess node) { - Element element = context.resolveName(node); - if (ElementKind.of(element) == ElementKind.CLASS) { - return resolveType(node); - } else { - element = node.getQualifier().accept(this); - recordElement(node.getQualifier(), element); - } - if (ElementKind.of(element) == ElementKind.CLASS) { - return Elements.constructorFromMethodNode( - method, node.getPropertyName(), (ClassElement) currentHolder, (ClassElement) element); - } else { - // Nothing else is valid. Already warned in getMethodKind(). - return getTypeProvider().getDynamicType().getElement(); - } - } - @Override - public Element visitIdentifier(DartIdentifier node) { - return resolveType(node); - } - private Element resolveType(DartNode node) { - return context.resolveType( - node, - node, - null, - true, - false, - false, - ResolverErrorCode.NO_SUCH_TYPE_CONSTRUCTOR, - ResolverErrorCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS).getElement(); - } - @Override - public Element visitParameterizedTypeNode(DartParameterizedTypeNode node) { - Element element = node.getExpression().accept(this); - if (ElementKind.of(element).equals(ElementKind.CONSTRUCTOR)) { - recordElement(node.getExpression(), currentHolder); - } else { - recordElement(node.getExpression(), element); - } - return element; - } - @Override - public Element visitNode(DartNode node) { - throw new RuntimeException("Unexpected node " + node); - } - }); - } - - private MethodNodeElement buildConstructor(final DartMethodDefinition method) { - // Resolve the constructor's name and class name. - Element e = resolveConstructorName(method); - - switch (ElementKind.of(e)) { - default: - // Report an error and create a fake constructor element below. - resolutionError(method.getName(), ResolverErrorCode.INVALID_TYPE_NAME_IN_CONSTRUCTOR); - break; - - case DYNAMIC: - case CLASS: - break; - - case CONSTRUCTOR: - return (ConstructorNodeElement) e; - } - - // If the constructor name resolves to a class or there was an error, - // create the unnamed constructor. - return Elements.constructorFromMethodNode(method, "", (ClassElement) currentHolder, - (ClassElement) e); - } - - private FieldElement buildField(DartField fieldNode, Type type) { - assert !fieldNode.getModifiers().isAbstractField(); - Modifiers modifiers = fieldNode.getModifiers(); - // top-level fields are implicitly static. - if (context == topLevelContext) { - modifiers = modifiers.makeStatic(); - } - if (fieldNode.getValue() != null) { - modifiers = modifiers.makeInitialized(); - } - FieldNodeElement fieldElement = fieldNode.getElement(); - if (fieldElement == null) { - fieldElement = Elements.fieldFromNode(fieldNode, currentHolder, fieldNode.getObsoleteMetadata(), - modifiers); - addField(currentHolder, fieldElement); - } else { - // This is a top-level element, and an element was already created in - // TopLevelElementBuilder. - Elements.addField(currentHolder, fieldElement); - assertTopLevel(fieldNode); - } - fieldElement.setType(type); - recordElement(fieldNode.getName(), fieldElement); - return recordElement(fieldNode, fieldElement); - } - - private void assertTopLevel(DartNode node) throws AssertionError { - if (!currentHolder.getKind().equals(ElementKind.LIBRARY)) { - throw topLevelContext.internalError(node, "expected top-level node"); - } - } - - /** - * Creates FieldElement for AST getters and setters. - * - * class A { - * int get foo() { ... } - * set foo(x) { ... } - * } - * - * The AST will have the shape (simplified): - * DartClass - * members - * DartFieldDefinition - * DartField - * + name: foo - * + modifiers: abstractfield - * + accessor: int get foo() { ... } - * DartFieldDefinition - * DartField - * + name: foo - * + modifiers: abstractfield - * + accessor: set foo(x) { ... } - * - * MemberBuilder will reduce to one class element as below (simplified): - * ClassElement - * members: - * FieldElement - * + name: foo - * + getter: - * MethodElement - * + name: foo - * + function: int get foo() { ... } - * + setter: - * MethodElement - * + name: foo - * + function: set foo(x) { ... } - * - */ - private FieldElement buildAbstractField(DartField fieldNode) { - assert fieldNode.getModifiers().isAbstractField(); - boolean topLevelDefinition = fieldNode.getParent().getParent() instanceof DartUnit; - DartMethodDefinition accessorNode = fieldNode.getAccessor(); - MethodNodeElement accessorElement = Elements.methodFromMethodNode(accessorNode, currentHolder); - EnclosingElement previousEnclosingElement = enclosingElement; - enclosingElement = accessorElement; - recordElement(accessorNode, accessorElement); - resolveFunction(accessorNode.getFunction(), accessorElement); - enclosingElement = previousEnclosingElement; - - String name = fieldNode.getName().getName(); - Element element = null; - if (currentHolder != null) { - element = currentHolder.lookupLocalElement(name); - if (element == null) { - element = currentHolder.lookupLocalElement("setter " + name); - } - } else { - // Top level nodes are not handled gracefully - Scope scope = topLevelContext.getScope(); - LibraryElement library = context.getScope().getLibrary(); - element = scope.findElement(library, name); - if (element == null) { - element = scope.findElement(library, "setter " + name); - } - } - - FieldElementImplementation fieldElement = null; - if (element == null || element.getKind().equals(ElementKind.FIELD) - && element.getModifiers().isAbstractField()) { - fieldElement = (FieldElementImplementation) element; - } - - if (accessorNode.getModifiers().isGetter() && fieldElement != null && fieldElement.getSetter() != null) { - MethodNodeElement oldSetter = fieldElement.getSetter(); - fieldElement = Elements.fieldFromNode(fieldNode, currentHolder, fieldNode.getObsoleteMetadata(), - fieldNode.getModifiers()); - fieldElement.setSetter(oldSetter); - addField(currentHolder, fieldElement); - } - - if (fieldElement == null) { - fieldElement = Elements.fieldFromNode(fieldNode, currentHolder, fieldNode.getObsoleteMetadata(), - fieldNode.getModifiers()); - addField(currentHolder, fieldElement); - } - - if (accessorNode.getModifiers().isGetter()) { - if (fieldElement.getGetter() != null) { - if (!topLevelDefinition) { - reportDuplicateDeclaration(ResolverErrorCode.DUPLICATE_MEMBER, fieldElement.getGetter()); - reportDuplicateDeclaration(ResolverErrorCode.DUPLICATE_MEMBER, accessorElement); - } - } else { - fieldElement.setGetter(accessorElement); - fieldElement.setType(accessorElement.getReturnType()); - } - } else if (accessorNode.getModifiers().isSetter()) { - if (fieldElement.getSetter() != null) { - if (!topLevelDefinition) { - reportDuplicateDeclaration(ResolverErrorCode.DUPLICATE_MEMBER, fieldElement.getSetter()); - reportDuplicateDeclaration(ResolverErrorCode.DUPLICATE_MEMBER, accessorElement); - } - } else { - fieldElement.setSetter(accessorElement); - List parameters = accessorElement.getParameters(); - Type type; - if (parameters.size() == 0) { - // Error flagged in parser - type = getTypeProvider().getDynamicType(); - } else { - type = parameters.get(0).getType(); - } - fieldElement.setType(type); - } - } - recordElement(fieldNode.getName(), accessorElement); - return recordElement(fieldNode, fieldElement); - } - - private void addField(EnclosingElement holder, FieldNodeElement element) { - if (holder != null) { - checkUniqueName(holder, element); - checkMemberNameNotSameAsEnclosingClassName(holder, element); - Elements.addField(holder, element); - } - } - - private void addMethod(EnclosingElement holder, MethodNodeElement element) { - checkUniqueName(holder, element); - checkMemberNameNotSameAsEnclosingClassName(holder, element); - Elements.addMethod(holder, element); - } - - private void addConstructor(ClassElement cls, ConstructorNodeElement element) { - checkUniqueName(cls, element); - Elements.addConstructor(cls, element); - } - - private ElementKind getMethodKind(DartMethodDefinition method) { - if (!ElementKind.of(currentHolder).equals(ElementKind.CLASS)) { - return ElementKind.METHOD; - } - - if (method.getModifiers().isFactory()) { - return ElementKind.CONSTRUCTOR; - } - - DartExpression name = method.getName(); - if (name instanceof DartIdentifier) { - if (((DartIdentifier) name).getName().equals(currentHolder.getName())) { - return ElementKind.CONSTRUCTOR; - } else { - return ElementKind.METHOD; - } - } else { - DartPropertyAccess property = (DartPropertyAccess) name; - if (property.getQualifier() instanceof DartIdentifier) { - DartIdentifier qualifier = (DartIdentifier) property.getQualifier(); - if (qualifier.getName().equals(currentHolder.getName())) { - return ElementKind.CONSTRUCTOR; - } - resolutionError(method.getName(), - ResolverErrorCode.CANNOT_DECLARE_NON_FACTORY_CONSTRUCTOR); - } else if (property.getQualifier() instanceof DartParameterizedTypeNode) { - DartParameterizedTypeNode paramNode = (DartParameterizedTypeNode)property.getQualifier(); - if (paramNode.getExpression() instanceof DartIdentifier) { - return ElementKind.CONSTRUCTOR; - } - resolutionError(method.getName(), - ResolverErrorCode.TOO_MANY_QUALIFIERS_FOR_METHOD); - } else { - // Multiple qualifiers (Foo.bar.baz) - resolutionError(method.getName(), - ResolverErrorCode.TOO_MANY_QUALIFIERS_FOR_METHOD); - } - } - - return ElementKind.NONE; - } - - /** - * Checks that top-level "main()" has no parameters. - */ - private void checkTopLevelMainFunction(DartMethodDefinition method) { - if (!method.getFunction().getParameters().isEmpty() - && currentHolder instanceof LibraryElement - && Objects.equal(method.getName().toString(), "main")) { - resolutionError(method.getName(), ResolverErrorCode.MAIN_FUNCTION_PARAMETERS); - } - } - - private void checkModifiers(MethodElement element, DartMethodDefinition method) { - Modifiers modifiers = method.getModifiers(); - boolean isNonFactoryConstructor = Elements.isNonFactoryConstructor(element); - // TODO(ngeoffray): The errors should report the position of the modifier. - if (isNonFactoryConstructor) { - if (modifiers.isStatic()) { - resolutionError(method.getName(), ResolverErrorCode.CONSTRUCTOR_CANNOT_BE_STATIC); - } - if (modifiers.isAbstract()) { - resolutionError(method.getName(), ResolverErrorCode.CONSTRUCTOR_CANNOT_BE_ABSTRACT); - } - if (modifiers.isConstant()) { - // Allow const ... native ... ; type of constructors. Used in core libraries. - DartBlock dartBlock = method.getFunction().getBody(); - if (dartBlock != null && !(dartBlock instanceof DartNativeBlock)) { - resolutionError(method.getName(), - ResolverErrorCode.CONST_CONSTRUCTOR_CANNOT_HAVE_BODY); - } - } - } - - if (modifiers.isFactory()) { - if (modifiers.isConstant()) { - // Allow const factory ... native ... ; type of constructors, used in core libraries. - // Allow const factory redirecting. - DartBlock dartBlock = method.getFunction().getBody(); - if (!(dartBlock instanceof DartNativeBlock || method.getRedirectedTypeName() != null)) { - resolutionError(method.getName(), ResolverErrorCode.FACTORY_CANNOT_BE_CONST); - } - } - } - // TODO(ngeoffray): Add more checks on the modifiers. For - // example const and missing body. - } - - private void checkConstructor(MethodElement element, DartMethodDefinition method) { - if (Elements.isNonFactoryConstructor(element) && method.getFunction() != null - && method.getFunction().getReturnTypeNode() != null) { - resolutionError(method.getFunction().getReturnTypeNode(), - ResolverErrorCode.CONSTRUCTOR_CANNOT_HAVE_RETURN_TYPE); - } - } - - private void checkMemberNameNotSameAsEnclosingClassName(EnclosingElement holder, Element e) { - if (ElementKind.of(holder) == ElementKind.CLASS) { - if (Objects.equal(holder.getName(), e.getName())) { - resolutionError(e.getNameLocation(), ResolverErrorCode.MEMBER_WITH_NAME_OF_CLASS); - } - } - } - - private void checkUniqueName(EnclosingElement holder, Element e) { - if (ElementKind.of(holder) == ElementKind.LIBRARY) { - return; - } - Element other = lookupElementByName(holder, e.getName(), e.getModifiers()); - assert e != other : "forgot to call checkUniqueName() before adding to the class?"; - - if (other == null && e instanceof FieldElement) { - FieldElement eField = (FieldElement) e; - if (!eField.getModifiers().isAbstractField()) { - other = lookupElementByName(holder, "setter " + e.getName(), e.getModifiers()); - } - if (eField.getModifiers().isAbstractField() - && StringUtils.startsWith(e.getName(), "setter ")) { - Element other2 = lookupElementByName(holder, - StringUtils.removeStart(e.getName(), "setter "), e.getModifiers()); - if (other2 instanceof FieldElement) { - FieldElement otherField = (FieldElement) other2; - if (!otherField.getModifiers().isAbstractField()) { - other = otherField; - } - } - } - } - - if (other != null) { - ElementKind eKind = ElementKind.of(e); - ElementKind oKind = ElementKind.of(other); - - // Constructors have a separate namespace. - boolean oIsConstructor = oKind.equals(ElementKind.CONSTRUCTOR); - boolean eIsConstructor = eKind.equals(ElementKind.CONSTRUCTOR); - if (oIsConstructor != eIsConstructor) { - return; - } - - // Both can be constructors, as long as they're for different classes. - if (oIsConstructor && eIsConstructor) { - if (((ConstructorElement) e).getConstructorType() != - ((ConstructorElement) other).getConstructorType()) { - return; - } - } - - boolean eIsOperator = e.getModifiers().isOperator(); - boolean oIsOperator = other.getModifiers().isOperator(); - if (oIsOperator != eIsOperator) { - return; - } - - // Operators and methods can share the same name. - boolean oIsMethod = oKind.equals(ElementKind.METHOD); - boolean eIsMethod = eKind.equals(ElementKind.METHOD); - if ((oIsOperator && eIsMethod) || (oIsMethod && eIsOperator)) { - return; - } - - // Report initial declaration and current declaration. - reportDuplicateDeclaration(ResolverErrorCode.DUPLICATE_MEMBER, other); - reportDuplicateDeclaration(ResolverErrorCode.DUPLICATE_MEMBER, e); - } - } - - private Element lookupElementByName(EnclosingElement holder, String name, Modifiers modifiers) { - Element element = holder.lookupLocalElement(name); - if (element == null && ElementKind.of(holder).equals(ElementKind.CLASS)) { - ClassElement cls = (ClassElement) holder; - String ctorName = name.equals(holder.getName()) ? "" : name; - for (Element e : cls.getConstructors()) { - if (e.getName().equals(ctorName)) { - return e; - } - } - } - return element; - } - - void resolutionError(HasSourceInfo node, ErrorCode errorCode, Object... arguments) { - resolutionError(node.getSourceInfo(), errorCode, arguments); - } - - void resolutionError(SourceInfo sourceInfo, ErrorCode errorCode, Object... arguments) { - topLevelContext.onError(sourceInfo, errorCode, arguments); - } - - /** - * Reports duplicate declaration for given named element. - */ - private void reportDuplicateDeclaration(ErrorCode errorCode, Element element) { - String name = - element instanceof MethodElement - ? Elements.getRawMethodName((MethodElement) element) - : element.getName(); - resolutionError(element.getNameLocation(), errorCode, name); - } - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/MethodElement.java b/compiler/java/com/google/dart/compiler/resolver/MethodElement.java deleted file mode 100644 index 43e88cece034..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/MethodElement.java +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.dart.compiler.type.FunctionType; -import com.google.dart.compiler.type.Type; - -import java.util.List; -import java.util.Set; - -public interface MethodElement extends Element, EnclosingElement { - boolean isConstructor(); - - boolean isStatic(); - - boolean hasBody(); - - List getParameters(); - - Type getReturnType(); - - FunctionType getFunctionType(); - - /** - * @return {@link Element}s overridden by this {@link MethodElement}. - */ - Set getOverridden(); -} diff --git a/compiler/java/com/google/dart/compiler/resolver/MethodElementImplementation.java b/compiler/java/com/google/dart/compiler/resolver/MethodElementImplementation.java deleted file mode 100644 index 74ca6091506c..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/MethodElementImplementation.java +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.ImmutableSet; -import com.google.dart.compiler.ast.DartBlock; -import com.google.dart.compiler.ast.DartClass; -import com.google.dart.compiler.ast.DartFunctionExpression; -import com.google.dart.compiler.ast.DartIdentifier; -import com.google.dart.compiler.ast.DartMethodDefinition; -import com.google.dart.compiler.ast.DartNativeBlock; -import com.google.dart.compiler.ast.DartNode; -import com.google.dart.compiler.ast.DartObsoleteMetadata; -import com.google.dart.compiler.ast.Modifiers; -import com.google.dart.compiler.common.SourceInfo; -import com.google.dart.compiler.type.FunctionType; -import com.google.dart.compiler.type.Type; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Set; - -class MethodElementImplementation extends AbstractNodeElement implements MethodNodeElement { - private final DartObsoleteMetadata metadata; - private final Modifiers modifiers; - private final EnclosingElement holder; - private final ElementKind kind; - private final List parameters = new ArrayList(); - private FunctionType type; - private final SourceInfo nameLocation; - private final boolean hasBody; - private Set overridden = ImmutableSet.of(); - - // TODO(ngeoffray): name, return type, argument types. - @VisibleForTesting - MethodElementImplementation(DartFunctionExpression node, String name, Modifiers modifiers) { - super(node, name); - this.metadata = DartObsoleteMetadata.EMPTY; - this.modifiers = modifiers; - this.hasBody = true; - this.holder = findParentEnclosingElement(node); - this.kind = ElementKind.FUNCTION_OBJECT; - if (node != null && node.getName() != null) { - this.nameLocation = node.getName().getSourceInfo(); - } else { - this.nameLocation = SourceInfo.UNKNOWN; - } - } - - protected MethodElementImplementation(DartMethodDefinition node, String name, - EnclosingElement holder) { - super(node, name); - if (node != null) { - this.metadata = node.getObsoleteMetadata(); - this.modifiers = node.getModifiers(); - this.nameLocation = node.getName().getSourceInfo(); - DartBlock body = node.getFunction().getBody(); - this.hasBody = body != null && !(body instanceof DartNativeBlock); - } else { - this.metadata = DartObsoleteMetadata.EMPTY; - this.modifiers = Modifiers.NONE; - this.nameLocation = SourceInfo.UNKNOWN; - this.hasBody = false; - } - this.holder = holder; - this.kind = ElementKind.METHOD; - } - - @Override - public DartObsoleteMetadata getMetadata() { - return metadata; - } - - @Override - public Modifiers getModifiers() { - return modifiers; - } - - @Override - public ElementKind getKind() { - return kind; - } - - @Override - public EnclosingElement getEnclosingElement() { - return holder; - } - - @Override - public boolean isConstructor() { - return false; - } - - @Override - public boolean isStatic() { - return getModifiers().isStatic(); - } - - @Override - public List getParameters() { - return parameters; - } - - @Override - public boolean hasBody() { - return hasBody; - } - - void addParameter(VariableElement parameter) { - parameters.add(parameter); - } - - @Override - public Type getReturnType() { - return getType().getReturnType(); - } - - @Override - void setType(Type type) { - this.type = (FunctionType) type; - } - - @Override - public FunctionType getType() { - return type; - } - - @Override - public FunctionType getFunctionType() { - return getType(); - } - - @Override - public boolean isInterface() { - return false; - } - - @Override - public Iterable getMembers() { - return Collections.emptyList(); - } - - @Override - public Element lookupLocalElement(String name) { - return null; - } - - public static MethodElementImplementation fromMethodNode(DartMethodDefinition node, - EnclosingElement holder) { - String targetName; - if(node.getName() instanceof DartIdentifier) { - targetName = ((DartIdentifier) node.getName()).getName(); - if (targetName.equals("-") && node.getFunction().getParameters().size() == 1) { - targetName += "binary"; - } - } else { - // Visit the unknown node to generate a string for our use. - targetName = node.toSource(); - } - return new MethodElementImplementation(node, targetName, holder); - } - - public static MethodElementImplementation fromFunctionExpression(DartFunctionExpression node, - Modifiers modifiers) { - return new MethodElementImplementation(node, node.getFunctionName(), modifiers); - } - - /** - * @return the innermost {@link EnclosingElement} for given {@link DartNode}, may be - * null. - */ - private static EnclosingElement findParentEnclosingElement(DartNode node) { - while (node != null && node.getParent() != null) { - node = node.getParent(); - boolean isEnclosingNode = node instanceof DartClass || node instanceof DartMethodDefinition - || node instanceof DartFunctionExpression; - if (isEnclosingNode && node.getElement() instanceof EnclosingElement) { - return (EnclosingElement) node.getElement(); - } - } - return null; - } - - @Override - public SourceInfo getNameLocation() { - return nameLocation; - } - - public void setOverridden(Set overridden) { - this.overridden = overridden; - } - - public Set getOverridden() { - return overridden; - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/MethodNodeElement.java b/compiler/java/com/google/dart/compiler/resolver/MethodNodeElement.java deleted file mode 100644 index 46db96591233..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/MethodNodeElement.java +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. -package com.google.dart.compiler.resolver; - -import com.google.dart.compiler.ast.DartNode; - -/** - * Extension of {@link MethodElement} which is based on {@link DartNode}. - */ -public interface MethodNodeElement extends MethodElement, NodeElement { -} diff --git a/compiler/java/com/google/dart/compiler/resolver/MixinScope.java b/compiler/java/com/google/dart/compiler/resolver/MixinScope.java deleted file mode 100644 index e40ff71f0e0b..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/MixinScope.java +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -/** - * Lexical scope corresponding to a mixin. - */ -class MixinScope extends Scope { - private final ClassElement mixinElement; - - MixinScope(ClassElement mixinElement) { - super(mixinElement.getName(), mixinElement.getLibrary(), null); - this.mixinElement = mixinElement; - } - - @Override - public Element declareElement(String name, Element element) { - throw new AssertionError("not supported yet"); - } - - @Override - public Element findLocalElement(String name) { - return Elements.findElement(mixinElement, name); - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/NodeElement.java b/compiler/java/com/google/dart/compiler/resolver/NodeElement.java deleted file mode 100644 index 215efb26fe59..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/NodeElement.java +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. -package com.google.dart.compiler.resolver; - -import com.google.dart.compiler.ast.DartNode; - -/** - * {@link Element} which has {@link DartNode}. - */ -public interface NodeElement extends Element { - DartNode getNode(); -} diff --git a/compiler/java/com/google/dart/compiler/resolver/ResolutionContext.java b/compiler/java/com/google/dart/compiler/resolver/ResolutionContext.java deleted file mode 100644 index c1522c3a7a09..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/ResolutionContext.java +++ /dev/null @@ -1,408 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; -import com.google.common.annotations.VisibleForTesting; -import com.google.dart.compiler.DartCompilationError; -import com.google.dart.compiler.DartCompilerContext; -import com.google.dart.compiler.ErrorCode; -import com.google.dart.compiler.ErrorSeverity; -import com.google.dart.compiler.PackageLibraryManager; -import com.google.dart.compiler.Source; -import com.google.dart.compiler.SubSystem; -import com.google.dart.compiler.ast.ASTVisitor; -import com.google.dart.compiler.ast.DartClassTypeAlias; -import com.google.dart.compiler.ast.DartFunctionExpression; -import com.google.dart.compiler.ast.DartFunctionTypeAlias; -import com.google.dart.compiler.ast.DartIdentifier; -import com.google.dart.compiler.ast.DartNode; -import com.google.dart.compiler.ast.DartPropertyAccess; -import com.google.dart.compiler.ast.DartSyntheticErrorIdentifier; -import com.google.dart.compiler.ast.DartTypeNode; -import com.google.dart.compiler.ast.LibraryUnit; -import com.google.dart.compiler.ast.Modifiers; -import com.google.dart.compiler.common.HasSourceInfo; -import com.google.dart.compiler.common.SourceInfo; -import com.google.dart.compiler.parser.DartParser; -import com.google.dart.compiler.type.InterfaceType; -import com.google.dart.compiler.type.Type; -import com.google.dart.compiler.type.TypeKind; -import com.google.dart.compiler.type.TypeVariable; -import com.google.dart.compiler.type.Types; - -import java.util.Arrays; -import java.util.List; - - -/** - * Resolution context for resolution of Dart programs. The initial context is - * derived from the library scope, which is then extended with class scope, - * method scope, and block scope as the program is traversed. - */ -@VisibleForTesting -public class ResolutionContext implements ResolutionErrorListener { - private Scope scope; - private final DartCompilerContext context; - private final CoreTypeProvider typeProvider; - private final boolean suppressSdkWarnings; - - ResolutionContext(String name, LibraryElement library, DartCompilerContext context, - CoreTypeProvider typeProvider) { - this(new Scope(name, library), context, typeProvider); - } - - @VisibleForTesting - public ResolutionContext(Scope scope, DartCompilerContext context, - CoreTypeProvider typeProvider) { - this.scope = scope; - this.context = context; - this.typeProvider = typeProvider; - this.suppressSdkWarnings = context.getCompilerConfiguration().getCompilerOptions() - .suppressSdkWarnings(); - } - - ResolutionContext(LibraryUnit unit, DartCompilerContext context, CoreTypeProvider typeProvider) { - this(unit.getElement().getScope(), context, typeProvider); - } - - @VisibleForTesting - public ResolutionContext extend(ClassElement element) { - return new ResolutionContext(new ClassScope(element, scope), context, typeProvider); - } - - ResolutionContext extend(String name) { - return new ResolutionContext(new Scope(name, scope.getLibrary(), scope), context, typeProvider); - } - - Scope getScope() { - return scope; - } - - void declare(Element element, ErrorCode errorCode) { - String name = element.getName(); - Element existingLocalElement = scope.findLocalElement(name); - // Check for duplicate declaration in the same scope. - if (existingLocalElement != null && errorCode != null) { - SourceInfo nameSourceInfo = element.getNameLocation(); - String existingLocation = Elements.getRelativeElementLocation(element, existingLocalElement); - onError(nameSourceInfo, errorCode, name, existingLocation); - } - // Declare, may be hide existing element. - scope.declareElement(name, element); - } - - void pushScope(String name) { - scope = new Scope(name, scope.getLibrary(), scope); - } - - void popScope() { - scope = scope.getParent(); - } - - /** - * Returns true if the type is dynamic or an interface type where - * {@link ClassElement#isInterface()} equals isInterface. - */ - private boolean isInterfaceEquals(Type type, boolean isInterface) { - switch (type.getKind()) { - case DYNAMIC: - // Considered to be a match. - return true; - - case INTERFACE: - InterfaceType interfaceType = (InterfaceType) type; - ClassElement element = interfaceType.getElement(); - return (element != null && element.isInterface() == isInterface); - - default: - break; - } - - return false; - } - - /** - * Returns true if the type is dynamic or is a class type. - */ - private boolean isClassType(Type type) { - return isInterfaceEquals(type, false); - } - - /** - * Returns true if the type is a class or interface type. - */ - private boolean isClassOrInterfaceType(Type type) { - return type.getKind() == TypeKind.INTERFACE - && ((InterfaceType) type).getElement() != null; - } - - /** - * To resolve the class specified for extends on a class definition. - */ - InterfaceType resolveClass(DartTypeNode node, boolean isStatic, boolean isFactory) { - if (node == null) { - return null; - } - - Type type = resolveType(node, isStatic, isFactory, false, ResolverErrorCode.NO_SUCH_TYPE, - ResolverErrorCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS); - if (!isClassType(type)) { - onError(node.getIdentifier(), ResolverErrorCode.NOT_A_CLASS, type); - type = typeProvider.getDynamicType(); - } - - node.setType(type); - return (InterfaceType) type; - } - - InterfaceType resolveInterface(DartTypeNode node, boolean isStatic, boolean isFactory) { - Type type = resolveType(node, isStatic, isFactory, false, - ResolverErrorCode.NO_SUCH_TYPE, ResolverErrorCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS); - if (type.getKind() != TypeKind.DYNAMIC && !isClassOrInterfaceType(type)) { - onError(node.getIdentifier(), ResolverErrorCode.NOT_A_CLASS_OR_INTERFACE, type); - type = typeProvider.getDynamicType(); - } - - node.setType(type); - return (InterfaceType) type; - } - - Type resolveType(DartTypeNode node, boolean isStatic, boolean isFactory, boolean isAnnotation, - ErrorCode errorCode, ErrorCode wrongNumberErrorCode) { - if (node == null) { - return null; - } else { - Type type = resolveType(node, node.getIdentifier(), node.getTypeArguments(), isStatic, - isFactory, isAnnotation, errorCode, wrongNumberErrorCode); - recordTypeIdentifier(node.getIdentifier(), type.getElement()); - return type; - } - } - - protected E recordTypeIdentifier(DartNode node, E element) { - node.getClass(); - if (node instanceof DartPropertyAccess) { - recordTypeIdentifier(((DartPropertyAccess)node).getQualifier(), - element.getEnclosingElement()); - return recordTypeIdentifier(((DartPropertyAccess)node).getName(), element); - } else if (node instanceof DartIdentifier) { - if (element == null) { - // TypeAnalyzer will diagnose unresolved identifiers. - return null; - } - node.setElement(element); - } else { - throw internalError(node, "Unexpected node: %s", node); - } - return element; - } - - Type resolveType(DartNode diagnosticNode, DartNode identifier, List typeArguments, - boolean isStatic, boolean isFactory, boolean isAnnotation, ErrorCode errorCode, - ErrorCode wrongNumberErrorCode) { - // Built-in identifier can not be used as a type annotation. - if (identifier instanceof DartIdentifier) { - String name = ((DartIdentifier) identifier).getName(); - if (DartParser.PSEUDO_KEYWORDS_SET.contains(name) && !"dynamic".equals(name) - && typeArguments.isEmpty()) { - onError(identifier, ResolverErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE, name); - return Types.newDynamicType(); - } - } - // OK, valid name for type. - Element element = resolveName(identifier); - ElementKind elementKind = ElementKind.of(element); - switch (elementKind) { - case TYPE_VARIABLE: { - TypeVariableElement typeVariableElement = (TypeVariableElement) element; - if (!isFactory && isStatic && - typeVariableElement.getDeclaringElement().getKind().equals(ElementKind.CLASS)) { - onError(identifier, ResolverErrorCode.TYPE_VARIABLE_IN_STATIC_CONTEXT, identifier); - return typeProvider.getDynamicType(); - } - return makeTypeVariable(typeVariableElement, typeArguments); - } - case CLASS: - case FUNCTION_TYPE_ALIAS: - case DYNAMIC: - return instantiateParameterizedType( - (ClassElement) element, - diagnosticNode, - typeArguments, - isStatic, - isFactory, - errorCode, - wrongNumberErrorCode); - case DUPLICATE: { - DuplicateElement duplicateElement = (DuplicateElement) element; - List locations = duplicateElement.getLocations(); - ResolverErrorCode duplicateErrorCode; - if (isAnnotation) { - duplicateErrorCode = ResolverErrorCode.DUPLICATE_IMPORTED_NAME_TYPE; - } else { - duplicateErrorCode = ResolverErrorCode.DUPLICATE_IMPORTED_NAME; - } - onError(identifier, duplicateErrorCode, element.getName(), locations.size(), locations); - return typeProvider.getDynamicType(); - } - case VOID: - return typeProvider.getVoidType(); - case NONE: - onError(identifier, errorCode, identifier); - return typeProvider.getDynamicType(); - default: - if (!(identifier instanceof DartSyntheticErrorIdentifier)) { - if (errorCode.getSubSystem().equals(SubSystem.RESOLVER)) { - onError(identifier, ResolverErrorCode.NOT_A_TYPE, identifier, elementKind); - } else { - onError(identifier, TypeErrorCode.NOT_A_TYPE, identifier, elementKind); - } - } - return typeProvider.getDynamicType(); - } - } - - InterfaceType instantiateParameterizedType(ClassElement element, DartNode node, - List typeArgumentNodes, - boolean isStatic, - boolean isFactory, - ErrorCode errorCode, - ErrorCode wrongNumberErrorCode) { - List typeParameters = element.getTypeParameters(); - Type[] typeArguments; - if (typeArgumentNodes == null || typeArgumentNodes.size() != typeParameters.size()) { - typeArguments = new Type[typeParameters.size()]; - for (int i = 0; i < typeArguments.length; i++) { - typeArguments[i] = typeProvider.getDynamicType(); - } - if (typeArgumentNodes != null && typeArgumentNodes.size() > 0) { - onError(node, wrongNumberErrorCode, element.getType(), typeArgumentNodes.size(), typeParameters.size()); - } - int index = 0; - if (typeArgumentNodes != null) { - for (DartTypeNode typeNode : typeArgumentNodes) { - Type type = resolveType(typeNode, isStatic, isFactory, false, errorCode, - wrongNumberErrorCode); - typeNode.setType(type); - if (index < typeArguments.length) { - typeArguments[index] = type; - } - index++; - } - } - } else { - typeArguments = new Type[typeArgumentNodes.size()]; - for (int i = 0; i < typeArguments.length; i++) { - typeArguments[i] = resolveType(typeArgumentNodes.get(i), isStatic, isFactory, false, errorCode, - wrongNumberErrorCode); - typeArgumentNodes.get(i).setType(typeArguments[i]); - } - } - return element.getType().subst(Arrays.asList(typeArguments), typeParameters); - } - - private TypeVariable makeTypeVariable(TypeVariableElement element, - List typeArguments) { - for (DartTypeNode typeArgument : typeArguments) { - onError(typeArgument, ResolverErrorCode.EXTRA_TYPE_ARGUMENT); - } - return element.getTypeVariable(); - } - - /* - * Interpret this node as a name reference, - */ - Element resolveName(DartNode node) { - Element result = node.accept(new Selector()); - if (result == null) { - if (Elements.isIdentifierName(node, "void")) { - return typeProvider.getVoidType().getElement(); - } - if (Elements.isIdentifierName(node, "dynamic")) { - return typeProvider.getDynamicType().getElement(); - } - } - return result; - } - - MethodElement declareFunction(DartFunctionExpression node) { - MethodElement element = Elements.methodFromFunctionExpression(node, Modifiers.NONE); - if (node.getFunctionName() != null) { - declare( - element, - ResolverErrorCode.DUPLICATE_FUNCTION_EXPRESSION); - } - return element; - } - - void pushFunctionScope(DartFunctionExpression x) { - pushScope(x.getFunctionName() == null ? "" : x.getFunctionName()); - } - - void pushFunctionAliasScope(DartFunctionTypeAlias x) { - pushScope(x.getName().getName() == null ? "" : x.getName().getName()); - } - - void pushClassAliasScope(DartClassTypeAlias x) { - pushScope(x.getName().getName() == null ? "" : x.getName().getName()); - } - - AssertionError internalError(HasSourceInfo node, String message, Object... arguments) { - message = String.format(message, arguments); - context.onError(new DartCompilationError(node, ResolverErrorCode.INTERNAL_ERROR, - message)); - return new AssertionError("Internal error: " + message); - } - - @Override - public void onError(HasSourceInfo hasSourceInfo, ErrorCode errorCode, Object... arguments) { - onError(hasSourceInfo.getSourceInfo(), errorCode, arguments); - } - - public void onError(SourceInfo sourceInfo, ErrorCode errorCode, Object... arguments) { - if (suppressSdkWarnings) { - ErrorSeverity errorSeverity = errorCode.getErrorSeverity(); - if (errorSeverity == ErrorSeverity.WARNING || errorSeverity == ErrorSeverity.INFO) { - Source source = sourceInfo.getSource(); - if (source != null && PackageLibraryManager.isDartUri(source.getUri())) { - return; - } - } - } - context.onError(new DartCompilationError(sourceInfo, errorCode, arguments)); - } - - class Selector extends ASTVisitor { - @Override - public Element visitNode(DartNode node) { - throw internalError(node, "Unexpected node: %s", node); - } - - @Override - public Element visitPropertyAccess(DartPropertyAccess node) { - Element element = node.getQualifier().accept(this); - if (element != null) { - switch (element.getKind()) { - case LIBRARY_PREFIX : - Scope elementScope = ((LibraryPrefixElement) element).getScope(); - return elementScope.findElement(scope.getLibrary(), node.getPropertyName()); - case CLASS : - return Elements.findElement((ClassElement) element, node.getPropertyName()); - } - } - return null; - } - - @Override - public Element visitIdentifier(DartIdentifier node) { - String name = node.getName(); - return scope.findElement(scope.getLibrary(), name); - } - - @Override - public Element visitSyntheticErrorIdentifier(DartSyntheticErrorIdentifier node) { - return Elements.dynamicElement(); - } - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/ResolutionErrorListener.java b/compiler/java/com/google/dart/compiler/resolver/ResolutionErrorListener.java deleted file mode 100644 index ff699398286c..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/ResolutionErrorListener.java +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.dart.compiler.ErrorCode; -import com.google.dart.compiler.common.HasSourceInfo; - -public interface ResolutionErrorListener { - - void onError(HasSourceInfo hasSourceInfo, ErrorCode errorCode, Object... arguments); -} diff --git a/compiler/java/com/google/dart/compiler/resolver/ResolveVisitor.java b/compiler/java/com/google/dart/compiler/resolver/ResolveVisitor.java deleted file mode 100644 index 20559ef66000..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/ResolveVisitor.java +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.dart.compiler.ErrorCode; -import com.google.dart.compiler.ast.ASTNodes; -import com.google.dart.compiler.ast.ASTVisitor; -import com.google.dart.compiler.ast.DartFunction; -import com.google.dart.compiler.ast.DartFunctionTypeAlias; -import com.google.dart.compiler.ast.DartIdentifier; -import com.google.dart.compiler.ast.DartNode; -import com.google.dart.compiler.ast.DartParameter; -import com.google.dart.compiler.ast.DartThisExpression; -import com.google.dart.compiler.ast.DartTypeNode; -import com.google.dart.compiler.ast.DartTypeParameter; -import com.google.dart.compiler.common.HasSourceInfo; -import com.google.dart.compiler.type.FunctionType; -import com.google.dart.compiler.type.Type; -import com.google.dart.compiler.type.Types; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; - -/** - * Shared visitor between Resolver and MemberBuilder. - */ -abstract class ResolveVisitor extends ASTVisitor { - private final CoreTypeProvider typeProvider; - - ResolveVisitor(CoreTypeProvider typeProvider) { - this.typeProvider = typeProvider; - } - - abstract ResolutionContext getContext(); - - final MethodElement resolveFunction(DartFunction node, MethodElement element) { - for (DartParameter parameter : node.getParameters()) { - Elements.addParameter(element, (VariableElement) parameter.accept(this)); - } - resolveFunctionWithParameters(node, element); - Type returnType = - resolveType( - node.getReturnTypeNode(), - element.getModifiers().isStatic(), - element.getModifiers().isFactory(), - true, - TypeErrorCode.NO_SUCH_TYPE, - TypeErrorCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS); - ClassElement functionElement = typeProvider.getFunctionType().getElement(); - FunctionType type = Types.makeFunctionType(getContext(), functionElement, - element.getParameters(), returnType); - Elements.setType(element, type); - for (DartParameter parameter : node.getParameters()) { - if (!(parameter.getQualifier() instanceof DartThisExpression) && - DartIdentifier.isPrivateName(parameter.getElement().getName())) { - if (parameter.getModifiers().isOptional()) { - getContext().onError(parameter.getName(), - ResolverErrorCode.OPTIONAL_PARAMETERS_CANNOT_START_WITH_UNDER); - } - if (parameter.getModifiers().isNamed()) { - getContext().onError(parameter.getName(), - ResolverErrorCode.NAMED_PARAMETERS_CANNOT_START_WITH_UNDER); - } - } - } - return element; - } - - /** - * Allows subclass to process {@link DartFunction} element with parameters, but before - * {@link FunctionType} is created for it. - */ - protected void resolveFunctionWithParameters(DartFunction node, MethodElement element) { - } - - final FunctionAliasElement resolveFunctionAlias(DartFunctionTypeAlias node) { - HashSet parameterNames = new HashSet(); - for (DartTypeParameter parameter : node.getTypeParameters()) { - TypeVariableElement typeVar = (TypeVariableElement) parameter.getElement(); - String parameterName = typeVar.getName(); - if (parameterNames.contains(parameterName)) { - getContext().onError(parameter, ResolverErrorCode.DUPLICATE_TYPE_VARIABLE, parameterName); - } else { - parameterNames.add(parameterName); - } - getContext().getScope().declareElement(parameterName, typeVar); - } - return null; - } - - @Override - public Element visitParameter(DartParameter node) { - Type type = resolveType(node.getTypeNode(), ASTNodes.isStaticContext(node), - ASTNodes.isFactoryContext(node), true, TypeErrorCode.NO_SUCH_TYPE, - TypeErrorCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS); - VariableElement element = - Elements.parameterElement( - getEnclosingElement(), - node, - node.getParameterName(), - node.getModifiers()); - List functionParameters = node.getFunctionParameters(); - if (functionParameters != null) { - List parameterElements = - new ArrayList(functionParameters.size()); - for (DartParameter parameter: functionParameters) { - parameterElements.add((VariableElement) parameter.accept(this)); - } - ClassElement functionElement = typeProvider.getFunctionType().getElement(); - type = Types.makeFunctionType(getContext(), functionElement, parameterElements, type); - } - Elements.setType(element, type); - recordElement(node.getName(), element); - return recordElement(node, element); - } - - protected EnclosingElement getEnclosingElement() { - return null; - } - - final Type resolveType(DartTypeNode node, boolean isStatic, boolean isFactory, - boolean isAnnotation, ErrorCode errorCode, ErrorCode wrongNumberErrorCode) { - if (node == null) { - return getTypeProvider().getDynamicType(); - } -// assert node.getType() == null || node.getType() instanceof DynamicType; - Type type = getContext().resolveType(node, isStatic, isFactory, isAnnotation, errorCode, - wrongNumberErrorCode); - if (type == null) { - type = getTypeProvider().getDynamicType(); - } - node.setType(type); - Element element = type.getElement(); - recordElement(node.getIdentifier(), element); - checkDeprecated(node, element); - return type; - } - - protected final void checkDeprecated(HasSourceInfo nameNode, Element element) { - if (element != null && element.getMetadata().isDeprecated()) { - getContext().onError(nameNode, TypeErrorCode.DEPRECATED_ELEMENT, - Elements.getDeprecatedElementTitle(element)); - } - } - - protected E recordElement(DartNode node, E element) { - node.getClass(); - if (element == null) { - // TypeAnalyzer will diagnose unresolved identifiers. - return null; - } - node.setElement(element); - return element; - } - - CoreTypeProvider getTypeProvider() { - return typeProvider; - } -} diff --git a/compiler/java/com/google/dart/compiler/resolver/Resolver.java b/compiler/java/com/google/dart/compiler/resolver/Resolver.java deleted file mode 100644 index 9a4cbf1e2956..000000000000 --- a/compiler/java/com/google/dart/compiler/resolver/Resolver.java +++ /dev/null @@ -1,2523 +0,0 @@ -// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -package com.google.dart.compiler.resolver; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Objects; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import com.google.dart.compiler.DartCompilationPhase; -import com.google.dart.compiler.DartCompilerContext; -import com.google.dart.compiler.ErrorCode; -import com.google.dart.compiler.Source; -import com.google.dart.compiler.ast.ASTNodes; -import com.google.dart.compiler.ast.ASTVisitor; -import com.google.dart.compiler.ast.DartArrayLiteral; -import com.google.dart.compiler.ast.DartBinaryExpression; -import com.google.dart.compiler.ast.DartBlock; -import com.google.dart.compiler.ast.DartBooleanLiteral; -import com.google.dart.compiler.ast.DartBreakStatement; -import com.google.dart.compiler.ast.DartCase; -import com.google.dart.compiler.ast.DartCatchBlock; -import com.google.dart.compiler.ast.DartClass; -import com.google.dart.compiler.ast.DartClassTypeAlias; -import com.google.dart.compiler.ast.DartComment; -import com.google.dart.compiler.ast.DartCommentNewName; -import com.google.dart.compiler.ast.DartCommentRefName; -import com.google.dart.compiler.ast.DartContinueStatement; -import com.google.dart.compiler.ast.DartDirective; -import com.google.dart.compiler.ast.DartDoWhileStatement; -import com.google.dart.compiler.ast.DartDoubleLiteral; -import com.google.dart.compiler.ast.DartExprStmt; -import com.google.dart.compiler.ast.DartExpression; -import com.google.dart.compiler.ast.DartField; -import com.google.dart.compiler.ast.DartFieldDefinition; -import com.google.dart.compiler.ast.DartForInStatement; -import com.google.dart.compiler.ast.DartForStatement; -import com.google.dart.compiler.ast.DartFunction; -import com.google.dart.compiler.ast.DartFunctionExpression; -import com.google.dart.compiler.ast.DartFunctionObjectInvocation; -import com.google.dart.compiler.ast.DartFunctionTypeAlias; -import com.google.dart.compiler.ast.DartGotoStatement; -import com.google.dart.compiler.ast.DartIdentifier; -import com.google.dart.compiler.ast.DartIfStatement; -import com.google.dart.compiler.ast.DartImportDirective; -import com.google.dart.compiler.ast.DartInitializer; -import com.google.dart.compiler.ast.DartIntegerLiteral; -import com.google.dart.compiler.ast.DartInvocation; -import com.google.dart.compiler.ast.DartLabel; -import com.google.dart.compiler.ast.DartMapLiteral; -import com.google.dart.compiler.ast.DartMethodDefinition; -import com.google.dart.compiler.ast.DartMethodInvocation; -import com.google.dart.compiler.ast.DartNamedExpression; -import com.google.dart.compiler.ast.DartNativeBlock; -import com.google.dart.compiler.ast.DartNewExpression; -import com.google.dart.compiler.ast.DartNode; -import com.google.dart.compiler.ast.DartParameter; -import com.google.dart.compiler.ast.DartParameterizedTypeNode; -import com.google.dart.compiler.ast.DartPartOfDirective; -import com.google.dart.compiler.ast.DartPropertyAccess; -import com.google.dart.compiler.ast.DartRedirectConstructorInvocation; -import com.google.dart.compiler.ast.DartReturnStatement; -import com.google.dart.compiler.ast.DartStatement; -import com.google.dart.compiler.ast.DartStringInterpolation; -import com.google.dart.compiler.ast.DartStringLiteral; -import com.google.dart.compiler.ast.DartSuperConstructorInvocation; -import com.google.dart.compiler.ast.DartSuperExpression; -import com.google.dart.compiler.ast.DartSwitchMember; -import com.google.dart.compiler.ast.DartSwitchStatement; -import com.google.dart.compiler.ast.DartThisExpression; -import com.google.dart.compiler.ast.DartThrowExpression; -import com.google.dart.compiler.ast.DartTryStatement; -import com.google.dart.compiler.ast.DartTypeExpression; -import com.google.dart.compiler.ast.DartTypeNode; -import com.google.dart.compiler.ast.DartTypeParameter; -import com.google.dart.compiler.ast.DartUnaryExpression; -import com.google.dart.compiler.ast.DartUnit; -import com.google.dart.compiler.ast.DartUnqualifiedInvocation; -import com.google.dart.compiler.ast.DartVariable; -import com.google.dart.compiler.ast.DartVariableStatement; -import com.google.dart.compiler.ast.DartWhileStatement; -import com.google.dart.compiler.ast.LibraryImport; -import com.google.dart.compiler.ast.LibraryUnit; -import com.google.dart.compiler.ast.Modifiers; -import com.google.dart.compiler.common.HasSourceInfo; -import com.google.dart.compiler.common.SourceInfo; -import com.google.dart.compiler.parser.Token; -import com.google.dart.compiler.resolver.LabelElement.LabeledStatementType; -import com.google.dart.compiler.type.InterfaceType; -import com.google.dart.compiler.type.InterfaceType.Member; -import com.google.dart.compiler.type.Type; -import com.google.dart.compiler.type.TypeAnalyzer; -import com.google.dart.compiler.type.TypeKind; -import com.google.dart.compiler.type.TypeQuality; -import com.google.dart.compiler.type.TypeVariable; -import com.google.dart.compiler.type.Types; - -import java.util.EnumSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -/** - * Resolves unqualified elements in a compilation unit. - */ -public class Resolver { - - private final ResolutionContext topLevelContext; - private final CoreTypeProvider typeProvider; - private final InterfaceType rawArrayType; - private final InterfaceType defaultLiteralMapType; - - - private static final EnumSet INVOKABLE_ELEMENTS = EnumSet.of( - ElementKind.FIELD, - ElementKind.PARAMETER, - ElementKind.VARIABLE, - ElementKind.FUNCTION_OBJECT, - ElementKind.METHOD); - - @VisibleForTesting - public Resolver(DartCompilerContext compilerContext, Scope libraryScope, - CoreTypeProvider typeProvider) { - compilerContext.getClass(); // Fast null-check. - libraryScope.getClass(); // Fast null-check. - typeProvider.getClass(); // Fast null-check. - this.topLevelContext = new ResolutionContext(libraryScope, compilerContext, typeProvider); - this.typeProvider = typeProvider; - Type dynamicType = typeProvider.getDynamicType(); - Type stringType = typeProvider.getStringType(); - this.defaultLiteralMapType = typeProvider.getMapType(stringType, dynamicType); - this.rawArrayType = typeProvider.getArrayType(dynamicType); - } - - @VisibleForTesting - public DartUnit exec(DartUnit unit) { - // Visits all top level elements of a compilation unit and resolves names used in method - // bodies. - LibraryElement library = unit.getLibrary() != null ? unit.getLibrary().getElement() : null; - unit.accept(new ResolveElementsVisitor(topLevelContext, library)); - return unit; - } - - /** - * Main entry point for IDE. Resolves a member (method or field) - * incrementally in the given context. - * - * @param classElement the class enclosing the member. - * @param member the member to resolve. - * @param context a resolution context corresponding to classElement. - */ - public void resolveMember(ClassNodeElement classElement, NodeElement member, ResolutionContext context) { - ResolveElementsVisitor visitor; - if(member == null) { - return; - } - switch (member.getKind()) { - case CONSTRUCTOR: - case METHOD: - ResolutionContext methodContext = context.extend(member.getName()); - visitor = new ResolveElementsVisitor(methodContext, classElement, - (MethodElement) member); - break; - - case FIELD: - ResolutionContext fieldContext = context; - if (member.getModifiers().isAbstractField()) { - fieldContext = context.extend(member.getName()); - } - visitor = new ResolveElementsVisitor(fieldContext, classElement); - break; - - default: - throw topLevelContext.internalError(member, - "unexpected element kind: %s", member.getKind()); - } - member.getNode().accept(visitor); - } - - /** - * Resolves names in a method body. - * - * TODO(ngeoffray): Errors reported: - * - A default implementation not providing the default methods. - * - An interface with default methods but without a default implementation. - * - A member method shadowing a super property. - * - A member property shadowing a super method. - * - A formal parameter in a non-constructor shadowing a member. - * - A local variable shadowing another variable. - * - A local variable shadowing a formal parameter. - * - A local variable shadowing a class member. - * - Using 'this' or 'super' in a static or factory method, or in an initializer. - * - Using 'super' in a class without a super class. - * - Incorrectly using a resolved element. - */ - @VisibleForTesting - public class ResolveElementsVisitor extends ResolveVisitor { - private EnclosingElement currentHolder; - private EnclosingElement enclosingElement; - private MethodElement currentMethod; - private boolean inInstanceVariableInitializer; - private boolean inInitializer; - private MethodElement innermostFunction; - private ResolutionContext context; - private Set referencedLabels = Sets.newHashSet(); - private Set labelsInScopes = Sets.newHashSet(); - private Set finalsNeedingInitializing = Sets.newHashSet(); - private Set resolvedFields = Sets.newHashSet(); - - @VisibleForTesting - public ResolveElementsVisitor(ResolutionContext context, - EnclosingElement currentHolder, - MethodElement currentMethod) { - super(typeProvider); - this.context = context; - this.currentMethod = currentMethod; - this.innermostFunction = currentMethod; - this.currentHolder = currentHolder; - this.enclosingElement = currentHolder; - this.inInitializer = false; - } - - private ResolveElementsVisitor(ResolutionContext context, EnclosingElement currentHolder) { - this(context, currentHolder, null); - } - - @Override - ResolutionContext getContext() { - return context; - } - - @Override - protected EnclosingElement getEnclosingElement() { - return enclosingElement; - } - - @Override - public Element visitUnit(DartUnit unit) { - List importDirectives = Lists.newArrayList(); - for (DartDirective directive : unit.getDirectives()) { - if (directive instanceof DartImportDirective) { - importDirectives.add((DartImportDirective) directive); - } - if (directive instanceof DartPartOfDirective) { - directive.accept(this); - } - } - // set LibraryElement for "import" directives - { - LibraryUnit library = unit.getLibrary(); - if (library != null) { - Iterator importIterator = library.getImports().iterator(); - Iterator directiveIterator = importDirectives.iterator(); - while (importIterator.hasNext() && directiveIterator.hasNext()) { - LibraryImport imp = importIterator.next(); - DartImportDirective dir = directiveIterator.next(); - DartStringLiteral uri = dir.getLibraryUri(); - LibraryUnit impLibrary = imp.getLibrary(); - if (uri != null && impLibrary != null) { - uri.setElement(impLibrary.getElement()); - } - } - } - } - // visit top-level nodes - for (DartNode node : unit.getTopLevelNodes()) { - node.accept(this); - } - checkRedirectingFactoryConstructorsCycle(unit); - return null; - } - - private void checkRedirectingFactoryConstructorsCycle(DartUnit unit) { - unit.accept(new ASTVisitor() { - @Override - public Void visitMethodDefinition(DartMethodDefinition node) { - MethodNodeElement element = node.getElement(); - if (ElementKind.of(element) == ElementKind.CONSTRUCTOR) { - ConstructorElement constructor = (ConstructorElement) element; - if (hasRedirectingFactoryConstructorCycle(constructor)) { - onError(constructor.getNameLocation(), - ResolverErrorCode.REDIRECTION_CONSTRUCTOR_CYCLE); - } - } - return super.visitMethodDefinition(node); - } - }); - } - - private boolean hasRedirectingFactoryConstructorCycle(ConstructorElement element) { - Set constructors = Sets.newHashSet(); - while (element != null) { - if (constructors.contains(element)) { - return true; - } - constructors.add(element); - element = element.getRedirectingFactoryConstructor(); - } - return false; - } - - @Override - public Element visitFunctionTypeAlias(DartFunctionTypeAlias alias) { - alias.getMetadata().accept(this); - getContext().pushFunctionAliasScope(alias); - resolveFunctionAlias(alias); - - getContext().pushScope(""); - try { - List parameters = alias.getParameters(); - for (DartParameter parameter : parameters) { - assert parameter.getElement() != null; - if (parameter.getQualifier() instanceof DartThisExpression) { - onError(parameter.getName(), ResolverErrorCode.PARAMETER_INIT_OUTSIDE_CONSTRUCTOR); - } else { - if (DartIdentifier.isPrivateName(parameter.getElement().getName())) { - if (parameter.getModifiers().isOptional()) { - onError(parameter.getName(), - ResolverErrorCode.OPTIONAL_PARAMETERS_CANNOT_START_WITH_UNDER); - } - if (parameter.getModifiers().isNamed()) { - onError(parameter.getName(), - ResolverErrorCode.NAMED_PARAMETERS_CANNOT_START_WITH_UNDER); - } - } - getContext().declare(parameter.getElement(), ResolverErrorCode.DUPLICATE_PARAMETER); - } - } - } finally { - getContext().popScope(); - } - - getContext().popScope(); - return null; - } - - @Override - public Element visitCommentRefName(DartCommentRefName node) { - Scope scope = getContext().getScope(); - String name = node.getName(); - Element element = scope.findElement(scope.getLibrary(), name); - return recordElement(node, element); - } - - @Override - public Element visitCommentNewName(DartCommentNewName node) { - String className = node.getClassName(); - String constructorName = node.getConstructorName(); - Scope scope = getContext().getScope(); - Element element = scope.findElement(scope.getLibrary(), className); - if (ElementKind.of(element) == ElementKind.CLASS) { - ClassElement classElement = (ClassElement) element; - for (ConstructorElement constructor : classElement.getConstructors()) { - if (constructor.getName().equals(constructorName)) { - node.setElements(classElement, constructor); - return constructor; - } - } - } - return null; - } - - @Override - public Element visitClassTypeAlias(DartClassTypeAlias cls) { - ClassNodeElement classElement = cls.getElement(); - try { - classElement.getAllSupertypes(); - } catch (CyclicDeclarationException e) { - HasSourceInfo errorTarget = e.getElement(); - if (errorTarget == null) { - errorTarget = cls; - } - onError(errorTarget, ResolverErrorCode.CYCLIC_CLASS, e.getElement().getName()); - } - checkMixinObjectIsSupertype(cls.getMixins()); - checkMixinNoConstructors(cls.getMixins()); - checkMixinNoSuperInvocations(cls.getMixins()); - return classElement; - } - - @Override - public Element visitClass(DartClass cls) { - assert currentMethod == null : "nested class?"; - ClassNodeElement classElement = cls.getElement(); - try { - classElement.getAllSupertypes(); - } catch (CyclicDeclarationException e) { - HasSourceInfo errorTarget = e.getElement(); - if (errorTarget == null) { - errorTarget = cls; - } - onError(errorTarget, ResolverErrorCode.CYCLIC_CLASS, e.getElement().getName()); - } - checkClassTypeVariables(classElement); - cls.getMetadata().accept(this); - - // Push new resolution context. - ResolutionContext previousContext = context; - EnclosingElement previousHolder = currentHolder; - EnclosingElement previousEnclosingElement = enclosingElement; - currentHolder = classElement; - enclosingElement = classElement; - context = topLevelContext.extend(classElement); - - // members - this.finalsNeedingInitializing.clear(); - for (DartNode member : cls.getMembers()) { - if (ElementKind.of(member.getElement()) == ElementKind.CONSTRUCTOR) { - continue; - } - member.accept(this); - } - - // constructors - boolean testForAllConstantFields = false; - for (DartNode member : cls.getMembers()) { - if (member instanceof DartMethodDefinition) { - DartMethodDefinition method = (DartMethodDefinition) member; - if (method.getElement().isConstructor()) { - method.accept(this); - if (method.getModifiers().isConstant()) { - testForAllConstantFields = true; - } - } - } - } - - if (testForAllConstantFields) { - InterfaceType interfaceType = classElement.getType(); - while (interfaceType != null && interfaceType != typeProvider.getObjectType()) { - ClassElement interfaceElement = interfaceType.getElement(); - constVerifyMembers(interfaceElement.getMembers(), classElement, interfaceElement); - interfaceType = interfaceElement.getSupertype(); - } - } - - checkRedirectConstructorCycle(classElement.getConstructors(), context); - if (Elements.needsImplicitDefaultConstructor(classElement)) { - checkImplicitDefaultDefaultSuperInvocation(cls, classElement); - } - - if (cls.getDefaultClass() != null && classElement.getDefaultClass() == null) { - onError(cls.getDefaultClass(), ResolverErrorCode.NO_SUCH_TYPE, cls.getDefaultClass()); - } else if (classElement.getDefaultClass() != null) { - recordElement(cls.getDefaultClass().getExpression(), - classElement.getDefaultClass().getElement()); - bindDefaultTypeParameters(classElement.getDefaultClass().getElement().getTypeParameters(), - cls.getDefaultClass().getTypeParameters(), - context); - - // Make sure the 'default' clause matches the referenced class type parameters - checkDefaultClassTypeParamsToDefaultDecl(classElement.getDefaultClass(), - cls.getDefaultClass()); - - ClassElement defaultClass = classElement.getDefaultClass().getElement(); - if (defaultClass.isInterface()) { - onError(cls.getDefaultClass().getExpression(), - ResolverErrorCode.DEFAULT_MUST_SPECIFY_CLASS); - } - - // Make sure the default class matches the interface type parameters - checkInterfaceTypeParamsToDefault(classElement, defaultClass); - } - - if (!classElement.isInterface() && Elements.needsImplicitDefaultConstructor(classElement)) { - // Check to see that all final fields are initialized when no explicit - // generative constructor is declared - cls.accept(new ASTVisitor() { - @Override - public DartNode visitField(DartField node) { - FieldElement fieldElement = node.getElement(); - if (fieldElement != null && fieldElement.getModifiers().isFinal() - && !fieldElement.isStatic() - && !fieldElement.getModifiers().isConstant() - && !fieldElement.getModifiers().isGetter() - && !fieldElement.getModifiers().isSetter() - && !fieldElement.getModifiers().isInitialized()) { - onError(node, ResolverErrorCode.FINAL_FIELD_MUST_BE_INITIALIZED, - fieldElement.getName()); - } - return null; - } - }); - } - - { - DartComment comment = cls.getDartDoc(); - if (comment != null) { - comment.accept(this); - } - } - - // check mixins - checkMixinObjectIsSupertype(cls.getMixins()); - checkMixinNoConstructors(cls.getMixins()); - checkMixinNoSuperInvocations(cls.getMixins()); - - context = previousContext; - currentHolder = previousHolder; - enclosingElement = previousEnclosingElement; - return classElement; - } - - /** - * Checks that the types of the given mixin type node don't have explicit constructors. - */ - private void checkMixinNoConstructors(List mixins) { - for (DartTypeNode mixNode : mixins) { - if (mixNode.getType() instanceof InterfaceType) { - InterfaceType mixType = (InterfaceType) mixNode.getType(); - for (ConstructorElement constructor : mixType.getElement().getConstructors()) { - if (!constructor.getModifiers().isFactory()) { - topLevelContext.onError(mixNode, ResolverErrorCode.CANNOT_MIXIN_CLASS_WITH_CONSTRUCTOR); - break; - } - } - } - } - } - - /** - * Checks that the types of the given mixin type nodes se subtypes of Object. - */ - private void checkMixinObjectIsSupertype(List mixins) { - for (DartTypeNode mixNode : mixins) { - if (mixNode.getType() instanceof InterfaceType) { - InterfaceType mixType = (InterfaceType) mixNode.getType(); - ClassElement mixElement = mixType.getElement(); - if (!mixElement.getMixins().isEmpty()) { - topLevelContext.onError(mixNode, ResolverErrorCode.CANNOT_MIXIN_CLASS_WITH_MIXINS); - continue; - } - if (!Objects.equal(mixElement.getSupertype(), typeProvider.getObjectType())) { - topLevelContext.onError(mixNode, ResolverErrorCode.ONLY_OBJECT_MIXIN_SUPERCLASS); - continue; - } - } - } - } - - /** - * Checks that the types of the given mixin type nodes don't have super invocations. - */ - private void checkMixinNoSuperInvocations(List mixins) { - for (DartTypeNode mixNode : mixins) { - if (mixNode.getType() instanceof InterfaceType) { - InterfaceType mixType = (InterfaceType) mixNode.getType(); - if (mixType.getElement() instanceof ClassElement) { - ClassElement mixElement = (ClassElement) mixType.getElement(); - if (mixElement.hasSuperInvocation()) { - topLevelContext.onError(mixNode, ResolverErrorCode.CANNOT_MIXIN_CLASS_WITH_SUPER); - break; - } - } - } - } - } - - private void constVerifyMembers(Iterable members, ClassElement originalClass, - ClassElement currentClass) { - for (Element element : members) { - Modifiers modifiers = element.getModifiers(); - if (ElementKind.of(element).equals(ElementKind.FIELD) && !modifiers.isFinal() - && !modifiers.isStatic() && !modifiers.isAbstractField()) { - FieldElement field = (FieldElement) element; - HasSourceInfo errorNode = field.getSetter() == null ? element : field.getSetter(); - onError(errorNode, currentClass == originalClass - ? ResolverErrorCode.CONST_CLASS_WITH_NONFINAL_FIELDS - : ResolverErrorCode.CONST_CLASS_WITH_INHERITED_NONFINAL_FIELDS, - originalClass.getName(), field.getName(), currentClass.getName()); - } - } - } - - /** - * Sets the type in the AST of the default clause of an interface so that the type - * parameters to resolve back to the default class. - */ - private void bindDefaultTypeParameters(List parameterTypes, - List parameterNodes, - ResolutionContext classContext) { - Iterator typeIterator = parameterTypes.iterator(); - Iterator nodeIterator = parameterNodes.iterator(); - - while(typeIterator.hasNext() && nodeIterator.hasNext()) { - - Type type = typeIterator.next(); - DartTypeParameter node = nodeIterator.next(); - - if (type.getElement().getName().equals(node.getName().getName())) { - node.setType(type); - recordElement(node.getName(), type.getElement()); - } else { - node.setType(typeProvider.getDynamicType()); - } - - DartTypeNode boundNode = node.getBound(); - if (boundNode != null) { - Type bound = - classContext.resolveType( - boundNode, - false, - false, - true, - ResolverErrorCode.NO_SUCH_TYPE, - ResolverErrorCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS); - boundNode.setType(bound); - } - } - - while (nodeIterator.hasNext()) { - DartTypeParameter node = nodeIterator.next(); - node.setType(typeProvider.getDynamicType()); - } - } - /** - * If type parameters are present, the type parameters of the default statement - * must exactly match those of those declared in the class it references. - * - */ - private void checkDefaultClassTypeParamsToDefaultDecl(InterfaceType defaultClassType, - DartParameterizedTypeNode defaultClassRef) { - if (defaultClassRef.getTypeParameters().isEmpty()) { - return; - } - ClassElement defaultClassElement = defaultClassType.getElement(); - boolean match = true; - if (defaultClassElement.getTypeParameters().isEmpty()) { - match = false; - } else { - // TODO(zundel): This is effective in catching mistakes, but highlights the entire type - // expression - A more specific indication of where the error started might be appreciated. - String defaultClassSource = defaultClassElement.getDeclarationNameWithTypeParameters(); - String refSource = defaultClassRef.toSource(); - if (!refSource.equals(defaultClassSource)) { - match = false; - } - } - if (!match) { - // TODO(zundel): work harder to point out where the type param match failure starts. - onError(defaultClassRef, ResolverErrorCode.TYPE_PARAMETERS_MUST_MATCH_EXACTLY); - } - } - - private void checkInterfaceTypeParamsToDefault(ClassElement interfaceElement, - ClassElement defaultClassElement) { - - List interfaceTypeParams = interfaceElement.getTypeParameters(); - - List defaultTypeParams = defaultClassElement.getTypeParameters(); - - - if (defaultTypeParams.size() != interfaceTypeParams.size()) { - - onError(interfaceElement.getNameLocation(), - ResolverErrorCode.DEFAULT_CLASS_MUST_HAVE_SAME_TYPE_PARAMS); - } else { - Iterator interfaceIterator = interfaceTypeParams.iterator(); - Iterator defaultIterator = defaultTypeParams.iterator(); - while (interfaceIterator.hasNext()) { - Type iVar = interfaceIterator.next(); - Type dVar = defaultIterator.next(); - String iVarName = iVar.getElement().getName(); - String dVarName = dVar.getElement().getName(); - if (!iVarName.equals(dVarName)) { - onError(iVar.getElement(), ResolverErrorCode.TYPE_VARIABLE_DOES_NOT_MATCH, - iVarName, dVarName, defaultClassElement.getName()); - } - } - } - } - - /** - * Check that used type variables are unique and don't shadow and existing elements. - */ - private void checkClassTypeVariables(ClassElement classElement) { - Set declaredVariableNames = Sets.newHashSet(); - for (Type type : classElement.getTypeParameters()) { - if (type instanceof TypeVariable) { - Element typeVariableElement = type.getElement(); - String name = typeVariableElement.getName(); - // Check that type variables are unique in this Class declaration. - if (declaredVariableNames.contains(name)) { - onError(typeVariableElement, ResolverErrorCode.DUPLICATE_TYPE_VARIABLE, name); - } else { - declaredVariableNames.add(name); - } - } - } - } - - /** - * Returns true if the {@link ClassElement} has an implicit or a declared - * default constructor. - */ - boolean hasDefaultConstructor(ClassElement classElement) { - if (Elements.needsImplicitDefaultConstructor(classElement)) { - return true; - } - - ConstructorElement defaultCtor = Elements.lookupConstructor(classElement, ""); - if (defaultCtor != null) { - return defaultCtor.getParameters().isEmpty(); - } - - return false; - } - - private void checkImplicitDefaultDefaultSuperInvocation(DartClass cls, - ClassElement classElement) { - assert (Elements.needsImplicitDefaultConstructor(classElement)); - - InterfaceType supertype = classElement.getSupertype(); - if (supertype != null) { - ClassElement superElement = supertype.getElement(); - if (!superElement.isDynamic()) { - ConstructorElement superCtor = Elements.lookupConstructor(superElement, ""); - boolean superHasDefaultCtor = - (superCtor != null && superCtor.getParameters().isEmpty()) - || (superCtor == null && Elements.needsImplicitDefaultConstructor(superElement)); - if (!superHasDefaultCtor) { - onError(cls.getName(), - ResolverErrorCode.CANNOT_RESOLVE_IMPLICIT_CALL_TO_SUPER_CONSTRUCTOR, - cls.getSuperclass()); - } - if (superCtor != null && superCtor.getModifiers().isFactory()) { - onError(cls.getName(), ResolverErrorCode.NOT_GENERATIVE_SUPER_CONSTRUCTOR, "", - supertype); - } - } - } - } - - private Element resolve(DartNode node) { - if (node == null) { - return null; - } else { - return node.accept(this); - } - } - - @Override - public Element visitTypeParameter(DartTypeParameter node) { - node.getMetadata().accept(this); - return super.visitTypeParameter(node); - } - - @Override - public MethodElement visitMethodDefinition(DartMethodDefinition node) { - node.getMetadata().accept(this); - MethodElement member = node.getElement(); - ResolutionContext previousContext = context; - context = context.extend(member.getName()); - assert currentMethod == null : "Nested methods?"; - innermostFunction = currentMethod = member; - EnclosingElement previousEnclosingElement = enclosingElement; - enclosingElement = member; - - DartFunction functionNode = node.getFunction(); - List parameters = functionNode.getParameters(); - Set initializedFields = Sets.newHashSet(); - - // remember field with initializers - if (previousEnclosingElement instanceof ClassElement) { - ClassElement classElement = (ClassElement) previousEnclosingElement; - for (Element classMember : classElement.getMembers()) { - if (ElementKind.of(classMember) == ElementKind.FIELD) { - FieldElement fieldMember = (FieldElement) classMember; - if (fieldMember.getModifiers().isFinal() && fieldMember.getModifiers().isInitialized()) { - initializedFields.add(fieldMember); - } - } - } - } - - // First declare all normal parameters in the scope, putting them in the - // scope of the default expressions so we can report better errors. - for (DartParameter parameter : parameters) { - assert parameter.getElement() != null; - parameter.getMetadata().accept(this); - - if (!(parameter.getQualifier() instanceof DartThisExpression)) { - getContext().declare( - parameter.getElement(), - ResolverErrorCode.DUPLICATE_PARAMETER); - } - } - for (DartParameter parameter : parameters) { - // Then resolve the default values. - resolve(parameter.getDefaultExpr()); - if (parameter.getQualifier() instanceof DartThisExpression && parameter.getElement() != null - && !initializedFields.add(parameter.getElement().getParameterInitializerElement())) { - onError(parameter, ResolverErrorCode.DUPLICATE_INITIALIZATION, parameter.getName()); - } - } - - { - DartComment comment = node.getDartDoc(); - if (comment != null) { - comment.accept(this); - } - } - - DartBlock body = functionNode.getBody(); - if (body == null) { - if (member.getModifiers().isStatic() && !member.getModifiers().isExternal()) { - onError(functionNode, ResolverErrorCode.STATIC_METHOD_MUST_HAVE_BODY); - } - } - resolve(functionNode.getBody()); - - if (Elements.isNonFactoryConstructor(member) && !(body instanceof DartNativeBlock)) { - resolveInitializers(node, initializedFields); - } - - // only generative constructor can have initializers, so resolve them, but report error - if (!member.isConstructor() || member.getModifiers().isFactory()) { - for (DartInitializer initializer : node.getInitializers()) { - resolve(initializer); - if (initializer.getName() != null) { - onError(initializer, ResolverErrorCode.INITIALIZER_ONLY_IN_GENERATIVE_CONSTRUCTOR); - } - } - } - - // resolve redirecting factory constructor - { - DartTypeNode rcTypeName = node.getRedirectedTypeName(); - if (rcTypeName != null) { - Type rcType = resolveType(rcTypeName, true, true, false, - TypeErrorCode.NO_SUCH_TYPE, ResolverErrorCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS); - switch (TypeKind.of(rcType)) { - case INTERFACE: - ConstructorElement targetConstructor = null; - Element element = recordType(rcTypeName, rcType); - DartIdentifier rcName = node.getRedirectedConstructorName(); - if (rcName != null) { - element = ((ClassElement) element).lookupConstructor(rcName.getName()); - switch (ElementKind.of(element)) { - case CONSTRUCTOR: - targetConstructor = (ConstructorElement) element; - recordElement(rcName, element); - if (member.getModifiers().isConstant() && !element.getModifiers().isConstant()) { - onError(rcName, - ResolverErrorCode.REDIRECTION_CONSTRUCTOR_TARGET_MUST_BE_CONST); - } - break; - } - } else { - targetConstructor = ((ClassElement) element).lookupConstructor(""); - } - Elements.setRedirectingFactoryConstructor(((ConstructorElement) member), - targetConstructor); - break; - default: - onError(rcTypeName, ResolverErrorCode.REDIRECTION_CONSTRUCTOR_TARGET_TYPE); - } - } - } - - context = previousContext; - innermostFunction = currentMethod = null; - enclosingElement = previousEnclosingElement; - return member; - } - - @Override - public Element visitField(DartField node) { - DartExpression expression = node.getValue(); - Modifiers modifiers = node.getModifiers(); - boolean isFinal = modifiers.isFinal(); - boolean isTopLevel = ElementKind.of(currentHolder).equals(ElementKind.LIBRARY); - boolean isStatic = modifiers.isStatic(); - - if (expression != null) { - inInstanceVariableInitializer = !isTopLevel; - try { - resolve(expression); - } finally { - inInstanceVariableInitializer = false; - } - // Now, this constant has a type. Save it for future reference. - Element element = node.getElement(); - Type expressionType = expression.getType(); - if (isFinal && expressionType != null && TypeKind.of(element.getType()) == TypeKind.DYNAMIC) { - TypeQuality typeQuality = TypeAnalyzer.getTypeQuality(expression); - Type fieldType = Types.makeInferred(expressionType, typeQuality); - Elements.setType(element, fieldType); - } - } else if (isFinal) { - if (modifiers.isConstant()) { - onError(node, ResolverErrorCode.CONST_REQUIRES_VALUE); - } else if (isStatic) { - onError(node, ResolverErrorCode.STATIC_FINAL_REQUIRES_VALUE); - } else if (isTopLevel) { - onError(node, ResolverErrorCode.TOPLEVEL_FINAL_REQUIRES_VALUE); - } else { - // If a final instance field wasn't initialized at declaration, we must check - // at construction time. - this.finalsNeedingInitializing.add(node.getElement()); - } - } - - // If field is an accessor, both getter and setter need to be visited (if present). - // We check for duplicates because top-level fields are visited twice - for each accessor. - FieldNodeElement field = node.getElement(); - if (!resolvedFields.contains(field)) { - resolvedFields.add(field); - if (field.getGetter() != null) { - resolve(field.getGetter().getNode()); - } - if (field.getSetter() != null) { - resolve(field.getSetter().getNode()); - } - } - return null; - } - - @Override - public Element visitFieldDefinition(DartFieldDefinition node) { - node.getMetadata().accept(this); - visit(node.getFields()); - return null; - } - - @Override - public Element visitFunction(DartFunction node) { - throw context.internalError(node, "should not be called."); - } - - @Override - public Element visitParameter(DartParameter x) { - x.getMetadata().accept(this); - Element element = super.visitParameter(x); - resolve(x.getDefaultExpr()); - getContext().declare( - element, - ResolverErrorCode.DUPLICATE_PARAMETER); - return element; - } - - @Override - public Element visitVariable(DartVariable node) { - node.getMetadata().accept(this); - return super.visitVariable(node); - } - - public VariableElement resolveVariable(DartVariable x, Modifiers modifiers) { - final DartIdentifier nameNode = x.getName(); - final String name = nameNode.getName(); - // Visit the initializer first. - DartExpression value = x.getValue(); - if (value != null) { - // It is a compile-time error if e refers to the name v or the name v=. - value.accept(new ASTVisitor() { - @Override - public Void visitIdentifier(DartIdentifier node) { - // ignore cases when name is used with some qualifier - if (node.getParent() instanceof DartPropertyAccess) { - DartPropertyAccess x = (DartPropertyAccess) node.getParent(); - if (x.getName() == node) { - return null; - } - } - if (node.getParent() instanceof DartMethodInvocation) { - DartMethodInvocation x = (DartMethodInvocation) node.getParent(); - if (x.getFunctionName() == node) { - return null; - } - } - // TODO(scheglov) remove this after http://code.google.com/p/dart/issues/detail?id=6869 - { - Source source = node.getSourceInfo().getSource(); - if (Elements.isSourceName(source, "dart://json/json.dart/json.dart")) { - return null; - } - } - if (Objects.equal(node.getName(), name)) { - onError(node, ResolverErrorCode.VARIABLE_REFERENCES_SAME_NAME_IN_INITIALIZER, name, - name); - node.markResolutionAlreadyReportedThatTheMethodCouldNotBeFound(); - } - return null; - } - }); - // do resolve - resolve(value); - } - // declare variable - VariableElement element = Elements.variableElement(enclosingElement, x, name, modifiers); - getContext().declare(recordElement(x, element), - ResolverErrorCode.DUPLICATE_LOCAL_VARIABLE_ERROR); - recordElement(nameNode, element); - return element; - } - - @Override - public Element visitVariableStatement(DartVariableStatement node) { - resolveVariableStatement(node, false); - return null; - } - - private void resolveVariableStatement(DartVariableStatement node, - boolean isImplicitlyInitialized) { - Type type = - resolveType( - node.getTypeNode(), - ASTNodes.isStaticContext(node), - ASTNodes.isFactoryContext(node), - true, - TypeErrorCode.NO_SUCH_TYPE, - TypeErrorCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS); - for (DartVariable variable : node.getVariables()) { - String name = variable.getVariableName(); - getContext().getScope().removeDeclaredButNotReachedVariable(name); - Elements.setType(resolveVariable(variable, node.getModifiers()), type); - checkVariableStatement(node, variable, isImplicitlyInitialized); - } - } - - @Override - public Element visitLabel(DartLabel x) { - DartNode parent = x.getParent(); - if (!(parent instanceof DartSwitchMember && ((DartSwitchMember) parent).getLabels().contains( - x))) { - LabelElement labelElement; - DartStatement childStatement = x.getStatement(); - while (childStatement instanceof DartLabel) { - childStatement = ((DartLabel) childStatement).getStatement(); - } - if (childStatement instanceof DartSwitchStatement) { - labelElement = Elements.switchLabelElement(x, x.getName(), innermostFunction); - } else { - labelElement = Elements.statementLabelElement(x, x.getName(), innermostFunction); - } - recordElement(x.getLabel(), labelElement); - recordElement(x, labelElement); - } - x.visitChildren(this); - return null; - } - - @Override - public Element visitFunctionExpression(DartFunctionExpression x) { - MethodElement element; - if (x.isStatement()) { - // Function statement names live in the outer scope. - element = getContext().declareFunction(x); - getContext().pushFunctionScope(x); - } else { - // Function expression names live in their own scope. - getContext().pushFunctionScope(x); - element = getContext().declareFunction(x); - } - // record element - if (x.getName() != null) { - recordElement(x.getName(), element); - } - recordElement(x, element); - // visit function - MethodElement previousFunction = innermostFunction; - innermostFunction = element; - { - DartFunction functionNode = x.getFunction(); - EnclosingElement previousEnclosingElement = enclosingElement; - enclosingElement = element; - getContext().pushFunctionScope(x); - try { - resolveFunction(functionNode, element); - resolve(functionNode.getBody()); - } finally { - getContext().popScope(); - enclosingElement = previousEnclosingElement; - } - } - innermostFunction = previousFunction; - getContext().popScope(); - return element; - } - - @Override - public Element visitBlock(DartBlock x) { - getContext().pushScope(""); - addLabelToStatement(x); - // Remember names of Block variables. - for (DartStatement statement : x.getStatements()) { - if (statement instanceof DartVariableStatement) { - DartVariableStatement node = (DartVariableStatement) statement; - List variables = node.getVariables(); - for (DartVariable variable : variables) { - String name = variable.getVariableName(); - getContext().getScope().addDeclaredButNotReachedVariable(name); - } - } - } - // Visit statements. - x.visitChildren(this); - getContext().popScope(); - return null; - } - - @Override - public Element visitBreakStatement(DartBreakStatement x) { - // Handle corner case of L: break L; - DartNode parent = x.getParent(); - if (parent instanceof DartLabel && x.getLabel() != null) { - if (((DartLabel) parent).getLabel().getName().equals(x.getLabel().getName())) { - getContext().pushScope(""); - addLabelToStatement(x); - visitGotoStatement(x); - getContext().popScope(); - return null; - } - } - return visitGotoStatement(x); - } - - @Override - public Element visitTryStatement(DartTryStatement x) { - getContext().pushScope(""); - addLabelToStatement(x); - x.visitChildren(this); - getContext().popScope(); - return null; - } - - @Override - public Element visitCatchBlock(DartCatchBlock x) { - getContext().pushScope(""); - addLabelToStatement(x); - x.visitChildren(this); - getContext().popScope(); - return null; - } - - @Override - public Element visitDoWhileStatement(DartDoWhileStatement x) { - getContext().pushScope(""); - addLabelToStatement(x); - x.visitChildren(this); - getContext().popScope(); - return null; - } - - @Override - public Element visitWhileStatement(DartWhileStatement x) { - getContext().pushScope(""); - addLabelToStatement(x); - x.visitChildren(this); - getContext().popScope(); - return null; - } - - @Override - public Element visitIfStatement(DartIfStatement x) { - getContext().pushScope(""); - addLabelToStatement(x); - x.visitChildren(this); - getContext().popScope(); - return null; - } - - @Override - public Element visitForInStatement(DartForInStatement x) { - getContext().pushScope(""); - addLabelToStatement(x); - - x.getIterable().accept(this); - if (x.introducesVariable()) { - resolveVariableStatement(x.getVariableStatement(), true); - } else { - x.getIdentifier().accept(this); - } - x.getBody().accept(this); - getContext().popScope(); - return null; - } - - private void addLabelToStatement(DartNode x) { - DartNode parent = x.getParent(); - while (parent instanceof DartLabel) { - DartLabel label = (DartLabel) parent; - LabelElement currentLabel = label.getElement(); - getContext().getScope().addLabel(currentLabel); - labelsInScopes.add(currentLabel); - parent = parent.getParent(); - } - } - - @Override - public Element visitForStatement(DartForStatement x) { - getContext().pushScope(""); - addLabelToStatement(x); - x.visitChildren(this); - getContext().popScope(); - return null; - } - - - @Override - public Element visitSwitchStatement(DartSwitchStatement x) { - getContext().pushScope(""); - addLabelToStatement(x); - // The scope of a label on the case statement is the case statement itself. These labels - // need to be resolved before the continue