Version 1.21.0-dev.1.0
Merge 941b0c8c392030b0e9b7ddf3b9dff69c7b3eaa51 into dev
diff --git a/build/config/compiler/BUILD.gn b/build/config/compiler/BUILD.gn
index c86203c..a2f8b13 100644
--- a/build/config/compiler/BUILD.gn
+++ b/build/config/compiler/BUILD.gn
@@ -720,7 +720,7 @@
if (is_win) {
# Favor size over speed, /O1 must be before the common flags. The GYP
# build also specifies /Os and /GF but these are implied by /O1.
- cflags = [ "/O1" ] + common_optimize_on_cflags + [ "/Oi" ]
+ cflags = [ "/O2" ] + common_optimize_on_cflags + [ "/Oi" ]
} else if (is_android) {
cflags = [ "-Os" ] + common_optimize_on_cflags # Favor size over speed.
} else {
@@ -733,9 +733,9 @@
config("no_optimize") {
if (is_win) {
cflags = [
- "/Od", # Disable optimization.
+ "/O2", # Do some optimizations.
+ "/Oy-", # Disable omitting frame pointers, must be after /O2.
"/Ob0", # Disable all inlining (on by default).
- "/RTC1", # Runtime checks for stack frame and uninitialized variables.
]
} else if (is_android) {
# On Android we kind of optimize some things that don't affect debugging
diff --git a/pkg/analysis_server/test/abstract_context.dart b/pkg/analysis_server/test/abstract_context.dart
index d7b70df..2b7a648 100644
--- a/pkg/analysis_server/test/abstract_context.dart
+++ b/pkg/analysis_server/test/abstract_context.dart
@@ -49,13 +49,13 @@
AnalysisContext context;
Source addPackageSource(String packageName, String filePath, String content) {
- packageMap[packageName] = [(provider.newFolder('/pubcache/$packageName'))];
- File file = provider.newFile('/pubcache/$packageName/$filePath', content);
+ packageMap[packageName] = [(newFolder('/pubcache/$packageName'))];
+ File file = newFile('/pubcache/$packageName/$filePath', content);
return file.createSource();
}
Source addSource(String path, String content, [Uri uri]) {
- File file = provider.newFile(path, content);
+ File file = newFile(path, content);
Source source = file.createSource(uri);
ChangeSet changeSet = new ChangeSet();
changeSet.addedSource(source);
@@ -64,6 +64,12 @@
return source;
}
+ File newFile(String path, [String content]) =>
+ provider.newFile(provider.convertPath(path), content ?? '');
+
+ Folder newFolder(String path) =>
+ provider.newFolder(provider.convertPath(path));
+
/**
* Performs all analysis tasks in [context].
*/
diff --git a/pkg/analysis_server/test/analysis/notification_errors_test.dart b/pkg/analysis_server/test/analysis/notification_errors_test.dart
index 3184665..8ab02c3 100644
--- a/pkg/analysis_server/test/analysis/notification_errors_test.dart
+++ b/pkg/analysis_server/test/analysis/notification_errors_test.dart
@@ -54,7 +54,7 @@
AnalysisError error = errors[0];
expect(error.severity, AnalysisErrorSeverity.ERROR);
expect(error.type, AnalysisErrorType.COMPILE_TIME_ERROR);
- expect(error.message, startsWith('Target of URI does not exist'));
+ expect(error.message, startsWith("Target of URI doesn't exist"));
}
test_lintError() async {
diff --git a/pkg/analysis_server/test/analysis/update_content_test.dart b/pkg/analysis_server/test/analysis/update_content_test.dart
index b5d77c6..788088f 100644
--- a/pkg/analysis_server/test/analysis/update_content_test.dart
+++ b/pkg/analysis_server/test/analysis/update_content_test.dart
@@ -170,7 +170,7 @@
{'/project/main.dart': new AddContentOverlay('import "target.dart";')});
await server.onAnalysisComplete;
expect(filesErrors, {
- '/project/main.dart': ["1: Target of URI does not exist: 'target.dart'"],
+ '/project/main.dart': ["1: Target of URI doesn't exist: 'target.dart'."],
'/project/target.dart': []
});
@@ -178,8 +178,8 @@
{'/project/target.dart': new AddContentOverlay('import "none.dart";')});
await server.onAnalysisComplete;
expect(filesErrors, {
- '/project/main.dart': ["1: Unused import"],
- '/project/target.dart': ["1: Target of URI does not exist: 'none.dart'"],
+ '/project/main.dart': ["1: Unused import."],
+ '/project/target.dart': ["1: Target of URI doesn't exist: 'none.dart'."],
'/project/none.dart': []
});
}
diff --git a/pkg/analysis_server/test/integration/analysis/error_test.dart b/pkg/analysis_server/test/integration/analysis/error_test.dart
index 847f895..f2abb51 100644
--- a/pkg/analysis_server/test/integration/analysis/error_test.dart
+++ b/pkg/analysis_server/test/integration/analysis/error_test.dart
@@ -63,11 +63,11 @@
expect(
allErrorMessages,
contains(
- "The class 'C' cannot be used as a mixin because it extends a class other than Object"));
+ "The class 'C' can't be used as a mixin because it extends a class other than Object."));
expect(
allErrorMessages,
contains(
- "The class 'C' cannot be used as a mixin because it references 'super'"));
+ "The class 'C' can't be used as a mixin because it references 'super'."));
}
test_super_mixins_enabled() async {
diff --git a/pkg/analysis_server/test/services/correction/fix_test.dart b/pkg/analysis_server/test/services/correction/fix_test.dart
index dbfb129..dc65a97 100644
--- a/pkg/analysis_server/test/services/correction/fix_test.dart
+++ b/pkg/analysis_server/test/services/correction/fix_test.dart
@@ -474,14 +474,14 @@
// No fix for ";".
{
AnalysisError error = errors[0];
- expect(error.message, "Expected to find ';'");
+ expect(error.message, "Expected to find ';'.");
List<Fix> fixes = await _computeFixes(error);
expect(fixes, isEmpty);
}
// Has fix for "await".
{
AnalysisError error = errors[1];
- expect(error.message, startsWith("Undefined name 'await';"));
+ expect(error.message, startsWith("Undefined name 'await'."));
List<Fix> fixes = await _computeFixes(error);
// has exactly one fix
expect(fixes, hasLength(1));
diff --git a/pkg/analyzer/lib/error/error.dart b/pkg/analyzer/lib/error/error.dart
index 648a447..2db4525 100644
--- a/pkg/analyzer/lib/error/error.dart
+++ b/pkg/analyzer/lib/error/error.dart
@@ -235,11 +235,59 @@
*
* Generally, we want to provide messages that consist of three sentences. From
* the user's perspective these sentences should explain:
+ *
* 1. what is wrong,
* 2. why is it wrong, and
* 3. how do I fix it.
+ *
* However, we combine the first two in the [message] and the last in the
* [correction].
+ *
+ * When composing messages (including correction messages) keep the following
+ * guidelines in mind.
+ *
+ * 1. The message should be a complete sentence starting with an uppercase
+ * letter, and ending with a period.
+ *
+ * 2. Reserved words and embedded identifiers should be in single quotes, so
+ * prefer double quotes for the complete message. For example,
+ * ```
+ * "The class '{0}' can't use 'super'."
+ * ```
+ * Notice that the word 'class' in the preceding message is not quoted as it
+ * refers to the concept 'class', not the reserved word. On the other hand,
+ * 'super' refers to the reserved word. Do not quote 'null' and numeric literals.
+ *
+ * 3. Do not try to compose messages, as it can make translating them hard.
+ *
+ * 4. Try to keep the error messages short, but informative.
+ *
+ * 5. Use simple words and terminology, assume the reader of the message doesn't
+ * have an advanced degree in math, and that English is not the reader's native
+ * language. Do not assume any formal computer science training. For example, do
+ * not use Latin abbreviations (prefer "that is" over "i.e.", and "for example"
+ * over "e.g."). Also avoid phrases such as "if and only if" and "iff"; that
+ * level of precision is unnecessary.
+ *
+ * 6. Prefer contractions when they are in common use, for example, prefer
+ * "can't" over "cannot". Using "cannot", "must not", "shall not", etc. is
+ * off-putting to people new to programming.
+ *
+ * 7. Use common terminology, preferably from the Dart Language Specification.
+ * This increases the user's chance of finding a good explanation on the web.
+ *
+ * 8. Do not try to be cute or funny. It is extremely frustrating to work on a
+ * product that crashes with a "tongue-in-cheek" message, especially if you did
+ * not want to use this product to begin with.
+ *
+ * 9. Do not lie, that is, do not write error messages containing phrases like
+ * "can't happen". If the user ever saw this message, it would be a lie. Prefer
+ * messages like: "Internal error: This function should not be called when 'x'
+ * is null.".
+ *
+ * 10. Prefer to not use the imperative tone. That is, the message should not
+ * sound accusing or like it is ordering the user around. The computer should
+ * describe the problem, not criticize the user for violating the specification.
*/
abstract class ErrorCode {
/**
@@ -247,18 +295,23 @@
*/
static const List<ErrorCode> values = const [
//
- // Manually generated. FWIW, this get's you most of the way there:
+ // Manually generated. You can mostly reproduce this list by running the
+ // following command from the root of the analyzer package:
//
- // > grep 'static const .*Code' (error.dart|parser|scanner.dart)
- // | awk '{print $3"."$4","}'
+ // > cat lib/src/dart/error/syntactic_errors.dart src/error/codes.dart |
+ // grep 'static const .*Code' |
+ // awk '{print $3"."$4","}' |
+ // sort > codes.txt
//
- // error.dart:
+ // There are a few error codes that are wrapped such that the name of the
+ // error code in on the line following the pattern we're grepping for. Those
+ // need to be filled in by hand.
//
AnalysisOptionsErrorCode.PARSE_ERROR,
- AnalysisOptionsWarningCode.UNSUPPORTED_OPTION_WITH_LEGAL_VALUES,
- AnalysisOptionsWarningCode.UNSUPPORTED_OPTION_WITH_LEGAL_VALUE,
- AnalysisOptionsWarningCode.UNSUPPORTED_VALUE,
AnalysisOptionsWarningCode.UNRECOGNIZED_ERROR_CODE,
+ AnalysisOptionsWarningCode.UNSUPPORTED_OPTION_WITH_LEGAL_VALUE,
+ AnalysisOptionsWarningCode.UNSUPPORTED_OPTION_WITH_LEGAL_VALUES,
+ AnalysisOptionsWarningCode.UNSUPPORTED_VALUE,
CheckedModeCompileTimeErrorCode.CONST_CONSTRUCTOR_FIELD_TYPE_MISMATCH,
CheckedModeCompileTimeErrorCode.CONST_CONSTRUCTOR_PARAM_TYPE_MISMATCH,
CheckedModeCompileTimeErrorCode.CONST_FIELD_INITIALIZER_NOT_ASSIGNABLE,
@@ -273,15 +326,14 @@
CompileTimeErrorCode.ASYNC_FOR_IN_WRONG_CONTEXT,
CompileTimeErrorCode.AWAIT_IN_WRONG_CONTEXT,
CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE,
- CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE_NAME,
CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPEDEF_NAME,
+ CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE_NAME,
CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE_PARAMETER_NAME,
CompileTimeErrorCode.CASE_EXPRESSION_TYPE_IMPLEMENTS_EQUALS,
- CompileTimeErrorCode.COMPILE_TIME_CONSTANT_RAISES_EXCEPTION,
- CompileTimeErrorCode.CONFLICTING_GETTER_AND_METHOD,
- CompileTimeErrorCode.CONFLICTING_METHOD_AND_GETTER,
CompileTimeErrorCode.CONFLICTING_CONSTRUCTOR_NAME_AND_FIELD,
CompileTimeErrorCode.CONFLICTING_CONSTRUCTOR_NAME_AND_METHOD,
+ CompileTimeErrorCode.CONFLICTING_GETTER_AND_METHOD,
+ CompileTimeErrorCode.CONFLICTING_METHOD_AND_GETTER,
CompileTimeErrorCode.CONFLICTING_TYPE_VARIABLE_AND_CLASS,
CompileTimeErrorCode.CONFLICTING_TYPE_VARIABLE_AND_MEMBER,
CompileTimeErrorCode.CONST_CONSTRUCTOR_THROWS_EXCEPTION,
@@ -290,19 +342,18 @@
CompileTimeErrorCode.CONST_CONSTRUCTOR_WITH_NON_CONST_SUPER,
CompileTimeErrorCode.CONST_CONSTRUCTOR_WITH_NON_FINAL_FIELD,
CompileTimeErrorCode.CONST_DEFERRED_CLASS,
- CompileTimeErrorCode.CONST_FORMAL_PARAMETER,
- CompileTimeErrorCode.CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE,
- CompileTimeErrorCode
- .CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE_FROM_DEFERRED_LIBRARY,
- CompileTimeErrorCode.CONST_INSTANCE_FIELD,
- CompileTimeErrorCode.CONST_MAP_KEY_EXPRESSION_TYPE_IMPLEMENTS_EQUALS,
- CompileTimeErrorCode.CONST_NOT_INITIALIZED,
+ CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION,
+ CompileTimeErrorCode.CONST_EVAL_THROWS_IDBZE,
CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL,
CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL_NUM_STRING,
CompileTimeErrorCode.CONST_EVAL_TYPE_INT,
CompileTimeErrorCode.CONST_EVAL_TYPE_NUM,
- CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION,
- CompileTimeErrorCode.CONST_EVAL_THROWS_IDBZE,
+ CompileTimeErrorCode.CONST_FORMAL_PARAMETER,
+ CompileTimeErrorCode.CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE,
+ CompileTimeErrorCode.CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE_FROM_DEFERRED_LIBRARY,
+ CompileTimeErrorCode.CONST_INSTANCE_FIELD,
+ CompileTimeErrorCode.CONST_MAP_KEY_EXPRESSION_TYPE_IMPLEMENTS_EQUALS,
+ CompileTimeErrorCode.CONST_NOT_INITIALIZED,
CompileTimeErrorCode.CONST_WITH_INVALID_TYPE_PARAMETERS,
CompileTimeErrorCode.CONST_WITH_NON_CONST,
CompileTimeErrorCode.CONST_WITH_NON_CONSTANT_ARGUMENT,
@@ -310,28 +361,29 @@
CompileTimeErrorCode.CONST_WITH_TYPE_PARAMETERS,
CompileTimeErrorCode.CONST_WITH_UNDEFINED_CONSTRUCTOR,
CompileTimeErrorCode.CONST_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT,
- CompileTimeErrorCode.DEFAULT_VALUE_IN_FUNCTION_TYPE_ALIAS,
CompileTimeErrorCode.DEFAULT_VALUE_IN_FUNCTION_TYPED_PARAMETER,
+ CompileTimeErrorCode.DEFAULT_VALUE_IN_FUNCTION_TYPE_ALIAS,
CompileTimeErrorCode.DEFAULT_VALUE_IN_REDIRECTING_FACTORY_CONSTRUCTOR,
CompileTimeErrorCode.DUPLICATE_CONSTRUCTOR_DEFAULT,
CompileTimeErrorCode.DUPLICATE_CONSTRUCTOR_NAME,
CompileTimeErrorCode.DUPLICATE_DEFINITION,
CompileTimeErrorCode.DUPLICATE_DEFINITION_INHERITANCE,
CompileTimeErrorCode.DUPLICATE_NAMED_ARGUMENT,
+ CompileTimeErrorCode.DUPLICATE_PART,
CompileTimeErrorCode.EXPORT_INTERNAL_LIBRARY,
CompileTimeErrorCode.EXPORT_OF_NON_LIBRARY,
+ CompileTimeErrorCode.EXTENDS_DEFERRED_CLASS,
+ CompileTimeErrorCode.EXTENDS_DISALLOWED_CLASS,
CompileTimeErrorCode.EXTENDS_ENUM,
CompileTimeErrorCode.EXTENDS_NON_CLASS,
- CompileTimeErrorCode.EXTENDS_DISALLOWED_CLASS,
- CompileTimeErrorCode.EXTENDS_DEFERRED_CLASS,
CompileTimeErrorCode.EXTRA_ARGUMENT_TO_ASSERT,
CompileTimeErrorCode.EXTRA_POSITIONAL_ARGUMENTS,
CompileTimeErrorCode.FIELD_INITIALIZED_BY_MULTIPLE_INITIALIZERS,
CompileTimeErrorCode.FIELD_INITIALIZED_IN_PARAMETER_AND_INITIALIZER,
- CompileTimeErrorCode.FINAL_INITIALIZED_MULTIPLE_TIMES,
CompileTimeErrorCode.FIELD_INITIALIZER_FACTORY_CONSTRUCTOR,
CompileTimeErrorCode.FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR,
CompileTimeErrorCode.FIELD_INITIALIZER_REDIRECTING_CONSTRUCTOR,
+ CompileTimeErrorCode.FINAL_INITIALIZED_MULTIPLE_TIMES,
CompileTimeErrorCode.GETTER_AND_METHOD_WITH_SAME_NAME,
CompileTimeErrorCode.IMPLEMENTS_DEFERRED_CLASS,
CompileTimeErrorCode.IMPLEMENTS_DISALLOWED_CLASS,
@@ -353,12 +405,12 @@
CompileTimeErrorCode.INSTANTIATE_ENUM,
CompileTimeErrorCode.INVALID_ANNOTATION,
CompileTimeErrorCode.INVALID_ANNOTATION_FROM_DEFERRED_LIBRARY,
- CompileTimeErrorCode.INVALID_IDENTIFIER_IN_ASYNC,
- CompileTimeErrorCode.INVALID_MODIFIER_ON_CONSTRUCTOR,
- CompileTimeErrorCode.INVALID_MODIFIER_ON_SETTER,
CompileTimeErrorCode.INVALID_CONSTANT,
CompileTimeErrorCode.INVALID_CONSTRUCTOR_NAME,
CompileTimeErrorCode.INVALID_FACTORY_NAME_NOT_A_CLASS,
+ CompileTimeErrorCode.INVALID_IDENTIFIER_IN_ASYNC,
+ CompileTimeErrorCode.INVALID_MODIFIER_ON_CONSTRUCTOR,
+ CompileTimeErrorCode.INVALID_MODIFIER_ON_SETTER,
CompileTimeErrorCode.INVALID_REFERENCE_TO_THIS,
CompileTimeErrorCode.INVALID_TYPE_ARGUMENT_IN_CONST_LIST,
CompileTimeErrorCode.INVALID_TYPE_ARGUMENT_IN_CONST_MAP,
@@ -380,10 +432,7 @@
CompileTimeErrorCode.MIXIN_WITH_NON_CLASS_SUPERCLASS,
CompileTimeErrorCode.MULTIPLE_REDIRECTING_CONSTRUCTOR_INVOCATIONS,
CompileTimeErrorCode.MULTIPLE_SUPER_INITIALIZERS,
- CompileTimeErrorCode.NO_ANNOTATION_CONSTRUCTOR_ARGUMENTS,
- CompileTimeErrorCode.NO_DEFAULT_SUPER_CONSTRUCTOR_EXPLICIT,
- CompileTimeErrorCode.NO_DEFAULT_SUPER_CONSTRUCTOR_IMPLICIT,
- CompileTimeErrorCode.NON_CONST_MAP_AS_EXPRESSION_STATEMENT,
+ CompileTimeErrorCode.NON_CONSTANT_ANNOTATION_CONSTRUCTOR,
CompileTimeErrorCode.NON_CONSTANT_CASE_EXPRESSION,
CompileTimeErrorCode.NON_CONSTANT_CASE_EXPRESSION_FROM_DEFERRED_LIBRARY,
CompileTimeErrorCode.NON_CONSTANT_DEFAULT_VALUE,
@@ -394,12 +443,14 @@
CompileTimeErrorCode.NON_CONSTANT_MAP_KEY_FROM_DEFERRED_LIBRARY,
CompileTimeErrorCode.NON_CONSTANT_MAP_VALUE,
CompileTimeErrorCode.NON_CONSTANT_MAP_VALUE_FROM_DEFERRED_LIBRARY,
- CompileTimeErrorCode.NON_CONSTANT_ANNOTATION_CONSTRUCTOR,
CompileTimeErrorCode.NON_CONSTANT_VALUE_IN_INITIALIZER,
- CompileTimeErrorCode
- .NON_CONSTANT_VALUE_IN_INITIALIZER_FROM_DEFERRED_LIBRARY,
- CompileTimeErrorCode.NOT_ENOUGH_REQUIRED_ARGUMENTS,
+ CompileTimeErrorCode.NON_CONSTANT_VALUE_IN_INITIALIZER_FROM_DEFERRED_LIBRARY,
+ CompileTimeErrorCode.NON_CONST_MAP_AS_EXPRESSION_STATEMENT,
CompileTimeErrorCode.NON_GENERATIVE_CONSTRUCTOR,
+ CompileTimeErrorCode.NOT_ENOUGH_REQUIRED_ARGUMENTS,
+ CompileTimeErrorCode.NO_ANNOTATION_CONSTRUCTOR_ARGUMENTS,
+ CompileTimeErrorCode.NO_DEFAULT_SUPER_CONSTRUCTOR_EXPLICIT,
+ CompileTimeErrorCode.NO_DEFAULT_SUPER_CONSTRUCTOR_IMPLICIT,
CompileTimeErrorCode.OBJECT_CANNOT_EXTEND_ANOTHER_CLASS,
CompileTimeErrorCode.OPTIONAL_PARAMETER_IN_OPERATOR,
CompileTimeErrorCode.PART_OF_NON_PART,
@@ -413,26 +464,27 @@
CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_EXTENDS,
CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_IMPLEMENTS,
CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_WITH,
+ CompileTimeErrorCode.REDIRECT_GENERATIVE_TO_MISSING_CONSTRUCTOR,
+ CompileTimeErrorCode.REDIRECT_GENERATIVE_TO_NON_GENERATIVE_CONSTRUCTOR,
CompileTimeErrorCode.REDIRECT_TO_MISSING_CONSTRUCTOR,
CompileTimeErrorCode.REDIRECT_TO_NON_CLASS,
CompileTimeErrorCode.REDIRECT_TO_NON_CONST_CONSTRUCTOR,
- CompileTimeErrorCode.REDIRECT_GENERATIVE_TO_MISSING_CONSTRUCTOR,
- CompileTimeErrorCode.REDIRECT_GENERATIVE_TO_NON_GENERATIVE_CONSTRUCTOR,
CompileTimeErrorCode.REFERENCED_BEFORE_DECLARATION,
CompileTimeErrorCode.RETHROW_OUTSIDE_CATCH,
CompileTimeErrorCode.RETURN_IN_GENERATIVE_CONSTRUCTOR,
CompileTimeErrorCode.RETURN_IN_GENERATOR,
CompileTimeErrorCode.SHARED_DEFERRED_PREFIX,
+ CompileTimeErrorCode.SUPER_INITIALIZER_IN_OBJECT,
CompileTimeErrorCode.SUPER_IN_INVALID_CONTEXT,
CompileTimeErrorCode.SUPER_IN_REDIRECTING_CONSTRUCTOR,
- CompileTimeErrorCode.SUPER_INITIALIZER_IN_OBJECT,
- CompileTimeErrorCode.TYPE_ARGUMENT_NOT_MATCHING_BOUNDS,
CompileTimeErrorCode.TYPE_ALIAS_CANNOT_REFERENCE_ITSELF,
+ CompileTimeErrorCode.TYPE_ARGUMENT_NOT_MATCHING_BOUNDS,
CompileTimeErrorCode.UNDEFINED_CLASS,
CompileTimeErrorCode.UNDEFINED_CONSTRUCTOR_IN_INITIALIZER,
CompileTimeErrorCode.UNDEFINED_CONSTRUCTOR_IN_INITIALIZER_DEFAULT,
CompileTimeErrorCode.UNDEFINED_NAMED_PARAMETER,
CompileTimeErrorCode.URI_DOES_NOT_EXIST,
+ CompileTimeErrorCode.URI_HAS_NOT_BEEN_GENERATED,
CompileTimeErrorCode.URI_WITH_INTERPOLATION,
CompileTimeErrorCode.WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR,
CompileTimeErrorCode.WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR_MINUS,
@@ -446,28 +498,32 @@
HintCode.DEAD_CODE_CATCH_FOLLOWING_CATCH,
HintCode.DEAD_CODE_ON_CATCH_SUBTYPE,
HintCode.DEPRECATED_MEMBER_USE,
- HintCode.DUPLICATE_IMPORT,
HintCode.DIVISION_OPTIMIZATION,
+ HintCode.DUPLICATE_IMPORT,
+ HintCode.FILE_IMPORT_INSIDE_LIB_REFERENCES_FILE_OUTSIDE,
+ HintCode.FILE_IMPORT_OUTSIDE_LIB_REFERENCES_FILE_INSIDE,
+ HintCode.IMPORT_DEFERRED_LIBRARY_WITH_LOAD_FUNCTION,
+ HintCode.INVALID_ASSIGNMENT,
HintCode.INVALID_FACTORY_ANNOTATION,
HintCode.INVALID_FACTORY_METHOD_DECL,
HintCode.INVALID_FACTORY_METHOD_IMPL,
+ HintCode.INVALID_USE_OF_PROTECTED_MEMBER,
HintCode.IS_DOUBLE,
HintCode.IS_INT,
HintCode.IS_NOT_DOUBLE,
HintCode.IS_NOT_INT,
- HintCode.IMPORT_DEFERRED_LIBRARY_WITH_LOAD_FUNCTION,
- HintCode.INVALID_ASSIGNMENT,
- HintCode.INVALID_USE_OF_PROTECTED_MEMBER,
HintCode.MISSING_JS_LIB_ANNOTATION,
HintCode.MISSING_REQUIRED_PARAM,
HintCode.MISSING_REQUIRED_PARAM_WITH_DETAILS,
HintCode.MISSING_RETURN,
+ HintCode.MUST_CALL_SUPER,
HintCode.NULL_AWARE_IN_CONDITION,
- HintCode.OVERRIDE_ON_NON_OVERRIDING_GETTER,
+ HintCode.OVERRIDE_EQUALS_BUT_NOT_HASH_CODE,
HintCode.OVERRIDE_ON_NON_OVERRIDING_FIELD,
+ HintCode.OVERRIDE_ON_NON_OVERRIDING_GETTER,
HintCode.OVERRIDE_ON_NON_OVERRIDING_METHOD,
HintCode.OVERRIDE_ON_NON_OVERRIDING_SETTER,
- HintCode.OVERRIDE_EQUALS_BUT_NOT_HASH_CODE,
+ HintCode.PACKAGE_IMPORT_CONTAINS_DOT_DOT,
HintCode.TYPE_CHECK_IS_NOT_NULL,
HintCode.TYPE_CHECK_IS_NULL,
HintCode.UNDEFINED_GETTER,
@@ -480,180 +536,17 @@
HintCode.UNNECESSARY_NO_SUCH_METHOD,
HintCode.UNNECESSARY_TYPE_CHECK_FALSE,
HintCode.UNNECESSARY_TYPE_CHECK_TRUE,
+ HintCode.UNUSED_CATCH_CLAUSE,
+ HintCode.UNUSED_CATCH_STACK,
HintCode.UNUSED_ELEMENT,
HintCode.UNUSED_FIELD,
HintCode.UNUSED_IMPORT,
- HintCode.UNUSED_CATCH_CLAUSE,
- HintCode.UNUSED_CATCH_STACK,
HintCode.UNUSED_LOCAL_VARIABLE,
HintCode.UNUSED_SHOWN_NAME,
HintCode.USE_OF_VOID_RESULT,
- HintCode.FILE_IMPORT_INSIDE_LIB_REFERENCES_FILE_OUTSIDE,
- HintCode.FILE_IMPORT_OUTSIDE_LIB_REFERENCES_FILE_INSIDE,
- HintCode.PACKAGE_IMPORT_CONTAINS_DOT_DOT,
HtmlErrorCode.PARSE_ERROR,
HtmlWarningCode.INVALID_URI,
HtmlWarningCode.URI_DOES_NOT_EXIST,
- StaticTypeWarningCode.EXPECTED_ONE_LIST_TYPE_ARGUMENTS,
- StaticTypeWarningCode.EXPECTED_TWO_MAP_TYPE_ARGUMENTS,
- StaticTypeWarningCode.ILLEGAL_ASYNC_GENERATOR_RETURN_TYPE,
- StaticTypeWarningCode.ILLEGAL_ASYNC_RETURN_TYPE,
- StaticTypeWarningCode.ILLEGAL_SYNC_GENERATOR_RETURN_TYPE,
- StaticTypeWarningCode.INACCESSIBLE_SETTER,
- StaticTypeWarningCode.INCONSISTENT_METHOD_INHERITANCE,
- StaticTypeWarningCode.INSTANCE_ACCESS_TO_STATIC_MEMBER,
- StaticTypeWarningCode.INVALID_ASSIGNMENT,
- StaticTypeWarningCode.INVOCATION_OF_NON_FUNCTION,
- StaticTypeWarningCode.INVOCATION_OF_NON_FUNCTION_EXPRESSION,
- StaticTypeWarningCode.NON_BOOL_CONDITION,
- StaticTypeWarningCode.NON_BOOL_EXPRESSION,
- StaticTypeWarningCode.NON_BOOL_NEGATION_EXPRESSION,
- StaticTypeWarningCode.NON_BOOL_OPERAND,
- StaticTypeWarningCode.NON_NULLABLE_FIELD_NOT_INITIALIZED,
- StaticTypeWarningCode.NON_TYPE_AS_TYPE_ARGUMENT,
- StaticTypeWarningCode.RETURN_OF_INVALID_TYPE,
- StaticTypeWarningCode.TYPE_ARGUMENT_NOT_MATCHING_BOUNDS,
- StaticTypeWarningCode.TYPE_PARAMETER_SUPERTYPE_OF_ITS_BOUND,
- StaticTypeWarningCode.UNDEFINED_ENUM_CONSTANT,
- StaticTypeWarningCode.UNDEFINED_FUNCTION,
- StaticTypeWarningCode.UNDEFINED_GETTER,
- StaticTypeWarningCode.UNDEFINED_METHOD,
- StaticTypeWarningCode.UNDEFINED_METHOD_WITH_CONSTRUCTOR,
- StaticTypeWarningCode.UNDEFINED_OPERATOR,
- StaticTypeWarningCode.UNDEFINED_SETTER,
- StaticTypeWarningCode.UNDEFINED_SUPER_GETTER,
- StaticTypeWarningCode.UNDEFINED_SUPER_METHOD,
- StaticTypeWarningCode.UNDEFINED_SUPER_OPERATOR,
- StaticTypeWarningCode.UNDEFINED_SUPER_SETTER,
- StaticTypeWarningCode.UNQUALIFIED_REFERENCE_TO_NON_LOCAL_STATIC_MEMBER,
- StaticTypeWarningCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS,
- StaticTypeWarningCode.YIELD_OF_INVALID_TYPE,
- StaticTypeWarningCode.FOR_IN_OF_INVALID_TYPE,
- StaticTypeWarningCode.FOR_IN_OF_INVALID_ELEMENT_TYPE,
- StaticWarningCode.AMBIGUOUS_IMPORT,
- StaticWarningCode.ARGUMENT_TYPE_NOT_ASSIGNABLE,
- StaticWarningCode.ASSIGNMENT_TO_CONST,
- StaticWarningCode.ASSIGNMENT_TO_FINAL,
- StaticWarningCode.ASSIGNMENT_TO_FINAL_NO_SETTER,
- StaticWarningCode.ASSIGNMENT_TO_FUNCTION,
- StaticWarningCode.ASSIGNMENT_TO_METHOD,
- StaticWarningCode.ASSIGNMENT_TO_TYPE,
- StaticWarningCode.CASE_BLOCK_NOT_TERMINATED,
- StaticWarningCode.CAST_TO_NON_TYPE,
- StaticWarningCode.CONCRETE_CLASS_WITH_ABSTRACT_MEMBER,
- StaticWarningCode.CONFLICTING_DART_IMPORT,
- StaticWarningCode.CONFLICTING_INSTANCE_GETTER_AND_SUPERCLASS_MEMBER,
- StaticWarningCode.CONFLICTING_INSTANCE_METHOD_SETTER,
- StaticWarningCode.CONFLICTING_INSTANCE_METHOD_SETTER2,
- StaticWarningCode.CONFLICTING_INSTANCE_SETTER_AND_SUPERCLASS_MEMBER,
- StaticWarningCode.CONFLICTING_STATIC_GETTER_AND_INSTANCE_SETTER,
- StaticWarningCode.CONFLICTING_STATIC_SETTER_AND_INSTANCE_MEMBER,
- StaticWarningCode.CONST_WITH_ABSTRACT_CLASS,
- StaticWarningCode.EQUAL_KEYS_IN_MAP,
- StaticWarningCode.EXPORT_DUPLICATED_LIBRARY_NAMED,
- StaticWarningCode.EXTRA_POSITIONAL_ARGUMENTS,
- StaticWarningCode.FIELD_INITIALIZED_IN_INITIALIZER_AND_DECLARATION,
- StaticWarningCode.FINAL_INITIALIZED_IN_DECLARATION_AND_CONSTRUCTOR,
- StaticWarningCode.FIELD_INITIALIZER_NOT_ASSIGNABLE,
- StaticWarningCode.FIELD_INITIALIZING_FORMAL_NOT_ASSIGNABLE,
- StaticWarningCode.FINAL_NOT_INITIALIZED,
- StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUCTOR_1,
- StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUCTOR_2,
- StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUCTOR_3_PLUS,
- StaticWarningCode.FUNCTION_WITHOUT_CALL,
- StaticWarningCode.IMPORT_DUPLICATED_LIBRARY_NAMED,
- StaticWarningCode.IMPORT_OF_NON_LIBRARY,
- StaticWarningCode.INCONSISTENT_METHOD_INHERITANCE_GETTER_AND_METHOD,
- StaticWarningCode.INSTANCE_METHOD_NAME_COLLIDES_WITH_SUPERCLASS_STATIC,
- StaticWarningCode.INVALID_GETTER_OVERRIDE_RETURN_TYPE,
- StaticWarningCode.INVALID_METHOD_OVERRIDE_NAMED_PARAM_TYPE,
- StaticWarningCode.INVALID_METHOD_OVERRIDE_TYPE_PARAMETERS,
- StaticWarningCode.INVALID_METHOD_OVERRIDE_TYPE_PARAMETER_BOUND,
- StaticWarningCode.INVALID_METHOD_OVERRIDE_NORMAL_PARAM_TYPE,
- StaticWarningCode.INVALID_METHOD_OVERRIDE_OPTIONAL_PARAM_TYPE,
- StaticWarningCode.INVALID_METHOD_OVERRIDE_RETURN_TYPE,
- StaticWarningCode.INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_NAMED,
- StaticWarningCode.INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_POSITIONAL,
- StaticWarningCode.INVALID_OVERRIDE_NAMED,
- StaticWarningCode.INVALID_OVERRIDE_POSITIONAL,
- StaticWarningCode.INVALID_OVERRIDE_REQUIRED,
- StaticWarningCode.INVALID_SETTER_OVERRIDE_NORMAL_PARAM_TYPE,
- StaticWarningCode.LIST_ELEMENT_TYPE_NOT_ASSIGNABLE,
- StaticWarningCode.MAP_KEY_TYPE_NOT_ASSIGNABLE,
- StaticWarningCode.MAP_VALUE_TYPE_NOT_ASSIGNABLE,
- StaticWarningCode.MISMATCHED_GETTER_AND_SETTER_TYPES,
- StaticWarningCode.MISMATCHED_GETTER_AND_SETTER_TYPES_FROM_SUPERTYPE,
- StaticWarningCode.MIXED_RETURN_TYPES,
- StaticWarningCode.NEW_WITH_ABSTRACT_CLASS,
- StaticWarningCode.NEW_WITH_INVALID_TYPE_PARAMETERS,
- StaticWarningCode.NEW_WITH_NON_TYPE,
- StaticWarningCode.NEW_WITH_UNDEFINED_CONSTRUCTOR,
- StaticWarningCode.NEW_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT,
- StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FIVE_PLUS,
- StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FOUR,
- StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_ONE,
- StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_THREE,
- StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_TWO,
- StaticWarningCode.NON_TYPE_IN_CATCH_CLAUSE,
- StaticWarningCode.NON_VOID_RETURN_FOR_OPERATOR,
- StaticWarningCode.NON_VOID_RETURN_FOR_SETTER,
- StaticWarningCode.NOT_A_TYPE,
- StaticWarningCode.NOT_ENOUGH_REQUIRED_ARGUMENTS,
- StaticWarningCode.PART_OF_DIFFERENT_LIBRARY,
- StaticWarningCode.REDIRECT_TO_INVALID_FUNCTION_TYPE,
- StaticWarningCode.REDIRECT_TO_INVALID_RETURN_TYPE,
- StaticWarningCode.REDIRECT_TO_MISSING_CONSTRUCTOR,
- StaticWarningCode.REDIRECT_TO_NON_CLASS,
- StaticWarningCode.RETURN_WITHOUT_VALUE,
- StaticWarningCode.STATIC_ACCESS_TO_INSTANCE_MEMBER,
- StaticWarningCode.SWITCH_EXPRESSION_NOT_ASSIGNABLE,
- StaticWarningCode.TYPE_ANNOTATION_DEFERRED_CLASS,
- StaticWarningCode.TYPE_TEST_WITH_NON_TYPE,
- StaticWarningCode.TYPE_TEST_WITH_UNDEFINED_NAME,
- StaticWarningCode.TYPE_PARAMETER_REFERENCED_BY_STATIC,
- StaticWarningCode.UNDEFINED_CLASS,
- StaticWarningCode.UNDEFINED_CLASS_BOOLEAN,
- StaticWarningCode.UNDEFINED_GETTER,
- StaticWarningCode.UNDEFINED_IDENTIFIER,
- StaticWarningCode.UNDEFINED_NAMED_PARAMETER,
- StaticWarningCode.UNDEFINED_SETTER,
- StaticWarningCode.UNDEFINED_STATIC_METHOD_OR_GETTER,
- StaticWarningCode.UNDEFINED_SUPER_GETTER,
- StaticWarningCode.UNDEFINED_SUPER_SETTER,
- StaticWarningCode.VOID_RETURN_FOR_GETTER,
- StaticWarningCode.MISSING_ENUM_CONSTANT_IN_SWITCH,
- StrongModeCode.ASSIGNMENT_CAST,
- StrongModeCode.DOWN_CAST_COMPOSITE,
- StrongModeCode.DOWN_CAST_IMPLICIT,
- StrongModeCode.DYNAMIC_CAST,
- StrongModeCode.DYNAMIC_INVOKE,
- StrongModeCode.IMPLICIT_DYNAMIC_FIELD,
- StrongModeCode.IMPLICIT_DYNAMIC_FUNCTION,
- StrongModeCode.IMPLICIT_DYNAMIC_INVOKE,
- StrongModeCode.IMPLICIT_DYNAMIC_LIST_LITERAL,
- StrongModeCode.IMPLICIT_DYNAMIC_MAP_LITERAL,
- StrongModeCode.IMPLICIT_DYNAMIC_METHOD,
- StrongModeCode.IMPLICIT_DYNAMIC_PARAMETER,
- StrongModeCode.IMPLICIT_DYNAMIC_RETURN,
- StrongModeCode.IMPLICIT_DYNAMIC_TYPE,
- StrongModeCode.IMPLICIT_DYNAMIC_VARIABLE,
- StrongModeCode.INFERRED_TYPE,
- StrongModeCode.INFERRED_TYPE_ALLOCATION,
- StrongModeCode.INFERRED_TYPE_CLOSURE,
- StrongModeCode.INFERRED_TYPE_LITERAL,
- StrongModeCode.INVALID_FIELD_OVERRIDE,
- StrongModeCode.INVALID_METHOD_OVERRIDE,
- StrongModeCode.INVALID_METHOD_OVERRIDE_FROM_BASE,
- StrongModeCode.INVALID_METHOD_OVERRIDE_FROM_MIXIN,
- StrongModeCode.INVALID_PARAMETER_DECLARATION,
- StrongModeCode.INVALID_SUPER_INVOCATION,
- StrongModeCode.NON_GROUND_TYPE_CHECK_INFO,
- StrongModeCode.STATIC_TYPE_ERROR,
- StrongModeCode.UNSAFE_BLOCK_CLOSURE_INFERENCE,
- TodoCode.TODO,
- //
- // parser.dart:
- //
ParserErrorCode.ABSTRACT_CLASS_MEMBER,
ParserErrorCode.ABSTRACT_ENUM,
ParserErrorCode.ABSTRACT_STATIC_METHOD,
@@ -662,10 +555,10 @@
ParserErrorCode.ABSTRACT_TYPEDEF,
ParserErrorCode.ANNOTATION_ON_ENUM_CONSTANT,
ParserErrorCode.ASYNC_KEYWORD_USED_AS_IDENTIFIER,
- ParserErrorCode.ASYNC_NOT_SUPPORTED,
ParserErrorCode.BREAK_OUTSIDE_OF_LOOP,
ParserErrorCode.CLASS_IN_CLASS,
ParserErrorCode.COLON_IN_PLACE_OF_IN,
+ ParserErrorCode.CONSTRUCTOR_WITH_RETURN_TYPE,
ParserErrorCode.CONST_AND_FINAL,
ParserErrorCode.CONST_AND_VAR,
ParserErrorCode.CONST_CLASS,
@@ -674,13 +567,12 @@
ParserErrorCode.CONST_FACTORY,
ParserErrorCode.CONST_METHOD,
ParserErrorCode.CONST_TYPEDEF,
- ParserErrorCode.CONSTRUCTOR_WITH_RETURN_TYPE,
ParserErrorCode.CONTINUE_OUTSIDE_OF_LOOP,
ParserErrorCode.CONTINUE_WITHOUT_LABEL_IN_CASE,
ParserErrorCode.DEPRECATED_CLASS_TYPE_ALIAS,
ParserErrorCode.DIRECTIVE_AFTER_DECLARATION,
- ParserErrorCode.DUPLICATE_LABEL_IN_SWITCH_STATEMENT,
ParserErrorCode.DUPLICATED_MODIFIER,
+ ParserErrorCode.DUPLICATE_LABEL_IN_SWITCH_STATEMENT,
ParserErrorCode.EMPTY_ENUM_BODY,
ParserErrorCode.ENUM_IN_CLASS,
ParserErrorCode.EQUALITY_CANNOT_BE_EQUALITY_OPERAND,
@@ -705,8 +597,8 @@
ParserErrorCode.EXTERNAL_SETTER_WITH_BODY,
ParserErrorCode.EXTERNAL_TYPEDEF,
ParserErrorCode.FACTORY_TOP_LEVEL_DECLARATION,
- ParserErrorCode.FACTORY_WITH_INITIALIZERS,
ParserErrorCode.FACTORY_WITHOUT_BODY,
+ ParserErrorCode.FACTORY_WITH_INITIALIZERS,
ParserErrorCode.FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR,
ParserErrorCode.FINAL_AND_VAR,
ParserErrorCode.FINAL_CLASS,
@@ -745,11 +637,11 @@
ParserErrorCode.MISSING_EXPRESSION_IN_THROW,
ParserErrorCode.MISSING_FUNCTION_BODY,
ParserErrorCode.MISSING_FUNCTION_PARAMETERS,
- ParserErrorCode.MISSING_METHOD_PARAMETERS,
ParserErrorCode.MISSING_GET,
ParserErrorCode.MISSING_IDENTIFIER,
ParserErrorCode.MISSING_INITIALIZER,
ParserErrorCode.MISSING_KEYWORD_OPERATOR,
+ ParserErrorCode.MISSING_METHOD_PARAMETERS,
ParserErrorCode.MISSING_NAME_IN_LIBRARY_DIRECTIVE,
ParserErrorCode.MISSING_NAME_IN_PART_OF_DIRECTIVE,
ParserErrorCode.MISSING_PREFIX_IN_DEFERRED_IMPORT,
@@ -777,6 +669,10 @@
ParserErrorCode.NON_STRING_LITERAL_AS_URI,
ParserErrorCode.NON_USER_DEFINABLE_OPERATOR,
ParserErrorCode.NORMAL_BEFORE_OPTIONAL_PARAMETERS,
+ ParserErrorCode.NULLABLE_TYPE_IN_EXTENDS,
+ ParserErrorCode.NULLABLE_TYPE_IN_IMPLEMENTS,
+ ParserErrorCode.NULLABLE_TYPE_IN_WITH,
+ ParserErrorCode.NULLABLE_TYPE_PARAMETER,
ParserErrorCode.POSITIONAL_AFTER_NAMED_ARGUMENT,
ParserErrorCode.POSITIONAL_PARAMETER_OUTSIDE_GROUP,
ParserErrorCode.REDIRECTING_CONSTRUCTOR_WITH_BODY,
@@ -796,10 +692,6 @@
ParserErrorCode.TYPEDEF_IN_CLASS,
ParserErrorCode.UNEXPECTED_TERMINATOR_FOR_PARAMETER_GROUP,
ParserErrorCode.UNEXPECTED_TOKEN,
- ParserErrorCode.WITH_BEFORE_EXTENDS,
- ParserErrorCode.WITH_WITHOUT_EXTENDS,
- ParserErrorCode.WRONG_SEPARATOR_FOR_POSITIONAL_PARAMETER,
- ParserErrorCode.WRONG_TERMINATOR_FOR_PARAMETER_GROUP,
ParserErrorCode.VAR_AND_TYPE,
ParserErrorCode.VAR_AS_TYPE_NAME,
ParserErrorCode.VAR_CLASS,
@@ -808,9 +700,10 @@
ParserErrorCode.VAR_TYPEDEF,
ParserErrorCode.VOID_PARAMETER,
ParserErrorCode.VOID_VARIABLE,
- //
- // scanner.dart:
- //
+ ParserErrorCode.WITH_BEFORE_EXTENDS,
+ ParserErrorCode.WITH_WITHOUT_EXTENDS,
+ ParserErrorCode.WRONG_SEPARATOR_FOR_POSITIONAL_PARAMETER,
+ ParserErrorCode.WRONG_TERMINATOR_FOR_PARAMETER_GROUP,
ScannerErrorCode.ILLEGAL_CHARACTER,
ScannerErrorCode.MISSING_DIGIT,
ScannerErrorCode.MISSING_HEX_DIGIT,
@@ -818,6 +711,165 @@
ScannerErrorCode.UNABLE_GET_CONTENT,
ScannerErrorCode.UNTERMINATED_MULTI_LINE_COMMENT,
ScannerErrorCode.UNTERMINATED_STRING_LITERAL,
+ StaticTypeWarningCode.EXPECTED_ONE_LIST_TYPE_ARGUMENTS,
+ StaticTypeWarningCode.EXPECTED_TWO_MAP_TYPE_ARGUMENTS,
+ StaticTypeWarningCode.FOR_IN_OF_INVALID_ELEMENT_TYPE,
+ StaticTypeWarningCode.FOR_IN_OF_INVALID_TYPE,
+ StaticTypeWarningCode.ILLEGAL_ASYNC_GENERATOR_RETURN_TYPE,
+ StaticTypeWarningCode.ILLEGAL_ASYNC_RETURN_TYPE,
+ StaticTypeWarningCode.ILLEGAL_SYNC_GENERATOR_RETURN_TYPE,
+ StaticTypeWarningCode.INCONSISTENT_METHOD_INHERITANCE,
+ StaticTypeWarningCode.INSTANCE_ACCESS_TO_STATIC_MEMBER,
+ StaticTypeWarningCode.INVALID_ASSIGNMENT,
+ StaticTypeWarningCode.INVOCATION_OF_NON_FUNCTION,
+ StaticTypeWarningCode.INVOCATION_OF_NON_FUNCTION_EXPRESSION,
+ StaticTypeWarningCode.NON_BOOL_CONDITION,
+ StaticTypeWarningCode.NON_BOOL_EXPRESSION,
+ StaticTypeWarningCode.NON_BOOL_NEGATION_EXPRESSION,
+ StaticTypeWarningCode.NON_BOOL_OPERAND,
+ StaticTypeWarningCode.NON_NULLABLE_FIELD_NOT_INITIALIZED,
+ StaticTypeWarningCode.NON_TYPE_AS_TYPE_ARGUMENT,
+ StaticTypeWarningCode.RETURN_OF_INVALID_TYPE,
+ StaticTypeWarningCode.TYPE_ARGUMENT_NOT_MATCHING_BOUNDS,
+ StaticTypeWarningCode.TYPE_PARAMETER_SUPERTYPE_OF_ITS_BOUND,
+ StaticTypeWarningCode.UNDEFINED_ENUM_CONSTANT,
+ StaticTypeWarningCode.UNDEFINED_FUNCTION,
+ StaticTypeWarningCode.UNDEFINED_GETTER,
+ StaticTypeWarningCode.UNDEFINED_METHOD,
+ StaticTypeWarningCode.UNDEFINED_METHOD_WITH_CONSTRUCTOR,
+ StaticTypeWarningCode.UNDEFINED_OPERATOR,
+ StaticTypeWarningCode.UNDEFINED_SETTER,
+ StaticTypeWarningCode.UNDEFINED_SUPER_GETTER,
+ StaticTypeWarningCode.UNDEFINED_SUPER_METHOD,
+ StaticTypeWarningCode.UNDEFINED_SUPER_OPERATOR,
+ StaticTypeWarningCode.UNDEFINED_SUPER_SETTER,
+ StaticTypeWarningCode.UNQUALIFIED_REFERENCE_TO_NON_LOCAL_STATIC_MEMBER,
+ StaticTypeWarningCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS,
+ StaticTypeWarningCode.YIELD_OF_INVALID_TYPE,
+ StaticWarningCode.AMBIGUOUS_IMPORT,
+ StaticWarningCode.ARGUMENT_TYPE_NOT_ASSIGNABLE,
+ StaticWarningCode.ASSIGNMENT_TO_CONST,
+ StaticWarningCode.ASSIGNMENT_TO_FINAL,
+ StaticWarningCode.ASSIGNMENT_TO_FINAL_NO_SETTER,
+ StaticWarningCode.ASSIGNMENT_TO_FUNCTION,
+ StaticWarningCode.ASSIGNMENT_TO_METHOD,
+ StaticWarningCode.ASSIGNMENT_TO_TYPE,
+ StaticWarningCode.CASE_BLOCK_NOT_TERMINATED,
+ StaticWarningCode.CAST_TO_NON_TYPE,
+ StaticWarningCode.CONCRETE_CLASS_WITH_ABSTRACT_MEMBER,
+ StaticWarningCode.CONFLICTING_DART_IMPORT,
+ StaticWarningCode.CONFLICTING_INSTANCE_GETTER_AND_SUPERCLASS_MEMBER,
+ StaticWarningCode.CONFLICTING_INSTANCE_METHOD_SETTER,
+ StaticWarningCode.CONFLICTING_INSTANCE_METHOD_SETTER2,
+ StaticWarningCode.CONFLICTING_INSTANCE_SETTER_AND_SUPERCLASS_MEMBER,
+ StaticWarningCode.CONFLICTING_STATIC_GETTER_AND_INSTANCE_SETTER,
+ StaticWarningCode.CONFLICTING_STATIC_SETTER_AND_INSTANCE_MEMBER,
+ StaticWarningCode.CONST_WITH_ABSTRACT_CLASS,
+ StaticWarningCode.EQUAL_KEYS_IN_MAP,
+ StaticWarningCode.EXPORT_DUPLICATED_LIBRARY_NAMED,
+ StaticWarningCode.EXTRA_POSITIONAL_ARGUMENTS,
+ StaticWarningCode.FIELD_INITIALIZED_IN_INITIALIZER_AND_DECLARATION,
+ StaticWarningCode.FINAL_INITIALIZED_IN_DECLARATION_AND_CONSTRUCTOR,
+ StaticWarningCode.FIELD_INITIALIZER_NOT_ASSIGNABLE,
+ StaticWarningCode.FIELD_INITIALIZING_FORMAL_NOT_ASSIGNABLE,
+ StaticWarningCode.FINAL_NOT_INITIALIZED,
+ StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUCTOR_1,
+ StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUCTOR_2,
+ StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUCTOR_3_PLUS,
+ StaticWarningCode.FUNCTION_WITHOUT_CALL,
+ StaticWarningCode.IMPORT_DUPLICATED_LIBRARY_NAMED,
+ StaticWarningCode.IMPORT_OF_NON_LIBRARY,
+ StaticWarningCode.INCONSISTENT_METHOD_INHERITANCE_GETTER_AND_METHOD,
+ StaticWarningCode.INSTANCE_METHOD_NAME_COLLIDES_WITH_SUPERCLASS_STATIC,
+ StaticWarningCode.INVALID_GETTER_OVERRIDE_RETURN_TYPE,
+ StaticWarningCode.INVALID_METHOD_OVERRIDE_NAMED_PARAM_TYPE,
+ StaticWarningCode.INVALID_METHOD_OVERRIDE_NORMAL_PARAM_TYPE,
+ StaticWarningCode.INVALID_METHOD_OVERRIDE_OPTIONAL_PARAM_TYPE,
+ StaticWarningCode.INVALID_METHOD_OVERRIDE_RETURN_TYPE,
+ StaticWarningCode.INVALID_METHOD_OVERRIDE_TYPE_PARAMETERS,
+ StaticWarningCode.INVALID_METHOD_OVERRIDE_TYPE_PARAMETER_BOUND,
+ StaticWarningCode.INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_NAMED,
+ StaticWarningCode.INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_POSITIONAL,
+ StaticWarningCode.INVALID_OVERRIDE_NAMED,
+ StaticWarningCode.INVALID_OVERRIDE_POSITIONAL,
+ StaticWarningCode.INVALID_OVERRIDE_REQUIRED,
+ StaticWarningCode.INVALID_SETTER_OVERRIDE_NORMAL_PARAM_TYPE,
+ StaticWarningCode.LIST_ELEMENT_TYPE_NOT_ASSIGNABLE,
+ StaticWarningCode.MAP_KEY_TYPE_NOT_ASSIGNABLE,
+ StaticWarningCode.MAP_VALUE_TYPE_NOT_ASSIGNABLE,
+ StaticWarningCode.MISMATCHED_GETTER_AND_SETTER_TYPES,
+ StaticWarningCode.MISMATCHED_GETTER_AND_SETTER_TYPES_FROM_SUPERTYPE,
+ StaticWarningCode.MISSING_ENUM_CONSTANT_IN_SWITCH,
+ StaticWarningCode.MIXED_RETURN_TYPES,
+ StaticWarningCode.NEW_WITH_ABSTRACT_CLASS,
+ StaticWarningCode.NEW_WITH_INVALID_TYPE_PARAMETERS,
+ StaticWarningCode.NEW_WITH_NON_TYPE,
+ StaticWarningCode.NEW_WITH_UNDEFINED_CONSTRUCTOR,
+ StaticWarningCode.NEW_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT,
+ StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FIVE_PLUS,
+ StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FOUR,
+ StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_ONE,
+ StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_THREE,
+ StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_TWO,
+ StaticWarningCode.NON_TYPE_IN_CATCH_CLAUSE,
+ StaticWarningCode.NON_VOID_RETURN_FOR_OPERATOR,
+ StaticWarningCode.NON_VOID_RETURN_FOR_SETTER,
+ StaticWarningCode.NOT_A_TYPE,
+ StaticWarningCode.NOT_ENOUGH_REQUIRED_ARGUMENTS,
+ StaticWarningCode.PART_OF_DIFFERENT_LIBRARY,
+ StaticWarningCode.REDIRECT_TO_INVALID_FUNCTION_TYPE,
+ StaticWarningCode.REDIRECT_TO_INVALID_RETURN_TYPE,
+ StaticWarningCode.REDIRECT_TO_MISSING_CONSTRUCTOR,
+ StaticWarningCode.REDIRECT_TO_NON_CLASS,
+ StaticWarningCode.RETURN_WITHOUT_VALUE,
+ StaticWarningCode.STATIC_ACCESS_TO_INSTANCE_MEMBER,
+ StaticWarningCode.SWITCH_EXPRESSION_NOT_ASSIGNABLE,
+ StaticWarningCode.TYPE_ANNOTATION_DEFERRED_CLASS,
+ StaticWarningCode.TYPE_PARAMETER_REFERENCED_BY_STATIC,
+ StaticWarningCode.TYPE_TEST_WITH_NON_TYPE,
+ StaticWarningCode.TYPE_TEST_WITH_UNDEFINED_NAME,
+ StaticWarningCode.UNDEFINED_CLASS,
+ StaticWarningCode.UNDEFINED_CLASS_BOOLEAN,
+ StaticWarningCode.UNDEFINED_GETTER,
+ StaticWarningCode.UNDEFINED_IDENTIFIER,
+ StaticWarningCode.UNDEFINED_IDENTIFIER_AWAIT,
+ StaticWarningCode.UNDEFINED_NAMED_PARAMETER,
+ StaticWarningCode.UNDEFINED_SETTER,
+ StaticWarningCode.UNDEFINED_STATIC_METHOD_OR_GETTER,
+ StaticWarningCode.UNDEFINED_SUPER_GETTER,
+ StaticWarningCode.UNDEFINED_SUPER_SETTER,
+ StaticWarningCode.VOID_RETURN_FOR_GETTER,
+ StrongModeCode.ASSIGNMENT_CAST,
+ StrongModeCode.COULD_NOT_INFER,
+ StrongModeCode.DOWN_CAST_COMPOSITE,
+ StrongModeCode.DOWN_CAST_IMPLICIT,
+ StrongModeCode.DOWN_CAST_IMPLICIT_ASSIGN,
+ StrongModeCode.DYNAMIC_CAST,
+ StrongModeCode.DYNAMIC_INVOKE,
+ StrongModeCode.IMPLICIT_DYNAMIC_FIELD,
+ StrongModeCode.IMPLICIT_DYNAMIC_FUNCTION,
+ StrongModeCode.IMPLICIT_DYNAMIC_INVOKE,
+ StrongModeCode.IMPLICIT_DYNAMIC_LIST_LITERAL,
+ StrongModeCode.IMPLICIT_DYNAMIC_MAP_LITERAL,
+ StrongModeCode.IMPLICIT_DYNAMIC_METHOD,
+ StrongModeCode.IMPLICIT_DYNAMIC_PARAMETER,
+ StrongModeCode.IMPLICIT_DYNAMIC_RETURN,
+ StrongModeCode.IMPLICIT_DYNAMIC_TYPE,
+ StrongModeCode.IMPLICIT_DYNAMIC_VARIABLE,
+ StrongModeCode.INFERRED_TYPE,
+ StrongModeCode.INFERRED_TYPE_ALLOCATION,
+ StrongModeCode.INFERRED_TYPE_CLOSURE,
+ StrongModeCode.INFERRED_TYPE_LITERAL,
+ StrongModeCode.INVALID_FIELD_OVERRIDE,
+ StrongModeCode.INVALID_METHOD_OVERRIDE,
+ StrongModeCode.INVALID_METHOD_OVERRIDE_FROM_BASE,
+ StrongModeCode.INVALID_METHOD_OVERRIDE_FROM_MIXIN,
+ StrongModeCode.INVALID_PARAMETER_DECLARATION,
+ StrongModeCode.INVALID_SUPER_INVOCATION,
+ StrongModeCode.NON_GROUND_TYPE_CHECK_INFO,
+ StrongModeCode.STATIC_TYPE_ERROR,
+ StrongModeCode.UNSAFE_BLOCK_CLOSURE_INFERENCE,
+ TodoCode.TODO,
];
/**
diff --git a/pkg/analyzer/lib/src/dart/ast/utilities.dart b/pkg/analyzer/lib/src/dart/ast/utilities.dart
index 8cf5463..a1e5448 100644
--- a/pkg/analyzer/lib/src/dart/ast/utilities.dart
+++ b/pkg/analyzer/lib/src/dart/ast/utilities.dart
@@ -17,6 +17,7 @@
import 'package:analyzer/src/generated/java_core.dart';
import 'package:analyzer/src/generated/utilities_collection.dart' show TokenMap;
import 'package:analyzer/src/generated/utilities_dart.dart';
+import 'package:meta/meta.dart';
/**
* A function used to handle exceptions that are thrown by delegates while using
@@ -7913,3 +7914,1163 @@
}
}
}
+
+/**
+ * A visitor used to write a source representation of a visited AST node (and
+ * all of it's children) to a sink.
+ */
+class ToSourceVisitor2 implements AstVisitor<Object> {
+ /**
+ * The sink to which the source is to be written.
+ */
+ @protected
+ final StringSink sink;
+
+ /**
+ * Initialize a newly created visitor to write source code representing the
+ * visited nodes to the given [sink].
+ */
+ ToSourceVisitor2(this.sink);
+
+ /**
+ * Visit the given function [body], printing the [prefix] before if the body
+ * is not empty.
+ */
+ @protected
+ void safelyVisitFunctionWithPrefix(String prefix, FunctionBody body) {
+ if (body is! EmptyFunctionBody) {
+ sink.write(prefix);
+ }
+ safelyVisitNode(body);
+ }
+
+ /**
+ * Safely visit the given [node].
+ */
+ @protected
+ void safelyVisitNode(AstNode node) {
+ if (node != null) {
+ node.accept(this);
+ }
+ }
+
+ /**
+ * Print a list of [nodes] without any separation.
+ */
+ @protected
+ void safelyVisitNodeList(NodeList<AstNode> nodes) {
+ safelyVisitNodeListWithSeparator(nodes, "");
+ }
+
+ /**
+ * Print a list of [nodes], separated by the given [separator].
+ */
+ @protected
+ void safelyVisitNodeListWithSeparator(
+ NodeList<AstNode> nodes, String separator) {
+ if (nodes != null) {
+ int size = nodes.length;
+ for (int i = 0; i < size; i++) {
+ if (i > 0) {
+ sink.write(separator);
+ }
+ nodes[i].accept(this);
+ }
+ }
+ }
+
+ /**
+ * Print a list of [nodes], prefixed by the given [prefix] if the list is not
+ * empty, and separated by the given [separator].
+ */
+ @protected
+ void safelyVisitNodeListWithSeparatorAndPrefix(
+ String prefix, NodeList<AstNode> nodes, String separator) {
+ if (nodes != null) {
+ int size = nodes.length;
+ if (size > 0) {
+ sink.write(prefix);
+ for (int i = 0; i < size; i++) {
+ if (i > 0) {
+ sink.write(separator);
+ }
+ nodes[i].accept(this);
+ }
+ }
+ }
+ }
+
+ /**
+ * Print a list of [nodes], separated by the given [separator], followed by
+ * the given [suffix] if the list is not empty.
+ */
+ @protected
+ void safelyVisitNodeListWithSeparatorAndSuffix(
+ NodeList<AstNode> nodes, String separator, String suffix) {
+ if (nodes != null) {
+ int size = nodes.length;
+ if (size > 0) {
+ for (int i = 0; i < size; i++) {
+ if (i > 0) {
+ sink.write(separator);
+ }
+ nodes[i].accept(this);
+ }
+ sink.write(suffix);
+ }
+ }
+ }
+
+ /**
+ * Safely visit the given [node], printing the [prefix] before the node if it
+ * is non-`null`.
+ */
+ @protected
+ void safelyVisitNodeWithPrefix(String prefix, AstNode node) {
+ if (node != null) {
+ sink.write(prefix);
+ node.accept(this);
+ }
+ }
+
+ /**
+ * Safely visit the given [node], printing the [suffix] after the node if it
+ * is non-`null`.
+ */
+ @protected
+ void safelyVisitNodeWithSuffix(AstNode node, String suffix) {
+ if (node != null) {
+ node.accept(this);
+ sink.write(suffix);
+ }
+ }
+
+ /**
+ * Safely visit the given [token], printing the [suffix] after the token if it
+ * is non-`null`.
+ */
+ @protected
+ void safelyVisitTokenWithSuffix(Token token, String suffix) {
+ if (token != null) {
+ sink.write(token.lexeme);
+ sink.write(suffix);
+ }
+ }
+
+ @override
+ Object visitAdjacentStrings(AdjacentStrings node) {
+ safelyVisitNodeListWithSeparator(node.strings, " ");
+ return null;
+ }
+
+ @override
+ Object visitAnnotation(Annotation node) {
+ sink.write('@');
+ safelyVisitNode(node.name);
+ safelyVisitNodeWithPrefix(".", node.constructorName);
+ safelyVisitNode(node.arguments);
+ return null;
+ }
+
+ @override
+ Object visitArgumentList(ArgumentList node) {
+ sink.write('(');
+ safelyVisitNodeListWithSeparator(node.arguments, ", ");
+ sink.write(')');
+ return null;
+ }
+
+ @override
+ Object visitAsExpression(AsExpression node) {
+ safelyVisitNode(node.expression);
+ sink.write(" as ");
+ safelyVisitNode(node.type);
+ return null;
+ }
+
+ @override
+ Object visitAssertStatement(AssertStatement node) {
+ sink.write("assert (");
+ safelyVisitNode(node.condition);
+ if (node.message != null) {
+ sink.write(', ');
+ safelyVisitNode(node.message);
+ }
+ sink.write(");");
+ return null;
+ }
+
+ @override
+ Object visitAssignmentExpression(AssignmentExpression node) {
+ safelyVisitNode(node.leftHandSide);
+ sink.write(' ');
+ sink.write(node.operator.lexeme);
+ sink.write(' ');
+ safelyVisitNode(node.rightHandSide);
+ return null;
+ }
+
+ @override
+ Object visitAwaitExpression(AwaitExpression node) {
+ sink.write("await ");
+ safelyVisitNode(node.expression);
+ return null;
+ }
+
+ @override
+ Object visitBinaryExpression(BinaryExpression node) {
+ safelyVisitNode(node.leftOperand);
+ sink.write(' ');
+ sink.write(node.operator.lexeme);
+ sink.write(' ');
+ safelyVisitNode(node.rightOperand);
+ return null;
+ }
+
+ @override
+ Object visitBlock(Block node) {
+ sink.write('{');
+ safelyVisitNodeListWithSeparator(node.statements, " ");
+ sink.write('}');
+ return null;
+ }
+
+ @override
+ Object visitBlockFunctionBody(BlockFunctionBody node) {
+ Token keyword = node.keyword;
+ if (keyword != null) {
+ sink.write(keyword.lexeme);
+ if (node.star != null) {
+ sink.write('*');
+ }
+ sink.write(' ');
+ }
+ safelyVisitNode(node.block);
+ return null;
+ }
+
+ @override
+ Object visitBooleanLiteral(BooleanLiteral node) {
+ sink.write(node.literal.lexeme);
+ return null;
+ }
+
+ @override
+ Object visitBreakStatement(BreakStatement node) {
+ sink.write("break");
+ safelyVisitNodeWithPrefix(" ", node.label);
+ sink.write(";");
+ return null;
+ }
+
+ @override
+ Object visitCascadeExpression(CascadeExpression node) {
+ safelyVisitNode(node.target);
+ safelyVisitNodeList(node.cascadeSections);
+ return null;
+ }
+
+ @override
+ Object visitCatchClause(CatchClause node) {
+ safelyVisitNodeWithPrefix("on ", node.exceptionType);
+ if (node.catchKeyword != null) {
+ if (node.exceptionType != null) {
+ sink.write(' ');
+ }
+ sink.write("catch (");
+ safelyVisitNode(node.exceptionParameter);
+ safelyVisitNodeWithPrefix(", ", node.stackTraceParameter);
+ sink.write(") ");
+ } else {
+ sink.write(" ");
+ }
+ safelyVisitNode(node.body);
+ return null;
+ }
+
+ @override
+ Object visitClassDeclaration(ClassDeclaration node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
+ safelyVisitTokenWithSuffix(node.abstractKeyword, " ");
+ sink.write("class ");
+ safelyVisitNode(node.name);
+ safelyVisitNode(node.typeParameters);
+ safelyVisitNodeWithPrefix(" ", node.extendsClause);
+ safelyVisitNodeWithPrefix(" ", node.withClause);
+ safelyVisitNodeWithPrefix(" ", node.implementsClause);
+ sink.write(" {");
+ safelyVisitNodeListWithSeparator(node.members, " ");
+ sink.write("}");
+ return null;
+ }
+
+ @override
+ Object visitClassTypeAlias(ClassTypeAlias node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
+ if (node.abstractKeyword != null) {
+ sink.write("abstract ");
+ }
+ sink.write("class ");
+ safelyVisitNode(node.name);
+ safelyVisitNode(node.typeParameters);
+ sink.write(" = ");
+ safelyVisitNode(node.superclass);
+ safelyVisitNodeWithPrefix(" ", node.withClause);
+ safelyVisitNodeWithPrefix(" ", node.implementsClause);
+ sink.write(";");
+ return null;
+ }
+
+ @override
+ Object visitComment(Comment node) => null;
+
+ @override
+ Object visitCommentReference(CommentReference node) => null;
+
+ @override
+ Object visitCompilationUnit(CompilationUnit node) {
+ ScriptTag scriptTag = node.scriptTag;
+ NodeList<Directive> directives = node.directives;
+ safelyVisitNode(scriptTag);
+ String prefix = scriptTag == null ? "" : " ";
+ safelyVisitNodeListWithSeparatorAndPrefix(prefix, directives, " ");
+ prefix = scriptTag == null && directives.isEmpty ? "" : " ";
+ safelyVisitNodeListWithSeparatorAndPrefix(prefix, node.declarations, " ");
+ return null;
+ }
+
+ @override
+ Object visitConditionalExpression(ConditionalExpression node) {
+ safelyVisitNode(node.condition);
+ sink.write(" ? ");
+ safelyVisitNode(node.thenExpression);
+ sink.write(" : ");
+ safelyVisitNode(node.elseExpression);
+ return null;
+ }
+
+ @override
+ Object visitConfiguration(Configuration node) {
+ sink.write('if (');
+ safelyVisitNode(node.name);
+ safelyVisitNodeWithPrefix(" == ", node.value);
+ sink.write(') ');
+ safelyVisitNode(node.uri);
+ return null;
+ }
+
+ @override
+ Object visitConstructorDeclaration(ConstructorDeclaration node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
+ safelyVisitTokenWithSuffix(node.externalKeyword, " ");
+ safelyVisitTokenWithSuffix(node.constKeyword, " ");
+ safelyVisitTokenWithSuffix(node.factoryKeyword, " ");
+ safelyVisitNode(node.returnType);
+ safelyVisitNodeWithPrefix(".", node.name);
+ safelyVisitNode(node.parameters);
+ safelyVisitNodeListWithSeparatorAndPrefix(" : ", node.initializers, ", ");
+ safelyVisitNodeWithPrefix(" = ", node.redirectedConstructor);
+ safelyVisitFunctionWithPrefix(" ", node.body);
+ return null;
+ }
+
+ @override
+ Object visitConstructorFieldInitializer(ConstructorFieldInitializer node) {
+ safelyVisitTokenWithSuffix(node.thisKeyword, ".");
+ safelyVisitNode(node.fieldName);
+ sink.write(" = ");
+ safelyVisitNode(node.expression);
+ return null;
+ }
+
+ @override
+ Object visitConstructorName(ConstructorName node) {
+ safelyVisitNode(node.type);
+ safelyVisitNodeWithPrefix(".", node.name);
+ return null;
+ }
+
+ @override
+ Object visitContinueStatement(ContinueStatement node) {
+ sink.write("continue");
+ safelyVisitNodeWithPrefix(" ", node.label);
+ sink.write(";");
+ return null;
+ }
+
+ @override
+ Object visitDeclaredIdentifier(DeclaredIdentifier node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
+ safelyVisitTokenWithSuffix(node.keyword, " ");
+ safelyVisitNodeWithSuffix(node.type, " ");
+ safelyVisitNode(node.identifier);
+ return null;
+ }
+
+ @override
+ Object visitDefaultFormalParameter(DefaultFormalParameter node) {
+ safelyVisitNode(node.parameter);
+ if (node.separator != null) {
+ sink.write(" ");
+ sink.write(node.separator.lexeme);
+ safelyVisitNodeWithPrefix(" ", node.defaultValue);
+ }
+ return null;
+ }
+
+ @override
+ Object visitDoStatement(DoStatement node) {
+ sink.write("do ");
+ safelyVisitNode(node.body);
+ sink.write(" while (");
+ safelyVisitNode(node.condition);
+ sink.write(");");
+ return null;
+ }
+
+ @override
+ Object visitDottedName(DottedName node) {
+ safelyVisitNodeListWithSeparator(node.components, ".");
+ return null;
+ }
+
+ @override
+ Object visitDoubleLiteral(DoubleLiteral node) {
+ sink.write(node.literal.lexeme);
+ return null;
+ }
+
+ @override
+ Object visitEmptyFunctionBody(EmptyFunctionBody node) {
+ sink.write(';');
+ return null;
+ }
+
+ @override
+ Object visitEmptyStatement(EmptyStatement node) {
+ sink.write(';');
+ return null;
+ }
+
+ @override
+ Object visitEnumConstantDeclaration(EnumConstantDeclaration node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
+ safelyVisitNode(node.name);
+ return null;
+ }
+
+ @override
+ Object visitEnumDeclaration(EnumDeclaration node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
+ sink.write("enum ");
+ safelyVisitNode(node.name);
+ sink.write(" {");
+ safelyVisitNodeListWithSeparator(node.constants, ", ");
+ sink.write("}");
+ return null;
+ }
+
+ @override
+ Object visitExportDirective(ExportDirective node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
+ sink.write("export ");
+ safelyVisitNode(node.uri);
+ safelyVisitNodeListWithSeparatorAndPrefix(" ", node.combinators, " ");
+ sink.write(';');
+ return null;
+ }
+
+ @override
+ Object visitExpressionFunctionBody(ExpressionFunctionBody node) {
+ Token keyword = node.keyword;
+ if (keyword != null) {
+ sink.write(keyword.lexeme);
+ sink.write(' ');
+ }
+ sink.write("=> ");
+ safelyVisitNode(node.expression);
+ if (node.semicolon != null) {
+ sink.write(';');
+ }
+ return null;
+ }
+
+ @override
+ Object visitExpressionStatement(ExpressionStatement node) {
+ safelyVisitNode(node.expression);
+ sink.write(';');
+ return null;
+ }
+
+ @override
+ Object visitExtendsClause(ExtendsClause node) {
+ sink.write("extends ");
+ safelyVisitNode(node.superclass);
+ return null;
+ }
+
+ @override
+ Object visitFieldDeclaration(FieldDeclaration node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
+ safelyVisitTokenWithSuffix(node.staticKeyword, " ");
+ safelyVisitNode(node.fields);
+ sink.write(";");
+ return null;
+ }
+
+ @override
+ Object visitFieldFormalParameter(FieldFormalParameter node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, ' ', ' ');
+ safelyVisitTokenWithSuffix(node.keyword, " ");
+ safelyVisitNodeWithSuffix(node.type, " ");
+ sink.write("this.");
+ safelyVisitNode(node.identifier);
+ safelyVisitNode(node.typeParameters);
+ safelyVisitNode(node.parameters);
+ return null;
+ }
+
+ @override
+ Object visitForEachStatement(ForEachStatement node) {
+ DeclaredIdentifier loopVariable = node.loopVariable;
+ if (node.awaitKeyword != null) {
+ sink.write("await ");
+ }
+ sink.write("for (");
+ if (loopVariable == null) {
+ safelyVisitNode(node.identifier);
+ } else {
+ safelyVisitNode(loopVariable);
+ }
+ sink.write(" in ");
+ safelyVisitNode(node.iterable);
+ sink.write(") ");
+ safelyVisitNode(node.body);
+ return null;
+ }
+
+ @override
+ Object visitFormalParameterList(FormalParameterList node) {
+ String groupEnd = null;
+ sink.write('(');
+ NodeList<FormalParameter> parameters = node.parameters;
+ int size = parameters.length;
+ for (int i = 0; i < size; i++) {
+ FormalParameter parameter = parameters[i];
+ if (i > 0) {
+ sink.write(", ");
+ }
+ if (groupEnd == null && parameter is DefaultFormalParameter) {
+ if (parameter.kind == ParameterKind.NAMED) {
+ groupEnd = "}";
+ sink.write('{');
+ } else {
+ groupEnd = "]";
+ sink.write('[');
+ }
+ }
+ parameter.accept(this);
+ }
+ if (groupEnd != null) {
+ sink.write(groupEnd);
+ }
+ sink.write(')');
+ return null;
+ }
+
+ @override
+ Object visitForStatement(ForStatement node) {
+ Expression initialization = node.initialization;
+ sink.write("for (");
+ if (initialization != null) {
+ safelyVisitNode(initialization);
+ } else {
+ safelyVisitNode(node.variables);
+ }
+ sink.write(";");
+ safelyVisitNodeWithPrefix(" ", node.condition);
+ sink.write(";");
+ safelyVisitNodeListWithSeparatorAndPrefix(" ", node.updaters, ", ");
+ sink.write(") ");
+ safelyVisitNode(node.body);
+ return null;
+ }
+
+ @override
+ Object visitFunctionDeclaration(FunctionDeclaration node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
+ safelyVisitTokenWithSuffix(node.externalKeyword, " ");
+ safelyVisitNodeWithSuffix(node.returnType, " ");
+ safelyVisitTokenWithSuffix(node.propertyKeyword, " ");
+ safelyVisitNode(node.name);
+ safelyVisitNode(node.functionExpression);
+ return null;
+ }
+
+ @override
+ Object visitFunctionDeclarationStatement(FunctionDeclarationStatement node) {
+ safelyVisitNode(node.functionDeclaration);
+ return null;
+ }
+
+ @override
+ Object visitFunctionExpression(FunctionExpression node) {
+ safelyVisitNode(node.typeParameters);
+ safelyVisitNode(node.parameters);
+ if (node.body is! EmptyFunctionBody) {
+ sink.write(' ');
+ }
+ safelyVisitNode(node.body);
+ return null;
+ }
+
+ @override
+ Object visitFunctionExpressionInvocation(FunctionExpressionInvocation node) {
+ safelyVisitNode(node.function);
+ safelyVisitNode(node.typeArguments);
+ safelyVisitNode(node.argumentList);
+ return null;
+ }
+
+ @override
+ Object visitFunctionTypeAlias(FunctionTypeAlias node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
+ sink.write("typedef ");
+ safelyVisitNodeWithSuffix(node.returnType, " ");
+ safelyVisitNode(node.name);
+ safelyVisitNode(node.typeParameters);
+ safelyVisitNode(node.parameters);
+ sink.write(";");
+ return null;
+ }
+
+ @override
+ Object visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, ' ', ' ');
+ safelyVisitNodeWithSuffix(node.returnType, " ");
+ safelyVisitNode(node.identifier);
+ safelyVisitNode(node.typeParameters);
+ safelyVisitNode(node.parameters);
+ if (node.question != null) {
+ sink.write('?');
+ }
+ return null;
+ }
+
+ @override
+ Object visitHideCombinator(HideCombinator node) {
+ sink.write("hide ");
+ safelyVisitNodeListWithSeparator(node.hiddenNames, ", ");
+ return null;
+ }
+
+ @override
+ Object visitIfStatement(IfStatement node) {
+ sink.write("if (");
+ safelyVisitNode(node.condition);
+ sink.write(") ");
+ safelyVisitNode(node.thenStatement);
+ safelyVisitNodeWithPrefix(" else ", node.elseStatement);
+ return null;
+ }
+
+ @override
+ Object visitImplementsClause(ImplementsClause node) {
+ sink.write("implements ");
+ safelyVisitNodeListWithSeparator(node.interfaces, ", ");
+ return null;
+ }
+
+ @override
+ Object visitImportDirective(ImportDirective node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
+ sink.write("import ");
+ safelyVisitNode(node.uri);
+ if (node.deferredKeyword != null) {
+ sink.write(" deferred");
+ }
+ safelyVisitNodeWithPrefix(" as ", node.prefix);
+ safelyVisitNodeListWithSeparatorAndPrefix(" ", node.combinators, " ");
+ sink.write(';');
+ return null;
+ }
+
+ @override
+ Object visitIndexExpression(IndexExpression node) {
+ if (node.isCascaded) {
+ sink.write("..");
+ } else {
+ safelyVisitNode(node.target);
+ }
+ sink.write('[');
+ safelyVisitNode(node.index);
+ sink.write(']');
+ return null;
+ }
+
+ @override
+ Object visitInstanceCreationExpression(InstanceCreationExpression node) {
+ safelyVisitTokenWithSuffix(node.keyword, " ");
+ safelyVisitNode(node.constructorName);
+ safelyVisitNode(node.argumentList);
+ return null;
+ }
+
+ @override
+ Object visitIntegerLiteral(IntegerLiteral node) {
+ sink.write(node.literal.lexeme);
+ return null;
+ }
+
+ @override
+ Object visitInterpolationExpression(InterpolationExpression node) {
+ if (node.rightBracket != null) {
+ sink.write("\${");
+ safelyVisitNode(node.expression);
+ sink.write("}");
+ } else {
+ sink.write("\$");
+ safelyVisitNode(node.expression);
+ }
+ return null;
+ }
+
+ @override
+ Object visitInterpolationString(InterpolationString node) {
+ sink.write(node.contents.lexeme);
+ return null;
+ }
+
+ @override
+ Object visitIsExpression(IsExpression node) {
+ safelyVisitNode(node.expression);
+ if (node.notOperator == null) {
+ sink.write(" is ");
+ } else {
+ sink.write(" is! ");
+ }
+ safelyVisitNode(node.type);
+ return null;
+ }
+
+ @override
+ Object visitLabel(Label node) {
+ safelyVisitNode(node.label);
+ sink.write(":");
+ return null;
+ }
+
+ @override
+ Object visitLabeledStatement(LabeledStatement node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.labels, " ", " ");
+ safelyVisitNode(node.statement);
+ return null;
+ }
+
+ @override
+ Object visitLibraryDirective(LibraryDirective node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
+ sink.write("library ");
+ safelyVisitNode(node.name);
+ sink.write(';');
+ return null;
+ }
+
+ @override
+ Object visitLibraryIdentifier(LibraryIdentifier node) {
+ sink.write(node.name);
+ return null;
+ }
+
+ @override
+ Object visitListLiteral(ListLiteral node) {
+ if (node.constKeyword != null) {
+ sink.write(node.constKeyword.lexeme);
+ sink.write(' ');
+ }
+ safelyVisitNodeWithSuffix(node.typeArguments, " ");
+ sink.write("[");
+ safelyVisitNodeListWithSeparator(node.elements, ", ");
+ sink.write("]");
+ return null;
+ }
+
+ @override
+ Object visitMapLiteral(MapLiteral node) {
+ if (node.constKeyword != null) {
+ sink.write(node.constKeyword.lexeme);
+ sink.write(' ');
+ }
+ safelyVisitNodeWithSuffix(node.typeArguments, " ");
+ sink.write("{");
+ safelyVisitNodeListWithSeparator(node.entries, ", ");
+ sink.write("}");
+ return null;
+ }
+
+ @override
+ Object visitMapLiteralEntry(MapLiteralEntry node) {
+ safelyVisitNode(node.key);
+ sink.write(" : ");
+ safelyVisitNode(node.value);
+ return null;
+ }
+
+ @override
+ Object visitMethodDeclaration(MethodDeclaration node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
+ safelyVisitTokenWithSuffix(node.externalKeyword, " ");
+ safelyVisitTokenWithSuffix(node.modifierKeyword, " ");
+ safelyVisitNodeWithSuffix(node.returnType, " ");
+ safelyVisitTokenWithSuffix(node.propertyKeyword, " ");
+ safelyVisitTokenWithSuffix(node.operatorKeyword, " ");
+ safelyVisitNode(node.name);
+ if (!node.isGetter) {
+ safelyVisitNode(node.typeParameters);
+ safelyVisitNode(node.parameters);
+ }
+ safelyVisitFunctionWithPrefix(" ", node.body);
+ return null;
+ }
+
+ @override
+ Object visitMethodInvocation(MethodInvocation node) {
+ if (node.isCascaded) {
+ sink.write("..");
+ } else {
+ if (node.target != null) {
+ node.target.accept(this);
+ sink.write(node.operator.lexeme);
+ }
+ }
+ safelyVisitNode(node.methodName);
+ safelyVisitNode(node.typeArguments);
+ safelyVisitNode(node.argumentList);
+ return null;
+ }
+
+ @override
+ Object visitNamedExpression(NamedExpression node) {
+ safelyVisitNode(node.name);
+ safelyVisitNodeWithPrefix(" ", node.expression);
+ return null;
+ }
+
+ @override
+ Object visitNativeClause(NativeClause node) {
+ sink.write("native ");
+ safelyVisitNode(node.name);
+ return null;
+ }
+
+ @override
+ Object visitNativeFunctionBody(NativeFunctionBody node) {
+ sink.write("native ");
+ safelyVisitNode(node.stringLiteral);
+ sink.write(';');
+ return null;
+ }
+
+ @override
+ Object visitNullLiteral(NullLiteral node) {
+ sink.write("null");
+ return null;
+ }
+
+ @override
+ Object visitParenthesizedExpression(ParenthesizedExpression node) {
+ sink.write('(');
+ safelyVisitNode(node.expression);
+ sink.write(')');
+ return null;
+ }
+
+ @override
+ Object visitPartDirective(PartDirective node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
+ sink.write("part ");
+ safelyVisitNode(node.uri);
+ sink.write(';');
+ return null;
+ }
+
+ @override
+ Object visitPartOfDirective(PartOfDirective node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
+ sink.write("part of ");
+ safelyVisitNode(node.libraryName);
+ sink.write(';');
+ return null;
+ }
+
+ @override
+ Object visitPostfixExpression(PostfixExpression node) {
+ safelyVisitNode(node.operand);
+ sink.write(node.operator.lexeme);
+ return null;
+ }
+
+ @override
+ Object visitPrefixedIdentifier(PrefixedIdentifier node) {
+ safelyVisitNode(node.prefix);
+ sink.write('.');
+ safelyVisitNode(node.identifier);
+ return null;
+ }
+
+ @override
+ Object visitPrefixExpression(PrefixExpression node) {
+ sink.write(node.operator.lexeme);
+ safelyVisitNode(node.operand);
+ return null;
+ }
+
+ @override
+ Object visitPropertyAccess(PropertyAccess node) {
+ if (node.isCascaded) {
+ sink.write("..");
+ } else {
+ safelyVisitNode(node.target);
+ sink.write(node.operator.lexeme);
+ }
+ safelyVisitNode(node.propertyName);
+ return null;
+ }
+
+ @override
+ Object visitRedirectingConstructorInvocation(
+ RedirectingConstructorInvocation node) {
+ sink.write("this");
+ safelyVisitNodeWithPrefix(".", node.constructorName);
+ safelyVisitNode(node.argumentList);
+ return null;
+ }
+
+ @override
+ Object visitRethrowExpression(RethrowExpression node) {
+ sink.write("rethrow");
+ return null;
+ }
+
+ @override
+ Object visitReturnStatement(ReturnStatement node) {
+ Expression expression = node.expression;
+ if (expression == null) {
+ sink.write("return;");
+ } else {
+ sink.write("return ");
+ expression.accept(this);
+ sink.write(";");
+ }
+ return null;
+ }
+
+ @override
+ Object visitScriptTag(ScriptTag node) {
+ sink.write(node.scriptTag.lexeme);
+ return null;
+ }
+
+ @override
+ Object visitShowCombinator(ShowCombinator node) {
+ sink.write("show ");
+ safelyVisitNodeListWithSeparator(node.shownNames, ", ");
+ return null;
+ }
+
+ @override
+ Object visitSimpleFormalParameter(SimpleFormalParameter node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, ' ', ' ');
+ safelyVisitTokenWithSuffix(node.keyword, " ");
+ safelyVisitNodeWithSuffix(node.type, " ");
+ safelyVisitNode(node.identifier);
+ return null;
+ }
+
+ @override
+ Object visitSimpleIdentifier(SimpleIdentifier node) {
+ sink.write(node.token.lexeme);
+ return null;
+ }
+
+ @override
+ Object visitSimpleStringLiteral(SimpleStringLiteral node) {
+ sink.write(node.literal.lexeme);
+ return null;
+ }
+
+ @override
+ Object visitStringInterpolation(StringInterpolation node) {
+ safelyVisitNodeList(node.elements);
+ return null;
+ }
+
+ @override
+ Object visitSuperConstructorInvocation(SuperConstructorInvocation node) {
+ sink.write("super");
+ safelyVisitNodeWithPrefix(".", node.constructorName);
+ safelyVisitNode(node.argumentList);
+ return null;
+ }
+
+ @override
+ Object visitSuperExpression(SuperExpression node) {
+ sink.write("super");
+ return null;
+ }
+
+ @override
+ Object visitSwitchCase(SwitchCase node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.labels, " ", " ");
+ sink.write("case ");
+ safelyVisitNode(node.expression);
+ sink.write(": ");
+ safelyVisitNodeListWithSeparator(node.statements, " ");
+ return null;
+ }
+
+ @override
+ Object visitSwitchDefault(SwitchDefault node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.labels, " ", " ");
+ sink.write("default: ");
+ safelyVisitNodeListWithSeparator(node.statements, " ");
+ return null;
+ }
+
+ @override
+ Object visitSwitchStatement(SwitchStatement node) {
+ sink.write("switch (");
+ safelyVisitNode(node.expression);
+ sink.write(") {");
+ safelyVisitNodeListWithSeparator(node.members, " ");
+ sink.write("}");
+ return null;
+ }
+
+ @override
+ Object visitSymbolLiteral(SymbolLiteral node) {
+ sink.write("#");
+ List<Token> components = node.components;
+ for (int i = 0; i < components.length; i++) {
+ if (i > 0) {
+ sink.write(".");
+ }
+ sink.write(components[i].lexeme);
+ }
+ return null;
+ }
+
+ @override
+ Object visitThisExpression(ThisExpression node) {
+ sink.write("this");
+ return null;
+ }
+
+ @override
+ Object visitThrowExpression(ThrowExpression node) {
+ sink.write("throw ");
+ safelyVisitNode(node.expression);
+ return null;
+ }
+
+ @override
+ Object visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) {
+ safelyVisitNodeWithSuffix(node.variables, ";");
+ return null;
+ }
+
+ @override
+ Object visitTryStatement(TryStatement node) {
+ sink.write("try ");
+ safelyVisitNode(node.body);
+ safelyVisitNodeListWithSeparatorAndPrefix(" ", node.catchClauses, " ");
+ safelyVisitNodeWithPrefix(" finally ", node.finallyBlock);
+ return null;
+ }
+
+ @override
+ Object visitTypeArgumentList(TypeArgumentList node) {
+ sink.write('<');
+ safelyVisitNodeListWithSeparator(node.arguments, ", ");
+ sink.write('>');
+ return null;
+ }
+
+ @override
+ Object visitTypeName(TypeName node) {
+ safelyVisitNode(node.name);
+ safelyVisitNode(node.typeArguments);
+ if (node.question != null) {
+ sink.write('?');
+ }
+ return null;
+ }
+
+ @override
+ Object visitTypeParameter(TypeParameter node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
+ safelyVisitNode(node.name);
+ safelyVisitNodeWithPrefix(" extends ", node.bound);
+ return null;
+ }
+
+ @override
+ Object visitTypeParameterList(TypeParameterList node) {
+ sink.write('<');
+ safelyVisitNodeListWithSeparator(node.typeParameters, ", ");
+ sink.write('>');
+ return null;
+ }
+
+ @override
+ Object visitVariableDeclaration(VariableDeclaration node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
+ safelyVisitNode(node.name);
+ safelyVisitNodeWithPrefix(" = ", node.initializer);
+ return null;
+ }
+
+ @override
+ Object visitVariableDeclarationList(VariableDeclarationList node) {
+ safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
+ safelyVisitTokenWithSuffix(node.keyword, " ");
+ safelyVisitNodeWithSuffix(node.type, " ");
+ safelyVisitNodeListWithSeparator(node.variables, ", ");
+ return null;
+ }
+
+ @override
+ Object visitVariableDeclarationStatement(VariableDeclarationStatement node) {
+ safelyVisitNode(node.variables);
+ sink.write(";");
+ return null;
+ }
+
+ @override
+ Object visitWhileStatement(WhileStatement node) {
+ sink.write("while (");
+ safelyVisitNode(node.condition);
+ sink.write(") ");
+ safelyVisitNode(node.body);
+ return null;
+ }
+
+ @override
+ Object visitWithClause(WithClause node) {
+ sink.write("with ");
+ safelyVisitNodeListWithSeparator(node.mixinTypes, ", ");
+ return null;
+ }
+
+ @override
+ Object visitYieldStatement(YieldStatement node) {
+ if (node.star != null) {
+ sink.write("yield* ");
+ } else {
+ sink.write("yield ");
+ }
+ safelyVisitNode(node.expression);
+ sink.write(";");
+ return null;
+ }
+}
diff --git a/pkg/analyzer/lib/src/dart/element/builder.dart b/pkg/analyzer/lib/src/dart/element/builder.dart
index 7e06a56..b45f44e 100644
--- a/pkg/analyzer/lib/src/dart/element/builder.dart
+++ b/pkg/analyzer/lib/src/dart/element/builder.dart
@@ -23,6 +23,719 @@
import 'package:analyzer/src/generated/utilities_dart.dart';
/**
+ * Instances of the class `ApiElementBuilder` traverse an AST structure and
+ * build elements outside of function bodies and initializers.
+ */
+class ApiElementBuilder extends _BaseElementBuilder {
+ /**
+ * A table mapping field names to field elements for the fields defined in the current class, or
+ * `null` if we are not in the scope of a class.
+ */
+ HashMap<String, FieldElement> _fieldMap;
+
+ /**
+ * Initialize a newly created element builder to build the elements for a
+ * compilation unit. The [initialHolder] is the element holder to which the
+ * children of the visited compilation unit node will be added.
+ */
+ ApiElementBuilder(ElementHolder initialHolder,
+ CompilationUnitElementImpl compilationUnitElement)
+ : super(initialHolder, compilationUnitElement);
+
+ @override
+ Object visitAnnotation(Annotation node) {
+ // Although it isn't valid to do so because closures are not constant
+ // expressions, it's possible for one of the arguments to the constructor to
+ // contain a closure. Wrapping the processing of the annotation this way
+ // prevents these closures from being added to the list of functions in the
+ // annotated declaration.
+ ElementHolder holder = new ElementHolder();
+ ElementHolder previousHolder = _currentHolder;
+ _currentHolder = holder;
+ try {
+ super.visitAnnotation(node);
+ } finally {
+ _currentHolder = previousHolder;
+ }
+ return null;
+ }
+
+ @override
+ Object visitBlockFunctionBody(BlockFunctionBody node) {
+ return null;
+ }
+
+ @override
+ Object visitClassDeclaration(ClassDeclaration node) {
+ ElementHolder holder = new ElementHolder();
+ //
+ // Process field declarations before constructors and methods so that field
+ // formal parameters can be correctly resolved to their fields.
+ //
+ ElementHolder previousHolder = _currentHolder;
+ _currentHolder = holder;
+ try {
+ List<ClassMember> nonFields = new List<ClassMember>();
+ node.visitChildren(
+ new _ElementBuilder_visitClassDeclaration(this, nonFields));
+ _buildFieldMap(holder.fieldsWithoutFlushing);
+ int count = nonFields.length;
+ for (int i = 0; i < count; i++) {
+ nonFields[i].accept(this);
+ }
+ } finally {
+ _currentHolder = previousHolder;
+ }
+ SimpleIdentifier className = node.name;
+ ClassElementImpl element = new ClassElementImpl.forNode(className);
+ _setCodeRange(element, node);
+ element.metadata = _createElementAnnotations(node.metadata);
+ element.typeParameters = holder.typeParameters;
+ setElementDocumentationComment(element, node);
+ element.abstract = node.isAbstract;
+ element.accessors = holder.accessors;
+ List<ConstructorElement> constructors = holder.constructors;
+ if (constructors.isEmpty) {
+ constructors = _createDefaultConstructors(element);
+ }
+ element.constructors = constructors;
+ element.fields = holder.fields;
+ element.methods = holder.methods;
+ _currentHolder.addType(element);
+ className.staticElement = element;
+ _fieldMap = null;
+ holder.validate();
+ return null;
+ }
+
+ @override
+ Object visitClassTypeAlias(ClassTypeAlias node) {
+ ElementHolder holder = new ElementHolder();
+ _visitChildren(holder, node);
+ SimpleIdentifier className = node.name;
+ ClassElementImpl element = new ClassElementImpl.forNode(className);
+ _setCodeRange(element, node);
+ element.metadata = _createElementAnnotations(node.metadata);
+ element.abstract = node.abstractKeyword != null;
+ element.mixinApplication = true;
+ element.typeParameters = holder.typeParameters;
+ setElementDocumentationComment(element, node);
+ _currentHolder.addType(element);
+ className.staticElement = element;
+ holder.validate();
+ return null;
+ }
+
+ @override
+ Object visitCompilationUnit(CompilationUnit node) {
+ if (_unitElement is ElementImpl) {
+ _setCodeRange(_unitElement, node);
+ }
+ return super.visitCompilationUnit(node);
+ }
+
+ @override
+ Object visitConstructorDeclaration(ConstructorDeclaration node) {
+ ElementHolder holder = new ElementHolder();
+ _visitChildren(holder, node);
+ FunctionBody body = node.body;
+ SimpleIdentifier constructorName = node.name;
+ ConstructorElementImpl element =
+ new ConstructorElementImpl.forNode(constructorName);
+ _setCodeRange(element, node);
+ element.metadata = _createElementAnnotations(node.metadata);
+ setElementDocumentationComment(element, node);
+ if (node.externalKeyword != null) {
+ element.external = true;
+ }
+ if (node.factoryKeyword != null) {
+ element.factory = true;
+ }
+ element.functions = holder.functions;
+ element.labels = holder.labels;
+ element.localVariables = holder.localVariables;
+ element.parameters = holder.parameters;
+ element.const2 = node.constKeyword != null;
+ if (body.isAsynchronous) {
+ element.asynchronous = true;
+ }
+ if (body.isGenerator) {
+ element.generator = true;
+ }
+ _currentHolder.addConstructor(element);
+ node.element = element;
+ if (constructorName == null) {
+ Identifier returnType = node.returnType;
+ if (returnType != null) {
+ element.nameOffset = returnType.offset;
+ element.nameEnd = returnType.end;
+ }
+ } else {
+ constructorName.staticElement = element;
+ element.periodOffset = node.period.offset;
+ element.nameEnd = constructorName.end;
+ }
+ holder.validate();
+ return null;
+ }
+
+ @override
+ Object visitEnumDeclaration(EnumDeclaration node) {
+ SimpleIdentifier enumName = node.name;
+ EnumElementImpl enumElement = new EnumElementImpl.forNode(enumName);
+ _setCodeRange(enumElement, node);
+ enumElement.metadata = _createElementAnnotations(node.metadata);
+ setElementDocumentationComment(enumElement, node);
+ InterfaceTypeImpl enumType = enumElement.type;
+ //
+ // Build the elements for the constants. These are minimal elements; the
+ // rest of the constant elements (and elements for other fields) must be
+ // built later after we can access the type provider.
+ //
+ List<FieldElement> fields = new List<FieldElement>();
+ NodeList<EnumConstantDeclaration> constants = node.constants;
+ for (EnumConstantDeclaration constant in constants) {
+ SimpleIdentifier constantName = constant.name;
+ FieldElementImpl constantField =
+ new ConstFieldElementImpl.forNode(constantName);
+ constantField.static = true;
+ constantField.const3 = true;
+ constantField.type = enumType;
+ setElementDocumentationComment(constantField, constant);
+ fields.add(constantField);
+ new PropertyAccessorElementImpl_ImplicitGetter(constantField);
+ constantName.staticElement = constantField;
+ }
+ enumElement.fields = fields;
+
+ _currentHolder.addEnum(enumElement);
+ enumName.staticElement = enumElement;
+ return super.visitEnumDeclaration(node);
+ }
+
+ @override
+ Object visitExportDirective(ExportDirective node) {
+ List<ElementAnnotation> annotations =
+ _createElementAnnotations(node.metadata);
+ _unitElement.setAnnotations(node.offset, annotations);
+ return super.visitExportDirective(node);
+ }
+
+ @override
+ Object visitExpressionFunctionBody(ExpressionFunctionBody node) {
+ return null;
+ }
+
+ @override
+ Object visitFieldFormalParameter(FieldFormalParameter node) {
+ if (node.parent is! DefaultFormalParameter) {
+ SimpleIdentifier parameterName = node.identifier;
+ FieldElement field =
+ _fieldMap == null ? null : _fieldMap[parameterName.name];
+ FieldFormalParameterElementImpl parameter =
+ new FieldFormalParameterElementImpl.forNode(parameterName);
+ _setCodeRange(parameter, node);
+ parameter.const3 = node.isConst;
+ parameter.final2 = node.isFinal;
+ parameter.parameterKind = node.kind;
+ if (field != null) {
+ parameter.field = field;
+ }
+ _currentHolder.addParameter(parameter);
+ parameterName.staticElement = parameter;
+ }
+ //
+ // The children of this parameter include any parameters defined on the type
+ // of this parameter.
+ //
+ ElementHolder holder = new ElementHolder();
+ _visitChildren(holder, node);
+ ParameterElementImpl element = node.element;
+ element.metadata = _createElementAnnotations(node.metadata);
+ element.parameters = holder.parameters;
+ element.typeParameters = holder.typeParameters;
+ holder.validate();
+ return null;
+ }
+
+ @override
+ Object visitFunctionDeclaration(FunctionDeclaration node) {
+ FunctionExpression expression = node.functionExpression;
+ if (expression != null) {
+ ElementHolder holder = new ElementHolder();
+ _visitChildren(holder, node);
+ FunctionBody body = expression.body;
+ Token property = node.propertyKeyword;
+ if (property == null) {
+ SimpleIdentifier functionName = node.name;
+ FunctionElementImpl element =
+ new FunctionElementImpl.forNode(functionName);
+ _setCodeRange(element, node);
+ element.metadata = _createElementAnnotations(node.metadata);
+ setElementDocumentationComment(element, node);
+ if (node.externalKeyword != null) {
+ element.external = true;
+ }
+ element.functions = holder.functions;
+ element.labels = holder.labels;
+ element.localVariables = holder.localVariables;
+ element.parameters = holder.parameters;
+ element.typeParameters = holder.typeParameters;
+ if (body.isAsynchronous) {
+ element.asynchronous = true;
+ }
+ if (body.isGenerator) {
+ element.generator = true;
+ }
+ if (node.returnType == null) {
+ element.hasImplicitReturnType = true;
+ }
+ _currentHolder.addFunction(element);
+ expression.element = element;
+ functionName.staticElement = element;
+ } else {
+ SimpleIdentifier propertyNameNode = node.name;
+ if (propertyNameNode == null) {
+ // TODO(brianwilkerson) Report this internal error.
+ return null;
+ }
+ String propertyName = propertyNameNode.name;
+ TopLevelVariableElementImpl variable = _currentHolder
+ .getTopLevelVariable(propertyName) as TopLevelVariableElementImpl;
+ if (variable == null) {
+ variable = new TopLevelVariableElementImpl(node.name.name, -1);
+ variable.final2 = true;
+ variable.synthetic = true;
+ _currentHolder.addTopLevelVariable(variable);
+ }
+ if (node.isGetter) {
+ PropertyAccessorElementImpl getter =
+ new PropertyAccessorElementImpl.forNode(propertyNameNode);
+ _setCodeRange(getter, node);
+ getter.metadata = _createElementAnnotations(node.metadata);
+ setElementDocumentationComment(getter, node);
+ if (node.externalKeyword != null) {
+ getter.external = true;
+ }
+ getter.functions = holder.functions;
+ getter.labels = holder.labels;
+ getter.localVariables = holder.localVariables;
+ if (body.isAsynchronous) {
+ getter.asynchronous = true;
+ }
+ if (body.isGenerator) {
+ getter.generator = true;
+ }
+ getter.variable = variable;
+ getter.getter = true;
+ getter.static = true;
+ variable.getter = getter;
+ if (node.returnType == null) {
+ getter.hasImplicitReturnType = true;
+ }
+ _currentHolder.addAccessor(getter);
+ expression.element = getter;
+ propertyNameNode.staticElement = getter;
+ } else {
+ PropertyAccessorElementImpl setter =
+ new PropertyAccessorElementImpl.forNode(propertyNameNode);
+ _setCodeRange(setter, node);
+ setter.metadata = _createElementAnnotations(node.metadata);
+ setElementDocumentationComment(setter, node);
+ if (node.externalKeyword != null) {
+ setter.external = true;
+ }
+ setter.functions = holder.functions;
+ setter.labels = holder.labels;
+ setter.localVariables = holder.localVariables;
+ setter.parameters = holder.parameters;
+ if (body.isAsynchronous) {
+ setter.asynchronous = true;
+ }
+ if (body.isGenerator) {
+ setter.generator = true;
+ }
+ setter.variable = variable;
+ setter.setter = true;
+ setter.static = true;
+ if (node.returnType == null) {
+ setter.hasImplicitReturnType = true;
+ }
+ variable.setter = setter;
+ variable.final2 = false;
+ _currentHolder.addAccessor(setter);
+ expression.element = setter;
+ propertyNameNode.staticElement = setter;
+ }
+ }
+ holder.validate();
+ }
+ return null;
+ }
+
+ @override
+ Object visitFunctionExpression(FunctionExpression node) {
+ if (node.parent is FunctionDeclaration) {
+ // visitFunctionDeclaration has already created the element for the
+ // declaration. We just need to visit children.
+ return super.visitFunctionExpression(node);
+ }
+ ElementHolder holder = new ElementHolder();
+ _visitChildren(holder, node);
+ FunctionBody body = node.body;
+ FunctionElementImpl element =
+ new FunctionElementImpl.forOffset(node.beginToken.offset);
+ _setCodeRange(element, node);
+ element.functions = holder.functions;
+ element.labels = holder.labels;
+ element.localVariables = holder.localVariables;
+ element.parameters = holder.parameters;
+ element.typeParameters = holder.typeParameters;
+ if (body.isAsynchronous) {
+ element.asynchronous = true;
+ }
+ if (body.isGenerator) {
+ element.generator = true;
+ }
+ element.type = new FunctionTypeImpl(element);
+ element.hasImplicitReturnType = true;
+ _currentHolder.addFunction(element);
+ node.element = element;
+ holder.validate();
+ return null;
+ }
+
+ @override
+ Object visitFunctionTypeAlias(FunctionTypeAlias node) {
+ ElementHolder holder = new ElementHolder();
+ _visitChildren(holder, node);
+ SimpleIdentifier aliasName = node.name;
+ List<ParameterElement> parameters = holder.parameters;
+ List<TypeParameterElement> typeParameters = holder.typeParameters;
+ FunctionTypeAliasElementImpl element =
+ new FunctionTypeAliasElementImpl.forNode(aliasName);
+ _setCodeRange(element, node);
+ element.metadata = _createElementAnnotations(node.metadata);
+ setElementDocumentationComment(element, node);
+ element.parameters = parameters;
+ element.typeParameters = typeParameters;
+ _createTypeParameterTypes(typeParameters);
+ element.type = new FunctionTypeImpl.forTypedef(element);
+ _currentHolder.addTypeAlias(element);
+ aliasName.staticElement = element;
+ holder.validate();
+ return null;
+ }
+
+ @override
+ Object visitImportDirective(ImportDirective node) {
+ List<ElementAnnotation> annotations =
+ _createElementAnnotations(node.metadata);
+ _unitElement.setAnnotations(node.offset, annotations);
+ return super.visitImportDirective(node);
+ }
+
+ @override
+ Object visitLibraryDirective(LibraryDirective node) {
+ List<ElementAnnotation> annotations =
+ _createElementAnnotations(node.metadata);
+ _unitElement.setAnnotations(node.offset, annotations);
+ return super.visitLibraryDirective(node);
+ }
+
+ @override
+ Object visitMethodDeclaration(MethodDeclaration node) {
+ try {
+ ElementHolder holder = new ElementHolder();
+ _visitChildren(holder, node);
+ bool isStatic = node.isStatic;
+ Token property = node.propertyKeyword;
+ FunctionBody body = node.body;
+ if (property == null) {
+ SimpleIdentifier methodName = node.name;
+ String nameOfMethod = methodName.name;
+ if (nameOfMethod == TokenType.MINUS.lexeme &&
+ node.parameters.parameters.length == 0) {
+ nameOfMethod = "unary-";
+ }
+ MethodElementImpl element =
+ new MethodElementImpl(nameOfMethod, methodName.offset);
+ _setCodeRange(element, node);
+ element.metadata = _createElementAnnotations(node.metadata);
+ setElementDocumentationComment(element, node);
+ element.abstract = node.isAbstract;
+ if (node.externalKeyword != null) {
+ element.external = true;
+ }
+ element.functions = holder.functions;
+ element.labels = holder.labels;
+ element.localVariables = holder.localVariables;
+ element.parameters = holder.parameters;
+ element.static = isStatic;
+ element.typeParameters = holder.typeParameters;
+ if (body.isAsynchronous) {
+ element.asynchronous = true;
+ }
+ if (body.isGenerator) {
+ element.generator = true;
+ }
+ if (node.returnType == null) {
+ element.hasImplicitReturnType = true;
+ }
+ _currentHolder.addMethod(element);
+ methodName.staticElement = element;
+ } else {
+ SimpleIdentifier propertyNameNode = node.name;
+ String propertyName = propertyNameNode.name;
+ FieldElementImpl field = _currentHolder.getField(propertyName,
+ synthetic: true) as FieldElementImpl;
+ if (field == null) {
+ field = new FieldElementImpl(node.name.name, -1);
+ field.final2 = true;
+ field.static = isStatic;
+ field.synthetic = true;
+ _currentHolder.addField(field);
+ }
+ if (node.isGetter) {
+ PropertyAccessorElementImpl getter =
+ new PropertyAccessorElementImpl.forNode(propertyNameNode);
+ _setCodeRange(getter, node);
+ getter.metadata = _createElementAnnotations(node.metadata);
+ setElementDocumentationComment(getter, node);
+ if (node.externalKeyword != null) {
+ getter.external = true;
+ }
+ getter.functions = holder.functions;
+ getter.labels = holder.labels;
+ getter.localVariables = holder.localVariables;
+ if (body.isAsynchronous) {
+ getter.asynchronous = true;
+ }
+ if (body.isGenerator) {
+ getter.generator = true;
+ }
+ getter.variable = field;
+ getter.abstract = node.isAbstract;
+ getter.getter = true;
+ getter.static = isStatic;
+ field.getter = getter;
+ if (node.returnType == null) {
+ getter.hasImplicitReturnType = true;
+ }
+ _currentHolder.addAccessor(getter);
+ propertyNameNode.staticElement = getter;
+ } else {
+ PropertyAccessorElementImpl setter =
+ new PropertyAccessorElementImpl.forNode(propertyNameNode);
+ _setCodeRange(setter, node);
+ setter.metadata = _createElementAnnotations(node.metadata);
+ setElementDocumentationComment(setter, node);
+ if (node.externalKeyword != null) {
+ setter.external = true;
+ }
+ setter.functions = holder.functions;
+ setter.labels = holder.labels;
+ setter.localVariables = holder.localVariables;
+ setter.parameters = holder.parameters;
+ if (body.isAsynchronous) {
+ setter.asynchronous = true;
+ }
+ if (body.isGenerator) {
+ setter.generator = true;
+ }
+ setter.variable = field;
+ setter.abstract = node.isAbstract;
+ setter.setter = true;
+ setter.static = isStatic;
+ if (node.returnType == null) {
+ setter.hasImplicitReturnType = true;
+ }
+ field.setter = setter;
+ field.final2 = false;
+ _currentHolder.addAccessor(setter);
+ propertyNameNode.staticElement = setter;
+ }
+ }
+ holder.validate();
+ } catch (exception, stackTrace) {
+ if (node.name.staticElement == null) {
+ ClassDeclaration classNode =
+ node.getAncestor((node) => node is ClassDeclaration);
+ StringBuffer buffer = new StringBuffer();
+ buffer.write("The element for the method ");
+ buffer.write(node.name);
+ buffer.write(" in ");
+ buffer.write(classNode.name);
+ buffer.write(" was not set while trying to build the element model.");
+ AnalysisEngine.instance.logger.logError(
+ buffer.toString(), new CaughtException(exception, stackTrace));
+ } else {
+ String message =
+ "Exception caught in ElementBuilder.visitMethodDeclaration()";
+ AnalysisEngine.instance.logger
+ .logError(message, new CaughtException(exception, stackTrace));
+ }
+ } finally {
+ if (node.name.staticElement == null) {
+ ClassDeclaration classNode =
+ node.getAncestor((node) => node is ClassDeclaration);
+ StringBuffer buffer = new StringBuffer();
+ buffer.write("The element for the method ");
+ buffer.write(node.name);
+ buffer.write(" in ");
+ buffer.write(classNode.name);
+ buffer.write(" was not set while trying to resolve types.");
+ AnalysisEngine.instance.logger.logError(
+ buffer.toString(),
+ new CaughtException(
+ new AnalysisException(buffer.toString()), null));
+ }
+ }
+ return null;
+ }
+
+ @override
+ Object visitPartDirective(PartDirective node) {
+ List<ElementAnnotation> annotations =
+ _createElementAnnotations(node.metadata);
+ _unitElement.setAnnotations(node.offset, annotations);
+ return super.visitPartDirective(node);
+ }
+
+ @override
+ Object visitVariableDeclaration(VariableDeclaration node) {
+ bool isConst = node.isConst;
+ bool isFinal = node.isFinal;
+ Expression initializerNode = node.initializer;
+ bool hasInitializer = initializerNode != null;
+ VariableDeclarationList varList = node.parent;
+ FieldDeclaration fieldNode =
+ varList.parent is FieldDeclaration ? varList.parent : null;
+ VariableElementImpl element;
+ if (fieldNode != null) {
+ SimpleIdentifier fieldName = node.name;
+ FieldElementImpl field;
+ if ((isConst || isFinal && !fieldNode.isStatic) && hasInitializer) {
+ field = new ConstFieldElementImpl.forNode(fieldName);
+ } else {
+ field = new FieldElementImpl.forNode(fieldName);
+ }
+ element = field;
+ field.static = fieldNode.isStatic;
+ _setCodeRange(element, node);
+ setElementDocumentationComment(element, fieldNode);
+ field.hasImplicitType = varList.type == null;
+ _currentHolder.addField(field);
+ fieldName.staticElement = field;
+ } else {
+ SimpleIdentifier variableName = node.name;
+ TopLevelVariableElementImpl variable;
+ if (isConst && hasInitializer) {
+ variable = new ConstTopLevelVariableElementImpl.forNode(variableName);
+ } else {
+ variable = new TopLevelVariableElementImpl.forNode(variableName);
+ }
+ element = variable;
+ _setCodeRange(element, node);
+ if (varList.parent is TopLevelVariableDeclaration) {
+ setElementDocumentationComment(element, varList.parent);
+ }
+ variable.hasImplicitType = varList.type == null;
+ _currentHolder.addTopLevelVariable(variable);
+ variableName.staticElement = element;
+ }
+ element.const3 = isConst;
+ element.final2 = isFinal;
+ if (element is PropertyInducingElementImpl) {
+ PropertyAccessorElementImpl_ImplicitGetter getter =
+ new PropertyAccessorElementImpl_ImplicitGetter(element);
+ _currentHolder.addAccessor(getter);
+ if (!isConst && !isFinal) {
+ PropertyAccessorElementImpl_ImplicitSetter setter =
+ new PropertyAccessorElementImpl_ImplicitSetter(element);
+ _currentHolder.addAccessor(setter);
+ }
+ }
+ return null;
+ }
+
+ @override
+ Object visitVariableDeclarationList(VariableDeclarationList node) {
+ super.visitVariableDeclarationList(node);
+ AstNode parent = node.parent;
+ List<ElementAnnotation> elementAnnotations;
+ if (parent is FieldDeclaration) {
+ elementAnnotations = _createElementAnnotations(parent.metadata);
+ } else if (parent is TopLevelVariableDeclaration) {
+ elementAnnotations = _createElementAnnotations(parent.metadata);
+ } else {
+ // Local variable declaration
+ elementAnnotations = _createElementAnnotations(node.metadata);
+ }
+ _setVariableDeclarationListAnnotations(node, elementAnnotations);
+ return null;
+ }
+
+ /**
+ * Build the table mapping field names to field elements for the [fields]
+ * defined in the current class.
+ */
+ void _buildFieldMap(List<FieldElement> fields) {
+ _fieldMap = new HashMap<String, FieldElement>();
+ int count = fields.length;
+ for (int i = 0; i < count; i++) {
+ FieldElement field = fields[i];
+ _fieldMap[field.name] ??= field;
+ }
+ }
+
+ /**
+ * Creates the [ConstructorElement]s array with the single default constructor element.
+ *
+ * @param interfaceType the interface type for which to create a default constructor
+ * @return the [ConstructorElement]s array with the single default constructor element
+ */
+ List<ConstructorElement> _createDefaultConstructors(
+ ClassElementImpl definingClass) {
+ ConstructorElementImpl constructor =
+ new ConstructorElementImpl.forNode(null);
+ constructor.synthetic = true;
+ constructor.enclosingElement = definingClass;
+ return <ConstructorElement>[constructor];
+ }
+
+ /**
+ * Create the types associated with the given type parameters, setting the type of each type
+ * parameter, and return an array of types corresponding to the given parameters.
+ *
+ * @param typeParameters the type parameters for which types are to be created
+ * @return an array of types corresponding to the given parameters
+ */
+ List<DartType> _createTypeParameterTypes(
+ List<TypeParameterElement> typeParameters) {
+ int typeParameterCount = typeParameters.length;
+ List<DartType> typeArguments = new List<DartType>(typeParameterCount);
+ for (int i = 0; i < typeParameterCount; i++) {
+ TypeParameterElementImpl typeParameter =
+ typeParameters[i] as TypeParameterElementImpl;
+ TypeParameterTypeImpl typeParameterType =
+ new TypeParameterTypeImpl(typeParameter);
+ typeParameter.type = typeParameterType;
+ typeArguments[i] = typeParameterType;
+ }
+ return typeArguments;
+ }
+
+ @override
+ void _setFieldParameterField(FieldFormalParameterElementImpl parameter) {
+ FieldElement field = _fieldMap == null ? null : _fieldMap[parameter.name];
+ if (field != null) {
+ parameter.field = field;
+ }
+ }
+}
+
+/**
* A `CompilationUnitBuilder` builds an element model for a single compilation
* unit.
*/
@@ -309,72 +1022,63 @@
* Instances of the class `ElementBuilder` traverse an AST structure and build the element
* model representing the AST structure.
*/
-class ElementBuilder extends RecursiveAstVisitor<Object> {
- /**
- * The compilation unit element into which the elements being built will be
- * stored.
- */
- final CompilationUnitElementImpl compilationUnitElement;
-
- /**
- * The element holder associated with the element that is currently being built.
- */
- ElementHolder _currentHolder;
-
- /**
- * A flag indicating whether a variable declaration is within the body of a method or function.
- */
- bool _inFunction = false;
-
- /**
- * A collection holding the elements defined in a class that need to have
- * their function type fixed to take into account type parameters of the
- * enclosing class, or `null` if we are not currently processing nodes within
- * a class.
- */
- List<ExecutableElementImpl> _functionTypesToFix = null;
-
- /**
- * A table mapping field names to field elements for the fields defined in the current class, or
- * `null` if we are not in the scope of a class.
- */
- HashMap<String, FieldElement> _fieldMap;
-
+class ElementBuilder extends ApiElementBuilder {
/**
* Initialize a newly created element builder to build the elements for a
* compilation unit. The [initialHolder] is the element holder to which the
* children of the visited compilation unit node will be added.
*/
- ElementBuilder(ElementHolder initialHolder, this.compilationUnitElement) {
- _currentHolder = initialHolder;
- }
+ ElementBuilder(ElementHolder initialHolder,
+ CompilationUnitElement compilationUnitElement)
+ : super(initialHolder, compilationUnitElement);
- /**
- * Prepares for incremental resolution of a function body.
- */
- void initForFunctionBodyIncrementalResolution() {
- _inFunction = true;
+ @override
+ Object visitBlockFunctionBody(BlockFunctionBody node) {
+ _buildLocal(node);
+ return null;
}
@override
- Object visitAnnotation(Annotation node) {
- // Although it isn't valid to do so because closures are not constant
- // expressions, it's possible for one of the arguments to the constructor to
- // contain a closure. Wrapping the processing of the annotation this way
- // prevents these closures from being added to the list of functions in the
- // annotated declaration.
- ElementHolder holder = new ElementHolder();
- ElementHolder previousHolder = _currentHolder;
- _currentHolder = holder;
- try {
- super.visitAnnotation(node);
- } finally {
- _currentHolder = previousHolder;
- }
+ Object visitDefaultFormalParameter(DefaultFormalParameter node) {
+ super.visitDefaultFormalParameter(node);
+ buildParameterInitializer(
+ node.element as ParameterElementImpl, node.defaultValue);
return null;
}
@override
+ Object visitExpressionFunctionBody(ExpressionFunctionBody node) {
+ _buildLocal(node);
+ return null;
+ }
+
+ @override
+ Object visitVariableDeclaration(VariableDeclaration node) {
+ super.visitVariableDeclaration(node);
+ VariableElementImpl element = node.element as VariableElementImpl;
+ buildVariableInitializer(element, node.initializer);
+ return null;
+ }
+
+ void _buildLocal(AstNode node) {
+ node.accept(new LocalElementBuilder(_currentHolder, _unitElement));
+ }
+}
+
+/**
+ * Traverse a [FunctionBody] and build elements for AST structures.
+ */
+class LocalElementBuilder extends _BaseElementBuilder {
+ /**
+ * Initialize a newly created element builder to build the elements for a
+ * compilation unit. The [initialHolder] is the element holder to which the
+ * children of the visited compilation unit node will be added.
+ */
+ LocalElementBuilder(ElementHolder initialHolder,
+ CompilationUnitElementImpl compilationUnitElement)
+ : super(initialHolder, compilationUnitElement);
+
+ @override
Object visitCatchClause(CatchClause node) {
SimpleIdentifier exceptionParameter = node.exceptionParameter;
if (exceptionParameter != null) {
@@ -402,133 +1106,6 @@
}
@override
- Object visitClassDeclaration(ClassDeclaration node) {
- ElementHolder holder = new ElementHolder();
- _functionTypesToFix = new List<ExecutableElementImpl>();
- //
- // Process field declarations before constructors and methods so that field
- // formal parameters can be correctly resolved to their fields.
- //
- ElementHolder previousHolder = _currentHolder;
- _currentHolder = holder;
- try {
- List<ClassMember> nonFields = new List<ClassMember>();
- node.visitChildren(
- new _ElementBuilder_visitClassDeclaration(this, nonFields));
- _buildFieldMap(holder.fieldsWithoutFlushing);
- int count = nonFields.length;
- for (int i = 0; i < count; i++) {
- nonFields[i].accept(this);
- }
- } finally {
- _currentHolder = previousHolder;
- }
- SimpleIdentifier className = node.name;
- ClassElementImpl element = new ClassElementImpl.forNode(className);
- _setCodeRange(element, node);
- element.metadata = _createElementAnnotations(node.metadata);
- element.typeParameters = holder.typeParameters;
- setElementDocumentationComment(element, node);
- element.abstract = node.isAbstract;
- element.accessors = holder.accessors;
- List<ConstructorElement> constructors = holder.constructors;
- if (constructors.isEmpty) {
- constructors = _createDefaultConstructors(element);
- }
- element.constructors = constructors;
- element.fields = holder.fields;
- element.methods = holder.methods;
- // Function types must be initialized after the enclosing element has been
- // set, for them to pick up the type parameters.
- for (ExecutableElementImpl e in _functionTypesToFix) {
- e.type = new FunctionTypeImpl(e);
- }
- _functionTypesToFix = null;
- _currentHolder.addType(element);
- className.staticElement = element;
- _fieldMap = null;
- holder.validate();
- return null;
- }
-
- @override
- Object visitClassTypeAlias(ClassTypeAlias node) {
- ElementHolder holder = new ElementHolder();
- _visitChildren(holder, node);
- SimpleIdentifier className = node.name;
- ClassElementImpl element = new ClassElementImpl.forNode(className);
- _setCodeRange(element, node);
- element.metadata = _createElementAnnotations(node.metadata);
- element.abstract = node.abstractKeyword != null;
- element.mixinApplication = true;
- element.typeParameters = holder.typeParameters;
- setElementDocumentationComment(element, node);
- _currentHolder.addType(element);
- className.staticElement = element;
- holder.validate();
- return null;
- }
-
- @override
- Object visitCompilationUnit(CompilationUnit node) {
- if (compilationUnitElement is ElementImpl) {
- _setCodeRange(compilationUnitElement, node);
- }
- return super.visitCompilationUnit(node);
- }
-
- @override
- Object visitConstructorDeclaration(ConstructorDeclaration node) {
- ElementHolder holder = new ElementHolder();
- bool wasInFunction = _inFunction;
- _inFunction = true;
- try {
- _visitChildren(holder, node);
- } finally {
- _inFunction = wasInFunction;
- }
- FunctionBody body = node.body;
- SimpleIdentifier constructorName = node.name;
- ConstructorElementImpl element =
- new ConstructorElementImpl.forNode(constructorName);
- _setCodeRange(element, node);
- element.metadata = _createElementAnnotations(node.metadata);
- setElementDocumentationComment(element, node);
- if (node.externalKeyword != null) {
- element.external = true;
- }
- if (node.factoryKeyword != null) {
- element.factory = true;
- }
- element.functions = holder.functions;
- element.labels = holder.labels;
- element.localVariables = holder.localVariables;
- element.parameters = holder.parameters;
- element.const2 = node.constKeyword != null;
- if (body.isAsynchronous) {
- element.asynchronous = true;
- }
- if (body.isGenerator) {
- element.generator = true;
- }
- _currentHolder.addConstructor(element);
- node.element = element;
- if (constructorName == null) {
- Identifier returnType = node.returnType;
- if (returnType != null) {
- element.nameOffset = returnType.offset;
- element.nameEnd = returnType.end;
- }
- } else {
- constructorName.staticElement = element;
- element.periodOffset = node.period.offset;
- element.nameEnd = constructorName.end;
- }
- holder.validate();
- return null;
- }
-
- @override
Object visitDeclaredIdentifier(DeclaredIdentifier node) {
SimpleIdentifier variableName = node.identifier;
LocalVariableElementImpl element =
@@ -544,33 +1121,216 @@
}
_currentHolder.addLocalVariable(element);
variableName.staticElement = element;
- return super.visitDeclaredIdentifier(node);
+ return null;
}
@override
Object visitDefaultFormalParameter(DefaultFormalParameter node) {
- ElementHolder holder = new ElementHolder();
- NormalFormalParameter normalParameter = node.parameter;
- SimpleIdentifier parameterName = normalParameter.identifier;
- ParameterElementImpl parameter;
- if (normalParameter is FieldFormalParameter) {
- parameter =
- new DefaultFieldFormalParameterElementImpl.forNode(parameterName);
- FieldElement field =
- _fieldMap == null ? null : _fieldMap[parameterName.name];
- if (field != null) {
- (parameter as DefaultFieldFormalParameterElementImpl).field = field;
- }
- } else {
- parameter = new DefaultParameterElementImpl.forNode(parameterName);
+ super.visitDefaultFormalParameter(node);
+ buildParameterInitializer(
+ node.element as ParameterElementImpl, node.defaultValue);
+ return null;
+ }
+
+ @override
+ Object visitFunctionDeclaration(FunctionDeclaration node) {
+ FunctionExpression expression = node.functionExpression;
+ if (expression == null) {
+ return null;
}
- _setCodeRange(parameter, node);
- parameter.const3 = node.isConst;
- parameter.final2 = node.isFinal;
- parameter.parameterKind = node.kind;
- // set initializer, default value range
- Expression defaultValue = node.defaultValue;
+
+ ElementHolder holder = new ElementHolder();
+ _visitChildren(holder, node);
+
+ FunctionElementImpl element = new FunctionElementImpl.forNode(node.name);
+ _setCodeRange(element, node);
+ setElementDocumentationComment(element, node);
+ element.metadata = _createElementAnnotations(node.metadata);
+ if (node.externalKeyword != null) {
+ element.external = true;
+ }
+ element.functions = holder.functions;
+ element.labels = holder.labels;
+ element.localVariables = holder.localVariables;
+ element.parameters = holder.parameters;
+ element.typeParameters = holder.typeParameters;
+
+ FunctionBody body = expression.body;
+ if (body.isAsynchronous) {
+ element.asynchronous = body.isAsynchronous;
+ }
+ if (body.isGenerator) {
+ element.generator = true;
+ }
+
+ {
+ Block enclosingBlock = node.getAncestor((node) => node is Block);
+ if (enclosingBlock != null) {
+ element.setVisibleRange(enclosingBlock.offset, enclosingBlock.length);
+ }
+ }
+
+ if (node.returnType == null) {
+ element.hasImplicitReturnType = true;
+ }
+
+ _currentHolder.addFunction(element);
+ expression.element = element;
+ node.name.staticElement = element;
+ holder.validate();
+ return null;
+ }
+
+ @override
+ Object visitFunctionExpression(FunctionExpression node) {
+ if (node.parent is FunctionDeclaration) {
+ // visitFunctionDeclaration has already created the element for the
+ // declaration. We just need to visit children.
+ return super.visitFunctionExpression(node);
+ }
+
+ ElementHolder holder = new ElementHolder();
+ _visitChildren(holder, node);
+ FunctionElementImpl element =
+ new FunctionElementImpl.forOffset(node.beginToken.offset);
+ _setCodeRange(element, node);
+ element.functions = holder.functions;
+ element.labels = holder.labels;
+ element.localVariables = holder.localVariables;
+ element.parameters = holder.parameters;
+ element.typeParameters = holder.typeParameters;
+
+ FunctionBody body = node.body;
+ if (body.isAsynchronous) {
+ element.asynchronous = true;
+ }
+ if (body.isGenerator) {
+ element.generator = true;
+ }
+
+ {
+ Block enclosingBlock = node.getAncestor((node) => node is Block);
+ if (enclosingBlock != null) {
+ element.setVisibleRange(enclosingBlock.offset, enclosingBlock.length);
+ }
+ }
+
+ element.type = new FunctionTypeImpl(element);
+ element.hasImplicitReturnType = true;
+ _currentHolder.addFunction(element);
+ node.element = element;
+ holder.validate();
+ return null;
+ }
+
+ @override
+ Object visitLabeledStatement(LabeledStatement node) {
+ bool onSwitchStatement = node.statement is SwitchStatement;
+ for (Label label in node.labels) {
+ SimpleIdentifier labelName = label.label;
+ LabelElementImpl element =
+ new LabelElementImpl.forNode(labelName, onSwitchStatement, false);
+ _currentHolder.addLabel(element);
+ labelName.staticElement = element;
+ }
+ return super.visitLabeledStatement(node);
+ }
+
+ @override
+ Object visitSwitchCase(SwitchCase node) {
+ for (Label label in node.labels) {
+ SimpleIdentifier labelName = label.label;
+ LabelElementImpl element =
+ new LabelElementImpl.forNode(labelName, false, true);
+ _currentHolder.addLabel(element);
+ labelName.staticElement = element;
+ }
+ return super.visitSwitchCase(node);
+ }
+
+ @override
+ Object visitSwitchDefault(SwitchDefault node) {
+ for (Label label in node.labels) {
+ SimpleIdentifier labelName = label.label;
+ LabelElementImpl element =
+ new LabelElementImpl.forNode(labelName, false, true);
+ _currentHolder.addLabel(element);
+ labelName.staticElement = element;
+ }
+ return super.visitSwitchDefault(node);
+ }
+
+ @override
+ Object visitVariableDeclaration(VariableDeclaration node) {
+ bool isConst = node.isConst;
+ bool isFinal = node.isFinal;
+ Expression initializerNode = node.initializer;
+ VariableDeclarationList varList = node.parent;
+ SimpleIdentifier variableName = node.name;
+ LocalVariableElementImpl element;
+ if (isConst && initializerNode != null) {
+ element = new ConstLocalVariableElementImpl.forNode(variableName);
+ } else {
+ element = new LocalVariableElementImpl.forNode(variableName);
+ }
+ _setCodeRange(element, node);
+ _setVariableVisibleRange(element, node);
+ element.hasImplicitType = varList.type == null;
+ _currentHolder.addLocalVariable(element);
+ variableName.staticElement = element;
+ element.const3 = isConst;
+ element.final2 = isFinal;
+ buildVariableInitializer(element, initializerNode);
+ return null;
+ }
+
+ @override
+ Object visitVariableDeclarationList(VariableDeclarationList node) {
+ super.visitVariableDeclarationList(node);
+ List<ElementAnnotation> elementAnnotations =
+ _createElementAnnotations(node.metadata);
+ _setVariableDeclarationListAnnotations(node, elementAnnotations);
+ return null;
+ }
+
+ void _setVariableVisibleRange(
+ LocalVariableElementImpl element, VariableDeclaration node) {
+ AstNode scopeNode;
+ AstNode parent2 = node.parent.parent;
+ if (parent2 is ForStatement) {
+ scopeNode = parent2;
+ } else {
+ scopeNode = node.getAncestor((node) => node is Block);
+ }
+ element.setVisibleRange(scopeNode.offset, scopeNode.length);
+ }
+}
+
+/**
+ * Base class for API and local element builders.
+ */
+abstract class _BaseElementBuilder extends RecursiveAstVisitor<Object> {
+ /**
+ * The compilation unit element into which the elements being built will be
+ * stored.
+ */
+ final CompilationUnitElementImpl _unitElement;
+
+ /**
+ * The element holder associated with the element that is currently being built.
+ */
+ ElementHolder _currentHolder;
+
+ _BaseElementBuilder(this._currentHolder, this._unitElement);
+
+ /**
+ * If the [defaultValue] is not `null`, build the [FunctionElementImpl]
+ * that corresponds it, and set it as the initializer for the [parameter].
+ */
+ void buildParameterInitializer(
+ ParameterElementImpl parameter, Expression defaultValue) {
if (defaultValue != null) {
+ ElementHolder holder = new ElementHolder();
_visit(holder, defaultValue);
FunctionElementImpl initializer =
new FunctionElementImpl.forOffset(defaultValue.beginToken.offset);
@@ -583,7 +1343,49 @@
initializer.type = new FunctionTypeImpl(initializer);
parameter.initializer = initializer;
parameter.defaultValueCode = defaultValue.toSource();
+ holder.validate();
}
+ }
+
+ /**
+ * If the [initializer] is not `null`, build the [FunctionElementImpl] that
+ * corresponds it, and set it as the initializer for the [variable].
+ */
+ void buildVariableInitializer(
+ VariableElementImpl variable, Expression initializer) {
+ if (initializer != null) {
+ ElementHolder holder = new ElementHolder();
+ _visit(holder, initializer);
+ FunctionElementImpl initializerElement =
+ new FunctionElementImpl.forOffset(initializer.beginToken.offset);
+ initializerElement.hasImplicitReturnType = true;
+ initializerElement.functions = holder.functions;
+ initializerElement.labels = holder.labels;
+ initializerElement.localVariables = holder.localVariables;
+ initializerElement.synthetic = true;
+ initializerElement.type = new FunctionTypeImpl(initializerElement);
+ variable.initializer = initializerElement;
+ holder.validate();
+ }
+ }
+
+ @override
+ Object visitDefaultFormalParameter(DefaultFormalParameter node) {
+ NormalFormalParameter normalParameter = node.parameter;
+ SimpleIdentifier parameterName = normalParameter.identifier;
+ ParameterElementImpl parameter;
+ if (normalParameter is FieldFormalParameter) {
+ DefaultFieldFormalParameterElementImpl fieldParameter =
+ new DefaultFieldFormalParameterElementImpl.forNode(parameterName);
+ _setFieldParameterField(fieldParameter);
+ parameter = fieldParameter;
+ } else {
+ parameter = new DefaultParameterElementImpl.forNode(parameterName);
+ }
+ _setCodeRange(parameter, node);
+ parameter.const3 = node.isConst;
+ parameter.final2 = node.isFinal;
+ parameter.parameterKind = node.kind;
// visible range
_setParameterVisibleRange(node, parameter);
if (normalParameter is SimpleFormalParameter &&
@@ -593,279 +1395,6 @@
_currentHolder.addParameter(parameter);
parameterName.staticElement = parameter;
normalParameter.accept(this);
- holder.validate();
- return null;
- }
-
- @override
- Object visitEnumDeclaration(EnumDeclaration node) {
- SimpleIdentifier enumName = node.name;
- EnumElementImpl enumElement = new EnumElementImpl.forNode(enumName);
- _setCodeRange(enumElement, node);
- enumElement.metadata = _createElementAnnotations(node.metadata);
- setElementDocumentationComment(enumElement, node);
- InterfaceTypeImpl enumType = enumElement.type;
- //
- // Build the elements for the constants. These are minimal elements; the
- // rest of the constant elements (and elements for other fields) must be
- // built later after we can access the type provider.
- //
- List<FieldElement> fields = new List<FieldElement>();
- NodeList<EnumConstantDeclaration> constants = node.constants;
- for (EnumConstantDeclaration constant in constants) {
- SimpleIdentifier constantName = constant.name;
- FieldElementImpl constantField =
- new ConstFieldElementImpl.forNode(constantName);
- constantField.static = true;
- constantField.const3 = true;
- constantField.type = enumType;
- setElementDocumentationComment(constantField, constant);
- fields.add(constantField);
- new PropertyAccessorElementImpl_ImplicitGetter(constantField);
- constantName.staticElement = constantField;
- }
- enumElement.fields = fields;
-
- _currentHolder.addEnum(enumElement);
- enumName.staticElement = enumElement;
- return super.visitEnumDeclaration(node);
- }
-
- @override
- Object visitExportDirective(ExportDirective node) {
- List<ElementAnnotation> annotations =
- _createElementAnnotations(node.metadata);
- compilationUnitElement.setAnnotations(node.offset, annotations);
- return super.visitExportDirective(node);
- }
-
- @override
- Object visitFieldFormalParameter(FieldFormalParameter node) {
- if (node.parent is! DefaultFormalParameter) {
- SimpleIdentifier parameterName = node.identifier;
- FieldElement field =
- _fieldMap == null ? null : _fieldMap[parameterName.name];
- FieldFormalParameterElementImpl parameter =
- new FieldFormalParameterElementImpl.forNode(parameterName);
- _setCodeRange(parameter, node);
- parameter.const3 = node.isConst;
- parameter.final2 = node.isFinal;
- parameter.parameterKind = node.kind;
- if (field != null) {
- parameter.field = field;
- }
- _currentHolder.addParameter(parameter);
- parameterName.staticElement = parameter;
- }
- //
- // The children of this parameter include any parameters defined on the type
- // of this parameter.
- //
- ElementHolder holder = new ElementHolder();
- _visitChildren(holder, node);
- ParameterElementImpl element = node.element;
- element.metadata = _createElementAnnotations(node.metadata);
- element.parameters = holder.parameters;
- element.typeParameters = holder.typeParameters;
- holder.validate();
- return null;
- }
-
- @override
- Object visitFunctionDeclaration(FunctionDeclaration node) {
- FunctionExpression expression = node.functionExpression;
- if (expression != null) {
- ElementHolder holder = new ElementHolder();
- bool wasInFunction = _inFunction;
- _inFunction = true;
- try {
- _visitChildren(holder, node);
- } finally {
- _inFunction = wasInFunction;
- }
- FunctionBody body = expression.body;
- Token property = node.propertyKeyword;
- if (property == null || _inFunction) {
- SimpleIdentifier functionName = node.name;
- FunctionElementImpl element =
- new FunctionElementImpl.forNode(functionName);
- _setCodeRange(element, node);
- element.metadata = _createElementAnnotations(node.metadata);
- setElementDocumentationComment(element, node);
- if (node.externalKeyword != null) {
- element.external = true;
- }
- element.functions = holder.functions;
- element.labels = holder.labels;
- element.localVariables = holder.localVariables;
- element.parameters = holder.parameters;
- element.typeParameters = holder.typeParameters;
- if (body.isAsynchronous) {
- element.asynchronous = true;
- }
- if (body.isGenerator) {
- element.generator = true;
- }
- if (_inFunction) {
- Block enclosingBlock = node.getAncestor((node) => node is Block);
- if (enclosingBlock != null) {
- element.setVisibleRange(
- enclosingBlock.offset, enclosingBlock.length);
- }
- }
- if (node.returnType == null) {
- element.hasImplicitReturnType = true;
- }
- _currentHolder.addFunction(element);
- expression.element = element;
- functionName.staticElement = element;
- } else {
- SimpleIdentifier propertyNameNode = node.name;
- if (propertyNameNode == null) {
- // TODO(brianwilkerson) Report this internal error.
- return null;
- }
- String propertyName = propertyNameNode.name;
- TopLevelVariableElementImpl variable = _currentHolder
- .getTopLevelVariable(propertyName) as TopLevelVariableElementImpl;
- if (variable == null) {
- variable = new TopLevelVariableElementImpl(node.name.name, -1);
- variable.final2 = true;
- variable.synthetic = true;
- _currentHolder.addTopLevelVariable(variable);
- }
- if (node.isGetter) {
- PropertyAccessorElementImpl getter =
- new PropertyAccessorElementImpl.forNode(propertyNameNode);
- _setCodeRange(getter, node);
- getter.metadata = _createElementAnnotations(node.metadata);
- setElementDocumentationComment(getter, node);
- if (node.externalKeyword != null) {
- getter.external = true;
- }
- getter.functions = holder.functions;
- getter.labels = holder.labels;
- getter.localVariables = holder.localVariables;
- if (body.isAsynchronous) {
- getter.asynchronous = true;
- }
- if (body.isGenerator) {
- getter.generator = true;
- }
- getter.variable = variable;
- getter.getter = true;
- getter.static = true;
- variable.getter = getter;
- if (node.returnType == null) {
- getter.hasImplicitReturnType = true;
- }
- _currentHolder.addAccessor(getter);
- expression.element = getter;
- propertyNameNode.staticElement = getter;
- } else {
- PropertyAccessorElementImpl setter =
- new PropertyAccessorElementImpl.forNode(propertyNameNode);
- _setCodeRange(setter, node);
- setter.metadata = _createElementAnnotations(node.metadata);
- setElementDocumentationComment(setter, node);
- if (node.externalKeyword != null) {
- setter.external = true;
- }
- setter.functions = holder.functions;
- setter.labels = holder.labels;
- setter.localVariables = holder.localVariables;
- setter.parameters = holder.parameters;
- if (body.isAsynchronous) {
- setter.asynchronous = true;
- }
- if (body.isGenerator) {
- setter.generator = true;
- }
- setter.variable = variable;
- setter.setter = true;
- setter.static = true;
- if (node.returnType == null) {
- setter.hasImplicitReturnType = true;
- }
- variable.setter = setter;
- variable.final2 = false;
- _currentHolder.addAccessor(setter);
- expression.element = setter;
- propertyNameNode.staticElement = setter;
- }
- }
- holder.validate();
- }
- return null;
- }
-
- @override
- Object visitFunctionExpression(FunctionExpression node) {
- if (node.parent is FunctionDeclaration) {
- // visitFunctionDeclaration has already created the element for the
- // declaration. We just need to visit children.
- return super.visitFunctionExpression(node);
- }
- ElementHolder holder = new ElementHolder();
- bool wasInFunction = _inFunction;
- _inFunction = true;
- try {
- _visitChildren(holder, node);
- } finally {
- _inFunction = wasInFunction;
- }
- FunctionBody body = node.body;
- FunctionElementImpl element =
- new FunctionElementImpl.forOffset(node.beginToken.offset);
- _setCodeRange(element, node);
- element.functions = holder.functions;
- element.labels = holder.labels;
- element.localVariables = holder.localVariables;
- element.parameters = holder.parameters;
- element.typeParameters = holder.typeParameters;
- if (body.isAsynchronous) {
- element.asynchronous = true;
- }
- if (body.isGenerator) {
- element.generator = true;
- }
- if (_inFunction) {
- Block enclosingBlock = node.getAncestor((node) => node is Block);
- if (enclosingBlock != null) {
- element.setVisibleRange(enclosingBlock.offset, enclosingBlock.length);
- }
- }
- if (_functionTypesToFix != null) {
- _functionTypesToFix.add(element);
- } else {
- element.type = new FunctionTypeImpl(element);
- }
- element.hasImplicitReturnType = true;
- _currentHolder.addFunction(element);
- node.element = element;
- holder.validate();
- return null;
- }
-
- @override
- Object visitFunctionTypeAlias(FunctionTypeAlias node) {
- ElementHolder holder = new ElementHolder();
- _visitChildren(holder, node);
- SimpleIdentifier aliasName = node.name;
- List<ParameterElement> parameters = holder.parameters;
- List<TypeParameterElement> typeParameters = holder.typeParameters;
- FunctionTypeAliasElementImpl element =
- new FunctionTypeAliasElementImpl.forNode(aliasName);
- _setCodeRange(element, node);
- element.metadata = _createElementAnnotations(node.metadata);
- setElementDocumentationComment(element, node);
- element.parameters = parameters;
- element.typeParameters = typeParameters;
- _createTypeParameterTypes(typeParameters);
- element.type = new FunctionTypeImpl.forTypedef(element);
- _currentHolder.addTypeAlias(element);
- aliasName.staticElement = element;
- holder.validate();
return null;
}
@@ -896,200 +1425,6 @@
}
@override
- Object visitImportDirective(ImportDirective node) {
- List<ElementAnnotation> annotations =
- _createElementAnnotations(node.metadata);
- compilationUnitElement.setAnnotations(node.offset, annotations);
- return super.visitImportDirective(node);
- }
-
- @override
- Object visitLabeledStatement(LabeledStatement node) {
- bool onSwitchStatement = node.statement is SwitchStatement;
- for (Label label in node.labels) {
- SimpleIdentifier labelName = label.label;
- LabelElementImpl element =
- new LabelElementImpl.forNode(labelName, onSwitchStatement, false);
- _currentHolder.addLabel(element);
- labelName.staticElement = element;
- }
- return super.visitLabeledStatement(node);
- }
-
- @override
- Object visitLibraryDirective(LibraryDirective node) {
- List<ElementAnnotation> annotations =
- _createElementAnnotations(node.metadata);
- compilationUnitElement.setAnnotations(node.offset, annotations);
- return super.visitLibraryDirective(node);
- }
-
- @override
- Object visitMethodDeclaration(MethodDeclaration node) {
- try {
- ElementHolder holder = new ElementHolder();
- bool wasInFunction = _inFunction;
- _inFunction = true;
- try {
- _visitChildren(holder, node);
- } finally {
- _inFunction = wasInFunction;
- }
- bool isStatic = node.isStatic;
- Token property = node.propertyKeyword;
- FunctionBody body = node.body;
- if (property == null) {
- SimpleIdentifier methodName = node.name;
- String nameOfMethod = methodName.name;
- if (nameOfMethod == TokenType.MINUS.lexeme &&
- node.parameters.parameters.length == 0) {
- nameOfMethod = "unary-";
- }
- MethodElementImpl element =
- new MethodElementImpl(nameOfMethod, methodName.offset);
- _setCodeRange(element, node);
- element.metadata = _createElementAnnotations(node.metadata);
- setElementDocumentationComment(element, node);
- element.abstract = node.isAbstract;
- if (node.externalKeyword != null) {
- element.external = true;
- }
- element.functions = holder.functions;
- element.labels = holder.labels;
- element.localVariables = holder.localVariables;
- element.parameters = holder.parameters;
- element.static = isStatic;
- element.typeParameters = holder.typeParameters;
- if (body.isAsynchronous) {
- element.asynchronous = true;
- }
- if (body.isGenerator) {
- element.generator = true;
- }
- if (node.returnType == null) {
- element.hasImplicitReturnType = true;
- }
- _currentHolder.addMethod(element);
- methodName.staticElement = element;
- } else {
- SimpleIdentifier propertyNameNode = node.name;
- String propertyName = propertyNameNode.name;
- FieldElementImpl field = _currentHolder.getField(propertyName,
- synthetic: true) as FieldElementImpl;
- if (field == null) {
- field = new FieldElementImpl(node.name.name, -1);
- field.final2 = true;
- field.static = isStatic;
- field.synthetic = true;
- _currentHolder.addField(field);
- }
- if (node.isGetter) {
- PropertyAccessorElementImpl getter =
- new PropertyAccessorElementImpl.forNode(propertyNameNode);
- _setCodeRange(getter, node);
- getter.metadata = _createElementAnnotations(node.metadata);
- setElementDocumentationComment(getter, node);
- if (node.externalKeyword != null) {
- getter.external = true;
- }
- getter.functions = holder.functions;
- getter.labels = holder.labels;
- getter.localVariables = holder.localVariables;
- if (body.isAsynchronous) {
- getter.asynchronous = true;
- }
- if (body.isGenerator) {
- getter.generator = true;
- }
- getter.variable = field;
- getter.abstract = node.isAbstract;
- getter.getter = true;
- getter.static = isStatic;
- field.getter = getter;
- if (node.returnType == null) {
- getter.hasImplicitReturnType = true;
- }
- _currentHolder.addAccessor(getter);
- propertyNameNode.staticElement = getter;
- } else {
- PropertyAccessorElementImpl setter =
- new PropertyAccessorElementImpl.forNode(propertyNameNode);
- _setCodeRange(setter, node);
- setter.metadata = _createElementAnnotations(node.metadata);
- setElementDocumentationComment(setter, node);
- if (node.externalKeyword != null) {
- setter.external = true;
- }
- setter.functions = holder.functions;
- setter.labels = holder.labels;
- setter.localVariables = holder.localVariables;
- setter.parameters = holder.parameters;
- if (body.isAsynchronous) {
- setter.asynchronous = true;
- }
- if (body.isGenerator) {
- setter.generator = true;
- }
- setter.variable = field;
- setter.abstract = node.isAbstract;
- setter.setter = true;
- setter.static = isStatic;
- if (node.returnType == null) {
- setter.hasImplicitReturnType = true;
- }
- field.setter = setter;
- field.final2 = false;
- _currentHolder.addAccessor(setter);
- propertyNameNode.staticElement = setter;
- }
- }
- holder.validate();
- } catch (exception, stackTrace) {
- if (node.name.staticElement == null) {
- ClassDeclaration classNode =
- node.getAncestor((node) => node is ClassDeclaration);
- StringBuffer buffer = new StringBuffer();
- buffer.write("The element for the method ");
- buffer.write(node.name);
- buffer.write(" in ");
- buffer.write(classNode.name);
- buffer.write(" was not set while trying to build the element model.");
- AnalysisEngine.instance.logger.logError(
- buffer.toString(), new CaughtException(exception, stackTrace));
- } else {
- String message =
- "Exception caught in ElementBuilder.visitMethodDeclaration()";
- AnalysisEngine.instance.logger
- .logError(message, new CaughtException(exception, stackTrace));
- }
- } finally {
- if (node.name.staticElement == null) {
- ClassDeclaration classNode =
- node.getAncestor((node) => node is ClassDeclaration);
- StringBuffer buffer = new StringBuffer();
- buffer.write("The element for the method ");
- buffer.write(node.name);
- buffer.write(" in ");
- buffer.write(classNode.name);
- buffer.write(" was not set while trying to resolve types.");
- AnalysisEngine.instance.logger.logError(
- buffer.toString(),
- new CaughtException(
- new AnalysisException(buffer.toString()), null));
- }
- }
- return null;
- }
-
- @override
- Object visitPartDirective(PartDirective node) {
- List<ElementAnnotation> annotations =
- _createElementAnnotations(node.metadata);
- compilationUnitElement.setAnnotations(node.offset, annotations);
- return super.visitPartDirective(node);
- }
-
- @override
Object visitSimpleFormalParameter(SimpleFormalParameter node) {
if (node.parent is! DefaultFormalParameter) {
SimpleIdentifier parameterName = node.identifier;
@@ -1113,30 +1448,6 @@
}
@override
- Object visitSwitchCase(SwitchCase node) {
- for (Label label in node.labels) {
- SimpleIdentifier labelName = label.label;
- LabelElementImpl element =
- new LabelElementImpl.forNode(labelName, false, true);
- _currentHolder.addLabel(element);
- labelName.staticElement = element;
- }
- return super.visitSwitchCase(node);
- }
-
- @override
- Object visitSwitchDefault(SwitchDefault node) {
- for (Label label in node.labels) {
- SimpleIdentifier labelName = label.label;
- LabelElementImpl element =
- new LabelElementImpl.forNode(labelName, false, true);
- _currentHolder.addLabel(element);
- labelName.staticElement = element;
- }
- return super.visitSwitchDefault(node);
- }
-
- @override
Object visitTypeParameter(TypeParameter node) {
SimpleIdentifier parameterName = node.name;
TypeParameterElementImpl typeParameter =
@@ -1151,141 +1462,6 @@
return super.visitTypeParameter(node);
}
- @override
- Object visitVariableDeclaration(VariableDeclaration node) {
- bool isConst = node.isConst;
- bool isFinal = node.isFinal;
- bool hasInitializer = node.initializer != null;
- VariableDeclarationList varList = node.parent;
- FieldDeclaration fieldNode =
- varList.parent is FieldDeclaration ? varList.parent : null;
- VariableElementImpl element;
- if (fieldNode != null) {
- SimpleIdentifier fieldName = node.name;
- FieldElementImpl field;
- if ((isConst || isFinal && !fieldNode.isStatic) && hasInitializer) {
- field = new ConstFieldElementImpl.forNode(fieldName);
- } else {
- field = new FieldElementImpl.forNode(fieldName);
- }
- element = field;
- field.static = fieldNode.isStatic;
- _setCodeRange(element, node);
- setElementDocumentationComment(element, fieldNode);
- field.hasImplicitType = varList.type == null;
- _currentHolder.addField(field);
- fieldName.staticElement = field;
- } else if (_inFunction) {
- SimpleIdentifier variableName = node.name;
- LocalVariableElementImpl variable;
- if (isConst && hasInitializer) {
- variable = new ConstLocalVariableElementImpl.forNode(variableName);
- } else {
- variable = new LocalVariableElementImpl.forNode(variableName);
- }
- element = variable;
- _setCodeRange(element, node);
- _setVariableVisibleRange(variable, node);
- variable.hasImplicitType = varList.type == null;
- _currentHolder.addLocalVariable(variable);
- variableName.staticElement = element;
- } else {
- SimpleIdentifier variableName = node.name;
- TopLevelVariableElementImpl variable;
- if (isConst && hasInitializer) {
- variable = new ConstTopLevelVariableElementImpl.forNode(variableName);
- } else {
- variable = new TopLevelVariableElementImpl.forNode(variableName);
- }
- element = variable;
- _setCodeRange(element, node);
- if (varList.parent is TopLevelVariableDeclaration) {
- setElementDocumentationComment(element, varList.parent);
- }
- variable.hasImplicitType = varList.type == null;
- _currentHolder.addTopLevelVariable(variable);
- variableName.staticElement = element;
- }
- element.const3 = isConst;
- element.final2 = isFinal;
- if (hasInitializer) {
- ElementHolder holder = new ElementHolder();
- _visit(holder, node.initializer);
- FunctionElementImpl initializer =
- new FunctionElementImpl.forOffset(node.initializer.beginToken.offset);
- initializer.hasImplicitReturnType = true;
- initializer.functions = holder.functions;
- initializer.labels = holder.labels;
- initializer.localVariables = holder.localVariables;
- initializer.synthetic = true;
- initializer.type = new FunctionTypeImpl(initializer);
- element.initializer = initializer;
- holder.validate();
- }
- if (element is PropertyInducingElementImpl) {
- PropertyAccessorElementImpl_ImplicitGetter getter =
- new PropertyAccessorElementImpl_ImplicitGetter(element);
- _currentHolder.addAccessor(getter);
- if (!isConst && !isFinal) {
- PropertyAccessorElementImpl_ImplicitSetter setter =
- new PropertyAccessorElementImpl_ImplicitSetter(element);
- _currentHolder.addAccessor(setter);
- }
- }
- return null;
- }
-
- @override
- Object visitVariableDeclarationList(VariableDeclarationList node) {
- super.visitVariableDeclarationList(node);
- AstNode parent = node.parent;
- List<ElementAnnotation> elementAnnotations;
- if (parent is FieldDeclaration) {
- elementAnnotations = _createElementAnnotations(parent.metadata);
- } else if (parent is TopLevelVariableDeclaration) {
- elementAnnotations = _createElementAnnotations(parent.metadata);
- } else {
- // Local variable declaration
- elementAnnotations = _createElementAnnotations(node.metadata);
- }
- for (VariableDeclaration variableDeclaration in node.variables) {
- ElementImpl element = variableDeclaration.element as ElementImpl;
- _setCodeRange(element, node.parent);
- element.metadata = elementAnnotations;
- }
- return null;
- }
-
- /**
- * Build the table mapping field names to field elements for the fields defined in the current
- * class.
- *
- * @param fields the field elements defined in the current class
- */
- void _buildFieldMap(List<FieldElement> fields) {
- _fieldMap = new HashMap<String, FieldElement>();
- int count = fields.length;
- for (int i = 0; i < count; i++) {
- FieldElement field = fields[i];
- _fieldMap[field.name] ??= field;
- }
- }
-
- /**
- * Creates the [ConstructorElement]s array with the single default constructor element.
- *
- * @param interfaceType the interface type for which to create a default constructor
- * @return the [ConstructorElement]s array with the single default constructor element
- */
- List<ConstructorElement> _createDefaultConstructors(
- ClassElementImpl definingClass) {
- ConstructorElementImpl constructor =
- new ConstructorElementImpl.forNode(null);
- constructor.synthetic = true;
- constructor.enclosingElement = definingClass;
- return <ConstructorElement>[constructor];
- }
-
/**
* For each [Annotation] found in [annotations], create a new
* [ElementAnnotation] object and set the [Annotation] to point to it.
@@ -1297,35 +1473,13 @@
}
return annotations.map((Annotation a) {
ElementAnnotationImpl elementAnnotation =
- new ElementAnnotationImpl(compilationUnitElement);
+ new ElementAnnotationImpl(_unitElement);
a.elementAnnotation = elementAnnotation;
return elementAnnotation;
}).toList();
}
/**
- * Create the types associated with the given type parameters, setting the type of each type
- * parameter, and return an array of types corresponding to the given parameters.
- *
- * @param typeParameters the type parameters for which types are to be created
- * @return an array of types corresponding to the given parameters
- */
- List<DartType> _createTypeParameterTypes(
- List<TypeParameterElement> typeParameters) {
- int typeParameterCount = typeParameters.length;
- List<DartType> typeArguments = new List<DartType>(typeParameterCount);
- for (int i = 0; i < typeParameterCount; i++) {
- TypeParameterElementImpl typeParameter =
- typeParameters[i] as TypeParameterElementImpl;
- TypeParameterTypeImpl typeParameterType =
- new TypeParameterTypeImpl(typeParameter);
- typeParameter.type = typeParameterType;
- typeArguments[i] = typeParameterType;
- }
- return typeArguments;
- }
-
- /**
* Return the body of the function that contains the given [parameter], or
* `null` if no function body could be found.
*/
@@ -1345,6 +1499,8 @@
element.setCodeRange(node.offset, node.length);
}
+ void _setFieldParameterField(FieldFormalParameterElementImpl parameter) {}
+
/**
* Sets the visible source range for formal parameter.
*/
@@ -1356,16 +1512,13 @@
}
}
- void _setVariableVisibleRange(
- LocalVariableElementImpl element, VariableDeclaration node) {
- AstNode scopeNode;
- AstNode parent2 = node.parent.parent;
- if (parent2 is ForStatement) {
- scopeNode = parent2;
- } else {
- scopeNode = node.getAncestor((node) => node is Block);
+ void _setVariableDeclarationListAnnotations(VariableDeclarationList node,
+ List<ElementAnnotation> elementAnnotations) {
+ for (VariableDeclaration variableDeclaration in node.variables) {
+ ElementImpl element = variableDeclaration.element as ElementImpl;
+ _setCodeRange(element, node.parent);
+ element.metadata = elementAnnotations;
}
- element.setVisibleRange(scopeNode.offset, scopeNode.length);
}
/**
@@ -1406,7 +1559,7 @@
}
class _ElementBuilder_visitClassDeclaration extends UnifyingAstVisitor<Object> {
- final ElementBuilder builder;
+ final ApiElementBuilder builder;
List<ClassMember> nonFields;
diff --git a/pkg/analyzer/lib/src/dart/error/syntactic_errors.dart b/pkg/analyzer/lib/src/dart/error/syntactic_errors.dart
index 706abd1..ffc9fab 100644
--- a/pkg/analyzer/lib/src/dart/error/syntactic_errors.dart
+++ b/pkg/analyzer/lib/src/dart/error/syntactic_errors.dart
@@ -3,7 +3,7 @@
// BSD-style license that can be found in the LICENSE file.
/**
- * The errors produced during sytactic analysis (scanning and parsing).
+ * The errors produced during syntactic analysis (scanning and parsing).
*/
library analyzer.src.dart.error.syntactic_errors;
@@ -18,29 +18,41 @@
class ParserErrorCode extends ErrorCode {
static const ParserErrorCode ABSTRACT_CLASS_MEMBER = const ParserErrorCode(
'ABSTRACT_CLASS_MEMBER',
- "Members of classes cannot be declared to be 'abstract'");
+ "Members of classes can't be declared to be 'abstract'.",
+ "Try removing the keyword 'abstract'.");
static const ParserErrorCode ABSTRACT_ENUM = const ParserErrorCode(
- 'ABSTRACT_ENUM', "Enums cannot be declared to be 'abstract'");
+ 'ABSTRACT_ENUM',
+ "Enums can't be declared to be 'abstract'.",
+ "Try removing the keyword 'abstract'.");
static const ParserErrorCode ABSTRACT_STATIC_METHOD = const ParserErrorCode(
'ABSTRACT_STATIC_METHOD',
- "Static methods cannot be declared to be 'abstract'");
+ "Static methods can't be declared to be 'abstract'.",
+ "Try removing the keyword 'abstract'.");
static const ParserErrorCode ABSTRACT_TOP_LEVEL_FUNCTION =
- const ParserErrorCode('ABSTRACT_TOP_LEVEL_FUNCTION',
- "Top-level functions cannot be declared to be 'abstract'");
+ const ParserErrorCode(
+ 'ABSTRACT_TOP_LEVEL_FUNCTION',
+ "Top-level functions can't be declared to be 'abstract'.",
+ "Try removing the keyword 'abstract'.");
static const ParserErrorCode ABSTRACT_TOP_LEVEL_VARIABLE =
- const ParserErrorCode('ABSTRACT_TOP_LEVEL_VARIABLE',
- "Top-level variables cannot be declared to be 'abstract'");
+ const ParserErrorCode(
+ 'ABSTRACT_TOP_LEVEL_VARIABLE',
+ "Top-level variables can't be declared to be 'abstract'.",
+ "Try removing the keyword 'abstract'.");
static const ParserErrorCode ABSTRACT_TYPEDEF = const ParserErrorCode(
- 'ABSTRACT_TYPEDEF', "Type aliases cannot be declared to be 'abstract'");
+ 'ABSTRACT_TYPEDEF',
+ "Typedefs can't be declared to be 'abstract'.",
+ "Try removing the keyword 'abstract'.");
static const ParserErrorCode ANNOTATION_ON_ENUM_CONSTANT =
- const ParserErrorCode('ANNOTATION_ON_ENUM_CONSTANT',
- "Enum constants cannot have annotations");
+ const ParserErrorCode(
+ 'ANNOTATION_ON_ENUM_CONSTANT',
+ "Enum constants can't have annotations.",
+ "Try removing the annotation.");
/**
* 16.32 Identifier Reference: It is a compile-time error if any of the
@@ -48,19 +60,15 @@
* body marked with either async, async*, or sync*.
*/
static const ParserErrorCode ASYNC_KEYWORD_USED_AS_IDENTIFIER =
- const ParserErrorCode('ASYNC_KEYWORD_USED_AS_IDENTIFIER',
- "The keywords 'async', 'await', and 'yield' may not be used as identifiers in an asynchronous or generator function.");
-
- /**
- * Some environments, such as Fletch, do not support async.
- */
- static const ParserErrorCode ASYNC_NOT_SUPPORTED = const ParserErrorCode(
- 'ASYNC_NOT_SUPPORTED',
- "Async and sync are not supported in this environment.");
+ const ParserErrorCode(
+ 'ASYNC_KEYWORD_USED_AS_IDENTIFIER',
+ "The keywords 'async', 'await', and 'yield' can't be used as "
+ "identifiers in an asynchronous or generator function.");
static const ParserErrorCode BREAK_OUTSIDE_OF_LOOP = const ParserErrorCode(
'BREAK_OUTSIDE_OF_LOOP',
- "A break statement cannot be used outside of a loop or switch statement");
+ "A break statement can't be used outside of a loop or switch statement.",
+ "Try removing the break statement.");
static const ParserErrorCode CLASS_IN_CLASS = const ParserErrorCode(
'CLASS_IN_CLASS',
@@ -68,7 +76,9 @@
"Try moving the class to the top-level.");
static const ParserErrorCode COLON_IN_PLACE_OF_IN = const ParserErrorCode(
- 'COLON_IN_PLACE_OF_IN', "For-in loops use 'in' rather than a colon");
+ 'COLON_IN_PLACE_OF_IN',
+ "For-in loops use 'in' rather than a colon.",
+ "Try replacing the colon with the keyword 'in'.");
static const ParserErrorCode CONST_AND_FINAL = const ParserErrorCode(
'CONST_AND_FINAL',
@@ -83,13 +93,15 @@
static const ParserErrorCode CONST_CLASS = const ParserErrorCode(
'CONST_CLASS',
"Classes can't be declared to be 'const'.",
- "Try removing the 'const' keyword or moving to the class' constructor(s).");
+ "Try removing the 'const' keyword. If you're trying to indicate that "
+ "instances of the class can be constants, place the 'const' keyword on "
+ "the class' constructor(s).");
static const ParserErrorCode CONST_CONSTRUCTOR_WITH_BODY =
const ParserErrorCode(
'CONST_CONSTRUCTOR_WITH_BODY',
- "Const constructor can't have a body.",
- "Try removing the 'const' keyword or the body.");
+ "Const constructors can't have a body.",
+ "Try removing either the 'const' keyword or the body.");
static const ParserErrorCode CONST_ENUM = const ParserErrorCode(
'CONST_ENUM',
@@ -99,7 +111,8 @@
static const ParserErrorCode CONST_FACTORY = const ParserErrorCode(
'CONST_FACTORY',
"Only redirecting factory constructors can be declared to be 'const'.",
- "Try removing the 'const' keyword or replacing the body with '=' followed by a valid target.");
+ "Try removing the 'const' keyword, or "
+ "replacing the body with '=' followed by a valid target.");
static const ParserErrorCode CONST_METHOD = const ParserErrorCode(
'CONST_METHOD',
@@ -119,533 +132,797 @@
static const ParserErrorCode CONTINUE_OUTSIDE_OF_LOOP = const ParserErrorCode(
'CONTINUE_OUTSIDE_OF_LOOP',
- "A continue statement cannot be used outside of a loop or switch statement");
+ "A continue statement can't be used outside of a loop or switch statement.",
+ "Try removing the continue statement.");
- static const ParserErrorCode CONTINUE_WITHOUT_LABEL_IN_CASE =
- const ParserErrorCode('CONTINUE_WITHOUT_LABEL_IN_CASE',
- "A continue statement in a switch statement must have a label as a target");
+ static const ParserErrorCode CONTINUE_WITHOUT_LABEL_IN_CASE = const ParserErrorCode(
+ 'CONTINUE_WITHOUT_LABEL_IN_CASE',
+ "A continue statement in a switch statement must have a label as a target.",
+ "Try adding a label associated with one of the case clauses to the continue statement.");
static const ParserErrorCode DEPRECATED_CLASS_TYPE_ALIAS =
- const ParserErrorCode('DEPRECATED_CLASS_TYPE_ALIAS',
- "The 'typedef' mixin application was replaced with 'class'");
+ const ParserErrorCode(
+ 'DEPRECATED_CLASS_TYPE_ALIAS',
+ "The 'typedef' mixin application was replaced with 'class'.",
+ "Try re-writing the typedef as 'class C = S with M'.");
static const ParserErrorCode DIRECTIVE_AFTER_DECLARATION =
- const ParserErrorCode('DIRECTIVE_AFTER_DECLARATION',
- "Directives must appear before any declarations");
+ const ParserErrorCode(
+ 'DIRECTIVE_AFTER_DECLARATION',
+ "Directives must appear before any declarations.",
+ "Try moving the directive before any declarations.");
+ /**
+ * Parameters:
+ * 0: the label that was duplicated
+ */
static const ParserErrorCode DUPLICATE_LABEL_IN_SWITCH_STATEMENT =
- const ParserErrorCode('DUPLICATE_LABEL_IN_SWITCH_STATEMENT',
- "The label {0} was already used in this switch statement");
+ const ParserErrorCode(
+ 'DUPLICATE_LABEL_IN_SWITCH_STATEMENT',
+ "The label '{0}' was already used in this switch statement.",
+ "Try choosing a different name for this label.");
+ /**
+ * Parameters:
+ * 0: the modifier that was duplicated
+ */
static const ParserErrorCode DUPLICATED_MODIFIER = const ParserErrorCode(
- 'DUPLICATED_MODIFIER', "The modifier '{0}' was already specified.");
+ 'DUPLICATED_MODIFIER',
+ "The modifier '{0}' was already specified.",
+ "Try removing all but one occurance of the modifier.");
static const ParserErrorCode EMPTY_ENUM_BODY = const ParserErrorCode(
- 'EMPTY_ENUM_BODY', "An enum must declare at least one constant name");
+ 'EMPTY_ENUM_BODY',
+ "An enum must declare at least one constant name.",
+ "Try declaring a constant.");
static const ParserErrorCode ENUM_IN_CLASS = const ParserErrorCode(
- 'ENUM_IN_CLASS', "Enums cannot be declared inside classes");
+ 'ENUM_IN_CLASS',
+ "Enums can't be declared inside classes.",
+ "Try moving the enum to the top-level.");
static const ParserErrorCode EQUALITY_CANNOT_BE_EQUALITY_OPERAND =
- const ParserErrorCode('EQUALITY_CANNOT_BE_EQUALITY_OPERAND',
- "Equality expression cannot be operand of another equality expression.");
+ const ParserErrorCode(
+ 'EQUALITY_CANNOT_BE_EQUALITY_OPERAND',
+ "An equality expression can't be an operand of another equality expression.",
+ "Try re-writing the expression.");
static const ParserErrorCode EXPECTED_CASE_OR_DEFAULT = const ParserErrorCode(
- 'EXPECTED_CASE_OR_DEFAULT', "Expected 'case' or 'default'");
+ 'EXPECTED_CASE_OR_DEFAULT',
+ "Expected 'case' or 'default'.",
+ "Try placing this code inside a case clause.");
- static const ParserErrorCode EXPECTED_CLASS_MEMBER =
- const ParserErrorCode('EXPECTED_CLASS_MEMBER', "Expected a class member");
+ static const ParserErrorCode EXPECTED_CLASS_MEMBER = const ParserErrorCode(
+ 'EXPECTED_CLASS_MEMBER',
+ "Expected a class member.",
+ "Try placing this code inside a class member.");
static const ParserErrorCode EXPECTED_EXECUTABLE = const ParserErrorCode(
'EXPECTED_EXECUTABLE',
- "Expected a method, getter, setter or operator declaration");
+ "Expected a method, getter, setter or operator declaration.",
+ "This appears to be incomplete code. Try removing it or completing it.");
static const ParserErrorCode EXPECTED_LIST_OR_MAP_LITERAL =
const ParserErrorCode(
- 'EXPECTED_LIST_OR_MAP_LITERAL', "Expected a list or map literal");
+ 'EXPECTED_LIST_OR_MAP_LITERAL',
+ "Expected a list or map literal.",
+ "Try inserting a list or map literal, or remove the type arguments.");
static const ParserErrorCode EXPECTED_STRING_LITERAL = const ParserErrorCode(
- 'EXPECTED_STRING_LITERAL', "Expected a string literal");
+ 'EXPECTED_STRING_LITERAL', "Expected a string literal.");
+ /**
+ * Parameters:
+ * 0: the token that was expected but not found
+ */
static const ParserErrorCode EXPECTED_TOKEN =
- const ParserErrorCode('EXPECTED_TOKEN', "Expected to find '{0}'");
+ const ParserErrorCode('EXPECTED_TOKEN', "Expected to find '{0}'.");
static const ParserErrorCode EXPECTED_TYPE_NAME =
- const ParserErrorCode('EXPECTED_TYPE_NAME', "Expected a type name");
+ const ParserErrorCode('EXPECTED_TYPE_NAME', "Expected a type name.");
static const ParserErrorCode EXPORT_DIRECTIVE_AFTER_PART_DIRECTIVE =
- const ParserErrorCode('EXPORT_DIRECTIVE_AFTER_PART_DIRECTIVE',
- "Export directives must preceed part directives");
+ const ParserErrorCode(
+ 'EXPORT_DIRECTIVE_AFTER_PART_DIRECTIVE',
+ "Export directives must preceed part directives.",
+ "Try moving the export directives before the part directives.");
static const ParserErrorCode EXTERNAL_AFTER_CONST = const ParserErrorCode(
'EXTERNAL_AFTER_CONST',
- "The modifier 'external' should be before the modifier 'const'");
+ "The modifier 'external' should be before the modifier 'const'.",
+ "Try re-ordering the modifiers.");
static const ParserErrorCode EXTERNAL_AFTER_FACTORY = const ParserErrorCode(
'EXTERNAL_AFTER_FACTORY',
- "The modifier 'external' should be before the modifier 'factory'");
+ "The modifier 'external' should be before the modifier 'factory'.",
+ "Try re-ordering the modifiers.");
static const ParserErrorCode EXTERNAL_AFTER_STATIC = const ParserErrorCode(
'EXTERNAL_AFTER_STATIC',
- "The modifier 'external' should be before the modifier 'static'");
+ "The modifier 'external' should be before the modifier 'static'.",
+ "Try re-ordering the modifiers.");
static const ParserErrorCode EXTERNAL_CLASS = const ParserErrorCode(
- 'EXTERNAL_CLASS', "Classes cannot be declared to be 'external'");
+ 'EXTERNAL_CLASS',
+ "Classes can't be declared to be 'external'.",
+ "Try removing the keyword 'external'.");
static const ParserErrorCode EXTERNAL_CONSTRUCTOR_WITH_BODY =
- const ParserErrorCode('EXTERNAL_CONSTRUCTOR_WITH_BODY',
- "External constructors cannot have a body");
+ const ParserErrorCode(
+ 'EXTERNAL_CONSTRUCTOR_WITH_BODY',
+ "External constructors can't have a body.",
+ "Try removing the body of the constructor, or "
+ "removing the keyword 'external'.");
static const ParserErrorCode EXTERNAL_ENUM = const ParserErrorCode(
- 'EXTERNAL_ENUM', "Enums cannot be declared to be 'external'");
+ 'EXTERNAL_ENUM',
+ "Enums can't be declared to be 'external'.",
+ "Try removing the keyword 'external'.");
static const ParserErrorCode EXTERNAL_FIELD = const ParserErrorCode(
- 'EXTERNAL_FIELD', "Fields cannot be declared to be 'external'");
+ 'EXTERNAL_FIELD',
+ "Fields can't be declared to be 'external'.",
+ "Try removing the keyword 'external'.");
static const ParserErrorCode EXTERNAL_GETTER_WITH_BODY =
const ParserErrorCode(
- 'EXTERNAL_GETTER_WITH_BODY', "External getters cannot have a body");
+ 'EXTERNAL_GETTER_WITH_BODY',
+ "External getters can't have a body.",
+ "Try removing the body of the getter, or "
+ "removing the keyword 'external'.");
static const ParserErrorCode EXTERNAL_METHOD_WITH_BODY =
const ParserErrorCode(
- 'EXTERNAL_METHOD_WITH_BODY', "External methods cannot have a body");
+ 'EXTERNAL_METHOD_WITH_BODY',
+ "External methods can't have a body.",
+ "Try removing the body of the method, or "
+ "removing the keyword 'external'.");
static const ParserErrorCode EXTERNAL_OPERATOR_WITH_BODY =
- const ParserErrorCode('EXTERNAL_OPERATOR_WITH_BODY',
- "External operators cannot have a body");
+ const ParserErrorCode(
+ 'EXTERNAL_OPERATOR_WITH_BODY',
+ "External operators can't have a body.",
+ "Try removing the body of the operator, or "
+ "removing the keyword 'external'.");
static const ParserErrorCode EXTERNAL_SETTER_WITH_BODY =
const ParserErrorCode(
- 'EXTERNAL_SETTER_WITH_BODY', "External setters cannot have a body");
+ 'EXTERNAL_SETTER_WITH_BODY',
+ "External setters can't have a body.",
+ "Try removing the body of the setter, or "
+ "removing the keyword 'external'.");
static const ParserErrorCode EXTERNAL_TYPEDEF = const ParserErrorCode(
- 'EXTERNAL_TYPEDEF', "Type aliases cannot be declared to be 'external'");
+ 'EXTERNAL_TYPEDEF',
+ "Typedefs can't be declared to be 'external'.",
+ "Try removing the keyword 'external'.");
static const ParserErrorCode FACTORY_TOP_LEVEL_DECLARATION =
- const ParserErrorCode('FACTORY_TOP_LEVEL_DECLARATION',
- "Top-level declarations cannot be declared to be 'factory'");
-
- static const ParserErrorCode FACTORY_WITH_INITIALIZERS =
const ParserErrorCode(
- 'FACTORY_WITH_INITIALIZERS',
- "A 'factory' constructor cannot have initializers",
- "Either remove the 'factory' keyword to make this a generative "
- "constructor or remove the initializers.");
+ 'FACTORY_TOP_LEVEL_DECLARATION',
+ "Top-level declarations can't be declared to be 'factory'.",
+ "Try removing the keyword 'factory'.");
+
+ static const ParserErrorCode FACTORY_WITH_INITIALIZERS = const ParserErrorCode(
+ 'FACTORY_WITH_INITIALIZERS',
+ "A 'factory' constructor can't have initializers.",
+ "Try removing the 'factory' keyword to make this a generative constructor, or "
+ "removing the initializers.");
static const ParserErrorCode FACTORY_WITHOUT_BODY = const ParserErrorCode(
'FACTORY_WITHOUT_BODY',
- "A non-redirecting 'factory' constructor must have a body");
+ "A non-redirecting 'factory' constructor must have a body.",
+ "Try adding a body to the constructor.");
static const ParserErrorCode FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR =
- const ParserErrorCode('FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR',
- "Field initializers can only be used in a constructor");
+ const ParserErrorCode(
+ 'FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR',
+ "Field formal parameters can only be used in a constructor.",
+ "Try replacing the field formal parameter with a normal parameter.");
static const ParserErrorCode FINAL_AND_VAR = const ParserErrorCode(
'FINAL_AND_VAR',
- "Members cannot be declared to be both 'final' and 'var'");
+ "Members can't be declared to be both 'final' and 'var'.",
+ "Try removing the keyword 'var'.");
static const ParserErrorCode FINAL_CLASS = const ParserErrorCode(
- 'FINAL_CLASS', "Classes cannot be declared to be 'final'");
+ 'FINAL_CLASS',
+ "Classes can't be declared to be 'final'.",
+ "Try removing the keyword 'final'.");
static const ParserErrorCode FINAL_CONSTRUCTOR = const ParserErrorCode(
- 'FINAL_CONSTRUCTOR', "A constructor cannot be declared to be 'final'");
+ 'FINAL_CONSTRUCTOR',
+ "A constructor can't be declared to be 'final'.",
+ "Try removing the keyword 'final'.");
static const ParserErrorCode FINAL_ENUM = const ParserErrorCode(
- 'FINAL_ENUM', "Enums cannot be declared to be 'final'");
+ 'FINAL_ENUM',
+ "Enums can't be declared to be 'final'.",
+ "Try removing the keyword 'final'.");
static const ParserErrorCode FINAL_METHOD = const ParserErrorCode(
'FINAL_METHOD',
- "Getters, setters and methods cannot be declared to be 'final'");
+ "Getters, setters and methods can't be declared to be 'final'.",
+ "Try removing the keyword 'final'.");
static const ParserErrorCode FINAL_TYPEDEF = const ParserErrorCode(
- 'FINAL_TYPEDEF', "Type aliases cannot be declared to be 'final'");
+ 'FINAL_TYPEDEF',
+ "Typedefs can't be declared to be 'final'.",
+ "Try removing the keyword 'final'.");
static const ParserErrorCode FUNCTION_TYPED_PARAMETER_VAR = const ParserErrorCode(
'FUNCTION_TYPED_PARAMETER_VAR',
- "Function typed parameters cannot specify 'const', 'final' or 'var' instead of return type");
+ "Function-typed parameters can't specify 'const', 'final' or 'var' in place of a return type.",
+ "Try replacing the keyword with a return type.");
static const ParserErrorCode GETTER_IN_FUNCTION = const ParserErrorCode(
'GETTER_IN_FUNCTION',
- "Getters cannot be defined within methods or functions");
+ "Getters can't be defined within methods or functions.",
+ "Try moving the getter outside the method or function, or "
+ "converting the getter to a function.");
static const ParserErrorCode GETTER_WITH_PARAMETERS = const ParserErrorCode(
'GETTER_WITH_PARAMETERS',
- "Getter should be declared without a parameter list");
+ "Getters must be declared without a parameter list.",
+ "Try removing the parameter list, or "
+ "removing the keyword 'get' to define a method rather than a getter.");
static const ParserErrorCode ILLEGAL_ASSIGNMENT_TO_NON_ASSIGNABLE =
const ParserErrorCode('ILLEGAL_ASSIGNMENT_TO_NON_ASSIGNABLE',
- "Illegal assignment to non-assignable expression");
+ "Illegal assignment to non-assignable expression.");
static const ParserErrorCode IMPLEMENTS_BEFORE_EXTENDS =
- const ParserErrorCode('IMPLEMENTS_BEFORE_EXTENDS',
- "The extends clause must be before the implements clause");
+ const ParserErrorCode(
+ 'IMPLEMENTS_BEFORE_EXTENDS',
+ "The extends clause must be before the implements clause.",
+ "Try moving the extends clause before the implements clause.");
static const ParserErrorCode IMPLEMENTS_BEFORE_WITH = const ParserErrorCode(
'IMPLEMENTS_BEFORE_WITH',
- "The with clause must be before the implements clause");
+ "The with clause must be before the implements clause.",
+ "Try moving the with clause before the implements clause.");
static const ParserErrorCode IMPORT_DIRECTIVE_AFTER_PART_DIRECTIVE =
- const ParserErrorCode('IMPORT_DIRECTIVE_AFTER_PART_DIRECTIVE',
- "Import directives must preceed part directives");
+ const ParserErrorCode(
+ 'IMPORT_DIRECTIVE_AFTER_PART_DIRECTIVE',
+ "Import directives must preceed part directives.",
+ "Try moving the import directives before the part directives.");
static const ParserErrorCode INITIALIZED_VARIABLE_IN_FOR_EACH =
- const ParserErrorCode('INITIALIZED_VARIABLE_IN_FOR_EACH',
- "The loop variable in a for-each loop cannot be initialized");
+ const ParserErrorCode(
+ 'INITIALIZED_VARIABLE_IN_FOR_EACH',
+ "The loop variable in a for-each loop can't be initialized.",
+ "Try removing the initializer, or using a different kind of loop.");
static const ParserErrorCode INVALID_AWAIT_IN_FOR = const ParserErrorCode(
'INVALID_AWAIT_IN_FOR',
- "The modifier 'await' is not allowed for a normal 'for' statement",
- "Remove the keyword or use a for-each statement.");
+ "The keyword 'await' isn't allowed for a normal 'for' statement.",
+ "Try removing the keyword, or use a for-each statement.");
+ /**
+ * Parameters:
+ * 0: the invalid escape sequence
+ */
static const ParserErrorCode INVALID_CODE_POINT = const ParserErrorCode(
'INVALID_CODE_POINT',
- "The escape sequence '{0}' is not a valid code point");
+ "The escape sequence '{0}' isn't a valid code point.");
static const ParserErrorCode INVALID_COMMENT_REFERENCE = const ParserErrorCode(
'INVALID_COMMENT_REFERENCE',
- "Comment references should contain a possibly prefixed identifier and can start with 'new', but should not contain anything else");
+ "Comment references should contain a possibly prefixed identifier and "
+ "can start with 'new', but shouldn't contain anything else.");
static const ParserErrorCode INVALID_HEX_ESCAPE = const ParserErrorCode(
'INVALID_HEX_ESCAPE',
- "An escape sequence starting with '\\x' must be followed by 2 hexidecimal digits");
+ "An escape sequence starting with '\\x' must be followed by 2 hexidecimal digits.");
static const ParserErrorCode INVALID_LITERAL_IN_CONFIGURATION =
- const ParserErrorCode('INVALID_LITERAL_IN_CONFIGURATION',
- "The literal in a configuration cannot contain interpolation");
+ const ParserErrorCode(
+ 'INVALID_LITERAL_IN_CONFIGURATION',
+ "The literal in a configuration can't contain interpolation.",
+ "Try removing the interpolation expressions.");
+ /**
+ * Parameters:
+ * 0: the operator that is invalid
+ */
static const ParserErrorCode INVALID_OPERATOR = const ParserErrorCode(
- 'INVALID_OPERATOR', "The string '{0}' is not a valid operator");
+ 'INVALID_OPERATOR', "The string '{0}' isn't a user-definable operator.");
+ /**
+ * Parameters:
+ * 0: the operator being applied to 'super'
+ */
static const ParserErrorCode INVALID_OPERATOR_FOR_SUPER =
const ParserErrorCode('INVALID_OPERATOR_FOR_SUPER',
- "The operator '{0}' cannot be used with 'super'");
+ "The operator '{0}' can't be used with 'super'.");
static const ParserErrorCode INVALID_STAR_AFTER_ASYNC = const ParserErrorCode(
'INVALID_STAR_AFTER_ASYNC',
- "The modifier 'async*' is not allowed for an expression function body",
- "Convert the body to a block.");
+ "The modifier 'async*' isn't allowed for an expression function body.",
+ "Try converting the body to a block.");
static const ParserErrorCode INVALID_SYNC = const ParserErrorCode(
'INVALID_SYNC',
- "The modifier 'sync' is not allowed for an exrpression function body",
- "Convert the body to a block.");
+ "The modifier 'sync' isn't allowed for an exrpression function body.",
+ "Try converting the body to a block.");
static const ParserErrorCode INVALID_UNICODE_ESCAPE = const ParserErrorCode(
'INVALID_UNICODE_ESCAPE',
- "An escape sequence starting with '\\u' must be followed by 4 hexidecimal digits or from 1 to 6 digits between '{' and '}'");
+ "An escape sequence starting with '\\u' must be followed by 4 "
+ "hexidecimal digits or from 1 to 6 digits between '{' and '}'.");
static const ParserErrorCode LIBRARY_DIRECTIVE_NOT_FIRST =
- const ParserErrorCode('LIBRARY_DIRECTIVE_NOT_FIRST',
- "The library directive must appear before all other directives");
+ const ParserErrorCode(
+ 'LIBRARY_DIRECTIVE_NOT_FIRST',
+ "The library directive must appear before all other directives.",
+ "Try moving the library directive before any other directives.");
static const ParserErrorCode LOCAL_FUNCTION_DECLARATION_MODIFIER =
- const ParserErrorCode('LOCAL_FUNCTION_DECLARATION_MODIFIER',
- "Local function declarations cannot specify any modifier");
+ const ParserErrorCode(
+ 'LOCAL_FUNCTION_DECLARATION_MODIFIER',
+ "Local function declarations can't specify any modifiers.",
+ "Try removing the modifier.");
static const ParserErrorCode MISSING_ASSIGNABLE_SELECTOR =
- const ParserErrorCode('MISSING_ASSIGNABLE_SELECTOR',
- "Missing selector such as \".<identifier>\" or \"[0]\"");
+ const ParserErrorCode(
+ 'MISSING_ASSIGNABLE_SELECTOR',
+ "Missing selector such as '.<identifier>' or '[0]'.",
+ "Try adding a selector.");
static const ParserErrorCode MISSING_ASSIGNMENT_IN_INITIALIZER =
- const ParserErrorCode('MISSING_ASSIGNMENT_IN_INITIALIZER',
- "Expected an assignment after the field name");
+ const ParserErrorCode(
+ 'MISSING_ASSIGNMENT_IN_INITIALIZER',
+ "Expected an assignment after the field name.",
+ "Try adding an assignment to initialize the field.");
static const ParserErrorCode MISSING_CATCH_OR_FINALLY = const ParserErrorCode(
'MISSING_CATCH_OR_FINALLY',
- "A try statement must have either a catch or finally clause");
+ "A try statement must have either a catch or finally clause.",
+ "Try adding either a catch or finally clause, or "
+ "remove the try statement.");
static const ParserErrorCode MISSING_CLASS_BODY = const ParserErrorCode(
'MISSING_CLASS_BODY',
- "A class definition must have a body, even if it is empty");
+ "A class definition must have a body, even if it is empty.",
+ "Try adding a class body.");
static const ParserErrorCode MISSING_CLOSING_PARENTHESIS =
const ParserErrorCode(
- 'MISSING_CLOSING_PARENTHESIS', "The closing parenthesis is missing");
+ 'MISSING_CLOSING_PARENTHESIS',
+ "The closing parenthesis is missing.",
+ "Try adding the closing parenthesis.");
- static const ParserErrorCode MISSING_CONST_FINAL_VAR_OR_TYPE =
- const ParserErrorCode('MISSING_CONST_FINAL_VAR_OR_TYPE',
- "Variables must be declared using the keywords 'const', 'final', 'var' or a type name");
+ static const ParserErrorCode MISSING_CONST_FINAL_VAR_OR_TYPE = const ParserErrorCode(
+ 'MISSING_CONST_FINAL_VAR_OR_TYPE',
+ "Variables must be declared using the keywords 'const', 'final', 'var' or a type name.",
+ "Try adding the name of the type of the variable or the keyword 'var'.");
static const ParserErrorCode MISSING_ENUM_BODY = const ParserErrorCode(
'MISSING_ENUM_BODY',
- "An enum definition must have a body with at least one constant name");
+ "An enum definition must have a body with at least one constant name.",
+ "Try adding a body and defining at least one constant.");
static const ParserErrorCode MISSING_EXPRESSION_IN_INITIALIZER =
- const ParserErrorCode('MISSING_EXPRESSION_IN_INITIALIZER',
- "Expected an expression after the assignment operator");
+ const ParserErrorCode(
+ 'MISSING_EXPRESSION_IN_INITIALIZER',
+ "Expected an expression after the assignment operator.",
+ "Try adding the value to be assigned, or "
+ "remove the assignment operator.");
static const ParserErrorCode MISSING_EXPRESSION_IN_THROW =
- const ParserErrorCode('MISSING_EXPRESSION_IN_THROW',
- "Missing expression after 'throw'.", "Did you mean 'rethrow'?");
+ const ParserErrorCode(
+ 'MISSING_EXPRESSION_IN_THROW',
+ "Missing expression after 'throw'.",
+ "Try using 'rethrow' to throw the caught exception.");
static const ParserErrorCode MISSING_FUNCTION_BODY = const ParserErrorCode(
- 'MISSING_FUNCTION_BODY', "A function body must be provided");
+ 'MISSING_FUNCTION_BODY',
+ "A function body must be provided.",
+ "Try adding a function body.");
static const ParserErrorCode MISSING_FUNCTION_PARAMETERS =
- const ParserErrorCode('MISSING_FUNCTION_PARAMETERS',
- "Functions must have an explicit list of parameters");
+ const ParserErrorCode(
+ 'MISSING_FUNCTION_PARAMETERS',
+ "Functions must have an explicit list of parameters.",
+ "Try adding a parameter list.");
static const ParserErrorCode MISSING_METHOD_PARAMETERS =
- const ParserErrorCode('MISSING_METHOD_PARAMETERS',
- "Methods must have an explicit list of parameters");
+ const ParserErrorCode(
+ 'MISSING_METHOD_PARAMETERS',
+ "Methods must have an explicit list of parameters.",
+ "Try adding a parameter list.");
static const ParserErrorCode MISSING_GET = const ParserErrorCode(
'MISSING_GET',
- "Getters must have the keyword 'get' before the getter name");
+ "Getters must have the keyword 'get' before the getter name.",
+ "Try adding the keyword 'get'.");
static const ParserErrorCode MISSING_IDENTIFIER =
- const ParserErrorCode('MISSING_IDENTIFIER', "Expected an identifier");
+ const ParserErrorCode('MISSING_IDENTIFIER', "Expected an identifier.");
static const ParserErrorCode MISSING_INITIALIZER =
- const ParserErrorCode('MISSING_INITIALIZER', "Expected an initializer");
+ const ParserErrorCode('MISSING_INITIALIZER', "Expected an initializer.");
static const ParserErrorCode MISSING_KEYWORD_OPERATOR = const ParserErrorCode(
'MISSING_KEYWORD_OPERATOR',
- "Operator declarations must be preceeded by the keyword 'operator'");
+ "Operator declarations must be preceeded by the keyword 'operator'.",
+ "Try adding the keyword 'operator'.");
static const ParserErrorCode MISSING_NAME_IN_LIBRARY_DIRECTIVE =
- const ParserErrorCode('MISSING_NAME_IN_LIBRARY_DIRECTIVE',
- "Library directives must include a library name");
+ const ParserErrorCode(
+ 'MISSING_NAME_IN_LIBRARY_DIRECTIVE',
+ "Library directives must include a library name.",
+ "Try adding a library name after the keyword 'library', or "
+ "remove the library directive if the library doesn't have any parts.");
static const ParserErrorCode MISSING_NAME_IN_PART_OF_DIRECTIVE =
- const ParserErrorCode('MISSING_NAME_IN_PART_OF_DIRECTIVE',
- "Library directives must include a library name");
+ const ParserErrorCode(
+ 'MISSING_NAME_IN_PART_OF_DIRECTIVE',
+ "Part-of directives must include a library name.",
+ "Try adding a library name after the 'of'.");
static const ParserErrorCode MISSING_PREFIX_IN_DEFERRED_IMPORT =
- const ParserErrorCode('MISSING_PREFIX_IN_DEFERRED_IMPORT',
- "Deferred imports must have a prefix");
+ const ParserErrorCode(
+ 'MISSING_PREFIX_IN_DEFERRED_IMPORT',
+ "Deferred imports must have a prefix.",
+ "Try adding a prefix to the import.");
static const ParserErrorCode MISSING_STAR_AFTER_SYNC = const ParserErrorCode(
'MISSING_STAR_AFTER_SYNC',
- "The modifier 'sync' must be followed by a star ('*')",
- "Remove the modifier or add a star.");
+ "The modifier 'sync' must be followed by a star ('*').",
+ "Try removing the modifier, or add a star.");
static const ParserErrorCode MISSING_STATEMENT =
- const ParserErrorCode('MISSING_STATEMENT', "Expected a statement");
+ const ParserErrorCode('MISSING_STATEMENT', "Expected a statement.");
+ /**
+ * Parameters:
+ * 0: the terminator that is missing
+ */
static const ParserErrorCode MISSING_TERMINATOR_FOR_PARAMETER_GROUP =
- const ParserErrorCode('MISSING_TERMINATOR_FOR_PARAMETER_GROUP',
- "There is no '{0}' to close the parameter group");
+ const ParserErrorCode(
+ 'MISSING_TERMINATOR_FOR_PARAMETER_GROUP',
+ "There is no '{0}' to close the parameter group.",
+ "Try inserting a '{0}' at the end of the group.");
static const ParserErrorCode MISSING_TYPEDEF_PARAMETERS =
- const ParserErrorCode('MISSING_TYPEDEF_PARAMETERS',
- "Type aliases for functions must have an explicit list of parameters");
+ const ParserErrorCode(
+ 'MISSING_TYPEDEF_PARAMETERS',
+ "Typedefs must have an explicit list of parameters.",
+ "Try adding a parameter list.");
static const ParserErrorCode MISSING_VARIABLE_IN_FOR_EACH = const ParserErrorCode(
'MISSING_VARIABLE_IN_FOR_EACH',
- "A loop variable must be declared in a for-each loop before the 'in', but none were found");
+ "A loop variable must be declared in a for-each loop before the 'in', but none was found.",
+ "Try declaring a loop variable.");
static const ParserErrorCode MIXED_PARAMETER_GROUPS = const ParserErrorCode(
'MIXED_PARAMETER_GROUPS',
- "Cannot have both positional and named parameters in a single parameter list");
+ "Can't have both positional and named parameters in a single parameter list.",
+ "Try choosing a single style of optional parameters.");
static const ParserErrorCode MULTIPLE_EXTENDS_CLAUSES = const ParserErrorCode(
'MULTIPLE_EXTENDS_CLAUSES',
- "Each class definition can have at most one extends clause");
+ "Each class definition can have at most one extends clause.",
+ "Try choosing one superclass and define your class to implement (or mix in) the others.");
static const ParserErrorCode MULTIPLE_IMPLEMENTS_CLAUSES =
- const ParserErrorCode('MULTIPLE_IMPLEMENTS_CLAUSES',
- "Each class definition can have at most one implements clause");
+ const ParserErrorCode(
+ 'MULTIPLE_IMPLEMENTS_CLAUSES',
+ "Each class definition can have at most one implements clause.",
+ "Try combining all of the implements clauses into a single clause.");
static const ParserErrorCode MULTIPLE_LIBRARY_DIRECTIVES =
- const ParserErrorCode('MULTIPLE_LIBRARY_DIRECTIVES',
- "Only one library directive may be declared in a file");
+ const ParserErrorCode(
+ 'MULTIPLE_LIBRARY_DIRECTIVES',
+ "Only one library directive may be declared in a file.",
+ "Try removing all but one of the library directives.");
static const ParserErrorCode MULTIPLE_NAMED_PARAMETER_GROUPS =
- const ParserErrorCode('MULTIPLE_NAMED_PARAMETER_GROUPS',
- "Cannot have multiple groups of named parameters in a single parameter list");
+ const ParserErrorCode(
+ 'MULTIPLE_NAMED_PARAMETER_GROUPS',
+ "Can't have multiple groups of named parameters in a single parameter list.",
+ "Try combining all of the groups into a single group.");
static const ParserErrorCode MULTIPLE_PART_OF_DIRECTIVES =
- const ParserErrorCode('MULTIPLE_PART_OF_DIRECTIVES',
- "Only one part-of directive may be declared in a file");
+ const ParserErrorCode(
+ 'MULTIPLE_PART_OF_DIRECTIVES',
+ "Only one part-of directive may be declared in a file.",
+ "Try removing all but one of the part-of directives.");
static const ParserErrorCode MULTIPLE_POSITIONAL_PARAMETER_GROUPS =
- const ParserErrorCode('MULTIPLE_POSITIONAL_PARAMETER_GROUPS',
- "Cannot have multiple groups of positional parameters in a single parameter list");
+ const ParserErrorCode(
+ 'MULTIPLE_POSITIONAL_PARAMETER_GROUPS',
+ "Can't have multiple groups of positional parameters in a single parameter list.",
+ "Try combining all of the groups into a single group.");
+ /**
+ * Parameters:
+ * 0: the number of variables being declared
+ */
static const ParserErrorCode MULTIPLE_VARIABLES_IN_FOR_EACH =
- const ParserErrorCode('MULTIPLE_VARIABLES_IN_FOR_EACH',
- "A single loop variable must be declared in a for-each loop before the 'in', but {0} were found");
+ const ParserErrorCode(
+ 'MULTIPLE_VARIABLES_IN_FOR_EACH',
+ "A single loop variable must be declared in a for-each loop before "
+ "the 'in', but {0} were found.",
+ "Try moving all but one of the declarations inside the loop body.");
static const ParserErrorCode MULTIPLE_WITH_CLAUSES = const ParserErrorCode(
'MULTIPLE_WITH_CLAUSES',
- "Each class definition can have at most one with clause");
+ "Each class definition can have at most one with clause.",
+ "Try combining all of the with clauses into a single clause.");
- static const ParserErrorCode NAMED_FUNCTION_EXPRESSION =
- const ParserErrorCode(
- 'NAMED_FUNCTION_EXPRESSION', "Function expressions cannot be named");
+ static const ParserErrorCode NAMED_FUNCTION_EXPRESSION = const ParserErrorCode(
+ 'NAMED_FUNCTION_EXPRESSION',
+ "Function expressions can't be named.",
+ "Try removing the name, or "
+ "moving the function expression to a function declaration statement.");
static const ParserErrorCode NAMED_PARAMETER_OUTSIDE_GROUP =
- const ParserErrorCode('NAMED_PARAMETER_OUTSIDE_GROUP',
- "Named parameters must be enclosed in curly braces ('{' and '}')");
+ const ParserErrorCode(
+ 'NAMED_PARAMETER_OUTSIDE_GROUP',
+ "Named parameters must be enclosed in curly braces ('{' and '}').",
+ "Try surrounding the named parameters in curly braces.");
static const ParserErrorCode NATIVE_CLAUSE_IN_NON_SDK_CODE =
- const ParserErrorCode('NATIVE_CLAUSE_IN_NON_SDK_CODE',
- "Native clause can only be used in the SDK and code that is loaded through native extensions");
+ const ParserErrorCode(
+ 'NATIVE_CLAUSE_IN_NON_SDK_CODE',
+ "Native clause can only be used in the SDK and code that is loaded "
+ "through native extensions.",
+ "Try removing the native clause.");
static const ParserErrorCode NATIVE_FUNCTION_BODY_IN_NON_SDK_CODE =
- const ParserErrorCode('NATIVE_FUNCTION_BODY_IN_NON_SDK_CODE',
- "Native functions can only be declared in the SDK and code that is loaded through native extensions");
+ const ParserErrorCode(
+ 'NATIVE_FUNCTION_BODY_IN_NON_SDK_CODE',
+ "Native functions can only be declared in the SDK and code that is "
+ "loaded through native extensions.",
+ "Try removing the word 'native'.");
static const ParserErrorCode NON_CONSTRUCTOR_FACTORY = const ParserErrorCode(
'NON_CONSTRUCTOR_FACTORY',
- "Only constructors can be declared to be a 'factory'");
+ "Only a constructor can be declared to be a factory.",
+ "Try removing the keyword 'factory'.");
static const ParserErrorCode NON_IDENTIFIER_LIBRARY_NAME =
- const ParserErrorCode('NON_IDENTIFIER_LIBRARY_NAME',
- "The name of a library must be an identifier");
+ const ParserErrorCode(
+ 'NON_IDENTIFIER_LIBRARY_NAME',
+ "The name of a library must be an identifier.",
+ "Try using an identifier as the name of the library.");
static const ParserErrorCode NON_PART_OF_DIRECTIVE_IN_PART =
- const ParserErrorCode('NON_PART_OF_DIRECTIVE_IN_PART',
- "The part-of directive must be the only directive in a part");
+ const ParserErrorCode(
+ 'NON_PART_OF_DIRECTIVE_IN_PART',
+ "The part-of directive must be the only directive in a part.",
+ "Try removing the other directives, or "
+ "moving them to the library for which this is a part.");
static const ParserErrorCode NON_STRING_LITERAL_AS_URI =
const ParserErrorCode(
'NON_STRING_LITERAL_AS_URI',
- "The URI must be a string literal",
- "Enclose the URI in either single or double quotes.");
+ "The URI must be a string literal.",
+ "Try enclosing the URI in either single or double quotes.");
+ /**
+ * Parameters:
+ * 0: the operator that the user is trying to define
+ */
static const ParserErrorCode NON_USER_DEFINABLE_OPERATOR =
const ParserErrorCode('NON_USER_DEFINABLE_OPERATOR',
- "The operator '{0}' is not user definable");
+ "The operator '{0}' isn't user definable.");
static const ParserErrorCode NORMAL_BEFORE_OPTIONAL_PARAMETERS =
- const ParserErrorCode('NORMAL_BEFORE_OPTIONAL_PARAMETERS',
- "Normal parameters must occur before optional parameters");
+ const ParserErrorCode(
+ 'NORMAL_BEFORE_OPTIONAL_PARAMETERS',
+ "Normal parameters must occur before optional parameters.",
+ "Try moving all of the normal parameters before the optional parameters.");
static const ParserErrorCode NULLABLE_TYPE_IN_EXTENDS = const ParserErrorCode(
'NULLABLE_TYPE_IN_EXTENDS',
- "A nullable type cannot be used in an extends clause",
- "Remove the '?' from the type name");
+ "A nullable type can't be used in an extends clause.",
+ "Try removing the '?' from the type name.");
static const ParserErrorCode NULLABLE_TYPE_IN_IMPLEMENTS =
const ParserErrorCode(
'NULLABLE_TYPE_IN_IMPLEMENTS',
- "A nullable type cannot be used in an implements clause",
- "Remove the '?' from the type name");
+ "A nullable type can't be used in an implements clause.",
+ "Try removing the '?' from the type name.");
static const ParserErrorCode NULLABLE_TYPE_IN_WITH = const ParserErrorCode(
'NULLABLE_TYPE_IN_WITH',
- "A nullable type cannot be used in a with clause",
- "Remove the '?' from the type name");
+ "A nullable type can't be used in a with clause.",
+ "Try removing the '?' from the type name.");
static const ParserErrorCode NULLABLE_TYPE_PARAMETER = const ParserErrorCode(
'NULLABLE_TYPE_PARAMETER',
- "Type parameters cannot be nullable",
- "Remove the '?' from the type name");
+ "Type parameters can't be nullable.",
+ "Try removing the '?' from the type name.");
static const ParserErrorCode POSITIONAL_AFTER_NAMED_ARGUMENT =
- const ParserErrorCode('POSITIONAL_AFTER_NAMED_ARGUMENT',
- "Positional arguments must occur before named arguments");
+ const ParserErrorCode(
+ 'POSITIONAL_AFTER_NAMED_ARGUMENT',
+ "Positional arguments must occur before named arguments.",
+ "Try moving all of the positional arguments before the named arguments.");
static const ParserErrorCode POSITIONAL_PARAMETER_OUTSIDE_GROUP =
- const ParserErrorCode('POSITIONAL_PARAMETER_OUTSIDE_GROUP',
- "Positional parameters must be enclosed in square brackets ('[' and ']')");
+ const ParserErrorCode(
+ 'POSITIONAL_PARAMETER_OUTSIDE_GROUP',
+ "Positional parameters must be enclosed in square brackets ('[' and ']').",
+ "Try surrounding the positional parameters in square brackets.");
static const ParserErrorCode REDIRECTING_CONSTRUCTOR_WITH_BODY =
- const ParserErrorCode('REDIRECTING_CONSTRUCTOR_WITH_BODY',
- "Redirecting constructors cannot have a body");
+ const ParserErrorCode(
+ 'REDIRECTING_CONSTRUCTOR_WITH_BODY',
+ "Redirecting constructors can't have a body.",
+ "Try removing the body, or "
+ "not making this a redirecting constructor.");
static const ParserErrorCode REDIRECTION_IN_NON_FACTORY_CONSTRUCTOR =
- const ParserErrorCode('REDIRECTION_IN_NON_FACTORY_CONSTRUCTOR',
- "Only factory constructor can specify '=' redirection.");
+ const ParserErrorCode(
+ 'REDIRECTION_IN_NON_FACTORY_CONSTRUCTOR',
+ "Only factory constructor can specify '=' redirection.",
+ "Try making this a factory constructor, or "
+ "not making this a redirecting constructor.");
static const ParserErrorCode SETTER_IN_FUNCTION = const ParserErrorCode(
'SETTER_IN_FUNCTION',
- "Setters cannot be defined within methods or functions");
+ "Setters can't be defined within methods or functions.",
+ "Try moving the setter outside the method or function.");
static const ParserErrorCode STATIC_AFTER_CONST = const ParserErrorCode(
'STATIC_AFTER_CONST',
- "The modifier 'static' should be before the modifier 'const'");
+ "The modifier 'static' should be before the modifier 'const'.",
+ "Try re-ordering the modifiers.");
static const ParserErrorCode STATIC_AFTER_FINAL = const ParserErrorCode(
'STATIC_AFTER_FINAL',
- "The modifier 'static' should be before the modifier 'final'");
+ "The modifier 'static' should be before the modifier 'final'.",
+ "Try re-ordering the modifiers.");
static const ParserErrorCode STATIC_AFTER_VAR = const ParserErrorCode(
'STATIC_AFTER_VAR',
- "The modifier 'static' should be before the modifier 'var'");
+ "The modifier 'static' should be before the modifier 'var'.",
+ "Try re-ordering the modifiers.");
static const ParserErrorCode STATIC_CONSTRUCTOR = const ParserErrorCode(
- 'STATIC_CONSTRUCTOR', "Constructors cannot be static");
+ 'STATIC_CONSTRUCTOR',
+ "Constructors can't be static.",
+ "Try removing the keyword 'static'.");
static const ParserErrorCode STATIC_GETTER_WITHOUT_BODY =
const ParserErrorCode(
- 'STATIC_GETTER_WITHOUT_BODY', "A 'static' getter must have a body");
+ 'STATIC_GETTER_WITHOUT_BODY',
+ "A 'static' getter must have a body.",
+ "Try adding a body to the getter, or removing the keyword 'static'.");
- static const ParserErrorCode STATIC_OPERATOR =
- const ParserErrorCode('STATIC_OPERATOR', "Operators cannot be static");
+ static const ParserErrorCode STATIC_OPERATOR = const ParserErrorCode(
+ 'STATIC_OPERATOR',
+ "Operators can't be static.",
+ "Try removing the keyword 'static'.");
static const ParserErrorCode STATIC_SETTER_WITHOUT_BODY =
const ParserErrorCode(
- 'STATIC_SETTER_WITHOUT_BODY', "A 'static' setter must have a body");
+ 'STATIC_SETTER_WITHOUT_BODY',
+ "A 'static' setter must have a body.",
+ "Try adding a body to the setter, or removing the keyword 'static'.");
static const ParserErrorCode STATIC_TOP_LEVEL_DECLARATION =
- const ParserErrorCode('STATIC_TOP_LEVEL_DECLARATION',
- "Top-level declarations cannot be declared to be 'static'");
+ const ParserErrorCode(
+ 'STATIC_TOP_LEVEL_DECLARATION',
+ "Top-level declarations can't be declared to be static.",
+ "Try removing the keyword 'static'.");
static const ParserErrorCode SWITCH_HAS_CASE_AFTER_DEFAULT_CASE =
- const ParserErrorCode('SWITCH_HAS_CASE_AFTER_DEFAULT_CASE',
- "The 'default' case should be the last case in a switch statement");
+ const ParserErrorCode(
+ 'SWITCH_HAS_CASE_AFTER_DEFAULT_CASE',
+ "The default case should be the last case in a switch statement.",
+ "Try moving the default case after the other case clauses.");
static const ParserErrorCode SWITCH_HAS_MULTIPLE_DEFAULT_CASES =
- const ParserErrorCode('SWITCH_HAS_MULTIPLE_DEFAULT_CASES',
- "The 'default' case can only be declared once");
+ const ParserErrorCode(
+ 'SWITCH_HAS_MULTIPLE_DEFAULT_CASES',
+ "The 'default' case can only be declared once.",
+ "Try removing all but one default case.");
static const ParserErrorCode TOP_LEVEL_OPERATOR = const ParserErrorCode(
- 'TOP_LEVEL_OPERATOR', "Operators must be declared within a class");
+ 'TOP_LEVEL_OPERATOR',
+ "Operators must be declared within a class.",
+ "Try removing the operator, "
+ "moving it to a class, or "
+ "converting it to be a function.");
static const ParserErrorCode TYPEDEF_IN_CLASS = const ParserErrorCode(
'TYPEDEF_IN_CLASS',
- "Function type aliases cannot be declared inside classes");
+ "Typedefs can't be declared inside classes.",
+ "Try moving the typedef to the top-level.");
+ /**
+ * Parameters:
+ * 0: the starting character that was missing
+ */
static const ParserErrorCode UNEXPECTED_TERMINATOR_FOR_PARAMETER_GROUP =
- const ParserErrorCode('UNEXPECTED_TERMINATOR_FOR_PARAMETER_GROUP',
- "There is no '{0}' to open a parameter group");
+ const ParserErrorCode(
+ 'UNEXPECTED_TERMINATOR_FOR_PARAMETER_GROUP',
+ "There is no '{0}' to open a parameter group.",
+ "Try inserting the '{0}' at the appropriate location.");
- static const ParserErrorCode UNEXPECTED_TOKEN =
- const ParserErrorCode('UNEXPECTED_TOKEN', "Unexpected token '{0}'");
+ /**
+ * Parameters:
+ * 0: the unexpected text that was found
+ */
+ static const ParserErrorCode UNEXPECTED_TOKEN = const ParserErrorCode(
+ 'UNEXPECTED_TOKEN', "Unexpected text '{0}'.", "Try removing the text.");
static const ParserErrorCode WITH_BEFORE_EXTENDS = const ParserErrorCode(
'WITH_BEFORE_EXTENDS',
- "The extends clause must be before the with clause");
+ "The extends clause must be before the with clause.",
+ "Try moving the extends clause before the with clause.");
static const ParserErrorCode WITH_WITHOUT_EXTENDS = const ParserErrorCode(
'WITH_WITHOUT_EXTENDS',
- "The with clause cannot be used without an extends clause");
+ "The with clause can't be used without an extends clause.",
+ "Try adding an extends clause such as 'extends Object'.");
static const ParserErrorCode WRONG_SEPARATOR_FOR_POSITIONAL_PARAMETER =
- const ParserErrorCode('WRONG_SEPARATOR_FOR_POSITIONAL_PARAMETER',
- "The default value of a positional parameter should be preceeded by '='");
+ const ParserErrorCode(
+ 'WRONG_SEPARATOR_FOR_POSITIONAL_PARAMETER',
+ "The default value of a positional parameter should be preceeded by '='.",
+ "Try replacing the ':' with '='.");
+ /**
+ * Parameters:
+ * 0: the terminator that was expected
+ * 1: the terminator that was found
+ */
static const ParserErrorCode WRONG_TERMINATOR_FOR_PARAMETER_GROUP =
- const ParserErrorCode('WRONG_TERMINATOR_FOR_PARAMETER_GROUP',
- "Expected '{0}' to close parameter group");
+ const ParserErrorCode(
+ 'WRONG_TERMINATOR_FOR_PARAMETER_GROUP',
+ "Expected '{0}' to close parameter group.",
+ "Try replacing '{0}' with '{1}'.");
static const ParserErrorCode VAR_AND_TYPE = const ParserErrorCode(
'VAR_AND_TYPE',
- "Variables cannot be declared using both 'var' and a type name; remove the 'var'");
+ "Variables can't be declared using both 'var' and a type name.",
+ "Try removing the keyword 'var'.");
static const ParserErrorCode VAR_AS_TYPE_NAME = const ParserErrorCode(
- 'VAR_AS_TYPE_NAME', "The keyword 'var' cannot be used as a type name");
+ 'VAR_AS_TYPE_NAME',
+ "The keyword 'var' can't be used as a type name.",
+ "Try using 'dynamic' instead of 'var'.");
static const ParserErrorCode VAR_CLASS = const ParserErrorCode(
- 'VAR_CLASS', "Classes cannot be declared to be 'var'");
+ 'VAR_CLASS',
+ "Classes can't be declared to be 'var'.",
+ "Try removing the keyword 'var'.");
- static const ParserErrorCode VAR_ENUM =
- const ParserErrorCode('VAR_ENUM', "Enums cannot be declared to be 'var'");
+ static const ParserErrorCode VAR_ENUM = const ParserErrorCode(
+ 'VAR_ENUM',
+ "Enums can't be declared to be 'var'.",
+ "Try removing the keyword 'var'.");
static const ParserErrorCode VAR_RETURN_TYPE = const ParserErrorCode(
- 'VAR_RETURN_TYPE', "The return type cannot be 'var'");
+ 'VAR_RETURN_TYPE',
+ "The return type can't be 'var'.",
+ "Try removing the keyword 'var', or "
+ "replacing it with the name of the return type.");
static const ParserErrorCode VAR_TYPEDEF = const ParserErrorCode(
- 'VAR_TYPEDEF', "Type aliases cannot be declared to be 'var'");
+ 'VAR_TYPEDEF',
+ "Typedefs can't be declared to be 'var'.",
+ "Try removing the keyword 'var', or "
+ "replacing it with the name of the return type.");
static const ParserErrorCode VOID_PARAMETER = const ParserErrorCode(
- 'VOID_PARAMETER', "Parameters cannot have a type of 'void'");
+ 'VOID_PARAMETER',
+ "Parameters can't have a type of 'void'.",
+ "Try removing the keyword 'var', or "
+ "replacing it with the name of the type of the parameter.");
static const ParserErrorCode VOID_VARIABLE = const ParserErrorCode(
- 'VOID_VARIABLE', "Variables cannot have a type of 'void'");
+ 'VOID_VARIABLE',
+ "Variables can't have a type of 'void'.",
+ "Try removing the keyword 'void', or "
+ "replacing it with the name of the type of the variable.");
/**
* Initialize a newly created error code to have the given [name]. The message
@@ -667,28 +944,39 @@
* The error codes used for errors detected by the scanner.
*/
class ScannerErrorCode extends ErrorCode {
+ /**
+ * Parameters:
+ * 0: the illegal character
+ */
static const ScannerErrorCode ILLEGAL_CHARACTER =
- const ScannerErrorCode('ILLEGAL_CHARACTER', "Illegal character {0}");
+ const ScannerErrorCode('ILLEGAL_CHARACTER', "Illegal character '{0}'.");
static const ScannerErrorCode MISSING_DIGIT =
- const ScannerErrorCode('MISSING_DIGIT', "Decimal digit expected");
+ const ScannerErrorCode('MISSING_DIGIT', "Decimal digit expected.");
- static const ScannerErrorCode MISSING_HEX_DIGIT =
- const ScannerErrorCode('MISSING_HEX_DIGIT', "Hexidecimal digit expected");
+ static const ScannerErrorCode MISSING_HEX_DIGIT = const ScannerErrorCode(
+ 'MISSING_HEX_DIGIT', "Hexidecimal digit expected.");
static const ScannerErrorCode MISSING_QUOTE =
- const ScannerErrorCode('MISSING_QUOTE', "Expected quote (' or \")");
+ const ScannerErrorCode('MISSING_QUOTE', "Expected quote (' or \").");
+ /**
+ * Parameters:
+ * 0: the path of the file that cannot be read
+ */
static const ScannerErrorCode UNABLE_GET_CONTENT = const ScannerErrorCode(
- 'UNABLE_GET_CONTENT', "Unable to get content: {0}");
+ 'UNABLE_GET_CONTENT', "Unable to get content of '{0}'.");
static const ScannerErrorCode UNTERMINATED_MULTI_LINE_COMMENT =
const ScannerErrorCode(
- 'UNTERMINATED_MULTI_LINE_COMMENT', "Unterminated multi-line comment");
+ 'UNTERMINATED_MULTI_LINE_COMMENT',
+ "Unterminated multi-line comment.",
+ "Try terminating the comment with '*/', or "
+ "removing any unbalanced occurances of '/*' (because comments nest in Dart).");
static const ScannerErrorCode UNTERMINATED_STRING_LITERAL =
const ScannerErrorCode(
- 'UNTERMINATED_STRING_LITERAL', "Unterminated string literal");
+ 'UNTERMINATED_STRING_LITERAL', "Unterminated string literal.");
/**
* Initialize a newly created error code to have the given [name]. The message
diff --git a/pkg/analyzer/lib/src/error/codes.dart b/pkg/analyzer/lib/src/error/codes.dart
index 7d9eec5..812d030 100644
--- a/pkg/analyzer/lib/src/error/codes.dart
+++ b/pkg/analyzer/lib/src/error/codes.dart
@@ -54,8 +54,10 @@
* 2: legal values
*/
static const AnalysisOptionsWarningCode UNSUPPORTED_OPTION_WITH_LEGAL_VALUES =
- const AnalysisOptionsWarningCode('UNSUPPORTED_OPTION_WITH_LEGAL_VALUES',
- "The option '{1}' is not supported by {0}, supported values are {2}");
+ const AnalysisOptionsWarningCode(
+ 'UNSUPPORTED_OPTION_WITH_LEGAL_VALUES',
+ "The option '{1}' isn't supported by '{0}'.",
+ "Try using one of the supported options: {2}.");
/**
* An error code indicating that a plugin is being configured with an
@@ -67,8 +69,10 @@
* 2: the legal value
*/
static const AnalysisOptionsWarningCode UNSUPPORTED_OPTION_WITH_LEGAL_VALUE =
- const AnalysisOptionsWarningCode('UNSUPPORTED_OPTION_WITH_LEGAL_VALUE',
- "The option '{1}' is not supported by {0}, did you mean {2}?");
+ const AnalysisOptionsWarningCode(
+ 'UNSUPPORTED_OPTION_WITH_LEGAL_VALUE',
+ "The option '{1}' isn't supported by '{0}'."
+ "Try using the only supported option: '{2}'.");
/**
* An error code indicating that an option entry is being configured with an
@@ -80,8 +84,10 @@
* 2: legal values
*/
static const AnalysisOptionsWarningCode UNSUPPORTED_VALUE =
- const AnalysisOptionsWarningCode('UNSUPPORTED_VALUE',
- "The value '{1}' is not supported by {0}, legal values are {2}");
+ const AnalysisOptionsWarningCode(
+ 'UNSUPPORTED_VALUE',
+ "The value '{1}' isn't supported by '{0}'.",
+ "Try using one of the supported options: {2}.");
/**
* An error code indicating that an unrecognized error code is being used to
@@ -92,7 +98,7 @@
*/
static const AnalysisOptionsWarningCode UNRECOGNIZED_ERROR_CODE =
const AnalysisOptionsWarningCode(
- 'UNRECOGNIZED_ERROR_CODE', "'{0}' is not a recognized error code");
+ 'UNRECOGNIZED_ERROR_CODE', "'{0}' isn't a recognized error code.");
/**
* Initialize a newly created warning code to have the given [name].
@@ -125,31 +131,33 @@
// errors.
/**
- * 12.11.2 Const: It is a compile-time error if evaluation of a constant
+ * 16.12.2 Const: It is a compile-time error if evaluation of a constant
* object results in an uncaught exception being thrown.
*/
static const CheckedModeCompileTimeErrorCode
CONST_CONSTRUCTOR_FIELD_TYPE_MISMATCH =
const CheckedModeCompileTimeErrorCode(
'CONST_CONSTRUCTOR_FIELD_TYPE_MISMATCH',
- "The object type '{0}' cannot be assigned to the field '{1}', which has type '{2}'");
+ "A value of type '{0}' can't be assigned to the field '{1}', which "
+ "has type '{2}'.");
/**
- * 12.11.2 Const: It is a compile-time error if evaluation of a constant
+ * 16.12.2 Const: It is a compile-time error if evaluation of a constant
* object results in an uncaught exception being thrown.
*/
static const CheckedModeCompileTimeErrorCode
CONST_CONSTRUCTOR_PARAM_TYPE_MISMATCH =
const CheckedModeCompileTimeErrorCode(
'CONST_CONSTRUCTOR_PARAM_TYPE_MISMATCH',
- "The object type '{0}' cannot be assigned to a parameter of type '{1}'");
+ "A value of type '{0}' can't be assigned to a parameter of type "
+ "'{1}'.");
/**
* 7.6.1 Generative Constructors: In checked mode, it is a dynamic type error
* if o is not <b>null</b> and the interface of the class of <i>o</i> is not a
* subtype of the static type of the field <i>v</i>.
*
- * 12.11.2 Const: It is a compile-time error if evaluation of a constant
+ * 16.12.2 Const: It is a compile-time error if evaluation of a constant
* object results in an uncaught exception being thrown.
*
* Parameters:
@@ -160,7 +168,8 @@
CONST_FIELD_INITIALIZER_NOT_ASSIGNABLE =
const CheckedModeCompileTimeErrorCode(
'CONST_FIELD_INITIALIZER_NOT_ASSIGNABLE',
- "The initializer type '{0}' cannot be assigned to the field type '{1}'");
+ "The initializer type '{0}' can't be assigned to the field type "
+ "'{1}'.");
/**
* 12.6 Lists: A run-time list literal <<i>E</i>> [<i>e<sub>1</sub></i>
@@ -178,7 +187,7 @@
static const CheckedModeCompileTimeErrorCode
LIST_ELEMENT_TYPE_NOT_ASSIGNABLE = const CheckedModeCompileTimeErrorCode(
'LIST_ELEMENT_TYPE_NOT_ASSIGNABLE',
- "The element type '{0}' cannot be assigned to the list type '{1}'");
+ "The element type '{0}' can't be assigned to the list type '{1}'.");
/**
* 12.7 Map: A run-time map literal <<i>K</i>, <i>V</i>>
@@ -197,7 +206,7 @@
*/
static const CheckedModeCompileTimeErrorCode MAP_KEY_TYPE_NOT_ASSIGNABLE =
const CheckedModeCompileTimeErrorCode('MAP_KEY_TYPE_NOT_ASSIGNABLE',
- "The element type '{0}' cannot be assigned to the map key type '{1}'");
+ "The element type '{0}' can't be assigned to the map key type '{1}'.");
/**
* 12.7 Map: A run-time map literal <<i>K</i>, <i>V</i>>
@@ -215,16 +224,20 @@
* <= j <= m</i>.
*/
static const CheckedModeCompileTimeErrorCode MAP_VALUE_TYPE_NOT_ASSIGNABLE =
- const CheckedModeCompileTimeErrorCode('MAP_VALUE_TYPE_NOT_ASSIGNABLE',
- "The element type '{0}' cannot be assigned to the map value type '{1}'");
+ const CheckedModeCompileTimeErrorCode(
+ 'MAP_VALUE_TYPE_NOT_ASSIGNABLE',
+ "The element type '{0}' can't be assigned to the map value type "
+ "'{1}'.");
/**
- * 12.11.2 Const: It is a compile-time error if evaluation of a constant
+ * 16.12.2 Const: It is a compile-time error if evaluation of a constant
* object results in an uncaught exception being thrown.
*/
static const CheckedModeCompileTimeErrorCode VARIABLE_TYPE_MISMATCH =
- const CheckedModeCompileTimeErrorCode('VARIABLE_TYPE_MISMATCH',
- "The object type '{0}' cannot be assigned to a variable of type '{1}'");
+ const CheckedModeCompileTimeErrorCode(
+ 'VARIABLE_TYPE_MISMATCH',
+ "A value of type '{0}' can't be assigned to a variable of type "
+ "'{1}'.");
/**
* Initialize a newly created error code to have the given [name]. The message
@@ -256,8 +269,10 @@
* enum via 'new' or 'const' or to access its private fields.
*/
static const CompileTimeErrorCode ACCESS_PRIVATE_ENUM_FIELD =
- const CompileTimeErrorCode('ACCESS_PRIVATE_ENUM_FIELD',
- "The private fields of an enum cannot be accessed, even within the same library");
+ const CompileTimeErrorCode(
+ 'ACCESS_PRIVATE_ENUM_FIELD',
+ "The private fields of an enum can't be accessed, even within the "
+ "same library.");
/**
* 14.2 Exports: It is a compile-time error if a name <i>N</i> is re-exported
@@ -267,21 +282,24 @@
*
* Parameters:
* 0: the name of the ambiguous element
- * 1: the name of the first library that the type is found
- * 2: the name of the second library that the type is found
+ * 1: the name of the first library in which the type is found
+ * 2: the name of the second library in which the type is found
*/
static const CompileTimeErrorCode AMBIGUOUS_EXPORT =
- const CompileTimeErrorCode('AMBIGUOUS_EXPORT',
- "The name '{0}' is defined in the libraries '{1}' and '{2}'");
+ const CompileTimeErrorCode(
+ 'AMBIGUOUS_EXPORT',
+ "The name '{0}' is defined in the libraries '{1}' and '{2}'.",
+ "Try removing the export of one of the libraries, or "
+ "explicitly hiding the name in one of the export directives.");
/**
* 15 Metadata: The constant expression given in an annotation is type checked
* and evaluated in the scope surrounding the declaration being annotated.
*
- * 12.11.2 Const: It is a compile-time error if <i>T</i> is not a class
+ * 16.12.2 Const: It is a compile-time error if <i>T</i> is not a class
* accessible in the current scope, optionally followed by type arguments.
*
- * 12.11.2 Const: If <i>e</i> is of the form <i>const T.id(a<sub>1</sub>,
+ * 16.12.2 Const: If <i>e</i> is of the form <i>const T.id(a<sub>1</sub>,
* …, a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, …
* x<sub>n+k</sub>: a<sub>n+k</sub>)</i> it is a compile-time error if
* <i>T</i> is not a class accessible in the current scope, optionally
@@ -292,7 +310,11 @@
*/
static const CompileTimeErrorCode ANNOTATION_WITH_NON_CLASS =
const CompileTimeErrorCode(
- 'ANNOTATION_WITH_NON_CLASS', "The name '{0}' is not a class");
+ 'ANNOTATION_WITH_NON_CLASS',
+ "The name '{0}' isn't a class.",
+ "Try importing the library that declares the class, "
+ "correcting the name to match a defined class, or "
+ "defining a class with the given name.");
/**
* 12.33 Argument Definition Test: It is a compile time error if <i>v</i> does
@@ -304,151 +326,222 @@
*/
static const CompileTimeErrorCode ARGUMENT_DEFINITION_TEST_NON_PARAMETER =
const CompileTimeErrorCode(
- 'ARGUMENT_DEFINITION_TEST_NON_PARAMETER', "'{0}' is not a parameter");
+ 'ARGUMENT_DEFINITION_TEST_NON_PARAMETER', "'{0}' isn't a parameter.");
/**
- * ?? Asynchronous For-in: It is a compile-time error if an asynchronous
+ * 17.6.3 Asynchronous For-in: It is a compile-time error if an asynchronous
* for-in statement appears inside a synchronous function.
*/
static const CompileTimeErrorCode ASYNC_FOR_IN_WRONG_CONTEXT =
- const CompileTimeErrorCode('ASYNC_FOR_IN_WRONG_CONTEXT',
- "The asynchronous for-in can only be used in a function marked with async or async*");
+ const CompileTimeErrorCode(
+ 'ASYNC_FOR_IN_WRONG_CONTEXT',
+ "The asynchronous for-in can only be used in an asynchronous function.",
+ "Try marking the function body with either 'async' or 'async*', or "
+ "removing the 'await' before the for loop.");
/**
- * ??: It is a compile-time error if the function immediately enclosing a is
- * not declared asynchronous.
+ * 16.30 Await Expressions: It is a compile-time error if the function
+ * immediately enclosing _a_ is not declared asynchronous. (Where _a_ is the
+ * await expression.)
*/
static const CompileTimeErrorCode AWAIT_IN_WRONG_CONTEXT =
- const CompileTimeErrorCode('AWAIT_IN_WRONG_CONTEXT',
- "The await expression can only be used in a function marked as async or async*");
+ const CompileTimeErrorCode(
+ 'AWAIT_IN_WRONG_CONTEXT',
+ "The await expression can only be used in an asynchronous function.",
+ "Try marking the function body with either 'async' or 'async*'.");
/**
* 12.30 Identifier Reference: It is a compile-time error to use a built-in
* identifier other than dynamic as a type annotation.
+ *
+ * Parameters:
+ * 0: the built-in identifier that is being used
*/
static const CompileTimeErrorCode BUILT_IN_IDENTIFIER_AS_TYPE =
- const CompileTimeErrorCode('BUILT_IN_IDENTIFIER_AS_TYPE',
- "The built-in identifier '{0}' cannot be used as a type");
+ const CompileTimeErrorCode(
+ 'BUILT_IN_IDENTIFIER_AS_TYPE',
+ "The built-in identifier '{0}' can't be used as a type.",
+ "Try correcting the name to match an existing type.");
/**
* 12.30 Identifier Reference: It is a compile-time error if a built-in
* identifier is used as the declared name of a class, type parameter or type
* alias.
+ *
+ * Parameters:
+ * 0: the built-in identifier that is being used
*/
static const CompileTimeErrorCode BUILT_IN_IDENTIFIER_AS_TYPE_NAME =
- const CompileTimeErrorCode('BUILT_IN_IDENTIFIER_AS_TYPE_NAME',
- "The built-in identifier '{0}' cannot be used as a type name");
+ const CompileTimeErrorCode(
+ 'BUILT_IN_IDENTIFIER_AS_TYPE_NAME',
+ "The built-in identifier '{0}' can't be used as a type name.",
+ "Try choosing a different name for the type.");
/**
* 12.30 Identifier Reference: It is a compile-time error if a built-in
* identifier is used as the declared name of a class, type parameter or type
* alias.
+ *
+ * Parameters:
+ * 0: the built-in identifier that is being used
*/
static const CompileTimeErrorCode BUILT_IN_IDENTIFIER_AS_TYPEDEF_NAME =
- const CompileTimeErrorCode('BUILT_IN_IDENTIFIER_AS_TYPEDEF_NAME',
- "The built-in identifier '{0}' cannot be used as a type alias name");
+ const CompileTimeErrorCode(
+ 'BUILT_IN_IDENTIFIER_AS_TYPEDEF_NAME',
+ "The built-in identifier '{0}' can't be used as a typedef name.",
+ "Try choosing a different name for the typedef.");
/**
* 12.30 Identifier Reference: It is a compile-time error if a built-in
* identifier is used as the declared name of a class, type parameter or type
* alias.
+ *
+ * Parameters:
+ * 0: the built-in identifier that is being used
*/
static const CompileTimeErrorCode BUILT_IN_IDENTIFIER_AS_TYPE_PARAMETER_NAME =
- const CompileTimeErrorCode('BUILT_IN_IDENTIFIER_AS_TYPE_PARAMETER_NAME',
- "The built-in identifier '{0}' cannot be used as a type parameter name");
+ const CompileTimeErrorCode(
+ 'BUILT_IN_IDENTIFIER_AS_TYPE_PARAMETER_NAME',
+ "The built-in identifier '{0}' can't be used as a type parameter name.",
+ "Try choosing a different name for the type parameter.");
/**
* 13.9 Switch: It is a compile-time error if the class <i>C</i> implements
* the operator <i>==</i>.
+ *
+ * Parameters:
+ * 0: the this of the switch case expression
*/
static const CompileTimeErrorCode CASE_EXPRESSION_TYPE_IMPLEMENTS_EQUALS =
const CompileTimeErrorCode('CASE_EXPRESSION_TYPE_IMPLEMENTS_EQUALS',
- "The switch case expression type '{0}' cannot override the == operator");
-
- /**
- * 12.1 Constants: It is a compile-time error if evaluation of a compile-time
- * constant would raise
- * an exception.
- */
- static const CompileTimeErrorCode COMPILE_TIME_CONSTANT_RAISES_EXCEPTION =
- const CompileTimeErrorCode('COMPILE_TIME_CONSTANT_RAISES_EXCEPTION', "");
+ "The switch case expression type '{0}' can't override the == operator.");
/**
* 7.2 Getters: It is a compile-time error if a class has both a getter and a
* method with the same name. This restriction holds regardless of whether the
* getter is defined explicitly or implicitly, or whether the getter or the
* method are inherited or not.
+ *
+ * Parameters:
+ * 0: the name of the class defining the conflicting method
+ * 1: the name of the class defining the getter with which the method conflicts
+ * 2: the name of the conflicting method
*/
static const CompileTimeErrorCode CONFLICTING_GETTER_AND_METHOD =
- const CompileTimeErrorCode('CONFLICTING_GETTER_AND_METHOD',
- "Class '{0}' cannot have both getter '{1}.{2}' and method with the same name");
+ const CompileTimeErrorCode(
+ 'CONFLICTING_GETTER_AND_METHOD',
+ "Class '{0}' can't have both getter '{1}.{2}' and method with the "
+ "same name.",
+ "Try converting the method to a getter, or "
+ "renaming the method to a name that doesn't conflit.");
/**
* 7.2 Getters: It is a compile-time error if a class has both a getter and a
* method with the same name. This restriction holds regardless of whether the
* getter is defined explicitly or implicitly, or whether the getter or the
* method are inherited or not.
+ *
+ * Parameters:
+ * 0: the name of the class defining the conflicting getter
+ * 1: the name of the class defining the method with which the getter conflicts
+ * 2: the name of the conflicting getter
*/
static const CompileTimeErrorCode CONFLICTING_METHOD_AND_GETTER =
- const CompileTimeErrorCode('CONFLICTING_METHOD_AND_GETTER',
- "Class '{0}' cannot have both method '{1}.{2}' and getter with the same name");
+ const CompileTimeErrorCode(
+ 'CONFLICTING_METHOD_AND_GETTER',
+ "Class '{0}' can't have both method '{1}.{2}' and getter with the "
+ "same name.",
+ "Try converting the getter to a method, or "
+ "renaming the getter to a name that doesn't conflit.");
/**
* 7.6 Constructors: A constructor name always begins with the name of its
* immediately enclosing class, and may optionally be followed by a dot and an
* identifier <i>id</i>. It is a compile-time error if <i>id</i> is the name
* of a member declared in the immediately enclosing class.
+ *
+ * Parameters:
+ * 0: the name of the constructor
*/
static const CompileTimeErrorCode CONFLICTING_CONSTRUCTOR_NAME_AND_FIELD =
- const CompileTimeErrorCode('CONFLICTING_CONSTRUCTOR_NAME_AND_FIELD',
- "'{0}' cannot be used to name a constructor and a field in this class");
+ const CompileTimeErrorCode(
+ 'CONFLICTING_CONSTRUCTOR_NAME_AND_FIELD',
+ "'{0}' can't be used to name both a constructor and a field in this "
+ "class.",
+ "Try renaming either the constructor or the field.");
/**
* 7.6 Constructors: A constructor name always begins with the name of its
* immediately enclosing class, and may optionally be followed by a dot and an
* identifier <i>id</i>. It is a compile-time error if <i>id</i> is the name
* of a member declared in the immediately enclosing class.
+ *
+ * Parameters:
+ * 0: the name of the constructor
*/
static const CompileTimeErrorCode CONFLICTING_CONSTRUCTOR_NAME_AND_METHOD =
- const CompileTimeErrorCode('CONFLICTING_CONSTRUCTOR_NAME_AND_METHOD',
- "'{0}' cannot be used to name a constructor and a method in this class");
+ const CompileTimeErrorCode(
+ 'CONFLICTING_CONSTRUCTOR_NAME_AND_METHOD',
+ "'{0}' can't be used to name both a constructor and a method in this "
+ "class.",
+ "Try renaming either the constructor or the field.");
/**
* 7. Classes: It is a compile time error if a generic class declares a type
* variable with the same name as the class or any of its members or
* constructors.
+ *
+ * Parameters:
+ * 0: the name of the type variable
*/
static const CompileTimeErrorCode CONFLICTING_TYPE_VARIABLE_AND_CLASS =
- const CompileTimeErrorCode('CONFLICTING_TYPE_VARIABLE_AND_CLASS',
- "'{0}' cannot be used to name a type variable in a class with the same name");
+ const CompileTimeErrorCode(
+ 'CONFLICTING_TYPE_VARIABLE_AND_CLASS',
+ "'{0}' can't be used to name both a type variable and the class in "
+ "which the type variable is defined.",
+ "Try renaming either the type variable or the class.");
/**
* 7. Classes: It is a compile time error if a generic class declares a type
* variable with the same name as the class or any of its members or
* constructors.
+ *
+ * Parameters:
+ * 0: the name of the type variable
*/
static const CompileTimeErrorCode CONFLICTING_TYPE_VARIABLE_AND_MEMBER =
- const CompileTimeErrorCode('CONFLICTING_TYPE_VARIABLE_AND_MEMBER',
- "'{0}' cannot be used to name a type variable and member in this class");
+ const CompileTimeErrorCode(
+ 'CONFLICTING_TYPE_VARIABLE_AND_MEMBER',
+ "'{0}' can't be used to name both a type variable and a member in "
+ "this class.",
+ "Try renaming either the type variable or the member.");
/**
- * 12.11.2 Const: It is a compile-time error if evaluation of a constant
+ * 16.12.2 Const: It is a compile-time error if evaluation of a constant
* object results in an uncaught exception being thrown.
*/
static const CompileTimeErrorCode CONST_CONSTRUCTOR_THROWS_EXCEPTION =
- const CompileTimeErrorCode('CONST_CONSTRUCTOR_THROWS_EXCEPTION',
- "'const' constructors cannot throw exceptions");
+ const CompileTimeErrorCode(
+ 'CONST_CONSTRUCTOR_THROWS_EXCEPTION',
+ "Const constructors can't throw exceptions.",
+ "Try removing the throw statement, or removing the keyword 'const'.");
/**
* 10.6.3 Constant Constructors: It is a compile-time error if a constant
* constructor is declared by a class C if any instance variable declared in C
* is initialized with an expression that is not a constant expression.
+ *
+ * Parameters:
+ * 0: the name of the field
*/
static const CompileTimeErrorCode
CONST_CONSTRUCTOR_WITH_FIELD_INITIALIZED_BY_NON_CONST =
const CompileTimeErrorCode(
'CONST_CONSTRUCTOR_WITH_FIELD_INITIALIZED_BY_NON_CONST',
- "Can't define the 'const' constructor because the field '{0}' is initialized with a non-constant value");
+ "Can't define the const constructor because the field '{0}' "
+ "is initialized with a non-constant value.",
+ "Try initializing the field to a constant value, or "
+ "removing the keyword 'const' from the constructor.");
/**
* 7.6.3 Constant Constructors: The superinitializer that appears, explicitly
@@ -460,18 +553,28 @@
* constructor named ... is declared.
*/
static const CompileTimeErrorCode CONST_CONSTRUCTOR_WITH_MIXIN =
- const CompileTimeErrorCode('CONST_CONSTRUCTOR_WITH_MIXIN',
- "Constant constructor cannot be declared for a class with a mixin");
+ const CompileTimeErrorCode(
+ 'CONST_CONSTRUCTOR_WITH_MIXIN',
+ "Const constructor can't be declared for a class with a mixin.",
+ "Try removing the 'const' keyword, or "
+ "removing the 'with' clause from the class declaration.");
/**
* 7.6.3 Constant Constructors: The superinitializer that appears, explicitly
* or implicitly, in the initializer list of a constant constructor must
* specify a constant constructor of the superclass of the immediately
* enclosing class or a compile-time error occurs.
+ *
+ * Parameters:
+ * 0: the name of the superclass
*/
static const CompileTimeErrorCode CONST_CONSTRUCTOR_WITH_NON_CONST_SUPER =
- const CompileTimeErrorCode('CONST_CONSTRUCTOR_WITH_NON_CONST_SUPER',
- "Constant constructor cannot call non-constant super constructor of '{0}'");
+ const CompileTimeErrorCode(
+ 'CONST_CONSTRUCTOR_WITH_NON_CONST_SUPER',
+ "Constant constructor can't call non-constant super constructor of "
+ "'{0}'.",
+ "Try calling a const constructor in the superclass, or "
+ "removing the keyword 'const' from the constructor.");
/**
* 7.6.3 Constant Constructors: It is a compile-time error if a constant
@@ -480,31 +583,39 @@
* The above refers to both locally declared and inherited instance variables.
*/
static const CompileTimeErrorCode CONST_CONSTRUCTOR_WITH_NON_FINAL_FIELD =
- const CompileTimeErrorCode('CONST_CONSTRUCTOR_WITH_NON_FINAL_FIELD',
- "Cannot define the 'const' constructor for a class with non-final fields");
+ const CompileTimeErrorCode(
+ 'CONST_CONSTRUCTOR_WITH_NON_FINAL_FIELD',
+ "Can't define a const constructor for a class with non-final fields.",
+ "Try making all of the fields final, or "
+ "removing the keyword 'const' from the constructor.");
/**
* 12.12.2 Const: It is a compile-time error if <i>T</i> is a deferred type.
*/
static const CompileTimeErrorCode CONST_DEFERRED_CLASS =
- const CompileTimeErrorCode('CONST_DEFERRED_CLASS',
- "Deferred classes cannot be created with 'const'");
+ const CompileTimeErrorCode(
+ 'CONST_DEFERRED_CLASS',
+ "Deferred classes can't be created with 'const'.",
+ "Try using 'new' to create the instance, or "
+ "changing the import to not be deferred.");
/**
* 6.2 Formal Parameters: It is a compile-time error if a formal parameter is
* declared as a constant variable.
*/
static const CompileTimeErrorCode CONST_FORMAL_PARAMETER =
- const CompileTimeErrorCode(
- 'CONST_FORMAL_PARAMETER', "Parameters cannot be 'const'");
+ const CompileTimeErrorCode('CONST_FORMAL_PARAMETER',
+ "Parameters can't be const.", "Try removing the 'const' keyword.");
/**
* 5 Variables: A constant variable must be initialized to a compile-time
* constant or a compile-time error occurs.
*/
static const CompileTimeErrorCode CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE =
- const CompileTimeErrorCode('CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE',
- "'const' variables must be constant value");
+ const CompileTimeErrorCode(
+ 'CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE',
+ "Const variables must be initialized with a constant value.",
+ "Try changing the initializer to be a constant expression.");
/**
* 5 Variables: A constant variable must be initialized to a compile-time
@@ -517,26 +628,38 @@
CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE_FROM_DEFERRED_LIBRARY =
const CompileTimeErrorCode(
'CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE_FROM_DEFERRED_LIBRARY',
- "Constant values from a deferred library cannot be used to initialized a 'const' variable");
+ "Constant values from a deferred library can't be used to "
+ "initialized a const variable.",
+ "Try initializing the variable without referencing members of the "
+ "deferred library, or"
+ "changing the import to not be deferred.");
/**
* 7.5 Instance Variables: It is a compile-time error if an instance variable
* is declared to be constant.
*/
static const CompileTimeErrorCode CONST_INSTANCE_FIELD =
- const CompileTimeErrorCode('CONST_INSTANCE_FIELD',
- "Only static fields can be declared as 'const'");
+ const CompileTimeErrorCode(
+ 'CONST_INSTANCE_FIELD',
+ "Only static fields can be declared as const.",
+ "Try declaring the field as final, or adding the keyword 'static'.");
/**
* 12.8 Maps: It is a compile-time error if the key of an entry in a constant
* map literal is an instance of a class that implements the operator
* <i>==</i> unless the key is a string or integer.
+ *
+ * Parameters:
+ * 0: the type of the entry's key
*/
static const CompileTimeErrorCode
CONST_MAP_KEY_EXPRESSION_TYPE_IMPLEMENTS_EQUALS =
const CompileTimeErrorCode(
'CONST_MAP_KEY_EXPRESSION_TYPE_IMPLEMENTS_EQUALS',
- "The constant map entry key expression type '{0}' cannot override the == operator");
+ "The constant map entry key expression type '{0}' can't override "
+ "the == operator.",
+ "Try using a different value for the key, or "
+ "removing the keyword 'const' from the map.");
/**
* 5 Variables: A constant variable must be initialized to a compile-time
@@ -546,64 +669,76 @@
* 0: the name of the uninitialized final variable
*/
static const CompileTimeErrorCode CONST_NOT_INITIALIZED =
- const CompileTimeErrorCode('CONST_NOT_INITIALIZED',
- "The const variable '{0}' must be initialized");
+ const CompileTimeErrorCode(
+ 'CONST_NOT_INITIALIZED',
+ "The const variable '{0}' must be initialized.",
+ "Try adding an initialization to the declaration.");
/**
- * 12.11.2 Const: An expression of one of the forms !e, e1 && e2 or e1 || e2,
+ * 16.12.2 Const: An expression of one of the forms !e, e1 && e2 or e1 || e2,
* where e, e1 and e2 are constant expressions that evaluate to a boolean
* value.
*/
static const CompileTimeErrorCode CONST_EVAL_TYPE_BOOL =
- const CompileTimeErrorCode('CONST_EVAL_TYPE_BOOL',
- "In constant expressions, operand(s) of this operator must be of type 'bool'");
+ const CompileTimeErrorCode(
+ 'CONST_EVAL_TYPE_BOOL',
+ "In constant expressions, operands of this operator must be of type "
+ "'bool'.");
/**
- * 12.11.2 Const: An expression of one of the forms e1 == e2 or e1 != e2 where
+ * 16.12.2 Const: An expression of one of the forms e1 == e2 or e1 != e2 where
* e1 and e2 are constant expressions that evaluate to a numeric, string or
* boolean value or to null.
*/
static const CompileTimeErrorCode CONST_EVAL_TYPE_BOOL_NUM_STRING =
- const CompileTimeErrorCode('CONST_EVAL_TYPE_BOOL_NUM_STRING',
- "In constant expressions, operands of this operator must be of type 'bool', 'num', 'String' or 'null'");
+ const CompileTimeErrorCode(
+ 'CONST_EVAL_TYPE_BOOL_NUM_STRING',
+ "In constant expressions, operands of this operator must be of type "
+ "'bool', 'num', 'String' or 'null'.");
/**
- * 12.11.2 Const: An expression of one of the forms ~e, e1 ^ e2, e1 & e2,
+ * 16.12.2 Const: An expression of one of the forms ~e, e1 ^ e2, e1 & e2,
* e1 | e2, e1 >> e2 or e1 << e2, where e, e1 and e2 are constant expressions
* that evaluate to an integer value or to null.
*/
static const CompileTimeErrorCode CONST_EVAL_TYPE_INT =
- const CompileTimeErrorCode('CONST_EVAL_TYPE_INT',
- "In constant expressions, operand(s) of this operator must be of type 'int'");
+ const CompileTimeErrorCode(
+ 'CONST_EVAL_TYPE_INT',
+ "In constant expressions, operands of this operator must be of type "
+ "'int'.");
/**
- * 12.11.2 Const: An expression of one of the forms e, e1 + e2, e1 - e2, e1 *
+ * 16.12.2 Const: An expression of one of the forms e, e1 + e2, e1 - e2, e1 *
* e2, e1 / e2, e1 ~/ e2, e1 > e2, e1 < e2, e1 >= e2, e1 <= e2 or e1 % e2,
* where e, e1 and e2 are constant expressions that evaluate to a numeric
* value or to null.
*/
static const CompileTimeErrorCode CONST_EVAL_TYPE_NUM =
- const CompileTimeErrorCode('CONST_EVAL_TYPE_NUM',
- "In constant expressions, operand(s) of this operator must be of type 'num'");
+ const CompileTimeErrorCode(
+ 'CONST_EVAL_TYPE_NUM',
+ "In constant expressions, operands of this operator must be of type "
+ "'num'.");
/**
- * 12.11.2 Const: It is a compile-time error if evaluation of a constant
+ * 16.12.2 Const: It is a compile-time error if evaluation of a constant
* object results in an uncaught exception being thrown.
*/
static const CompileTimeErrorCode CONST_EVAL_THROWS_EXCEPTION =
const CompileTimeErrorCode('CONST_EVAL_THROWS_EXCEPTION',
- "Evaluation of this constant expression causes exception");
+ "Evaluation of this constant expression throws an exception.");
/**
- * 12.11.2 Const: It is a compile-time error if evaluation of a constant
+ * 16.12.2 Const: It is a compile-time error if evaluation of a constant
* object results in an uncaught exception being thrown.
*/
static const CompileTimeErrorCode CONST_EVAL_THROWS_IDBZE =
- const CompileTimeErrorCode('CONST_EVAL_THROWS_IDBZE',
- "Evaluation of this constant expression throws IntegerDivisionByZeroException");
+ const CompileTimeErrorCode(
+ 'CONST_EVAL_THROWS_IDBZE',
+ "Evaluation of this constant expression throws an "
+ "IntegerDivisionByZeroException.");
/**
- * 12.11.2 Const: If <i>T</i> is a parameterized type <i>S<U<sub>1</sub>,
+ * 16.12.2 Const: If <i>T</i> is a parameterized type <i>S<U<sub>1</sub>,
* …, U<sub>m</sub>></i>, let <i>R = S</i>; It is a compile time
* error if <i>S</i> is not a generic type with <i>m</i> type parameters.
*
@@ -616,34 +751,43 @@
* [StaticTypeWarningCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS].
*/
static const CompileTimeErrorCode CONST_WITH_INVALID_TYPE_PARAMETERS =
- const CompileTimeErrorCode('CONST_WITH_INVALID_TYPE_PARAMETERS',
- "The type '{0}' is declared with {1} type parameters, but {2} type arguments were given");
+ const CompileTimeErrorCode(
+ 'CONST_WITH_INVALID_TYPE_PARAMETERS',
+ "The type '{0}' is declared with {1} type parameters, but {2} type "
+ "arguments were given.",
+ "Try adjusting the number of type arguments to match the number of "
+ "type parameters.");
/**
- * 12.11.2 Const: If <i>e</i> is of the form <i>const T(a<sub>1</sub>,
+ * 16.12.2 Const: If <i>e</i> is of the form <i>const T(a<sub>1</sub>,
* …, a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, …,
* x<sub>n+k</sub>: a<sub>n+k</sub>)</i> it is a compile-time error if the
* type <i>T</i> does not declare a constant constructor with the same name as
* the declaration of <i>T</i>.
*/
static const CompileTimeErrorCode CONST_WITH_NON_CONST =
- const CompileTimeErrorCode('CONST_WITH_NON_CONST',
- "The constructor being called is not a 'const' constructor");
+ const CompileTimeErrorCode(
+ 'CONST_WITH_NON_CONST',
+ "The constructor being called isn't a const constructor.",
+ "Try using 'new' to call the constructor.");
/**
- * 12.11.2 Const: In all of the above cases, it is a compile-time error if
+ * 16.12.2 Const: In all of the above cases, it is a compile-time error if
* <i>a<sub>i</sub>, 1 <= i <= n + k</i>, is not a compile-time constant
* expression.
*/
static const CompileTimeErrorCode CONST_WITH_NON_CONSTANT_ARGUMENT =
- const CompileTimeErrorCode('CONST_WITH_NON_CONSTANT_ARGUMENT',
- "Arguments of a constant creation must be constant expressions");
+ const CompileTimeErrorCode(
+ 'CONST_WITH_NON_CONSTANT_ARGUMENT',
+ "Arguments of a constant creation must be constant expressions.",
+ "Try making the argument a valid constant, or "
+ "use 'new' to call the constructor.");
/**
- * 12.11.2 Const: It is a compile-time error if <i>T</i> is not a class
+ * 16.12.2 Const: It is a compile-time error if <i>T</i> is not a class
* accessible in the current scope, optionally followed by type arguments.
*
- * 12.11.2 Const: If <i>e</i> is of the form <i>const T.id(a<sub>1</sub>,
+ * 16.12.2 Const: If <i>e</i> is of the form <i>const T.id(a<sub>1</sub>,
* …, a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, …
* x<sub>n+k</sub>: a<sub>n+k</sub>)</i> it is a compile-time error if
* <i>T</i> is not a class accessible in the current scope, optionally
@@ -654,18 +798,22 @@
*/
static const CompileTimeErrorCode CONST_WITH_NON_TYPE =
const CompileTimeErrorCode(
- 'CONST_WITH_NON_TYPE', "The name '{0}' is not a class");
+ 'CONST_WITH_NON_TYPE',
+ "The name '{0}' isn't a class.",
+ "Try correcting the name to match an existing class.");
/**
- * 12.11.2 Const: It is a compile-time error if <i>T</i> includes any type
- * parameters.
+ * 16.12.2 Const: If <i>T</i> is a parameterized type, it is a compile-time
+ * error if <i>T</i> includes a type variable among its type arguments.
*/
static const CompileTimeErrorCode CONST_WITH_TYPE_PARAMETERS =
- const CompileTimeErrorCode('CONST_WITH_TYPE_PARAMETERS',
- "The constant creation cannot use a type parameter");
+ const CompileTimeErrorCode(
+ 'CONST_WITH_TYPE_PARAMETERS',
+ "A constant creation can't use a type parameter as a type argument.",
+ "Try replacing the type parameter with a different type.");
/**
- * 12.11.2 Const: It is a compile-time error if <i>T.id</i> is not the name of
+ * 16.12.2 Const: It is a compile-time error if <i>T.id</i> is not the name of
* a constant constructor declared by the type <i>T</i>.
*
* Parameters:
@@ -673,27 +821,33 @@
* 1: the name of the requested constant constructor
*/
static const CompileTimeErrorCode CONST_WITH_UNDEFINED_CONSTRUCTOR =
- const CompileTimeErrorCode('CONST_WITH_UNDEFINED_CONSTRUCTOR',
- "The class '{0}' does not have a constant constructor '{1}'");
+ const CompileTimeErrorCode(
+ 'CONST_WITH_UNDEFINED_CONSTRUCTOR',
+ "The class '{0}' doesn't have a constant constructor '{1}'.",
+ "Try calling a different contructor.");
/**
- * 12.11.2 Const: It is a compile-time error if <i>T.id</i> is not the name of
+ * 16.12.2 Const: It is a compile-time error if <i>T.id</i> is not the name of
* a constant constructor declared by the type <i>T</i>.
*
* Parameters:
* 0: the name of the type
*/
static const CompileTimeErrorCode CONST_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT =
- const CompileTimeErrorCode('CONST_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT',
- "The class '{0}' does not have a default constant constructor");
+ const CompileTimeErrorCode(
+ 'CONST_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT',
+ "The class '{0}' doesn't have a default constant constructor.",
+ "Try calling a different contructor.");
/**
* 15.3.1 Typedef: It is a compile-time error if any default values are
* specified in the signature of a function type alias.
*/
static const CompileTimeErrorCode DEFAULT_VALUE_IN_FUNCTION_TYPE_ALIAS =
- const CompileTimeErrorCode('DEFAULT_VALUE_IN_FUNCTION_TYPE_ALIAS',
- "Default values aren't allowed in typedefs");
+ const CompileTimeErrorCode(
+ 'DEFAULT_VALUE_IN_FUNCTION_TYPE_ALIAS',
+ "Default parameter values aren't allowed in typedefs.",
+ "Try removing the default value.");
/**
* 6.2.1 Required Formals: By means of a function signature that names the
@@ -702,8 +856,10 @@
* function type.
*/
static const CompileTimeErrorCode DEFAULT_VALUE_IN_FUNCTION_TYPED_PARAMETER =
- const CompileTimeErrorCode('DEFAULT_VALUE_IN_FUNCTION_TYPED_PARAMETER',
- "Default values aren't allowed in function type parameters");
+ const CompileTimeErrorCode(
+ 'DEFAULT_VALUE_IN_FUNCTION_TYPED_PARAMETER',
+ "Default values aren't allowed in function typed parameters.",
+ "Try removing the default value.");
/**
* 7.6.2 Factories: It is a compile-time error if <i>k</i> explicitly
@@ -713,15 +869,19 @@
DEFAULT_VALUE_IN_REDIRECTING_FACTORY_CONSTRUCTOR =
const CompileTimeErrorCode(
'DEFAULT_VALUE_IN_REDIRECTING_FACTORY_CONSTRUCTOR',
- "Default values aren't allowed in factory constructors that redirect to another constructor");
+ "Default values aren't allowed in factory constructors that redirect "
+ "to another constructor.",
+ "Try removing the default value.");
/**
* 3.1 Scoping: It is a compile-time error if there is more than one entity
* with the same name declared in the same scope.
*/
static const CompileTimeErrorCode DUPLICATE_CONSTRUCTOR_DEFAULT =
- const CompileTimeErrorCode('DUPLICATE_CONSTRUCTOR_DEFAULT',
- "The default constructor is already defined");
+ const CompileTimeErrorCode(
+ 'DUPLICATE_CONSTRUCTOR_DEFAULT',
+ "The default constructor is already defined.",
+ "Try giving one of the constructors a name.");
/**
* 3.1 Scoping: It is a compile-time error if there is more than one entity
@@ -731,8 +891,10 @@
* 0: the name of the duplicate entity
*/
static const CompileTimeErrorCode DUPLICATE_CONSTRUCTOR_NAME =
- const CompileTimeErrorCode('DUPLICATE_CONSTRUCTOR_NAME',
- "The constructor with name '{0}' is already defined");
+ const CompileTimeErrorCode(
+ 'DUPLICATE_CONSTRUCTOR_NAME',
+ "The constructor with name '{0}' is already defined.",
+ "Try renaming one of the constructors.");
/**
* 3.1 Scoping: It is a compile-time error if there is more than one entity
@@ -749,7 +911,9 @@
*/
static const CompileTimeErrorCode DUPLICATE_DEFINITION =
const CompileTimeErrorCode(
- 'DUPLICATE_DEFINITION', "The name '{0}' is already defined");
+ 'DUPLICATE_DEFINITION',
+ "The name '{0}' is already defined.",
+ "Try renaming one of the declarations.");
/**
* 18.3 Parts: It's a compile-time error if the same library contains two part
@@ -760,7 +924,8 @@
*/
static const CompileTimeErrorCode DUPLICATE_PART = const CompileTimeErrorCode(
'DUPLICATE_PART',
- "The library already contains a part with the uri '{0}'.");
+ "The library already contains a part with the uri '{0}'.",
+ "Try removing all but one of the duplicated part directives.");
/**
* 7. Classes: It is a compile-time error if a class has an instance member
@@ -771,22 +936,30 @@
*
* Parameters:
* 0: the name of the class that has conflicting instance/static members
- * 1: the name of the conflicting members
+ * 1: the name of the conflicting member
*
* See [DUPLICATE_DEFINITION].
*/
static const CompileTimeErrorCode DUPLICATE_DEFINITION_INHERITANCE =
- const CompileTimeErrorCode('DUPLICATE_DEFINITION_INHERITANCE',
- "The name '{0}' is already defined in '{1}'");
+ const CompileTimeErrorCode(
+ 'DUPLICATE_DEFINITION_INHERITANCE',
+ "The name '{0}' is already defined in '{1}'.",
+ "Try renaming one of the declarations.");
/**
* 12.14.2 Binding Actuals to Formals: It is a compile-time error if
* <i>q<sub>i</sub> = q<sub>j</sub></i> for any <i>i != j</i> [where
* <i>q<sub>i</sub></i> is the label for a named argument].
+ *
+ * Parameters:
+ * 0: the name of the parameter that was duplicated
*/
static const CompileTimeErrorCode DUPLICATE_NAMED_ARGUMENT =
- const CompileTimeErrorCode('DUPLICATE_NAMED_ARGUMENT',
- "The argument for the named parameter '{0}' was already specified");
+ const CompileTimeErrorCode(
+ 'DUPLICATE_NAMED_ARGUMENT',
+ "The argument for the named parameter '{0}' was already specified.",
+ "Try removing one of the named arguments, or "
+ "correcting one of the names to reference a different named parameter.");
/**
* SDK implementation libraries can be exported only by other SDK libraries.
@@ -796,7 +969,7 @@
*/
static const CompileTimeErrorCode EXPORT_INTERNAL_LIBRARY =
const CompileTimeErrorCode('EXPORT_INTERNAL_LIBRARY',
- "The library '{0}' is internal and cannot be exported");
+ "The library '{0}' is internal and can't be exported.");
/**
* 14.2 Exports: It is a compile-time error if the compilation unit found at
@@ -806,15 +979,19 @@
* 0: the uri pointing to a non-library declaration
*/
static const CompileTimeErrorCode EXPORT_OF_NON_LIBRARY =
- const CompileTimeErrorCode('EXPORT_OF_NON_LIBRARY',
- "The exported library '{0}' must not have a part-of directive");
+ const CompileTimeErrorCode(
+ 'EXPORT_OF_NON_LIBRARY',
+ "The exported library '{0}' can't have a part-of directive.",
+ "Try exporting the library that the part is a part of.");
/**
* Enum proposal: It is a compile-time error to subclass, mix-in or implement
* an enum.
*/
static const CompileTimeErrorCode EXTENDS_ENUM = const CompileTimeErrorCode(
- 'EXTENDS_ENUM', "Classes cannot extend an enum");
+ 'EXTENDS_ENUM',
+ "Classes can't extend an enum.",
+ "Try specifying a different superclass, or removing the extends clause.");
/**
* 7.9 Superclasses: It is a compile-time error if the extends clause of a
@@ -824,9 +1001,10 @@
* Parameters:
* 0: the name of the superclass that was not found
*/
- static const CompileTimeErrorCode EXTENDS_NON_CLASS =
- const CompileTimeErrorCode(
- 'EXTENDS_NON_CLASS', "Classes can only extend other classes");
+ static const CompileTimeErrorCode EXTENDS_NON_CLASS = const CompileTimeErrorCode(
+ 'EXTENDS_NON_CLASS',
+ "Classes can only extend other classes.",
+ "Try specifying a different superclass, or removing the extends clause.");
/**
* 12.2 Null: It is a compile-time error for a class to attempt to extend or
@@ -855,7 +1033,10 @@
*/
static const CompileTimeErrorCode EXTENDS_DISALLOWED_CLASS =
const CompileTimeErrorCode(
- 'EXTENDS_DISALLOWED_CLASS', "Classes cannot extend '{0}'");
+ 'EXTENDS_DISALLOWED_CLASS',
+ "Classes can't extend '{0}'.",
+ "Try specifying a different superclass, or "
+ "removing the extends clause.");
/**
* 7.9 Superclasses: It is a compile-time error if the extends clause of a
@@ -867,8 +1048,11 @@
* See [IMPLEMENTS_DEFERRED_CLASS], and [MIXIN_DEFERRED_CLASS].
*/
static const CompileTimeErrorCode EXTENDS_DEFERRED_CLASS =
- const CompileTimeErrorCode('EXTENDS_DEFERRED_CLASS',
- "This class cannot extend the deferred class '{0}'");
+ const CompileTimeErrorCode(
+ 'EXTENDS_DEFERRED_CLASS',
+ "This class can't extend the deferred class '{0}'.",
+ "Try specifying a different superclass, or "
+ "removing the extends clause.");
/**
* DEP 37 extends the syntax for assert() to allow a second "message"
@@ -876,14 +1060,16 @@
* argument but the DEP is not enabled.
*/
static const CompileTimeErrorCode EXTRA_ARGUMENT_TO_ASSERT =
- const CompileTimeErrorCode('EXTRA_ARGUMENT_TO_ASSERT',
- "Assertions only accept a single argument");
+ const CompileTimeErrorCode(
+ 'EXTRA_ARGUMENT_TO_ASSERT',
+ "Assertions only accept a single argument.",
+ "Try removing the message, or enable messages in assert statements.");
/**
* 12.14.2 Binding Actuals to Formals: It is a static warning if <i>m <
* h</i> or if <i>m > n</i>.
*
- * 12.11.2 Const: It is a compile-time error if evaluation of a constant
+ * 16.12.2 Const: It is a compile-time error if evaluation of a constant
* object results in an uncaught exception being thrown.
*
* Parameters:
@@ -891,17 +1077,24 @@
* 1: the actual number of positional arguments given
*/
static const CompileTimeErrorCode EXTRA_POSITIONAL_ARGUMENTS =
- const CompileTimeErrorCode('EXTRA_POSITIONAL_ARGUMENTS',
- "{0} positional arguments expected, but {1} found");
+ const CompileTimeErrorCode(
+ 'EXTRA_POSITIONAL_ARGUMENTS',
+ "{0} positional arguments expected, but {1} found.",
+ "Try removing the extra arguments.");
/**
* 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor. It
* is a compile time error if more than one initializer corresponding to a
* given instance variable appears in <i>k</i>'s list.
+ *
+ * Parameters:
+ * 0: the name of the field being initialized multiple times
*/
static const CompileTimeErrorCode FIELD_INITIALIZED_BY_MULTIPLE_INITIALIZERS =
- const CompileTimeErrorCode('FIELD_INITIALIZED_BY_MULTIPLE_INITIALIZERS',
- "The field '{0}' cannot be initialized twice in the same constructor");
+ const CompileTimeErrorCode(
+ 'FIELD_INITIALIZED_BY_MULTIPLE_INITIALIZERS',
+ "The field '{0}' can't be initialized twice in the same constructor.",
+ "Try removing one of the initializations.");
/**
* 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor. It
@@ -913,7 +1106,9 @@
FIELD_INITIALIZED_IN_PARAMETER_AND_INITIALIZER =
const CompileTimeErrorCode(
'FIELD_INITIALIZED_IN_PARAMETER_AND_INITIALIZER',
- "Fields cannot be initialized in both the parameter list and the initializers");
+ "Fields can't be initialized in both the parameter list and the "
+ "initializers.",
+ "Try removing one of the initializations.");
/**
* 5 Variables: It is a compile-time error if a final instance variable that
@@ -924,8 +1119,10 @@
* 0: the name of the field in question
*/
static const CompileTimeErrorCode FINAL_INITIALIZED_MULTIPLE_TIMES =
- const CompileTimeErrorCode('FINAL_INITIALIZED_MULTIPLE_TIMES',
- "'{0}' is a final field and so can only be set once");
+ const CompileTimeErrorCode(
+ 'FINAL_INITIALIZED_MULTIPLE_TIMES',
+ "'{0}' is a final field and so can only be set once.",
+ "Try removing all but one of the initializations.");
/**
* 7.6.1 Generative Constructors: It is a compile-time error if an
@@ -933,8 +1130,10 @@
* generative constructor.
*/
static const CompileTimeErrorCode FIELD_INITIALIZER_FACTORY_CONSTRUCTOR =
- const CompileTimeErrorCode('FIELD_INITIALIZER_FACTORY_CONSTRUCTOR',
- "Initializing formal fields cannot be used in factory constructors");
+ const CompileTimeErrorCode(
+ 'FIELD_INITIALIZER_FACTORY_CONSTRUCTOR',
+ "Initializing formal parameters can't be used in factory constructors.",
+ "Try using a normal parameter.");
/**
* 7.6.1 Generative Constructors: It is a compile-time error if an
@@ -942,8 +1141,10 @@
* generative constructor.
*/
static const CompileTimeErrorCode FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR =
- const CompileTimeErrorCode('FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR',
- "Initializing formal fields can only be used in constructors");
+ const CompileTimeErrorCode(
+ 'FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR',
+ "Initializing formal parameters can only be used in constructors.",
+ "Try using a normal parameter.");
/**
* 7.6.1 Generative Constructors: A generative constructor may be redirecting,
@@ -954,8 +1155,10 @@
* generative constructor.
*/
static const CompileTimeErrorCode FIELD_INITIALIZER_REDIRECTING_CONSTRUCTOR =
- const CompileTimeErrorCode('FIELD_INITIALIZER_REDIRECTING_CONSTRUCTOR',
- "The redirecting constructor cannot have a field initializer");
+ const CompileTimeErrorCode(
+ 'FIELD_INITIALIZER_REDIRECTING_CONSTRUCTOR',
+ "The redirecting constructor can't have a field initializer.",
+ "Try using a normal parameter.");
/**
* 7.2 Getters: It is a compile-time error if a class has both a getter and a
@@ -965,8 +1168,11 @@
* 0: the conflicting name of the getter and method
*/
static const CompileTimeErrorCode GETTER_AND_METHOD_WITH_SAME_NAME =
- const CompileTimeErrorCode('GETTER_AND_METHOD_WITH_SAME_NAME',
- "'{0}' cannot be used to name a getter, there is already a method with the same name");
+ const CompileTimeErrorCode(
+ 'GETTER_AND_METHOD_WITH_SAME_NAME',
+ "'{0}' can't be used to name a getter, there is already a method "
+ "with the same name.",
+ "Try renaming either the getter or the method.");
/**
* 7.10 Superinterfaces: It is a compile-time error if the implements clause
@@ -974,13 +1180,17 @@
* superinterface.
*
* Parameters:
- * 0: the name of the type that cannot be extended
+ * 0: the name of the type that is deferred
*
* See [EXTENDS_DEFERRED_CLASS], and [MIXIN_DEFERRED_CLASS].
*/
static const CompileTimeErrorCode IMPLEMENTS_DEFERRED_CLASS =
- const CompileTimeErrorCode('IMPLEMENTS_DEFERRED_CLASS',
- "This class cannot implement the deferred class '{0}'");
+ const CompileTimeErrorCode(
+ 'IMPLEMENTS_DEFERRED_CLASS',
+ "This class can't implement the deferred class '{0}'.",
+ "Try specifying a different interface, "
+ "removing the class from the list, or "
+ "changing the import to not be deferred..");
/**
* 12.2 Null: It is a compile-time error for a class to attempt to extend or
@@ -1009,7 +1219,10 @@
*/
static const CompileTimeErrorCode IMPLEMENTS_DISALLOWED_CLASS =
const CompileTimeErrorCode(
- 'IMPLEMENTS_DISALLOWED_CLASS', "Classes cannot implement '{0}'");
+ 'IMPLEMENTS_DISALLOWED_CLASS',
+ "Classes can't implement '{0}'.",
+ "Try specifying a different interface, or "
+ "remove the class from the list.");
/**
* 7.10 Superinterfaces: It is a compile-time error if the implements clause
@@ -1017,7 +1230,9 @@
*/
static const CompileTimeErrorCode IMPLEMENTS_DYNAMIC =
const CompileTimeErrorCode(
- 'IMPLEMENTS_DYNAMIC', "Classes cannot implement 'dynamic'");
+ 'IMPLEMENTS_DYNAMIC',
+ "Classes can't implement 'dynamic'.",
+ "Try specifying an interface, or remove 'dynamic' from the list.");
/**
* Enum proposal: It is a compile-time error to subclass, mix-in or implement
@@ -1025,7 +1240,9 @@
*/
static const CompileTimeErrorCode IMPLEMENTS_ENUM =
const CompileTimeErrorCode(
- 'IMPLEMENTS_ENUM', "Classes cannot implement an enum");
+ 'IMPLEMENTS_ENUM',
+ "Classes can't implement an enum.",
+ "Try specifying an interface, or remove the enum from the list.");
/**
* 7.10 Superinterfaces: It is a compile-time error if the implements clause
@@ -1037,7 +1254,9 @@
*/
static const CompileTimeErrorCode IMPLEMENTS_NON_CLASS =
const CompileTimeErrorCode(
- 'IMPLEMENTS_NON_CLASS', "Classes can only implement other classes");
+ 'IMPLEMENTS_NON_CLASS',
+ "Classes can only implement other classes.",
+ "Try specifying a class, or remove the name from the list.");
/**
* 7.10 Superinterfaces: It is a compile-time error if a type <i>T</i> appears
@@ -1048,7 +1267,9 @@
*/
static const CompileTimeErrorCode IMPLEMENTS_REPEATED =
const CompileTimeErrorCode(
- 'IMPLEMENTS_REPEATED', "'{0}' can only be implemented once");
+ 'IMPLEMENTS_REPEATED',
+ "'{0}' can only be implemented once.",
+ "Try removing all but one occurance of the class name.");
/**
* 7.10 Superinterfaces: It is a compile-time error if the superclass of a
@@ -1059,8 +1280,10 @@
* clauses
*/
static const CompileTimeErrorCode IMPLEMENTS_SUPER_CLASS =
- const CompileTimeErrorCode('IMPLEMENTS_SUPER_CLASS',
- "'{0}' cannot be used in both 'extends' and 'implements' clauses");
+ const CompileTimeErrorCode(
+ 'IMPLEMENTS_SUPER_CLASS',
+ "'{0}' can't be used in both 'extends' and 'implements' clauses.",
+ "Try removing one of the occurances.");
/**
* 7.6.1 Generative Constructors: Note that <b>this</b> is not in scope on the
@@ -1070,13 +1293,10 @@
* function or variable initializer, in a factory constructor, or in a static
* method or variable initializer, or in the initializer of an instance
* variable.
- *
- * Parameters:
- * 0: the name of the type in question
*/
static const CompileTimeErrorCode IMPLICIT_THIS_REFERENCE_IN_INITIALIZER =
const CompileTimeErrorCode('IMPLICIT_THIS_REFERENCE_IN_INITIALIZER',
- "Only static members can be accessed in initializers");
+ "Only static members can be accessed in initializers.");
/**
* SDK implementation libraries can be imported only by other SDK libraries.
@@ -1086,7 +1306,7 @@
*/
static const CompileTimeErrorCode IMPORT_INTERNAL_LIBRARY =
const CompileTimeErrorCode('IMPORT_INTERNAL_LIBRARY',
- "The library '{0}' is internal and cannot be imported");
+ "The library '{0}' is internal and can't be imported.");
/**
* 14.1 Imports: It is a compile-time error if the specified URI of an
@@ -1098,8 +1318,10 @@
* See [StaticWarningCode.IMPORT_OF_NON_LIBRARY].
*/
static const CompileTimeErrorCode IMPORT_OF_NON_LIBRARY =
- const CompileTimeErrorCode('IMPORT_OF_NON_LIBRARY',
- "The imported library '{0}' must not have a part-of directive");
+ const CompileTimeErrorCode(
+ 'IMPORT_OF_NON_LIBRARY',
+ "The imported library '{0}' can't have a part-of directive.",
+ "Try importing the library that the part is a part of.");
/**
* 13.9 Switch: It is a compile-time error if values of the expressions
@@ -1112,7 +1334,7 @@
*/
static const CompileTimeErrorCode INCONSISTENT_CASE_EXPRESSION_TYPES =
const CompileTimeErrorCode('INCONSISTENT_CASE_EXPRESSION_TYPES',
- "Case expressions must have the same types, '{0}' is not a '{1}'");
+ "Case expressions must have the same types, '{0}' isn't a '{1}'.");
/**
* 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor. It
@@ -1127,8 +1349,11 @@
* See [INITIALIZING_FORMAL_FOR_NON_EXISTENT_FIELD].
*/
static const CompileTimeErrorCode INITIALIZER_FOR_NON_EXISTENT_FIELD =
- const CompileTimeErrorCode('INITIALIZER_FOR_NON_EXISTENT_FIELD',
- "'{0}' is not a variable in the enclosing class");
+ const CompileTimeErrorCode(
+ 'INITIALIZER_FOR_NON_EXISTENT_FIELD',
+ "'{0}' isn't a field in the enclosing class.",
+ "Try correcting the name to match an existing field, or "
+ "defining a field named '{0}'.");
/**
* 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor. It
@@ -1143,8 +1368,11 @@
* See [INITIALIZING_FORMAL_FOR_STATIC_FIELD].
*/
static const CompileTimeErrorCode INITIALIZER_FOR_STATIC_FIELD =
- const CompileTimeErrorCode('INITIALIZER_FOR_STATIC_FIELD',
- "'{0}' is a static variable in the enclosing class, variables initialized in a constructor cannot be static");
+ const CompileTimeErrorCode(
+ 'INITIALIZER_FOR_STATIC_FIELD',
+ "'{0}' is a static field in the enclosing class. Fields initialized "
+ "in a constructor can't be static.",
+ "Try removing the initialization.");
/**
* 7.6.1 Generative Constructors: An initializing formal has the form
@@ -1159,8 +1387,11 @@
* [INITIALIZER_FOR_NON_EXISTENT_FIELD].
*/
static const CompileTimeErrorCode INITIALIZING_FORMAL_FOR_NON_EXISTENT_FIELD =
- const CompileTimeErrorCode('INITIALIZING_FORMAL_FOR_NON_EXISTENT_FIELD',
- "'{0}' is not a variable in the enclosing class");
+ const CompileTimeErrorCode(
+ 'INITIALIZING_FORMAL_FOR_NON_EXISTENT_FIELD',
+ "'{0}' isn't a field in the enclosing class.",
+ "Try correcting the name to match an existing field, or "
+ "defining a field named '{0}'.");
/**
* 7.6.1 Generative Constructors: An initializing formal has the form
@@ -1174,24 +1405,32 @@
* See [INITIALIZER_FOR_STATIC_FIELD].
*/
static const CompileTimeErrorCode INITIALIZING_FORMAL_FOR_STATIC_FIELD =
- const CompileTimeErrorCode('INITIALIZING_FORMAL_FOR_STATIC_FIELD',
- "'{0}' is a static field in the enclosing class, fields initialized in a constructor cannot be static");
+ const CompileTimeErrorCode(
+ 'INITIALIZING_FORMAL_FOR_STATIC_FIELD',
+ "'{0}' is a static field in the enclosing class. Fields initialized "
+ "in a constructor can't be static.",
+ "Try removing the initialization.");
/**
* 12.30 Identifier Reference: Otherwise, e is equivalent to the property
* extraction <b>this</b>.<i>id</i>.
*/
static const CompileTimeErrorCode INSTANCE_MEMBER_ACCESS_FROM_FACTORY =
- const CompileTimeErrorCode('INSTANCE_MEMBER_ACCESS_FROM_FACTORY',
- "Instance members cannot be accessed from a factory constructor");
+ const CompileTimeErrorCode(
+ 'INSTANCE_MEMBER_ACCESS_FROM_FACTORY',
+ "Instance members can't be accessed from a factory constructor.",
+ "Try removing the reference to the instance member.");
/**
* 12.30 Identifier Reference: Otherwise, e is equivalent to the property
* extraction <b>this</b>.<i>id</i>.
*/
static const CompileTimeErrorCode INSTANCE_MEMBER_ACCESS_FROM_STATIC =
- const CompileTimeErrorCode('INSTANCE_MEMBER_ACCESS_FROM_STATIC',
- "Instance members cannot be accessed from a static method");
+ const CompileTimeErrorCode(
+ 'INSTANCE_MEMBER_ACCESS_FROM_STATIC',
+ "Instance members can't be accessed from a static method.",
+ "Try removing the reference to the instance member, or ."
+ "removing the keyword 'static' from the method.");
/**
* Enum proposal: It is also a compile-time error to explicitly instantiate an
@@ -1199,20 +1438,24 @@
*/
static const CompileTimeErrorCode INSTANTIATE_ENUM =
const CompileTimeErrorCode(
- 'INSTANTIATE_ENUM', "Enums cannot be instantiated");
+ 'INSTANTIATE_ENUM',
+ "Enums can't be instantiated.",
+ "Try using one of the defined constants.");
/**
- * 11 Metadata: Metadata consists of a series of annotations, each of which
+ * 15 Metadata: Metadata consists of a series of annotations, each of which
* begin with the character @, followed by a constant expression that must be
* either a reference to a compile-time constant variable, or a call to a
* constant constructor.
*/
- static const CompileTimeErrorCode INVALID_ANNOTATION = const CompileTimeErrorCode(
- 'INVALID_ANNOTATION',
- "Annotation can be only constant variable or constant constructor invocation");
+ static const CompileTimeErrorCode INVALID_ANNOTATION =
+ const CompileTimeErrorCode(
+ 'INVALID_ANNOTATION',
+ "Annotation must be either a const variable reference or const "
+ "constructor invocation.");
/**
- * 11 Metadata: Metadata consists of a series of annotations, each of which
+ * 15 Metadata: Metadata consists of a series of annotations, each of which
* begin with the character @, followed by a constant expression that must be
* either a reference to a compile-time constant variable, or a call to a
* constant constructor.
@@ -1221,8 +1464,11 @@
* not qualified by a deferred prefix.
*/
static const CompileTimeErrorCode INVALID_ANNOTATION_FROM_DEFERRED_LIBRARY =
- const CompileTimeErrorCode('INVALID_ANNOTATION_FROM_DEFERRED_LIBRARY',
- "Constant values from a deferred library cannot be used as annotations");
+ const CompileTimeErrorCode(
+ 'INVALID_ANNOTATION_FROM_DEFERRED_LIBRARY',
+ "Constant values from a deferred library can't be used as annotations.",
+ "Try removing the annotation, or "
+ "changing the import to not be deferred.");
/**
* 15.31 Identifier Reference: It is a compile-time error if any of the
@@ -1230,24 +1476,32 @@
* body marked with either async, async* or sync*.
*/
static const CompileTimeErrorCode INVALID_IDENTIFIER_IN_ASYNC =
- const CompileTimeErrorCode('INVALID_IDENTIFIER_IN_ASYNC',
- "The identifier '{0}' cannot be used in a function marked with async, async* or sync*");
+ const CompileTimeErrorCode(
+ 'INVALID_IDENTIFIER_IN_ASYNC',
+ "The identifier '{0}' can't be used in a function marked with "
+ "'async', 'async*' or 'sync*'.",
+ "Try using a different name, or "
+ "remove the modifier on the function body.");
/**
* 9. Functions: It is a compile-time error if an async, async* or sync*
* modifier is attached to the body of a setter or constructor.
*/
static const CompileTimeErrorCode INVALID_MODIFIER_ON_CONSTRUCTOR =
- const CompileTimeErrorCode('INVALID_MODIFIER_ON_CONSTRUCTOR',
- "The modifier '{0}' cannot be applied to the body of a constructor");
+ const CompileTimeErrorCode(
+ 'INVALID_MODIFIER_ON_CONSTRUCTOR',
+ "The modifier '{0}' can't be applied to the body of a constructor.",
+ "Try removing the modifier.");
/**
* 9. Functions: It is a compile-time error if an async, async* or sync*
* modifier is attached to the body of a setter or constructor.
*/
static const CompileTimeErrorCode INVALID_MODIFIER_ON_SETTER =
- const CompileTimeErrorCode('INVALID_MODIFIER_ON_SETTER',
- "The modifier '{0}' cannot be applied to the body of a setter");
+ const CompileTimeErrorCode(
+ 'INVALID_MODIFIER_ON_SETTER',
+ "The modifier '{0}' can't be applied to the body of a setter.",
+ "Try removing the modifier.");
/**
* TODO(brianwilkerson) Remove this when we have decided on how to report
@@ -1257,7 +1511,7 @@
* See TODOs in ConstantVisitor
*/
static const CompileTimeErrorCode INVALID_CONSTANT =
- const CompileTimeErrorCode('INVALID_CONSTANT', "Invalid constant value");
+ const CompileTimeErrorCode('INVALID_CONSTANT', "Invalid constant value.");
/**
* 7.6 Constructors: It is a compile-time error if the name of a constructor
@@ -1265,15 +1519,17 @@
*/
static const CompileTimeErrorCode INVALID_CONSTRUCTOR_NAME =
const CompileTimeErrorCode(
- 'INVALID_CONSTRUCTOR_NAME', "Invalid constructor name");
+ 'INVALID_CONSTRUCTOR_NAME', "Invalid constructor name.");
/**
* 7.6.2 Factories: It is a compile-time error if <i>M</i> is not the name of
* the immediately enclosing class.
*/
static const CompileTimeErrorCode INVALID_FACTORY_NAME_NOT_A_CLASS =
- const CompileTimeErrorCode('INVALID_FACTORY_NAME_NOT_A_CLASS',
- "The name of the immediately enclosing class expected");
+ const CompileTimeErrorCode(
+ 'INVALID_FACTORY_NAME_NOT_A_CLASS',
+ "The name of a factory constructor must be the same as the name of "
+ "the immediately enclosing class.");
/**
* 12.10 This: It is a compile-time error if this appears in a top-level
@@ -1283,7 +1539,7 @@
*/
static const CompileTimeErrorCode INVALID_REFERENCE_TO_THIS =
const CompileTimeErrorCode('INVALID_REFERENCE_TO_THIS',
- "Invalid reference to 'this' expression");
+ "Invalid reference to 'this' expression.");
/**
* 12.6 Lists: It is a compile time error if the type argument of a constant
@@ -1293,8 +1549,11 @@
* 0: the name of the type parameter
*/
static const CompileTimeErrorCode INVALID_TYPE_ARGUMENT_IN_CONST_LIST =
- const CompileTimeErrorCode('INVALID_TYPE_ARGUMENT_IN_CONST_LIST',
- "Constant list literals cannot include a type parameter as a type argument, such as '{0}'");
+ const CompileTimeErrorCode(
+ 'INVALID_TYPE_ARGUMENT_IN_CONST_LIST',
+ "Constant list literals can't include a type parameter as a type "
+ "argument, such as '{0}'.",
+ "Try replacing the type parameter with a different type.");
/**
* 12.7 Maps: It is a compile time error if the type arguments of a constant
@@ -1304,8 +1563,11 @@
* 0: the name of the type parameter
*/
static const CompileTimeErrorCode INVALID_TYPE_ARGUMENT_IN_CONST_MAP =
- const CompileTimeErrorCode('INVALID_TYPE_ARGUMENT_IN_CONST_MAP',
- "Constant map literals cannot include a type parameter as a type argument, such as '{0}'");
+ const CompileTimeErrorCode(
+ 'INVALID_TYPE_ARGUMENT_IN_CONST_MAP',
+ "Constant map literals can't include a type parameter as a type "
+ "argument, such as '{0}'.",
+ "Try replacing the type parameter with a different type.");
/**
* 14.2 Exports: It is a compile-time error if the compilation unit found at
@@ -1323,7 +1585,7 @@
* See [URI_DOES_NOT_EXIST].
*/
static const CompileTimeErrorCode INVALID_URI =
- const CompileTimeErrorCode('INVALID_URI', "Invalid URI syntax: '{0}'");
+ const CompileTimeErrorCode('INVALID_URI', "Invalid URI syntax: '{0}'.");
/**
* 13.13 Break: It is a compile-time error if no such statement
@@ -1339,7 +1601,7 @@
*/
static const CompileTimeErrorCode LABEL_IN_OUTER_SCOPE =
const CompileTimeErrorCode('LABEL_IN_OUTER_SCOPE',
- "Cannot reference label '{0}' declared in an outer method");
+ "Can't reference label '{0}' declared in an outer method.");
/**
* 13.13 Break: It is a compile-time error if no such statement
@@ -1355,7 +1617,10 @@
*/
static const CompileTimeErrorCode LABEL_UNDEFINED =
const CompileTimeErrorCode(
- 'LABEL_UNDEFINED', "Cannot reference undefined label '{0}'");
+ 'LABEL_UNDEFINED',
+ "Can't reference undefined label '{0}'.",
+ "Try defining the label, or "
+ "correcting the name to match an existing label.");
/**
* 7 Classes: It is a compile time error if a class <i>C</i> declares a member
@@ -1363,7 +1628,7 @@
*/
static const CompileTimeErrorCode MEMBER_WITH_CLASS_NAME =
const CompileTimeErrorCode('MEMBER_WITH_CLASS_NAME',
- "Class members cannot have the same name as the enclosing class");
+ "Class members can't have the same name as the enclosing class.");
/**
* 7.2 Getters: It is a compile-time error if a class has both a getter and a
@@ -1373,22 +1638,30 @@
* 0: the conflicting name of the getter and method
*/
static const CompileTimeErrorCode METHOD_AND_GETTER_WITH_SAME_NAME =
- const CompileTimeErrorCode('METHOD_AND_GETTER_WITH_SAME_NAME',
- "'{0}' cannot be used to name a method, there is already a getter with the same name");
+ const CompileTimeErrorCode(
+ 'METHOD_AND_GETTER_WITH_SAME_NAME',
+ "'{0}' can't be used to name a method, there is already a getter "
+ "with the same name.");
/**
* 12.1 Constants: A constant expression is ... a constant list literal.
*/
static const CompileTimeErrorCode MISSING_CONST_IN_LIST_LITERAL =
- const CompileTimeErrorCode('MISSING_CONST_IN_LIST_LITERAL',
- "List literals must be prefixed with 'const' when used as a constant expression");
+ const CompileTimeErrorCode(
+ 'MISSING_CONST_IN_LIST_LITERAL',
+ "List literals must be prefixed with 'const' when used as a constant "
+ "expression.",
+ "Try adding the keyword 'const' before the literal.");
/**
* 12.1 Constants: A constant expression is ... a constant map literal.
*/
static const CompileTimeErrorCode MISSING_CONST_IN_MAP_LITERAL =
- const CompileTimeErrorCode('MISSING_CONST_IN_MAP_LITERAL',
- "Map literals must be prefixed with 'const' when used as a constant expression");
+ const CompileTimeErrorCode(
+ 'MISSING_CONST_IN_MAP_LITERAL',
+ "Map literals must be prefixed with 'const' when used as a constant "
+ "expression.",
+ "Try adding the keyword 'const' before the literal.");
/**
* 9 Mixins: It is a compile-time error if a declared or derived mixin
@@ -1398,8 +1671,10 @@
* 0: the name of the mixin that is invalid
*/
static const CompileTimeErrorCode MIXIN_DECLARES_CONSTRUCTOR =
- const CompileTimeErrorCode('MIXIN_DECLARES_CONSTRUCTOR',
- "The class '{0}' cannot be used as a mixin because it declares a constructor");
+ const CompileTimeErrorCode(
+ 'MIXIN_DECLARES_CONSTRUCTOR',
+ "The class '{0}' can't be used as a mixin because it declares a "
+ "constructor.");
/**
* 9.1 Mixin Application: It is a compile-time error if the with clause of a
@@ -1411,8 +1686,10 @@
* See [EXTENDS_DEFERRED_CLASS], and [IMPLEMENTS_DEFERRED_CLASS].
*/
static const CompileTimeErrorCode MIXIN_DEFERRED_CLASS =
- const CompileTimeErrorCode('MIXIN_DEFERRED_CLASS',
- "This class cannot mixin the deferred class '{0}'");
+ const CompileTimeErrorCode(
+ 'MIXIN_DEFERRED_CLASS',
+ "This class can't mixin the deferred class '{0}'.",
+ "Try changing the import to not be deferred.");
/**
* Not yet in the spec, but consistent with VM behavior. It is a
@@ -1435,8 +1712,10 @@
* 0: the name of the mixin that is invalid
*/
static const CompileTimeErrorCode MIXIN_INHERITS_FROM_NOT_OBJECT =
- const CompileTimeErrorCode('MIXIN_INHERITS_FROM_NOT_OBJECT',
- "The class '{0}' cannot be used as a mixin because it extends a class other than Object");
+ const CompileTimeErrorCode(
+ 'MIXIN_INHERITS_FROM_NOT_OBJECT',
+ "The class '{0}' can't be used as a mixin because it extends a class "
+ "other than Object.");
/**
* 12.2 Null: It is a compile-time error for a class to attempt to extend or
@@ -1464,14 +1743,14 @@
*/
static const CompileTimeErrorCode MIXIN_OF_DISALLOWED_CLASS =
const CompileTimeErrorCode(
- 'MIXIN_OF_DISALLOWED_CLASS', "Classes cannot mixin '{0}'");
+ 'MIXIN_OF_DISALLOWED_CLASS', "Classes can't mixin '{0}'.");
/**
* Enum proposal: It is a compile-time error to subclass, mix-in or implement
* an enum.
*/
static const CompileTimeErrorCode MIXIN_OF_ENUM = const CompileTimeErrorCode(
- 'MIXIN_OF_ENUM', "Classes cannot mixin an enum");
+ 'MIXIN_OF_ENUM', "Classes can't mixin an enum.");
/**
* 9.1 Mixin Application: It is a compile-time error if <i>M</i> does not
@@ -1479,15 +1758,17 @@
*/
static const CompileTimeErrorCode MIXIN_OF_NON_CLASS =
const CompileTimeErrorCode(
- 'MIXIN_OF_NON_CLASS', "Classes can only mixin other classes");
+ 'MIXIN_OF_NON_CLASS', "Classes can only mixin other classes.");
/**
* 9 Mixins: It is a compile-time error if a declared or derived mixin refers
* to super.
*/
static const CompileTimeErrorCode MIXIN_REFERENCES_SUPER =
- const CompileTimeErrorCode('MIXIN_REFERENCES_SUPER',
- "The class '{0}' cannot be used as a mixin because it references 'super'");
+ const CompileTimeErrorCode(
+ 'MIXIN_REFERENCES_SUPER',
+ "The class '{0}' can't be used as a mixin because it references "
+ "'super'.");
/**
* 9.1 Mixin Application: It is a compile-time error if <i>S</i> does not
@@ -1495,7 +1776,7 @@
*/
static const CompileTimeErrorCode MIXIN_WITH_NON_CLASS_SUPERCLASS =
const CompileTimeErrorCode('MIXIN_WITH_NON_CLASS_SUPERCLASS',
- "Mixin can only be applied to class");
+ "Mixin can only be applied to class.");
/**
* 7.6.1 Generative Constructors: A generative constructor may be redirecting,
@@ -1504,7 +1785,8 @@
static const CompileTimeErrorCode
MULTIPLE_REDIRECTING_CONSTRUCTOR_INVOCATIONS = const CompileTimeErrorCode(
'MULTIPLE_REDIRECTING_CONSTRUCTOR_INVOCATIONS',
- "Constructor may have at most one 'this' redirection");
+ "Constructors can have at most one 'this' redirection.",
+ "Try removing all but one of the redirections.");
/**
* 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor.
@@ -1512,20 +1794,28 @@
* list or a compile time error occurs.
*/
static const CompileTimeErrorCode MULTIPLE_SUPER_INITIALIZERS =
- const CompileTimeErrorCode('MULTIPLE_SUPER_INITIALIZERS',
- "Constructor may have at most one 'super' initializer");
+ const CompileTimeErrorCode(
+ 'MULTIPLE_SUPER_INITIALIZERS',
+ "Constructor may have at most one 'super' initializer.",
+ "Try removing all but one of the 'super' initializers.");
/**
- * 11 Metadata: Metadata consists of a series of annotations, each of which
+ * 15 Metadata: Metadata consists of a series of annotations, each of which
* begin with the character @, followed by a constant expression that must be
* either a reference to a compile-time constant variable, or a call to a
* constant constructor.
*/
static const CompileTimeErrorCode NO_ANNOTATION_CONSTRUCTOR_ARGUMENTS =
- const CompileTimeErrorCode('NO_ANNOTATION_CONSTRUCTOR_ARGUMENTS',
- "Annotation creation must have arguments");
+ const CompileTimeErrorCode(
+ 'NO_ANNOTATION_CONSTRUCTOR_ARGUMENTS',
+ "Annotation creation must have arguments.",
+ "Try adding an empty argument list.");
/**
+ * This error is generated if a constructor declaration has an implicit
+ * invocation of a zero argument super constructor (`super()`), but the
+ * superclass does not define a zero argument constructor.
+ *
* 7.6.1 Generative Constructors: If no superinitializer is provided, an
* implicit superinitializer of the form <b>super</b>() is added at the end of
* <i>k</i>'s initializer list, unless the enclosing class is class
@@ -1534,12 +1824,24 @@
* 7.6.1 Generative constructors. It is a compile-time error if class <i>S</i>
* does not declare a generative constructor named <i>S</i> (respectively
* <i>S.id</i>)
+ *
+ * Parameters:
+ * 0: the name of the superclass that does not define the implicitly invoked
+ * constructor
*/
static const CompileTimeErrorCode NO_DEFAULT_SUPER_CONSTRUCTOR_EXPLICIT =
- const CompileTimeErrorCode('NO_DEFAULT_SUPER_CONSTRUCTOR_EXPLICIT',
- "The class '{0}' does not have a default constructor");
+ const CompileTimeErrorCode(
+ 'NO_DEFAULT_SUPER_CONSTRUCTOR_EXPLICIT',
+ "The superclass '{0}' doesn't have a zero argument constructor.",
+ "Try declaring a zero argument constructor in '{0}', or "
+ "explicitly invoking a different constructor in '{0}'.");
/**
+ * This error is generated if a class declaration has an implicit default
+ * constructor, which implicitly invokes a zero argument super constructor
+ * (`super()`), but the superclass does not define a zero argument
+ * constructor.
+ *
* 7.6 Constructors: Iff no constructor is specified for a class <i>C</i>, it
* implicitly has a default constructor C() : <b>super<b>() {}, unless
* <i>C</i> is class <i>Object</i>.
@@ -1547,10 +1849,19 @@
* 7.6.1 Generative constructors. It is a compile-time error if class <i>S</i>
* does not declare a generative constructor named <i>S</i> (respectively
* <i>S.id</i>)
+ *
+ * Parameters:
+ * 0: the name of the superclass that does not define the implicitly invoked
+ * constructor
+ * 1: the name of the subclass that does not contain any explicit constructors
*/
static const CompileTimeErrorCode NO_DEFAULT_SUPER_CONSTRUCTOR_IMPLICIT =
- const CompileTimeErrorCode('NO_DEFAULT_SUPER_CONSTRUCTOR_IMPLICIT',
- "The class '{0}' does not have a default constructor");
+ const CompileTimeErrorCode(
+ 'NO_DEFAULT_SUPER_CONSTRUCTOR_IMPLICIT',
+ "The superclass '{0}' doesn't have a zero argument constructor.",
+ "Try declaring a zero argument constructor in '{0}', or "
+ "declaring a constructor in {1} that explicitly invokes a "
+ "constructor in '{0}'.");
/**
* 13.2 Expression Statements: It is a compile-time error if a non-constant
@@ -1558,8 +1869,10 @@
* statement is expected.
*/
static const CompileTimeErrorCode NON_CONST_MAP_AS_EXPRESSION_STATEMENT =
- const CompileTimeErrorCode('NON_CONST_MAP_AS_EXPRESSION_STATEMENT',
- "A non-constant map literal without type arguments cannot be used as an expression statement");
+ const CompileTimeErrorCode(
+ 'NON_CONST_MAP_AS_EXPRESSION_STATEMENT',
+ "A non-constant map literal without type arguments can't be used as "
+ "an expression statement.");
/**
* 13.9 Switch: Given a switch statement of the form <i>switch (e) {
@@ -1574,7 +1887,7 @@
*/
static const CompileTimeErrorCode NON_CONSTANT_CASE_EXPRESSION =
const CompileTimeErrorCode(
- 'NON_CONSTANT_CASE_EXPRESSION', "Case expressions must be constant");
+ 'NON_CONSTANT_CASE_EXPRESSION', "Case expressions must be constant.");
/**
* 13.9 Switch: Given a switch statement of the form <i>switch (e) {
@@ -1594,7 +1907,10 @@
NON_CONSTANT_CASE_EXPRESSION_FROM_DEFERRED_LIBRARY =
const CompileTimeErrorCode(
'NON_CONSTANT_CASE_EXPRESSION_FROM_DEFERRED_LIBRARY',
- "Constant values from a deferred library cannot be used as a case expression");
+ "Constant values from a deferred library can't be used as a case "
+ "expression.",
+ "Try re-writing the switch as a series of if statements, or "
+ "changing the import to not be deferred.");
/**
* 6.2.2 Optional Formals: It is a compile-time error if the default value of
@@ -1602,7 +1918,7 @@
*/
static const CompileTimeErrorCode NON_CONSTANT_DEFAULT_VALUE =
const CompileTimeErrorCode('NON_CONSTANT_DEFAULT_VALUE',
- "Default values of an optional parameter must be constant");
+ "Default values of an optional parameter must be constant.");
/**
* 6.2.2 Optional Formals: It is a compile-time error if the default value of
@@ -1615,15 +1931,20 @@
NON_CONSTANT_DEFAULT_VALUE_FROM_DEFERRED_LIBRARY =
const CompileTimeErrorCode(
'NON_CONSTANT_DEFAULT_VALUE_FROM_DEFERRED_LIBRARY',
- "Constant values from a deferred library cannot be used as a default parameter value");
+ "Constant values from a deferred library can't be used as a default "
+ "parameter value.",
+ "Try leaving the default as null and initializing the parameter "
+ "inside the function body.");
/**
* 12.6 Lists: It is a compile time error if an element of a constant list
* literal is not a compile-time constant.
*/
static const CompileTimeErrorCode NON_CONSTANT_LIST_ELEMENT =
- const CompileTimeErrorCode('NON_CONSTANT_LIST_ELEMENT',
- "'const' lists must have all constant values");
+ const CompileTimeErrorCode(
+ 'NON_CONSTANT_LIST_ELEMENT',
+ "The values in a const list literal must be constants.",
+ "Try removing the keyword 'const' from the map literal.");
/**
* 12.6 Lists: It is a compile time error if an element of a constant list
@@ -1636,7 +1957,9 @@
NON_CONSTANT_LIST_ELEMENT_FROM_DEFERRED_LIBRARY =
const CompileTimeErrorCode(
'NON_CONSTANT_LIST_ELEMENT_FROM_DEFERRED_LIBRARY',
- "Constant values from a deferred library cannot be used as values in a 'const' list");
+ "Constant values from a deferred library can't be used as values in "
+ "a 'const' list.",
+ "Try removing the keyword 'const' from the list literal.");
/**
* 12.7 Maps: It is a compile time error if either a key or a value of an
@@ -1644,7 +1967,9 @@
*/
static const CompileTimeErrorCode NON_CONSTANT_MAP_KEY =
const CompileTimeErrorCode(
- 'NON_CONSTANT_MAP_KEY', "The keys in a map must be constant");
+ 'NON_CONSTANT_MAP_KEY',
+ "The keys in a const map literal must be constant.",
+ "Try removing the keyword 'const' from the map literal.");
/**
* 12.7 Maps: It is a compile time error if either a key or a value of an
@@ -1654,16 +1979,21 @@
* not qualified by a deferred prefix.
*/
static const CompileTimeErrorCode NON_CONSTANT_MAP_KEY_FROM_DEFERRED_LIBRARY =
- const CompileTimeErrorCode('NON_CONSTANT_MAP_KEY_FROM_DEFERRED_LIBRARY',
- "Constant values from a deferred library cannot be used as keys in a map");
+ const CompileTimeErrorCode(
+ 'NON_CONSTANT_MAP_KEY_FROM_DEFERRED_LIBRARY',
+ "Constant values from a deferred library can't be used as keys in a "
+ "const map literal.",
+ "Try removing the keyword 'const' from the map literal.");
/**
* 12.7 Maps: It is a compile time error if either a key or a value of an
* entry in a constant map literal is not a compile-time constant.
*/
static const CompileTimeErrorCode NON_CONSTANT_MAP_VALUE =
- const CompileTimeErrorCode('NON_CONSTANT_MAP_VALUE',
- "The values in a 'const' map must be constant");
+ const CompileTimeErrorCode(
+ 'NON_CONSTANT_MAP_VALUE',
+ "The values in a const map literal must be constant.",
+ "Try removing the keyword 'const' from the map literal.");
/**
* 12.7 Maps: It is a compile time error if either a key or a value of an
@@ -1675,10 +2005,12 @@
static const CompileTimeErrorCode
NON_CONSTANT_MAP_VALUE_FROM_DEFERRED_LIBRARY = const CompileTimeErrorCode(
'NON_CONSTANT_MAP_VALUE_FROM_DEFERRED_LIBRARY',
- "Constant values from a deferred library cannot be used as values in a 'const' map");
+ "Constant values from a deferred library can't be used as values in "
+ "a const map literal.",
+ "Try removing the keyword 'const' from the map literal.");
/**
- * 11 Metadata: Metadata consists of a series of annotations, each of which
+ * 15 Metadata: Metadata consists of a series of annotations, each of which
* begin with the character @, followed by a constant expression that must be
* either a reference to a compile-time constant variable, or a call to a
* constant constructor.
@@ -1688,7 +2020,7 @@
*/
static const CompileTimeErrorCode NON_CONSTANT_ANNOTATION_CONSTRUCTOR =
const CompileTimeErrorCode('NON_CONSTANT_ANNOTATION_CONSTRUCTOR',
- "Annotation creation can use only 'const' constructor");
+ "Annotation creation can only call a const constructor.");
/**
* 7.6.3 Constant Constructors: Any expression that appears within the
@@ -1697,7 +2029,7 @@
*/
static const CompileTimeErrorCode NON_CONSTANT_VALUE_IN_INITIALIZER =
const CompileTimeErrorCode('NON_CONSTANT_VALUE_IN_INITIALIZER',
- "Initializer expressions in constant constructors must be constants");
+ "Initializer expressions in constant constructors must be constants.");
/**
* 7.6.3 Constant Constructors: Any expression that appears within the
@@ -1711,13 +2043,15 @@
NON_CONSTANT_VALUE_IN_INITIALIZER_FROM_DEFERRED_LIBRARY =
const CompileTimeErrorCode(
'NON_CONSTANT_VALUE_IN_INITIALIZER_FROM_DEFERRED_LIBRARY',
- "Constant values from a deferred library cannot be used as constant initializers");
+ "Constant values from a deferred library can't be used as constant "
+ "initializers.",
+ "Try changing the import to not be deferred.");
/**
* 12.14.2 Binding Actuals to Formals: It is a static warning if <i>m < h</i>
* or if <i>m > n</i>.
*
- * 12.11.2 Const: It is a compile-time error if evaluation of a constant
+ * 16.12.2 Const: It is a compile-time error if evaluation of a constant
* object results in an uncaught exception being thrown.
*
* Parameters:
@@ -1725,8 +2059,10 @@
* 1: the actual number of positional arguments given
*/
static const CompileTimeErrorCode NOT_ENOUGH_REQUIRED_ARGUMENTS =
- const CompileTimeErrorCode('NOT_ENOUGH_REQUIRED_ARGUMENTS',
- "{0} required argument(s) expected, but {1} found");
+ const CompileTimeErrorCode(
+ 'NOT_ENOUGH_REQUIRED_ARGUMENTS',
+ "{0} required argument(s) expected, but {1} found.",
+ "Try adding the missing arguments.");
/**
* 7.6.1 Generative Constructors: Let <i>C</i> be the class in which the
@@ -1736,23 +2072,29 @@
* (respectively <i>S.id</i>)
*/
static const CompileTimeErrorCode NON_GENERATIVE_CONSTRUCTOR =
- const CompileTimeErrorCode('NON_GENERATIVE_CONSTRUCTOR',
- "The generative constructor '{0}' expected, but factory found");
+ const CompileTimeErrorCode(
+ 'NON_GENERATIVE_CONSTRUCTOR',
+ "The generative constructor '{0}' expected, but factory found.",
+ "Try calling a different constructor in the superclass, or "
+ "making the called constructor not be a factory constructor.");
/**
* 7.9 Superclasses: It is a compile-time error to specify an extends clause
* for class Object.
*/
static const CompileTimeErrorCode OBJECT_CANNOT_EXTEND_ANOTHER_CLASS =
- const CompileTimeErrorCode('OBJECT_CANNOT_EXTEND_ANOTHER_CLASS', "");
+ const CompileTimeErrorCode('OBJECT_CANNOT_EXTEND_ANOTHER_CLASS',
+ "The class 'Object' can't extend any other class.");
/**
* 7.1.1 Operators: It is a compile-time error to declare an optional
* parameter in an operator.
*/
static const CompileTimeErrorCode OPTIONAL_PARAMETER_IN_OPERATOR =
- const CompileTimeErrorCode('OPTIONAL_PARAMETER_IN_OPERATOR',
- "Optional parameters are not allowed when defining an operator");
+ const CompileTimeErrorCode(
+ 'OPTIONAL_PARAMETER_IN_OPERATOR',
+ "Optional parameters aren't allowed when defining an operator.",
+ "Try removing the optional parameters.");
/**
* 14.3 Parts: It is a compile time error if the contents of the URI are not a
@@ -1762,24 +2104,33 @@
* 0: the uri pointing to a non-library declaration
*/
static const CompileTimeErrorCode PART_OF_NON_PART =
- const CompileTimeErrorCode('PART_OF_NON_PART',
- "The included part '{0}' must have a part-of directive");
+ const CompileTimeErrorCode(
+ 'PART_OF_NON_PART',
+ "The included part '{0}' must have a part-of directive.",
+ "Try adding a part-of directive to '{0}'.");
/**
* 14.1 Imports: It is a compile-time error if the current library declares a
* top-level member named <i>p</i>.
*/
static const CompileTimeErrorCode PREFIX_COLLIDES_WITH_TOP_LEVEL_MEMBER =
- const CompileTimeErrorCode('PREFIX_COLLIDES_WITH_TOP_LEVEL_MEMBER',
- "The name '{0}' is already used as an import prefix and cannot be used to name a top-level element");
+ const CompileTimeErrorCode(
+ 'PREFIX_COLLIDES_WITH_TOP_LEVEL_MEMBER',
+ "The name '{0}' is already used as an import prefix and can't be "
+ "used to name a top-level element.",
+ "Try renaming either the top-level element or the prefix.");
/**
* 16.32 Identifier Reference: If d is a prefix p, a compile-time error
* occurs unless the token immediately following d is '.'.
*/
static const CompileTimeErrorCode PREFIX_IDENTIFIER_NOT_FOLLOWED_BY_DOT =
- const CompileTimeErrorCode('PREFIX_IDENTIFIER_NOT_FOLLOWED_BY_DOT',
- "The name '{0}' refers to an import prefix, so it must be followed by '.'");
+ const CompileTimeErrorCode(
+ 'PREFIX_IDENTIFIER_NOT_FOLLOWED_BY_DOT',
+ "The name '{0}' refers to an import prefix, so it must be followed "
+ "by '.'.",
+ "Try correcting the name to refer to something other than a prefix, or "
+ "renaming the prefix.");
/**
* 6.2.2 Optional Formals: It is a compile-time error if the name of a named
@@ -1787,7 +2138,7 @@
*/
static const CompileTimeErrorCode PRIVATE_OPTIONAL_PARAMETER =
const CompileTimeErrorCode('PRIVATE_OPTIONAL_PARAMETER',
- "Named optional parameters cannot start with an underscore");
+ "Named optional parameters can't start with an underscore.");
/**
* 12.1 Constants: It is a compile-time error if the value of a compile-time
@@ -1795,7 +2146,7 @@
*/
static const CompileTimeErrorCode RECURSIVE_COMPILE_TIME_CONSTANT =
const CompileTimeErrorCode('RECURSIVE_COMPILE_TIME_CONSTANT',
- "Compile-time constant expression depends on itself");
+ "Compile-time constant expression depends on itself.");
/**
* 7.6.1 Generative Constructors: A generative constructor may be redirecting,
@@ -1809,7 +2160,7 @@
*/
static const CompileTimeErrorCode RECURSIVE_CONSTRUCTOR_REDIRECT =
const CompileTimeErrorCode('RECURSIVE_CONSTRUCTOR_REDIRECT',
- "Cycle in redirecting generative constructors");
+ "Cycle in redirecting generative constructors.");
/**
* 7.6.2 Factories: It is a compile-time error if a redirecting factory
@@ -1818,7 +2169,7 @@
*/
static const CompileTimeErrorCode RECURSIVE_FACTORY_REDIRECT =
const CompileTimeErrorCode('RECURSIVE_FACTORY_REDIRECT',
- "Cycle in redirecting factory constructors");
+ "Cycle in redirecting factory constructors.");
/**
* 7.10 Superinterfaces: It is a compile-time error if the interface of a
@@ -1836,7 +2187,7 @@
*/
static const CompileTimeErrorCode RECURSIVE_INTERFACE_INHERITANCE =
const CompileTimeErrorCode('RECURSIVE_INTERFACE_INHERITANCE',
- "'{0}' cannot be a superinterface of itself: {1}");
+ "'{0}' can't be a superinterface of itself: {1}.");
/**
* 7.10 Superinterfaces: It is a compile-time error if the interface of a
@@ -1855,7 +2206,7 @@
RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_EXTENDS =
const CompileTimeErrorCode(
'RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_EXTENDS',
- "'{0}' cannot extend itself");
+ "'{0}' can't extend itself.");
/**
* 7.10 Superinterfaces: It is a compile-time error if the interface of a
@@ -1874,7 +2225,7 @@
RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_IMPLEMENTS =
const CompileTimeErrorCode(
'RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_IMPLEMENTS',
- "'{0}' cannot implement itself");
+ "'{0}' can't implement itself.");
/**
* 7.10 Superinterfaces: It is a compile-time error if the interface of a
@@ -1893,31 +2244,40 @@
RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_WITH =
const CompileTimeErrorCode(
'RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_WITH',
- "'{0}' cannot use itself as a mixin");
+ "'{0}' can't use itself as a mixin.");
/**
* 7.6.2 Factories: It is a compile-time error if <i>k</i> is prefixed with
* the const modifier but <i>k'</i> is not a constant constructor.
*/
static const CompileTimeErrorCode REDIRECT_TO_MISSING_CONSTRUCTOR =
- const CompileTimeErrorCode('REDIRECT_TO_MISSING_CONSTRUCTOR',
- "The constructor '{0}' could not be found in '{1}'");
+ const CompileTimeErrorCode(
+ 'REDIRECT_TO_MISSING_CONSTRUCTOR',
+ "The constructor '{0}' couldn't be found in '{1}'.",
+ "Try redirecting to a different constructor, or "
+ "define the constructor named '{0}'.");
/**
* 7.6.2 Factories: It is a compile-time error if <i>k</i> is prefixed with
* the const modifier but <i>k'</i> is not a constant constructor.
*/
static const CompileTimeErrorCode REDIRECT_TO_NON_CLASS =
- const CompileTimeErrorCode('REDIRECT_TO_NON_CLASS',
- "The name '{0}' is not a type and cannot be used in a redirected constructor");
+ const CompileTimeErrorCode(
+ 'REDIRECT_TO_NON_CLASS',
+ "The name '{0}' isn't a type and can't be used in a redirected "
+ "constructor.",
+ "Try redirecting to a different constructor.");
/**
* 7.6.2 Factories: It is a compile-time error if <i>k</i> is prefixed with
* the const modifier but <i>k'</i> is not a constant constructor.
*/
static const CompileTimeErrorCode REDIRECT_TO_NON_CONST_CONSTRUCTOR =
- const CompileTimeErrorCode('REDIRECT_TO_NON_CONST_CONSTRUCTOR',
- "Constant factory constructor cannot delegate to a non-constant constructor");
+ const CompileTimeErrorCode(
+ 'REDIRECT_TO_NON_CONST_CONSTRUCTOR',
+ "Constant factory constructor can't delegate to a non-constant "
+ "constructor.",
+ "Try redirecting to a different constructor.");
/**
* 7.6.1 Generative constructors: A generative constructor may be
@@ -1925,8 +2285,11 @@
* generative constructor.
*/
static const CompileTimeErrorCode REDIRECT_GENERATIVE_TO_MISSING_CONSTRUCTOR =
- const CompileTimeErrorCode('REDIRECT_GENERATIVE_TO_MISSING_CONSTRUCTOR',
- "The constructor '{0}' could not be found in '{1}'");
+ const CompileTimeErrorCode(
+ 'REDIRECT_GENERATIVE_TO_MISSING_CONSTRUCTOR',
+ "The constructor '{0}' couldn't be found in '{1}'.",
+ "Try redirecting to a different constructor, or "
+ "defining the constructor named '{0}'.");
/**
* 7.6.1 Generative constructors: A generative constructor may be
@@ -1937,7 +2300,8 @@
REDIRECT_GENERATIVE_TO_NON_GENERATIVE_CONSTRUCTOR =
const CompileTimeErrorCode(
'REDIRECT_GENERATIVE_TO_NON_GENERATIVE_CONSTRUCTOR',
- "Generative constructor cannot redirect to a factory constructor");
+ "Generative constructor can't redirect to a factory constructor.",
+ "Try redirecting to a different constructor.");
/**
* 5 Variables: A local variable may only be referenced at a source code
@@ -1945,8 +2309,12 @@
* compile-time error occurs.
*/
static const CompileTimeErrorCode REFERENCED_BEFORE_DECLARATION =
- const CompileTimeErrorCode('REFERENCED_BEFORE_DECLARATION',
- "Local variable '{0}' cannot be referenced before it is declared");
+ const CompileTimeErrorCode(
+ 'REFERENCED_BEFORE_DECLARATION',
+ "Local variable '{0}' can't be referenced before it is declared.",
+ "Try moving the declaration to before the first use, or "
+ "renaming the local variable so that it doesn't hide a name from an "
+ "enclosing scope.");
/**
* 12.8.1 Rethrow: It is a compile-time error if an expression of the form
@@ -1956,7 +2324,8 @@
const CompileTimeErrorCode(
'RETHROW_OUTSIDE_CATCH',
"Rethrow must be inside of catch clause.",
- "Try moving the expression into a catch clause, or using a 'throw' expression.");
+ "Try moving the expression into a catch clause, or using a 'throw' "
+ "expression.");
/**
* 13.12 Return: It is a compile-time error if a return statement of the form
@@ -1975,15 +2344,19 @@
static const CompileTimeErrorCode RETURN_IN_GENERATOR = const CompileTimeErrorCode(
'RETURN_IN_GENERATOR',
"Can't return a value from a generator function (using the '{0}' modifier).",
- "Try removing the value, replacing 'return' with 'yield' or changing the method body modifier.");
+ "Try removing the value, replacing 'return' with 'yield' or changing the "
+ "method body modifier.");
/**
* 14.1 Imports: It is a compile-time error if a prefix used in a deferred
* import is used in another import clause.
*/
static const CompileTimeErrorCode SHARED_DEFERRED_PREFIX =
- const CompileTimeErrorCode('SHARED_DEFERRED_PREFIX',
- "The prefix of a deferred import cannot be used in other import directives");
+ const CompileTimeErrorCode(
+ 'SHARED_DEFERRED_PREFIX',
+ "The prefix of a deferred import can't be used in other import "
+ "directives.",
+ "Try renaming one of the prefixes.");
/**
* 12.15.4 Super Invocation: A super method invocation <i>i</i> has the form
@@ -1995,8 +2368,8 @@
* method or variable initializer.
*/
static const CompileTimeErrorCode SUPER_IN_INVALID_CONTEXT =
- const CompileTimeErrorCode(
- 'SUPER_IN_INVALID_CONTEXT', "Invalid context for 'super' invocation");
+ const CompileTimeErrorCode('SUPER_IN_INVALID_CONTEXT',
+ "Invalid context for 'super' invocation.");
/**
* 7.6.1 Generative Constructors: A generative constructor may be redirecting,
@@ -2004,7 +2377,7 @@
*/
static const CompileTimeErrorCode SUPER_IN_REDIRECTING_CONSTRUCTOR =
const CompileTimeErrorCode('SUPER_IN_REDIRECTING_CONSTRUCTOR',
- "The redirecting constructor cannot have a 'super' initializer");
+ "The redirecting constructor can't have a 'super' initializer.");
/**
* 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor. It
@@ -2012,7 +2385,8 @@
* includes a superinitializer.
*/
static const CompileTimeErrorCode SUPER_INITIALIZER_IN_OBJECT =
- const CompileTimeErrorCode('SUPER_INITIALIZER_IN_OBJECT', "");
+ const CompileTimeErrorCode('SUPER_INITIALIZER_IN_OBJECT',
+ "The class 'Object' can't invoke a constructor from a superclass.");
/**
* 12.11 Instance Creation: It is a static type warning if any of the type
@@ -2035,22 +2409,27 @@
*/
static const CompileTimeErrorCode TYPE_ARGUMENT_NOT_MATCHING_BOUNDS =
const CompileTimeErrorCode(
- 'TYPE_ARGUMENT_NOT_MATCHING_BOUNDS', "'{0}' does not extend '{1}'");
+ 'TYPE_ARGUMENT_NOT_MATCHING_BOUNDS',
+ "'{0}' doesn't extend '{1}'.",
+ "Try using a type that is or is a subclass of '{1}'.");
/**
* 15.3.1 Typedef: Any self reference, either directly, or recursively via
* another typedef, is a compile time error.
*/
static const CompileTimeErrorCode TYPE_ALIAS_CANNOT_REFERENCE_ITSELF =
- const CompileTimeErrorCode('TYPE_ALIAS_CANNOT_REFERENCE_ITSELF',
- "Type alias cannot reference itself directly or recursively via another typedef");
+ const CompileTimeErrorCode(
+ 'TYPE_ALIAS_CANNOT_REFERENCE_ITSELF',
+ "Typedefs can't reference themselves directly or recursively via "
+ "another typedef.");
/**
- * 12.11.2 Const: It is a compile-time error if <i>T</i> is not a class
+ * 16.12.2 Const: It is a compile-time error if <i>T</i> is not a class
* accessible in the current scope, optionally followed by type arguments.
*/
static const CompileTimeErrorCode UNDEFINED_CLASS =
- const CompileTimeErrorCode('UNDEFINED_CLASS', "Undefined class '{0}'");
+ const CompileTimeErrorCode('UNDEFINED_CLASS', "Undefined class '{0}'.",
+ "Try defining the class.");
/**
* 7.6.1 Generative Constructors: Let <i>C</i> be the class in which the
@@ -2058,10 +2437,17 @@
* Let <i>k</i> be a generative constructor. It is a compile-time error if
* class <i>S</i> does not declare a generative constructor named <i>S</i>
* (respectively <i>S.id</i>)
+ *
+ * Parameters:
+ * 0: the name of the superclass that does not define the invoked constructor
+ * 1: the name of the constructor being invoked
*/
static const CompileTimeErrorCode UNDEFINED_CONSTRUCTOR_IN_INITIALIZER =
- const CompileTimeErrorCode('UNDEFINED_CONSTRUCTOR_IN_INITIALIZER',
- "The class '{0}' does not have a generative constructor '{1}'");
+ const CompileTimeErrorCode(
+ 'UNDEFINED_CONSTRUCTOR_IN_INITIALIZER',
+ "The class '{0}' doesn't have a constructor named '{1}'.",
+ "Try defining a constructor named '{1}' in '{0}', or "
+ "invoking a different constructor.");
/**
* 7.6.1 Generative Constructors: Let <i>C</i> be the class in which the
@@ -2069,11 +2455,16 @@
* Let <i>k</i> be a generative constructor. It is a compile-time error if
* class <i>S</i> does not declare a generative constructor named <i>S</i>
* (respectively <i>S.id</i>)
+ *
+ * Parameters:
+ * 0: the name of the superclass that does not define the invoked constructor
*/
static const CompileTimeErrorCode
UNDEFINED_CONSTRUCTOR_IN_INITIALIZER_DEFAULT = const CompileTimeErrorCode(
'UNDEFINED_CONSTRUCTOR_IN_INITIALIZER_DEFAULT',
- "The class '{0}' does not have a default generative constructor");
+ "The class '{0}' doesn't have an unnamed constructor.",
+ "Try defining an unnamed constructor in '{0}', or "
+ "invoking a different constructor.");
/**
* 12.14.2 Binding Actuals to Formals: Furthermore, each <i>q<sub>i</sub></i>,
@@ -2081,15 +2472,18 @@
* {<i>p<sub>n+1</sub></i> ... <i>p<sub>n+k</sub></i>} or a static warning
* occurs.
*
- * 12.11.2 Const: It is a compile-time error if evaluation of a constant
+ * 16.12.2 Const: It is a compile-time error if evaluation of a constant
* object results in an uncaught exception being thrown.
*
* Parameters:
* 0: the name of the requested named parameter
*/
static const CompileTimeErrorCode UNDEFINED_NAMED_PARAMETER =
- const CompileTimeErrorCode('UNDEFINED_NAMED_PARAMETER',
- "The named parameter '{0}' is not defined");
+ const CompileTimeErrorCode(
+ 'UNDEFINED_NAMED_PARAMETER',
+ "The named parameter '{0}' isn't defined.",
+ "Try correcting the name to an existing named parameter's name, or "
+ "defining a named parameter with the name '{0}'.");
/**
* 14.2 Exports: It is a compile-time error if the compilation unit found at
@@ -2108,7 +2502,10 @@
*/
static const CompileTimeErrorCode URI_DOES_NOT_EXIST =
const CompileTimeErrorCode(
- 'URI_DOES_NOT_EXIST', "Target of URI does not exist: '{0}'");
+ 'URI_DOES_NOT_EXIST',
+ "Target of URI doesn't exist: '{0}'.",
+ "Try creating the file referenced by the URI, or "
+ "try using a URI for a file that does exist.");
/**
* Just like [URI_DOES_NOT_EXIST], but used when the URI refers to a file that
@@ -2120,8 +2517,11 @@
* See [INVALID_URI], [URI_DOES_NOT_EXIST].
*/
static const CompileTimeErrorCode URI_HAS_NOT_BEEN_GENERATED =
- const CompileTimeErrorCode('URI_HAS_NOT_BEEN_GENERATED',
- "Target of URI has not been generated: '{0}'");
+ const CompileTimeErrorCode(
+ 'URI_HAS_NOT_BEEN_GENERATED',
+ "Target of URI hasn't been generated: '{0}'.",
+ "Try running the generator that will generate the file referenced by "
+ "the URI.");
/**
* 14.1 Imports: It is a compile-time error if <i>x</i> is not a compile-time
@@ -2136,7 +2536,7 @@
*/
static const CompileTimeErrorCode URI_WITH_INTERPOLATION =
const CompileTimeErrorCode(
- 'URI_WITH_INTERPOLATION', "URIs cannot use string interpolation");
+ 'URI_WITH_INTERPOLATION', "URIs can't use string interpolation.");
/**
* 7.1.1 Operators: It is a compile-time error if the arity of the
@@ -2154,7 +2554,7 @@
*/
static const CompileTimeErrorCode WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR =
const CompileTimeErrorCode('WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR',
- "Operator '{0}' should declare exactly {1} parameter(s), but {2} found");
+ "Operator '{0}' should declare exactly {1} parameter(s), but {2} found.");
/**
* 7.1.1 Operators: It is a compile time error if the arity of the
@@ -2167,7 +2567,7 @@
WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR_MINUS =
const CompileTimeErrorCode(
'WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR_MINUS',
- "Operator '-' should declare 0 or 1 parameter, but {0} found");
+ "Operator '-' should declare 0 or 1 parameter, but {0} found.");
/**
* 7.3 Setters: It is a compile-time error if a setter's formal parameter list
@@ -2175,23 +2575,29 @@
*/
static const CompileTimeErrorCode WRONG_NUMBER_OF_PARAMETERS_FOR_SETTER =
const CompileTimeErrorCode('WRONG_NUMBER_OF_PARAMETERS_FOR_SETTER',
- "Setters should declare exactly one required parameter");
+ "Setters should declare exactly one required parameter.");
/**
* ?? Yield: It is a compile-time error if a yield statement appears in a
* function that is not a generator function.
*/
static const CompileTimeErrorCode YIELD_EACH_IN_NON_GENERATOR =
- const CompileTimeErrorCode('YIELD_EACH_IN_NON_GENERATOR',
- "Yield-each statements must be in a generator function (one marked with either 'async*' or 'sync*')");
+ const CompileTimeErrorCode(
+ 'YIELD_EACH_IN_NON_GENERATOR',
+ "Yield-each statements must be in a generator function "
+ "(one marked with either 'async*' or 'sync*').",
+ "Try adding 'async*' or 'sync*' to the enclosing function.");
/**
* ?? Yield: It is a compile-time error if a yield statement appears in a
* function that is not a generator function.
*/
static const CompileTimeErrorCode YIELD_IN_NON_GENERATOR =
- const CompileTimeErrorCode('YIELD_IN_NON_GENERATOR',
- "Yield statements must be in a generator function (one marked with either 'async*' or 'sync*')");
+ const CompileTimeErrorCode(
+ 'YIELD_IN_NON_GENERATOR',
+ "Yield statements must be in a generator function "
+ "(one marked with either 'async*' or 'sync*').",
+ "Try adding 'async*' or 'sync*' to the enclosing function.");
/**
* Initialize a newly created error code to have the given [name]. The message
@@ -2215,7 +2621,7 @@
*/
class HintCode extends ErrorCode {
/**
- * When an abstract supertype member is references with `super` as its target,
+ * When an abstract supertype member is referenced with `super` as its target,
* it cannot be overridden, so it is always a runtime error.
*
* Parameters:
@@ -2224,8 +2630,7 @@
*/
static const HintCode ABSTRACT_SUPER_MEMBER_REFERENCE = const HintCode(
'ABSTRACT_SUPER_MEMBER_REFERENCE',
- "The {0} '{1}' is always abstract in the supertype.",
- null);
+ "The {0} '{1}' is always abstract in the supertype.");
/**
* This hint is generated anywhere where the
@@ -2238,8 +2643,7 @@
*/
static const HintCode ARGUMENT_TYPE_NOT_ASSIGNABLE = const HintCode(
'ARGUMENT_TYPE_NOT_ASSIGNABLE',
- "The argument type '{0}' cannot be assigned to the parameter type '{1}'.",
- null);
+ "The argument type '{0}' can't be assigned to the parameter type '{1}'.");
/**
* When the target expression uses '?.' operator, it can be `null`, so all the
@@ -2247,14 +2651,18 @@
*/
static const HintCode CAN_BE_NULL_AFTER_NULL_AWARE = const HintCode(
'CAN_BE_NULL_AFTER_NULL_AWARE',
- "The expression uses '?.', so can be 'null'",
- "Replace the '.' with a '?.' in the invocation");
+ "The target expression uses '?.', so its value can be null.",
+ "Replace the '.' with a '?.' in the invocation.");
/**
* Dead code is code that is never reached, this can happen for instance if a
* statement follows a return statement.
*/
- static const HintCode DEAD_CODE = const HintCode('DEAD_CODE', "Dead code");
+ static const HintCode DEAD_CODE = const HintCode(
+ 'DEAD_CODE',
+ "Dead code.",
+ "Try removing the code, or "
+ "fixing the code before it so that it can be reached.");
/**
* Dead code is code that is never reached. This case covers cases where the
@@ -2262,7 +2670,10 @@
*/
static const HintCode DEAD_CODE_CATCH_FOLLOWING_CATCH = const HintCode(
'DEAD_CODE_CATCH_FOLLOWING_CATCH',
- "Dead code, catch clauses after a 'catch (e)' or an 'on Object catch (e)' are never reached");
+ "Dead code: catch clauses after a 'catch (e)' or "
+ "an 'on Object catch (e)' are never reached.",
+ "Try reordering the catch clauses so that they can be reached, or "
+ "removing the unreachable catch clauses.");
/**
* Dead code is code that is never reached. This case covers cases where the
@@ -2275,7 +2686,10 @@
*/
static const HintCode DEAD_CODE_ON_CATCH_SUBTYPE = const HintCode(
'DEAD_CODE_ON_CATCH_SUBTYPE',
- "Dead code, this on-catch block will never be executed since '{0}' is a subtype of '{1}'");
+ "Dead code: this on-catch block will never be executed because '{0}' is "
+ "a subtype of '{1}' and hence will have been caught above.",
+ "Try reordering the catch clauses so that this block can be reached, or "
+ "removing the unreachable catch clause.");
/**
* Deprecated members should not be invoked or used.
@@ -2283,52 +2697,71 @@
* Parameters:
* 0: the name of the member
*/
- static const HintCode DEPRECATED_MEMBER_USE =
- const HintCode('DEPRECATED_MEMBER_USE', "'{0}' is deprecated");
+ static const HintCode DEPRECATED_MEMBER_USE = const HintCode(
+ 'DEPRECATED_MEMBER_USE',
+ "'{0}' is deprecated and shouldn't be used.",
+ "Try replacing the use of the deprecated member with the replacement.");
/**
* Duplicate imports.
*/
- static const HintCode DUPLICATE_IMPORT =
- const HintCode('DUPLICATE_IMPORT', "Duplicate import");
+ static const HintCode DUPLICATE_IMPORT = const HintCode('DUPLICATE_IMPORT',
+ "Duplicate import.", "Try removing all but one import of the library.");
/**
* Hint to use the ~/ operator.
*/
static const HintCode DIVISION_OPTIMIZATION = const HintCode(
'DIVISION_OPTIMIZATION',
- "The operator x ~/ y is more efficient than (x / y).toInt()");
+ "The operator x ~/ y is more efficient than (x / y).toInt().",
+ "Try re-writing the expression to use the '~/' operator.");
/**
* Hint for the `x is double` type checks.
*/
- static const HintCode IS_DOUBLE = const HintCode('IS_DOUBLE',
- "When compiled to JS, this test might return true when the left hand side is an int");
+ static const HintCode IS_DOUBLE = const HintCode(
+ 'IS_DOUBLE',
+ "When compiled to JS, this test might return true when the left hand "
+ "side is an int.",
+ "Try testing for 'num' instead.");
/**
* Hint for the `x is int` type checks.
*/
- static const HintCode IS_INT = const HintCode('IS_INT',
- "When compiled to JS, this test might return true when the left hand side is a double");
+ static const HintCode IS_INT = const HintCode(
+ 'IS_INT',
+ "When compiled to JS, this test might return true when the left hand "
+ "side is a double.",
+ "Try testing for 'num' instead.");
/**
* Hint for the `x is! double` type checks.
*/
- static const HintCode IS_NOT_DOUBLE = const HintCode('IS_NOT_DOUBLE',
- "When compiled to JS, this test might return false when the left hand side is an int");
+ static const HintCode IS_NOT_DOUBLE = const HintCode(
+ 'IS_NOT_DOUBLE',
+ "When compiled to JS, this test might return false when the left hand "
+ "side is an int.",
+ "Try testing for 'num' instead.");
/**
* Hint for the `x is! int` type checks.
*/
- static const HintCode IS_NOT_INT = const HintCode('IS_NOT_INT',
- "When compiled to JS, this test might return false when the left hand side is a double");
+ static const HintCode IS_NOT_INT = const HintCode(
+ 'IS_NOT_INT',
+ "When compiled to JS, this test might return false when the left hand "
+ "side is a double.",
+ "Try testing for 'num' instead.");
/**
* Deferred libraries shouldn't define a top level function 'loadLibrary'.
*/
- static const HintCode IMPORT_DEFERRED_LIBRARY_WITH_LOAD_FUNCTION = const HintCode(
- 'IMPORT_DEFERRED_LIBRARY_WITH_LOAD_FUNCTION',
- "The library '{0}' defines a top-level function named 'loadLibrary' which is hidden by deferring this library");
+ static const HintCode IMPORT_DEFERRED_LIBRARY_WITH_LOAD_FUNCTION =
+ const HintCode(
+ 'IMPORT_DEFERRED_LIBRARY_WITH_LOAD_FUNCTION',
+ "The library '{0}' defines a top-level function named 'loadLibrary' "
+ "which is hidden by deferring this library.",
+ "Try changing the import to not be deferred, or "
+ "rename the function in the imported library.");
/**
* This hint is generated anywhere where the
@@ -2341,7 +2774,9 @@
*/
static const HintCode INVALID_ASSIGNMENT = const HintCode(
'INVALID_ASSIGNMENT',
- "A value of type '{0}' cannot be assigned to a variable of type '{1}'");
+ "A value of type '{0}' can't be assigned to a variable of type '{1}'.",
+ "Try changing the type of the variable, or "
+ "casting the right-hand type to '{1}'.");
/**
* This hint is generated anywhere a @factory annotation is associated with
@@ -2369,7 +2804,7 @@
*/
static const HintCode INVALID_FACTORY_METHOD_IMPL = const HintCode(
'INVALID_FACTORY_METHOD_IMPL',
- "Factory method '{0}' does not return a newly allocated object.");
+ "Factory method '{0}' doesn't return a newly allocated object.");
/**
* This hint is generated anywhere where a member annotated with `@protected`
@@ -2381,7 +2816,8 @@
*/
static const HintCode INVALID_USE_OF_PROTECTED_MEMBER = const HintCode(
'INVALID_USE_OF_PROTECTED_MEMBER',
- "The member '{0}' can only be used within instance members of subclasses of '{1}'");
+ "The member '{0}' can only be used within instance members of subclasses "
+ "of '{1}'.");
/**
* Generate a hint for a constructor, function or method invocation where a
@@ -2403,7 +2839,7 @@
*/
static const HintCode MISSING_REQUIRED_PARAM_WITH_DETAILS = const HintCode(
'MISSING_REQUIRED_PARAM_WITH_DETAILS',
- "The parameter '{0}' is required. {1}");
+ "The parameter '{0}' is required. {1}.");
/**
* Generate a hint for an element that is annotated with `@JS(...)` whose
@@ -2411,7 +2847,9 @@
*/
static const HintCode MISSING_JS_LIB_ANNOTATION = const HintCode(
'MISSING_JS_LIB_ANNOTATION',
- "The @JS() annotation can only be used if it is also declared on the library directive.");
+ "The @JS() annotation can only be used if it is also declared on the "
+ "library directive.",
+ "Try adding the annotation to the library directive.");
/**
* Generate a hint for methods or functions that have a return type, but do
@@ -2424,8 +2862,9 @@
*/
static const HintCode MISSING_RETURN = const HintCode(
'MISSING_RETURN',
- "This function declares a return type of '{0}', but does not end with a return statement",
- "Either add a return statement or change the return type to 'void'");
+ "This function declares a return type of '{0}', but doesn't end with a "
+ "return statement.",
+ "Try adding a return statement, or changing the return type to 'void'.");
/**
* Generate a hint for methods that override methods annotated `@mustCallSuper`
@@ -2437,7 +2876,7 @@
static const HintCode MUST_CALL_SUPER = const HintCode(
'MUST_CALL_SUPER',
"This method overrides a method annotated as @mustCall super in '{0}', "
- "but does invoke the overriden method");
+ "but does invoke the overriden method.");
/**
* A condition in a control flow statement could evaluate to `null` because it
@@ -2445,36 +2884,46 @@
*/
static const HintCode NULL_AWARE_IN_CONDITION = const HintCode(
'NULL_AWARE_IN_CONDITION',
- "The value of the '?.' operator can be 'null', which is not appropriate in a condition",
- "Replace the '?.' with a '.', testing the left-hand side for null if necessary");
+ "The value of the '?.' operator can be 'null', which isn't appropriate "
+ "in a condition.",
+ "Try replacing the '?.' with a '.', testing the left-hand side for null if "
+ "necessary.");
/**
* A getter with the override annotation does not override an existing getter.
*/
static const HintCode OVERRIDE_ON_NON_OVERRIDING_GETTER = const HintCode(
'OVERRIDE_ON_NON_OVERRIDING_GETTER',
- "Getter does not override an inherited getter");
+ "Getter doesn't override an inherited getter.",
+ "Try updating this class to match the superclass, or "
+ "removing the override annotation.");
/**
* A field with the override annotation does not override a getter or setter.
*/
static const HintCode OVERRIDE_ON_NON_OVERRIDING_FIELD = const HintCode(
'OVERRIDE_ON_NON_OVERRIDING_FIELD',
- "Field does not override an inherited getter or setter");
+ "Field doesn't override an inherited getter or setter.",
+ "Try updating this class to match the superclass, or "
+ "removing the override annotation.");
/**
* A method with the override annotation does not override an existing method.
*/
static const HintCode OVERRIDE_ON_NON_OVERRIDING_METHOD = const HintCode(
'OVERRIDE_ON_NON_OVERRIDING_METHOD',
- "Method does not override an inherited method");
+ "Method doesn't override an inherited method.",
+ "Try updating this class to match the superclass, or "
+ "removing the override annotation.");
/**
* A setter with the override annotation does not override an existing setter.
*/
static const HintCode OVERRIDE_ON_NON_OVERRIDING_SETTER = const HintCode(
'OVERRIDE_ON_NON_OVERRIDING_SETTER',
- "Setter does not override an inherited setter");
+ "Setter doesn't override an inherited setter.",
+ "Try updating this class to match the superclass, or "
+ "removing the override annotation.");
/**
* Hint for classes that override equals, but not hashCode.
@@ -2484,20 +2933,24 @@
*/
static const HintCode OVERRIDE_EQUALS_BUT_NOT_HASH_CODE = const HintCode(
'OVERRIDE_EQUALS_BUT_NOT_HASH_CODE',
- "The class '{0}' overrides 'operator==', but not 'get hashCode'");
+ "The class '{0}' overrides 'operator==', but not 'get hashCode'.",
+ "Try implementing 'hashCode'.");
/**
* Type checks of the type `x is! Null` should be done with `x != null`.
*/
static const HintCode TYPE_CHECK_IS_NOT_NULL = const HintCode(
'TYPE_CHECK_IS_NOT_NULL',
- "Tests for non-null should be done with '!= null'");
+ "Tests for non-null should be done with '!= null'.",
+ "Try replacing the 'is! Null' check with '!= null'.");
/**
* Type checks of the type `x is Null` should be done with `x == null`.
*/
static const HintCode TYPE_CHECK_IS_NULL = const HintCode(
- 'TYPE_CHECK_IS_NULL', "Tests for null should be done with '== null'");
+ 'TYPE_CHECK_IS_NULL',
+ "Tests for null should be done with '== null'.",
+ "Try replacing the 'is Null' check with '== null'.");
/**
* This hint is generated anywhere where the
@@ -2509,15 +2962,18 @@
* 0: the name of the getter
* 1: the name of the enclosing type where the getter is being looked for
*/
- static const HintCode UNDEFINED_GETTER = const HintCode('UNDEFINED_GETTER',
- "The getter '{0}' is not defined for the class '{1}'.", null);
+ static const HintCode UNDEFINED_GETTER = const HintCode(
+ 'UNDEFINED_GETTER',
+ "The getter '{0}' isn't defined for the class '{1}'.",
+ "Try defining a getter or field named '{0}', or invoke a different getter.");
/**
* An undefined name hidden in an import or export directive.
*/
static const HintCode UNDEFINED_HIDDEN_NAME = const HintCode(
'UNDEFINED_HIDDEN_NAME',
- "The library '{0}' doesn't export a member with the hidden name '{1}'");
+ "The library '{0}' doesn't export a member with the hidden name '{1}'.",
+ "Try removing the name from the list of hidden members.");
/**
* This hint is generated anywhere where the
@@ -2528,8 +2984,11 @@
* 0: the name of the method that is undefined
* 1: the resolved type name that the method lookup is happening on
*/
- static const HintCode UNDEFINED_METHOD = const HintCode('UNDEFINED_METHOD',
- "The method '{0}' is not defined for the class '{1}'.", null);
+ static const HintCode UNDEFINED_METHOD = const HintCode(
+ 'UNDEFINED_METHOD',
+ "The method '{0}' isn't defined for the class '{1}'.",
+ "Try correcting the name to the name of an existing method, or"
+ "defining a method named '{0}'.");
/**
* This hint is generated anywhere where the
@@ -2542,8 +3001,8 @@
*/
static const HintCode UNDEFINED_OPERATOR = const HintCode(
'UNDEFINED_OPERATOR',
- "The operator '{0}' is not defined for the class '{1}'.",
- null);
+ "The operator '{0}' isn't defined for the class '{1}'.",
+ "Try defining the operator '{0}'.");
/**
* This hint is generated anywhere where the
@@ -2555,86 +3014,103 @@
* 0: the name of the setter
* 1: the name of the enclosing type where the setter is being looked for
*/
- static const HintCode UNDEFINED_SETTER = const HintCode('UNDEFINED_SETTER',
- "The setter '{0}' is not defined for the class '{1}'.", null);
+ static const HintCode UNDEFINED_SETTER = const HintCode(
+ 'UNDEFINED_SETTER',
+ "The setter '{0}' isn't defined for the class '{1}'.",
+ "Try defining a setter or field named '{0}', or invoke a different setter.");
/**
* An undefined name shown in an import or export directive.
*/
static const HintCode UNDEFINED_SHOWN_NAME = const HintCode(
'UNDEFINED_SHOWN_NAME',
- "The library '{0}' doesn't export a member with the shown name '{1}'");
+ "The library '{0}' doesn't export a member with the shown name '{1}'.",
+ "Try removing the name from the list of shown members.");
/**
* Unnecessary cast.
*/
- static const HintCode UNNECESSARY_CAST =
- const HintCode('UNNECESSARY_CAST', "Unnecessary cast");
+ static const HintCode UNNECESSARY_CAST = const HintCode(
+ 'UNNECESSARY_CAST', "Unnecessary cast.", "Try removing the cast.");
/**
* Unnecessary `noSuchMethod` declaration.
*/
static const HintCode UNNECESSARY_NO_SUCH_METHOD = const HintCode(
- 'UNNECESSARY_NO_SUCH_METHOD', "Unnecessary 'noSuchMethod' declaration");
-
- /**
- * Unnecessary type checks, the result is always true.
- */
- static const HintCode UNNECESSARY_TYPE_CHECK_FALSE = const HintCode(
- 'UNNECESSARY_TYPE_CHECK_FALSE',
- "Unnecessary type check, the result is always false");
+ 'UNNECESSARY_NO_SUCH_METHOD',
+ "Unnecessary 'noSuchMethod' declaration.",
+ "Try removing the declaration of 'noSuchMethod'.");
/**
* Unnecessary type checks, the result is always false.
*/
+ static const HintCode UNNECESSARY_TYPE_CHECK_FALSE = const HintCode(
+ 'UNNECESSARY_TYPE_CHECK_FALSE',
+ "Unnecessary type check, the result is always false.",
+ "Try correcting the type check, or removing the type check.");
+
+ /**
+ * Unnecessary type checks, the result is always true.
+ */
static const HintCode UNNECESSARY_TYPE_CHECK_TRUE = const HintCode(
'UNNECESSARY_TYPE_CHECK_TRUE',
- "Unnecessary type check, the result is always true");
+ "Unnecessary type check, the result is always true.",
+ "Try correcting the type check, or removing the type check.");
/**
* See [Modifier.IS_USED_IN_LIBRARY].
*/
- static const HintCode UNUSED_ELEMENT =
- const HintCode('UNUSED_ELEMENT', "The {0} '{1}' is not used");
+ static const HintCode UNUSED_ELEMENT = const HintCode('UNUSED_ELEMENT',
+ "The {0} '{1}' isn't used.", "Try removing the declaration of '{1}'.");
/**
* Unused fields are fields which are never read.
*/
static const HintCode UNUSED_FIELD = const HintCode(
- 'UNUSED_FIELD', "The value of the field '{0}' is not used");
+ 'UNUSED_FIELD',
+ "The value of the field '{0}' isn't used.",
+ "Try removing the field, or using it.");
/**
* Unused imports are imports which are never used.
*/
- static const HintCode UNUSED_IMPORT =
- const HintCode('UNUSED_IMPORT', "Unused import");
+ static const HintCode UNUSED_IMPORT = const HintCode(
+ 'UNUSED_IMPORT', "Unused import.", "Try removing the import directive.");
/**
* Unused catch exception variables.
*/
static const HintCode UNUSED_CATCH_CLAUSE = const HintCode(
'UNUSED_CATCH_CLAUSE',
- "The exception variable '{0}' is not used, so the 'catch' clause can be removed");
+ "The exception variable '{0}' isn't used, so the 'catch' clause can be removed.",
+ // TODO(brianwilkerson) Split this error code so that we can differentiate
+ // between removing the catch clause and replacing the catch clause with
+ // an on clause.
+ "Try removing the catch clause.");
/**
* Unused catch stack trace variables.
*/
static const HintCode UNUSED_CATCH_STACK = const HintCode(
'UNUSED_CATCH_STACK',
- "The stack trace variable '{0}' is not used and can be removed");
+ "The stack trace variable '{0}' isn't used and can be removed.",
+ "Try removing the stack trace variable, or using it.");
/**
* Unused local variables are local variables which are never read.
*/
static const HintCode UNUSED_LOCAL_VARIABLE = const HintCode(
'UNUSED_LOCAL_VARIABLE',
- "The value of the local variable '{0}' is not used");
+ "The value of the local variable '{0}' isn't used.",
+ "Try removing the variable, or using it.");
/**
* Unused shown names are names shown on imports which are never used.
*/
static const HintCode UNUSED_SHOWN_NAME = const HintCode(
- 'UNUSED_SHOWN_NAME', "The name {0} is shown, but not used.");
+ 'UNUSED_SHOWN_NAME',
+ "The name {0} is shown, but not used.",
+ "Try removing the name from the list of shown members.");
/**
* Hint for cases where the source expects a method or function to return a
@@ -2645,7 +3121,7 @@
*/
static const HintCode USE_OF_VOID_RESULT = const HintCode(
'USE_OF_VOID_RESULT',
- "The result of '{0}' is being used, even though it is declared to be 'void'");
+ "The result of '{0}' is being used, even though it is declared to be 'void'.");
/**
* It is a bad practice for a source file in a package "lib" directory
@@ -2655,8 +3131,12 @@
* directory.
*/
static const HintCode FILE_IMPORT_INSIDE_LIB_REFERENCES_FILE_OUTSIDE =
- const HintCode('FILE_IMPORT_INSIDE_LIB_REFERENCES_FILE_OUTSIDE',
- "A file in the 'lib' directory hierarchy should not reference a file outside that hierarchy");
+ const HintCode(
+ 'FILE_IMPORT_INSIDE_LIB_REFERENCES_FILE_OUTSIDE',
+ "A file in the 'lib' directory shouldn't import a file outside the "
+ "'lib' directory.",
+ "Try removing the import, or "
+ "moving the imported file inside the 'lib' directory.");
/**
* It is a bad practice for a source file ouside a package "lib" directory
@@ -2666,8 +3146,11 @@
* directory.
*/
static const HintCode FILE_IMPORT_OUTSIDE_LIB_REFERENCES_FILE_INSIDE =
- const HintCode('FILE_IMPORT_OUTSIDE_LIB_REFERENCES_FILE_INSIDE',
- "A file outside the 'lib' directory hierarchy should not reference a file inside that hierarchy. Use a package: reference instead.");
+ const HintCode(
+ 'FILE_IMPORT_OUTSIDE_LIB_REFERENCES_FILE_INSIDE',
+ "A file outside the 'lib' directory shouldn't reference a file "
+ "inside the 'lib' directory using a relative path.",
+ "Try using a package: URI instead.");
/**
* It is a bad practice for a package import to reference anything outside the
@@ -2677,7 +3160,7 @@
*/
static const HintCode PACKAGE_IMPORT_CONTAINS_DOT_DOT = const HintCode(
'PACKAGE_IMPORT_CONTAINS_DOT_DOT',
- "A package import should not contain '..'");
+ "A package import shouldn't contain '..'.");
/**
* Initialize a newly created error code to have the given [name]. The message
@@ -2742,7 +3225,7 @@
* 0: the URI that is invalid
*/
static const HtmlWarningCode INVALID_URI =
- const HtmlWarningCode('INVALID_URI', "Invalid URI syntax: '{0}'");
+ const HtmlWarningCode('INVALID_URI', "Invalid URI syntax: '{0}'.");
/**
* An error code indicating that the value of the 'src' attribute of a Dart
@@ -2752,7 +3235,7 @@
* 0: the URI pointing to a non-existent file
*/
static const HtmlWarningCode URI_DOES_NOT_EXIST = const HtmlWarningCode(
- 'URI_DOES_NOT_EXIST', "Target of URI does not exist: '{0}'");
+ 'URI_DOES_NOT_EXIST', "Target of URI doesn't exist: '{0}'.");
/**
* Initialize a newly created error code to have the given [name]. The message
@@ -2803,8 +3286,11 @@
* 0: the number of provided type arguments
*/
static const StaticTypeWarningCode EXPECTED_ONE_LIST_TYPE_ARGUMENTS =
- const StaticTypeWarningCode('EXPECTED_ONE_LIST_TYPE_ARGUMENTS',
- "List literal requires exactly one type arguments or none, but {0} found");
+ const StaticTypeWarningCode(
+ 'EXPECTED_ONE_LIST_TYPE_ARGUMENTS',
+ "List literals require exactly one type argument or none, "
+ "but {0} found.",
+ "Try adjusting the number of type arguments.");
/**
* 12.8 Maps: A fresh instance (7.6.1) <i>m</i>, of size <i>n</i>, whose class
@@ -2814,42 +3300,46 @@
* 0: the number of provided type arguments
*/
static const StaticTypeWarningCode EXPECTED_TWO_MAP_TYPE_ARGUMENTS =
- const StaticTypeWarningCode('EXPECTED_TWO_MAP_TYPE_ARGUMENTS',
- "Map literal requires exactly two type arguments or none, but {0} found");
+ const StaticTypeWarningCode(
+ 'EXPECTED_TWO_MAP_TYPE_ARGUMENTS',
+ "Map literals require exactly two type arguments or none, "
+ "but {0} found.",
+ "Try adjusting the number of type arguments.");
/**
* 9 Functions: It is a static warning if the declared return type of a
* function marked async* may not be assigned to Stream.
*/
static const StaticTypeWarningCode ILLEGAL_ASYNC_GENERATOR_RETURN_TYPE =
- const StaticTypeWarningCode('ILLEGAL_ASYNC_GENERATOR_RETURN_TYPE',
- "Functions marked 'async*' must have a return type assignable to 'Stream'");
+ const StaticTypeWarningCode(
+ 'ILLEGAL_ASYNC_GENERATOR_RETURN_TYPE',
+ "Functions marked 'async*' must have a return type assignable to "
+ "'Stream'.",
+ "Try fixing the return type of the function, or "
+ "removing the modifier 'async*' from the function body.");
/**
* 9 Functions: It is a static warning if the declared return type of a
* function marked async may not be assigned to Future.
*/
static const StaticTypeWarningCode ILLEGAL_ASYNC_RETURN_TYPE =
- const StaticTypeWarningCode('ILLEGAL_ASYNC_RETURN_TYPE',
- "Functions marked 'async' must have a return type assignable to 'Future'");
+ const StaticTypeWarningCode(
+ 'ILLEGAL_ASYNC_RETURN_TYPE',
+ "Functions marked 'async' must have a return type assignable to "
+ "'Future'.",
+ "Try fixing the return type of the function, or "
+ "removing the modifier 'async' from the function body.");
/**
* 9 Functions: It is a static warning if the declared return type of a
* function marked sync* may not be assigned to Iterable.
*/
static const StaticTypeWarningCode ILLEGAL_SYNC_GENERATOR_RETURN_TYPE =
- const StaticTypeWarningCode('ILLEGAL_SYNC_GENERATOR_RETURN_TYPE',
- "Functions marked 'sync*' must have a return type assignable to 'Iterable'");
-
- /**
- * 12.18 Assignment: Let <i>T</i> be the static type of <i>e<sub>1</sub></i>.
- * It is a static type warning if <i>T</i> does not have an accessible
- * instance setter named <i>v=</i>.
- *
- * See [UNDEFINED_SETTER].
- */
- static const StaticTypeWarningCode INACCESSIBLE_SETTER =
- const StaticTypeWarningCode('INACCESSIBLE_SETTER', "");
+ const StaticTypeWarningCode(
+ 'ILLEGAL_SYNC_GENERATOR_RETURN_TYPE',
+ "Functions marked 'sync*' must have a return type assignable to 'Iterable'.",
+ "Try fixing the return type of the function, or "
+ "removing the modifier 'sync*' from the function body.");
/**
* 8.1.1 Inheritance and Overriding: However, if the above rules would cause
@@ -2880,8 +3370,11 @@
* m<sub>k</sub></i> is inherited.
*/
static const StaticTypeWarningCode INCONSISTENT_METHOD_INHERITANCE =
- const StaticTypeWarningCode('INCONSISTENT_METHOD_INHERITANCE',
- "'{0}' is inherited by at least two interfaces inconsistently, from {1}");
+ const StaticTypeWarningCode(
+ 'INCONSISTENT_METHOD_INHERITANCE',
+ "Inconsistent declarations of '{0}' are inherited from {1}.",
+ "Try adjusting the supertypes of this class to remove the "
+ "inconsistency.");
/**
* 12.15.1 Ordinary Invocation: It is a static type warning if <i>T</i> does
@@ -2889,12 +3382,16 @@
*
* Parameters:
* 0: the name of the static member
+ * 1: the kind of the static member (field, getter, setter, or method)
+ * 2: the name of the defining class
*
* See [UNQUALIFIED_REFERENCE_TO_NON_LOCAL_STATIC_MEMBER].
*/
static const StaticTypeWarningCode INSTANCE_ACCESS_TO_STATIC_MEMBER =
- const StaticTypeWarningCode('INSTANCE_ACCESS_TO_STATIC_MEMBER',
- "Static member '{0}' cannot be accessed using instance access");
+ const StaticTypeWarningCode(
+ 'INSTANCE_ACCESS_TO_STATIC_MEMBER',
+ "Static {1} '{0}' can't be accessed through an instance.",
+ "Try using the class '{2}' to access the {1}.");
/**
* 12.18 Assignment: It is a static type warning if the static type of
@@ -2914,8 +3411,11 @@
* 1: the name of the left hand side type
*/
static const StaticTypeWarningCode INVALID_ASSIGNMENT =
- const StaticTypeWarningCode('INVALID_ASSIGNMENT',
- "A value of type '{0}' cannot be assigned to a variable of type '{1}'");
+ const StaticTypeWarningCode(
+ 'INVALID_ASSIGNMENT',
+ "A value of type '{0}' can't be assigned to a variable of type '{1}'.",
+ "Try changing the type of the variable, or "
+ "casting the right-hand type to '{1}'.");
/**
* 12.15.1 Ordinary Invocation: An ordinary method invocation <i>i</i> has the
@@ -2943,7 +3443,12 @@
*/
static const StaticTypeWarningCode INVOCATION_OF_NON_FUNCTION =
const StaticTypeWarningCode(
- 'INVOCATION_OF_NON_FUNCTION', "'{0}' is not a method");
+ 'INVOCATION_OF_NON_FUNCTION',
+ "'{0}' isn't a function.",
+ // TODO(brianwilkerson) Split this error code so that we can provide
+ // better error and correction messages.
+ "Try correcting the name to match an existing function, or "
+ "define a method or function named '{0}'.");
/**
* 12.14.4 Function Expression Invocation: A function expression invocation
@@ -2956,7 +3461,7 @@
*/
static const StaticTypeWarningCode INVOCATION_OF_NON_FUNCTION_EXPRESSION =
const StaticTypeWarningCode('INVOCATION_OF_NON_FUNCTION_EXPRESSION',
- "Cannot invoke a non-function");
+ "The expression doesn't evaluate to a function, so it can't invoked.");
/**
* 12.20 Conditional: It is a static type warning if the type of
@@ -2973,15 +3478,19 @@
*/
static const StaticTypeWarningCode NON_BOOL_CONDITION =
const StaticTypeWarningCode(
- 'NON_BOOL_CONDITION', "Conditions must have a static type of 'bool'");
+ 'NON_BOOL_CONDITION',
+ "Conditions must have a static type of 'bool'.",
+ "Try changing the condition.");
/**
* 13.15 Assert: It is a static type warning if the type of <i>e</i> may not
* be assigned to either bool or () → bool
*/
static const StaticTypeWarningCode NON_BOOL_EXPRESSION =
- const StaticTypeWarningCode('NON_BOOL_EXPRESSION',
- "Assertions must be on either a 'bool' or '() -> bool'");
+ const StaticTypeWarningCode(
+ 'NON_BOOL_EXPRESSION',
+ "Assertions must be on either a 'bool' or '() -> bool'.",
+ "Try changing the expression.");
/**
* 12.28 Unary Expressions: The expression !<i>e</i> is equivalent to the
@@ -2991,8 +3500,10 @@
* <i>e<sub>1</sub></i> may not be assigned to bool.
*/
static const StaticTypeWarningCode NON_BOOL_NEGATION_EXPRESSION =
- const StaticTypeWarningCode('NON_BOOL_NEGATION_EXPRESSION',
- "Negation argument must have a static type of 'bool'");
+ const StaticTypeWarningCode(
+ 'NON_BOOL_NEGATION_EXPRESSION',
+ "Negation argument must have a static type of 'bool'.",
+ "Try changing the argument to the '!' operator.");
/**
* 12.21 Logical Boolean Expressions: It is a static type warning if the
@@ -3004,19 +3515,30 @@
*/
static const StaticTypeWarningCode NON_BOOL_OPERAND =
const StaticTypeWarningCode('NON_BOOL_OPERAND',
- "The operands of the '{0}' operator must be assignable to 'bool'");
+ "The operands of the '{0}' operator must be assignable to 'bool'.");
+ /**
+ * Parameters:
+ * 0: the name of the variable
+ * 1: the type of the variable
+ */
static const StaticTypeWarningCode NON_NULLABLE_FIELD_NOT_INITIALIZED =
- const StaticTypeWarningCode('NON_NULLABLE_FIELD_NOT_INITIALIZED',
- "Variable '{0}' of non-nullable type '{1}' must be initialized");
+ const StaticTypeWarningCode(
+ 'NON_NULLABLE_FIELD_NOT_INITIALIZED',
+ "Variable '{0}' of non-nullable type '{1}' must be initialized.",
+ "Try adding an initializer to the declaration, or "
+ "making the variable nullable by adding a '?' after the type name.");
/**
* 15.8 Parameterized Types: It is a static type warning if <i>A<sub>i</sub>,
* 1 <= i <= n</i> does not denote a type in the enclosing lexical scope.
*/
static const StaticTypeWarningCode NON_TYPE_AS_TYPE_ARGUMENT =
- const StaticTypeWarningCode('NON_TYPE_AS_TYPE_ARGUMENT',
- "The name '{0}' is not a type and cannot be used as a parameterized type");
+ const StaticTypeWarningCode(
+ 'NON_TYPE_AS_TYPE_ARGUMENT',
+ "The name '{0}' isn't a type so it can't be used as a type argument.",
+ "Try correcting the name to an existing type, or"
+ "defining a type named '{0}'.");
/**
* 13.11 Return: It is a static type warning if the type of <i>e</i> may not
@@ -3029,10 +3551,8 @@
* 2: the name of the method
*/
static const StaticTypeWarningCode RETURN_OF_INVALID_TYPE =
- const StaticTypeWarningCode(
- 'RETURN_OF_INVALID_TYPE',
- "The return type '{0}' is not a '{1}', as defined by the method '{2}'.",
- null);
+ const StaticTypeWarningCode('RETURN_OF_INVALID_TYPE',
+ "The return type '{0}' isn't a '{1}', as defined by the method '{2}'.");
/**
* 12.11 Instance Creation: It is a static type warning if any of the type
@@ -3064,7 +3584,9 @@
*/
static const StaticTypeWarningCode TYPE_ARGUMENT_NOT_MATCHING_BOUNDS =
const StaticTypeWarningCode(
- 'TYPE_ARGUMENT_NOT_MATCHING_BOUNDS', "'{0}' does not extend '{1}'");
+ 'TYPE_ARGUMENT_NOT_MATCHING_BOUNDS',
+ "'{0}' doesn't extend '{1}'.",
+ "Try using a type that is or is a subclass of '{1}'.");
/**
* 10 Generics: It is a static type warning if a type parameter is a supertype
@@ -3072,12 +3594,15 @@
*
* Parameters:
* 0: the name of the type parameter
+ * 1: the name of the bounding type
*
* See [TYPE_ARGUMENT_NOT_MATCHING_BOUNDS].
*/
static const StaticTypeWarningCode TYPE_PARAMETER_SUPERTYPE_OF_ITS_BOUND =
- const StaticTypeWarningCode('TYPE_PARAMETER_SUPERTYPE_OF_ITS_BOUND',
- "'{0}' cannot be a supertype of its upper bound");
+ const StaticTypeWarningCode(
+ 'TYPE_PARAMETER_SUPERTYPE_OF_ITS_BOUND',
+ "'{0}' can't be a supertype of its upper bound.",
+ "Try using a type that is or is a subclass of '{1}'.");
/**
* 12.17 Getter Invocation: It is a static warning if there is no class
@@ -3089,8 +3614,11 @@
* 1: the name of the enumeration used to access the constant
*/
static const StaticTypeWarningCode UNDEFINED_ENUM_CONSTANT =
- const StaticTypeWarningCode('UNDEFINED_ENUM_CONSTANT',
- "There is no constant named '{0}' in '{1}'.", null);
+ const StaticTypeWarningCode(
+ 'UNDEFINED_ENUM_CONSTANT',
+ "There is no constant named '{0}' in '{1}'.",
+ "Try correcting the name to the name of an existing constant, or"
+ "defining a constant named '{0}'.");
/**
* 12.15.3 Unqualified Invocation: If there exists a lexically visible
@@ -3106,7 +3634,11 @@
*/
static const StaticTypeWarningCode UNDEFINED_FUNCTION =
const StaticTypeWarningCode(
- 'UNDEFINED_FUNCTION', "The function '{0}' is not defined.", null);
+ 'UNDEFINED_FUNCTION',
+ "The function '{0}' isn't defined.",
+ "Try importing the library that defines '{0}', "
+ "correcting the name to the name of an existing function, or"
+ "defining a funtion named '{0}'.");
/**
* 12.17 Getter Invocation: Let <i>T</i> be the static type of <i>e</i>. It is
@@ -3117,8 +3649,12 @@
* 1: the name of the enclosing type where the getter is being looked for
*/
static const StaticTypeWarningCode UNDEFINED_GETTER =
- const StaticTypeWarningCode('UNDEFINED_GETTER',
- "The getter '{0}' is not defined for the class '{1}'.", null);
+ const StaticTypeWarningCode(
+ 'UNDEFINED_GETTER',
+ "The getter '{0}' isn't defined for the class '{1}'.",
+ "Try importing the library that defines '{0}', "
+ "correcting the name to the name of an existing getter, or"
+ "defining a getter or field named '{0}'.");
/**
* 12.15.1 Ordinary Invocation: Let <i>T</i> be the static type of <i>o</i>.
@@ -3130,8 +3666,11 @@
* 1: the resolved type name that the method lookup is happening on
*/
static const StaticTypeWarningCode UNDEFINED_METHOD =
- const StaticTypeWarningCode('UNDEFINED_METHOD',
- "The method '{0}' is not defined for the class '{1}'.", null);
+ const StaticTypeWarningCode(
+ 'UNDEFINED_METHOD',
+ "The method '{0}' isn't defined for the class '{1}'.",
+ "Try correcting the name to the name of an existing method, or"
+ "defining a method named '{0}'.");
/**
* 12.15.1 Ordinary Invocation: Let <i>T</i> be the static type of <i>o</i>.
@@ -3145,8 +3684,9 @@
static const StaticTypeWarningCode UNDEFINED_METHOD_WITH_CONSTRUCTOR =
const StaticTypeWarningCode(
'UNDEFINED_METHOD_WITH_CONSTRUCTOR',
- "The method '{0}' is not defined for the class '{1}', but a constructor with that name is defined.",
- "Try adding 'new' or 'const' to invoke the constuctor, or change the method name.");
+ "The method '{0}' isn't defined for the class '{1}', but a constructor with that name is defined.",
+ "Try adding 'new' or 'const' to invoke the constuctor, or "
+ "correcting the name to the name of an existing method.");
/**
* 12.18 Assignment: Evaluation of an assignment of the form
@@ -3169,8 +3709,10 @@
* 1: the name of the enclosing type where the operator is being looked for
*/
static const StaticTypeWarningCode UNDEFINED_OPERATOR =
- const StaticTypeWarningCode('UNDEFINED_OPERATOR',
- "The operator '{0}' is not defined for the class '{1}'.", null);
+ const StaticTypeWarningCode(
+ 'UNDEFINED_OPERATOR',
+ "The operator '{0}' isn't defined for the class '{1}'.",
+ "Try defining the operator '{0}'.");
/**
* 12.18 Assignment: Let <i>T</i> be the static type of <i>e<sub>1</sub></i>.
@@ -3180,12 +3722,14 @@
* Parameters:
* 0: the name of the setter
* 1: the name of the enclosing type where the setter is being looked for
- *
- * See [INACCESSIBLE_SETTER].
*/
static const StaticTypeWarningCode UNDEFINED_SETTER =
- const StaticTypeWarningCode('UNDEFINED_SETTER',
- "The setter '{0}' is not defined for the class '{1}'.", null);
+ const StaticTypeWarningCode(
+ 'UNDEFINED_SETTER',
+ "The setter '{0}' isn't defined for the class '{1}'.",
+ "Try importing the library that defines '{0}', "
+ "correcting the name to the name of an existing setter, or"
+ "defining a setter or field named '{0}'.");
/**
* 12.17 Getter Invocation: Let <i>T</i> be the static type of <i>e</i>. It is
@@ -3196,8 +3740,11 @@
* 1: the name of the enclosing type where the getter is being looked for
*/
static const StaticTypeWarningCode UNDEFINED_SUPER_GETTER =
- const StaticTypeWarningCode('UNDEFINED_SUPER_GETTER',
- "The getter '{0}' is not defined in a superclass of '{1}'.", null);
+ const StaticTypeWarningCode(
+ 'UNDEFINED_SUPER_GETTER',
+ "The getter '{0}' isn't defined in a superclass of '{1}'.",
+ "Try correcting the name to the name of an existing getter, or"
+ "defining a getter or field named '{0}' in a superclass.");
/**
* 12.15.4 Super Invocation: A super method invocation <i>i</i> has the form
@@ -3211,8 +3758,11 @@
* 1: the resolved type name that the method lookup is happening on
*/
static const StaticTypeWarningCode UNDEFINED_SUPER_METHOD =
- const StaticTypeWarningCode('UNDEFINED_SUPER_METHOD',
- "The method '{0}' is not defined in a superclass of '{1}'.", null);
+ const StaticTypeWarningCode(
+ 'UNDEFINED_SUPER_METHOD',
+ "The method '{0}' isn't defined in a superclass of '{1}'.",
+ "Try correcting the name to the name of an existing method, or"
+ "defining a method named '{0}' in a superclass.");
/**
* 12.18 Assignment: Evaluation of an assignment of the form
@@ -3235,8 +3785,10 @@
* 1: the name of the enclosing type where the operator is being looked for
*/
static const StaticTypeWarningCode UNDEFINED_SUPER_OPERATOR =
- const StaticTypeWarningCode('UNDEFINED_SUPER_OPERATOR',
- "The operator '{0}' is not defined in a superclass of '{1}'.", null);
+ const StaticTypeWarningCode(
+ 'UNDEFINED_SUPER_OPERATOR',
+ "The operator '{0}' isn't defined in a superclass of '{1}'.",
+ "Try defining the operator '{0}' in a superclass.");
/**
* 12.18 Assignment: Let <i>T</i> be the static type of <i>e<sub>1</sub></i>.
@@ -3246,12 +3798,13 @@
* Parameters:
* 0: the name of the setter
* 1: the name of the enclosing type where the setter is being looked for
- *
- * See [INACCESSIBLE_SETTER].
*/
static const StaticTypeWarningCode UNDEFINED_SUPER_SETTER =
- const StaticTypeWarningCode('UNDEFINED_SUPER_SETTER',
- "The setter '{0}' is not defined in a superclass of '{1}'.", null);
+ const StaticTypeWarningCode(
+ 'UNDEFINED_SUPER_SETTER',
+ "The setter '{0}' isn't defined in a superclass of '{1}'.",
+ "Try correcting the name to the name of an existing setter, or"
+ "defining a setter or field named '{0}' in a superclass.");
/**
* 12.15.1 Ordinary Invocation: It is a static type warning if <i>T</i> does
@@ -3260,12 +3813,16 @@
* This is a specialization of [INSTANCE_ACCESS_TO_STATIC_MEMBER] that is used
* when we are able to find the name defined in a supertype. It exists to
* provide a more informative error message.
+ *
+ * Parameters:
+ * 0: the name of the defining type
*/
static const StaticTypeWarningCode
UNQUALIFIED_REFERENCE_TO_NON_LOCAL_STATIC_MEMBER =
const StaticTypeWarningCode(
'UNQUALIFIED_REFERENCE_TO_NON_LOCAL_STATIC_MEMBER',
- "Static members from supertypes must be qualified by the name of the defining type");
+ "Static members from supertypes must be qualified by the name of the defining type.",
+ "Try adding '{0}.' before the name.");
/**
* 15.8 Parameterized Types: It is a static type warning if <i>G</i> is not a
@@ -3280,8 +3837,11 @@
* [CompileTimeErrorCode.NEW_WITH_INVALID_TYPE_PARAMETERS].
*/
static const StaticTypeWarningCode WRONG_NUMBER_OF_TYPE_ARGUMENTS =
- const StaticTypeWarningCode('WRONG_NUMBER_OF_TYPE_ARGUMENTS',
- "The type '{0}' is declared with {1} type parameters, but {2} type arguments were given");
+ const StaticTypeWarningCode(
+ 'WRONG_NUMBER_OF_TYPE_ARGUMENTS',
+ "The type '{0}' is declared with {1} type parameters, "
+ "but {2} type arguments were given.",
+ "Try adjusting the number of type arguments.");
/**
* 17.16.1 Yield: Let T be the static type of e [the expression to the right
@@ -3302,8 +3862,10 @@
* T may not be assigned to Stream.
*/
static const StaticTypeWarningCode YIELD_OF_INVALID_TYPE =
- const StaticTypeWarningCode('YIELD_OF_INVALID_TYPE',
- "The type '{0}' implied by the 'yield' expression must be assignable to '{1}'");
+ const StaticTypeWarningCode(
+ 'YIELD_OF_INVALID_TYPE',
+ "The type '{0}' implied by the 'yield' expression must be assignable "
+ "to '{1}'.");
/**
* 17.6.2 For-in. If the iterable expression does not implement Iterable,
@@ -3315,7 +3877,7 @@
*/
static const StaticTypeWarningCode FOR_IN_OF_INVALID_TYPE =
const StaticTypeWarningCode('FOR_IN_OF_INVALID_TYPE',
- "The type '{0}' used in the 'for' loop must implement {1}");
+ "The type '{0}' used in the 'for' loop must implement {1}.");
/**
* 17.6.2 For-in. It the iterable expression does not implement Iterable with
@@ -3328,8 +3890,10 @@
* 2: The loop variable type.
*/
static const StaticTypeWarningCode FOR_IN_OF_INVALID_ELEMENT_TYPE =
- const StaticTypeWarningCode('FOR_IN_OF_INVALID_ELEMENT_TYPE',
- "The type '{0}' used in the 'for' loop must implement {1} with a type argument that can be assigned to '{2}'");
+ const StaticTypeWarningCode(
+ 'FOR_IN_OF_INVALID_ELEMENT_TYPE',
+ "The type '{0}' used in the 'for' loop must implement {1} with a "
+ "type argument that can be assigned to '{2}'.");
/**
* Initialize a newly created error code to have the given [name]. The message
@@ -3370,9 +3934,9 @@
*/
static const StaticWarningCode AMBIGUOUS_IMPORT = const StaticWarningCode(
'AMBIGUOUS_IMPORT',
- "The name '{0}' is defined in the libraries {1}",
- "Consider using 'as prefix' for one of the import directives "
- "or hiding the name from all but one of the imports.");
+ "The name '{0}' is defined in the libraries {1}.",
+ "Try using 'as prefix' for one of the import directives, or "
+ "hiding the name from all but one of the imports.");
/**
* 12.11.1 New: It is a static warning if the static type of <i>a<sub>i</sub>,
@@ -3380,7 +3944,7 @@
* corresponding formal parameter of the constructor <i>T.id</i> (respectively
* <i>T</i>).
*
- * 12.11.2 Const: It is a static warning if the static type of
+ * 16.12.2 Const: It is a static warning if the static type of
* <i>a<sub>i</sub>, 1 <= i <= n+ k</i> may not be assigned to the type
* of the corresponding formal parameter of the constructor <i>T.id</i>
* (respectively <i>T</i>).
@@ -3404,10 +3968,8 @@
* 1: the name of the expected type
*/
static const StaticWarningCode ARGUMENT_TYPE_NOT_ASSIGNABLE =
- const StaticWarningCode(
- 'ARGUMENT_TYPE_NOT_ASSIGNABLE',
- "The argument type '{0}' cannot be assigned to the parameter type '{1}'.",
- null);
+ const StaticWarningCode('ARGUMENT_TYPE_NOT_ASSIGNABLE',
+ "The argument type '{0}' can't be assigned to the parameter type '{1}'.");
/**
* 5 Variables: Attempting to assign to a final variable elsewhere will cause
@@ -3417,7 +3979,10 @@
* A constant variable is always implicitly final.
*/
static const StaticWarningCode ASSIGNMENT_TO_CONST = const StaticWarningCode(
- 'ASSIGNMENT_TO_CONST', "Constant variables cannot be assigned a value");
+ 'ASSIGNMENT_TO_CONST',
+ "Constant variables can't be assigned a value.",
+ "Try removing the assignment, or "
+ "remove the modifier 'const' from the variable.");
/**
* 5 Variables: Attempting to assign to a final variable elsewhere will cause
@@ -3425,7 +3990,9 @@
* assignment will also give rise to a static warning for the same reason.
*/
static const StaticWarningCode ASSIGNMENT_TO_FINAL = const StaticWarningCode(
- 'ASSIGNMENT_TO_FINAL', "'{0}' cannot be used as a setter, it is final");
+ 'ASSIGNMENT_TO_FINAL',
+ "'{0}' can't be used as a setter because it is final.",
+ "Try finding a different setter, or making '{0}' non-final.");
/**
* 5 Variables: Attempting to assign to a final variable elsewhere will cause
@@ -3433,8 +4000,11 @@
* assignment will also give rise to a static warning for the same reason.
*/
static const StaticWarningCode ASSIGNMENT_TO_FINAL_NO_SETTER =
- const StaticWarningCode('ASSIGNMENT_TO_FINAL_NO_SETTER',
- "No setter named '{0}' in class '{1}'");
+ const StaticWarningCode(
+ 'ASSIGNMENT_TO_FINAL_NO_SETTER',
+ "No setter named '{0}' in class '{1}'.",
+ "Try correcting the name to reference an existing setter, or "
+ "declare the setter.");
/**
* 12.18 Assignment: It is as static warning if an assignment of the form
@@ -3445,7 +4015,7 @@
*/
static const StaticWarningCode ASSIGNMENT_TO_FUNCTION =
const StaticWarningCode(
- 'ASSIGNMENT_TO_FUNCTION', "Functions cannot be assigned a value");
+ 'ASSIGNMENT_TO_FUNCTION', "Functions can't be assigned a value.");
/**
* 12.18 Assignment: Let <i>T</i> be the static type of <i>e<sub>1</sub></i>
@@ -3453,7 +4023,7 @@
* instance setter named <i>v=</i>.
*/
static const StaticWarningCode ASSIGNMENT_TO_METHOD = const StaticWarningCode(
- 'ASSIGNMENT_TO_METHOD', "Methods cannot be assigned a value");
+ 'ASSIGNMENT_TO_METHOD', "Methods can't be assigned a value.");
/**
* 12.18 Assignment: It is as static warning if an assignment of the form
@@ -3463,7 +4033,7 @@
* name <i>v=</i> in the lexical scope enclosing the assignment.
*/
static const StaticWarningCode ASSIGNMENT_TO_TYPE = const StaticWarningCode(
- 'ASSIGNMENT_TO_TYPE', "Types cannot be assigned a value");
+ 'ASSIGNMENT_TO_TYPE', "Types can't be assigned a value.");
/**
* 13.9 Switch: It is a static warning if the last statement of the statement
@@ -3471,8 +4041,11 @@
* statement.
*/
static const StaticWarningCode CASE_BLOCK_NOT_TERMINATED =
- const StaticWarningCode('CASE_BLOCK_NOT_TERMINATED',
- "The last statement of the 'case' should be 'break', 'continue', 'return' or 'throw'");
+ const StaticWarningCode(
+ 'CASE_BLOCK_NOT_TERMINATED',
+ "The last statement of the 'case' should be 'break', 'continue', "
+ "'return' or 'throw'.",
+ "Try adding one of the required statements.");
/**
* 12.32 Type Cast: It is a static warning if <i>T</i> does not denote a type
@@ -3480,15 +4053,23 @@
*/
static const StaticWarningCode CAST_TO_NON_TYPE = const StaticWarningCode(
'CAST_TO_NON_TYPE',
- "The name '{0}' is not a type and cannot be used in an 'as' expression");
+ "The name '{0}' isn't a type, so it can't be used in an 'as' expression.",
+ "Try changing the name to the name of an existing type, or "
+ "creating a type with the name '{0}'.");
/**
* 7.4 Abstract Instance Members: It is a static warning if an abstract member
* is declared or inherited in a concrete class.
+ *
+ * Parameters:
+ * 0: the name of the abstract method
+ * 1: the name of the enclosing class
*/
static const StaticWarningCode CONCRETE_CLASS_WITH_ABSTRACT_MEMBER =
- const StaticWarningCode('CONCRETE_CLASS_WITH_ABSTRACT_MEMBER',
- "'{0}' must have a method body because '{1}' is not abstract");
+ const StaticWarningCode(
+ 'CONCRETE_CLASS_WITH_ABSTRACT_MEMBER',
+ "'{0}' must have a method body because '{1}' isn't abstract.",
+ "Try making '{1}' abstract, or adding a body to '{0}'.");
/**
* 14.1 Imports: If a name <i>N</i> is referenced by a library <i>L</i> and
@@ -3504,8 +4085,10 @@
* 2: the name of the non-dart: library in which the element is found
*/
static const StaticWarningCode CONFLICTING_DART_IMPORT =
- const StaticWarningCode('CONFLICTING_DART_IMPORT',
- "Element '{0}' from SDK library '{1}' is implicitly hidden by '{2}'");
+ const StaticWarningCode(
+ 'CONFLICTING_DART_IMPORT',
+ "Element '{0}' from SDK library '{1}' is implicitly hidden by '{2}'.",
+ "Try adding an explicit hide combinator.");
/**
* 7.2 Getters: It is a static warning if a class <i>C</i> declares an
@@ -3519,23 +4102,30 @@
CONFLICTING_INSTANCE_GETTER_AND_SUPERCLASS_MEMBER =
const StaticWarningCode(
'CONFLICTING_INSTANCE_GETTER_AND_SUPERCLASS_MEMBER',
- "Superclass '{0}' declares static member with the same name");
+ "Superclass '{0}' declares static member with the same name.",
+ "Try renaming either the getter or the static member.");
/**
* 7.1 Instance Methods: It is a static warning if a class <i>C</i> declares
* an instance method named <i>n</i> and has a setter named <i>n=</i>.
*/
static const StaticWarningCode CONFLICTING_INSTANCE_METHOD_SETTER =
- const StaticWarningCode('CONFLICTING_INSTANCE_METHOD_SETTER',
- "Class '{0}' declares instance method '{1}', but also has a setter with the same name from '{2}'");
+ const StaticWarningCode(
+ 'CONFLICTING_INSTANCE_METHOD_SETTER',
+ "Class '{0}' declares instance method '{1}', "
+ "but also has a setter with the same name from '{2}'.",
+ "Try renaming either the method or the setter.");
/**
* 7.1 Instance Methods: It is a static warning if a class <i>C</i> declares
* an instance method named <i>n</i> and has a setter named <i>n=</i>.
*/
static const StaticWarningCode CONFLICTING_INSTANCE_METHOD_SETTER2 =
- const StaticWarningCode('CONFLICTING_INSTANCE_METHOD_SETTER2',
- "Class '{0}' declares the setter '{1}', but also has an instance method in the same class");
+ const StaticWarningCode(
+ 'CONFLICTING_INSTANCE_METHOD_SETTER2',
+ "Class '{0}' declares the setter '{1}', "
+ "but also has an instance method in the same class.",
+ "Try renaming either the method or the setter.");
/**
* 7.3 Setters: It is a static warning if a class <i>C</i> declares an
@@ -3549,40 +4139,47 @@
CONFLICTING_INSTANCE_SETTER_AND_SUPERCLASS_MEMBER =
const StaticWarningCode(
'CONFLICTING_INSTANCE_SETTER_AND_SUPERCLASS_MEMBER',
- "Superclass '{0}' declares static member with the same name");
+ "Superclass '{0}' declares a static member with the same name.",
+ "Try renaming either the setter or the inherited member.");
/**
* 7.2 Getters: It is a static warning if a class declares a static getter
* named <i>v</i> and also has a non-static setter named <i>v=</i>.
*/
static const StaticWarningCode CONFLICTING_STATIC_GETTER_AND_INSTANCE_SETTER =
- const StaticWarningCode('CONFLICTING_STATIC_GETTER_AND_INSTANCE_SETTER',
- "Class '{0}' declares non-static setter with the same name");
+ const StaticWarningCode(
+ 'CONFLICTING_STATIC_GETTER_AND_INSTANCE_SETTER',
+ "Class '{0}' declares non-static setter with the same name.",
+ "Try renaming either the getter or the setter.");
/**
* 7.3 Setters: It is a static warning if a class declares a static setter
* named <i>v=</i> and also has a non-static member named <i>v</i>.
*/
static const StaticWarningCode CONFLICTING_STATIC_SETTER_AND_INSTANCE_MEMBER =
- const StaticWarningCode('CONFLICTING_STATIC_SETTER_AND_INSTANCE_MEMBER',
- "Class '{0}' declares non-static member with the same name");
+ const StaticWarningCode(
+ 'CONFLICTING_STATIC_SETTER_AND_INSTANCE_MEMBER',
+ "Class '{0}' declares non-static member with the same name.",
+ "Try renaming either the inherited member or the setter.");
/**
- * 12.11.2 Const: Given an instance creation expression of the form <i>const
+ * 16.12.2 Const: Given an instance creation expression of the form <i>const
* q(a<sub>1</sub>, … a<sub>n</sub>)</i> it is a static warning if
* <i>q</i> is the constructor of an abstract class but <i>q</i> is not a
* factory constructor.
*/
static const StaticWarningCode CONST_WITH_ABSTRACT_CLASS =
- const StaticWarningCode('CONST_WITH_ABSTRACT_CLASS',
- "Abstract classes cannot be created with a 'const' expression");
+ const StaticWarningCode(
+ 'CONST_WITH_ABSTRACT_CLASS',
+ "Abstract classes can't be created with a 'const' expression.",
+ "Try creating an instance of a subtype.");
/**
* 12.7 Maps: It is a static warning if the values of any two keys in a map
* literal are equal.
*/
static const StaticWarningCode EQUAL_KEYS_IN_MAP = const StaticWarningCode(
- 'EQUAL_KEYS_IN_MAP', "Keys in a map cannot be equal");
+ 'EQUAL_KEYS_IN_MAP', "Two keys in a map literal can't be equal.");
/**
* 14.2 Exports: It is a static warning to export two different libraries with
@@ -3594,8 +4191,10 @@
* 2:e the shared name of the exported libraries
*/
static const StaticWarningCode EXPORT_DUPLICATED_LIBRARY_NAMED =
- const StaticWarningCode('EXPORT_DUPLICATED_LIBRARY_NAMED',
- "The exported libraries '{0}' and '{1}' cannot have the same name '{2}'");
+ const StaticWarningCode(
+ 'EXPORT_DUPLICATED_LIBRARY_NAMED',
+ "The exported libraries '{0}' and '{1}' can't have the same name '{2}'.",
+ "Try adding a hide clause to one of the export directives.");
/**
* 12.14.2 Binding Actuals to Formals: It is a static warning if <i>m <
@@ -3608,8 +4207,10 @@
* See [NOT_ENOUGH_REQUIRED_ARGUMENTS].
*/
static const StaticWarningCode EXTRA_POSITIONAL_ARGUMENTS =
- const StaticWarningCode('EXTRA_POSITIONAL_ARGUMENTS',
- "{0} positional arguments expected, but {1} found");
+ const StaticWarningCode(
+ 'EXTRA_POSITIONAL_ARGUMENTS',
+ "{0} positional arguments expected, but {1} found.",
+ "Try removing the extra positional arguments.");
/**
* 5. Variables: It is a static warning if a final instance variable that has
@@ -3620,7 +4221,9 @@
FIELD_INITIALIZED_IN_INITIALIZER_AND_DECLARATION =
const StaticWarningCode(
'FIELD_INITIALIZED_IN_INITIALIZER_AND_DECLARATION',
- "Values cannot be set in the constructor if they are final, and have already been set");
+ "Fields can't be initialized in the constructor if they are final "
+ "and have already been initialized at their declaration.",
+ "Try removing one of the initializations.");
/**
* 5. Variables: It is a static warning if a final instance variable that has
@@ -3634,7 +4237,9 @@
FINAL_INITIALIZED_IN_DECLARATION_AND_CONSTRUCTOR =
const StaticWarningCode(
'FINAL_INITIALIZED_IN_DECLARATION_AND_CONSTRUCTOR',
- "'{0}' is final and was given a value when it was declared, so it cannot be set to a new value");
+ "'{0}' is final and was given a value when it was declared, "
+ "so it can't be set to a new value.",
+ "Try removing one of the initializations.");
/**
* 7.6.1 Generative Constructors: Execution of an initializer of the form
@@ -3655,7 +4260,7 @@
*/
static const StaticWarningCode FIELD_INITIALIZER_NOT_ASSIGNABLE =
const StaticWarningCode('FIELD_INITIALIZER_NOT_ASSIGNABLE',
- "The initializer type '{0}' cannot be assigned to the field type '{1}'");
+ "The initializer type '{0}' can't be assigned to the field type '{1}'.");
/**
* 7.6.1 Generative Constructors: An initializing formal has the form
@@ -3667,8 +4272,11 @@
* 1: the name of the type of the field
*/
static const StaticWarningCode FIELD_INITIALIZING_FORMAL_NOT_ASSIGNABLE =
- const StaticWarningCode('FIELD_INITIALIZING_FORMAL_NOT_ASSIGNABLE',
- "The parameter type '{0}' is incompatable with the field type '{1}'");
+ const StaticWarningCode(
+ 'FIELD_INITIALIZING_FORMAL_NOT_ASSIGNABLE',
+ "The parameter type '{0}' is incompatable with the field type '{1}'.",
+ "Try changing or removing the parameter's type, or "
+ "changing the field's type.");
/**
* 5 Variables: It is a static warning if a library, static or local variable
@@ -3679,8 +4287,14 @@
* 0: the name of the uninitialized final variable
*/
static const StaticWarningCode FINAL_NOT_INITIALIZED =
- const StaticWarningCode('FINAL_NOT_INITIALIZED',
- "The final variable '{0}' must be initialized", null, false);
+ const StaticWarningCode(
+ 'FINAL_NOT_INITIALIZED',
+ "The final variable '{0}' must be initialized.",
+ // TODO(brianwilkerson) Split this error code so that we can suggest
+ // initializing fields in constructors (FINAL_FIELD_NOT_INITIALIZED
+ // and FINAL_VARIABLE_NOT_INITIALIZED).
+ "Try initializing the variable.",
+ false);
/**
* 7.6.1 Generative Constructors: Each final instance variable <i>f</i>
@@ -3695,8 +4309,11 @@
* 0: the name of the uninitialized final variable
*/
static const StaticWarningCode FINAL_NOT_INITIALIZED_CONSTRUCTOR_1 =
- const StaticWarningCode('FINAL_NOT_INITIALIZED_CONSTRUCTOR_1',
- "The final variable '{0}' must be initialized", null, false);
+ const StaticWarningCode(
+ 'FINAL_NOT_INITIALIZED_CONSTRUCTOR_1',
+ "The final variable '{0}' must be initialized.",
+ "Try adding an initializer for the field.",
+ false);
/**
* 7.6.1 Generative Constructors: Each final instance variable <i>f</i>
@@ -3714,8 +4331,8 @@
static const StaticWarningCode FINAL_NOT_INITIALIZED_CONSTRUCTOR_2 =
const StaticWarningCode(
'FINAL_NOT_INITIALIZED_CONSTRUCTOR_2',
- "The final variables '{0}' and '{1}' must be initialized",
- null,
+ "The final variables '{0}' and '{1}' must be initialized.",
+ "Try adding initializers for the fields.",
false);
/**
@@ -3735,8 +4352,8 @@
static const StaticWarningCode FINAL_NOT_INITIALIZED_CONSTRUCTOR_3_PLUS =
const StaticWarningCode(
'FINAL_NOT_INITIALIZED_CONSTRUCTOR_3',
- "The final variables '{0}', '{1}' and '{2}' more must be initialized",
- null,
+ "The final variables '{0}', '{1}' and '{2}' more must be initialized.",
+ "Try adding initializers for the fields.",
false);
/**
@@ -3745,7 +4362,8 @@
*/
static const StaticWarningCode FUNCTION_WITHOUT_CALL = const StaticWarningCode(
'FUNCTION_WITHOUT_CALL',
- "Concrete classes that implement Function must implement the method call()");
+ "Concrete classes that implement 'Function' must implement the method 'call'.",
+ "Try implementing a 'call' method, or don't implement 'Function'.");
/**
* 14.1 Imports: It is a static warning to import two different libraries with
@@ -3757,8 +4375,10 @@
* 2: the shared name of the imported libraries
*/
static const StaticWarningCode IMPORT_DUPLICATED_LIBRARY_NAMED =
- const StaticWarningCode('IMPORT_DUPLICATED_LIBRARY_NAMED',
- "The imported libraries '{0}' and '{1}' cannot have the same name '{2}'");
+ const StaticWarningCode(
+ 'IMPORT_DUPLICATED_LIBRARY_NAMED',
+ "The imported libraries '{0}' and '{1}' can't have the same name '{2}'.",
+ "Try adding a hide clause to one of the imports.");
/**
* 14.1 Imports: It is a static warning if the specified URI of a deferred
@@ -3770,8 +4390,10 @@
* See [CompileTimeErrorCode.IMPORT_OF_NON_LIBRARY].
*/
static const StaticWarningCode IMPORT_OF_NON_LIBRARY =
- const StaticWarningCode('IMPORT_OF_NON_LIBRARY',
- "The imported library '{0}' must not have a part-of directive");
+ const StaticWarningCode(
+ 'IMPORT_OF_NON_LIBRARY',
+ "The imported library '{0}' can't have a part-of directive.",
+ "Try importing the library that the part is a part of.");
/**
* 8.1.1 Inheritance and Overriding: However, if the above rules would cause
@@ -3788,7 +4410,9 @@
INCONSISTENT_METHOD_INHERITANCE_GETTER_AND_METHOD =
const StaticWarningCode(
'INCONSISTENT_METHOD_INHERITANCE_GETTER_AND_METHOD',
- "'{0}' is inherited as a getter and also a method");
+ "'{0}' is inherited as a getter and also a method.",
+ "Try adjusting the supertypes of this class to remove the "
+ "inconsistency.");
/**
* 7.1 Instance Methods: It is a static warning if a class <i>C</i> declares
@@ -3803,7 +4427,8 @@
INSTANCE_METHOD_NAME_COLLIDES_WITH_SUPERCLASS_STATIC =
const StaticWarningCode(
'INSTANCE_METHOD_NAME_COLLIDES_WITH_SUPERCLASS_STATIC',
- "'{0}' collides with a static member in the superclass '{1}'");
+ "'{0}' collides with a static member in the superclass '{1}'.",
+ "Try renaming either the method or the inherited member.");
/**
* 7.2 Getters: It is a static warning if a getter <i>m1</i> overrides a
@@ -3819,8 +4444,11 @@
* See [INVALID_METHOD_OVERRIDE_RETURN_TYPE].
*/
static const StaticWarningCode INVALID_GETTER_OVERRIDE_RETURN_TYPE =
- const StaticWarningCode('INVALID_GETTER_OVERRIDE_RETURN_TYPE',
- "The return type '{0}' is not assignable to '{1}' as required by the getter it is overriding from '{2}'");
+ const StaticWarningCode(
+ 'INVALID_GETTER_OVERRIDE_RETURN_TYPE',
+ "The return type '{0}' isn't assignable to '{1}' as required by the "
+ "getter it is overriding from '{2}'.",
+ "Try changing the return types so that they are compatible.");
/**
* 7.1 Instance Methods: It is a static warning if an instance method
@@ -3834,8 +4462,11 @@
* 2: the name of the class where the overridden method is declared
*/
static const StaticWarningCode INVALID_METHOD_OVERRIDE_NAMED_PARAM_TYPE =
- const StaticWarningCode('INVALID_METHOD_OVERRIDE_NAMED_PARAM_TYPE',
- "The parameter type '{0}' is not assignable to '{1}' as required by the method it is overriding from '{2}'");
+ const StaticWarningCode(
+ 'INVALID_METHOD_OVERRIDE_NAMED_PARAM_TYPE',
+ "The parameter type '{0}' isn't assignable to '{1}' as required by "
+ "the method it is overriding from '{2}'.",
+ "Try changing the parameter types so that they are compatible.");
/**
* Generic Method DEP: number of type parameters must match.
@@ -3847,8 +4478,11 @@
* 2: the name of the class where the overridden method is declared
*/
static const StaticWarningCode INVALID_METHOD_OVERRIDE_TYPE_PARAMETERS =
- const StaticWarningCode('INVALID_METHOD_OVERRIDE_TYPE_PARAMETERS',
- "The method has {0} type parameters, but it is overriding a method with {1} type parameters from '{2}'");
+ const StaticWarningCode(
+ 'INVALID_METHOD_OVERRIDE_TYPE_PARAMETERS',
+ "The method has {0} type parameters, but it is overriding a method "
+ "with {1} type parameters from '{2}'.",
+ "Try changing the number of type parameters so that they are the same.");
/**
* Generic Method DEP: bounds of type parameters must be compatible.
@@ -3862,8 +4496,11 @@
* 4: the name of the class where the overridden method is declared
*/
static const StaticWarningCode INVALID_METHOD_OVERRIDE_TYPE_PARAMETER_BOUND =
- const StaticWarningCode('INVALID_METHOD_OVERRIDE_TYPE_PARAMETER_BOUND',
- "The type parameter '{0}' extends '{1}', but that is stricter than '{2}' extends '{3}' in the overridden method from '{4}'");
+ const StaticWarningCode(
+ 'INVALID_METHOD_OVERRIDE_TYPE_PARAMETER_BOUND',
+ "The type parameter '{0}' extends '{1}', but that is stricter than "
+ "'{2}' extends '{3}' in the overridden method from '{4}'.",
+ "Try changing the bounds on the type parameters so that they are compatible.");
/**
* 7.1 Instance Methods: It is a static warning if an instance method
@@ -3878,8 +4515,11 @@
* See [INVALID_SETTER_OVERRIDE_NORMAL_PARAM_TYPE].
*/
static const StaticWarningCode INVALID_METHOD_OVERRIDE_NORMAL_PARAM_TYPE =
- const StaticWarningCode('INVALID_METHOD_OVERRIDE_NORMAL_PARAM_TYPE',
- "The parameter type '{0}' is not assignable to '{1}' as required by the method it is overriding from '{2}'");
+ const StaticWarningCode(
+ 'INVALID_METHOD_OVERRIDE_NORMAL_PARAM_TYPE',
+ "The parameter type '{0}' isn't assignable to '{1}' as required by "
+ "the method it is overriding from '{2}'.",
+ "Try changing the parameter types so that they are compatible.");
/**
* 7.1 Instance Methods: It is a static warning if an instance method
@@ -3893,8 +4533,11 @@
* 2: the name of the class where the overridden method is declared
*/
static const StaticWarningCode INVALID_METHOD_OVERRIDE_OPTIONAL_PARAM_TYPE =
- const StaticWarningCode('INVALID_METHOD_OVERRIDE_OPTIONAL_PARAM_TYPE',
- "The parameter type '{0}' is not assignable to '{1}' as required by the method it is overriding from '{2}'");
+ const StaticWarningCode(
+ 'INVALID_METHOD_OVERRIDE_OPTIONAL_PARAM_TYPE',
+ "The parameter type '{0}' isn't assignable to '{1}' as required by "
+ "the method it is overriding from '{2}'.",
+ "Try changing the parameter types so that they are compatible.");
/**
* 7.1 Instance Methods: It is a static warning if an instance method
@@ -3910,8 +4553,11 @@
* See [INVALID_GETTER_OVERRIDE_RETURN_TYPE].
*/
static const StaticWarningCode INVALID_METHOD_OVERRIDE_RETURN_TYPE =
- const StaticWarningCode('INVALID_METHOD_OVERRIDE_RETURN_TYPE',
- "The return type '{0}' is not assignable to '{1}' as required by the method it is overriding from '{2}'");
+ const StaticWarningCode(
+ 'INVALID_METHOD_OVERRIDE_RETURN_TYPE',
+ "The return type '{0}' isn't assignable to '{1}' as required by the "
+ "method it is overriding from '{2}'.",
+ "Try changing the return types so that they are compatible.");
/**
* 7.1 Instance Methods: It is a static warning if an instance method
@@ -3923,7 +4569,9 @@
static const StaticWarningCode
INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_NAMED = const StaticWarningCode(
'INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_NAMED',
- "Parameters cannot override default values, this method overrides '{0}.{1}' where '{2}' has a different value");
+ "Parameters can't override default values, "
+ "this method overrides '{0}.{1}' where '{2}' has a different value.",
+ "Try using the same default value in both methods.");
/**
* 7.1 Instance Methods: It is a static warning if an instance method
@@ -3936,7 +4584,9 @@
INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_POSITIONAL =
const StaticWarningCode(
'INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_POSITIONAL',
- "Parameters cannot override default values, this method overrides '{0}.{1}' where this positional parameter has a different value");
+ "Parameters can't override default values, this method overrides "
+ "'{0}.{1}' where this positional parameter has a different value.",
+ "Try using the same default value in both methods.");
/**
* 7.1 Instance Methods: It is a static warning if an instance method
@@ -3948,9 +4598,13 @@
* 1: the signature of the overridden member
* 2: the name of the class from the overridden method
*/
- static const StaticWarningCode INVALID_OVERRIDE_NAMED = const StaticWarningCode(
- 'INVALID_OVERRIDE_NAMED',
- "Missing the named parameter '{0}' to match the overridden method from '{1}' from '{2}'");
+ static const StaticWarningCode INVALID_OVERRIDE_NAMED =
+ const StaticWarningCode(
+ 'INVALID_OVERRIDE_NAMED',
+ "Missing the named parameter '{0}' "
+ "to match the overridden method from '{1}' from '{2}'.",
+ "Try adding the named parameter to this method, or "
+ "removing it from the overridden method.");
/**
* 7.1 Instance Methods: It is a static warning if an instance method
@@ -3963,8 +4617,11 @@
* 2: the name of the class from the overridden method
*/
static const StaticWarningCode INVALID_OVERRIDE_POSITIONAL =
- const StaticWarningCode('INVALID_OVERRIDE_POSITIONAL',
- "Must have at least {0} parameters to match the overridden method '{1}' from '{2}'");
+ const StaticWarningCode(
+ 'INVALID_OVERRIDE_POSITIONAL',
+ "Must have at least {0} parameters "
+ "to match the overridden method '{1}' from '{2}'.",
+ "Try adding the necessary parameters.");
/**
* 7.1 Instance Methods: It is a static warning if an instance method
@@ -3977,8 +4634,11 @@
* 2: the name of the class from the overridden method
*/
static const StaticWarningCode INVALID_OVERRIDE_REQUIRED =
- const StaticWarningCode('INVALID_OVERRIDE_REQUIRED',
- "Must have {0} required parameters or less to match the overridden method '{1}' from '{2}'");
+ const StaticWarningCode(
+ 'INVALID_OVERRIDE_REQUIRED',
+ "Must have {0} required parameters or less "
+ "to match the overridden method '{1}' from '{2}'.",
+ "Try removing the extra parameters.");
/**
* 7.3 Setters: It is a static warning if a setter <i>m1</i> overrides a
@@ -3994,8 +4654,11 @@
* See [INVALID_METHOD_OVERRIDE_NORMAL_PARAM_TYPE].
*/
static const StaticWarningCode INVALID_SETTER_OVERRIDE_NORMAL_PARAM_TYPE =
- const StaticWarningCode('INVALID_SETTER_OVERRIDE_NORMAL_PARAM_TYPE',
- "The parameter type '{0}' is not assignable to '{1}' as required by the setter it is overriding from '{2}'");
+ const StaticWarningCode(
+ 'INVALID_SETTER_OVERRIDE_NORMAL_PARAM_TYPE',
+ "The parameter type '{0}' isn't assignable to '{1}' as required by "
+ "the setter it is overriding from '{2}'.",
+ "Try changing the parameter types so that they are compatible.");
/**
* 12.6 Lists: A run-time list literal <<i>E</i>> [<i>e<sub>1</sub></i>
@@ -4012,7 +4675,7 @@
*/
static const StaticWarningCode LIST_ELEMENT_TYPE_NOT_ASSIGNABLE =
const StaticWarningCode('LIST_ELEMENT_TYPE_NOT_ASSIGNABLE',
- "The element type '{0}' cannot be assigned to the list type '{1}'");
+ "The element type '{0}' can't be assigned to the list type '{1}'.");
/**
* 12.7 Map: A run-time map literal <<i>K</i>, <i>V</i>>
@@ -4031,7 +4694,7 @@
*/
static const StaticWarningCode MAP_KEY_TYPE_NOT_ASSIGNABLE =
const StaticWarningCode('MAP_KEY_TYPE_NOT_ASSIGNABLE',
- "The element type '{0}' cannot be assigned to the map key type '{1}'");
+ "The element type '{0}' can't be assigned to the map key type '{1}'.");
/**
* 12.7 Map: A run-time map literal <<i>K</i>, <i>V</i>>
@@ -4050,7 +4713,7 @@
*/
static const StaticWarningCode MAP_VALUE_TYPE_NOT_ASSIGNABLE =
const StaticWarningCode('MAP_VALUE_TYPE_NOT_ASSIGNABLE',
- "The element type '{0}' cannot be assigned to the map value type '{1}'");
+ "The element type '{0}' can't be assigned to the map value type '{1}'.");
/**
* 7.3 Setters: It is a static warning if a class has a setter named <i>v=</i>
@@ -4060,8 +4723,9 @@
static const StaticWarningCode MISMATCHED_GETTER_AND_SETTER_TYPES =
const StaticWarningCode(
'MISMATCHED_GETTER_AND_SETTER_TYPES',
- "The parameter type for setter '{0}' is '{1}' which is not assignable to its getter (of type '{2}')",
- null,
+ "The parameter type for setter '{0}' is '{1}' which isn't assignable "
+ "to its getter (of type '{2}').",
+ "Try changing the types so that they are compatible.",
false);
/**
@@ -4073,8 +4737,9 @@
MISMATCHED_GETTER_AND_SETTER_TYPES_FROM_SUPERTYPE =
const StaticWarningCode(
'MISMATCHED_GETTER_AND_SETTER_TYPES_FROM_SUPERTYPE',
- "The parameter type for setter '{0}' is '{1}' which is not assignable to its getter (of type '{2}'), from superclass '{3}'",
- null,
+ "The parameter type for setter '{0}' is '{1}' which isn't assignable "
+ "to its getter (of type '{2}'), from superclass '{3}'.",
+ "Try changing the types so that they are compatible.",
false);
/**
@@ -4093,8 +4758,9 @@
static const StaticWarningCode MISSING_ENUM_CONSTANT_IN_SWITCH =
const StaticWarningCode(
'MISSING_ENUM_CONSTANT_IN_SWITCH',
- "Missing case clause for '{0}'",
- "Add a case clause for the missing constant or add a default clause.",
+ "Missing case clause for '{0}'.",
+ "Try adding a case clause for the missing constant, or "
+ "adding a default clause.",
false);
/**
@@ -4104,8 +4770,11 @@
*/
static const StaticWarningCode MIXED_RETURN_TYPES = const StaticWarningCode(
'MIXED_RETURN_TYPES',
- "Methods and functions cannot use return both with and without values",
- null,
+ "Functions can't include return statements both with and without values.",
+ // TODO(brianwilkerson) Split this error code depending on whether the
+ // function declares a return type.
+ "Try making all the return statements consistent "
+ "(either include a value or not).",
false);
/**
@@ -4113,8 +4782,10 @@
* abstract class and <i>q</i> is not a factory constructor.
*/
static const StaticWarningCode NEW_WITH_ABSTRACT_CLASS =
- const StaticWarningCode('NEW_WITH_ABSTRACT_CLASS',
- "Abstract classes cannot be created with a 'new' expression");
+ const StaticWarningCode(
+ 'NEW_WITH_ABSTRACT_CLASS',
+ "Abstract classes can't be created with a 'new' expression.",
+ "Try creating an instance of a subtype.");
/**
* 15.8 Parameterized Types: Any use of a malbounded type gives rise to a
@@ -4129,8 +4800,11 @@
* [StaticTypeWarningCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS].
*/
static const StaticWarningCode NEW_WITH_INVALID_TYPE_PARAMETERS =
- const StaticWarningCode('NEW_WITH_INVALID_TYPE_PARAMETERS',
- "The type '{0}' is declared with {1} type parameters, but {2} type arguments were given");
+ const StaticWarningCode(
+ 'NEW_WITH_INVALID_TYPE_PARAMETERS',
+ "The type '{0}' is declared with {1} type parameters, "
+ "but {2} type arguments were given.",
+ "Try adjusting the number of type arguments.");
/**
* 12.11.1 New: It is a static warning if <i>T</i> is not a class accessible
@@ -4140,7 +4814,9 @@
* 0: the name of the non-type element
*/
static const StaticWarningCode NEW_WITH_NON_TYPE = const StaticWarningCode(
- 'NEW_WITH_NON_TYPE', "The name '{0}' is not a class");
+ 'NEW_WITH_NON_TYPE',
+ "The name '{0}' isn't a class.",
+ "Try correcting the name to match an existing class.");
/**
* 12.11.1 New: If <i>T</i> is a class or parameterized type accessible in the
@@ -4156,8 +4832,11 @@
* declare a constructor with the same name as the declaration of <i>T</i>.
*/
static const StaticWarningCode NEW_WITH_UNDEFINED_CONSTRUCTOR =
- const StaticWarningCode('NEW_WITH_UNDEFINED_CONSTRUCTOR',
- "The class '{0}' does not have a constructor '{1}'");
+ const StaticWarningCode(
+ 'NEW_WITH_UNDEFINED_CONSTRUCTOR',
+ "The class '{0}' doesn't have a constructor named '{1}'.",
+ "Try invoking a different constructor, or "
+ "define a constructor named '{1}'.");
/**
* 12.11.1 New: If <i>T</i> is a class or parameterized type accessible in the
@@ -4172,8 +4851,10 @@
* same name as the declaration of <i>T</i>.
*/
static const StaticWarningCode NEW_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT =
- const StaticWarningCode('NEW_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT',
- "The class '{0}' does not have a default constructor");
+ const StaticWarningCode(
+ 'NEW_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT',
+ "The class '{0}' doesn't have a default constructor.",
+ "Try using one of the named constructors defined in '{0}'.");
/**
* 7.9.1 Inheritance and Overriding: It is a static warning if a non-abstract
@@ -4200,7 +4881,8 @@
NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FIVE_PLUS =
const StaticWarningCode(
'NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FIVE_PLUS',
- "Missing concrete implementation of {0}, {1}, {2}, {3} and {4} more");
+ "Missing concrete implementations of {0}, {1}, {2}, {3} and {4} more.",
+ "Try implementing the missing methods, or make the class abstract.");
/**
* 7.9.1 Inheritance and Overriding: It is a static warning if a non-abstract
@@ -4226,7 +4908,8 @@
NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FOUR =
const StaticWarningCode(
'NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FOUR',
- "Missing concrete implementation of {0}, {1}, {2} and {3}");
+ "Missing concrete implementations of {0}, {1}, {2} and {3}.",
+ "Try implementing the missing methods, or make the class abstract.");
/**
* 7.9.1 Inheritance and Overriding: It is a static warning if a non-abstract
@@ -4248,7 +4931,8 @@
static const StaticWarningCode
NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_ONE = const StaticWarningCode(
'NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_ONE',
- "Missing concrete implementation of {0}");
+ "Missing concrete implementation of {0}.",
+ "Try implementing the missing method, or make the class abstract.");
/**
* 7.9.1 Inheritance and Overriding: It is a static warning if a non-abstract
@@ -4273,7 +4957,8 @@
NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_THREE =
const StaticWarningCode(
'NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_THREE',
- "Missing concrete implementation of {0}, {1} and {2}");
+ "Missing concrete implementations of {0}, {1} and {2}.",
+ "Try implementing the missing methods, or make the class abstract.");
/**
* 7.9.1 Inheritance and Overriding: It is a static warning if a non-abstract
@@ -4296,7 +4981,8 @@
static const StaticWarningCode
NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_TWO = const StaticWarningCode(
'NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_TWO',
- "Missing concrete implementation of {0} and {1}");
+ "Missing concrete implementations of {0} and {1}.",
+ "Try implementing the missing methods, or make the class abstract.");
/**
* 13.11 Try: An on-catch clause of the form <i>on T catch (p<sub>1</sub>,
@@ -4309,24 +4995,33 @@
* 0: the name of the non-type element
*/
static const StaticWarningCode NON_TYPE_IN_CATCH_CLAUSE =
- const StaticWarningCode('NON_TYPE_IN_CATCH_CLAUSE',
- "The name '{0}' is not a type and cannot be used in an on-catch clause");
+ const StaticWarningCode(
+ 'NON_TYPE_IN_CATCH_CLAUSE',
+ "The name '{0}' isn't a type and can't be used in an on-catch clause.",
+ "Try correcting the name to match an existing class.");
/**
* 7.1.1 Operators: It is a static warning if the return type of the
* user-declared operator []= is explicitly declared and not void.
*/
static const StaticWarningCode NON_VOID_RETURN_FOR_OPERATOR =
- const StaticWarningCode('NON_VOID_RETURN_FOR_OPERATOR',
- "The return type of the operator []= must be 'void'", null, false);
+ const StaticWarningCode(
+ 'NON_VOID_RETURN_FOR_OPERATOR',
+ "The return type of the operator []= must be 'void'.",
+ "Try changing the return type to 'void'.",
+ false);
/**
* 7.3 Setters: It is a static warning if a setter declares a return type
* other than void.
*/
static const StaticWarningCode NON_VOID_RETURN_FOR_SETTER =
- const StaticWarningCode('NON_VOID_RETURN_FOR_SETTER',
- "The return type of the setter must be 'void'", null, false);
+ const StaticWarningCode(
+ 'NON_VOID_RETURN_FOR_SETTER',
+ "The return type of the setter must be 'void' or absent.",
+ "Try removing the return type, or "
+ "define a method rather than a setter.",
+ false);
/**
* 15.1 Static Types: A type <i>T</i> is malformed iff:
@@ -4343,8 +5038,10 @@
* Parameters:
* 0: the name that is not a type
*/
- static const StaticWarningCode NOT_A_TYPE =
- const StaticWarningCode('NOT_A_TYPE', "{0} is not a type");
+ static const StaticWarningCode NOT_A_TYPE = const StaticWarningCode(
+ 'NOT_A_TYPE',
+ "{0} isn't a type.",
+ "Try correcting the name to match an existing type.");
/**
* 12.14.2 Binding Actuals to Formals: It is a static warning if <i>m <
@@ -4357,8 +5054,10 @@
* See [EXTRA_POSITIONAL_ARGUMENTS].
*/
static const StaticWarningCode NOT_ENOUGH_REQUIRED_ARGUMENTS =
- const StaticWarningCode('NOT_ENOUGH_REQUIRED_ARGUMENTS',
- "{0} required argument(s) expected, but {1} found");
+ const StaticWarningCode(
+ 'NOT_ENOUGH_REQUIRED_ARGUMENTS',
+ "{0} required argument(s) expected, but {1} found.",
+ "Try adding the additional required arguments.");
/**
* 14.3 Parts: It is a static warning if the referenced part declaration
@@ -4370,8 +5069,11 @@
* 1: the non-matching actual library name from the "part of" declaration
*/
static const StaticWarningCode PART_OF_DIFFERENT_LIBRARY =
- const StaticWarningCode('PART_OF_DIFFERENT_LIBRARY',
- "Expected this library to be part of '{0}', not '{1}'");
+ const StaticWarningCode(
+ 'PART_OF_DIFFERENT_LIBRARY',
+ "Expected this library to be part of '{0}', not '{1}'.",
+ "Try including a different part, or "
+ "changing the name of the library in the part's part-of directive.");
/**
* 7.6.2 Factories: It is a static warning if the function type of <i>k'</i>
@@ -4382,20 +5084,26 @@
* 1: the name of the redirecting constructor
*/
static const StaticWarningCode REDIRECT_TO_INVALID_FUNCTION_TYPE =
- const StaticWarningCode('REDIRECT_TO_INVALID_FUNCTION_TYPE',
- "The redirected constructor '{0}' has incompatible parameters with '{1}'");
+ const StaticWarningCode(
+ 'REDIRECT_TO_INVALID_FUNCTION_TYPE',
+ "The redirected constructor '{0}' has incompatible parameters with '{1}'.",
+ "Try redirecting to a different constructor, or "
+ "directly invoking the desired constructor rather than redirecting to it.");
/**
* 7.6.2 Factories: It is a static warning if the function type of <i>k'</i>
* is not a subtype of the type of <i>k</i>.
*
* Parameters:
- * 0: the name of the redirected constructor return type
- * 1: the name of the redirecting constructor return type
+ * 0: the name of the redirected constructor's return type
+ * 1: the name of the redirecting constructor's return type
*/
static const StaticWarningCode REDIRECT_TO_INVALID_RETURN_TYPE =
- const StaticWarningCode('REDIRECT_TO_INVALID_RETURN_TYPE',
- "The return type '{0}' of the redirected constructor is not assignable to '{1}'");
+ const StaticWarningCode(
+ 'REDIRECT_TO_INVALID_RETURN_TYPE',
+ "The return type '{0}' of the redirected constructor isn't assignable to '{1}'.",
+ "Try redirecting to a different constructor, or "
+ "directly invoking the desired constructor rather than redirecting to it.");
/**
* 7.6.2 Factories: It is a static warning if type does not denote a class
@@ -4404,8 +5112,11 @@
* <i>type.id</i>) is not a constructor of <i>C</i>.
*/
static const StaticWarningCode REDIRECT_TO_MISSING_CONSTRUCTOR =
- const StaticWarningCode('REDIRECT_TO_MISSING_CONSTRUCTOR',
- "The constructor '{0}' could not be found in '{1}'");
+ const StaticWarningCode(
+ 'REDIRECT_TO_MISSING_CONSTRUCTOR',
+ "The constructor '{0}' couldn't be found in '{1}'.",
+ "Try correcting the constructor name to an existing constructor, or "
+ "defining the constructor in '{1}'.");
/**
* 7.6.2 Factories: It is a static warning if type does not denote a class
@@ -4415,7 +5126,8 @@
*/
static const StaticWarningCode REDIRECT_TO_NON_CLASS = const StaticWarningCode(
'REDIRECT_TO_NON_CLASS',
- "The name '{0}' is not a type and cannot be used in a redirected constructor");
+ "The name '{0}' isn't a type and can't be used in a redirected constructor.",
+ "Try correcting the name to match an existing class.");
/**
* 13.12 Return: Let <i>f</i> be the function immediately enclosing a return
@@ -4426,7 +5138,7 @@
*/
static const StaticWarningCode RETURN_WITHOUT_VALUE = const StaticWarningCode(
'RETURN_WITHOUT_VALUE',
- "Missing return value after 'return'",
+ "Missing return value after 'return'.",
null,
false);
@@ -4439,15 +5151,17 @@
*/
static const StaticWarningCode STATIC_ACCESS_TO_INSTANCE_MEMBER =
const StaticWarningCode('STATIC_ACCESS_TO_INSTANCE_MEMBER',
- "Instance member '{0}' cannot be accessed using static access");
+ "Instance member '{0}' can't be accessed using static access.");
/**
* 13.9 Switch: It is a static warning if the type of <i>e</i> may not be
* assigned to the type of <i>e<sub>k</sub></i>.
*/
static const StaticWarningCode SWITCH_EXPRESSION_NOT_ASSIGNABLE =
- const StaticWarningCode('SWITCH_EXPRESSION_NOT_ASSIGNABLE',
- "Type '{0}' of the switch expression is not assignable to the type '{1}' of case expressions");
+ const StaticWarningCode(
+ 'SWITCH_EXPRESSION_NOT_ASSIGNABLE',
+ "Type '{0}' of the switch expression isn't assignable to "
+ "the type '{1}' of case expressions.");
/**
* 15.1 Static Types: It is a static warning to use a deferred type in a type
@@ -4458,24 +5172,32 @@
* annotation
*/
static const StaticWarningCode TYPE_ANNOTATION_DEFERRED_CLASS =
- const StaticWarningCode('TYPE_ANNOTATION_DEFERRED_CLASS',
- "The deferred type '{0}' cannot be used in a declaration, cast or type test");
+ const StaticWarningCode(
+ 'TYPE_ANNOTATION_DEFERRED_CLASS',
+ "The deferred type '{0}' can't be used in a declaration, cast or type test.",
+ "Try using a different type, or "
+ "changing the import to not be deferred.");
/**
* 12.31 Type Test: It is a static warning if <i>T</i> does not denote a type
* available in the current lexical scope.
*/
- static const StaticWarningCode TYPE_TEST_WITH_NON_TYPE = const StaticWarningCode(
- 'TYPE_TEST_WITH_NON_TYPE',
- "The name '{0}' is not a type and cannot be used in an 'is' expression");
+ static const StaticWarningCode TYPE_TEST_WITH_NON_TYPE =
+ const StaticWarningCode(
+ 'TYPE_TEST_WITH_NON_TYPE',
+ "The name '{0}' isn't a type and can't be used in an 'is' expression.",
+ "Try correcting the name to match an existing type.");
/**
* 12.31 Type Test: It is a static warning if <i>T</i> does not denote a type
* available in the current lexical scope.
*/
static const StaticWarningCode TYPE_TEST_WITH_UNDEFINED_NAME =
- const StaticWarningCode('TYPE_TEST_WITH_UNDEFINED_NAME',
- "The name '{0}' is not defined and cannot be used in an 'is' expression");
+ const StaticWarningCode(
+ 'TYPE_TEST_WITH_UNDEFINED_NAME',
+ "The name '{0}' isn't defined, so it can't be used in an 'is' expression.",
+ "Try changing the name to the name of an existing type, or "
+ "creating a type with the name '{0}'.");
/**
* 10 Generics: However, a type parameter is considered to be a malformed type
@@ -4486,8 +5208,11 @@
* checker and the runtime.
*/
static const StaticWarningCode TYPE_PARAMETER_REFERENCED_BY_STATIC =
- const StaticWarningCode('TYPE_PARAMETER_REFERENCED_BY_STATIC',
- "Static members cannot reference type parameters of the class");
+ const StaticWarningCode(
+ 'TYPE_PARAMETER_REFERENCED_BY_STATIC',
+ "Static members can't reference type parameters of the class.",
+ "Try removing the reference to the type parameter, or "
+ "making the member an instance member.");
/**
* 12.16.3 Static Invocation: A static method invocation <i>i</i> has the form
@@ -4498,15 +5223,18 @@
* Parameters:
* 0: the name of the undefined class
*/
- static const StaticWarningCode UNDEFINED_CLASS =
- const StaticWarningCode('UNDEFINED_CLASS', "Undefined class '{0}'");
+ static const StaticWarningCode UNDEFINED_CLASS = const StaticWarningCode(
+ 'UNDEFINED_CLASS',
+ "Undefined class '{0}'.",
+ "Try changing the name to the name of an existing class, or "
+ "creating a class with the name '{0}'.");
/**
* Same as [UNDEFINED_CLASS], but to catch using "boolean" instead of "bool".
*/
static const StaticWarningCode UNDEFINED_CLASS_BOOLEAN =
const StaticWarningCode('UNDEFINED_CLASS_BOOLEAN',
- "Undefined class 'boolean'; did you mean 'bool'?");
+ "Undefined class 'boolean'.", "Try using the type 'bool'.");
/**
* 12.17 Getter Invocation: It is a static warning if there is no class
@@ -4519,8 +5247,8 @@
*/
static const StaticWarningCode UNDEFINED_GETTER = const StaticWarningCode(
'UNDEFINED_GETTER',
- "The getter '{0}' is not defined for the class '{1}'.",
- null);
+ "The getter '{0}' isn't defined for the class '{1}'.",
+ "Try defining a getter or field named '{0}', or invoke a different getter.");
/**
* 12.30 Identifier Reference: It is as static warning if an identifier
@@ -4532,15 +5260,22 @@
* Parameters:
* 0: the name of the identifier
*/
- static const StaticWarningCode UNDEFINED_IDENTIFIER =
- const StaticWarningCode('UNDEFINED_IDENTIFIER', "Undefined name '{0}'");
+ static const StaticWarningCode UNDEFINED_IDENTIFIER = const StaticWarningCode(
+ 'UNDEFINED_IDENTIFIER',
+ "Undefined name '{0}'.",
+ "Try correcting the name to one that is defined, or "
+ "defining the name.");
/**
* If the identifier is 'await', be helpful about it.
*/
static const StaticWarningCode UNDEFINED_IDENTIFIER_AWAIT =
- const StaticWarningCode('UNDEFINED_IDENTIFIER_AWAIT',
- "Undefined name 'await'; did you mean to add the 'async' marker to '{0}'?");
+ const StaticWarningCode(
+ 'UNDEFINED_IDENTIFIER_AWAIT',
+ "Undefined name 'await'.",
+ "Try correcting the name to one that is defined, "
+ "defining the name, or "
+ "adding 'async' to the enclosing function body.");
/**
* 12.14.2 Binding Actuals to Formals: Furthermore, each <i>q<sub>i</sub></i>,
@@ -4552,8 +5287,11 @@
* 0: the name of the requested named parameter
*/
static const StaticWarningCode UNDEFINED_NAMED_PARAMETER =
- const StaticWarningCode('UNDEFINED_NAMED_PARAMETER',
- "The named parameter '{0}' is not defined");
+ const StaticWarningCode(
+ 'UNDEFINED_NAMED_PARAMETER',
+ "The named parameter '{0}' isn't defined.",
+ "Try correcting the name to an existing named parameter, or "
+ "defining a new parameter with this name.");
/**
* 12.18 Assignment: It is as static warning if an assignment of the form
@@ -4572,8 +5310,8 @@
*/
static const StaticWarningCode UNDEFINED_SETTER = const StaticWarningCode(
'UNDEFINED_SETTER',
- "The setter '{0}' is not defined for the class '{1}'.",
- null);
+ "The setter '{0}' isn't defined for the class '{1}'.",
+ "Try defining a setter or field named '{0}', or invoke a different setter.");
/**
* 12.16.3 Static Invocation: It is a static warning if <i>C</i> does not
@@ -4584,8 +5322,11 @@
* 1: the name of the enclosing type where the method is being looked for
*/
static const StaticWarningCode UNDEFINED_STATIC_METHOD_OR_GETTER =
- const StaticWarningCode('UNDEFINED_STATIC_METHOD_OR_GETTER',
- "The static method, getter or setter '{0}' is not defined for the class '{1}'");
+ const StaticWarningCode(
+ 'UNDEFINED_STATIC_METHOD_OR_GETTER',
+ "The static method, getter or setter '{0}' isn't defined for the class '{1}'.",
+ "Try correcting the name to an existing member, or "
+ "defining the member in '{1}'.");
/**
* 12.17 Getter Invocation: It is a static warning if there is no class
@@ -4597,8 +5338,11 @@
* 1: the name of the enclosing type where the getter is being looked for
*/
static const StaticWarningCode UNDEFINED_SUPER_GETTER =
- const StaticWarningCode('UNDEFINED_SUPER_GETTER',
- "The getter '{0}' is not defined in a superclass of '{1}'.", null);
+ const StaticWarningCode(
+ 'UNDEFINED_SUPER_GETTER',
+ "The getter '{0}' isn't defined in a superclass of '{1}'.",
+ "Try correcting the name to an existing getter, or "
+ "defining the getter in a superclass of '{1}'.");
/**
* 12.18 Assignment: It is as static warning if an assignment of the form
@@ -4616,15 +5360,21 @@
* 1: the name of the enclosing type where the setter is being looked for
*/
static const StaticWarningCode UNDEFINED_SUPER_SETTER =
- const StaticWarningCode('UNDEFINED_SUPER_SETTER',
- "The setter '{0}' is not defined in a superclass of '{1}'.", null);
+ const StaticWarningCode(
+ 'UNDEFINED_SUPER_SETTER',
+ "The setter '{0}' isn't defined in a superclass of '{1}'.",
+ "Try correcting the name to an existing setter, or "
+ "defining the setter in a superclass of '{1}'.");
/**
* 7.2 Getters: It is a static warning if the return type of a getter is void.
*/
static const StaticWarningCode VOID_RETURN_FOR_GETTER =
- const StaticWarningCode('VOID_RETURN_FOR_GETTER',
- "The return type of the getter must not be 'void'", null, false);
+ const StaticWarningCode(
+ 'VOID_RETURN_FOR_GETTER',
+ "The return type of a getter can't be 'void'.",
+ "Try providing a return type for the getter.",
+ false);
/**
* A flag indicating whether this warning is an error when running with strong
@@ -4659,19 +5409,13 @@
*/
class StrongModeCode extends ErrorCode {
static const String _implicitCastMessage =
- 'Unsound implicit cast from {0} to {1}';
+ "Unsound implicit cast from '{0}' to '{1}'.";
- static const String _unsafeBlockClosureInferenceMessage =
- 'Unsafe use of block closure in a type-inferred variable outside a '
- 'function body. Workaround: add a type annotation for `{0}`. See '
- 'dartbug.com/26947';
-
- static const String _typeCheckMessage =
- 'Type check failed: {0} is not of type {1}';
+ static const String _implicitCastCorrection =
+ "Try adding an explicit cast to '{1}'.";
static const String _invalidOverrideMessage =
- 'The type of {0}.{1} ({2}) is not a '
- 'subtype of {3}.{1} ({4}).';
+ "The type of '{0}.{1}' ('{2}') isn't a subtype of '{3}.{1}' ('{4}').";
/**
* This is appended to the end of an error message about implicit dynamic.
@@ -4680,35 +5424,52 @@
* result of turning on a particular option, and they are free to turn it
* back off.
*/
- static const String _implicitDynamicTip =
- ". Either add an explicit type like 'dynamic'"
- ", or enable implicit-dynamic in your Analyzer options.";
+ static const String _implicitDynamicCorrection =
+ "Try adding an explicit type like 'dynamic', or "
+ "enable implicit-dynamic in your analysis options file.";
- static const String _inferredTypeMessage = '{0} has inferred type {1}';
+ static const String _inferredTypeMessage = "'{0}' has inferred type '{1}'.";
static const StrongModeCode DOWN_CAST_COMPOSITE = const StrongModeCode(
- ErrorType.STATIC_WARNING, 'DOWN_CAST_COMPOSITE', _implicitCastMessage);
+ ErrorType.STATIC_WARNING,
+ 'DOWN_CAST_COMPOSITE',
+ _implicitCastMessage,
+ _implicitCastCorrection);
static const StrongModeCode DOWN_CAST_IMPLICIT = const StrongModeCode(
- ErrorType.HINT, 'DOWN_CAST_IMPLICIT', _implicitCastMessage);
+ ErrorType.HINT,
+ 'DOWN_CAST_IMPLICIT',
+ _implicitCastMessage,
+ _implicitCastCorrection);
static const StrongModeCode DOWN_CAST_IMPLICIT_ASSIGN = const StrongModeCode(
- ErrorType.HINT, 'DOWN_CAST_IMPLICIT_ASSIGN', _implicitCastMessage);
+ ErrorType.HINT,
+ 'DOWN_CAST_IMPLICIT_ASSIGN',
+ _implicitCastMessage,
+ _implicitCastCorrection);
static const StrongModeCode DYNAMIC_CAST = const StrongModeCode(
- ErrorType.HINT, 'DYNAMIC_CAST', _implicitCastMessage);
+ ErrorType.HINT,
+ 'DYNAMIC_CAST',
+ _implicitCastMessage,
+ _implicitCastCorrection);
static const StrongModeCode ASSIGNMENT_CAST = const StrongModeCode(
- ErrorType.HINT, 'ASSIGNMENT_CAST', _implicitCastMessage);
+ ErrorType.HINT,
+ 'ASSIGNMENT_CAST',
+ _implicitCastMessage,
+ _implicitCastCorrection);
static const StrongModeCode INVALID_PARAMETER_DECLARATION =
- const StrongModeCode(ErrorType.COMPILE_TIME_ERROR,
- 'INVALID_PARAMETER_DECLARATION', _typeCheckMessage);
+ const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'INVALID_PARAMETER_DECLARATION',
+ "Type check failed: '{0}' isn't of type '{1}'.");
static const StrongModeCode COULD_NOT_INFER = const StrongModeCode(
ErrorType.COMPILE_TIME_ERROR,
'COULD_NOT_INFER',
- "Could not infer type parameter {0}, {1} must be of type {2}.");
+ "Couldn't infer type parameter '{0}'; '{1}' must be of type '{2}'.");
static const StrongModeCode INFERRED_TYPE = const StrongModeCode(
ErrorType.HINT, 'INFERRED_TYPE', _inferredTypeMessage);
@@ -4725,107 +5486,111 @@
static const StrongModeCode STATIC_TYPE_ERROR = const StrongModeCode(
ErrorType.COMPILE_TIME_ERROR,
'STATIC_TYPE_ERROR',
- 'Type check failed: {0} ({1}) is not of type {2}');
+ "Type check failed: '{0}' ('{1}') isn't of type '{2}'.");
static const StrongModeCode INVALID_SUPER_INVOCATION = const StrongModeCode(
ErrorType.COMPILE_TIME_ERROR,
'INVALID_SUPER_INVOCATION',
"super call must be last in an initializer "
- "list (see https://goo.gl/EY6hDP): {0}");
+ "list (see https://goo.gl/EY6hDP): '{0}'.");
static const StrongModeCode NON_GROUND_TYPE_CHECK_INFO = const StrongModeCode(
ErrorType.HINT,
'NON_GROUND_TYPE_CHECK_INFO',
- "Runtime check on non-ground type {0} may throw StrongModeError");
+ "Runtime check on non-ground type '{0}' may throw StrongModeError.");
static const StrongModeCode DYNAMIC_INVOKE = const StrongModeCode(
- ErrorType.HINT, 'DYNAMIC_INVOKE', '{0} requires a dynamic invoke');
+ ErrorType.HINT, 'DYNAMIC_INVOKE', "'{0}' requires a dynamic invoke.");
static const StrongModeCode INVALID_METHOD_OVERRIDE = const StrongModeCode(
ErrorType.COMPILE_TIME_ERROR,
'INVALID_METHOD_OVERRIDE',
- 'Invalid override. $_invalidOverrideMessage');
+ "Invalid override. $_invalidOverrideMessage");
static const StrongModeCode INVALID_METHOD_OVERRIDE_FROM_BASE =
const StrongModeCode(
ErrorType.COMPILE_TIME_ERROR,
'INVALID_METHOD_OVERRIDE_FROM_BASE',
- 'Base class introduces an invalid override. '
- '$_invalidOverrideMessage');
+ "Base class introduces an invalid override. $_invalidOverrideMessage");
static const StrongModeCode INVALID_METHOD_OVERRIDE_FROM_MIXIN =
const StrongModeCode(
ErrorType.COMPILE_TIME_ERROR,
'INVALID_METHOD_OVERRIDE_FROM_MIXIN',
- 'Mixin introduces an invalid override. $_invalidOverrideMessage');
+ "Mixin introduces an invalid override. $_invalidOverrideMessage");
static const StrongModeCode INVALID_FIELD_OVERRIDE = const StrongModeCode(
ErrorType.COMPILE_TIME_ERROR,
'INVALID_FIELD_OVERRIDE',
- 'Field declaration {3}.{1} cannot be '
- 'overridden in {0}.');
+ "Field declaration '{3}.{1}' can't be overridden in '{0}'.");
static const StrongModeCode IMPLICIT_DYNAMIC_PARAMETER = const StrongModeCode(
ErrorType.COMPILE_TIME_ERROR,
'IMPLICIT_DYNAMIC_PARAMETER',
- "Missing parameter type for '{0}'$_implicitDynamicTip");
+ "Missing parameter type for '{0}'.",
+ _implicitDynamicCorrection);
static const StrongModeCode IMPLICIT_DYNAMIC_RETURN = const StrongModeCode(
ErrorType.COMPILE_TIME_ERROR,
'IMPLICIT_DYNAMIC_RETURN',
- "Missing return type for '{0}'$_implicitDynamicTip");
+ "Missing return type for '{0}'.",
+ _implicitDynamicCorrection);
static const StrongModeCode IMPLICIT_DYNAMIC_VARIABLE = const StrongModeCode(
ErrorType.COMPILE_TIME_ERROR,
'IMPLICIT_DYNAMIC_VARIABLE',
- "Missing variable type for '{0}'$_implicitDynamicTip");
+ "Missing variable type for '{0}'.",
+ _implicitDynamicCorrection);
static const StrongModeCode IMPLICIT_DYNAMIC_FIELD = const StrongModeCode(
ErrorType.COMPILE_TIME_ERROR,
'IMPLICIT_DYNAMIC_FIELD',
- "Missing field type for '{0}'$_implicitDynamicTip");
+ "Missing field type for '{0}'.",
+ _implicitDynamicCorrection);
static const StrongModeCode IMPLICIT_DYNAMIC_TYPE = const StrongModeCode(
ErrorType.COMPILE_TIME_ERROR,
'IMPLICIT_DYNAMIC_TYPE',
- "Missing type arguments for generic type '{0}'"
- "$_implicitDynamicTip");
+ "Missing type arguments for generic type '{0}'.",
+ _implicitDynamicCorrection);
static const StrongModeCode IMPLICIT_DYNAMIC_LIST_LITERAL =
const StrongModeCode(
ErrorType.COMPILE_TIME_ERROR,
'IMPLICIT_DYNAMIC_LIST_LITERAL',
- "Missing type argument for list literal$_implicitDynamicTip");
+ "Missing type argument for list literal.",
+ _implicitDynamicCorrection);
static const StrongModeCode IMPLICIT_DYNAMIC_MAP_LITERAL =
const StrongModeCode(
ErrorType.COMPILE_TIME_ERROR,
'IMPLICIT_DYNAMIC_MAP_LITERAL',
- 'Missing type arguments for map literal$_implicitDynamicTip');
+ "Missing type arguments for map literal.",
+ _implicitDynamicCorrection);
static const StrongModeCode IMPLICIT_DYNAMIC_FUNCTION = const StrongModeCode(
ErrorType.COMPILE_TIME_ERROR,
'IMPLICIT_DYNAMIC_FUNCTION',
- "Missing type arguments for generic function '{0}<{1}>'"
- "$_implicitDynamicTip");
+ "Missing type arguments for generic function '{0}<{1}>'.",
+ _implicitDynamicCorrection);
static const StrongModeCode IMPLICIT_DYNAMIC_METHOD = const StrongModeCode(
ErrorType.COMPILE_TIME_ERROR,
'IMPLICIT_DYNAMIC_METHOD',
- "Missing type arguments for generic method '{0}<{1}>'"
- "$_implicitDynamicTip");
+ "Missing type arguments for generic method '{0}<{1}>'.",
+ _implicitDynamicCorrection);
static const StrongModeCode IMPLICIT_DYNAMIC_INVOKE = const StrongModeCode(
ErrorType.COMPILE_TIME_ERROR,
'IMPLICIT_DYNAMIC_INVOKE',
- "Missing type arguments for calling generic function type '{0}'"
- "$_implicitDynamicTip");
+ "Missing type arguments for calling generic function type '{0}'.",
+ _implicitDynamicCorrection);
- static const StrongModeCode UNSAFE_BLOCK_CLOSURE_INFERENCE =
- const StrongModeCode(
- ErrorType.STATIC_WARNING,
- 'UNSAFE_BLOCK_CLOSURE_INFERENCE',
- _unsafeBlockClosureInferenceMessage);
+ static const StrongModeCode UNSAFE_BLOCK_CLOSURE_INFERENCE = const StrongModeCode(
+ ErrorType.STATIC_WARNING,
+ 'UNSAFE_BLOCK_CLOSURE_INFERENCE',
+ "Unsafe use of a block closure in a type-inferred variable outside a function body.",
+ "Try adding a type annotation for '{0}'. See dartbug.com/26947.");
@override
final ErrorType type;
diff --git a/pkg/analyzer/lib/src/generated/declaration_resolver.dart b/pkg/analyzer/lib/src/generated/declaration_resolver.dart
index d67bc4c..a6b8a13 100644
--- a/pkg/analyzer/lib/src/generated/declaration_resolver.dart
+++ b/pkg/analyzer/lib/src/generated/declaration_resolver.dart
@@ -9,7 +9,9 @@
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/exception/exception.dart';
+import 'package:analyzer/src/dart/element/builder.dart';
import 'package:analyzer/src/dart/element/element.dart';
+import 'package:analyzer/src/generated/resolver.dart';
/**
* A visitor that resolves declarations in an AST structure to already built
@@ -51,6 +53,17 @@
}
@override
+ Object visitAnnotation(Annotation node) {
+ // Annotations can only contain elements in certain erroneous situations,
+ // in which case the elements are disconnected from the rest of the element
+ // model, thus we can't reconnect to them. To avoid crashes, just create
+ // fresh elements.
+ ElementHolder elementHolder = new ElementHolder();
+ new ElementBuilder(elementHolder, _enclosingUnit).visitAnnotation(node);
+ return null;
+ }
+
+ @override
Object visitCatchClause(CatchClause node) {
SimpleIdentifier exceptionParameter = node.exceptionParameter;
if (exceptionParameter != null) {
@@ -515,7 +528,8 @@
*/
ElementWalker.forParameter(ParameterElement element)
: element = element,
- _parameters = element.parameters;
+ _parameters = element.parameters,
+ _typeParameters = element.typeParameters;
/**
* Creates an [ElementWalker] which walks the child elements of a typedef
diff --git a/pkg/analyzer/lib/src/generated/error_verifier.dart b/pkg/analyzer/lib/src/generated/error_verifier.dart
index 792e5db..31131b7 100644
--- a/pkg/analyzer/lib/src/generated/error_verifier.dart
+++ b/pkg/analyzer/lib/src/generated/error_verifier.dart
@@ -3767,16 +3767,19 @@
if (_isInNativeClass || list.isSynthetic) {
return;
}
-
+ bool isConst = list.isConst;
+ if (!(isConst || list.isFinal)) {
+ return;
+ }
NodeList<VariableDeclaration> variables = list.variables;
for (VariableDeclaration variable in variables) {
if (variable.initializer == null) {
- if (list.isConst) {
+ if (isConst) {
_errorReporter.reportErrorForNode(
CompileTimeErrorCode.CONST_NOT_INITIALIZED,
variable.name,
[variable.name.name]);
- } else if (list.isFinal) {
+ } else {
_errorReporter.reportErrorForNode(
StaticWarningCode.FINAL_NOT_INITIALIZED,
variable.name,
@@ -4256,7 +4259,7 @@
_errorReporter.reportErrorForNode(
StaticTypeWarningCode.INSTANCE_ACCESS_TO_STATIC_MEMBER,
name,
- [name.name]);
+ [name.name, _getKind(element), element.enclosingElement.name]);
}
}
@@ -4952,7 +4955,7 @@
_errorReporter.reportErrorForNode(
CompileTimeErrorCode.NO_DEFAULT_SUPER_CONSTRUCTOR_IMPLICIT,
declaration.name,
- [superType.displayName]);
+ [superType.displayName, _enclosingClass.displayName]);
}
/**
@@ -5773,7 +5776,7 @@
_errorReporter.reportErrorForNode(
StaticTypeWarningCode.TYPE_PARAMETER_SUPERTYPE_OF_ITS_BOUND,
parameter,
- [element.displayName]);
+ [element.displayName, bound.displayName]);
}
/**
@@ -5868,14 +5871,13 @@
if (enclosingElement is! ClassElement) {
return;
}
- if ((element is MethodElement && !element.isStatic) ||
- (element is PropertyAccessorElement && !element.isStatic)) {
+ if (element is ExecutableElement && !element.isStatic) {
return;
}
_errorReporter.reportErrorForNode(
StaticTypeWarningCode.UNQUALIFIED_REFERENCE_TO_NON_LOCAL_STATIC_MEMBER,
name,
- [name.name]);
+ [enclosingElement.name]);
}
void _checkForValidField(FieldFormalParameter parameter) {
@@ -6314,6 +6316,32 @@
}
/**
+ * Return a human-readable representation of the kind of the [element].
+ */
+ String _getKind(ExecutableElement element) {
+ if (element is MethodElement) {
+ return 'method';
+ } else if (element is PropertyAccessorElement) {
+ if (element.isSynthetic) {
+ PropertyInducingElement variable = element.variable;
+ if (variable is FieldElement) {
+ return 'field';
+ }
+ return 'variable';
+ } else if (element.isGetter) {
+ return 'getter';
+ } else {
+ return 'setter';
+ }
+ } else if (element is ConstructorElement) {
+ return 'constructor';
+ } else if (element is FunctionElement) {
+ return 'function';
+ }
+ return 'member';
+ }
+
+ /**
* Return the name of the library that defines given [element].
*/
String _getLibraryName(Element element) {
diff --git a/pkg/analyzer/lib/src/generated/incremental_resolver.dart b/pkg/analyzer/lib/src/generated/incremental_resolver.dart
index f17e793..d847a7b 100644
--- a/pkg/analyzer/lib/src/generated/incremental_resolver.dart
+++ b/pkg/analyzer/lib/src/generated/incremental_resolver.dart
@@ -274,9 +274,7 @@
LoggingTimer timer = logger.startTimer();
try {
ElementHolder holder = new ElementHolder();
- ElementBuilder builder = new ElementBuilder(holder, _definingUnit);
- builder.initForFunctionBodyIncrementalResolution();
- node.accept(builder);
+ node.accept(new LocalElementBuilder(holder, _definingUnit));
// Move local elements into the ExecutableElementImpl.
ExecutableElementImpl executableElement =
executable.element as ExecutableElementImpl;
diff --git a/pkg/analyzer/lib/src/generated/parser.dart b/pkg/analyzer/lib/src/generated/parser.dart
index 1f51d66..7e91310 100644
--- a/pkg/analyzer/lib/src/generated/parser.dart
+++ b/pkg/analyzer/lib/src/generated/parser.dart
@@ -6430,7 +6430,8 @@
if (leftSquareBracket == null) {
if (leftCurlyBracket != null) {
_reportErrorForCurrentToken(
- ParserErrorCode.WRONG_TERMINATOR_FOR_PARAMETER_GROUP, ["}"]);
+ ParserErrorCode.WRONG_TERMINATOR_FOR_PARAMETER_GROUP,
+ ['}', ']']);
rightCurlyBracket = rightSquareBracket;
rightSquareBracket = null;
} else {
@@ -6445,7 +6446,8 @@
if (leftCurlyBracket == null) {
if (leftSquareBracket != null) {
_reportErrorForCurrentToken(
- ParserErrorCode.WRONG_TERMINATOR_FOR_PARAMETER_GROUP, ["]"]);
+ ParserErrorCode.WRONG_TERMINATOR_FOR_PARAMETER_GROUP,
+ [']', '}']);
rightSquareBracket = rightCurlyBracket;
rightCurlyBracket = null;
} else {
@@ -7842,7 +7844,7 @@
}
/**
- * Validate that the given set of [modifiers] is appropriate for a class and
+ * Validate that the given set of [modifiers] is appropriate for an enum and
* return the 'abstract' keyword if there is one.
*/
void _validateModifiersForEnum(Modifiers modifiers) {
diff --git a/pkg/analyzer/lib/src/generated/resolver.dart b/pkg/analyzer/lib/src/generated/resolver.dart
index d9dd238..e831fc0 100644
--- a/pkg/analyzer/lib/src/generated/resolver.dart
+++ b/pkg/analyzer/lib/src/generated/resolver.dart
@@ -9379,6 +9379,31 @@
}
/**
+ * Modes in which [TypeResolverVisitor] works.
+ */
+enum TypeResolverMode {
+ /**
+ * Resolve all names types of all nodes.
+ */
+ everything,
+
+ /**
+ * Resolve only type names outside of function bodies, variable initializers,
+ * and parameter default values.
+ */
+ api,
+
+ /**
+ * Resolve only type names that would be skipped during [api].
+ *
+ * Resolution must start from a unit member or a class member. For example
+ * it is not allowed to resolve types in a separate statement, or a function
+ * body.
+ */
+ local
+}
+
+/**
* Instances of the class `TypeResolverVisitor` are used to resolve the types associated with
* the elements in the element model. This includes the types of superclasses, mixins, interfaces,
* fields, methods, parameters, and local variables. As a side-effect, this also finishes building
@@ -9415,6 +9440,19 @@
*/
TypeNameResolver _typeNameResolver;
+ final TypeResolverMode mode;
+
+ /**
+ * Is `true` when we are visiting all nodes in [TypeResolverMode.local] mode.
+ */
+ bool _localModeVisitAll = false;
+
+ /**
+ * Is `true` if we are in [TypeResolverMode.local] mode, and the initial
+ * [nameScope] was computed.
+ */
+ bool _localModeScopeReady = false;
+
/**
* Initialize a newly created visitor to resolve the nodes in an AST node.
*
@@ -9432,7 +9470,7 @@
*/
TypeResolverVisitor(LibraryElement definingLibrary, Source source,
TypeProvider typeProvider, AnalysisErrorListener errorListener,
- {Scope nameScope})
+ {Scope nameScope, this.mode: TypeResolverMode.everything})
: super(definingLibrary, source, typeProvider, errorListener,
nameScope: nameScope) {
_dynamicType = typeProvider.dynamicType;
@@ -9742,6 +9780,112 @@
}
@override
+ Object visitNode(AstNode node) {
+ // In API mode we need to skip:
+ // - function bodies;
+ // - default values of parameters;
+ // - initializers of top-level variables.
+ if (mode == TypeResolverMode.api) {
+ if (node is FunctionBody) {
+ return null;
+ }
+ if (node is DefaultFormalParameter) {
+ node.parameter.accept(this);
+ return null;
+ }
+ if (node is VariableDeclaration) {
+ return null;
+ }
+ }
+
+ // In local mode we need to resolve only:
+ // - function bodies;
+ // - default values of parameters;
+ // - initializers of top-level variables.
+ // So, we carefully visit only nodes that are, or contain, these nodes.
+ // The client may choose to start visiting any node, but we still want to
+ // resolve only type names that are local.
+ if (mode == TypeResolverMode.local) {
+ // We are in the state of visiting all nodes.
+ if (_localModeVisitAll) {
+ return super.visitNode(node);
+ }
+
+ // Ensure that the name scope is ready.
+ if (!_localModeScopeReady) {
+ void fillNameScope(AstNode node) {
+ if (node is FunctionBody ||
+ node is FormalParameterList ||
+ node is VariableDeclaration) {
+ throw new StateError(
+ 'Local type resolution must start from a class or unit member.');
+ }
+ // Create enclosing name scopes.
+ AstNode parent = node.parent;
+ if (parent != null) {
+ fillNameScope(parent);
+ }
+ // Create the name scope for the node.
+ if (node is ClassDeclaration) {
+ ClassElement classElement = node.element;
+ nameScope = new TypeParameterScope(nameScope, classElement);
+ nameScope = new ClassScope(nameScope, classElement);
+ }
+ }
+
+ fillNameScope(node);
+ _localModeScopeReady = true;
+ }
+
+ /**
+ * Visit the given [node] and all its children.
+ */
+ void visitAllNodes(AstNode node) {
+ if (node != null) {
+ bool wasVisitAllInLocalMode = _localModeVisitAll;
+ try {
+ _localModeVisitAll = true;
+ node.accept(this);
+ } finally {
+ _localModeVisitAll = wasVisitAllInLocalMode;
+ }
+ }
+ }
+
+ // Visit only nodes that may contain type names to resolve.
+ if (node is CompilationUnit) {
+ node.declarations.forEach(visitNode);
+ } else if (node is ClassDeclaration) {
+ node.members.forEach(visitNode);
+ } else if (node is DefaultFormalParameter) {
+ visitAllNodes(node.defaultValue);
+ } else if (node is FieldDeclaration) {
+ visitNode(node.fields);
+ } else if (node is FunctionBody) {
+ visitAllNodes(node);
+ } else if (node is FunctionDeclaration) {
+ visitNode(node.functionExpression.parameters);
+ visitAllNodes(node.functionExpression.body);
+ } else if (node is FormalParameterList) {
+ node.parameters.accept(this);
+ } else if (node is MethodDeclaration) {
+ visitNode(node.parameters);
+ visitAllNodes(node.body);
+ } else if (node is TopLevelVariableDeclaration) {
+ visitNode(node.variables);
+ } else if (node is VariableDeclaration) {
+ visitAllNodes(node.initializer);
+ } else if (node is VariableDeclarationList) {
+ node.variables.forEach(visitNode);
+ }
+ return null;
+ }
+
+ // The mode in which we visit all nodes.
+ return super.visitNode(node);
+ }
+
+ @override
Object visitSimpleFormalParameter(SimpleFormalParameter node) {
super.visitSimpleFormalParameter(node);
DartType declaredType;
diff --git a/pkg/analyzer/lib/src/generated/type_system.dart b/pkg/analyzer/lib/src/generated/type_system.dart
index 5574aed..2462145 100644
--- a/pkg/analyzer/lib/src/generated/type_system.dart
+++ b/pkg/analyzer/lib/src/generated/type_system.dart
@@ -419,16 +419,6 @@
new _StrongInferenceTypeSystem(typeProvider, this, typeFormals);
if (returnContextType != null) {
- // If we're in a future union context, choose either the Future<T>
- // or the T based on the declared return type.
- if (returnContextType is FutureUnionType) {
- var futureUnion = returnContextType as FutureUnionType;
- returnContextType =
- isSubtypeOf(declaredReturnType, typeProvider.futureDynamicType)
- ? futureUnion.futureOfType
- : futureUnion.type;
- }
-
inferringTypeSystem.isSubtypeOf(declaredReturnType, returnContextType);
}
@@ -851,7 +841,7 @@
if (identical(i1, i2)) {
return true;
}
-
+
// Guard recursive calls
_GuardedSubtypeChecker<InterfaceType> guardedInterfaceSubtype = _guard(
(DartType i1, DartType i2, Set<Element> visited) =>
@@ -946,6 +936,19 @@
return guardedInferTypeParameter(t1, t2, visited);
}
+ if (t1 is FutureUnionType) {
+ // given t1 is Future<A> | A, then:
+ // (Future<A> | A) <: t2 iff t2 <: Future<A> and t2 <: A.
+ return guardedSubtype(t1.futureOfType, t2, visited) &&
+ guardedSubtype(t1.type, t2, visited);
+ }
+ if (t2 is FutureUnionType) {
+ // given t2 is Future<A> | A, then:
+ // t1 <: (Future<A> | A) iff t1 <: Future<A> or t1 <: A
+ return guardedSubtype(t1, t2.futureOfType, visited) ||
+ guardedSubtype(t1, t2.type, visited);
+ }
+
// Void only appears as the return type of a function, and we handle it
// directly in the function subtype rules. We should not get to a point
// where we're doing a subtype test on a "bare" void, but just in case we
@@ -1578,6 +1581,39 @@
DartType lowerBound = bound.lower;
DartType upperBound = bound.upper;
+ // Collapse future unions if we inferred them somehow.
+ //
+ // TODO(jmesserly): in our initial upward phase it would be fine to
+ // keep the FutureUnionType for the argument downward context.
+ //
+ // We need to track in `inferGenericFunctionCall` whether we are going up
+ // or down. This would also allow for an improved heuristic: if we are
+ // doing our final inference, the downward context can take priority.
+ if (lowerBound is FutureUnionType) {
+ // lowerBound <: T, where lowerBound is Future<A> | A.
+ // So we choose lowerBound as LUB(A, Future<A>).
+ //
+ // This will typically lead to top with the current rules, but it will
+ // work with `bottom` or if we remove Future flattening.
+ var f = upperBound as FutureUnionType;
+ lowerBound = _typeSystem.getLeastUpperBound(
+ _typeProvider, f.futureOfType, f.type);
+ }
+ if (upperBound is FutureUnionType) {
+ // T <: upperBound, where upperBound is Future<A> | A.
+ // Therefore we need T <: Future<A> or T <: A.
+ //
+ // This is just an arbitrarily heuristic.
+ var f = upperBound as FutureUnionType;
+ if (_typeSystem.isSubtypeOf(lowerBound, f.type)) {
+ upperBound = f.type;
+ } else if (_typeSystem.isSubtypeOf(lowerBound, f.futureOfType)) {
+ upperBound = f.futureOfType;
+ } else {
+ upperBound = f.type;
+ }
+ }
+
// See if the bounds can be satisfied.
// TODO(jmesserly): also we should have an error for unconstrained type
// parameters, rather than silently inferring dynamic.
diff --git a/pkg/analyzer/lib/src/summary/format.dart b/pkg/analyzer/lib/src/summary/format.dart
index a515954..6d4ecc8 100644
--- a/pkg/analyzer/lib/src/summary/format.dart
+++ b/pkg/analyzer/lib/src/summary/format.dart
@@ -5370,6 +5370,8 @@
_redirectedConstructor?.flushInformative();
_returnType?.flushInformative();
_typeParameters?.forEach((b) => b.flushInformative());
+ _visibleLength = null;
+ _visibleOffset = null;
}
/**
@@ -5430,8 +5432,6 @@
x?.collectApiSignature(signature);
}
}
- signature.addInt(this._visibleLength ?? 0);
- signature.addInt(this._visibleOffset ?? 0);
signature.addInt(this._constCycleSlot ?? 0);
signature.addBool(this._bodyExpr != null);
this._bodyExpr?.collectApiSignature(signature);
diff --git a/pkg/analyzer/lib/src/summary/idl.dart b/pkg/analyzer/lib/src/summary/idl.dart
index ba024af..07a9461 100644
--- a/pkg/analyzer/lib/src/summary/idl.dart
+++ b/pkg/analyzer/lib/src/summary/idl.dart
@@ -1926,12 +1926,14 @@
/**
* If a local function, the length of the visible range; zero otherwise.
*/
+ @informative
@Id(20)
int get visibleLength;
/**
* If a local function, the beginning of the visible range; zero otherwise.
*/
+ @informative
@Id(21)
int get visibleOffset;
}
diff --git a/pkg/analyzer/test/dart/element/builder_test.dart b/pkg/analyzer/test/dart/element/builder_test.dart
new file mode 100644
index 0000000..db35770
--- /dev/null
+++ b/pkg/analyzer/test/dart/element/builder_test.dart
@@ -0,0 +1,2477 @@
+// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+library analyzer.test.dart.element.builder_test;
+
+import 'package:analyzer/dart/ast/ast.dart';
+import 'package:analyzer/dart/ast/token.dart';
+import 'package:analyzer/dart/element/element.dart';
+import 'package:analyzer/src/dart/ast/ast.dart';
+import 'package:analyzer/src/dart/element/builder.dart';
+import 'package:analyzer/src/dart/element/element.dart';
+import 'package:analyzer/src/generated/engine.dart';
+import 'package:analyzer/src/generated/resolver.dart';
+import 'package:analyzer/src/generated/source.dart';
+import 'package:analyzer/src/generated/testing/ast_factory.dart';
+import 'package:analyzer/src/generated/testing/element_factory.dart';
+import 'package:analyzer/src/generated/testing/token_factory.dart';
+import 'package:analyzer/src/generated/utilities_dart.dart';
+import 'package:test/test.dart';
+import 'package:test_reflective_loader/test_reflective_loader.dart';
+
+import '../../generated/parser_test.dart';
+import '../../generated/test_support.dart';
+
+main() {
+ defineReflectiveSuite(() {
+ defineReflectiveTests(ApiElementBuilderTest);
+ defineReflectiveTests(ElementBuilderTest);
+ defineReflectiveTests(LocalElementBuilderTest);
+ });
+}
+
+@reflectiveTest
+class ApiElementBuilderTest extends _BaseTest with _ApiElementBuilderTestMixin {
+ @override
+ AstVisitor createElementBuilder(ElementHolder holder) {
+ return new ApiElementBuilder(holder, compilationUnitElement);
+ }
+
+ void test_api_class_field() {
+ List<FieldElement> fields = buildElementsForText(r'''
+class C {
+ var a = 42;
+ var b = () {
+ int v = 0;
+ localFunction() {}
+ };
+}
+''').types[0].fields;
+ expect(fields, hasLength(2));
+ {
+ FieldElement a = fields[0];
+ expect(a.displayName, 'a');
+ expect(a.initializer, isNull);
+ }
+ {
+ FieldElement b = fields[1];
+ expect(b.displayName, 'b');
+ expect(b.initializer, isNull);
+ }
+ }
+
+ void test_api_class_method_blockBody() {
+ MethodElement method = buildElementsForText(r'''
+class C {
+ void m(int a, {int b: 42}) {
+ int v = 0;
+ localFunction() {}
+ }
+}
+''').types[0].methods[0];
+ {
+ expect(method.parameters, hasLength(2));
+ expect(method.parameters[0].displayName, 'a');
+ expect(method.parameters[0].initializer, isNull);
+ expect(method.parameters[1].displayName, 'b');
+ expect(method.parameters[1].initializer, isNull);
+ }
+ expect(method.localVariables, isEmpty);
+ expect(method.functions, isEmpty);
+ }
+
+ void test_api_topLevelFunction_blockBody() {
+ FunctionElement function = buildElementsForText(r'''
+void topLevelFunction() {
+ int v = 0;
+ localFunction() {}
+}
+''').functions[0];
+ expect(function.localVariables, isEmpty);
+ expect(function.functions, isEmpty);
+ }
+
+ void test_api_topLevelFunction_expressionBody() {
+ FunctionElement function = buildElementsForText(r'''
+topLevelFunction() => () {
+ int localVar = 0;
+};
+''').functions[0];
+ expect(function.localVariables, isEmpty);
+ expect(function.functions, isEmpty);
+ }
+
+ void test_api_topLevelFunction_parameters() {
+ FunctionElement function = buildElementsForText(r'''
+void topLevelFunction(int a, int b(double b2), {c: () {int c2; c3() {} }}) {
+}
+''').functions[0];
+ List<ParameterElement> parameters = function.parameters;
+ expect(parameters, hasLength(3));
+ {
+ ParameterElement a = parameters[0];
+ expect(a.displayName, 'a');
+ expect(a.initializer, isNull);
+ }
+ {
+ ParameterElement b = parameters[1];
+ expect(b.displayName, 'b');
+ expect(b.initializer, isNull);
+ expect(b.parameters, hasLength(1));
+ expect(b.parameters[0].displayName, 'b2');
+ }
+ {
+ var c = parameters[2] as DefaultParameterElementImpl;
+ expect(c.displayName, 'c');
+ expect(c.initializer, isNull);
+ }
+ }
+
+ void test_api_topLevelVariable() {
+ List<TopLevelVariableElement> variables = buildElementsForText(r'''
+var A = 42;
+var B = () {
+ int v = 0;
+ localFunction(int _) {}
+};
+''').topLevelVariables;
+ expect(variables, hasLength(2));
+ {
+ TopLevelVariableElement a = variables[0];
+ expect(a.displayName, 'A');
+ expect(a.initializer, isNull);
+ }
+ {
+ TopLevelVariableElement b = variables[1];
+ expect(b.displayName, 'B');
+ expect(b.initializer, isNull);
+ }
+ }
+}
+
+@reflectiveTest
+class ElementBuilderTest extends _BaseTest with _ApiElementBuilderTestMixin {
+ /**
+ * Parse the given [code], pass it through [ElementBuilder], and return the
+ * resulting [ElementHolder].
+ */
+ ElementHolder buildElementsForText(String code) {
+ ElementHolder holder = new ElementHolder();
+ ElementBuilder builder = new ElementBuilder(holder, compilationUnitElement);
+ _visitAstOfCode(code, builder);
+ return holder;
+ }
+
+ AstVisitor createElementBuilder(ElementHolder holder) {
+ return new ElementBuilder(holder, compilationUnitElement);
+ }
+
+ void fail_visitMethodDeclaration_setter_duplicate() {
+ // https://github.com/dart-lang/sdk/issues/25601
+ String code = r'''
+class C {
+ set zzz(x) {}
+ set zzz(y) {}
+}
+''';
+ ClassElement classElement = buildElementsForText(code).types[0];
+ for (PropertyAccessorElement accessor in classElement.accessors) {
+ expect(accessor.variable.setter, same(accessor));
+ }
+ }
+
+ @override
+ void setUp() {
+ super.setUp();
+ compilationUnitElement = new CompilationUnitElementImpl('test.dart');
+ }
+
+ void test_metadata_localVariableDeclaration() {
+ List<LocalVariableElement> localVariables =
+ buildElementsForText('f() { @a int x, y; }')
+ .functions[0]
+ .localVariables;
+ checkMetadata(localVariables[0]);
+ checkMetadata(localVariables[1]);
+ expect(localVariables[0].metadata, same(localVariables[1].metadata));
+ }
+
+ void test_metadata_visitDeclaredIdentifier() {
+ LocalVariableElement localVariableElement =
+ buildElementsForText('f() { for (@a var x in y) {} }')
+ .functions[0]
+ .localVariables[0];
+ checkMetadata(localVariableElement);
+ }
+
+ void test_visitCatchClause() {
+ List<LocalVariableElement> variables =
+ buildElementsForText('f() { try {} catch (e, s) {} }')
+ .functions[0]
+ .localVariables;
+ String exceptionParameterName = "e";
+ String stackParameterName = "s";
+ expect(variables, hasLength(2));
+
+ LocalVariableElement exceptionVariable = variables[0];
+ expect(exceptionVariable, isNotNull);
+ expect(exceptionVariable.name, exceptionParameterName);
+ expect(exceptionVariable.hasImplicitType, isTrue);
+ expect(exceptionVariable.isSynthetic, isFalse);
+ expect(exceptionVariable.isConst, isFalse);
+ expect(exceptionVariable.isFinal, isFalse);
+ expect(exceptionVariable.initializer, isNull);
+ _assertVisibleRange(exceptionVariable, 13, 28);
+
+ LocalVariableElement stackVariable = variables[1];
+ expect(stackVariable, isNotNull);
+ expect(stackVariable.name, stackParameterName);
+ expect(stackVariable.isSynthetic, isFalse);
+ expect(stackVariable.isConst, isFalse);
+ expect(stackVariable.isFinal, isFalse);
+ expect(stackVariable.initializer, isNull);
+ _assertVisibleRange(stackVariable, 13, 28);
+ }
+
+ void test_visitCatchClause_withType() {
+ List<LocalVariableElement> variables =
+ buildElementsForText('f() { try {} on E catch (e) {} }')
+ .functions[0]
+ .localVariables;
+ String exceptionParameterName = "e";
+ expect(variables, hasLength(1));
+ VariableElement exceptionVariable = variables[0];
+ expect(exceptionVariable, isNotNull);
+ expect(exceptionVariable.name, exceptionParameterName);
+ expect(exceptionVariable.hasImplicitType, isFalse);
+ }
+
+ void test_visitCompilationUnit_codeRange() {
+ TopLevelVariableDeclaration topLevelVariableDeclaration = AstFactory
+ .topLevelVariableDeclaration(null, AstFactory.typeName4('int'),
+ [AstFactory.variableDeclaration('V')]);
+ CompilationUnit unit = new CompilationUnit(
+ topLevelVariableDeclaration.beginToken,
+ null,
+ [],
+ [topLevelVariableDeclaration],
+ topLevelVariableDeclaration.endToken);
+ ElementHolder holder = new ElementHolder();
+ ElementBuilder builder = _makeBuilder(holder);
+ unit.beginToken.offset = 10;
+ unit.endToken.offset = 40;
+ unit.accept(builder);
+
+ assertHasCodeRange(compilationUnitElement, 0, 41);
+ }
+
+ void test_visitDeclaredIdentifier_noType() {
+ LocalVariableElement variable =
+ buildElementsForText('f() { for (var i in []) {} }')
+ .functions[0]
+ .localVariables[0];
+ assertHasCodeRange(variable, 11, 5);
+ expect(variable, isNotNull);
+ expect(variable.hasImplicitType, isTrue);
+ expect(variable.isConst, isFalse);
+ expect(variable.isDeprecated, isFalse);
+ expect(variable.isFinal, isFalse);
+ expect(variable.isOverride, isFalse);
+ expect(variable.isPrivate, isFalse);
+ expect(variable.isPublic, isTrue);
+ expect(variable.isSynthetic, isFalse);
+ expect(variable.name, 'i');
+ }
+
+ void test_visitDeclaredIdentifier_type() {
+ LocalVariableElement variable =
+ buildElementsForText('f() { for (int i in []) {} }')
+ .functions[0]
+ .localVariables[0];
+ assertHasCodeRange(variable, 11, 5);
+ expect(variable.hasImplicitType, isFalse);
+ expect(variable.isConst, isFalse);
+ expect(variable.isDeprecated, isFalse);
+ expect(variable.isFinal, isFalse);
+ expect(variable.isOverride, isFalse);
+ expect(variable.isPrivate, isFalse);
+ expect(variable.isPublic, isTrue);
+ expect(variable.isSynthetic, isFalse);
+ expect(variable.name, 'i');
+ }
+
+ void test_visitDefaultFormalParameter_noType() {
+ // p = 0
+ String parameterName = 'p';
+ DefaultFormalParameter formalParameter =
+ AstFactory.positionalFormalParameter(
+ AstFactory.simpleFormalParameter3(parameterName),
+ AstFactory.integer(0));
+ formalParameter.beginToken.offset = 50;
+ formalParameter.endToken.offset = 80;
+
+ ElementHolder holder = buildElementsForAst(formalParameter);
+ List<ParameterElement> parameters = holder.parameters;
+ expect(parameters, hasLength(1));
+ ParameterElement parameter = parameters[0];
+ assertHasCodeRange(parameter, 50, 31);
+ expect(parameter.hasImplicitType, isTrue);
+ expect(parameter.initializer, isNotNull);
+ expect(parameter.initializer.type, isNotNull);
+ expect(parameter.initializer.hasImplicitReturnType, isTrue);
+ expect(parameter.isConst, isFalse);
+ expect(parameter.isDeprecated, isFalse);
+ expect(parameter.isFinal, isFalse);
+ expect(parameter.isInitializingFormal, isFalse);
+ expect(parameter.isOverride, isFalse);
+ expect(parameter.isPrivate, isFalse);
+ expect(parameter.isPublic, isTrue);
+ expect(parameter.isSynthetic, isFalse);
+ expect(parameter.name, parameterName);
+ }
+
+ void test_visitDefaultFormalParameter_type() {
+ // E p = 0
+ String parameterName = 'p';
+ DefaultFormalParameter formalParameter = AstFactory.namedFormalParameter(
+ AstFactory.simpleFormalParameter4(
+ AstFactory.typeName4('E'), parameterName),
+ AstFactory.integer(0));
+
+ ElementHolder holder = buildElementsForAst(formalParameter);
+ List<ParameterElement> parameters = holder.parameters;
+ expect(parameters, hasLength(1));
+ ParameterElement parameter = parameters[0];
+ expect(parameter.hasImplicitType, isFalse);
+ expect(parameter.initializer, isNotNull);
+ expect(parameter.initializer.type, isNotNull);
+ expect(parameter.initializer.hasImplicitReturnType, isTrue);
+ expect(parameter.isConst, isFalse);
+ expect(parameter.isDeprecated, isFalse);
+ expect(parameter.isFinal, isFalse);
+ expect(parameter.isInitializingFormal, isFalse);
+ expect(parameter.isOverride, isFalse);
+ expect(parameter.isPrivate, isFalse);
+ expect(parameter.isPublic, isTrue);
+ expect(parameter.isSynthetic, isFalse);
+ expect(parameter.name, parameterName);
+ }
+
+ void test_visitFunctionExpression() {
+ ElementHolder holder = new ElementHolder();
+ ElementBuilder builder = _makeBuilder(holder);
+ FunctionExpression expression = AstFactory.functionExpression2(
+ AstFactory.formalParameterList(), AstFactory.blockFunctionBody2());
+ expression.accept(builder);
+ List<FunctionElement> functions = holder.functions;
+ expect(functions, hasLength(1));
+ FunctionElement function = functions[0];
+ expect(function, isNotNull);
+ expect(expression.element, same(function));
+ expect(function.hasImplicitReturnType, isTrue);
+ expect(function.isSynthetic, isFalse);
+ expect(function.typeParameters, hasLength(0));
+ }
+
+ void test_visitFunctionExpression_inBlockBody() {
+ List<FunctionElement> functions =
+ buildElementsForText('f() { return () => 42; }').functions[0].functions;
+ expect(functions, hasLength(1));
+ FunctionElement function = functions[0];
+ expect(function, isNotNull);
+ expect(function.hasImplicitReturnType, isTrue);
+ expect(function.isSynthetic, isFalse);
+ expect(function.typeParameters, hasLength(0));
+ }
+
+ void test_visitFunctionExpression_inExpressionBody() {
+ List<FunctionElement> functions =
+ buildElementsForText('f() => () => 42;').functions[0].functions;
+ expect(functions, hasLength(1));
+ FunctionElement function = functions[0];
+ expect(function, isNotNull);
+ expect(function.hasImplicitReturnType, isTrue);
+ expect(function.isSynthetic, isFalse);
+ expect(function.typeParameters, hasLength(0));
+ }
+
+ void test_visitFunctionTypeAlias() {
+ ElementHolder holder = new ElementHolder();
+ ElementBuilder builder = _makeBuilder(holder);
+ String aliasName = "F";
+ String parameterName = "E";
+ FunctionTypeAlias aliasNode = AstFactory.typeAlias(
+ null, aliasName, AstFactory.typeParameterList([parameterName]), null);
+ aliasNode.documentationComment = AstFactory.documentationComment(
+ [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
+ aliasNode.endToken.offset = 80;
+ aliasNode.accept(builder);
+
+ List<FunctionTypeAliasElement> aliases = holder.typeAliases;
+ expect(aliases, hasLength(1));
+ FunctionTypeAliasElement alias = aliases[0];
+ expect(alias, isNotNull);
+ assertHasCodeRange(alias, 50, 31);
+ expect(alias.documentationComment, '/// aaa');
+ expect(alias.name, aliasName);
+ expect(alias.parameters, hasLength(0));
+ List<TypeParameterElement> typeParameters = alias.typeParameters;
+ expect(typeParameters, hasLength(1));
+ TypeParameterElement typeParameter = typeParameters[0];
+ expect(typeParameter, isNotNull);
+ expect(typeParameter.name, parameterName);
+ }
+
+ void test_visitFunctionTypedFormalParameter() {
+ ElementHolder holder = new ElementHolder();
+ ElementBuilder builder = _makeBuilder(holder);
+ String parameterName = "p";
+ FunctionTypedFormalParameter formalParameter =
+ AstFactory.functionTypedFormalParameter(null, parameterName);
+ _useParameterInMethod(formalParameter, 100, 110);
+ formalParameter.accept(builder);
+ List<ParameterElement> parameters = holder.parameters;
+ expect(parameters, hasLength(1));
+ ParameterElement parameter = parameters[0];
+ expect(parameter, isNotNull);
+ expect(parameter.name, parameterName);
+ expect(parameter.initializer, isNull);
+ expect(parameter.isConst, isFalse);
+ expect(parameter.isFinal, isFalse);
+ expect(parameter.isSynthetic, isFalse);
+ expect(parameter.parameterKind, ParameterKind.REQUIRED);
+ _assertVisibleRange(parameter, 100, 110);
+ }
+
+ void test_visitFunctionTypedFormalParameter_withTypeParameters() {
+ ElementHolder holder = new ElementHolder();
+ ElementBuilder builder = _makeBuilder(holder);
+ String parameterName = "p";
+ FunctionTypedFormalParameter formalParameter =
+ AstFactory.functionTypedFormalParameter(null, parameterName);
+ formalParameter.typeParameters = AstFactory.typeParameterList(['F']);
+ _useParameterInMethod(formalParameter, 100, 110);
+ formalParameter.accept(builder);
+ List<ParameterElement> parameters = holder.parameters;
+ expect(parameters, hasLength(1));
+ ParameterElement parameter = parameters[0];
+ expect(parameter, isNotNull);
+ expect(parameter.name, parameterName);
+ expect(parameter.initializer, isNull);
+ expect(parameter.isConst, isFalse);
+ expect(parameter.isFinal, isFalse);
+ expect(parameter.isSynthetic, isFalse);
+ expect(parameter.parameterKind, ParameterKind.REQUIRED);
+ expect(parameter.typeParameters, hasLength(1));
+ _assertVisibleRange(parameter, 100, 110);
+ }
+
+ void test_visitLabeledStatement() {
+ List<LabelElement> labels =
+ buildElementsForText('f() { l: print(42); }').functions[0].labels;
+ expect(labels, hasLength(1));
+ LabelElement label = labels[0];
+ expect(label, isNotNull);
+ expect(label.name, 'l');
+ expect(label.isSynthetic, isFalse);
+ }
+
+ void test_visitMethodDeclaration_withMembers() {
+ MethodElement method = buildElementsForText(
+ 'class C { m(p) { var v; try { l: return; } catch (e) {} } }')
+ .types[0]
+ .methods[0];
+ String methodName = "m";
+ String parameterName = "p";
+ String localVariableName = "v";
+ String labelName = "l";
+ String exceptionParameterName = "e";
+ expect(method, isNotNull);
+ expect(method.hasImplicitReturnType, isTrue);
+ expect(method.name, methodName);
+ expect(method.typeParameters, hasLength(0));
+ expect(method.isAbstract, isFalse);
+ expect(method.isExternal, isFalse);
+ expect(method.isStatic, isFalse);
+ expect(method.isSynthetic, isFalse);
+ List<VariableElement> parameters = method.parameters;
+ expect(parameters, hasLength(1));
+ VariableElement parameter = parameters[0];
+ expect(parameter, isNotNull);
+ expect(parameter.name, parameterName);
+ List<VariableElement> localVariables = method.localVariables;
+ expect(localVariables, hasLength(2));
+ VariableElement firstVariable = localVariables[0];
+ VariableElement secondVariable = localVariables[1];
+ expect(firstVariable, isNotNull);
+ expect(secondVariable, isNotNull);
+ expect(
+ (firstVariable.name == localVariableName &&
+ secondVariable.name == exceptionParameterName) ||
+ (firstVariable.name == exceptionParameterName &&
+ secondVariable.name == localVariableName),
+ isTrue);
+ List<LabelElement> labels = method.labels;
+ expect(labels, hasLength(1));
+ LabelElement label = labels[0];
+ expect(label, isNotNull);
+ expect(label.name, labelName);
+ }
+
+ void test_visitNamedFormalParameter() {
+ ElementHolder holder = new ElementHolder();
+ ElementBuilder builder = _makeBuilder(holder);
+ String parameterName = "p";
+ DefaultFormalParameter formalParameter = AstFactory.namedFormalParameter(
+ AstFactory.simpleFormalParameter3(parameterName),
+ AstFactory.identifier3("42"));
+ _useParameterInMethod(formalParameter, 100, 110);
+ formalParameter.beginToken.offset = 50;
+ formalParameter.endToken.offset = 80;
+ formalParameter.accept(builder);
+ List<ParameterElement> parameters = holder.parameters;
+ expect(parameters, hasLength(1));
+ ParameterElement parameter = parameters[0];
+ expect(parameter, isNotNull);
+ assertHasCodeRange(parameter, 50, 32);
+ expect(parameter.name, parameterName);
+ expect(parameter.isConst, isFalse);
+ expect(parameter.isFinal, isFalse);
+ expect(parameter.isSynthetic, isFalse);
+ expect(parameter.parameterKind, ParameterKind.NAMED);
+ _assertVisibleRange(parameter, 100, 110);
+ expect(parameter.defaultValueCode, "42");
+ FunctionElement initializer = parameter.initializer;
+ expect(initializer, isNotNull);
+ expect(initializer.isSynthetic, isTrue);
+ expect(initializer.hasImplicitReturnType, isTrue);
+ }
+
+ void test_visitSimpleFormalParameter_noType() {
+ // p
+ ElementHolder holder = new ElementHolder();
+ ElementBuilder builder = _makeBuilder(holder);
+ String parameterName = "p";
+ SimpleFormalParameter formalParameter =
+ AstFactory.simpleFormalParameter3(parameterName);
+ _useParameterInMethod(formalParameter, 100, 110);
+ formalParameter.accept(builder);
+ List<ParameterElement> parameters = holder.parameters;
+ expect(parameters, hasLength(1));
+ ParameterElement parameter = parameters[0];
+ expect(parameter, isNotNull);
+ expect(parameter.hasImplicitType, isTrue);
+ expect(parameter.initializer, isNull);
+ expect(parameter.isConst, isFalse);
+ expect(parameter.isFinal, isFalse);
+ expect(parameter.isSynthetic, isFalse);
+ expect(parameter.name, parameterName);
+ expect(parameter.parameterKind, ParameterKind.REQUIRED);
+ _assertVisibleRange(parameter, 100, 110);
+ }
+
+ void test_visitSimpleFormalParameter_type() {
+ // T p
+ ElementHolder holder = new ElementHolder();
+ ElementBuilder builder = _makeBuilder(holder);
+ String parameterName = "p";
+ SimpleFormalParameter formalParameter = AstFactory.simpleFormalParameter4(
+ AstFactory.typeName4('T'), parameterName);
+ _useParameterInMethod(formalParameter, 100, 110);
+ formalParameter.accept(builder);
+ List<ParameterElement> parameters = holder.parameters;
+ expect(parameters, hasLength(1));
+ ParameterElement parameter = parameters[0];
+ expect(parameter, isNotNull);
+ expect(parameter.hasImplicitType, isFalse);
+ expect(parameter.initializer, isNull);
+ expect(parameter.isConst, isFalse);
+ expect(parameter.isFinal, isFalse);
+ expect(parameter.isSynthetic, isFalse);
+ expect(parameter.name, parameterName);
+ expect(parameter.parameterKind, ParameterKind.REQUIRED);
+ _assertVisibleRange(parameter, 100, 110);
+ }
+
+ void test_visitVariableDeclaration_inConstructor() {
+ List<ConstructorElement> constructors =
+ buildElementsForText('class C { C() { var v = 1; } }')
+ .types[0]
+ .constructors;
+ expect(constructors, hasLength(1));
+ List<LocalVariableElement> variableElements =
+ constructors[0].localVariables;
+ expect(variableElements, hasLength(1));
+ LocalVariableElement variableElement = variableElements[0];
+ assertHasCodeRange(variableElement, 16, 10);
+ expect(variableElement.hasImplicitType, isTrue);
+ expect(variableElement.name, 'v');
+ _assertVisibleRange(variableElement, 14, 28);
+ }
+
+ void test_visitVariableDeclaration_inForEachStatement() {
+ ElementHolder holder = new ElementHolder();
+ ElementBuilder builder = _makeBuilder(holder);
+ //
+ // m() { for (var v in []) }
+ //
+ String variableName = "v";
+ Statement statement = AstFactory.forEachStatement(
+ AstFactory.declaredIdentifier3('v'),
+ AstFactory.listLiteral(),
+ AstFactory.block());
+ _setNodeSourceRange(statement, 100, 110);
+ MethodDeclaration method = AstFactory.methodDeclaration2(
+ null,
+ null,
+ null,
+ null,
+ AstFactory.identifier3("m"),
+ AstFactory.formalParameterList(),
+ AstFactory.blockFunctionBody2([statement]));
+ _setBlockBodySourceRange(method.body, 200, 220);
+ method.accept(builder);
+
+ List<MethodElement> methods = holder.methods;
+ expect(methods, hasLength(1));
+ List<LocalVariableElement> variableElements = methods[0].localVariables;
+ expect(variableElements, hasLength(1));
+ LocalVariableElement variableElement = variableElements[0];
+ expect(variableElement.name, variableName);
+ _assertVisibleRange(variableElement, 100, 110);
+ }
+
+ void test_visitVariableDeclaration_inForStatement() {
+ ElementHolder holder = new ElementHolder();
+ ElementBuilder builder = _makeBuilder(holder);
+ //
+ // m() { for (T v;;) }
+ //
+ String variableName = "v";
+ ForStatement statement = AstFactory.forStatement2(
+ AstFactory.variableDeclarationList(null, AstFactory.typeName4('T'),
+ [AstFactory.variableDeclaration('v')]),
+ null,
+ null,
+ AstFactory.block());
+ _setNodeSourceRange(statement, 100, 110);
+ MethodDeclaration method = AstFactory.methodDeclaration2(
+ null,
+ null,
+ null,
+ null,
+ AstFactory.identifier3("m"),
+ AstFactory.formalParameterList(),
+ AstFactory.blockFunctionBody2([statement]));
+ _setBlockBodySourceRange(method.body, 200, 220);
+ method.accept(builder);
+
+ List<MethodElement> methods = holder.methods;
+ expect(methods, hasLength(1));
+ List<LocalVariableElement> variableElements = methods[0].localVariables;
+ expect(variableElements, hasLength(1));
+ LocalVariableElement variableElement = variableElements[0];
+ expect(variableElement.name, variableName);
+ _assertVisibleRange(variableElement, 100, 110);
+ }
+
+ void test_visitVariableDeclaration_inMethod() {
+ ElementHolder holder = new ElementHolder();
+ ElementBuilder builder = _makeBuilder(holder);
+ //
+ // m() {T v;}
+ //
+ String variableName = "v";
+ VariableDeclaration variable =
+ AstFactory.variableDeclaration2(variableName, null);
+ Statement statement = AstFactory.variableDeclarationStatement(
+ null, AstFactory.typeName4('T'), [variable]);
+ MethodDeclaration method = AstFactory.methodDeclaration2(
+ null,
+ null,
+ null,
+ null,
+ AstFactory.identifier3("m"),
+ AstFactory.formalParameterList(),
+ AstFactory.blockFunctionBody2([statement]));
+ _setBlockBodySourceRange(method.body, 100, 110);
+ method.accept(builder);
+
+ List<MethodElement> methods = holder.methods;
+ expect(methods, hasLength(1));
+ List<LocalVariableElement> variableElements = methods[0].localVariables;
+ expect(variableElements, hasLength(1));
+ LocalVariableElement variableElement = variableElements[0];
+ expect(variableElement.hasImplicitType, isFalse);
+ expect(variableElement.name, variableName);
+ _assertVisibleRange(variableElement, 100, 110);
+ }
+
+ void test_visitVariableDeclaration_localNestedInFunction() {
+ ElementHolder holder = new ElementHolder();
+ ElementBuilder builder = _makeBuilder(holder);
+ //
+ // var f = () {var v;};
+ //
+ String variableName = "v";
+ VariableDeclaration variable =
+ AstFactory.variableDeclaration2(variableName, null);
+ Statement statement =
+ AstFactory.variableDeclarationStatement2(null, [variable]);
+ Expression initializer = AstFactory.functionExpression2(
+ AstFactory.formalParameterList(),
+ AstFactory.blockFunctionBody2([statement]));
+ String fieldName = "f";
+ VariableDeclaration field =
+ AstFactory.variableDeclaration2(fieldName, initializer);
+ FieldDeclaration fieldDeclaration =
+ AstFactory.fieldDeclaration2(false, null, [field]);
+ fieldDeclaration.accept(builder);
+
+ List<FieldElement> variables = holder.fields;
+ expect(variables, hasLength(1));
+ FieldElement fieldElement = variables[0];
+ expect(fieldElement, isNotNull);
+ FunctionElement initializerElement = fieldElement.initializer;
+ expect(initializerElement, isNotNull);
+ expect(initializerElement.hasImplicitReturnType, isTrue);
+ List<FunctionElement> functionElements = initializerElement.functions;
+ expect(functionElements, hasLength(1));
+ List<LocalVariableElement> variableElements =
+ functionElements[0].localVariables;
+ expect(variableElements, hasLength(1));
+ LocalVariableElement variableElement = variableElements[0];
+ expect(variableElement.hasImplicitType, isTrue);
+ expect(variableElement.isConst, isFalse);
+ expect(variableElement.isFinal, isFalse);
+ expect(variableElement.isSynthetic, isFalse);
+ expect(variableElement.name, variableName);
+ }
+
+ void test_visitVariableDeclaration_noInitializer() {
+ // var v;
+ ElementHolder holder = new ElementHolder();
+ ElementBuilder builder = _makeBuilder(holder);
+ String variableName = "v";
+ VariableDeclaration variableDeclaration =
+ AstFactory.variableDeclaration2(variableName, null);
+ AstFactory.variableDeclarationList2(null, [variableDeclaration]);
+ variableDeclaration.accept(builder);
+
+ List<TopLevelVariableElement> variables = holder.topLevelVariables;
+ expect(variables, hasLength(1));
+ TopLevelVariableElement variable = variables[0];
+ expect(variable, isNotNull);
+ expect(variable.hasImplicitType, isTrue);
+ expect(variable.initializer, isNull);
+ expect(variable.name, variableName);
+ expect(variable.isConst, isFalse);
+ expect(variable.isFinal, isFalse);
+ expect(variable.isSynthetic, isFalse);
+ expect(variable.getter, isNotNull);
+ expect(variable.setter, isNotNull);
+ }
+
+ void test_visitVariableDeclaration_top() {
+ // final a, b;
+ ElementHolder holder = new ElementHolder();
+ ElementBuilder builder = _makeBuilder(holder);
+ VariableDeclaration variableDeclaration1 =
+ AstFactory.variableDeclaration('a');
+ VariableDeclaration variableDeclaration2 =
+ AstFactory.variableDeclaration('b');
+ TopLevelVariableDeclaration topLevelVariableDeclaration = AstFactory
+ .topLevelVariableDeclaration(
+ Keyword.FINAL, null, [variableDeclaration1, variableDeclaration2]);
+ topLevelVariableDeclaration.documentationComment = AstFactory
+ .documentationComment(
+ [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
+
+ topLevelVariableDeclaration.accept(builder);
+ List<TopLevelVariableElement> variables = holder.topLevelVariables;
+ expect(variables, hasLength(2));
+
+ TopLevelVariableElement variable1 = variables[0];
+ expect(variable1, isNotNull);
+ expect(variable1.documentationComment, '/// aaa');
+
+ TopLevelVariableElement variable2 = variables[1];
+ expect(variable2, isNotNull);
+ expect(variable2.documentationComment, '/// aaa');
+ }
+
+ void test_visitVariableDeclaration_top_const_hasInitializer() {
+ // const v = 42;
+ ElementHolder holder = new ElementHolder();
+ ElementBuilder builder = _makeBuilder(holder);
+ String variableName = "v";
+ VariableDeclaration variableDeclaration =
+ AstFactory.variableDeclaration2(variableName, AstFactory.integer(42));
+ AstFactory.variableDeclarationList2(Keyword.CONST, [variableDeclaration]);
+ variableDeclaration.accept(builder);
+
+ List<TopLevelVariableElement> variables = holder.topLevelVariables;
+ expect(variables, hasLength(1));
+ TopLevelVariableElement variable = variables[0];
+ expect(variable, new isInstanceOf<ConstTopLevelVariableElementImpl>());
+ expect(variable.initializer, isNotNull);
+ expect(variable.initializer.type, isNotNull);
+ expect(variable.initializer.hasImplicitReturnType, isTrue);
+ expect(variable.name, variableName);
+ expect(variable.hasImplicitType, isTrue);
+ expect(variable.isConst, isTrue);
+ expect(variable.isFinal, isFalse);
+ expect(variable.isSynthetic, isFalse);
+ expect(variable.getter, isNotNull);
+ expect(variable.setter, isNull);
+ }
+
+ void test_visitVariableDeclaration_top_final() {
+ // final v;
+ ElementHolder holder = new ElementHolder();
+ ElementBuilder builder = _makeBuilder(holder);
+ String variableName = "v";
+ VariableDeclaration variableDeclaration =
+ AstFactory.variableDeclaration2(variableName, null);
+ AstFactory.variableDeclarationList2(Keyword.FINAL, [variableDeclaration]);
+ variableDeclaration.accept(builder);
+ List<TopLevelVariableElement> variables = holder.topLevelVariables;
+ expect(variables, hasLength(1));
+ TopLevelVariableElement variable = variables[0];
+ expect(variable, isNotNull);
+ expect(variable.hasImplicitType, isTrue);
+ expect(variable.initializer, isNull);
+ expect(variable.name, variableName);
+ expect(variable.isConst, isFalse);
+ expect(variable.isFinal, isTrue);
+ expect(variable.isSynthetic, isFalse);
+ expect(variable.getter, isNotNull);
+ expect(variable.setter, isNull);
+ }
+
+ ElementBuilder _makeBuilder(ElementHolder holder) =>
+ new ElementBuilder(holder, compilationUnitElement);
+
+ void _setBlockBodySourceRange(BlockFunctionBody body, int offset, int end) {
+ _setNodeSourceRange(body.block, offset, end);
+ }
+
+ void _setNodeSourceRange(AstNode node, int offset, int end) {
+ node.beginToken.offset = offset;
+ Token endToken = node.endToken;
+ endToken.offset = end - endToken.length;
+ }
+
+ void _useParameterInMethod(
+ FormalParameter formalParameter, int blockOffset, int blockEnd) {
+ Block block = AstFactory.block();
+ block.leftBracket.offset = blockOffset;
+ block.rightBracket.offset = blockEnd - 1;
+ BlockFunctionBody body = AstFactory.blockFunctionBody(block);
+ AstFactory.methodDeclaration2(
+ null,
+ null,
+ null,
+ null,
+ AstFactory.identifier3("main"),
+ AstFactory.formalParameterList([formalParameter]),
+ body);
+ }
+}
+
+@reflectiveTest
+class LocalElementBuilderTest extends _BaseTest {
+ @override
+ AstVisitor createElementBuilder(ElementHolder holder) {
+ return new LocalElementBuilder(holder, compilationUnitElement);
+ }
+
+ void test_buildLocalElements() {
+ CompilationUnit unit = ParserTestCase.parseCompilationUnit(r'''
+main() {
+ int v1;
+ f1() {
+ int v2;
+ f2() {
+ int v3;
+ }
+ }
+}
+''');
+ var mainAst = unit.declarations.single as FunctionDeclaration;
+ // Build API elements.
+ FunctionElementImpl main;
+ {
+ ElementHolder holder = new ElementHolder();
+ unit.accept(new ApiElementBuilder(holder, compilationUnitElement));
+ main = holder.functions.single as FunctionElementImpl;
+ }
+ expect(main.localVariables, isEmpty);
+ expect(main.functions, isEmpty);
+ // Build local elements in body.
+ ElementHolder holder = new ElementHolder();
+ FunctionBody mainBody = mainAst.functionExpression.body;
+ mainBody.accept(new LocalElementBuilder(holder, compilationUnitElement));
+ main.functions = holder.functions;
+ main.localVariables = holder.localVariables;
+ expect(main.localVariables.map((v) => v.name), ['v1']);
+ expect(main.functions, hasLength(1));
+ {
+ FunctionElement f1 = main.functions[0];
+ expect(f1.name, 'f1');
+ expect(f1.localVariables.map((v) => v.name), ['v2']);
+ expect(f1.functions, hasLength(1));
+ {
+ FunctionElement f2 = f1.functions[0];
+ expect(f2.name, 'f2');
+ expect(f2.localVariables.map((v) => v.name), ['v3']);
+ expect(f2.functions, isEmpty);
+ }
+ }
+ }
+
+ void test_buildParameterInitializer() {
+ CompilationUnit unit = ParserTestCase.parseCompilationUnit('f({p: 42}) {}');
+ var function = unit.declarations.single as FunctionDeclaration;
+ var parameter = function.functionExpression.parameters.parameters.single
+ as DefaultFormalParameter;
+ // Build API elements.
+ {
+ ElementHolder holder = new ElementHolder();
+ unit.accept(new ApiElementBuilder(holder, compilationUnitElement));
+ }
+ // Validate the parameter element.
+ var parameterElement = parameter.element as ParameterElementImpl;
+ expect(parameterElement, isNotNull);
+ expect(parameterElement.initializer, isNull);
+ // Build the initializer element.
+ new LocalElementBuilder(new ElementHolder(), compilationUnitElement)
+ .buildParameterInitializer(parameterElement, parameter.defaultValue);
+ expect(parameterElement.initializer, isNotNull);
+ }
+
+ void test_buildVariableInitializer() {
+ CompilationUnit unit = ParserTestCase.parseCompilationUnit('var V = 42;');
+ TopLevelVariableDeclaration topLevelDecl =
+ unit.declarations[0] as TopLevelVariableDeclaration;
+ VariableDeclaration variable = topLevelDecl.variables.variables.single;
+ // Build the variable element.
+ {
+ ElementHolder holder = new ElementHolder();
+ unit.accept(new ApiElementBuilder(holder, compilationUnitElement));
+ }
+ // Validate the variable element.
+ var variableElement = variable.element as VariableElementImpl;
+ expect(variableElement, isNotNull);
+ expect(variableElement.initializer, isNull);
+ // Build the initializer element.
+ new LocalElementBuilder(new ElementHolder(), compilationUnitElement)
+ .buildVariableInitializer(variableElement, variable.initializer);
+ expect(variableElement.initializer, isNotNull);
+ }
+
+ void test_visitDefaultFormalParameter_local() {
+ CompilationUnit unit = ParserTestCase.parseCompilationUnit('''
+main() {
+ f({bool b: false}) {}
+}
+''');
+ var mainAst = unit.declarations.single as FunctionDeclaration;
+ // Build API elements.
+ FunctionElementImpl main;
+ {
+ ElementHolder holder = new ElementHolder();
+ unit.accept(new ApiElementBuilder(holder, compilationUnitElement));
+ main = holder.functions.single as FunctionElementImpl;
+ }
+ // Build local elements in body.
+ ElementHolder holder = new ElementHolder();
+ FunctionBody mainBody = mainAst.functionExpression.body;
+ mainBody.accept(new LocalElementBuilder(holder, compilationUnitElement));
+ main.functions = holder.functions;
+ main.localVariables = holder.localVariables;
+ expect(main.functions, hasLength(1));
+ FunctionElement f = main.functions[0];
+ expect(f.parameters, hasLength(1));
+ expect(f.parameters[0].initializer, isNotNull);
+ }
+
+ void test_visitVariableDeclaration_local() {
+ var holder = buildElementsForText('class C { m() { T v = null; } }');
+ List<LocalVariableElement> variableElements = holder.localVariables;
+ expect(variableElements, hasLength(1));
+ LocalVariableElement variableElement = variableElements[0];
+ expect(variableElement.hasImplicitType, isFalse);
+ expect(variableElement.name, 'v');
+ expect(variableElement.initializer, isNotNull);
+ _assertVisibleRange(variableElement, 14, 29);
+ }
+}
+
+/**
+ * Mixin with test methods for testing element building in [ApiElementBuilder].
+ * It is used to test the [ApiElementBuilder] itself, and its usage by
+ * [ElementBuilder].
+ */
+abstract class _ApiElementBuilderTestMixin {
+ CompilationUnit get compilationUnit;
+
+ void assertHasCodeRange(Element element, int offset, int length);
+
+ /**
+ * Build elements using [ApiElementBuilder].
+ */
+ ElementHolder buildElementsForAst(AstNode node);
+
+ /**
+ * Parse the given [code], and build elements using [ApiElementBuilder].
+ */
+ ElementHolder buildElementsForText(String code);
+
+ /**
+ * Verify that the given [metadata] has exactly one annotation, and that its
+ * [ElementAnnotationImpl] is unresolved.
+ */
+ void checkAnnotation(NodeList<Annotation> metadata);
+
+ /**
+ * Verify that the given [element] has exactly one annotation, and that its
+ * [ElementAnnotationImpl] is unresolved.
+ */
+ void checkMetadata(Element element);
+
+ void test_metadata_fieldDeclaration() {
+ List<FieldElement> fields =
+ buildElementsForText('class C { @a int x, y; }').types[0].fields;
+ checkMetadata(fields[0]);
+ checkMetadata(fields[1]);
+ expect(fields[0].metadata, same(fields[1].metadata));
+ }
+
+ void test_metadata_topLevelVariableDeclaration() {
+ List<TopLevelVariableElement> topLevelVariables =
+ buildElementsForText('@a int x, y;').topLevelVariables;
+ checkMetadata(topLevelVariables[0]);
+ checkMetadata(topLevelVariables[1]);
+ expect(topLevelVariables[0].metadata, same(topLevelVariables[1].metadata));
+ }
+
+ void test_metadata_visitClassDeclaration() {
+ ClassElement classElement = buildElementsForText('@a class C {}').types[0];
+ checkMetadata(classElement);
+ }
+
+ void test_metadata_visitClassTypeAlias() {
+ ClassElement classElement =
+ buildElementsForText('@a class C = D with E;').types[0];
+ checkMetadata(classElement);
+ }
+
+ void test_metadata_visitConstructorDeclaration() {
+ ConstructorElement constructorElement =
+ buildElementsForText('class C { @a C(); }').types[0].constructors[0];
+ checkMetadata(constructorElement);
+ }
+
+ void test_metadata_visitDefaultFormalParameter_fieldFormalParameter() {
+ ParameterElement parameterElement =
+ buildElementsForText('class C { var x; C([@a this.x = null]); }')
+ .types[0]
+ .constructors[0]
+ .parameters[0];
+ checkMetadata(parameterElement);
+ }
+
+ void
+ test_metadata_visitDefaultFormalParameter_functionTypedFormalParameter() {
+ ParameterElement parameterElement =
+ buildElementsForText('f([@a g() = null]) {}').functions[0].parameters[
+ 0];
+ checkMetadata(parameterElement);
+ }
+
+ void test_metadata_visitDefaultFormalParameter_simpleFormalParameter() {
+ ParameterElement parameterElement =
+ buildElementsForText('f([@a gx = null]) {}').functions[0].parameters[0];
+ checkMetadata(parameterElement);
+ }
+
+ void test_metadata_visitEnumDeclaration() {
+ ClassElement classElement =
+ buildElementsForText('@a enum E { v }').enums[0];
+ checkMetadata(classElement);
+ }
+
+ void test_metadata_visitExportDirective() {
+ buildElementsForText('@a export "foo.dart";');
+ expect(compilationUnit.directives[0], new isInstanceOf<ExportDirective>());
+ ExportDirective exportDirective = compilationUnit.directives[0];
+ checkAnnotation(exportDirective.metadata);
+ }
+
+ void test_metadata_visitFieldFormalParameter() {
+ ParameterElement parameterElement =
+ buildElementsForText('class C { var x; C(@a this.x); }')
+ .types[0]
+ .constructors[0]
+ .parameters[0];
+ checkMetadata(parameterElement);
+ }
+
+ void test_metadata_visitFunctionDeclaration_function() {
+ FunctionElement functionElement =
+ buildElementsForText('@a f() {}').functions[0];
+ checkMetadata(functionElement);
+ }
+
+ void test_metadata_visitFunctionDeclaration_getter() {
+ PropertyAccessorElement propertyAccessorElement =
+ buildElementsForText('@a get f => null;').accessors[0];
+ checkMetadata(propertyAccessorElement);
+ }
+
+ void test_metadata_visitFunctionDeclaration_setter() {
+ PropertyAccessorElement propertyAccessorElement =
+ buildElementsForText('@a set f(value) {}').accessors[0];
+ checkMetadata(propertyAccessorElement);
+ }
+
+ void test_metadata_visitFunctionTypeAlias() {
+ FunctionTypeAliasElement functionTypeAliasElement =
+ buildElementsForText('@a typedef F();').typeAliases[0];
+ checkMetadata(functionTypeAliasElement);
+ }
+
+ void test_metadata_visitFunctionTypedFormalParameter() {
+ ParameterElement parameterElement =
+ buildElementsForText('f(@a g()) {}').functions[0].parameters[0];
+ checkMetadata(parameterElement);
+ }
+
+ void test_metadata_visitImportDirective() {
+ buildElementsForText('@a import "foo.dart";');
+ expect(compilationUnit.directives[0], new isInstanceOf<ImportDirective>());
+ ImportDirective importDirective = compilationUnit.directives[0];
+ checkAnnotation(importDirective.metadata);
+ }
+
+ void test_metadata_visitLibraryDirective() {
+ buildElementsForText('@a library L;');
+ expect(compilationUnit.directives[0], new isInstanceOf<LibraryDirective>());
+ LibraryDirective libraryDirective = compilationUnit.directives[0];
+ checkAnnotation(libraryDirective.metadata);
+ }
+
+ void test_metadata_visitMethodDeclaration_getter() {
+ PropertyAccessorElement propertyAccessorElement =
+ buildElementsForText('class C { @a get m => null; }')
+ .types[0]
+ .accessors[0];
+ checkMetadata(propertyAccessorElement);
+ }
+
+ void test_metadata_visitMethodDeclaration_method() {
+ MethodElement methodElement =
+ buildElementsForText('class C { @a m() {} }').types[0].methods[0];
+ checkMetadata(methodElement);
+ }
+
+ void test_metadata_visitMethodDeclaration_setter() {
+ PropertyAccessorElement propertyAccessorElement =
+ buildElementsForText('class C { @a set f(value) {} }')
+ .types[0]
+ .accessors[0];
+ checkMetadata(propertyAccessorElement);
+ }
+
+ void test_metadata_visitPartDirective() {
+ buildElementsForText('@a part "foo.dart";');
+ expect(compilationUnit.directives[0], new isInstanceOf<PartDirective>());
+ PartDirective partDirective = compilationUnit.directives[0];
+ checkAnnotation(partDirective.metadata);
+ }
+
+ void test_metadata_visitPartOfDirective() {
+ // We don't build ElementAnnotation objects for `part of` directives, since
+ // analyzer ignores them in favor of annotations on the library directive.
+ buildElementsForText('@a part of L;');
+ expect(compilationUnit.directives[0], new isInstanceOf<PartOfDirective>());
+ PartOfDirective partOfDirective = compilationUnit.directives[0];
+ expect(partOfDirective.metadata, hasLength(1));
+ expect(partOfDirective.metadata[0].elementAnnotation, isNull);
+ }
+
+ void test_metadata_visitSimpleFormalParameter() {
+ ParameterElement parameterElement =
+ buildElementsForText('f(@a x) {}').functions[0].parameters[0];
+ checkMetadata(parameterElement);
+ }
+
+ void test_metadata_visitTypeParameter() {
+ TypeParameterElement typeParameterElement =
+ buildElementsForText('class C<@a T> {}').types[0].typeParameters[0];
+ checkMetadata(typeParameterElement);
+ }
+
+ void test_visitClassDeclaration_abstract() {
+ List<ClassElement> types =
+ buildElementsForText('abstract class C {}').types;
+ expect(types, hasLength(1));
+ ClassElement type = types[0];
+ expect(type, isNotNull);
+ expect(type.name, 'C');
+ List<TypeParameterElement> typeParameters = type.typeParameters;
+ expect(typeParameters, hasLength(0));
+ expect(type.isAbstract, isTrue);
+ expect(type.isMixinApplication, isFalse);
+ expect(type.isSynthetic, isFalse);
+ }
+
+ void test_visitClassDeclaration_invalidFunctionInAnnotation_class() {
+ // https://github.com/dart-lang/sdk/issues/25696
+ String code = r'''
+class A {
+ const A({f});
+}
+
+@A(f: () {})
+class C {}
+''';
+ buildElementsForText(code);
+ }
+
+ void test_visitClassDeclaration_invalidFunctionInAnnotation_method() {
+ String code = r'''
+class A {
+ const A({f});
+}
+
+class C {
+ @A(f: () {})
+ void m() {}
+}
+''';
+ ElementHolder holder = buildElementsForText(code);
+ ClassElement elementC = holder.types[1];
+ expect(elementC, isNotNull);
+ MethodElement methodM = elementC.methods[0];
+ expect(methodM, isNotNull);
+ expect(methodM.functions, isEmpty);
+ }
+
+ void test_visitClassDeclaration_minimal() {
+ String className = "C";
+ ClassDeclaration classDeclaration =
+ AstFactory.classDeclaration(null, className, null, null, null, null);
+ classDeclaration.documentationComment = AstFactory.documentationComment(
+ [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
+ classDeclaration.endToken.offset = 80;
+
+ ElementHolder holder = buildElementsForAst(classDeclaration);
+ List<ClassElement> types = holder.types;
+ expect(types, hasLength(1));
+ ClassElement type = types[0];
+ expect(type, isNotNull);
+ expect(type.name, className);
+ List<TypeParameterElement> typeParameters = type.typeParameters;
+ expect(typeParameters, hasLength(0));
+ expect(type.isAbstract, isFalse);
+ expect(type.isMixinApplication, isFalse);
+ expect(type.isSynthetic, isFalse);
+ expect(type.documentationComment, '/// aaa');
+ assertHasCodeRange(type, 50, 31);
+ }
+
+ void test_visitClassDeclaration_parameterized() {
+ String className = "C";
+ String firstVariableName = "E";
+ String secondVariableName = "F";
+ ClassDeclaration classDeclaration = AstFactory.classDeclaration(
+ null,
+ className,
+ AstFactory.typeParameterList([firstVariableName, secondVariableName]),
+ null,
+ null,
+ null);
+
+ ElementHolder holder = buildElementsForAst(classDeclaration);
+ List<ClassElement> types = holder.types;
+ expect(types, hasLength(1));
+ ClassElement type = types[0];
+ expect(type, isNotNull);
+ expect(type.name, className);
+ List<TypeParameterElement> typeParameters = type.typeParameters;
+ expect(typeParameters, hasLength(2));
+ expect(typeParameters[0].name, firstVariableName);
+ expect(typeParameters[1].name, secondVariableName);
+ expect(type.isAbstract, isFalse);
+ expect(type.isMixinApplication, isFalse);
+ expect(type.isSynthetic, isFalse);
+ }
+
+ void test_visitClassDeclaration_withMembers() {
+ String className = "C";
+ String typeParameterName = "E";
+ String fieldName = "f";
+ String methodName = "m";
+ ClassDeclaration classDeclaration = AstFactory.classDeclaration(
+ null,
+ className,
+ AstFactory.typeParameterList([typeParameterName]),
+ null,
+ null,
+ null, [
+ AstFactory.fieldDeclaration2(
+ false, null, [AstFactory.variableDeclaration(fieldName)]),
+ AstFactory.methodDeclaration2(
+ null,
+ null,
+ null,
+ null,
+ AstFactory.identifier3(methodName),
+ AstFactory.formalParameterList(),
+ AstFactory.blockFunctionBody2())
+ ]);
+
+ ElementHolder holder = buildElementsForAst(classDeclaration);
+ List<ClassElement> types = holder.types;
+ expect(types, hasLength(1));
+ ClassElement type = types[0];
+ expect(type, isNotNull);
+ expect(type.name, className);
+ expect(type.isAbstract, isFalse);
+ expect(type.isMixinApplication, isFalse);
+ expect(type.isSynthetic, isFalse);
+ List<TypeParameterElement> typeParameters = type.typeParameters;
+ expect(typeParameters, hasLength(1));
+ TypeParameterElement typeParameter = typeParameters[0];
+ expect(typeParameter, isNotNull);
+ expect(typeParameter.name, typeParameterName);
+ List<FieldElement> fields = type.fields;
+ expect(fields, hasLength(1));
+ FieldElement field = fields[0];
+ expect(field, isNotNull);
+ expect(field.name, fieldName);
+ List<MethodElement> methods = type.methods;
+ expect(methods, hasLength(1));
+ MethodElement method = methods[0];
+ expect(method, isNotNull);
+ expect(method.name, methodName);
+ }
+
+ void test_visitClassTypeAlias() {
+ // class B {}
+ // class M {}
+ // class C = B with M
+ ClassElementImpl classB = ElementFactory.classElement2('B', []);
+ ConstructorElementImpl constructorB =
+ ElementFactory.constructorElement2(classB, '', []);
+ constructorB.setModifier(Modifier.SYNTHETIC, true);
+ classB.constructors = [constructorB];
+ ClassElement classM = ElementFactory.classElement2('M', []);
+ WithClause withClause =
+ AstFactory.withClause([AstFactory.typeName(classM, [])]);
+ ClassTypeAlias alias = AstFactory.classTypeAlias(
+ 'C', null, null, AstFactory.typeName(classB, []), withClause, null);
+
+ ElementHolder holder = buildElementsForAst(alias);
+ List<ClassElement> types = holder.types;
+ expect(types, hasLength(1));
+ ClassElement type = types[0];
+ expect(alias.element, same(type));
+ expect(type.name, equals('C'));
+ expect(type.isAbstract, isFalse);
+ expect(type.isMixinApplication, isTrue);
+ expect(type.isSynthetic, isFalse);
+ expect(type.typeParameters, isEmpty);
+ expect(type.fields, isEmpty);
+ expect(type.methods, isEmpty);
+ }
+
+ void test_visitClassTypeAlias_abstract() {
+ // class B {}
+ // class M {}
+ // abstract class C = B with M
+ ClassElementImpl classB = ElementFactory.classElement2('B', []);
+ ConstructorElementImpl constructorB =
+ ElementFactory.constructorElement2(classB, '', []);
+ constructorB.setModifier(Modifier.SYNTHETIC, true);
+ classB.constructors = [constructorB];
+ ClassElement classM = ElementFactory.classElement2('M', []);
+ WithClause withClause =
+ AstFactory.withClause([AstFactory.typeName(classM, [])]);
+ ClassTypeAlias alias = AstFactory.classTypeAlias('C', null,
+ Keyword.ABSTRACT, AstFactory.typeName(classB, []), withClause, null);
+
+ ElementHolder holder = buildElementsForAst(alias);
+ List<ClassElement> types = holder.types;
+ expect(types, hasLength(1));
+ ClassElement type = types[0];
+ expect(type.isAbstract, isTrue);
+ expect(type.isMixinApplication, isTrue);
+ }
+
+ void test_visitClassTypeAlias_typeParams() {
+ // class B {}
+ // class M {}
+ // class C<T> = B with M
+ ClassElementImpl classB = ElementFactory.classElement2('B', []);
+ ConstructorElementImpl constructorB =
+ ElementFactory.constructorElement2(classB, '', []);
+ constructorB.setModifier(Modifier.SYNTHETIC, true);
+ classB.constructors = [constructorB];
+ ClassElementImpl classM = ElementFactory.classElement2('M', []);
+ WithClause withClause =
+ AstFactory.withClause([AstFactory.typeName(classM, [])]);
+ ClassTypeAlias alias = AstFactory.classTypeAlias(
+ 'C',
+ AstFactory.typeParameterList(['T']),
+ null,
+ AstFactory.typeName(classB, []),
+ withClause,
+ null);
+
+ ElementHolder holder = buildElementsForAst(alias);
+ List<ClassElement> types = holder.types;
+ expect(types, hasLength(1));
+ ClassElement type = types[0];
+ expect(type.typeParameters, hasLength(1));
+ expect(type.typeParameters[0].name, equals('T'));
+ }
+
+ void test_visitConstructorDeclaration_external() {
+ String className = "A";
+ ConstructorDeclaration constructorDeclaration =
+ AstFactory.constructorDeclaration2(
+ null,
+ null,
+ AstFactory.identifier3(className),
+ null,
+ AstFactory.formalParameterList(),
+ null,
+ AstFactory.blockFunctionBody2());
+ constructorDeclaration.externalKeyword =
+ TokenFactory.tokenFromKeyword(Keyword.EXTERNAL);
+
+ ElementHolder holder = buildElementsForAst(constructorDeclaration);
+ List<ConstructorElement> constructors = holder.constructors;
+ expect(constructors, hasLength(1));
+ ConstructorElement constructor = constructors[0];
+ expect(constructor, isNotNull);
+ expect(constructor.isExternal, isTrue);
+ expect(constructor.isFactory, isFalse);
+ expect(constructor.name, "");
+ expect(constructor.functions, hasLength(0));
+ expect(constructor.labels, hasLength(0));
+ expect(constructor.localVariables, hasLength(0));
+ expect(constructor.parameters, hasLength(0));
+ }
+
+ void test_visitConstructorDeclaration_factory() {
+ String className = "A";
+ ConstructorDeclaration constructorDeclaration =
+ AstFactory.constructorDeclaration2(
+ null,
+ Keyword.FACTORY,
+ AstFactory.identifier3(className),
+ null,
+ AstFactory.formalParameterList(),
+ null,
+ AstFactory.blockFunctionBody2());
+
+ ElementHolder holder = buildElementsForAst(constructorDeclaration);
+ List<ConstructorElement> constructors = holder.constructors;
+ expect(constructors, hasLength(1));
+ ConstructorElement constructor = constructors[0];
+ expect(constructor, isNotNull);
+ expect(constructor.isExternal, isFalse);
+ expect(constructor.isFactory, isTrue);
+ expect(constructor.name, "");
+ expect(constructor.functions, hasLength(0));
+ expect(constructor.labels, hasLength(0));
+ expect(constructor.localVariables, hasLength(0));
+ expect(constructor.parameters, hasLength(0));
+ }
+
+ void test_visitConstructorDeclaration_minimal() {
+ String className = "A";
+ ConstructorDeclaration constructorDeclaration =
+ AstFactory.constructorDeclaration2(
+ null,
+ null,
+ AstFactory.identifier3(className),
+ null,
+ AstFactory.formalParameterList(),
+ null,
+ AstFactory.blockFunctionBody2());
+ constructorDeclaration.documentationComment = AstFactory
+ .documentationComment(
+ [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
+ constructorDeclaration.endToken.offset = 80;
+
+ ElementHolder holder = buildElementsForAst(constructorDeclaration);
+ List<ConstructorElement> constructors = holder.constructors;
+ expect(constructors, hasLength(1));
+ ConstructorElement constructor = constructors[0];
+ expect(constructor, isNotNull);
+ assertHasCodeRange(constructor, 50, 31);
+ expect(constructor.documentationComment, '/// aaa');
+ expect(constructor.isExternal, isFalse);
+ expect(constructor.isFactory, isFalse);
+ expect(constructor.name, "");
+ expect(constructor.functions, hasLength(0));
+ expect(constructor.labels, hasLength(0));
+ expect(constructor.localVariables, hasLength(0));
+ expect(constructor.parameters, hasLength(0));
+ }
+
+ void test_visitConstructorDeclaration_named() {
+ String className = "A";
+ String constructorName = "c";
+ ConstructorDeclaration constructorDeclaration =
+ AstFactory.constructorDeclaration2(
+ null,
+ null,
+ AstFactory.identifier3(className),
+ constructorName,
+ AstFactory.formalParameterList(),
+ null,
+ AstFactory.blockFunctionBody2());
+
+ ElementHolder holder = buildElementsForAst(constructorDeclaration);
+ List<ConstructorElement> constructors = holder.constructors;
+ expect(constructors, hasLength(1));
+ ConstructorElement constructor = constructors[0];
+ expect(constructor, isNotNull);
+ expect(constructor.isExternal, isFalse);
+ expect(constructor.isFactory, isFalse);
+ expect(constructor.name, constructorName);
+ expect(constructor.functions, hasLength(0));
+ expect(constructor.labels, hasLength(0));
+ expect(constructor.localVariables, hasLength(0));
+ expect(constructor.parameters, hasLength(0));
+ expect(constructorDeclaration.name.staticElement, same(constructor));
+ expect(constructorDeclaration.element, same(constructor));
+ }
+
+ void test_visitConstructorDeclaration_unnamed() {
+ String className = "A";
+ ConstructorDeclaration constructorDeclaration =
+ AstFactory.constructorDeclaration2(
+ null,
+ null,
+ AstFactory.identifier3(className),
+ null,
+ AstFactory.formalParameterList(),
+ null,
+ AstFactory.blockFunctionBody2());
+
+ ElementHolder holder = buildElementsForAst(constructorDeclaration);
+ List<ConstructorElement> constructors = holder.constructors;
+ expect(constructors, hasLength(1));
+ ConstructorElement constructor = constructors[0];
+ expect(constructor, isNotNull);
+ expect(constructor.isExternal, isFalse);
+ expect(constructor.isFactory, isFalse);
+ expect(constructor.name, "");
+ expect(constructor.functions, hasLength(0));
+ expect(constructor.labels, hasLength(0));
+ expect(constructor.localVariables, hasLength(0));
+ expect(constructor.parameters, hasLength(0));
+ expect(constructorDeclaration.element, same(constructor));
+ }
+
+ void test_visitEnumDeclaration() {
+ String enumName = "E";
+ EnumDeclaration enumDeclaration =
+ AstFactory.enumDeclaration2(enumName, ["ONE"]);
+ enumDeclaration.documentationComment = AstFactory.documentationComment(
+ [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
+ enumDeclaration.endToken.offset = 80;
+ ElementHolder holder = buildElementsForAst(enumDeclaration);
+ List<ClassElement> enums = holder.enums;
+ expect(enums, hasLength(1));
+ ClassElement enumElement = enums[0];
+ expect(enumElement, isNotNull);
+ assertHasCodeRange(enumElement, 50, 31);
+ expect(enumElement.documentationComment, '/// aaa');
+ expect(enumElement.name, enumName);
+ }
+
+ void test_visitFieldDeclaration() {
+ String firstFieldName = "x";
+ String secondFieldName = "y";
+ FieldDeclaration fieldDeclaration =
+ AstFactory.fieldDeclaration2(false, null, [
+ AstFactory.variableDeclaration(firstFieldName),
+ AstFactory.variableDeclaration(secondFieldName)
+ ]);
+ fieldDeclaration.documentationComment = AstFactory.documentationComment(
+ [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
+ fieldDeclaration.endToken.offset = 110;
+
+ ElementHolder holder = buildElementsForAst(fieldDeclaration);
+ List<FieldElement> fields = holder.fields;
+ expect(fields, hasLength(2));
+
+ FieldElement firstField = fields[0];
+ expect(firstField, isNotNull);
+ assertHasCodeRange(firstField, 50, 61);
+ expect(firstField.documentationComment, '/// aaa');
+ expect(firstField.name, firstFieldName);
+ expect(firstField.initializer, isNull);
+ expect(firstField.isConst, isFalse);
+ expect(firstField.isFinal, isFalse);
+ expect(firstField.isSynthetic, isFalse);
+
+ FieldElement secondField = fields[1];
+ expect(secondField, isNotNull);
+ assertHasCodeRange(secondField, 50, 61);
+ expect(secondField.documentationComment, '/// aaa');
+ expect(secondField.name, secondFieldName);
+ expect(secondField.initializer, isNull);
+ expect(secondField.isConst, isFalse);
+ expect(secondField.isFinal, isFalse);
+ expect(secondField.isSynthetic, isFalse);
+ }
+
+ void test_visitFieldFormalParameter() {
+ String parameterName = "p";
+ FieldFormalParameter formalParameter =
+ AstFactory.fieldFormalParameter(null, null, parameterName);
+ formalParameter.beginToken.offset = 50;
+ formalParameter.endToken.offset = 80;
+ ElementHolder holder = buildElementsForAst(formalParameter);
+ List<ParameterElement> parameters = holder.parameters;
+ expect(parameters, hasLength(1));
+ ParameterElement parameter = parameters[0];
+ expect(parameter, isNotNull);
+ assertHasCodeRange(parameter, 50, 31);
+ expect(parameter.name, parameterName);
+ expect(parameter.initializer, isNull);
+ expect(parameter.isConst, isFalse);
+ expect(parameter.isFinal, isFalse);
+ expect(parameter.isSynthetic, isFalse);
+ expect(parameter.parameterKind, ParameterKind.REQUIRED);
+ expect(parameter.parameters, hasLength(0));
+ }
+
+ void test_visitFieldFormalParameter_functionTyped() {
+ String parameterName = "p";
+ FieldFormalParameter formalParameter = AstFactory.fieldFormalParameter(
+ null,
+ null,
+ parameterName,
+ AstFactory
+ .formalParameterList([AstFactory.simpleFormalParameter3("a")]));
+ ElementHolder holder = buildElementsForAst(formalParameter);
+ List<ParameterElement> parameters = holder.parameters;
+ expect(parameters, hasLength(1));
+ ParameterElement parameter = parameters[0];
+ expect(parameter, isNotNull);
+ expect(parameter.name, parameterName);
+ expect(parameter.initializer, isNull);
+ expect(parameter.isConst, isFalse);
+ expect(parameter.isFinal, isFalse);
+ expect(parameter.isSynthetic, isFalse);
+ expect(parameter.parameterKind, ParameterKind.REQUIRED);
+ expect(parameter.parameters, hasLength(1));
+ }
+
+ void test_visitFormalParameterList() {
+ String firstParameterName = "a";
+ String secondParameterName = "b";
+ FormalParameterList parameterList = AstFactory.formalParameterList([
+ AstFactory.simpleFormalParameter3(firstParameterName),
+ AstFactory.simpleFormalParameter3(secondParameterName)
+ ]);
+ ElementHolder holder = buildElementsForAst(parameterList);
+ List<ParameterElement> parameters = holder.parameters;
+ expect(parameters, hasLength(2));
+ expect(parameters[0].name, firstParameterName);
+ expect(parameters[1].name, secondParameterName);
+ }
+
+ void test_visitFunctionDeclaration_external() {
+ // external f();
+ String functionName = "f";
+ FunctionDeclaration declaration = AstFactory.functionDeclaration(
+ null,
+ null,
+ functionName,
+ AstFactory.functionExpression2(
+ AstFactory.formalParameterList(), AstFactory.emptyFunctionBody()));
+ declaration.externalKeyword =
+ TokenFactory.tokenFromKeyword(Keyword.EXTERNAL);
+
+ ElementHolder holder = buildElementsForAst(declaration);
+ List<FunctionElement> functions = holder.functions;
+ expect(functions, hasLength(1));
+ FunctionElement function = functions[0];
+ expect(function, isNotNull);
+ expect(function.name, functionName);
+ expect(declaration.element, same(function));
+ expect(declaration.functionExpression.element, same(function));
+ expect(function.hasImplicitReturnType, isTrue);
+ expect(function.isExternal, isTrue);
+ expect(function.isSynthetic, isFalse);
+ expect(function.typeParameters, hasLength(0));
+ }
+
+ void test_visitFunctionDeclaration_getter() {
+ // get f() {}
+ String functionName = "f";
+ FunctionDeclaration declaration = AstFactory.functionDeclaration(
+ null,
+ Keyword.GET,
+ functionName,
+ AstFactory.functionExpression2(
+ AstFactory.formalParameterList(), AstFactory.blockFunctionBody2()));
+ declaration.documentationComment = AstFactory.documentationComment(
+ [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
+ declaration.endToken.offset = 80;
+
+ ElementHolder holder = buildElementsForAst(declaration);
+ List<PropertyAccessorElement> accessors = holder.accessors;
+ expect(accessors, hasLength(1));
+ PropertyAccessorElement accessor = accessors[0];
+ expect(accessor, isNotNull);
+ assertHasCodeRange(accessor, 50, 31);
+ expect(accessor.documentationComment, '/// aaa');
+ expect(accessor.name, functionName);
+ expect(declaration.element, same(accessor));
+ expect(declaration.functionExpression.element, same(accessor));
+ expect(accessor.hasImplicitReturnType, isTrue);
+ expect(accessor.isGetter, isTrue);
+ expect(accessor.isExternal, isFalse);
+ expect(accessor.isSetter, isFalse);
+ expect(accessor.isSynthetic, isFalse);
+ expect(accessor.typeParameters, hasLength(0));
+ PropertyInducingElement variable = accessor.variable;
+ EngineTestCase.assertInstanceOf((obj) => obj is TopLevelVariableElement,
+ TopLevelVariableElement, variable);
+ expect(variable.isSynthetic, isTrue);
+ }
+
+ void test_visitFunctionDeclaration_plain() {
+ // T f() {}
+ String functionName = "f";
+ FunctionDeclaration declaration = AstFactory.functionDeclaration(
+ AstFactory.typeName4('T'),
+ null,
+ functionName,
+ AstFactory.functionExpression2(
+ AstFactory.formalParameterList(), AstFactory.blockFunctionBody2()));
+ declaration.documentationComment = AstFactory.documentationComment(
+ [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
+ declaration.endToken.offset = 80;
+
+ ElementHolder holder = buildElementsForAst(declaration);
+ List<FunctionElement> functions = holder.functions;
+ expect(functions, hasLength(1));
+ FunctionElement function = functions[0];
+ expect(function, isNotNull);
+ assertHasCodeRange(function, 50, 31);
+ expect(function.documentationComment, '/// aaa');
+ expect(function.hasImplicitReturnType, isFalse);
+ expect(function.name, functionName);
+ expect(declaration.element, same(function));
+ expect(declaration.functionExpression.element, same(function));
+ expect(function.isExternal, isFalse);
+ expect(function.isSynthetic, isFalse);
+ expect(function.typeParameters, hasLength(0));
+ }
+
+ void test_visitFunctionDeclaration_setter() {
+ // set f() {}
+ String functionName = "f";
+ FunctionDeclaration declaration = AstFactory.functionDeclaration(
+ null,
+ Keyword.SET,
+ functionName,
+ AstFactory.functionExpression2(
+ AstFactory.formalParameterList(), AstFactory.blockFunctionBody2()));
+ declaration.documentationComment = AstFactory.documentationComment(
+ [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
+ declaration.endToken.offset = 80;
+
+ ElementHolder holder = buildElementsForAst(declaration);
+ List<PropertyAccessorElement> accessors = holder.accessors;
+ expect(accessors, hasLength(1));
+ PropertyAccessorElement accessor = accessors[0];
+ expect(accessor, isNotNull);
+ assertHasCodeRange(accessor, 50, 31);
+ expect(accessor.documentationComment, '/// aaa');
+ expect(accessor.hasImplicitReturnType, isTrue);
+ expect(accessor.name, "$functionName=");
+ expect(declaration.element, same(accessor));
+ expect(declaration.functionExpression.element, same(accessor));
+ expect(accessor.isGetter, isFalse);
+ expect(accessor.isExternal, isFalse);
+ expect(accessor.isSetter, isTrue);
+ expect(accessor.isSynthetic, isFalse);
+ expect(accessor.typeParameters, hasLength(0));
+ PropertyInducingElement variable = accessor.variable;
+ EngineTestCase.assertInstanceOf((obj) => obj is TopLevelVariableElement,
+ TopLevelVariableElement, variable);
+ expect(variable.isSynthetic, isTrue);
+ }
+
+ void test_visitFunctionDeclaration_typeParameters() {
+ // f<E>() {}
+ String functionName = 'f';
+ String typeParameterName = 'E';
+ FunctionExpression expression = AstFactory.functionExpression3(
+ AstFactory.typeParameterList([typeParameterName]),
+ AstFactory.formalParameterList(),
+ AstFactory.blockFunctionBody2());
+ FunctionDeclaration declaration =
+ AstFactory.functionDeclaration(null, null, functionName, expression);
+
+ ElementHolder holder = buildElementsForAst(declaration);
+ List<FunctionElement> functions = holder.functions;
+ expect(functions, hasLength(1));
+ FunctionElement function = functions[0];
+ expect(function, isNotNull);
+ expect(function.hasImplicitReturnType, isTrue);
+ expect(function.name, functionName);
+ expect(function.isExternal, isFalse);
+ expect(function.isSynthetic, isFalse);
+ expect(declaration.element, same(function));
+ expect(expression.element, same(function));
+ List<TypeParameterElement> typeParameters = function.typeParameters;
+ expect(typeParameters, hasLength(1));
+ TypeParameterElement typeParameter = typeParameters[0];
+ expect(typeParameter, isNotNull);
+ expect(typeParameter.name, typeParameterName);
+ }
+
+ void test_visitMethodDeclaration_abstract() {
+ // m();
+ String methodName = "m";
+ MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
+ null,
+ null,
+ null,
+ null,
+ AstFactory.identifier3(methodName),
+ AstFactory.formalParameterList(),
+ AstFactory.emptyFunctionBody());
+
+ ElementHolder holder = buildElementsForAst(methodDeclaration);
+ List<MethodElement> methods = holder.methods;
+ expect(methods, hasLength(1));
+ MethodElement method = methods[0];
+ expect(method, isNotNull);
+ expect(method.hasImplicitReturnType, isTrue);
+ expect(method.name, methodName);
+ expect(method.functions, hasLength(0));
+ expect(method.labels, hasLength(0));
+ expect(method.localVariables, hasLength(0));
+ expect(method.parameters, hasLength(0));
+ expect(method.typeParameters, hasLength(0));
+ expect(method.isAbstract, isTrue);
+ expect(method.isExternal, isFalse);
+ expect(method.isStatic, isFalse);
+ expect(method.isSynthetic, isFalse);
+ }
+
+ void test_visitMethodDeclaration_duplicateField_synthetic() {
+ buildElementsForText(r'''
+class A {
+ int f;
+ int get f => 42;
+}
+''');
+ ClassDeclaration classNode = compilationUnit.declarations.single;
+ // ClassElement
+ ClassElement classElement = classNode.element;
+ expect(classElement.fields, hasLength(2));
+ expect(classElement.accessors, hasLength(3));
+ FieldElement notSyntheticFieldElement = classElement.fields
+ .singleWhere((f) => f.displayName == 'f' && !f.isSynthetic);
+ FieldElement syntheticFieldElement = classElement.fields
+ .singleWhere((f) => f.displayName == 'f' && f.isSynthetic);
+ PropertyAccessorElement syntheticGetterElement = classElement.accessors
+ .singleWhere(
+ (a) => a.displayName == 'f' && a.isGetter && a.isSynthetic);
+ PropertyAccessorElement syntheticSetterElement = classElement.accessors
+ .singleWhere(
+ (a) => a.displayName == 'f' && a.isSetter && a.isSynthetic);
+ PropertyAccessorElement notSyntheticGetterElement = classElement.accessors
+ .singleWhere(
+ (a) => a.displayName == 'f' && a.isGetter && !a.isSynthetic);
+ expect(notSyntheticFieldElement.getter, same(syntheticGetterElement));
+ expect(notSyntheticFieldElement.setter, same(syntheticSetterElement));
+ expect(syntheticFieldElement.getter, same(notSyntheticGetterElement));
+ expect(syntheticFieldElement.setter, isNull);
+ // class members nodes and their elements
+ FieldDeclaration fieldDeclNode = classNode.members[0];
+ VariableDeclaration fieldNode = fieldDeclNode.fields.variables.single;
+ MethodDeclaration getterNode = classNode.members[1];
+ expect(fieldNode.element, notSyntheticFieldElement);
+ expect(getterNode.element, notSyntheticGetterElement);
+ }
+
+ void test_visitMethodDeclaration_external() {
+ // external m();
+ String methodName = "m";
+ MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
+ null,
+ null,
+ null,
+ null,
+ AstFactory.identifier3(methodName),
+ AstFactory.formalParameterList(),
+ AstFactory.emptyFunctionBody());
+ methodDeclaration.externalKeyword =
+ TokenFactory.tokenFromKeyword(Keyword.EXTERNAL);
+
+ ElementHolder holder = buildElementsForAst(methodDeclaration);
+ List<MethodElement> methods = holder.methods;
+ expect(methods, hasLength(1));
+ MethodElement method = methods[0];
+ expect(method, isNotNull);
+ expect(method.hasImplicitReturnType, isTrue);
+ expect(method.name, methodName);
+ expect(method.functions, hasLength(0));
+ expect(method.labels, hasLength(0));
+ expect(method.localVariables, hasLength(0));
+ expect(method.parameters, hasLength(0));
+ expect(method.typeParameters, hasLength(0));
+ expect(method.isAbstract, isFalse);
+ expect(method.isExternal, isTrue);
+ expect(method.isStatic, isFalse);
+ expect(method.isSynthetic, isFalse);
+ }
+
+ void test_visitMethodDeclaration_getter() {
+ // get m() {}
+ String methodName = "m";
+ MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
+ null,
+ null,
+ Keyword.GET,
+ null,
+ AstFactory.identifier3(methodName),
+ AstFactory.formalParameterList(),
+ AstFactory.blockFunctionBody2());
+ methodDeclaration.documentationComment = AstFactory.documentationComment(
+ [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
+ methodDeclaration.endToken.offset = 80;
+
+ ElementHolder holder = buildElementsForAst(methodDeclaration);
+ List<FieldElement> fields = holder.fields;
+ expect(fields, hasLength(1));
+ FieldElement field = fields[0];
+ expect(field, isNotNull);
+ expect(field.name, methodName);
+ expect(field.isSynthetic, isTrue);
+ expect(field.setter, isNull);
+ PropertyAccessorElement getter = field.getter;
+ expect(getter, isNotNull);
+ assertHasCodeRange(getter, 50, 31);
+ expect(getter.documentationComment, '/// aaa');
+ expect(getter.hasImplicitReturnType, isTrue);
+ expect(getter.isAbstract, isFalse);
+ expect(getter.isExternal, isFalse);
+ expect(getter.isGetter, isTrue);
+ expect(getter.isSynthetic, isFalse);
+ expect(getter.name, methodName);
+ expect(getter.variable, field);
+ expect(getter.functions, hasLength(0));
+ expect(getter.labels, hasLength(0));
+ expect(getter.localVariables, hasLength(0));
+ expect(getter.parameters, hasLength(0));
+ }
+
+ void test_visitMethodDeclaration_getter_abstract() {
+ // get m();
+ String methodName = "m";
+ MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
+ null,
+ null,
+ Keyword.GET,
+ null,
+ AstFactory.identifier3(methodName),
+ AstFactory.formalParameterList(),
+ AstFactory.emptyFunctionBody());
+
+ ElementHolder holder = buildElementsForAst(methodDeclaration);
+ List<FieldElement> fields = holder.fields;
+ expect(fields, hasLength(1));
+ FieldElement field = fields[0];
+ expect(field, isNotNull);
+ expect(field.name, methodName);
+ expect(field.isSynthetic, isTrue);
+ expect(field.setter, isNull);
+ PropertyAccessorElement getter = field.getter;
+ expect(getter, isNotNull);
+ expect(getter.hasImplicitReturnType, isTrue);
+ expect(getter.isAbstract, isTrue);
+ expect(getter.isExternal, isFalse);
+ expect(getter.isGetter, isTrue);
+ expect(getter.isSynthetic, isFalse);
+ expect(getter.name, methodName);
+ expect(getter.variable, field);
+ expect(getter.functions, hasLength(0));
+ expect(getter.labels, hasLength(0));
+ expect(getter.localVariables, hasLength(0));
+ expect(getter.parameters, hasLength(0));
+ }
+
+ void test_visitMethodDeclaration_getter_external() {
+ // external get m();
+ String methodName = "m";
+ MethodDeclaration methodDeclaration = AstFactory.methodDeclaration(
+ null,
+ null,
+ Keyword.GET,
+ null,
+ AstFactory.identifier3(methodName),
+ AstFactory.formalParameterList());
+ methodDeclaration.externalKeyword =
+ TokenFactory.tokenFromKeyword(Keyword.EXTERNAL);
+
+ ElementHolder holder = buildElementsForAst(methodDeclaration);
+ List<FieldElement> fields = holder.fields;
+ expect(fields, hasLength(1));
+ FieldElement field = fields[0];
+ expect(field, isNotNull);
+ expect(field.name, methodName);
+ expect(field.isSynthetic, isTrue);
+ expect(field.setter, isNull);
+ PropertyAccessorElement getter = field.getter;
+ expect(getter, isNotNull);
+ expect(getter.hasImplicitReturnType, isTrue);
+ expect(getter.isAbstract, isFalse);
+ expect(getter.isExternal, isTrue);
+ expect(getter.isGetter, isTrue);
+ expect(getter.isSynthetic, isFalse);
+ expect(getter.name, methodName);
+ expect(getter.variable, field);
+ expect(getter.functions, hasLength(0));
+ expect(getter.labels, hasLength(0));
+ expect(getter.localVariables, hasLength(0));
+ expect(getter.parameters, hasLength(0));
+ }
+
+ void test_visitMethodDeclaration_minimal() {
+ // T m() {}
+ String methodName = "m";
+ MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
+ null,
+ AstFactory.typeName4('T'),
+ null,
+ null,
+ AstFactory.identifier3(methodName),
+ AstFactory.formalParameterList(),
+ AstFactory.blockFunctionBody2());
+ methodDeclaration.documentationComment = AstFactory.documentationComment(
+ [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
+ methodDeclaration.endToken.offset = 80;
+
+ ElementHolder holder = buildElementsForAst(methodDeclaration);
+ List<MethodElement> methods = holder.methods;
+ expect(methods, hasLength(1));
+ MethodElement method = methods[0];
+ expect(method, isNotNull);
+ assertHasCodeRange(method, 50, 31);
+ expect(method.documentationComment, '/// aaa');
+ expect(method.hasImplicitReturnType, isFalse);
+ expect(method.name, methodName);
+ expect(method.functions, hasLength(0));
+ expect(method.labels, hasLength(0));
+ expect(method.localVariables, hasLength(0));
+ expect(method.parameters, hasLength(0));
+ expect(method.typeParameters, hasLength(0));
+ expect(method.isAbstract, isFalse);
+ expect(method.isExternal, isFalse);
+ expect(method.isStatic, isFalse);
+ expect(method.isSynthetic, isFalse);
+ }
+
+ void test_visitMethodDeclaration_operator() {
+ // operator +(addend) {}
+ String methodName = "+";
+ MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
+ null,
+ null,
+ null,
+ Keyword.OPERATOR,
+ AstFactory.identifier3(methodName),
+ AstFactory
+ .formalParameterList([AstFactory.simpleFormalParameter3("addend")]),
+ AstFactory.blockFunctionBody2());
+
+ ElementHolder holder = buildElementsForAst(methodDeclaration);
+ List<MethodElement> methods = holder.methods;
+ expect(methods, hasLength(1));
+ MethodElement method = methods[0];
+ expect(method, isNotNull);
+ expect(method.hasImplicitReturnType, isTrue);
+ expect(method.name, methodName);
+ expect(method.functions, hasLength(0));
+ expect(method.labels, hasLength(0));
+ expect(method.localVariables, hasLength(0));
+ expect(method.parameters, hasLength(1));
+ expect(method.typeParameters, hasLength(0));
+ expect(method.isAbstract, isFalse);
+ expect(method.isExternal, isFalse);
+ expect(method.isStatic, isFalse);
+ expect(method.isSynthetic, isFalse);
+ }
+
+ void test_visitMethodDeclaration_setter() {
+ // set m() {}
+ String methodName = "m";
+ MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
+ null,
+ null,
+ Keyword.SET,
+ null,
+ AstFactory.identifier3(methodName),
+ AstFactory.formalParameterList(),
+ AstFactory.blockFunctionBody2());
+ methodDeclaration.documentationComment = AstFactory.documentationComment(
+ [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
+ methodDeclaration.endToken.offset = 80;
+
+ ElementHolder holder = buildElementsForAst(methodDeclaration);
+ List<FieldElement> fields = holder.fields;
+ expect(fields, hasLength(1));
+ FieldElement field = fields[0];
+ expect(field, isNotNull);
+ expect(field.name, methodName);
+ expect(field.isSynthetic, isTrue);
+ expect(field.getter, isNull);
+
+ PropertyAccessorElement setter = field.setter;
+ expect(setter, isNotNull);
+ assertHasCodeRange(setter, 50, 31);
+ expect(setter.documentationComment, '/// aaa');
+ expect(setter.hasImplicitReturnType, isTrue);
+ expect(setter.isAbstract, isFalse);
+ expect(setter.isExternal, isFalse);
+ expect(setter.isSetter, isTrue);
+ expect(setter.isSynthetic, isFalse);
+ expect(setter.name, "$methodName=");
+ expect(setter.displayName, methodName);
+ expect(setter.variable, field);
+ expect(setter.functions, hasLength(0));
+ expect(setter.labels, hasLength(0));
+ expect(setter.localVariables, hasLength(0));
+ expect(setter.parameters, hasLength(0));
+ }
+
+ void test_visitMethodDeclaration_setter_abstract() {
+ // set m();
+ String methodName = "m";
+ MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
+ null,
+ null,
+ Keyword.SET,
+ null,
+ AstFactory.identifier3(methodName),
+ AstFactory.formalParameterList(),
+ AstFactory.emptyFunctionBody());
+
+ ElementHolder holder = buildElementsForAst(methodDeclaration);
+ List<FieldElement> fields = holder.fields;
+ expect(fields, hasLength(1));
+ FieldElement field = fields[0];
+ expect(field, isNotNull);
+ expect(field.name, methodName);
+ expect(field.isSynthetic, isTrue);
+ expect(field.getter, isNull);
+ PropertyAccessorElement setter = field.setter;
+ expect(setter, isNotNull);
+ expect(setter.hasImplicitReturnType, isTrue);
+ expect(setter.isAbstract, isTrue);
+ expect(setter.isExternal, isFalse);
+ expect(setter.isSetter, isTrue);
+ expect(setter.isSynthetic, isFalse);
+ expect(setter.name, "$methodName=");
+ expect(setter.displayName, methodName);
+ expect(setter.variable, field);
+ expect(setter.functions, hasLength(0));
+ expect(setter.labels, hasLength(0));
+ expect(setter.localVariables, hasLength(0));
+ expect(setter.parameters, hasLength(0));
+ }
+
+ void test_visitMethodDeclaration_setter_external() {
+ // external m();
+ String methodName = "m";
+ MethodDeclaration methodDeclaration = AstFactory.methodDeclaration(
+ null,
+ null,
+ Keyword.SET,
+ null,
+ AstFactory.identifier3(methodName),
+ AstFactory.formalParameterList());
+ methodDeclaration.externalKeyword =
+ TokenFactory.tokenFromKeyword(Keyword.EXTERNAL);
+
+ ElementHolder holder = buildElementsForAst(methodDeclaration);
+ List<FieldElement> fields = holder.fields;
+ expect(fields, hasLength(1));
+ FieldElement field = fields[0];
+ expect(field, isNotNull);
+ expect(field.name, methodName);
+ expect(field.isSynthetic, isTrue);
+ expect(field.getter, isNull);
+ PropertyAccessorElement setter = field.setter;
+ expect(setter, isNotNull);
+ expect(setter.hasImplicitReturnType, isTrue);
+ expect(setter.isAbstract, isFalse);
+ expect(setter.isExternal, isTrue);
+ expect(setter.isSetter, isTrue);
+ expect(setter.isSynthetic, isFalse);
+ expect(setter.name, "$methodName=");
+ expect(setter.displayName, methodName);
+ expect(setter.variable, field);
+ expect(setter.functions, hasLength(0));
+ expect(setter.labels, hasLength(0));
+ expect(setter.localVariables, hasLength(0));
+ expect(setter.parameters, hasLength(0));
+ }
+
+ void test_visitMethodDeclaration_static() {
+ // static m() {}
+ String methodName = "m";
+ MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
+ Keyword.STATIC,
+ null,
+ null,
+ null,
+ AstFactory.identifier3(methodName),
+ AstFactory.formalParameterList(),
+ AstFactory.blockFunctionBody2());
+ ElementHolder holder = buildElementsForAst(methodDeclaration);
+ List<MethodElement> methods = holder.methods;
+ expect(methods, hasLength(1));
+ MethodElement method = methods[0];
+ expect(method, isNotNull);
+ expect(method.hasImplicitReturnType, isTrue);
+ expect(method.name, methodName);
+ expect(method.functions, hasLength(0));
+ expect(method.labels, hasLength(0));
+ expect(method.localVariables, hasLength(0));
+ expect(method.parameters, hasLength(0));
+ expect(method.typeParameters, hasLength(0));
+ expect(method.isAbstract, isFalse);
+ expect(method.isExternal, isFalse);
+ expect(method.isStatic, isTrue);
+ expect(method.isSynthetic, isFalse);
+ }
+
+ void test_visitMethodDeclaration_typeParameters() {
+ // m<E>() {}
+ String methodName = "m";
+ MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
+ null,
+ null,
+ null,
+ null,
+ AstFactory.identifier3(methodName),
+ AstFactory.formalParameterList(),
+ AstFactory.blockFunctionBody2());
+ methodDeclaration.typeParameters = AstFactory.typeParameterList(['E']);
+
+ ElementHolder holder = buildElementsForAst(methodDeclaration);
+ List<MethodElement> methods = holder.methods;
+ expect(methods, hasLength(1));
+ MethodElement method = methods[0];
+ expect(method, isNotNull);
+ expect(method.hasImplicitReturnType, isTrue);
+ expect(method.name, methodName);
+ expect(method.functions, hasLength(0));
+ expect(method.labels, hasLength(0));
+ expect(method.localVariables, hasLength(0));
+ expect(method.parameters, hasLength(0));
+ expect(method.typeParameters, hasLength(1));
+ expect(method.isAbstract, isFalse);
+ expect(method.isExternal, isFalse);
+ expect(method.isStatic, isFalse);
+ expect(method.isSynthetic, isFalse);
+ }
+
+ void test_visitTypeAlias_minimal() {
+ String aliasName = "F";
+ TypeAlias typeAlias = AstFactory.typeAlias(null, aliasName, null, null);
+ ElementHolder holder = buildElementsForAst(typeAlias);
+ List<FunctionTypeAliasElement> aliases = holder.typeAliases;
+ expect(aliases, hasLength(1));
+ FunctionTypeAliasElement alias = aliases[0];
+ expect(alias, isNotNull);
+ expect(alias.name, aliasName);
+ expect(alias.type, isNotNull);
+ expect(alias.isSynthetic, isFalse);
+ }
+
+ void test_visitTypeAlias_withFormalParameters() {
+ String aliasName = "F";
+ String firstParameterName = "x";
+ String secondParameterName = "y";
+ TypeAlias typeAlias = AstFactory.typeAlias(
+ null,
+ aliasName,
+ AstFactory.typeParameterList(),
+ AstFactory.formalParameterList([
+ AstFactory.simpleFormalParameter3(firstParameterName),
+ AstFactory.simpleFormalParameter3(secondParameterName)
+ ]));
+ typeAlias.beginToken.offset = 50;
+ typeAlias.endToken.offset = 80;
+ ElementHolder holder = buildElementsForAst(typeAlias);
+ List<FunctionTypeAliasElement> aliases = holder.typeAliases;
+ expect(aliases, hasLength(1));
+ FunctionTypeAliasElement alias = aliases[0];
+ expect(alias, isNotNull);
+ assertHasCodeRange(alias, 50, 31);
+ expect(alias.name, aliasName);
+ expect(alias.type, isNotNull);
+ expect(alias.isSynthetic, isFalse);
+ List<VariableElement> parameters = alias.parameters;
+ expect(parameters, hasLength(2));
+ expect(parameters[0].name, firstParameterName);
+ expect(parameters[1].name, secondParameterName);
+ List<TypeParameterElement> typeParameters = alias.typeParameters;
+ expect(typeParameters, isNotNull);
+ expect(typeParameters, hasLength(0));
+ }
+
+ void test_visitTypeAlias_withTypeParameters() {
+ String aliasName = "F";
+ String firstTypeParameterName = "A";
+ String secondTypeParameterName = "B";
+ TypeAlias typeAlias = AstFactory.typeAlias(
+ null,
+ aliasName,
+ AstFactory.typeParameterList(
+ [firstTypeParameterName, secondTypeParameterName]),
+ AstFactory.formalParameterList());
+ ElementHolder holder = buildElementsForAst(typeAlias);
+ List<FunctionTypeAliasElement> aliases = holder.typeAliases;
+ expect(aliases, hasLength(1));
+ FunctionTypeAliasElement alias = aliases[0];
+ expect(alias, isNotNull);
+ expect(alias.name, aliasName);
+ expect(alias.type, isNotNull);
+ expect(alias.isSynthetic, isFalse);
+ List<VariableElement> parameters = alias.parameters;
+ expect(parameters, isNotNull);
+ expect(parameters, hasLength(0));
+ List<TypeParameterElement> typeParameters = alias.typeParameters;
+ expect(typeParameters, hasLength(2));
+ expect(typeParameters[0].name, firstTypeParameterName);
+ expect(typeParameters[1].name, secondTypeParameterName);
+ }
+
+ void test_visitTypeParameter() {
+ String parameterName = "E";
+ TypeParameter typeParameter = AstFactory.typeParameter(parameterName);
+ typeParameter.beginToken.offset = 50;
+ ElementHolder holder = buildElementsForAst(typeParameter);
+ List<TypeParameterElement> typeParameters = holder.typeParameters;
+ expect(typeParameters, hasLength(1));
+ TypeParameterElement typeParameterElement = typeParameters[0];
+ expect(typeParameterElement, isNotNull);
+ assertHasCodeRange(typeParameterElement, 50, 1);
+ expect(typeParameterElement.name, parameterName);
+ expect(typeParameterElement.bound, isNull);
+ expect(typeParameterElement.isSynthetic, isFalse);
+ }
+}
+
+abstract class _BaseTest {
+ CompilationUnitElement compilationUnitElement;
+ CompilationUnit _compilationUnit;
+
+ CompilationUnit get compilationUnit => _compilationUnit;
+
+ void assertHasCodeRange(Element element, int offset, int length) {
+ ElementImpl elementImpl = element;
+ expect(elementImpl.codeOffset, offset);
+ expect(elementImpl.codeLength, length);
+ }
+
+ /**
+ * Build elements using [ApiElementBuilder].
+ */
+ ElementHolder buildElementsForAst(AstNode node) {
+ ElementHolder holder = new ElementHolder();
+ AstVisitor builder = createElementBuilder(holder);
+ node.accept(builder);
+ return holder;
+ }
+
+ /**
+ * Parse the given [code], and build elements using [ApiElementBuilder].
+ */
+ ElementHolder buildElementsForText(String code) {
+ ElementHolder holder = new ElementHolder();
+ AstVisitor builder = createElementBuilder(holder);
+ _visitAstOfCode(code, builder);
+ return holder;
+ }
+
+ /**
+ * Verify that the given [metadata] has exactly one annotation, and that its
+ * [ElementAnnotationImpl] is unresolved.
+ */
+ void checkAnnotation(NodeList<Annotation> metadata) {
+ expect(metadata, hasLength(1));
+ expect(metadata[0], new isInstanceOf<AnnotationImpl>());
+ AnnotationImpl annotation = metadata[0];
+ expect(annotation.elementAnnotation,
+ new isInstanceOf<ElementAnnotationImpl>());
+ ElementAnnotationImpl elementAnnotation = annotation.elementAnnotation;
+ expect(elementAnnotation.element, isNull); // Not yet resolved
+ expect(elementAnnotation.compilationUnit, isNotNull);
+ expect(elementAnnotation.compilationUnit, compilationUnitElement);
+ }
+
+ /**
+ * Verify that the given [element] has exactly one annotation, and that its
+ * [ElementAnnotationImpl] is unresolved.
+ */
+ void checkMetadata(Element element) {
+ expect(element.metadata, hasLength(1));
+ expect(element.metadata[0], new isInstanceOf<ElementAnnotationImpl>());
+ ElementAnnotationImpl elementAnnotation = element.metadata[0];
+ expect(elementAnnotation.element, isNull); // Not yet resolved
+ expect(elementAnnotation.compilationUnit, isNotNull);
+ expect(elementAnnotation.compilationUnit, compilationUnitElement);
+ }
+
+ AstVisitor createElementBuilder(ElementHolder holder);
+
+ void setUp() {
+ compilationUnitElement = new CompilationUnitElementImpl('test.dart');
+ }
+
+ void _assertVisibleRange(LocalElement element, int offset, int end) {
+ SourceRange visibleRange = element.visibleRange;
+ expect(visibleRange.offset, offset);
+ expect(visibleRange.end, end);
+ }
+
+ /**
+ * Parse the given [code], and visit it with the given [visitor].
+ * Fail if any error is logged.
+ */
+ void _visitAstOfCode(String code, AstVisitor visitor) {
+ TestLogger logger = new TestLogger();
+ AnalysisEngine.instance.logger = logger;
+ try {
+ _compilationUnit = ParserTestCase.parseCompilationUnit(code);
+ compilationUnit.accept(visitor);
+ } finally {
+ expect(logger.log, hasLength(0));
+ AnalysisEngine.instance.logger = Logger.NULL;
+ }
+ }
+}
diff --git a/pkg/analyzer/test/dart/element/test_all.dart b/pkg/analyzer/test/dart/element/test_all.dart
index bb4c779..d0e4cea 100644
--- a/pkg/analyzer/test/dart/element/test_all.dart
+++ b/pkg/analyzer/test/dart/element/test_all.dart
@@ -6,11 +6,13 @@
import 'package:test_reflective_loader/test_reflective_loader.dart';
+import 'builder_test.dart' as builder;
import 'element_test.dart' as element;
/// Utility for manually running all tests.
main() {
defineReflectiveSuite(() {
+ builder.main();
element.main();
}, name: 'element');
}
diff --git a/pkg/analyzer/test/generated/all_the_rest_test.dart b/pkg/analyzer/test/generated/all_the_rest_test.dart
index 7ba7573..127ce4e 100644
--- a/pkg/analyzer/test/generated/all_the_rest_test.dart
+++ b/pkg/analyzer/test/generated/all_the_rest_test.dart
@@ -13,7 +13,6 @@
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/file_system/memory_file_system.dart';
import 'package:analyzer/file_system/physical_file_system.dart';
-import 'package:analyzer/src/dart/ast/ast.dart';
import 'package:analyzer/src/dart/ast/utilities.dart' hide ConstantEvaluator;
import 'package:analyzer/src/dart/element/builder.dart';
import 'package:analyzer/src/dart/element/element.dart';
@@ -52,7 +51,6 @@
defineReflectiveTests(DirectoryBasedDartSdkTest);
// ignore: deprecated_member_use
defineReflectiveTests(DirectoryBasedSourceContainerTest);
- defineReflectiveTests(ElementBuilderTest);
defineReflectiveTests(ElementLocatorTest);
defineReflectiveTests(EnumMemberBuilderTest);
defineReflectiveTests(ErrorReporterTest);
@@ -352,2260 +350,6 @@
}
@reflectiveTest
-class ElementBuilderTest extends ParserTestCase {
- CompilationUnitElement compilationUnitElement;
- CompilationUnit compilationUnit;
-
- /**
- * Parse the given [code], pass it through [ElementBuilder], and return the
- * resulting [ElementHolder].
- */
- ElementHolder buildElementsForText(String code) {
- TestLogger logger = new TestLogger();
- AnalysisEngine.instance.logger = logger;
- try {
- compilationUnit = ParserTestCase.parseCompilationUnit(code);
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder =
- new ElementBuilder(holder, compilationUnitElement);
- compilationUnit.accept(builder);
- return holder;
- } finally {
- expect(logger.log, hasLength(0));
- AnalysisEngine.instance.logger = Logger.NULL;
- }
- }
-
- /**
- * Verify that the given [metadata] has exactly one annotation, and that its
- * [ElementAnnotationImpl] is unresolved.
- */
- void checkAnnotation(NodeList<Annotation> metadata) {
- expect(metadata, hasLength(1));
- expect(metadata[0], new isInstanceOf<AnnotationImpl>());
- AnnotationImpl annotation = metadata[0];
- expect(annotation.elementAnnotation,
- new isInstanceOf<ElementAnnotationImpl>());
- ElementAnnotationImpl elementAnnotation = annotation.elementAnnotation;
- expect(elementAnnotation.element, isNull); // Not yet resolved
- expect(elementAnnotation.compilationUnit, isNotNull);
- expect(elementAnnotation.compilationUnit, compilationUnitElement);
- }
-
- /**
- * Verify that the given [element] has exactly one annotation, and that its
- * [ElementAnnotationImpl] is unresolved.
- */
- void checkMetadata(Element element) {
- expect(element.metadata, hasLength(1));
- expect(element.metadata[0], new isInstanceOf<ElementAnnotationImpl>());
- ElementAnnotationImpl elementAnnotation = element.metadata[0];
- expect(elementAnnotation.element, isNull); // Not yet resolved
- expect(elementAnnotation.compilationUnit, isNotNull);
- expect(elementAnnotation.compilationUnit, compilationUnitElement);
- }
-
- void fail_visitMethodDeclaration_setter_duplicate() {
- // https://github.com/dart-lang/sdk/issues/25601
- String code = r'''
-class C {
- set zzz(x) {}
- set zzz(y) {}
-}
-''';
- ClassElement classElement = buildElementsForText(code).types[0];
- for (PropertyAccessorElement accessor in classElement.accessors) {
- expect(accessor.variable.setter, same(accessor));
- }
- }
-
- @override
- void setUp() {
- super.setUp();
- compilationUnitElement = new CompilationUnitElementImpl('test.dart');
- }
-
- void test_metadata_fieldDeclaration() {
- List<FieldElement> fields =
- buildElementsForText('class C { @a int x, y; }').types[0].fields;
- checkMetadata(fields[0]);
- checkMetadata(fields[1]);
- expect(fields[0].metadata, same(fields[1].metadata));
- }
-
- void test_metadata_localVariableDeclaration() {
- List<LocalVariableElement> localVariables =
- buildElementsForText('f() { @a int x, y; }')
- .functions[0]
- .localVariables;
- checkMetadata(localVariables[0]);
- checkMetadata(localVariables[1]);
- expect(localVariables[0].metadata, same(localVariables[1].metadata));
- }
-
- void test_metadata_topLevelVariableDeclaration() {
- List<TopLevelVariableElement> topLevelVariables =
- buildElementsForText('@a int x, y;').topLevelVariables;
- checkMetadata(topLevelVariables[0]);
- checkMetadata(topLevelVariables[1]);
- expect(topLevelVariables[0].metadata, same(topLevelVariables[1].metadata));
- }
-
- void test_metadata_visitClassDeclaration() {
- ClassElement classElement = buildElementsForText('@a class C {}').types[0];
- checkMetadata(classElement);
- }
-
- void test_metadata_visitClassTypeAlias() {
- ClassElement classElement =
- buildElementsForText('@a class C = D with E;').types[0];
- checkMetadata(classElement);
- }
-
- void test_metadata_visitConstructorDeclaration() {
- ConstructorElement constructorElement =
- buildElementsForText('class C { @a C(); }').types[0].constructors[0];
- checkMetadata(constructorElement);
- }
-
- void test_metadata_visitDeclaredIdentifier() {
- LocalVariableElement localVariableElement =
- buildElementsForText('f() { for (@a var x in y) {} }')
- .functions[0]
- .localVariables[0];
- checkMetadata(localVariableElement);
- }
-
- void test_metadata_visitDefaultFormalParameter_fieldFormalParameter() {
- ParameterElement parameterElement =
- buildElementsForText('class C { var x; C([@a this.x = null]); }')
- .types[0]
- .constructors[0]
- .parameters[0];
- checkMetadata(parameterElement);
- }
-
- void
- test_metadata_visitDefaultFormalParameter_functionTypedFormalParameter() {
- ParameterElement parameterElement =
- buildElementsForText('f([@a g() = null]) {}').functions[0].parameters[
- 0];
- checkMetadata(parameterElement);
- }
-
- void test_metadata_visitDefaultFormalParameter_simpleFormalParameter() {
- ParameterElement parameterElement =
- buildElementsForText('f([@a gx = null]) {}').functions[0].parameters[0];
- checkMetadata(parameterElement);
- }
-
- void test_metadata_visitEnumDeclaration() {
- ClassElement classElement =
- buildElementsForText('@a enum E { v }').enums[0];
- checkMetadata(classElement);
- }
-
- void test_metadata_visitExportDirective() {
- buildElementsForText('@a export "foo.dart";');
- expect(compilationUnit.directives[0], new isInstanceOf<ExportDirective>());
- ExportDirective exportDirective = compilationUnit.directives[0];
- checkAnnotation(exportDirective.metadata);
- }
-
- void test_metadata_visitFieldFormalParameter() {
- ParameterElement parameterElement =
- buildElementsForText('class C { var x; C(@a this.x); }')
- .types[0]
- .constructors[0]
- .parameters[0];
- checkMetadata(parameterElement);
- }
-
- void test_metadata_visitFunctionDeclaration_function() {
- FunctionElement functionElement =
- buildElementsForText('@a f() {}').functions[0];
- checkMetadata(functionElement);
- }
-
- void test_metadata_visitFunctionDeclaration_getter() {
- PropertyAccessorElement propertyAccessorElement =
- buildElementsForText('@a get f => null;').accessors[0];
- checkMetadata(propertyAccessorElement);
- }
-
- void test_metadata_visitFunctionDeclaration_setter() {
- PropertyAccessorElement propertyAccessorElement =
- buildElementsForText('@a set f(value) {}').accessors[0];
- checkMetadata(propertyAccessorElement);
- }
-
- void test_metadata_visitFunctionTypeAlias() {
- FunctionTypeAliasElement functionTypeAliasElement =
- buildElementsForText('@a typedef F();').typeAliases[0];
- checkMetadata(functionTypeAliasElement);
- }
-
- void test_metadata_visitFunctionTypedFormalParameter() {
- ParameterElement parameterElement =
- buildElementsForText('f(@a g()) {}').functions[0].parameters[0];
- checkMetadata(parameterElement);
- }
-
- void test_metadata_visitImportDirective() {
- buildElementsForText('@a import "foo.dart";');
- expect(compilationUnit.directives[0], new isInstanceOf<ImportDirective>());
- ImportDirective importDirective = compilationUnit.directives[0];
- checkAnnotation(importDirective.metadata);
- }
-
- void test_metadata_visitLibraryDirective() {
- buildElementsForText('@a library L;');
- expect(compilationUnit.directives[0], new isInstanceOf<LibraryDirective>());
- LibraryDirective libraryDirective = compilationUnit.directives[0];
- checkAnnotation(libraryDirective.metadata);
- }
-
- void test_metadata_visitMethodDeclaration_getter() {
- PropertyAccessorElement propertyAccessorElement =
- buildElementsForText('class C { @a get m => null; }')
- .types[0]
- .accessors[0];
- checkMetadata(propertyAccessorElement);
- }
-
- void test_metadata_visitMethodDeclaration_method() {
- MethodElement methodElement =
- buildElementsForText('class C { @a m() {} }').types[0].methods[0];
- checkMetadata(methodElement);
- }
-
- void test_metadata_visitMethodDeclaration_setter() {
- PropertyAccessorElement propertyAccessorElement =
- buildElementsForText('class C { @a set f(value) {} }')
- .types[0]
- .accessors[0];
- checkMetadata(propertyAccessorElement);
- }
-
- void test_metadata_visitPartDirective() {
- buildElementsForText('@a part "foo.dart";');
- expect(compilationUnit.directives[0], new isInstanceOf<PartDirective>());
- PartDirective partDirective = compilationUnit.directives[0];
- checkAnnotation(partDirective.metadata);
- }
-
- void test_metadata_visitPartOfDirective() {
- // We don't build ElementAnnotation objects for `part of` directives, since
- // analyzer ignores them in favor of annotations on the library directive.
- buildElementsForText('@a part of L;');
- expect(compilationUnit.directives[0], new isInstanceOf<PartOfDirective>());
- PartOfDirective partOfDirective = compilationUnit.directives[0];
- expect(partOfDirective.metadata, hasLength(1));
- expect(partOfDirective.metadata[0].elementAnnotation, isNull);
- }
-
- void test_metadata_visitSimpleFormalParameter() {
- ParameterElement parameterElement =
- buildElementsForText('f(@a x) {}').functions[0].parameters[0];
- checkMetadata(parameterElement);
- }
-
- void test_metadata_visitTypeParameter() {
- TypeParameterElement typeParameterElement =
- buildElementsForText('class C<@a T> {}').types[0].typeParameters[0];
- checkMetadata(typeParameterElement);
- }
-
- void test_visitCatchClause() {
- // } catch (e, s) {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String exceptionParameterName = "e";
- String stackParameterName = "s";
- CatchClause clause =
- AstFactory.catchClause2(exceptionParameterName, stackParameterName);
- _setNodeSourceRange(clause, 100, 110);
- clause.accept(builder);
-
- List<LocalVariableElement> variables = holder.localVariables;
- expect(variables, hasLength(2));
-
- LocalVariableElement exceptionVariable = variables[0];
- expect(exceptionVariable, isNotNull);
- expect(exceptionVariable.name, exceptionParameterName);
- expect(exceptionVariable.hasImplicitType, isTrue);
- expect(exceptionVariable.isSynthetic, isFalse);
- expect(exceptionVariable.isConst, isFalse);
- expect(exceptionVariable.isFinal, isFalse);
- expect(exceptionVariable.initializer, isNull);
- _assertVisibleRange(exceptionVariable, 100, 110);
-
- LocalVariableElement stackVariable = variables[1];
- expect(stackVariable, isNotNull);
- expect(stackVariable.name, stackParameterName);
- expect(stackVariable.isSynthetic, isFalse);
- expect(stackVariable.isConst, isFalse);
- expect(stackVariable.isFinal, isFalse);
- expect(stackVariable.initializer, isNull);
- _assertVisibleRange(stackVariable, 100, 110);
- }
-
- void test_visitCatchClause_withType() {
- // } on E catch (e) {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String exceptionParameterName = "e";
- CatchClause clause = AstFactory.catchClause4(
- AstFactory.typeName4('E'), exceptionParameterName);
- clause.accept(builder);
-
- List<LocalVariableElement> variables = holder.localVariables;
- expect(variables, hasLength(1));
- VariableElement exceptionVariable = variables[0];
- expect(exceptionVariable, isNotNull);
- expect(exceptionVariable.name, exceptionParameterName);
- expect(exceptionVariable.hasImplicitType, isFalse);
- }
-
- void test_visitClassDeclaration_abstract() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String className = "C";
- ClassDeclaration classDeclaration = AstFactory.classDeclaration(
- Keyword.ABSTRACT, className, null, null, null, null);
- classDeclaration.accept(builder);
- List<ClassElement> types = holder.types;
- expect(types, hasLength(1));
- ClassElement type = types[0];
- expect(type, isNotNull);
- expect(type.name, className);
- List<TypeParameterElement> typeParameters = type.typeParameters;
- expect(typeParameters, hasLength(0));
- expect(type.isAbstract, isTrue);
- expect(type.isMixinApplication, isFalse);
- expect(type.isSynthetic, isFalse);
- }
-
- void test_visitClassDeclaration_invalidFunctionInAnnotation_class() {
- // https://github.com/dart-lang/sdk/issues/25696
- String code = r'''
-class A {
- const A({f});
-}
-
-@A(f: () {})
-class C {}
-''';
- buildElementsForText(code);
- }
-
- void test_visitClassDeclaration_invalidFunctionInAnnotation_method() {
- String code = r'''
-class A {
- const A({f});
-}
-
-class C {
- @A(f: () {})
- void m() {}
-}
-''';
- ElementHolder holder = buildElementsForText(code);
- ClassElement elementC = holder.types[1];
- expect(elementC, isNotNull);
- MethodElement methodM = elementC.methods[0];
- expect(methodM, isNotNull);
- expect(methodM.functions, isEmpty);
- }
-
- void test_visitClassDeclaration_minimal() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String className = "C";
- ClassDeclaration classDeclaration =
- AstFactory.classDeclaration(null, className, null, null, null, null);
- classDeclaration.documentationComment = AstFactory.documentationComment(
- [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
- classDeclaration.endToken.offset = 80;
- classDeclaration.accept(builder);
- List<ClassElement> types = holder.types;
- expect(types, hasLength(1));
- ClassElement type = types[0];
- expect(type, isNotNull);
- expect(type.name, className);
- List<TypeParameterElement> typeParameters = type.typeParameters;
- expect(typeParameters, hasLength(0));
- expect(type.isAbstract, isFalse);
- expect(type.isMixinApplication, isFalse);
- expect(type.isSynthetic, isFalse);
- expect(type.documentationComment, '/// aaa');
- _assertHasCodeRange(type, 50, 31);
- }
-
- void test_visitClassDeclaration_parameterized() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String className = "C";
- String firstVariableName = "E";
- String secondVariableName = "F";
- ClassDeclaration classDeclaration = AstFactory.classDeclaration(
- null,
- className,
- AstFactory.typeParameterList([firstVariableName, secondVariableName]),
- null,
- null,
- null);
- classDeclaration.accept(builder);
- List<ClassElement> types = holder.types;
- expect(types, hasLength(1));
- ClassElement type = types[0];
- expect(type, isNotNull);
- expect(type.name, className);
- List<TypeParameterElement> typeParameters = type.typeParameters;
- expect(typeParameters, hasLength(2));
- expect(typeParameters[0].name, firstVariableName);
- expect(typeParameters[1].name, secondVariableName);
- expect(type.isAbstract, isFalse);
- expect(type.isMixinApplication, isFalse);
- expect(type.isSynthetic, isFalse);
- }
-
- void test_visitClassDeclaration_withMembers() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String className = "C";
- String typeParameterName = "E";
- String fieldName = "f";
- String methodName = "m";
- ClassDeclaration classDeclaration = AstFactory.classDeclaration(
- null,
- className,
- AstFactory.typeParameterList([typeParameterName]),
- null,
- null,
- null, [
- AstFactory.fieldDeclaration2(
- false, null, [AstFactory.variableDeclaration(fieldName)]),
- AstFactory.methodDeclaration2(
- null,
- null,
- null,
- null,
- AstFactory.identifier3(methodName),
- AstFactory.formalParameterList(),
- AstFactory.blockFunctionBody2())
- ]);
- classDeclaration.accept(builder);
- List<ClassElement> types = holder.types;
- expect(types, hasLength(1));
- ClassElement type = types[0];
- expect(type, isNotNull);
- expect(type.name, className);
- expect(type.isAbstract, isFalse);
- expect(type.isMixinApplication, isFalse);
- expect(type.isSynthetic, isFalse);
- List<TypeParameterElement> typeParameters = type.typeParameters;
- expect(typeParameters, hasLength(1));
- TypeParameterElement typeParameter = typeParameters[0];
- expect(typeParameter, isNotNull);
- expect(typeParameter.name, typeParameterName);
- List<FieldElement> fields = type.fields;
- expect(fields, hasLength(1));
- FieldElement field = fields[0];
- expect(field, isNotNull);
- expect(field.name, fieldName);
- List<MethodElement> methods = type.methods;
- expect(methods, hasLength(1));
- MethodElement method = methods[0];
- expect(method, isNotNull);
- expect(method.name, methodName);
- }
-
- void test_visitClassTypeAlias() {
- // class B {}
- // class M {}
- // class C = B with M
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- ClassElementImpl classB = ElementFactory.classElement2('B', []);
- ConstructorElementImpl constructorB =
- ElementFactory.constructorElement2(classB, '', []);
- constructorB.setModifier(Modifier.SYNTHETIC, true);
- classB.constructors = [constructorB];
- ClassElement classM = ElementFactory.classElement2('M', []);
- WithClause withClause =
- AstFactory.withClause([AstFactory.typeName(classM, [])]);
- ClassTypeAlias alias = AstFactory.classTypeAlias(
- 'C', null, null, AstFactory.typeName(classB, []), withClause, null);
- alias.accept(builder);
- List<ClassElement> types = holder.types;
- expect(types, hasLength(1));
- ClassElement type = types[0];
- expect(alias.element, same(type));
- expect(type.name, equals('C'));
- expect(type.isAbstract, isFalse);
- expect(type.isMixinApplication, isTrue);
- expect(type.isSynthetic, isFalse);
- expect(type.typeParameters, isEmpty);
- expect(type.fields, isEmpty);
- expect(type.methods, isEmpty);
- }
-
- void test_visitClassTypeAlias_abstract() {
- // class B {}
- // class M {}
- // abstract class C = B with M
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- ClassElementImpl classB = ElementFactory.classElement2('B', []);
- ConstructorElementImpl constructorB =
- ElementFactory.constructorElement2(classB, '', []);
- constructorB.setModifier(Modifier.SYNTHETIC, true);
- classB.constructors = [constructorB];
- ClassElement classM = ElementFactory.classElement2('M', []);
- WithClause withClause =
- AstFactory.withClause([AstFactory.typeName(classM, [])]);
- ClassTypeAlias classCAst = AstFactory.classTypeAlias('C', null,
- Keyword.ABSTRACT, AstFactory.typeName(classB, []), withClause, null);
- classCAst.accept(builder);
- List<ClassElement> types = holder.types;
- expect(types, hasLength(1));
- ClassElement type = types[0];
- expect(type.isAbstract, isTrue);
- expect(type.isMixinApplication, isTrue);
- }
-
- void test_visitClassTypeAlias_typeParams() {
- // class B {}
- // class M {}
- // class C<T> = B with M
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- ClassElementImpl classB = ElementFactory.classElement2('B', []);
- ConstructorElementImpl constructorB =
- ElementFactory.constructorElement2(classB, '', []);
- constructorB.setModifier(Modifier.SYNTHETIC, true);
- classB.constructors = [constructorB];
- ClassElementImpl classM = ElementFactory.classElement2('M', []);
- WithClause withClause =
- AstFactory.withClause([AstFactory.typeName(classM, [])]);
- ClassTypeAlias classCAst = AstFactory.classTypeAlias(
- 'C',
- AstFactory.typeParameterList(['T']),
- null,
- AstFactory.typeName(classB, []),
- withClause,
- null);
- classCAst.accept(builder);
- List<ClassElement> types = holder.types;
- expect(types, hasLength(1));
- ClassElement type = types[0];
- expect(type.typeParameters, hasLength(1));
- expect(type.typeParameters[0].name, equals('T'));
- }
-
- void test_visitCompilationUnit_codeRange() {
- TopLevelVariableDeclaration topLevelVariableDeclaration = AstFactory
- .topLevelVariableDeclaration(null, AstFactory.typeName4('int'),
- [AstFactory.variableDeclaration('V')]);
- CompilationUnit unit = new CompilationUnit(
- topLevelVariableDeclaration.beginToken,
- null,
- [],
- [topLevelVariableDeclaration],
- topLevelVariableDeclaration.endToken);
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- unit.beginToken.offset = 10;
- unit.endToken.offset = 40;
- unit.accept(builder);
-
- CompilationUnitElement element = builder.compilationUnitElement;
- _assertHasCodeRange(element, 0, 41);
- }
-
- void test_visitConstructorDeclaration_external() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String className = "A";
- ConstructorDeclaration constructorDeclaration =
- AstFactory.constructorDeclaration2(
- null,
- null,
- AstFactory.identifier3(className),
- null,
- AstFactory.formalParameterList(),
- null,
- AstFactory.blockFunctionBody2());
- constructorDeclaration.externalKeyword =
- TokenFactory.tokenFromKeyword(Keyword.EXTERNAL);
- constructorDeclaration.accept(builder);
- List<ConstructorElement> constructors = holder.constructors;
- expect(constructors, hasLength(1));
- ConstructorElement constructor = constructors[0];
- expect(constructor, isNotNull);
- expect(constructor.isExternal, isTrue);
- expect(constructor.isFactory, isFalse);
- expect(constructor.name, "");
- expect(constructor.functions, hasLength(0));
- expect(constructor.labels, hasLength(0));
- expect(constructor.localVariables, hasLength(0));
- expect(constructor.parameters, hasLength(0));
- }
-
- void test_visitConstructorDeclaration_factory() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String className = "A";
- ConstructorDeclaration constructorDeclaration =
- AstFactory.constructorDeclaration2(
- null,
- Keyword.FACTORY,
- AstFactory.identifier3(className),
- null,
- AstFactory.formalParameterList(),
- null,
- AstFactory.blockFunctionBody2());
- constructorDeclaration.accept(builder);
- List<ConstructorElement> constructors = holder.constructors;
- expect(constructors, hasLength(1));
- ConstructorElement constructor = constructors[0];
- expect(constructor, isNotNull);
- expect(constructor.isExternal, isFalse);
- expect(constructor.isFactory, isTrue);
- expect(constructor.name, "");
- expect(constructor.functions, hasLength(0));
- expect(constructor.labels, hasLength(0));
- expect(constructor.localVariables, hasLength(0));
- expect(constructor.parameters, hasLength(0));
- }
-
- void test_visitConstructorDeclaration_minimal() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String className = "A";
- ConstructorDeclaration constructorDeclaration =
- AstFactory.constructorDeclaration2(
- null,
- null,
- AstFactory.identifier3(className),
- null,
- AstFactory.formalParameterList(),
- null,
- AstFactory.blockFunctionBody2());
- constructorDeclaration.documentationComment = AstFactory
- .documentationComment(
- [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
- constructorDeclaration.endToken.offset = 80;
- constructorDeclaration.accept(builder);
-
- List<ConstructorElement> constructors = holder.constructors;
- expect(constructors, hasLength(1));
- ConstructorElement constructor = constructors[0];
- expect(constructor, isNotNull);
- _assertHasCodeRange(constructor, 50, 31);
- expect(constructor.documentationComment, '/// aaa');
- expect(constructor.isExternal, isFalse);
- expect(constructor.isFactory, isFalse);
- expect(constructor.name, "");
- expect(constructor.functions, hasLength(0));
- expect(constructor.labels, hasLength(0));
- expect(constructor.localVariables, hasLength(0));
- expect(constructor.parameters, hasLength(0));
- }
-
- void test_visitConstructorDeclaration_named() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String className = "A";
- String constructorName = "c";
- ConstructorDeclaration constructorDeclaration =
- AstFactory.constructorDeclaration2(
- null,
- null,
- AstFactory.identifier3(className),
- constructorName,
- AstFactory.formalParameterList(),
- null,
- AstFactory.blockFunctionBody2());
- constructorDeclaration.accept(builder);
- List<ConstructorElement> constructors = holder.constructors;
- expect(constructors, hasLength(1));
- ConstructorElement constructor = constructors[0];
- expect(constructor, isNotNull);
- expect(constructor.isExternal, isFalse);
- expect(constructor.isFactory, isFalse);
- expect(constructor.name, constructorName);
- expect(constructor.functions, hasLength(0));
- expect(constructor.labels, hasLength(0));
- expect(constructor.localVariables, hasLength(0));
- expect(constructor.parameters, hasLength(0));
- expect(constructorDeclaration.name.staticElement, same(constructor));
- expect(constructorDeclaration.element, same(constructor));
- }
-
- void test_visitConstructorDeclaration_unnamed() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String className = "A";
- ConstructorDeclaration constructorDeclaration =
- AstFactory.constructorDeclaration2(
- null,
- null,
- AstFactory.identifier3(className),
- null,
- AstFactory.formalParameterList(),
- null,
- AstFactory.blockFunctionBody2());
- constructorDeclaration.accept(builder);
- List<ConstructorElement> constructors = holder.constructors;
- expect(constructors, hasLength(1));
- ConstructorElement constructor = constructors[0];
- expect(constructor, isNotNull);
- expect(constructor.isExternal, isFalse);
- expect(constructor.isFactory, isFalse);
- expect(constructor.name, "");
- expect(constructor.functions, hasLength(0));
- expect(constructor.labels, hasLength(0));
- expect(constructor.localVariables, hasLength(0));
- expect(constructor.parameters, hasLength(0));
- expect(constructorDeclaration.element, same(constructor));
- }
-
- void test_visitDeclaredIdentifier_noType() {
- // var i
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- var variableName = 'i';
- DeclaredIdentifier identifier =
- AstFactory.declaredIdentifier3(variableName);
- AstFactory.forEachStatement(
- identifier, AstFactory.nullLiteral(), AstFactory.emptyStatement());
- identifier.beginToken.offset = 50;
- identifier.endToken.offset = 80;
- identifier.accept(builder);
-
- List<LocalVariableElement> variables = holder.localVariables;
- expect(variables, hasLength(1));
- LocalVariableElement variable = variables[0];
- _assertHasCodeRange(variable, 50, 31);
- expect(variable, isNotNull);
- expect(variable.hasImplicitType, isTrue);
- expect(variable.isConst, isFalse);
- expect(variable.isDeprecated, isFalse);
- expect(variable.isFinal, isFalse);
- expect(variable.isOverride, isFalse);
- expect(variable.isPrivate, isFalse);
- expect(variable.isPublic, isTrue);
- expect(variable.isSynthetic, isFalse);
- expect(variable.name, variableName);
- }
-
- void test_visitDeclaredIdentifier_type() {
- // E i
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- var variableName = 'i';
- DeclaredIdentifier identifier =
- AstFactory.declaredIdentifier4(AstFactory.typeName4('E'), variableName);
- AstFactory.forEachStatement(
- identifier, AstFactory.nullLiteral(), AstFactory.emptyStatement());
- identifier.beginToken.offset = 50;
- identifier.endToken.offset = 80;
- identifier.accept(builder);
-
- List<LocalVariableElement> variables = holder.localVariables;
- expect(variables, hasLength(1));
- LocalVariableElement variable = variables[0];
- expect(variable, isNotNull);
- _assertHasCodeRange(variable, 50, 31);
- expect(variable.hasImplicitType, isFalse);
- expect(variable.isConst, isFalse);
- expect(variable.isDeprecated, isFalse);
- expect(variable.isFinal, isFalse);
- expect(variable.isOverride, isFalse);
- expect(variable.isPrivate, isFalse);
- expect(variable.isPublic, isTrue);
- expect(variable.isSynthetic, isFalse);
- expect(variable.name, variableName);
- }
-
- void test_visitDefaultFormalParameter_noType() {
- // p = 0
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String parameterName = 'p';
- DefaultFormalParameter formalParameter =
- AstFactory.positionalFormalParameter(
- AstFactory.simpleFormalParameter3(parameterName),
- AstFactory.integer(0));
- formalParameter.beginToken.offset = 50;
- formalParameter.endToken.offset = 80;
- formalParameter.accept(builder);
-
- List<ParameterElement> parameters = holder.parameters;
- expect(parameters, hasLength(1));
- ParameterElement parameter = parameters[0];
- _assertHasCodeRange(parameter, 50, 31);
- expect(parameter.hasImplicitType, isTrue);
- expect(parameter.initializer, isNotNull);
- expect(parameter.initializer.type, isNotNull);
- expect(parameter.initializer.hasImplicitReturnType, isTrue);
- expect(parameter.isConst, isFalse);
- expect(parameter.isDeprecated, isFalse);
- expect(parameter.isFinal, isFalse);
- expect(parameter.isInitializingFormal, isFalse);
- expect(parameter.isOverride, isFalse);
- expect(parameter.isPrivate, isFalse);
- expect(parameter.isPublic, isTrue);
- expect(parameter.isSynthetic, isFalse);
- expect(parameter.name, parameterName);
- }
-
- void test_visitDefaultFormalParameter_type() {
- // E p = 0
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String parameterName = 'p';
- DefaultFormalParameter formalParameter = AstFactory.namedFormalParameter(
- AstFactory.simpleFormalParameter4(
- AstFactory.typeName4('E'), parameterName),
- AstFactory.integer(0));
- formalParameter.accept(builder);
-
- List<ParameterElement> parameters = holder.parameters;
- expect(parameters, hasLength(1));
- ParameterElement parameter = parameters[0];
- expect(parameter.hasImplicitType, isFalse);
- expect(parameter.initializer, isNotNull);
- expect(parameter.initializer.type, isNotNull);
- expect(parameter.initializer.hasImplicitReturnType, isTrue);
- expect(parameter.isConst, isFalse);
- expect(parameter.isDeprecated, isFalse);
- expect(parameter.isFinal, isFalse);
- expect(parameter.isInitializingFormal, isFalse);
- expect(parameter.isOverride, isFalse);
- expect(parameter.isPrivate, isFalse);
- expect(parameter.isPublic, isTrue);
- expect(parameter.isSynthetic, isFalse);
- expect(parameter.name, parameterName);
- }
-
- void test_visitEnumDeclaration() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String enumName = "E";
- EnumDeclaration enumDeclaration =
- AstFactory.enumDeclaration2(enumName, ["ONE"]);
- enumDeclaration.documentationComment = AstFactory.documentationComment(
- [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
- enumDeclaration.endToken.offset = 80;
- enumDeclaration.accept(builder);
- List<ClassElement> enums = holder.enums;
- expect(enums, hasLength(1));
- ClassElement enumElement = enums[0];
- expect(enumElement, isNotNull);
- _assertHasCodeRange(enumElement, 50, 31);
- expect(enumElement.documentationComment, '/// aaa');
- expect(enumElement.name, enumName);
- }
-
- void test_visitFieldDeclaration() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String firstFieldName = "x";
- String secondFieldName = "y";
- FieldDeclaration fieldDeclaration =
- AstFactory.fieldDeclaration2(false, null, [
- AstFactory.variableDeclaration(firstFieldName),
- AstFactory.variableDeclaration(secondFieldName)
- ]);
- fieldDeclaration.documentationComment = AstFactory.documentationComment(
- [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
- fieldDeclaration.endToken.offset = 110;
- fieldDeclaration.accept(builder);
-
- List<FieldElement> fields = holder.fields;
- expect(fields, hasLength(2));
-
- FieldElement firstField = fields[0];
- expect(firstField, isNotNull);
- _assertHasCodeRange(firstField, 50, 61);
- expect(firstField.documentationComment, '/// aaa');
- expect(firstField.name, firstFieldName);
- expect(firstField.initializer, isNull);
- expect(firstField.isConst, isFalse);
- expect(firstField.isFinal, isFalse);
- expect(firstField.isSynthetic, isFalse);
-
- FieldElement secondField = fields[1];
- expect(secondField, isNotNull);
- _assertHasCodeRange(secondField, 50, 61);
- expect(secondField.documentationComment, '/// aaa');
- expect(secondField.name, secondFieldName);
- expect(secondField.initializer, isNull);
- expect(secondField.isConst, isFalse);
- expect(secondField.isFinal, isFalse);
- expect(secondField.isSynthetic, isFalse);
- }
-
- void test_visitFieldFormalParameter() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String parameterName = "p";
- FieldFormalParameter formalParameter =
- AstFactory.fieldFormalParameter(null, null, parameterName);
- formalParameter.beginToken.offset = 50;
- formalParameter.endToken.offset = 80;
- formalParameter.accept(builder);
- List<ParameterElement> parameters = holder.parameters;
- expect(parameters, hasLength(1));
- ParameterElement parameter = parameters[0];
- expect(parameter, isNotNull);
- _assertHasCodeRange(parameter, 50, 31);
- expect(parameter.name, parameterName);
- expect(parameter.initializer, isNull);
- expect(parameter.isConst, isFalse);
- expect(parameter.isFinal, isFalse);
- expect(parameter.isSynthetic, isFalse);
- expect(parameter.parameterKind, ParameterKind.REQUIRED);
- expect(parameter.parameters, hasLength(0));
- }
-
- void test_visitFieldFormalParameter_functionTyped() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String parameterName = "p";
- FieldFormalParameter formalParameter = AstFactory.fieldFormalParameter(
- null,
- null,
- parameterName,
- AstFactory
- .formalParameterList([AstFactory.simpleFormalParameter3("a")]));
- formalParameter.accept(builder);
- List<ParameterElement> parameters = holder.parameters;
- expect(parameters, hasLength(1));
- ParameterElement parameter = parameters[0];
- expect(parameter, isNotNull);
- expect(parameter.name, parameterName);
- expect(parameter.initializer, isNull);
- expect(parameter.isConst, isFalse);
- expect(parameter.isFinal, isFalse);
- expect(parameter.isSynthetic, isFalse);
- expect(parameter.parameterKind, ParameterKind.REQUIRED);
- expect(parameter.parameters, hasLength(1));
- }
-
- void test_visitFormalParameterList() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String firstParameterName = "a";
- String secondParameterName = "b";
- FormalParameterList parameterList = AstFactory.formalParameterList([
- AstFactory.simpleFormalParameter3(firstParameterName),
- AstFactory.simpleFormalParameter3(secondParameterName)
- ]);
- parameterList.accept(builder);
- List<ParameterElement> parameters = holder.parameters;
- expect(parameters, hasLength(2));
- expect(parameters[0].name, firstParameterName);
- expect(parameters[1].name, secondParameterName);
- }
-
- void test_visitFunctionDeclaration_external() {
- // external f();
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String functionName = "f";
- FunctionDeclaration declaration = AstFactory.functionDeclaration(
- null,
- null,
- functionName,
- AstFactory.functionExpression2(
- AstFactory.formalParameterList(), AstFactory.emptyFunctionBody()));
- declaration.externalKeyword =
- TokenFactory.tokenFromKeyword(Keyword.EXTERNAL);
- declaration.accept(builder);
-
- List<FunctionElement> functions = holder.functions;
- expect(functions, hasLength(1));
- FunctionElement function = functions[0];
- expect(function, isNotNull);
- expect(function.name, functionName);
- expect(declaration.element, same(function));
- expect(declaration.functionExpression.element, same(function));
- expect(function.hasImplicitReturnType, isTrue);
- expect(function.isExternal, isTrue);
- expect(function.isSynthetic, isFalse);
- expect(function.typeParameters, hasLength(0));
- }
-
- void test_visitFunctionDeclaration_getter() {
- // get f() {}
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String functionName = "f";
- FunctionDeclaration declaration = AstFactory.functionDeclaration(
- null,
- Keyword.GET,
- functionName,
- AstFactory.functionExpression2(
- AstFactory.formalParameterList(), AstFactory.blockFunctionBody2()));
- declaration.documentationComment = AstFactory.documentationComment(
- [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
- declaration.endToken.offset = 80;
- declaration.accept(builder);
-
- List<PropertyAccessorElement> accessors = holder.accessors;
- expect(accessors, hasLength(1));
- PropertyAccessorElement accessor = accessors[0];
- expect(accessor, isNotNull);
- _assertHasCodeRange(accessor, 50, 31);
- expect(accessor.documentationComment, '/// aaa');
- expect(accessor.name, functionName);
- expect(declaration.element, same(accessor));
- expect(declaration.functionExpression.element, same(accessor));
- expect(accessor.hasImplicitReturnType, isTrue);
- expect(accessor.isGetter, isTrue);
- expect(accessor.isExternal, isFalse);
- expect(accessor.isSetter, isFalse);
- expect(accessor.isSynthetic, isFalse);
- expect(accessor.typeParameters, hasLength(0));
- PropertyInducingElement variable = accessor.variable;
- EngineTestCase.assertInstanceOf((obj) => obj is TopLevelVariableElement,
- TopLevelVariableElement, variable);
- expect(variable.isSynthetic, isTrue);
- }
-
- void test_visitFunctionDeclaration_plain() {
- // T f() {}
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String functionName = "f";
- FunctionDeclaration declaration = AstFactory.functionDeclaration(
- AstFactory.typeName4('T'),
- null,
- functionName,
- AstFactory.functionExpression2(
- AstFactory.formalParameterList(), AstFactory.blockFunctionBody2()));
- declaration.documentationComment = AstFactory.documentationComment(
- [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
- declaration.endToken.offset = 80;
- declaration.accept(builder);
-
- List<FunctionElement> functions = holder.functions;
- expect(functions, hasLength(1));
- FunctionElement function = functions[0];
- expect(function, isNotNull);
- _assertHasCodeRange(function, 50, 31);
- expect(function.documentationComment, '/// aaa');
- expect(function.hasImplicitReturnType, isFalse);
- expect(function.name, functionName);
- expect(declaration.element, same(function));
- expect(declaration.functionExpression.element, same(function));
- expect(function.isExternal, isFalse);
- expect(function.isSynthetic, isFalse);
- expect(function.typeParameters, hasLength(0));
- }
-
- void test_visitFunctionDeclaration_setter() {
- // set f() {}
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String functionName = "f";
- FunctionDeclaration declaration = AstFactory.functionDeclaration(
- null,
- Keyword.SET,
- functionName,
- AstFactory.functionExpression2(
- AstFactory.formalParameterList(), AstFactory.blockFunctionBody2()));
- declaration.documentationComment = AstFactory.documentationComment(
- [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
- declaration.endToken.offset = 80;
- declaration.accept(builder);
-
- List<PropertyAccessorElement> accessors = holder.accessors;
- expect(accessors, hasLength(1));
- PropertyAccessorElement accessor = accessors[0];
- expect(accessor, isNotNull);
- _assertHasCodeRange(accessor, 50, 31);
- expect(accessor.documentationComment, '/// aaa');
- expect(accessor.hasImplicitReturnType, isTrue);
- expect(accessor.name, "$functionName=");
- expect(declaration.element, same(accessor));
- expect(declaration.functionExpression.element, same(accessor));
- expect(accessor.isGetter, isFalse);
- expect(accessor.isExternal, isFalse);
- expect(accessor.isSetter, isTrue);
- expect(accessor.isSynthetic, isFalse);
- expect(accessor.typeParameters, hasLength(0));
- PropertyInducingElement variable = accessor.variable;
- EngineTestCase.assertInstanceOf((obj) => obj is TopLevelVariableElement,
- TopLevelVariableElement, variable);
- expect(variable.isSynthetic, isTrue);
- }
-
- void test_visitFunctionDeclaration_typeParameters() {
- // f<E>() {}
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String functionName = 'f';
- String typeParameterName = 'E';
- FunctionExpression expression = AstFactory.functionExpression3(
- AstFactory.typeParameterList([typeParameterName]),
- AstFactory.formalParameterList(),
- AstFactory.blockFunctionBody2());
- FunctionDeclaration declaration =
- AstFactory.functionDeclaration(null, null, functionName, expression);
- declaration.accept(builder);
-
- List<FunctionElement> functions = holder.functions;
- expect(functions, hasLength(1));
- FunctionElement function = functions[0];
- expect(function, isNotNull);
- expect(function.hasImplicitReturnType, isTrue);
- expect(function.name, functionName);
- expect(function.isExternal, isFalse);
- expect(function.isSynthetic, isFalse);
- expect(declaration.element, same(function));
- expect(expression.element, same(function));
- List<TypeParameterElement> typeParameters = function.typeParameters;
- expect(typeParameters, hasLength(1));
- TypeParameterElement typeParameter = typeParameters[0];
- expect(typeParameter, isNotNull);
- expect(typeParameter.name, typeParameterName);
- }
-
- void test_visitFunctionExpression() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- FunctionExpression expression = AstFactory.functionExpression2(
- AstFactory.formalParameterList(), AstFactory.blockFunctionBody2());
- expression.accept(builder);
- List<FunctionElement> functions = holder.functions;
- expect(functions, hasLength(1));
- FunctionElement function = functions[0];
- expect(function, isNotNull);
- expect(expression.element, same(function));
- expect(function.hasImplicitReturnType, isTrue);
- expect(function.isSynthetic, isFalse);
- expect(function.typeParameters, hasLength(0));
- }
-
- void test_visitFunctionTypeAlias() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String aliasName = "F";
- String parameterName = "E";
- FunctionTypeAlias aliasNode = AstFactory.typeAlias(
- null, aliasName, AstFactory.typeParameterList([parameterName]), null);
- aliasNode.documentationComment = AstFactory.documentationComment(
- [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
- aliasNode.endToken.offset = 80;
- aliasNode.accept(builder);
-
- List<FunctionTypeAliasElement> aliases = holder.typeAliases;
- expect(aliases, hasLength(1));
- FunctionTypeAliasElement alias = aliases[0];
- expect(alias, isNotNull);
- _assertHasCodeRange(alias, 50, 31);
- expect(alias.documentationComment, '/// aaa');
- expect(alias.name, aliasName);
- expect(alias.parameters, hasLength(0));
- List<TypeParameterElement> typeParameters = alias.typeParameters;
- expect(typeParameters, hasLength(1));
- TypeParameterElement typeParameter = typeParameters[0];
- expect(typeParameter, isNotNull);
- expect(typeParameter.name, parameterName);
- }
-
- void test_visitFunctionTypedFormalParameter() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String parameterName = "p";
- FunctionTypedFormalParameter formalParameter =
- AstFactory.functionTypedFormalParameter(null, parameterName);
- _useParameterInMethod(formalParameter, 100, 110);
- formalParameter.accept(builder);
- List<ParameterElement> parameters = holder.parameters;
- expect(parameters, hasLength(1));
- ParameterElement parameter = parameters[0];
- expect(parameter, isNotNull);
- expect(parameter.name, parameterName);
- expect(parameter.initializer, isNull);
- expect(parameter.isConst, isFalse);
- expect(parameter.isFinal, isFalse);
- expect(parameter.isSynthetic, isFalse);
- expect(parameter.parameterKind, ParameterKind.REQUIRED);
- _assertVisibleRange(parameter, 100, 110);
- }
-
- void test_visitFunctionTypedFormalParameter_withTypeParameters() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String parameterName = "p";
- FunctionTypedFormalParameter formalParameter =
- AstFactory.functionTypedFormalParameter(null, parameterName);
- formalParameter.typeParameters = AstFactory.typeParameterList(['F']);
- _useParameterInMethod(formalParameter, 100, 110);
- formalParameter.accept(builder);
- List<ParameterElement> parameters = holder.parameters;
- expect(parameters, hasLength(1));
- ParameterElement parameter = parameters[0];
- expect(parameter, isNotNull);
- expect(parameter.name, parameterName);
- expect(parameter.initializer, isNull);
- expect(parameter.isConst, isFalse);
- expect(parameter.isFinal, isFalse);
- expect(parameter.isSynthetic, isFalse);
- expect(parameter.parameterKind, ParameterKind.REQUIRED);
- expect(parameter.typeParameters, hasLength(1));
- _assertVisibleRange(parameter, 100, 110);
- }
-
- void test_visitLabeledStatement() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String labelName = "l";
- LabeledStatement statement = AstFactory.labeledStatement(
- [AstFactory.label2(labelName)], AstFactory.breakStatement());
- statement.accept(builder);
- List<LabelElement> labels = holder.labels;
- expect(labels, hasLength(1));
- LabelElement label = labels[0];
- expect(label, isNotNull);
- expect(label.name, labelName);
- expect(label.isSynthetic, isFalse);
- }
-
- void test_visitMethodDeclaration_abstract() {
- // m();
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String methodName = "m";
- MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
- null,
- null,
- null,
- null,
- AstFactory.identifier3(methodName),
- AstFactory.formalParameterList(),
- AstFactory.emptyFunctionBody());
- methodDeclaration.accept(builder);
-
- List<MethodElement> methods = holder.methods;
- expect(methods, hasLength(1));
- MethodElement method = methods[0];
- expect(method, isNotNull);
- expect(method.hasImplicitReturnType, isTrue);
- expect(method.name, methodName);
- expect(method.functions, hasLength(0));
- expect(method.labels, hasLength(0));
- expect(method.localVariables, hasLength(0));
- expect(method.parameters, hasLength(0));
- expect(method.typeParameters, hasLength(0));
- expect(method.isAbstract, isTrue);
- expect(method.isExternal, isFalse);
- expect(method.isStatic, isFalse);
- expect(method.isSynthetic, isFalse);
- }
-
- void test_visitMethodDeclaration_duplicateField_synthetic() {
- buildElementsForText(r'''
-class A {
- int f;
- int get f => 42;
-}
-''');
- ClassDeclaration classNode = compilationUnit.declarations.single;
- // ClassElement
- ClassElement classElement = classNode.element;
- expect(classElement.fields, hasLength(2));
- expect(classElement.accessors, hasLength(3));
- FieldElement notSyntheticFieldElement = classElement.fields
- .singleWhere((f) => f.displayName == 'f' && !f.isSynthetic);
- FieldElement syntheticFieldElement = classElement.fields
- .singleWhere((f) => f.displayName == 'f' && f.isSynthetic);
- PropertyAccessorElement syntheticGetterElement = classElement.accessors
- .singleWhere(
- (a) => a.displayName == 'f' && a.isGetter && a.isSynthetic);
- PropertyAccessorElement syntheticSetterElement = classElement.accessors
- .singleWhere(
- (a) => a.displayName == 'f' && a.isSetter && a.isSynthetic);
- PropertyAccessorElement notSyntheticGetterElement = classElement.accessors
- .singleWhere(
- (a) => a.displayName == 'f' && a.isGetter && !a.isSynthetic);
- expect(notSyntheticFieldElement.getter, same(syntheticGetterElement));
- expect(notSyntheticFieldElement.setter, same(syntheticSetterElement));
- expect(syntheticFieldElement.getter, same(notSyntheticGetterElement));
- expect(syntheticFieldElement.setter, isNull);
- // class members nodes and their elements
- FieldDeclaration fieldDeclNode = classNode.members[0];
- VariableDeclaration fieldNode = fieldDeclNode.fields.variables.single;
- MethodDeclaration getterNode = classNode.members[1];
- expect(fieldNode.element, notSyntheticFieldElement);
- expect(getterNode.element, notSyntheticGetterElement);
- }
-
- void test_visitMethodDeclaration_external() {
- // external m();
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String methodName = "m";
- MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
- null,
- null,
- null,
- null,
- AstFactory.identifier3(methodName),
- AstFactory.formalParameterList(),
- AstFactory.emptyFunctionBody());
- methodDeclaration.externalKeyword =
- TokenFactory.tokenFromKeyword(Keyword.EXTERNAL);
- methodDeclaration.accept(builder);
-
- List<MethodElement> methods = holder.methods;
- expect(methods, hasLength(1));
- MethodElement method = methods[0];
- expect(method, isNotNull);
- expect(method.hasImplicitReturnType, isTrue);
- expect(method.name, methodName);
- expect(method.functions, hasLength(0));
- expect(method.labels, hasLength(0));
- expect(method.localVariables, hasLength(0));
- expect(method.parameters, hasLength(0));
- expect(method.typeParameters, hasLength(0));
- expect(method.isAbstract, isFalse);
- expect(method.isExternal, isTrue);
- expect(method.isStatic, isFalse);
- expect(method.isSynthetic, isFalse);
- }
-
- void test_visitMethodDeclaration_getter() {
- // get m() {}
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String methodName = "m";
- MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
- null,
- null,
- Keyword.GET,
- null,
- AstFactory.identifier3(methodName),
- AstFactory.formalParameterList(),
- AstFactory.blockFunctionBody2());
- methodDeclaration.documentationComment = AstFactory.documentationComment(
- [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
- methodDeclaration.endToken.offset = 80;
- methodDeclaration.accept(builder);
-
- List<FieldElement> fields = holder.fields;
- expect(fields, hasLength(1));
- FieldElement field = fields[0];
- expect(field, isNotNull);
- expect(field.name, methodName);
- expect(field.isSynthetic, isTrue);
- expect(field.setter, isNull);
- PropertyAccessorElement getter = field.getter;
- expect(getter, isNotNull);
- _assertHasCodeRange(getter, 50, 31);
- expect(getter.documentationComment, '/// aaa');
- expect(getter.hasImplicitReturnType, isTrue);
- expect(getter.isAbstract, isFalse);
- expect(getter.isExternal, isFalse);
- expect(getter.isGetter, isTrue);
- expect(getter.isSynthetic, isFalse);
- expect(getter.name, methodName);
- expect(getter.variable, field);
- expect(getter.functions, hasLength(0));
- expect(getter.labels, hasLength(0));
- expect(getter.localVariables, hasLength(0));
- expect(getter.parameters, hasLength(0));
- }
-
- void test_visitMethodDeclaration_getter_abstract() {
- // get m();
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String methodName = "m";
- MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
- null,
- null,
- Keyword.GET,
- null,
- AstFactory.identifier3(methodName),
- AstFactory.formalParameterList(),
- AstFactory.emptyFunctionBody());
- methodDeclaration.accept(builder);
-
- List<FieldElement> fields = holder.fields;
- expect(fields, hasLength(1));
- FieldElement field = fields[0];
- expect(field, isNotNull);
- expect(field.name, methodName);
- expect(field.isSynthetic, isTrue);
- expect(field.setter, isNull);
- PropertyAccessorElement getter = field.getter;
- expect(getter, isNotNull);
- expect(getter.hasImplicitReturnType, isTrue);
- expect(getter.isAbstract, isTrue);
- expect(getter.isExternal, isFalse);
- expect(getter.isGetter, isTrue);
- expect(getter.isSynthetic, isFalse);
- expect(getter.name, methodName);
- expect(getter.variable, field);
- expect(getter.functions, hasLength(0));
- expect(getter.labels, hasLength(0));
- expect(getter.localVariables, hasLength(0));
- expect(getter.parameters, hasLength(0));
- }
-
- void test_visitMethodDeclaration_getter_external() {
- // external get m();
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String methodName = "m";
- MethodDeclaration methodDeclaration = AstFactory.methodDeclaration(
- null,
- null,
- Keyword.GET,
- null,
- AstFactory.identifier3(methodName),
- AstFactory.formalParameterList());
- methodDeclaration.externalKeyword =
- TokenFactory.tokenFromKeyword(Keyword.EXTERNAL);
- methodDeclaration.accept(builder);
-
- List<FieldElement> fields = holder.fields;
- expect(fields, hasLength(1));
- FieldElement field = fields[0];
- expect(field, isNotNull);
- expect(field.name, methodName);
- expect(field.isSynthetic, isTrue);
- expect(field.setter, isNull);
- PropertyAccessorElement getter = field.getter;
- expect(getter, isNotNull);
- expect(getter.hasImplicitReturnType, isTrue);
- expect(getter.isAbstract, isFalse);
- expect(getter.isExternal, isTrue);
- expect(getter.isGetter, isTrue);
- expect(getter.isSynthetic, isFalse);
- expect(getter.name, methodName);
- expect(getter.variable, field);
- expect(getter.functions, hasLength(0));
- expect(getter.labels, hasLength(0));
- expect(getter.localVariables, hasLength(0));
- expect(getter.parameters, hasLength(0));
- }
-
- void test_visitMethodDeclaration_minimal() {
- // T m() {}
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String methodName = "m";
- MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
- null,
- AstFactory.typeName4('T'),
- null,
- null,
- AstFactory.identifier3(methodName),
- AstFactory.formalParameterList(),
- AstFactory.blockFunctionBody2());
- methodDeclaration.documentationComment = AstFactory.documentationComment(
- [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
- methodDeclaration.endToken.offset = 80;
- methodDeclaration.accept(builder);
-
- List<MethodElement> methods = holder.methods;
- expect(methods, hasLength(1));
- MethodElement method = methods[0];
- expect(method, isNotNull);
- _assertHasCodeRange(method, 50, 31);
- expect(method.documentationComment, '/// aaa');
- expect(method.hasImplicitReturnType, isFalse);
- expect(method.name, methodName);
- expect(method.functions, hasLength(0));
- expect(method.labels, hasLength(0));
- expect(method.localVariables, hasLength(0));
- expect(method.parameters, hasLength(0));
- expect(method.typeParameters, hasLength(0));
- expect(method.isAbstract, isFalse);
- expect(method.isExternal, isFalse);
- expect(method.isStatic, isFalse);
- expect(method.isSynthetic, isFalse);
- }
-
- void test_visitMethodDeclaration_operator() {
- // operator +(addend) {}
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String methodName = "+";
- MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
- null,
- null,
- null,
- Keyword.OPERATOR,
- AstFactory.identifier3(methodName),
- AstFactory
- .formalParameterList([AstFactory.simpleFormalParameter3("addend")]),
- AstFactory.blockFunctionBody2());
- methodDeclaration.accept(builder);
-
- List<MethodElement> methods = holder.methods;
- expect(methods, hasLength(1));
- MethodElement method = methods[0];
- expect(method, isNotNull);
- expect(method.hasImplicitReturnType, isTrue);
- expect(method.name, methodName);
- expect(method.functions, hasLength(0));
- expect(method.labels, hasLength(0));
- expect(method.localVariables, hasLength(0));
- expect(method.parameters, hasLength(1));
- expect(method.typeParameters, hasLength(0));
- expect(method.isAbstract, isFalse);
- expect(method.isExternal, isFalse);
- expect(method.isStatic, isFalse);
- expect(method.isSynthetic, isFalse);
- }
-
- void test_visitMethodDeclaration_setter() {
- // set m() {}
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String methodName = "m";
- MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
- null,
- null,
- Keyword.SET,
- null,
- AstFactory.identifier3(methodName),
- AstFactory.formalParameterList(),
- AstFactory.blockFunctionBody2());
- methodDeclaration.documentationComment = AstFactory.documentationComment(
- [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
- methodDeclaration.endToken.offset = 80;
- methodDeclaration.accept(builder);
-
- List<FieldElement> fields = holder.fields;
- expect(fields, hasLength(1));
- FieldElement field = fields[0];
- expect(field, isNotNull);
- expect(field.name, methodName);
- expect(field.isSynthetic, isTrue);
- expect(field.getter, isNull);
-
- PropertyAccessorElement setter = field.setter;
- expect(setter, isNotNull);
- _assertHasCodeRange(setter, 50, 31);
- expect(setter.documentationComment, '/// aaa');
- expect(setter.hasImplicitReturnType, isTrue);
- expect(setter.isAbstract, isFalse);
- expect(setter.isExternal, isFalse);
- expect(setter.isSetter, isTrue);
- expect(setter.isSynthetic, isFalse);
- expect(setter.name, "$methodName=");
- expect(setter.displayName, methodName);
- expect(setter.variable, field);
- expect(setter.functions, hasLength(0));
- expect(setter.labels, hasLength(0));
- expect(setter.localVariables, hasLength(0));
- expect(setter.parameters, hasLength(0));
- }
-
- void test_visitMethodDeclaration_setter_abstract() {
- // set m();
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String methodName = "m";
- MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
- null,
- null,
- Keyword.SET,
- null,
- AstFactory.identifier3(methodName),
- AstFactory.formalParameterList(),
- AstFactory.emptyFunctionBody());
- methodDeclaration.accept(builder);
-
- List<FieldElement> fields = holder.fields;
- expect(fields, hasLength(1));
- FieldElement field = fields[0];
- expect(field, isNotNull);
- expect(field.name, methodName);
- expect(field.isSynthetic, isTrue);
- expect(field.getter, isNull);
- PropertyAccessorElement setter = field.setter;
- expect(setter, isNotNull);
- expect(setter.hasImplicitReturnType, isTrue);
- expect(setter.isAbstract, isTrue);
- expect(setter.isExternal, isFalse);
- expect(setter.isSetter, isTrue);
- expect(setter.isSynthetic, isFalse);
- expect(setter.name, "$methodName=");
- expect(setter.displayName, methodName);
- expect(setter.variable, field);
- expect(setter.functions, hasLength(0));
- expect(setter.labels, hasLength(0));
- expect(setter.localVariables, hasLength(0));
- expect(setter.parameters, hasLength(0));
- }
-
- void test_visitMethodDeclaration_setter_external() {
- // external m();
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String methodName = "m";
- MethodDeclaration methodDeclaration = AstFactory.methodDeclaration(
- null,
- null,
- Keyword.SET,
- null,
- AstFactory.identifier3(methodName),
- AstFactory.formalParameterList());
- methodDeclaration.externalKeyword =
- TokenFactory.tokenFromKeyword(Keyword.EXTERNAL);
- methodDeclaration.accept(builder);
-
- List<FieldElement> fields = holder.fields;
- expect(fields, hasLength(1));
- FieldElement field = fields[0];
- expect(field, isNotNull);
- expect(field.name, methodName);
- expect(field.isSynthetic, isTrue);
- expect(field.getter, isNull);
- PropertyAccessorElement setter = field.setter;
- expect(setter, isNotNull);
- expect(setter.hasImplicitReturnType, isTrue);
- expect(setter.isAbstract, isFalse);
- expect(setter.isExternal, isTrue);
- expect(setter.isSetter, isTrue);
- expect(setter.isSynthetic, isFalse);
- expect(setter.name, "$methodName=");
- expect(setter.displayName, methodName);
- expect(setter.variable, field);
- expect(setter.functions, hasLength(0));
- expect(setter.labels, hasLength(0));
- expect(setter.localVariables, hasLength(0));
- expect(setter.parameters, hasLength(0));
- }
-
- void test_visitMethodDeclaration_static() {
- // static m() {}
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String methodName = "m";
- MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
- Keyword.STATIC,
- null,
- null,
- null,
- AstFactory.identifier3(methodName),
- AstFactory.formalParameterList(),
- AstFactory.blockFunctionBody2());
- methodDeclaration.accept(builder);
- List<MethodElement> methods = holder.methods;
- expect(methods, hasLength(1));
- MethodElement method = methods[0];
- expect(method, isNotNull);
- expect(method.hasImplicitReturnType, isTrue);
- expect(method.name, methodName);
- expect(method.functions, hasLength(0));
- expect(method.labels, hasLength(0));
- expect(method.localVariables, hasLength(0));
- expect(method.parameters, hasLength(0));
- expect(method.typeParameters, hasLength(0));
- expect(method.isAbstract, isFalse);
- expect(method.isExternal, isFalse);
- expect(method.isStatic, isTrue);
- expect(method.isSynthetic, isFalse);
- }
-
- void test_visitMethodDeclaration_typeParameters() {
- // m<E>() {}
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String methodName = "m";
- MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
- null,
- null,
- null,
- null,
- AstFactory.identifier3(methodName),
- AstFactory.formalParameterList(),
- AstFactory.blockFunctionBody2());
- methodDeclaration.typeParameters = AstFactory.typeParameterList(['E']);
- methodDeclaration.accept(builder);
-
- List<MethodElement> methods = holder.methods;
- expect(methods, hasLength(1));
- MethodElement method = methods[0];
- expect(method, isNotNull);
- expect(method.hasImplicitReturnType, isTrue);
- expect(method.name, methodName);
- expect(method.functions, hasLength(0));
- expect(method.labels, hasLength(0));
- expect(method.localVariables, hasLength(0));
- expect(method.parameters, hasLength(0));
- expect(method.typeParameters, hasLength(1));
- expect(method.isAbstract, isFalse);
- expect(method.isExternal, isFalse);
- expect(method.isStatic, isFalse);
- expect(method.isSynthetic, isFalse);
- }
-
- void test_visitMethodDeclaration_withMembers() {
- // m(p) { var v; try { l: return; } catch (e) {} }
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String methodName = "m";
- String parameterName = "p";
- String localVariableName = "v";
- String labelName = "l";
- String exceptionParameterName = "e";
- MethodDeclaration methodDeclaration = AstFactory.methodDeclaration2(
- null,
- null,
- null,
- null,
- AstFactory.identifier3(methodName),
- AstFactory.formalParameterList(
- [AstFactory.simpleFormalParameter3(parameterName)]),
- AstFactory.blockFunctionBody2([
- AstFactory.variableDeclarationStatement2(
- Keyword.VAR, [AstFactory.variableDeclaration(localVariableName)]),
- AstFactory.tryStatement2(
- AstFactory.block([
- AstFactory.labeledStatement([AstFactory.label2(labelName)],
- AstFactory.returnStatement())
- ]),
- [AstFactory.catchClause(exceptionParameterName)])
- ]));
- methodDeclaration.accept(builder);
-
- List<MethodElement> methods = holder.methods;
- expect(methods, hasLength(1));
- MethodElement method = methods[0];
- expect(method, isNotNull);
- expect(method.hasImplicitReturnType, isTrue);
- expect(method.name, methodName);
- expect(method.typeParameters, hasLength(0));
- expect(method.isAbstract, isFalse);
- expect(method.isExternal, isFalse);
- expect(method.isStatic, isFalse);
- expect(method.isSynthetic, isFalse);
- List<VariableElement> parameters = method.parameters;
- expect(parameters, hasLength(1));
- VariableElement parameter = parameters[0];
- expect(parameter, isNotNull);
- expect(parameter.name, parameterName);
- List<VariableElement> localVariables = method.localVariables;
- expect(localVariables, hasLength(2));
- VariableElement firstVariable = localVariables[0];
- VariableElement secondVariable = localVariables[1];
- expect(firstVariable, isNotNull);
- expect(secondVariable, isNotNull);
- expect(
- (firstVariable.name == localVariableName &&
- secondVariable.name == exceptionParameterName) ||
- (firstVariable.name == exceptionParameterName &&
- secondVariable.name == localVariableName),
- isTrue);
- List<LabelElement> labels = method.labels;
- expect(labels, hasLength(1));
- LabelElement label = labels[0];
- expect(label, isNotNull);
- expect(label.name, labelName);
- }
-
- void test_visitNamedFormalParameter() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String parameterName = "p";
- DefaultFormalParameter formalParameter = AstFactory.namedFormalParameter(
- AstFactory.simpleFormalParameter3(parameterName),
- AstFactory.identifier3("42"));
- _useParameterInMethod(formalParameter, 100, 110);
- formalParameter.beginToken.offset = 50;
- formalParameter.endToken.offset = 80;
- formalParameter.accept(builder);
- List<ParameterElement> parameters = holder.parameters;
- expect(parameters, hasLength(1));
- ParameterElement parameter = parameters[0];
- expect(parameter, isNotNull);
- _assertHasCodeRange(parameter, 50, 32);
- expect(parameter.name, parameterName);
- expect(parameter.isConst, isFalse);
- expect(parameter.isFinal, isFalse);
- expect(parameter.isSynthetic, isFalse);
- expect(parameter.parameterKind, ParameterKind.NAMED);
- _assertVisibleRange(parameter, 100, 110);
- expect(parameter.defaultValueCode, "42");
- FunctionElement initializer = parameter.initializer;
- expect(initializer, isNotNull);
- expect(initializer.isSynthetic, isTrue);
- expect(initializer.hasImplicitReturnType, isTrue);
- }
-
- void test_visitSimpleFormalParameter_noType() {
- // p
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String parameterName = "p";
- SimpleFormalParameter formalParameter =
- AstFactory.simpleFormalParameter3(parameterName);
- _useParameterInMethod(formalParameter, 100, 110);
- formalParameter.accept(builder);
- List<ParameterElement> parameters = holder.parameters;
- expect(parameters, hasLength(1));
- ParameterElement parameter = parameters[0];
- expect(parameter, isNotNull);
- expect(parameter.hasImplicitType, isTrue);
- expect(parameter.initializer, isNull);
- expect(parameter.isConst, isFalse);
- expect(parameter.isFinal, isFalse);
- expect(parameter.isSynthetic, isFalse);
- expect(parameter.name, parameterName);
- expect(parameter.parameterKind, ParameterKind.REQUIRED);
- _assertVisibleRange(parameter, 100, 110);
- }
-
- void test_visitSimpleFormalParameter_type() {
- // T p
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String parameterName = "p";
- SimpleFormalParameter formalParameter = AstFactory.simpleFormalParameter4(
- AstFactory.typeName4('T'), parameterName);
- _useParameterInMethod(formalParameter, 100, 110);
- formalParameter.accept(builder);
- List<ParameterElement> parameters = holder.parameters;
- expect(parameters, hasLength(1));
- ParameterElement parameter = parameters[0];
- expect(parameter, isNotNull);
- expect(parameter.hasImplicitType, isFalse);
- expect(parameter.initializer, isNull);
- expect(parameter.isConst, isFalse);
- expect(parameter.isFinal, isFalse);
- expect(parameter.isSynthetic, isFalse);
- expect(parameter.name, parameterName);
- expect(parameter.parameterKind, ParameterKind.REQUIRED);
- _assertVisibleRange(parameter, 100, 110);
- }
-
- void test_visitTypeAlias_minimal() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String aliasName = "F";
- TypeAlias typeAlias = AstFactory.typeAlias(null, aliasName, null, null);
- typeAlias.accept(builder);
- List<FunctionTypeAliasElement> aliases = holder.typeAliases;
- expect(aliases, hasLength(1));
- FunctionTypeAliasElement alias = aliases[0];
- expect(alias, isNotNull);
- expect(alias.name, aliasName);
- expect(alias.type, isNotNull);
- expect(alias.isSynthetic, isFalse);
- }
-
- void test_visitTypeAlias_withFormalParameters() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String aliasName = "F";
- String firstParameterName = "x";
- String secondParameterName = "y";
- TypeAlias typeAlias = AstFactory.typeAlias(
- null,
- aliasName,
- AstFactory.typeParameterList(),
- AstFactory.formalParameterList([
- AstFactory.simpleFormalParameter3(firstParameterName),
- AstFactory.simpleFormalParameter3(secondParameterName)
- ]));
- typeAlias.beginToken.offset = 50;
- typeAlias.endToken.offset = 80;
- typeAlias.accept(builder);
- List<FunctionTypeAliasElement> aliases = holder.typeAliases;
- expect(aliases, hasLength(1));
- FunctionTypeAliasElement alias = aliases[0];
- expect(alias, isNotNull);
- _assertHasCodeRange(alias, 50, 31);
- expect(alias.name, aliasName);
- expect(alias.type, isNotNull);
- expect(alias.isSynthetic, isFalse);
- List<VariableElement> parameters = alias.parameters;
- expect(parameters, hasLength(2));
- expect(parameters[0].name, firstParameterName);
- expect(parameters[1].name, secondParameterName);
- List<TypeParameterElement> typeParameters = alias.typeParameters;
- expect(typeParameters, isNotNull);
- expect(typeParameters, hasLength(0));
- }
-
- void test_visitTypeAlias_withTypeParameters() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String aliasName = "F";
- String firstTypeParameterName = "A";
- String secondTypeParameterName = "B";
- TypeAlias typeAlias = AstFactory.typeAlias(
- null,
- aliasName,
- AstFactory.typeParameterList(
- [firstTypeParameterName, secondTypeParameterName]),
- AstFactory.formalParameterList());
- typeAlias.accept(builder);
- List<FunctionTypeAliasElement> aliases = holder.typeAliases;
- expect(aliases, hasLength(1));
- FunctionTypeAliasElement alias = aliases[0];
- expect(alias, isNotNull);
- expect(alias.name, aliasName);
- expect(alias.type, isNotNull);
- expect(alias.isSynthetic, isFalse);
- List<VariableElement> parameters = alias.parameters;
- expect(parameters, isNotNull);
- expect(parameters, hasLength(0));
- List<TypeParameterElement> typeParameters = alias.typeParameters;
- expect(typeParameters, hasLength(2));
- expect(typeParameters[0].name, firstTypeParameterName);
- expect(typeParameters[1].name, secondTypeParameterName);
- }
-
- void test_visitTypeParameter() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String parameterName = "E";
- TypeParameter typeParameter = AstFactory.typeParameter(parameterName);
- typeParameter.beginToken.offset = 50;
- typeParameter.accept(builder);
- List<TypeParameterElement> typeParameters = holder.typeParameters;
- expect(typeParameters, hasLength(1));
- TypeParameterElement typeParameterElement = typeParameters[0];
- expect(typeParameterElement, isNotNull);
- _assertHasCodeRange(typeParameterElement, 50, 1);
- expect(typeParameterElement.name, parameterName);
- expect(typeParameterElement.bound, isNull);
- expect(typeParameterElement.isSynthetic, isFalse);
- }
-
- void test_visitVariableDeclaration_inConstructor() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- //
- // C() {var v;}
- //
- String variableName = "v";
- VariableDeclaration variable =
- AstFactory.variableDeclaration2(variableName, null);
- VariableDeclarationStatement statement =
- AstFactory.variableDeclarationStatement2(Keyword.VAR, [variable]);
- ConstructorDeclaration constructor = AstFactory.constructorDeclaration2(
- null,
- null,
- AstFactory.identifier3("C"),
- "C",
- AstFactory.formalParameterList(),
- null,
- AstFactory.blockFunctionBody2([statement]));
- statement.beginToken.offset = 50;
- statement.endToken.offset = 80;
- _setBlockBodySourceRange(constructor.body, 100, 110);
- constructor.accept(builder);
-
- List<ConstructorElement> constructors = holder.constructors;
- expect(constructors, hasLength(1));
- List<LocalVariableElement> variableElements =
- constructors[0].localVariables;
- expect(variableElements, hasLength(1));
- LocalVariableElement variableElement = variableElements[0];
- _assertHasCodeRange(variableElement, 50, 31);
- expect(variableElement.hasImplicitType, isTrue);
- expect(variableElement.name, variableName);
- _assertVisibleRange(variableElement, 100, 110);
- }
-
- void test_visitVariableDeclaration_inForEachStatement() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- //
- // m() { for (var v in []) }
- //
- String variableName = "v";
- Statement statement = AstFactory.forEachStatement(
- AstFactory.declaredIdentifier3('v'),
- AstFactory.listLiteral(),
- AstFactory.block());
- _setNodeSourceRange(statement, 100, 110);
- MethodDeclaration method = AstFactory.methodDeclaration2(
- null,
- null,
- null,
- null,
- AstFactory.identifier3("m"),
- AstFactory.formalParameterList(),
- AstFactory.blockFunctionBody2([statement]));
- _setBlockBodySourceRange(method.body, 200, 220);
- method.accept(builder);
-
- List<MethodElement> methods = holder.methods;
- expect(methods, hasLength(1));
- List<LocalVariableElement> variableElements = methods[0].localVariables;
- expect(variableElements, hasLength(1));
- LocalVariableElement variableElement = variableElements[0];
- expect(variableElement.name, variableName);
- _assertVisibleRange(variableElement, 100, 110);
- }
-
- void test_visitVariableDeclaration_inForStatement() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- //
- // m() { for (T v;;) }
- //
- String variableName = "v";
- ForStatement statement = AstFactory.forStatement2(
- AstFactory.variableDeclarationList(null, AstFactory.typeName4('T'),
- [AstFactory.variableDeclaration('v')]),
- null,
- null,
- AstFactory.block());
- _setNodeSourceRange(statement, 100, 110);
- MethodDeclaration method = AstFactory.methodDeclaration2(
- null,
- null,
- null,
- null,
- AstFactory.identifier3("m"),
- AstFactory.formalParameterList(),
- AstFactory.blockFunctionBody2([statement]));
- _setBlockBodySourceRange(method.body, 200, 220);
- method.accept(builder);
-
- List<MethodElement> methods = holder.methods;
- expect(methods, hasLength(1));
- List<LocalVariableElement> variableElements = methods[0].localVariables;
- expect(variableElements, hasLength(1));
- LocalVariableElement variableElement = variableElements[0];
- expect(variableElement.name, variableName);
- _assertVisibleRange(variableElement, 100, 110);
- }
-
- void test_visitVariableDeclaration_inMethod() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- //
- // m() {T v;}
- //
- String variableName = "v";
- VariableDeclaration variable =
- AstFactory.variableDeclaration2(variableName, null);
- Statement statement = AstFactory.variableDeclarationStatement(
- null, AstFactory.typeName4('T'), [variable]);
- MethodDeclaration method = AstFactory.methodDeclaration2(
- null,
- null,
- null,
- null,
- AstFactory.identifier3("m"),
- AstFactory.formalParameterList(),
- AstFactory.blockFunctionBody2([statement]));
- _setBlockBodySourceRange(method.body, 100, 110);
- method.accept(builder);
-
- List<MethodElement> methods = holder.methods;
- expect(methods, hasLength(1));
- List<LocalVariableElement> variableElements = methods[0].localVariables;
- expect(variableElements, hasLength(1));
- LocalVariableElement variableElement = variableElements[0];
- expect(variableElement.hasImplicitType, isFalse);
- expect(variableElement.name, variableName);
- _assertVisibleRange(variableElement, 100, 110);
- }
-
- void test_visitVariableDeclaration_localNestedInFunction() {
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- //
- // var f = () {var v;};
- //
- String variableName = "v";
- VariableDeclaration variable =
- AstFactory.variableDeclaration2(variableName, null);
- Statement statement =
- AstFactory.variableDeclarationStatement2(null, [variable]);
- Expression initializer = AstFactory.functionExpression2(
- AstFactory.formalParameterList(),
- AstFactory.blockFunctionBody2([statement]));
- String fieldName = "f";
- VariableDeclaration field =
- AstFactory.variableDeclaration2(fieldName, initializer);
- FieldDeclaration fieldDeclaration =
- AstFactory.fieldDeclaration2(false, null, [field]);
- fieldDeclaration.accept(builder);
-
- List<FieldElement> variables = holder.fields;
- expect(variables, hasLength(1));
- FieldElement fieldElement = variables[0];
- expect(fieldElement, isNotNull);
- FunctionElement initializerElement = fieldElement.initializer;
- expect(initializerElement, isNotNull);
- expect(initializerElement.hasImplicitReturnType, isTrue);
- List<FunctionElement> functionElements = initializerElement.functions;
- expect(functionElements, hasLength(1));
- List<LocalVariableElement> variableElements =
- functionElements[0].localVariables;
- expect(variableElements, hasLength(1));
- LocalVariableElement variableElement = variableElements[0];
- expect(variableElement.hasImplicitType, isTrue);
- expect(variableElement.isConst, isFalse);
- expect(variableElement.isFinal, isFalse);
- expect(variableElement.isSynthetic, isFalse);
- expect(variableElement.name, variableName);
- }
-
- void test_visitVariableDeclaration_noInitializer() {
- // var v;
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String variableName = "v";
- VariableDeclaration variableDeclaration =
- AstFactory.variableDeclaration2(variableName, null);
- AstFactory.variableDeclarationList2(null, [variableDeclaration]);
- variableDeclaration.accept(builder);
-
- List<TopLevelVariableElement> variables = holder.topLevelVariables;
- expect(variables, hasLength(1));
- TopLevelVariableElement variable = variables[0];
- expect(variable, isNotNull);
- expect(variable.hasImplicitType, isTrue);
- expect(variable.initializer, isNull);
- expect(variable.name, variableName);
- expect(variable.isConst, isFalse);
- expect(variable.isFinal, isFalse);
- expect(variable.isSynthetic, isFalse);
- expect(variable.getter, isNotNull);
- expect(variable.setter, isNotNull);
- }
-
- void test_visitVariableDeclaration_top() {
- // final a, b;
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- VariableDeclaration variableDeclaration1 =
- AstFactory.variableDeclaration('a');
- VariableDeclaration variableDeclaration2 =
- AstFactory.variableDeclaration('b');
- TopLevelVariableDeclaration topLevelVariableDeclaration = AstFactory
- .topLevelVariableDeclaration(
- Keyword.FINAL, null, [variableDeclaration1, variableDeclaration2]);
- topLevelVariableDeclaration.documentationComment = AstFactory
- .documentationComment(
- [TokenFactory.tokenFromString('/// aaa')..offset = 50], []);
-
- topLevelVariableDeclaration.accept(builder);
- List<TopLevelVariableElement> variables = holder.topLevelVariables;
- expect(variables, hasLength(2));
-
- TopLevelVariableElement variable1 = variables[0];
- expect(variable1, isNotNull);
- expect(variable1.documentationComment, '/// aaa');
-
- TopLevelVariableElement variable2 = variables[1];
- expect(variable2, isNotNull);
- expect(variable2.documentationComment, '/// aaa');
- }
-
- void test_visitVariableDeclaration_top_const_hasInitializer() {
- // const v = 42;
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String variableName = "v";
- VariableDeclaration variableDeclaration =
- AstFactory.variableDeclaration2(variableName, AstFactory.integer(42));
- AstFactory.variableDeclarationList2(Keyword.CONST, [variableDeclaration]);
- variableDeclaration.accept(builder);
-
- List<TopLevelVariableElement> variables = holder.topLevelVariables;
- expect(variables, hasLength(1));
- TopLevelVariableElement variable = variables[0];
- expect(variable, new isInstanceOf<ConstTopLevelVariableElementImpl>());
- expect(variable.initializer, isNotNull);
- expect(variable.initializer.type, isNotNull);
- expect(variable.initializer.hasImplicitReturnType, isTrue);
- expect(variable.name, variableName);
- expect(variable.hasImplicitType, isTrue);
- expect(variable.isConst, isTrue);
- expect(variable.isFinal, isFalse);
- expect(variable.isSynthetic, isFalse);
- expect(variable.getter, isNotNull);
- expect(variable.setter, isNull);
- }
-
- void test_visitVariableDeclaration_top_final() {
- // final v;
- ElementHolder holder = new ElementHolder();
- ElementBuilder builder = _makeBuilder(holder);
- String variableName = "v";
- VariableDeclaration variableDeclaration =
- AstFactory.variableDeclaration2(variableName, null);
- AstFactory.variableDeclarationList2(Keyword.FINAL, [variableDeclaration]);
- variableDeclaration.accept(builder);
- List<TopLevelVariableElement> variables = holder.topLevelVariables;
- expect(variables, hasLength(1));
- TopLevelVariableElement variable = variables[0];
- expect(variable, isNotNull);
- expect(variable.hasImplicitType, isTrue);
- expect(variable.initializer, isNull);
- expect(variable.name, variableName);
- expect(variable.isConst, isFalse);
- expect(variable.isFinal, isTrue);
- expect(variable.isSynthetic, isFalse);
- expect(variable.getter, isNotNull);
- expect(variable.setter, isNull);
- }
-
- void _assertHasCodeRange(Element element, int offset, int length) {
- ElementImpl elementImpl = element;
- expect(elementImpl.codeOffset, offset);
- expect(elementImpl.codeLength, length);
- }
-
- void _assertVisibleRange(LocalElement element, int offset, int end) {
- SourceRange visibleRange = element.visibleRange;
- expect(visibleRange.offset, offset);
- expect(visibleRange.end, end);
- }
-
- ElementBuilder _makeBuilder(ElementHolder holder) =>
- new ElementBuilder(holder, new CompilationUnitElementImpl('test.dart'));
-
- void _setBlockBodySourceRange(BlockFunctionBody body, int offset, int end) {
- _setNodeSourceRange(body.block, offset, end);
- }
-
- void _setNodeSourceRange(AstNode node, int offset, int end) {
- node.beginToken.offset = offset;
- Token endToken = node.endToken;
- endToken.offset = end - endToken.length;
- }
-
- void _useParameterInMethod(
- FormalParameter formalParameter, int blockOffset, int blockEnd) {
- Block block = AstFactory.block();
- block.leftBracket.offset = blockOffset;
- block.rightBracket.offset = blockEnd - 1;
- BlockFunctionBody body = AstFactory.blockFunctionBody(block);
- AstFactory.methodDeclaration2(
- null,
- null,
- null,
- null,
- AstFactory.identifier3("main"),
- AstFactory.formalParameterList([formalParameter]),
- body);
- }
-}
-
-@reflectiveTest
class ElementLocatorTest extends ResolverTestCase {
void fail_locate_Identifier_partOfDirective() {
// Can't resolve the library element without the library declaration.
diff --git a/pkg/analyzer/test/generated/compile_time_error_code_test.dart b/pkg/analyzer/test/generated/compile_time_error_code_test.dart
index e03cba6..35dea2a 100644
--- a/pkg/analyzer/test/generated/compile_time_error_code_test.dart
+++ b/pkg/analyzer/test/generated/compile_time_error_code_test.dart
@@ -48,15 +48,6 @@
verify([source]);
}
- void fail_compileTimeConstantRaisesException() {
- Source source = addSource(r'''
-''');
- computeLibrarySourceErrors(source);
- assertErrors(
- source, [CompileTimeErrorCode.COMPILE_TIME_CONSTANT_RAISES_EXCEPTION]);
- verify([source]);
- }
-
void fail_constEvalThrowsException() {
Source source = addSource(r'''
class C {
@@ -6168,8 +6159,9 @@
assertErrors(source, [CompileTimeErrorCode.URI_DOES_NOT_EXIST]);
// Check that the file is represented as missing.
- Source target =
- analysisContext2.getSourcesWithFullName(resourceProvider.convertPath("/target.dart")).first;
+ Source target = analysisContext2
+ .getSourcesWithFullName(resourceProvider.convertPath("/target.dart"))
+ .first;
expect(analysisContext2.getModificationStamp(target), -1);
// Add an overlay in the same way as AnalysisServer.
diff --git a/pkg/analyzer/test/generated/hint_code_test.dart b/pkg/analyzer/test/generated/hint_code_test.dart
index 6dd9fb6..4e5009f 100644
--- a/pkg/analyzer/test/generated/hint_code_test.dart
+++ b/pkg/analyzer/test/generated/hint_code_test.dart
@@ -1504,8 +1504,7 @@
''');
List<AnalysisError> errors = analysisContext2.computeErrors(source2);
expect(errors, hasLength(1));
- expect(errors[0].message,
- "The member 'a' can only be used within instance members of subclasses of 'A'");
+ expect(errors[0].errorCode, HintCode.INVALID_USE_OF_PROTECTED_MEMBER);
verify([source, source2]);
}
diff --git a/pkg/analyzer/test/generated/parser_test.dart b/pkg/analyzer/test/generated/parser_test.dart
index 2e46dfe..61d6577 100644
--- a/pkg/analyzer/test/generated/parser_test.dart
+++ b/pkg/analyzer/test/generated/parser_test.dart
@@ -8,10 +8,12 @@
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/error/error.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/src/dart/ast/token.dart';
import 'package:analyzer/src/dart/scanner/reader.dart';
import 'package:analyzer/src/dart/scanner/scanner.dart';
import 'package:analyzer/src/generated/parser.dart';
+import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/testing/ast_factory.dart';
import 'package:analyzer/src/generated/testing/token_factory.dart';
import 'package:analyzer/src/generated/utilities_dart.dart';
@@ -2987,6 +2989,21 @@
}
/**
+ * Parse the given [code] as a compilation unit.
+ */
+ static CompilationUnit parseCompilationUnit2(String code,
+ {AnalysisErrorListener listener, bool parseGenericMethods: false}) {
+ listener ??= AnalysisErrorListener.NULL_LISTENER;
+ Scanner scanner = new Scanner(null, new CharSequenceReader(code), listener);
+ Token token = scanner.tokenize();
+ Parser parser = new Parser(null, listener);
+ parser.parseGenericMethods = parseGenericMethods;
+ CompilationUnit unit = parser.parseCompilationUnit(token);
+ unit.lineInfo = new LineInfo(scanner.lineStarts);
+ return unit;
+ }
+
+ /**
* Parse the given [source] as a statement. The [errorCodes] are the error
* codes of the errors that are expected to be found. If
* [enableLazyAssignmentOperators] is `true`, then lazy assignment operators
diff --git a/pkg/analyzer/test/generated/resolver_test.dart b/pkg/analyzer/test/generated/resolver_test.dart
index cc31a71..bdd6b8c 100644
--- a/pkg/analyzer/test/generated/resolver_test.dart
+++ b/pkg/analyzer/test/generated/resolver_test.dart
@@ -12,6 +12,7 @@
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/file_system/memory_file_system.dart';
+import 'package:analyzer/src/dart/element/builder.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/type.dart';
import 'package:analyzer/src/error/codes.dart';
@@ -28,6 +29,7 @@
import 'package:test_reflective_loader/test_reflective_loader.dart';
import 'analysis_context_factory.dart';
+import 'parser_test.dart';
import 'resolver_test_case.dart';
import 'test_support.dart';
@@ -2591,6 +2593,400 @@
nameScope: libraryScope);
}
+ void test_modeApi() {
+ CompilationUnit unit = ParserTestCase.parseCompilationUnit(r'''
+class C extends A with A implements A {
+ A f = new A();
+ A m() {
+ A v1;
+ }
+}
+A f([A p = const A()]) {
+ A v2;
+}
+A V = new A();
+''');
+ var unitElement = new CompilationUnitElementImpl('/test.dart');
+ ClassElementImpl A = ElementFactory.classElement2('A');
+
+ // Build API elements.
+ {
+ var holder = new ElementHolder();
+ unit.accept(new ApiElementBuilder(holder, unitElement));
+ }
+
+ // Resolve API types.
+ {
+ MemoryResourceProvider resourceProvider = new MemoryResourceProvider();
+ InternalAnalysisContext context = AnalysisContextFactory.contextWithCore(
+ resourceProvider: resourceProvider);
+ var source = resourceProvider.getFile('/test.dart').createSource();
+ var libraryElement = new LibraryElementImpl.forNode(context, null)
+ ..definingCompilationUnit = unitElement;
+ var libraryScope = new LibraryScope(libraryElement);
+ var visitor = new TypeResolverVisitor(
+ libraryElement, source, _typeProvider, _listener,
+ nameScope: libraryScope, mode: TypeResolverMode.api);
+ libraryScope.define(A);
+ unit.accept(visitor);
+ }
+
+ // Top-level: C
+ {
+ var c = unit.declarations[0] as ClassDeclaration;
+
+ // The extends/with/implements types are resolved.
+ expect(c.extendsClause.superclass.toString(), 'A');
+ expect(c.withClause.mixinTypes[0].type.toString(), 'A');
+ expect(c.implementsClause.interfaces[0].type.toString(), 'A');
+
+ {
+ var fd = c.members[0] as FieldDeclaration;
+ // The field type is resolved.
+ expect(fd.fields.type.type.toString(), 'A');
+ // The type in the initializer is not resolved.
+ var f = fd.fields.variables[0];
+ var fi = f.initializer as InstanceCreationExpression;
+ expect(fi.constructorName.type.type, isNull);
+ }
+
+ {
+ var m = c.members[1] as MethodDeclaration;
+ // The return type is resolved.
+ expect(m.returnType.type.toString(), 'A');
+ // The local variable type is not resolved.
+ var body = m.body as BlockFunctionBody;
+ var vd = body.block.statements.single as VariableDeclarationStatement;
+ expect(vd.variables.type.type, isNull);
+ }
+ }
+
+ // Top-level: f
+ {
+ var f = unit.declarations[1] as FunctionDeclaration;
+ FunctionExpression fe = f.functionExpression;
+ // The return type is resolved.
+ expect(f.returnType.type.toString(), 'A');
+ // The parameter type is resolved.
+ var pd = fe.parameters.parameters[0] as DefaultFormalParameter;
+ var p = pd.parameter as SimpleFormalParameter;
+ expect(p.type.type.toString(), 'A');
+ // The parameter default is not resolved.
+ {
+ var pde = pd.defaultValue as InstanceCreationExpression;
+ expect(pde.constructorName.type.type, isNull);
+ }
+ // The local variable type is not resolved.
+ var body = fe.body as BlockFunctionBody;
+ var vd = body.block.statements.single as VariableDeclarationStatement;
+ expect(vd.variables.type.type, isNull);
+ }
+
+ // Top-level: V
+ {
+ var vd = unit.declarations[2] as TopLevelVariableDeclaration;
+ // The type is resolved.
+ expect(vd.variables.type.toString(), 'A');
+ // The initializer is not resolved.
+ VariableDeclaration v = vd.variables.variables[0];
+ var vi = v.initializer as InstanceCreationExpression;
+ expect(vi.constructorName.type.type, isNull);
+ }
+ }
+
+ void test_modeLocal_noContext() {
+ CompilationUnit unit;
+ _resolveTypeModeLocal(
+ r'''
+class C {
+ A f = new A();
+ A m([A p = const A()]) {
+ A v;
+ }
+}
+A f([A p = const A()]) {
+ A v1 = new A();
+ A f2(A p2) {
+ A v2;
+ }
+}
+A V = new A();
+A get G => new A();
+''', (CompilationUnit u) {
+ unit = u;
+ return u;
+ });
+
+ // Top-level: C
+ {
+ var c = unit.declarations[0] as ClassDeclaration;
+ {
+ var fd = c.members[0] as FieldDeclaration;
+ // The type of "f" is not resolved.
+ expect(fd.fields.type.type, isNull);
+ // The initializer of "f" is resolved.
+ var f = fd.fields.variables[0];
+ var fi = f.initializer as InstanceCreationExpression;
+ expect(fi.constructorName.type.type.toString(), 'A');
+ }
+ {
+ var m = c.members[1] as MethodDeclaration;
+ // The return type of "m" is not resolved.
+ expect(m.returnType.type, isNull);
+ // The type of the parameter "p" is not resolved.
+ var pd = m.parameters.parameters[0] as DefaultFormalParameter;
+ var p = pd.parameter as SimpleFormalParameter;
+ expect(p.type.type, isNull);
+ // The default value of the parameter "p" is resolved.
+ var pdd = pd.defaultValue as InstanceCreationExpression;
+ expect(pdd.constructorName.type.type.toString(), 'A');
+ // The type of "v" is resolved.
+ var mb = m.body as BlockFunctionBody;
+ var vd = mb.block.statements[0] as VariableDeclarationStatement;
+ expect(vd.variables.type.type.toString(), 'A');
+ }
+ }
+
+ // Top-level: f
+ {
+ var f = unit.declarations[1] as FunctionDeclaration;
+ // The return type of "f" is not resolved.
+ expect(f.returnType.type, isNull);
+ // The type of the parameter "p" is not resolved.
+ var fe = f.functionExpression;
+ var pd = fe.parameters.parameters[0] as DefaultFormalParameter;
+ var p = pd.parameter as SimpleFormalParameter;
+ expect(p.type.type, isNull);
+ // The default value of the parameter "p" is resolved.
+ var pdd = pd.defaultValue as InstanceCreationExpression;
+ expect(pdd.constructorName.type.type.toString(), 'A');
+ // The type of "v1" is resolved.
+ var fb = fe.body as BlockFunctionBody;
+ var vd = fb.block.statements[0] as VariableDeclarationStatement;
+ expect(vd.variables.type.type.toString(), 'A');
+ // The initializer of "v1" is resolved.
+ var v = vd.variables.variables[0];
+ var vi = v.initializer as InstanceCreationExpression;
+ expect(vi.constructorName.type.type.toString(), 'A');
+ // Local: f2
+ {
+ var f2s = fb.block.statements[1] as FunctionDeclarationStatement;
+ var f2 = f2s.functionDeclaration;
+ // The return type of "f2" is resolved.
+ expect(f2.returnType.type.toString(), 'A');
+ // The type of the parameter "p2" is resolved.
+ var f2e = f2.functionExpression;
+ var p2 = f2e.parameters.parameters[0] as SimpleFormalParameter;
+ expect(p2.type.type.toString(), 'A');
+ // The type of "v2" is resolved.
+ var f2b = f2e.body as BlockFunctionBody;
+ var v2d = f2b.block.statements[0] as VariableDeclarationStatement;
+ expect(v2d.variables.type.type.toString(), 'A');
+ }
+ }
+
+ // Top-level: V
+ {
+ var vd = unit.declarations[2] as TopLevelVariableDeclaration;
+ // The type is not resolved.
+ expect(vd.variables.type.type, isNull);
+ // The initializer is resolved.
+ VariableDeclaration v = vd.variables.variables[0];
+ var vi = v.initializer as InstanceCreationExpression;
+ expect(vi.constructorName.type.type.toString(), 'A');
+ }
+
+ // Top-level: G
+ {
+ var g = unit.declarations[3] as FunctionDeclaration;
+ // The return type is not resolved.
+ expect(g.returnType.type, isNull);
+ // The body is resolved.
+ var gb = g.functionExpression.body as ExpressionFunctionBody;
+ var ge = gb.expression as InstanceCreationExpression;
+ expect(ge.constructorName.type.type.toString(), 'A');
+ }
+ }
+
+ void test_modeLocal_withContext_bad_methodBody() {
+ expect(() {
+ _resolveTypeModeLocal(
+ r'''
+class C<T1> {
+ A m<T2>() {
+ T1 v1;
+ T2 v2;
+ }
+}
+''', (CompilationUnit u) {
+ var c = u.declarations[0] as ClassDeclaration;
+ var m = c.members[0] as MethodDeclaration;
+ var mb = m.body as BlockFunctionBody;
+ return mb;
+ });
+ }, throwsStateError);
+ }
+
+ void test_modeLocal_withContext_bad_topLevelVariable_declaration() {
+ expect(() {
+ _resolveTypeModeLocal(
+ r'''
+var v = new A();
+''', (CompilationUnit u) {
+ var tlv = u.declarations[0] as TopLevelVariableDeclaration;
+ return tlv.variables.variables[0];
+ });
+ }, throwsStateError);
+ }
+
+ void test_modeLocal_withContext_bad_topLevelVariable_initializer() {
+ expect(() {
+ _resolveTypeModeLocal(
+ r'''
+var v = new A();
+''', (CompilationUnit u) {
+ var tlv = u.declarations[0] as TopLevelVariableDeclaration;
+ return tlv.variables.variables[0].initializer;
+ });
+ }, throwsStateError);
+ }
+
+ void test_modeLocal_withContext_class() {
+ ClassDeclaration c;
+ _resolveTypeModeLocal(
+ r'''
+class C<T1> {
+ A m<T2>() {
+ T1 v1;
+ T2 v2;
+ }
+}
+''', (CompilationUnit u) {
+ c = u.declarations[0] as ClassDeclaration;
+ return c;
+ });
+ var m = c.members[0] as MethodDeclaration;
+
+ // The return type of "m" is not resolved.
+ expect(m.returnType.type, isNull);
+
+ var mb = m.body as BlockFunctionBody;
+ var ms = mb.block.statements;
+
+ // The type of "v1" is resolved.
+ {
+ var vd = ms[0] as VariableDeclarationStatement;
+ expect(vd.variables.type.type.toString(), 'T1');
+ }
+
+ // The type of "v2" is resolved.
+ {
+ var vd = ms[1] as VariableDeclarationStatement;
+ expect(vd.variables.type.type.toString(), 'T2');
+ }
+ }
+
+ void test_modeLocal_withContext_inClass_constructor() {
+ ConstructorDeclaration cc;
+ _resolveTypeModeLocal(
+ r'''
+class C<T> {
+ C() {
+ T v1;
+ }
+}
+''', (CompilationUnit u) {
+ var c = u.declarations[0] as ClassDeclaration;
+ cc = c.members[0] as ConstructorDeclaration;
+ return cc;
+ });
+
+ var ccb = cc.body as BlockFunctionBody;
+ var ccs = ccb.block.statements;
+
+ // The type of "v" is resolved.
+ {
+ var vd = ccs[0] as VariableDeclarationStatement;
+ expect(vd.variables.type.type.toString(), 'T');
+ }
+ }
+
+ void test_modeLocal_withContext_inClass_method() {
+ MethodDeclaration m;
+ _resolveTypeModeLocal(
+ r'''
+class C<T1> {
+ A m<T2>() {
+ T1 v1;
+ T2 v2;
+ }
+}
+''', (CompilationUnit u) {
+ var c = u.declarations[0] as ClassDeclaration;
+ m = c.members[0] as MethodDeclaration;
+ return m;
+ });
+
+ // The return type of "m" is not resolved.
+ expect(m.returnType.type, isNull);
+
+ var mb = m.body as BlockFunctionBody;
+ var ms = mb.block.statements;
+
+ // The type of "v1" is resolved.
+ {
+ var vd = ms[0] as VariableDeclarationStatement;
+ expect(vd.variables.type.type.toString(), 'T1');
+ }
+
+ // The type of "v2" is resolved.
+ {
+ var vd = ms[1] as VariableDeclarationStatement;
+ expect(vd.variables.type.type.toString(), 'T2');
+ }
+ }
+
+ void test_modeLocal_withContext_topLevelFunction() {
+ FunctionDeclaration f;
+ _resolveTypeModeLocal(
+ r'''
+A m<T>() {
+ T v;
+}
+''', (CompilationUnit u) {
+ f = u.declarations[0] as FunctionDeclaration;
+ return f;
+ });
+
+ // The return type of "f" is not resolved.
+ expect(f.returnType.type, isNull);
+
+ var fb = f.functionExpression.body as BlockFunctionBody;
+ var fs = fb.block.statements;
+
+ // The type of "v" is resolved.
+ var vd = fs[0] as VariableDeclarationStatement;
+ expect(vd.variables.type.type.toString(), 'T');
+ }
+
+ void test_modeLocal_withContext_topLevelVariable() {
+ TopLevelVariableDeclaration v;
+ _resolveTypeModeLocal(
+ r'''
+A v = new A();
+''', (CompilationUnit u) {
+ v = u.declarations[0] as TopLevelVariableDeclaration;
+ return v;
+ });
+
+ // The type of "v" is not resolved.
+ expect(v.variables.type.type, isNull);
+
+ // The type of "v" initializer is resolved.
+ var vi = v.variables.variables[0].initializer as InstanceCreationExpression;
+ expect(vi.constructorName.type.type.toString(), 'A');
+ }
+
void test_visitCatchClause_exception() {
// catch (e)
CatchClause clause = AstFactory.catchClause("e");
@@ -3177,6 +3573,48 @@
}
node.accept(_visitor);
}
+
+ /**
+ * Parse the given [code], build elements and resolve in the
+ * [TypeResolverMode.local] mode. The [code] is allowed to use only the type
+ * named `A`.
+ */
+ void _resolveTypeModeLocal(
+ String code, AstNode getNodeToResolve(CompilationUnit unit)) {
+ CompilationUnit unit =
+ ParserTestCase.parseCompilationUnit2(code, parseGenericMethods: true);
+ var unitElement = new CompilationUnitElementImpl('/test.dart');
+
+ // Build API elements.
+ {
+ var holder = new ElementHolder();
+ unit.accept(new ElementBuilder(holder, unitElement));
+ }
+
+ // Prepare for resolution.
+ LibraryScope libraryScope;
+ TypeResolverVisitor visitor;
+ {
+ MemoryResourceProvider resourceProvider = new MemoryResourceProvider();
+ InternalAnalysisContext context = AnalysisContextFactory.contextWithCore(
+ resourceProvider: resourceProvider);
+ var source = resourceProvider.getFile('/test.dart').createSource();
+ var libraryElement = new LibraryElementImpl.forNode(context, null)
+ ..definingCompilationUnit = unitElement;
+ libraryScope = new LibraryScope(libraryElement);
+ visitor = new TypeResolverVisitor(
+ libraryElement, source, _typeProvider, _listener,
+ nameScope: libraryScope, mode: TypeResolverMode.local);
+ }
+
+ // Define top-level types.
+ ClassElementImpl A = ElementFactory.classElement2('A');
+ libraryScope.define(A);
+
+ // Perform resolution.
+ AstNode nodeToResolve = getNodeToResolve(unit);
+ nodeToResolve.accept(visitor);
+ }
}
class _RootScope extends Scope {
diff --git a/pkg/analyzer/test/generated/static_type_warning_code_test.dart b/pkg/analyzer/test/generated/static_type_warning_code_test.dart
index 982f643..45dbadc 100644
--- a/pkg/analyzer/test/generated/static_type_warning_code_test.dart
+++ b/pkg/analyzer/test/generated/static_type_warning_code_test.dart
@@ -23,14 +23,6 @@
@reflectiveTest
class StaticTypeWarningCodeTest extends ResolverTestCase {
- void fail_inaccessibleSetter() {
- // TODO(rnystrom): This doesn't look right.
- assertErrorsInCode(
- r'''
-''',
- [StaticTypeWarningCode.INACCESSIBLE_SETTER]);
- }
-
void fail_method_lookup_mixin_of_extends() {
// See dartbug.com/25605
resetWithOptions(new AnalysisOptionsImpl()..enableSuperMixins = true);
diff --git a/pkg/analyzer/test/src/context/context_test.dart b/pkg/analyzer/test/src/context/context_test.dart
index d5f9766..83de70d 100644
--- a/pkg/analyzer/test/src/context/context_test.dart
+++ b/pkg/analyzer/test/src/context/context_test.dart
@@ -2424,6 +2424,9 @@
}
void test_resolveCompilationUnit_existingElementModel() {
+ prepareAnalysisContext(new AnalysisOptionsImpl()
+ ..enableGenericMethods = true
+ ..strongMode = true);
Source source = addSource(
'/test.dart',
r'''
@@ -2438,6 +2441,11 @@
enum EnumeratedType {Invalid, Valid}
+class A {
+ const A(x);
+}
+
+@A(const [(_) => null])
class ClassOne {
int instanceField;
static int staticField;
@@ -2461,6 +2469,12 @@
class ClassTwo {
// Implicit no-argument constructor
}
+
+void topLevelFunctionWithLocalFunction() {
+ void localFunction({bool b: false}) {}
+}
+
+void functionWithGenericFunctionTypedParam/*<S>*/(/*=T*/ pf/*<T>*/(/*=T*/ e)) {}
''');
context.resolveCompilationUnit2(source, source);
LibraryElement firstElement = context.computeLibraryElement(source);
diff --git a/pkg/analyzer/test/src/dart/ast/utilities_test.dart b/pkg/analyzer/test/src/dart/ast/utilities_test.dart
index 7e83cf7..7b4d93a 100644
--- a/pkg/analyzer/test/src/dart/ast/utilities_test.dart
+++ b/pkg/analyzer/test/src/dart/ast/utilities_test.dart
@@ -29,6 +29,7 @@
defineReflectiveTests(NodeLocator2Test);
defineReflectiveTests(ResolutionCopierTest);
defineReflectiveTests(ToSourceVisitorTest);
+ defineReflectiveTests(ToSourceVisitor2Test);
});
}
@@ -1109,6 +1110,2241 @@
}
@reflectiveTest
+class ToSourceVisitor2Test extends EngineTestCase {
+ void test_visitAdjacentStrings() {
+ _assertSource(
+ "'a' 'b'",
+ AstFactory.adjacentStrings(
+ [AstFactory.string2("a"), AstFactory.string2("b")]));
+ }
+
+ void test_visitAnnotation_constant() {
+ _assertSource("@A", AstFactory.annotation(AstFactory.identifier3("A")));
+ }
+
+ void test_visitAnnotation_constructor() {
+ _assertSource(
+ "@A.c()",
+ AstFactory.annotation2(AstFactory.identifier3("A"),
+ AstFactory.identifier3("c"), AstFactory.argumentList()));
+ }
+
+ void test_visitArgumentList() {
+ _assertSource(
+ "(a, b)",
+ AstFactory.argumentList(
+ [AstFactory.identifier3("a"), AstFactory.identifier3("b")]));
+ }
+
+ void test_visitAsExpression() {
+ _assertSource(
+ "e as T",
+ AstFactory.asExpression(
+ AstFactory.identifier3("e"), AstFactory.typeName4("T")));
+ }
+
+ void test_visitAssertStatement() {
+ _assertSource(
+ "assert (a);", AstFactory.assertStatement(AstFactory.identifier3("a")));
+ }
+
+ void test_visitAssertStatement_withMessage() {
+ _assertSource(
+ "assert (a, b);",
+ AstFactory.assertStatement(
+ AstFactory.identifier3("a"), AstFactory.identifier3('b')));
+ }
+
+ void test_visitAssignmentExpression() {
+ _assertSource(
+ "a = b",
+ AstFactory.assignmentExpression(AstFactory.identifier3("a"),
+ TokenType.EQ, AstFactory.identifier3("b")));
+ }
+
+ void test_visitAwaitExpression() {
+ _assertSource(
+ "await e", AstFactory.awaitExpression(AstFactory.identifier3("e")));
+ }
+
+ void test_visitBinaryExpression() {
+ _assertSource(
+ "a + b",
+ AstFactory.binaryExpression(AstFactory.identifier3("a"), TokenType.PLUS,
+ AstFactory.identifier3("b")));
+ }
+
+ void test_visitBlock_empty() {
+ _assertSource("{}", AstFactory.block());
+ }
+
+ void test_visitBlock_nonEmpty() {
+ _assertSource(
+ "{break; break;}",
+ AstFactory
+ .block([AstFactory.breakStatement(), AstFactory.breakStatement()]));
+ }
+
+ void test_visitBlockFunctionBody_async() {
+ _assertSource("async {}", AstFactory.asyncBlockFunctionBody());
+ }
+
+ void test_visitBlockFunctionBody_async_star() {
+ _assertSource("async* {}", AstFactory.asyncGeneratorBlockFunctionBody());
+ }
+
+ void test_visitBlockFunctionBody_simple() {
+ _assertSource("{}", AstFactory.blockFunctionBody2());
+ }
+
+ void test_visitBlockFunctionBody_sync() {
+ _assertSource("sync {}", AstFactory.syncBlockFunctionBody());
+ }
+
+ void test_visitBlockFunctionBody_sync_star() {
+ _assertSource("sync* {}", AstFactory.syncGeneratorBlockFunctionBody());
+ }
+
+ void test_visitBooleanLiteral_false() {
+ _assertSource("false", AstFactory.booleanLiteral(false));
+ }
+
+ void test_visitBooleanLiteral_true() {
+ _assertSource("true", AstFactory.booleanLiteral(true));
+ }
+
+ void test_visitBreakStatement_label() {
+ _assertSource("break l;", AstFactory.breakStatement2("l"));
+ }
+
+ void test_visitBreakStatement_noLabel() {
+ _assertSource("break;", AstFactory.breakStatement());
+ }
+
+ void test_visitCascadeExpression_field() {
+ _assertSource(
+ "a..b..c",
+ AstFactory.cascadeExpression(AstFactory.identifier3("a"), [
+ AstFactory.cascadedPropertyAccess("b"),
+ AstFactory.cascadedPropertyAccess("c")
+ ]));
+ }
+
+ void test_visitCascadeExpression_index() {
+ _assertSource(
+ "a..[0]..[1]",
+ AstFactory.cascadeExpression(AstFactory.identifier3("a"), [
+ AstFactory.cascadedIndexExpression(AstFactory.integer(0)),
+ AstFactory.cascadedIndexExpression(AstFactory.integer(1))
+ ]));
+ }
+
+ void test_visitCascadeExpression_method() {
+ _assertSource(
+ "a..b()..c()",
+ AstFactory.cascadeExpression(AstFactory.identifier3("a"), [
+ AstFactory.cascadedMethodInvocation("b"),
+ AstFactory.cascadedMethodInvocation("c")
+ ]));
+ }
+
+ void test_visitCatchClause_catch_noStack() {
+ _assertSource("catch (e) {}", AstFactory.catchClause("e"));
+ }
+
+ void test_visitCatchClause_catch_stack() {
+ _assertSource("catch (e, s) {}", AstFactory.catchClause2("e", "s"));
+ }
+
+ void test_visitCatchClause_on() {
+ _assertSource(
+ "on E {}", AstFactory.catchClause3(AstFactory.typeName4("E")));
+ }
+
+ void test_visitCatchClause_on_catch() {
+ _assertSource("on E catch (e) {}",
+ AstFactory.catchClause4(AstFactory.typeName4("E"), "e"));
+ }
+
+ void test_visitClassDeclaration_abstract() {
+ _assertSource(
+ "abstract class C {}",
+ AstFactory.classDeclaration(
+ Keyword.ABSTRACT, "C", null, null, null, null));
+ }
+
+ void test_visitClassDeclaration_empty() {
+ _assertSource("class C {}",
+ AstFactory.classDeclaration(null, "C", null, null, null, null));
+ }
+
+ void test_visitClassDeclaration_extends() {
+ _assertSource(
+ "class C extends A {}",
+ AstFactory.classDeclaration(null, "C", null,
+ AstFactory.extendsClause(AstFactory.typeName4("A")), null, null));
+ }
+
+ void test_visitClassDeclaration_extends_implements() {
+ _assertSource(
+ "class C extends A implements B {}",
+ AstFactory.classDeclaration(
+ null,
+ "C",
+ null,
+ AstFactory.extendsClause(AstFactory.typeName4("A")),
+ null,
+ AstFactory.implementsClause([AstFactory.typeName4("B")])));
+ }
+
+ void test_visitClassDeclaration_extends_with() {
+ _assertSource(
+ "class C extends A with M {}",
+ AstFactory.classDeclaration(
+ null,
+ "C",
+ null,
+ AstFactory.extendsClause(AstFactory.typeName4("A")),
+ AstFactory.withClause([AstFactory.typeName4("M")]),
+ null));
+ }
+
+ void test_visitClassDeclaration_extends_with_implements() {
+ _assertSource(
+ "class C extends A with M implements B {}",
+ AstFactory.classDeclaration(
+ null,
+ "C",
+ null,
+ AstFactory.extendsClause(AstFactory.typeName4("A")),
+ AstFactory.withClause([AstFactory.typeName4("M")]),
+ AstFactory.implementsClause([AstFactory.typeName4("B")])));
+ }
+
+ void test_visitClassDeclaration_implements() {
+ _assertSource(
+ "class C implements B {}",
+ AstFactory.classDeclaration(null, "C", null, null, null,
+ AstFactory.implementsClause([AstFactory.typeName4("B")])));
+ }
+
+ void test_visitClassDeclaration_multipleMember() {
+ _assertSource(
+ "class C {var a; var b;}",
+ AstFactory.classDeclaration(null, "C", null, null, null, null, [
+ AstFactory.fieldDeclaration2(
+ false, Keyword.VAR, [AstFactory.variableDeclaration("a")]),
+ AstFactory.fieldDeclaration2(
+ false, Keyword.VAR, [AstFactory.variableDeclaration("b")])
+ ]));
+ }
+
+ void test_visitClassDeclaration_parameters() {
+ _assertSource(
+ "class C<E> {}",
+ AstFactory.classDeclaration(
+ null, "C", AstFactory.typeParameterList(["E"]), null, null, null));
+ }
+
+ void test_visitClassDeclaration_parameters_extends() {
+ _assertSource(
+ "class C<E> extends A {}",
+ AstFactory.classDeclaration(
+ null,
+ "C",
+ AstFactory.typeParameterList(["E"]),
+ AstFactory.extendsClause(AstFactory.typeName4("A")),
+ null,
+ null));
+ }
+
+ void test_visitClassDeclaration_parameters_extends_implements() {
+ _assertSource(
+ "class C<E> extends A implements B {}",
+ AstFactory.classDeclaration(
+ null,
+ "C",
+ AstFactory.typeParameterList(["E"]),
+ AstFactory.extendsClause(AstFactory.typeName4("A")),
+ null,
+ AstFactory.implementsClause([AstFactory.typeName4("B")])));
+ }
+
+ void test_visitClassDeclaration_parameters_extends_with() {
+ _assertSource(
+ "class C<E> extends A with M {}",
+ AstFactory.classDeclaration(
+ null,
+ "C",
+ AstFactory.typeParameterList(["E"]),
+ AstFactory.extendsClause(AstFactory.typeName4("A")),
+ AstFactory.withClause([AstFactory.typeName4("M")]),
+ null));
+ }
+
+ void test_visitClassDeclaration_parameters_extends_with_implements() {
+ _assertSource(
+ "class C<E> extends A with M implements B {}",
+ AstFactory.classDeclaration(
+ null,
+ "C",
+ AstFactory.typeParameterList(["E"]),
+ AstFactory.extendsClause(AstFactory.typeName4("A")),
+ AstFactory.withClause([AstFactory.typeName4("M")]),
+ AstFactory.implementsClause([AstFactory.typeName4("B")])));
+ }
+
+ void test_visitClassDeclaration_parameters_implements() {
+ _assertSource(
+ "class C<E> implements B {}",
+ AstFactory.classDeclaration(
+ null,
+ "C",
+ AstFactory.typeParameterList(["E"]),
+ null,
+ null,
+ AstFactory.implementsClause([AstFactory.typeName4("B")])));
+ }
+
+ void test_visitClassDeclaration_singleMember() {
+ _assertSource(
+ "class C {var a;}",
+ AstFactory.classDeclaration(null, "C", null, null, null, null, [
+ AstFactory.fieldDeclaration2(
+ false, Keyword.VAR, [AstFactory.variableDeclaration("a")])
+ ]));
+ }
+
+ void test_visitClassDeclaration_withMetadata() {
+ ClassDeclaration declaration =
+ AstFactory.classDeclaration(null, "C", null, null, null, null);
+ declaration.metadata
+ .add(AstFactory.annotation(AstFactory.identifier3("deprecated")));
+ _assertSource("@deprecated class C {}", declaration);
+ }
+
+ void test_visitClassTypeAlias_abstract() {
+ _assertSource(
+ "abstract class C = S with M1;",
+ AstFactory.classTypeAlias(
+ "C",
+ null,
+ Keyword.ABSTRACT,
+ AstFactory.typeName4("S"),
+ AstFactory.withClause([AstFactory.typeName4("M1")]),
+ null));
+ }
+
+ void test_visitClassTypeAlias_abstract_implements() {
+ _assertSource(
+ "abstract class C = S with M1 implements I;",
+ AstFactory.classTypeAlias(
+ "C",
+ null,
+ Keyword.ABSTRACT,
+ AstFactory.typeName4("S"),
+ AstFactory.withClause([AstFactory.typeName4("M1")]),
+ AstFactory.implementsClause([AstFactory.typeName4("I")])));
+ }
+
+ void test_visitClassTypeAlias_generic() {
+ _assertSource(
+ "class C<E> = S<E> with M1<E>;",
+ AstFactory.classTypeAlias(
+ "C",
+ AstFactory.typeParameterList(["E"]),
+ null,
+ AstFactory.typeName4("S", [AstFactory.typeName4("E")]),
+ AstFactory.withClause([
+ AstFactory.typeName4("M1", [AstFactory.typeName4("E")])
+ ]),
+ null));
+ }
+
+ void test_visitClassTypeAlias_implements() {
+ _assertSource(
+ "class C = S with M1 implements I;",
+ AstFactory.classTypeAlias(
+ "C",
+ null,
+ null,
+ AstFactory.typeName4("S"),
+ AstFactory.withClause([AstFactory.typeName4("M1")]),
+ AstFactory.implementsClause([AstFactory.typeName4("I")])));
+ }
+
+ void test_visitClassTypeAlias_minimal() {
+ _assertSource(
+ "class C = S with M1;",
+ AstFactory.classTypeAlias("C", null, null, AstFactory.typeName4("S"),
+ AstFactory.withClause([AstFactory.typeName4("M1")]), null));
+ }
+
+ void test_visitClassTypeAlias_parameters_abstract() {
+ _assertSource(
+ "abstract class C<E> = S with M1;",
+ AstFactory.classTypeAlias(
+ "C",
+ AstFactory.typeParameterList(["E"]),
+ Keyword.ABSTRACT,
+ AstFactory.typeName4("S"),
+ AstFactory.withClause([AstFactory.typeName4("M1")]),
+ null));
+ }
+
+ void test_visitClassTypeAlias_parameters_abstract_implements() {
+ _assertSource(
+ "abstract class C<E> = S with M1 implements I;",
+ AstFactory.classTypeAlias(
+ "C",
+ AstFactory.typeParameterList(["E"]),
+ Keyword.ABSTRACT,
+ AstFactory.typeName4("S"),
+ AstFactory.withClause([AstFactory.typeName4("M1")]),
+ AstFactory.implementsClause([AstFactory.typeName4("I")])));
+ }
+
+ void test_visitClassTypeAlias_parameters_implements() {
+ _assertSource(
+ "class C<E> = S with M1 implements I;",
+ AstFactory.classTypeAlias(
+ "C",
+ AstFactory.typeParameterList(["E"]),
+ null,
+ AstFactory.typeName4("S"),
+ AstFactory.withClause([AstFactory.typeName4("M1")]),
+ AstFactory.implementsClause([AstFactory.typeName4("I")])));
+ }
+
+ void test_visitClassTypeAlias_withMetadata() {
+ ClassTypeAlias declaration = AstFactory.classTypeAlias(
+ "C",
+ null,
+ null,
+ AstFactory.typeName4("S"),
+ AstFactory.withClause([AstFactory.typeName4("M1")]),
+ null);
+ declaration.metadata
+ .add(AstFactory.annotation(AstFactory.identifier3("deprecated")));
+ _assertSource("@deprecated class C = S with M1;", declaration);
+ }
+
+ void test_visitComment() {
+ _assertSource(
+ "",
+ Comment.createBlockComment(
+ <Token>[TokenFactory.tokenFromString("/* comment */")]));
+ }
+
+ void test_visitCommentReference() {
+ _assertSource("", new CommentReference(null, AstFactory.identifier3("a")));
+ }
+
+ void test_visitCompilationUnit_declaration() {
+ _assertSource(
+ "var a;",
+ AstFactory.compilationUnit2([
+ AstFactory.topLevelVariableDeclaration2(
+ Keyword.VAR, [AstFactory.variableDeclaration("a")])
+ ]));
+ }
+
+ void test_visitCompilationUnit_directive() {
+ _assertSource("library l;",
+ AstFactory.compilationUnit3([AstFactory.libraryDirective2("l")]));
+ }
+
+ void test_visitCompilationUnit_directive_declaration() {
+ _assertSource(
+ "library l; var a;",
+ AstFactory.compilationUnit4([
+ AstFactory.libraryDirective2("l")
+ ], [
+ AstFactory.topLevelVariableDeclaration2(
+ Keyword.VAR, [AstFactory.variableDeclaration("a")])
+ ]));
+ }
+
+ void test_visitCompilationUnit_empty() {
+ _assertSource("", AstFactory.compilationUnit());
+ }
+
+ void test_visitCompilationUnit_script() {
+ _assertSource(
+ "!#/bin/dartvm", AstFactory.compilationUnit5("!#/bin/dartvm"));
+ }
+
+ void test_visitCompilationUnit_script_declaration() {
+ _assertSource(
+ "!#/bin/dartvm var a;",
+ AstFactory.compilationUnit6("!#/bin/dartvm", [
+ AstFactory.topLevelVariableDeclaration2(
+ Keyword.VAR, [AstFactory.variableDeclaration("a")])
+ ]));
+ }
+
+ void test_visitCompilationUnit_script_directive() {
+ _assertSource(
+ "!#/bin/dartvm library l;",
+ AstFactory.compilationUnit7(
+ "!#/bin/dartvm", [AstFactory.libraryDirective2("l")]));
+ }
+
+ void test_visitCompilationUnit_script_directives_declarations() {
+ _assertSource(
+ "!#/bin/dartvm library l; var a;",
+ AstFactory.compilationUnit8("!#/bin/dartvm", [
+ AstFactory.libraryDirective2("l")
+ ], [
+ AstFactory.topLevelVariableDeclaration2(
+ Keyword.VAR, [AstFactory.variableDeclaration("a")])
+ ]));
+ }
+
+ void test_visitConditionalExpression() {
+ _assertSource(
+ "a ? b : c",
+ AstFactory.conditionalExpression(AstFactory.identifier3("a"),
+ AstFactory.identifier3("b"), AstFactory.identifier3("c")));
+ }
+
+ void test_visitConstructorDeclaration_const() {
+ _assertSource(
+ "const C() {}",
+ AstFactory.constructorDeclaration2(
+ Keyword.CONST,
+ null,
+ AstFactory.identifier3("C"),
+ null,
+ AstFactory.formalParameterList(),
+ null,
+ AstFactory.blockFunctionBody2()));
+ }
+
+ void test_visitConstructorDeclaration_external() {
+ _assertSource(
+ "external C();",
+ AstFactory.constructorDeclaration(AstFactory.identifier3("C"), null,
+ AstFactory.formalParameterList(), null));
+ }
+
+ void test_visitConstructorDeclaration_minimal() {
+ _assertSource(
+ "C() {}",
+ AstFactory.constructorDeclaration2(
+ null,
+ null,
+ AstFactory.identifier3("C"),
+ null,
+ AstFactory.formalParameterList(),
+ null,
+ AstFactory.blockFunctionBody2()));
+ }
+
+ void test_visitConstructorDeclaration_multipleInitializers() {
+ _assertSource(
+ "C() : a = b, c = d {}",
+ AstFactory.constructorDeclaration2(
+ null,
+ null,
+ AstFactory.identifier3("C"),
+ null,
+ AstFactory.formalParameterList(),
+ [
+ AstFactory.constructorFieldInitializer(
+ false, "a", AstFactory.identifier3("b")),
+ AstFactory.constructorFieldInitializer(
+ false, "c", AstFactory.identifier3("d"))
+ ],
+ AstFactory.blockFunctionBody2()));
+ }
+
+ void test_visitConstructorDeclaration_multipleParameters() {
+ _assertSource(
+ "C(var a, var b) {}",
+ AstFactory.constructorDeclaration2(
+ null,
+ null,
+ AstFactory.identifier3("C"),
+ null,
+ AstFactory.formalParameterList([
+ AstFactory.simpleFormalParameter(Keyword.VAR, "a"),
+ AstFactory.simpleFormalParameter(Keyword.VAR, "b")
+ ]),
+ null,
+ AstFactory.blockFunctionBody2()));
+ }
+
+ void test_visitConstructorDeclaration_named() {
+ _assertSource(
+ "C.m() {}",
+ AstFactory.constructorDeclaration2(
+ null,
+ null,
+ AstFactory.identifier3("C"),
+ "m",
+ AstFactory.formalParameterList(),
+ null,
+ AstFactory.blockFunctionBody2()));
+ }
+
+ void test_visitConstructorDeclaration_singleInitializer() {
+ _assertSource(
+ "C() : a = b {}",
+ AstFactory.constructorDeclaration2(
+ null,
+ null,
+ AstFactory.identifier3("C"),
+ null,
+ AstFactory.formalParameterList(),
+ [
+ AstFactory.constructorFieldInitializer(
+ false, "a", AstFactory.identifier3("b"))
+ ],
+ AstFactory.blockFunctionBody2()));
+ }
+
+ void test_visitConstructorDeclaration_withMetadata() {
+ ConstructorDeclaration declaration = AstFactory.constructorDeclaration2(
+ null,
+ null,
+ AstFactory.identifier3("C"),
+ null,
+ AstFactory.formalParameterList(),
+ null,
+ AstFactory.blockFunctionBody2());
+ declaration.metadata
+ .add(AstFactory.annotation(AstFactory.identifier3("deprecated")));
+ _assertSource("@deprecated C() {}", declaration);
+ }
+
+ void test_visitConstructorFieldInitializer_withoutThis() {
+ _assertSource(
+ "a = b",
+ AstFactory.constructorFieldInitializer(
+ false, "a", AstFactory.identifier3("b")));
+ }
+
+ void test_visitConstructorFieldInitializer_withThis() {
+ _assertSource(
+ "this.a = b",
+ AstFactory.constructorFieldInitializer(
+ true, "a", AstFactory.identifier3("b")));
+ }
+
+ void test_visitConstructorName_named_prefix() {
+ _assertSource("p.C.n",
+ AstFactory.constructorName(AstFactory.typeName4("p.C.n"), null));
+ }
+
+ void test_visitConstructorName_unnamed_noPrefix() {
+ _assertSource(
+ "C", AstFactory.constructorName(AstFactory.typeName4("C"), null));
+ }
+
+ void test_visitConstructorName_unnamed_prefix() {
+ _assertSource(
+ "p.C",
+ AstFactory.constructorName(
+ AstFactory.typeName3(AstFactory.identifier5("p", "C")), null));
+ }
+
+ void test_visitContinueStatement_label() {
+ _assertSource("continue l;", AstFactory.continueStatement("l"));
+ }
+
+ void test_visitContinueStatement_noLabel() {
+ _assertSource("continue;", AstFactory.continueStatement());
+ }
+
+ void test_visitDefaultFormalParameter_annotation() {
+ DefaultFormalParameter parameter = AstFactory.positionalFormalParameter(
+ AstFactory.simpleFormalParameter3("p"), AstFactory.integer(0));
+ parameter.metadata.add(AstFactory.annotation(AstFactory.identifier3("A")));
+ _assertSource('@A p = 0', parameter);
+ }
+
+ void test_visitDefaultFormalParameter_named_noValue() {
+ _assertSource(
+ "p",
+ AstFactory.namedFormalParameter(
+ AstFactory.simpleFormalParameter3("p"), null));
+ }
+
+ void test_visitDefaultFormalParameter_named_value() {
+ _assertSource(
+ "p : 0",
+ AstFactory.namedFormalParameter(
+ AstFactory.simpleFormalParameter3("p"), AstFactory.integer(0)));
+ }
+
+ void test_visitDefaultFormalParameter_positional_noValue() {
+ _assertSource(
+ "p",
+ AstFactory.positionalFormalParameter(
+ AstFactory.simpleFormalParameter3("p"), null));
+ }
+
+ void test_visitDefaultFormalParameter_positional_value() {
+ _assertSource(
+ "p = 0",
+ AstFactory.positionalFormalParameter(
+ AstFactory.simpleFormalParameter3("p"), AstFactory.integer(0)));
+ }
+
+ void test_visitDoStatement() {
+ _assertSource(
+ "do {} while (c);",
+ AstFactory.doStatement(
+ AstFactory.block(), AstFactory.identifier3("c")));
+ }
+
+ void test_visitDoubleLiteral() {
+ _assertSource("4.2", AstFactory.doubleLiteral(4.2));
+ }
+
+ void test_visitEmptyFunctionBody() {
+ _assertSource(";", AstFactory.emptyFunctionBody());
+ }
+
+ void test_visitEmptyStatement() {
+ _assertSource(";", AstFactory.emptyStatement());
+ }
+
+ void test_visitEnumDeclaration_multiple() {
+ _assertSource(
+ "enum E {ONE, TWO}", AstFactory.enumDeclaration2("E", ["ONE", "TWO"]));
+ }
+
+ void test_visitEnumDeclaration_single() {
+ _assertSource("enum E {ONE}", AstFactory.enumDeclaration2("E", ["ONE"]));
+ }
+
+ void test_visitExportDirective_combinator() {
+ _assertSource(
+ "export 'a.dart' show A;",
+ AstFactory.exportDirective2("a.dart", [
+ AstFactory.showCombinator([AstFactory.identifier3("A")])
+ ]));
+ }
+
+ void test_visitExportDirective_combinators() {
+ _assertSource(
+ "export 'a.dart' show A hide B;",
+ AstFactory.exportDirective2("a.dart", [
+ AstFactory.showCombinator([AstFactory.identifier3("A")]),
+ AstFactory.hideCombinator([AstFactory.identifier3("B")])
+ ]));
+ }
+
+ void test_visitExportDirective_minimal() {
+ _assertSource("export 'a.dart';", AstFactory.exportDirective2("a.dart"));
+ }
+
+ void test_visitExportDirective_withMetadata() {
+ ExportDirective directive = AstFactory.exportDirective2("a.dart");
+ directive.metadata
+ .add(AstFactory.annotation(AstFactory.identifier3("deprecated")));
+ _assertSource("@deprecated export 'a.dart';", directive);
+ }
+
+ void test_visitExpressionFunctionBody_async() {
+ _assertSource("async => a;",
+ AstFactory.asyncExpressionFunctionBody(AstFactory.identifier3("a")));
+ }
+
+ void test_visitExpressionFunctionBody_simple() {
+ _assertSource("=> a;",
+ AstFactory.expressionFunctionBody(AstFactory.identifier3("a")));
+ }
+
+ void test_visitExpressionStatement() {
+ _assertSource(
+ "a;", AstFactory.expressionStatement(AstFactory.identifier3("a")));
+ }
+
+ void test_visitExtendsClause() {
+ _assertSource(
+ "extends C", AstFactory.extendsClause(AstFactory.typeName4("C")));
+ }
+
+ void test_visitFieldDeclaration_instance() {
+ _assertSource(
+ "var a;",
+ AstFactory.fieldDeclaration2(
+ false, Keyword.VAR, [AstFactory.variableDeclaration("a")]));
+ }
+
+ void test_visitFieldDeclaration_static() {
+ _assertSource(
+ "static var a;",
+ AstFactory.fieldDeclaration2(
+ true, Keyword.VAR, [AstFactory.variableDeclaration("a")]));
+ }
+
+ void test_visitFieldDeclaration_withMetadata() {
+ FieldDeclaration declaration = AstFactory.fieldDeclaration2(
+ false, Keyword.VAR, [AstFactory.variableDeclaration("a")]);
+ declaration.metadata
+ .add(AstFactory.annotation(AstFactory.identifier3("deprecated")));
+ _assertSource("@deprecated var a;", declaration);
+ }
+
+ void test_visitFieldFormalParameter_annotation() {
+ FieldFormalParameter parameter = AstFactory.fieldFormalParameter2('f');
+ parameter.metadata.add(AstFactory.annotation(AstFactory.identifier3("A")));
+ _assertSource('@A this.f', parameter);
+ }
+
+ void test_visitFieldFormalParameter_functionTyped() {
+ _assertSource(
+ "A this.a(b)",
+ AstFactory.fieldFormalParameter(
+ null,
+ AstFactory.typeName4("A"),
+ "a",
+ AstFactory.formalParameterList(
+ [AstFactory.simpleFormalParameter3("b")])));
+ }
+
+ void test_visitFieldFormalParameter_functionTyped_typeParameters() {
+ _assertSource(
+ "A this.a<E, F>(b)",
+ new FieldFormalParameter(
+ null,
+ null,
+ null,
+ AstFactory.typeName4('A'),
+ TokenFactory.tokenFromKeyword(Keyword.THIS),
+ TokenFactory.tokenFromType(TokenType.PERIOD),
+ AstFactory.identifier3('a'),
+ AstFactory.typeParameterList(['E', 'F']),
+ AstFactory.formalParameterList(
+ [AstFactory.simpleFormalParameter3("b")])));
+ }
+
+ void test_visitFieldFormalParameter_keyword() {
+ _assertSource(
+ "var this.a", AstFactory.fieldFormalParameter(Keyword.VAR, null, "a"));
+ }
+
+ void test_visitFieldFormalParameter_keywordAndType() {
+ _assertSource(
+ "final A this.a",
+ AstFactory.fieldFormalParameter(
+ Keyword.FINAL, AstFactory.typeName4("A"), "a"));
+ }
+
+ void test_visitFieldFormalParameter_type() {
+ _assertSource("A this.a",
+ AstFactory.fieldFormalParameter(null, AstFactory.typeName4("A"), "a"));
+ }
+
+ void test_visitForEachStatement_declared() {
+ _assertSource(
+ "for (var a in b) {}",
+ AstFactory.forEachStatement(AstFactory.declaredIdentifier3("a"),
+ AstFactory.identifier3("b"), AstFactory.block()));
+ }
+
+ void test_visitForEachStatement_variable() {
+ _assertSource(
+ "for (a in b) {}",
+ new ForEachStatement.withReference(
+ null,
+ TokenFactory.tokenFromKeyword(Keyword.FOR),
+ TokenFactory.tokenFromType(TokenType.OPEN_PAREN),
+ AstFactory.identifier3("a"),
+ TokenFactory.tokenFromKeyword(Keyword.IN),
+ AstFactory.identifier3("b"),
+ TokenFactory.tokenFromType(TokenType.CLOSE_PAREN),
+ AstFactory.block()));
+ }
+
+ void test_visitForEachStatement_variable_await() {
+ _assertSource(
+ "await for (a in b) {}",
+ new ForEachStatement.withReference(
+ TokenFactory.tokenFromString("await"),
+ TokenFactory.tokenFromKeyword(Keyword.FOR),
+ TokenFactory.tokenFromType(TokenType.OPEN_PAREN),
+ AstFactory.identifier3("a"),
+ TokenFactory.tokenFromKeyword(Keyword.IN),
+ AstFactory.identifier3("b"),
+ TokenFactory.tokenFromType(TokenType.CLOSE_PAREN),
+ AstFactory.block()));
+ }
+
+ void test_visitFormalParameterList_empty() {
+ _assertSource("()", AstFactory.formalParameterList());
+ }
+
+ void test_visitFormalParameterList_n() {
+ _assertSource(
+ "({a : 0})",
+ AstFactory.formalParameterList([
+ AstFactory.namedFormalParameter(
+ AstFactory.simpleFormalParameter3("a"), AstFactory.integer(0))
+ ]));
+ }
+
+ void test_visitFormalParameterList_nn() {
+ _assertSource(
+ "({a : 0, b : 1})",
+ AstFactory.formalParameterList([
+ AstFactory.namedFormalParameter(
+ AstFactory.simpleFormalParameter3("a"), AstFactory.integer(0)),
+ AstFactory.namedFormalParameter(
+ AstFactory.simpleFormalParameter3("b"), AstFactory.integer(1))
+ ]));
+ }
+
+ void test_visitFormalParameterList_p() {
+ _assertSource(
+ "([a = 0])",
+ AstFactory.formalParameterList([
+ AstFactory.positionalFormalParameter(
+ AstFactory.simpleFormalParameter3("a"), AstFactory.integer(0))
+ ]));
+ }
+
+ void test_visitFormalParameterList_pp() {
+ _assertSource(
+ "([a = 0, b = 1])",
+ AstFactory.formalParameterList([
+ AstFactory.positionalFormalParameter(
+ AstFactory.simpleFormalParameter3("a"), AstFactory.integer(0)),
+ AstFactory.positionalFormalParameter(
+ AstFactory.simpleFormalParameter3("b"), AstFactory.integer(1))
+ ]));
+ }
+
+ void test_visitFormalParameterList_r() {
+ _assertSource(
+ "(a)",
+ AstFactory
+ .formalParameterList([AstFactory.simpleFormalParameter3("a")]));
+ }
+
+ void test_visitFormalParameterList_rn() {
+ _assertSource(
+ "(a, {b : 1})",
+ AstFactory.formalParameterList([
+ AstFactory.simpleFormalParameter3("a"),
+ AstFactory.namedFormalParameter(
+ AstFactory.simpleFormalParameter3("b"), AstFactory.integer(1))
+ ]));
+ }
+
+ void test_visitFormalParameterList_rnn() {
+ _assertSource(
+ "(a, {b : 1, c : 2})",
+ AstFactory.formalParameterList([
+ AstFactory.simpleFormalParameter3("a"),
+ AstFactory.namedFormalParameter(
+ AstFactory.simpleFormalParameter3("b"), AstFactory.integer(1)),
+ AstFactory.namedFormalParameter(
+ AstFactory.simpleFormalParameter3("c"), AstFactory.integer(2))
+ ]));
+ }
+
+ void test_visitFormalParameterList_rp() {
+ _assertSource(
+ "(a, [b = 1])",
+ AstFactory.formalParameterList([
+ AstFactory.simpleFormalParameter3("a"),
+ AstFactory.positionalFormalParameter(
+ AstFactory.simpleFormalParameter3("b"), AstFactory.integer(1))
+ ]));
+ }
+
+ void test_visitFormalParameterList_rpp() {
+ _assertSource(
+ "(a, [b = 1, c = 2])",
+ AstFactory.formalParameterList([
+ AstFactory.simpleFormalParameter3("a"),
+ AstFactory.positionalFormalParameter(
+ AstFactory.simpleFormalParameter3("b"), AstFactory.integer(1)),
+ AstFactory.positionalFormalParameter(
+ AstFactory.simpleFormalParameter3("c"), AstFactory.integer(2))
+ ]));
+ }
+
+ void test_visitFormalParameterList_rr() {
+ _assertSource(
+ "(a, b)",
+ AstFactory.formalParameterList([
+ AstFactory.simpleFormalParameter3("a"),
+ AstFactory.simpleFormalParameter3("b")
+ ]));
+ }
+
+ void test_visitFormalParameterList_rrn() {
+ _assertSource(
+ "(a, b, {c : 3})",
+ AstFactory.formalParameterList([
+ AstFactory.simpleFormalParameter3("a"),
+ AstFactory.simpleFormalParameter3("b"),
+ AstFactory.namedFormalParameter(
+ AstFactory.simpleFormalParameter3("c"), AstFactory.integer(3))
+ ]));
+ }
+
+ void test_visitFormalParameterList_rrnn() {
+ _assertSource(
+ "(a, b, {c : 3, d : 4})",
+ AstFactory.formalParameterList([
+ AstFactory.simpleFormalParameter3("a"),
+ AstFactory.simpleFormalParameter3("b"),
+ AstFactory.namedFormalParameter(
+ AstFactory.simpleFormalParameter3("c"), AstFactory.integer(3)),
+ AstFactory.namedFormalParameter(
+ AstFactory.simpleFormalParameter3("d"), AstFactory.integer(4))
+ ]));
+ }
+
+ void test_visitFormalParameterList_rrp() {
+ _assertSource(
+ "(a, b, [c = 3])",
+ AstFactory.formalParameterList([
+ AstFactory.simpleFormalParameter3("a"),
+ AstFactory.simpleFormalParameter3("b"),
+ AstFactory.positionalFormalParameter(
+ AstFactory.simpleFormalParameter3("c"), AstFactory.integer(3))
+ ]));
+ }
+
+ void test_visitFormalParameterList_rrpp() {
+ _assertSource(
+ "(a, b, [c = 3, d = 4])",
+ AstFactory.formalParameterList([
+ AstFactory.simpleFormalParameter3("a"),
+ AstFactory.simpleFormalParameter3("b"),
+ AstFactory.positionalFormalParameter(
+ AstFactory.simpleFormalParameter3("c"), AstFactory.integer(3)),
+ AstFactory.positionalFormalParameter(
+ AstFactory.simpleFormalParameter3("d"), AstFactory.integer(4))
+ ]));
+ }
+
+ void test_visitForStatement_c() {
+ _assertSource(
+ "for (; c;) {}",
+ AstFactory.forStatement(
+ null, AstFactory.identifier3("c"), null, AstFactory.block()));
+ }
+
+ void test_visitForStatement_cu() {
+ _assertSource(
+ "for (; c; u) {}",
+ AstFactory.forStatement(null, AstFactory.identifier3("c"),
+ [AstFactory.identifier3("u")], AstFactory.block()));
+ }
+
+ void test_visitForStatement_e() {
+ _assertSource(
+ "for (e;;) {}",
+ AstFactory.forStatement(
+ AstFactory.identifier3("e"), null, null, AstFactory.block()));
+ }
+
+ void test_visitForStatement_ec() {
+ _assertSource(
+ "for (e; c;) {}",
+ AstFactory.forStatement(AstFactory.identifier3("e"),
+ AstFactory.identifier3("c"), null, AstFactory.block()));
+ }
+
+ void test_visitForStatement_ecu() {
+ _assertSource(
+ "for (e; c; u) {}",
+ AstFactory.forStatement(
+ AstFactory.identifier3("e"),
+ AstFactory.identifier3("c"),
+ [AstFactory.identifier3("u")],
+ AstFactory.block()));
+ }
+
+ void test_visitForStatement_eu() {
+ _assertSource(
+ "for (e;; u) {}",
+ AstFactory.forStatement(AstFactory.identifier3("e"), null,
+ [AstFactory.identifier3("u")], AstFactory.block()));
+ }
+
+ void test_visitForStatement_i() {
+ _assertSource(
+ "for (var i;;) {}",
+ AstFactory.forStatement2(
+ AstFactory.variableDeclarationList2(
+ Keyword.VAR, [AstFactory.variableDeclaration("i")]),
+ null,
+ null,
+ AstFactory.block()));
+ }
+
+ void test_visitForStatement_ic() {
+ _assertSource(
+ "for (var i; c;) {}",
+ AstFactory.forStatement2(
+ AstFactory.variableDeclarationList2(
+ Keyword.VAR, [AstFactory.variableDeclaration("i")]),
+ AstFactory.identifier3("c"),
+ null,
+ AstFactory.block()));
+ }
+
+ void test_visitForStatement_icu() {
+ _assertSource(
+ "for (var i; c; u) {}",
+ AstFactory.forStatement2(
+ AstFactory.variableDeclarationList2(
+ Keyword.VAR, [AstFactory.variableDeclaration("i")]),
+ AstFactory.identifier3("c"),
+ [AstFactory.identifier3("u")],
+ AstFactory.block()));
+ }
+
+ void test_visitForStatement_iu() {
+ _assertSource(
+ "for (var i;; u) {}",
+ AstFactory.forStatement2(
+ AstFactory.variableDeclarationList2(
+ Keyword.VAR, [AstFactory.variableDeclaration("i")]),
+ null,
+ [AstFactory.identifier3("u")],
+ AstFactory.block()));
+ }
+
+ void test_visitForStatement_u() {
+ _assertSource(
+ "for (;; u) {}",
+ AstFactory.forStatement(
+ null, null, [AstFactory.identifier3("u")], AstFactory.block()));
+ }
+
+ void test_visitFunctionDeclaration_external() {
+ FunctionDeclaration functionDeclaration = AstFactory.functionDeclaration(
+ null,
+ null,
+ "f",
+ AstFactory.functionExpression2(
+ AstFactory.formalParameterList(), AstFactory.emptyFunctionBody()));
+ functionDeclaration.externalKeyword =
+ TokenFactory.tokenFromKeyword(Keyword.EXTERNAL);
+ _assertSource("external f();", functionDeclaration);
+ }
+
+ void test_visitFunctionDeclaration_getter() {
+ _assertSource(
+ "get f() {}",
+ AstFactory.functionDeclaration(
+ null, Keyword.GET, "f", AstFactory.functionExpression()));
+ }
+
+ void test_visitFunctionDeclaration_local_blockBody() {
+ FunctionDeclaration f = AstFactory.functionDeclaration(
+ null, null, "f", AstFactory.functionExpression());
+ FunctionDeclarationStatement fStatement =
+ new FunctionDeclarationStatement(f);
+ _assertSource(
+ "main() {f() {} 42;}",
+ AstFactory.functionDeclaration(
+ null,
+ null,
+ "main",
+ AstFactory.functionExpression2(
+ AstFactory.formalParameterList(),
+ AstFactory.blockFunctionBody2([
+ fStatement,
+ AstFactory.expressionStatement(AstFactory.integer(42))
+ ]))));
+ }
+
+ void test_visitFunctionDeclaration_local_expressionBody() {
+ FunctionDeclaration f = AstFactory.functionDeclaration(
+ null,
+ null,
+ "f",
+ AstFactory.functionExpression2(AstFactory.formalParameterList(),
+ AstFactory.expressionFunctionBody(AstFactory.integer(1))));
+ FunctionDeclarationStatement fStatement =
+ new FunctionDeclarationStatement(f);
+ _assertSource(
+ "main() {f() => 1; 2;}",
+ AstFactory.functionDeclaration(
+ null,
+ null,
+ "main",
+ AstFactory.functionExpression2(
+ AstFactory.formalParameterList(),
+ AstFactory.blockFunctionBody2([
+ fStatement,
+ AstFactory.expressionStatement(AstFactory.integer(2))
+ ]))));
+ }
+
+ void test_visitFunctionDeclaration_normal() {
+ _assertSource(
+ "f() {}",
+ AstFactory.functionDeclaration(
+ null, null, "f", AstFactory.functionExpression()));
+ }
+
+ void test_visitFunctionDeclaration_setter() {
+ _assertSource(
+ "set f() {}",
+ AstFactory.functionDeclaration(
+ null, Keyword.SET, "f", AstFactory.functionExpression()));
+ }
+
+ void test_visitFunctionDeclaration_typeParameters() {
+ _assertSource(
+ "f<E>() {}",
+ AstFactory.functionDeclaration(
+ null,
+ null,
+ "f",
+ AstFactory.functionExpression3(
+ AstFactory.typeParameterList(['E']),
+ AstFactory.formalParameterList(),
+ AstFactory.blockFunctionBody2())));
+ }
+
+ void test_visitFunctionDeclaration_withMetadata() {
+ FunctionDeclaration declaration = AstFactory.functionDeclaration(
+ null, null, "f", AstFactory.functionExpression());
+ declaration.metadata
+ .add(AstFactory.annotation(AstFactory.identifier3("deprecated")));
+ _assertSource("@deprecated f() {}", declaration);
+ }
+
+ void test_visitFunctionDeclarationStatement() {
+ _assertSource(
+ "f() {}",
+ AstFactory.functionDeclarationStatement(
+ null, null, "f", AstFactory.functionExpression()));
+ }
+
+ void test_visitFunctionExpression() {
+ _assertSource("() {}", AstFactory.functionExpression());
+ }
+
+ void test_visitFunctionExpression_typeParameters() {
+ _assertSource(
+ "<E>() {}",
+ AstFactory.functionExpression3(AstFactory.typeParameterList(['E']),
+ AstFactory.formalParameterList(), AstFactory.blockFunctionBody2()));
+ }
+
+ void test_visitFunctionExpressionInvocation_minimal() {
+ _assertSource("f()",
+ AstFactory.functionExpressionInvocation(AstFactory.identifier3("f")));
+ }
+
+ void test_visitFunctionExpressionInvocation_typeArguments() {
+ _assertSource(
+ "f<A>()",
+ AstFactory.functionExpressionInvocation2(AstFactory.identifier3("f"),
+ AstFactory.typeArgumentList([AstFactory.typeName4('A')])));
+ }
+
+ void test_visitFunctionTypeAlias_generic() {
+ _assertSource(
+ "typedef A F<B>();",
+ AstFactory.typeAlias(
+ AstFactory.typeName4("A"),
+ "F",
+ AstFactory.typeParameterList(["B"]),
+ AstFactory.formalParameterList()));
+ }
+
+ void test_visitFunctionTypeAlias_nonGeneric() {
+ _assertSource(
+ "typedef A F();",
+ AstFactory.typeAlias(AstFactory.typeName4("A"), "F", null,
+ AstFactory.formalParameterList()));
+ }
+
+ void test_visitFunctionTypeAlias_withMetadata() {
+ FunctionTypeAlias declaration = AstFactory.typeAlias(
+ AstFactory.typeName4("A"), "F", null, AstFactory.formalParameterList());
+ declaration.metadata
+ .add(AstFactory.annotation(AstFactory.identifier3("deprecated")));
+ _assertSource("@deprecated typedef A F();", declaration);
+ }
+
+ void test_visitFunctionTypedFormalParameter_annotation() {
+ FunctionTypedFormalParameter parameter =
+ AstFactory.functionTypedFormalParameter(null, "f");
+ parameter.metadata.add(AstFactory.annotation(AstFactory.identifier3("A")));
+ _assertSource('@A f()', parameter);
+ }
+
+ void test_visitFunctionTypedFormalParameter_noType() {
+ _assertSource("f()", AstFactory.functionTypedFormalParameter(null, "f"));
+ }
+
+ void test_visitFunctionTypedFormalParameter_type() {
+ _assertSource(
+ "T f()",
+ AstFactory.functionTypedFormalParameter(
+ AstFactory.typeName4("T"), "f"));
+ }
+
+ void test_visitFunctionTypedFormalParameter_typeParameters() {
+ _assertSource(
+ "T f<E>()",
+ new FunctionTypedFormalParameter(
+ null,
+ null,
+ AstFactory.typeName4("T"),
+ AstFactory.identifier3('f'),
+ AstFactory.typeParameterList(['E']),
+ AstFactory.formalParameterList([])));
+ }
+
+ void test_visitIfStatement_withElse() {
+ _assertSource(
+ "if (c) {} else {}",
+ AstFactory.ifStatement2(AstFactory.identifier3("c"), AstFactory.block(),
+ AstFactory.block()));
+ }
+
+ void test_visitIfStatement_withoutElse() {
+ _assertSource(
+ "if (c) {}",
+ AstFactory.ifStatement(
+ AstFactory.identifier3("c"), AstFactory.block()));
+ }
+
+ void test_visitImplementsClause_multiple() {
+ _assertSource(
+ "implements A, B",
+ AstFactory.implementsClause(
+ [AstFactory.typeName4("A"), AstFactory.typeName4("B")]));
+ }
+
+ void test_visitImplementsClause_single() {
+ _assertSource("implements A",
+ AstFactory.implementsClause([AstFactory.typeName4("A")]));
+ }
+
+ void test_visitImportDirective_combinator() {
+ _assertSource(
+ "import 'a.dart' show A;",
+ AstFactory.importDirective3("a.dart", null, [
+ AstFactory.showCombinator([AstFactory.identifier3("A")])
+ ]));
+ }
+
+ void test_visitImportDirective_combinators() {
+ _assertSource(
+ "import 'a.dart' show A hide B;",
+ AstFactory.importDirective3("a.dart", null, [
+ AstFactory.showCombinator([AstFactory.identifier3("A")]),
+ AstFactory.hideCombinator([AstFactory.identifier3("B")])
+ ]));
+ }
+
+ void test_visitImportDirective_deferred() {
+ _assertSource("import 'a.dart' deferred as p;",
+ AstFactory.importDirective2("a.dart", true, "p"));
+ }
+
+ void test_visitImportDirective_minimal() {
+ _assertSource(
+ "import 'a.dart';", AstFactory.importDirective3("a.dart", null));
+ }
+
+ void test_visitImportDirective_prefix() {
+ _assertSource(
+ "import 'a.dart' as p;", AstFactory.importDirective3("a.dart", "p"));
+ }
+
+ void test_visitImportDirective_prefix_combinator() {
+ _assertSource(
+ "import 'a.dart' as p show A;",
+ AstFactory.importDirective3("a.dart", "p", [
+ AstFactory.showCombinator([AstFactory.identifier3("A")])
+ ]));
+ }
+
+ void test_visitImportDirective_prefix_combinators() {
+ _assertSource(
+ "import 'a.dart' as p show A hide B;",
+ AstFactory.importDirective3("a.dart", "p", [
+ AstFactory.showCombinator([AstFactory.identifier3("A")]),
+ AstFactory.hideCombinator([AstFactory.identifier3("B")])
+ ]));
+ }
+
+ void test_visitImportDirective_withMetadata() {
+ ImportDirective directive = AstFactory.importDirective3("a.dart", null);
+ directive.metadata
+ .add(AstFactory.annotation(AstFactory.identifier3("deprecated")));
+ _assertSource("@deprecated import 'a.dart';", directive);
+ }
+
+ void test_visitImportHideCombinator_multiple() {
+ _assertSource(
+ "hide a, b",
+ AstFactory.hideCombinator(
+ [AstFactory.identifier3("a"), AstFactory.identifier3("b")]));
+ }
+
+ void test_visitImportHideCombinator_single() {
+ _assertSource(
+ "hide a", AstFactory.hideCombinator([AstFactory.identifier3("a")]));
+ }
+
+ void test_visitImportShowCombinator_multiple() {
+ _assertSource(
+ "show a, b",
+ AstFactory.showCombinator(
+ [AstFactory.identifier3("a"), AstFactory.identifier3("b")]));
+ }
+
+ void test_visitImportShowCombinator_single() {
+ _assertSource(
+ "show a", AstFactory.showCombinator([AstFactory.identifier3("a")]));
+ }
+
+ void test_visitIndexExpression() {
+ _assertSource(
+ "a[i]",
+ AstFactory.indexExpression(
+ AstFactory.identifier3("a"), AstFactory.identifier3("i")));
+ }
+
+ void test_visitInstanceCreationExpression_const() {
+ _assertSource(
+ "const C()",
+ AstFactory.instanceCreationExpression2(
+ Keyword.CONST, AstFactory.typeName4("C")));
+ }
+
+ void test_visitInstanceCreationExpression_named() {
+ _assertSource(
+ "new C.c()",
+ AstFactory.instanceCreationExpression3(
+ Keyword.NEW, AstFactory.typeName4("C"), "c"));
+ }
+
+ void test_visitInstanceCreationExpression_unnamed() {
+ _assertSource(
+ "new C()",
+ AstFactory.instanceCreationExpression2(
+ Keyword.NEW, AstFactory.typeName4("C")));
+ }
+
+ void test_visitIntegerLiteral() {
+ _assertSource("42", AstFactory.integer(42));
+ }
+
+ void test_visitInterpolationExpression_expression() {
+ _assertSource("\${a}",
+ AstFactory.interpolationExpression(AstFactory.identifier3("a")));
+ }
+
+ void test_visitInterpolationExpression_identifier() {
+ _assertSource("\$a", AstFactory.interpolationExpression2("a"));
+ }
+
+ void test_visitInterpolationString() {
+ _assertSource("'x", AstFactory.interpolationString("'x", "x"));
+ }
+
+ void test_visitIsExpression_negated() {
+ _assertSource(
+ "a is! C",
+ AstFactory.isExpression(
+ AstFactory.identifier3("a"), true, AstFactory.typeName4("C")));
+ }
+
+ void test_visitIsExpression_normal() {
+ _assertSource(
+ "a is C",
+ AstFactory.isExpression(
+ AstFactory.identifier3("a"), false, AstFactory.typeName4("C")));
+ }
+
+ void test_visitLabel() {
+ _assertSource("a:", AstFactory.label2("a"));
+ }
+
+ void test_visitLabeledStatement_multiple() {
+ _assertSource(
+ "a: b: return;",
+ AstFactory.labeledStatement(
+ [AstFactory.label2("a"), AstFactory.label2("b")],
+ AstFactory.returnStatement()));
+ }
+
+ void test_visitLabeledStatement_single() {
+ _assertSource(
+ "a: return;",
+ AstFactory.labeledStatement(
+ [AstFactory.label2("a")], AstFactory.returnStatement()));
+ }
+
+ void test_visitLibraryDirective() {
+ _assertSource("library l;", AstFactory.libraryDirective2("l"));
+ }
+
+ void test_visitLibraryDirective_withMetadata() {
+ LibraryDirective directive = AstFactory.libraryDirective2("l");
+ directive.metadata
+ .add(AstFactory.annotation(AstFactory.identifier3("deprecated")));
+ _assertSource("@deprecated library l;", directive);
+ }
+
+ void test_visitLibraryIdentifier_multiple() {
+ _assertSource(
+ "a.b.c",
+ AstFactory.libraryIdentifier([
+ AstFactory.identifier3("a"),
+ AstFactory.identifier3("b"),
+ AstFactory.identifier3("c")
+ ]));
+ }
+
+ void test_visitLibraryIdentifier_single() {
+ _assertSource(
+ "a", AstFactory.libraryIdentifier([AstFactory.identifier3("a")]));
+ }
+
+ void test_visitListLiteral_const() {
+ _assertSource("const []", AstFactory.listLiteral2(Keyword.CONST, null));
+ }
+
+ void test_visitListLiteral_empty() {
+ _assertSource("[]", AstFactory.listLiteral());
+ }
+
+ void test_visitListLiteral_nonEmpty() {
+ _assertSource(
+ "[a, b, c]",
+ AstFactory.listLiteral([
+ AstFactory.identifier3("a"),
+ AstFactory.identifier3("b"),
+ AstFactory.identifier3("c")
+ ]));
+ }
+
+ void test_visitMapLiteral_const() {
+ _assertSource("const {}", AstFactory.mapLiteral(Keyword.CONST, null));
+ }
+
+ void test_visitMapLiteral_empty() {
+ _assertSource("{}", AstFactory.mapLiteral2());
+ }
+
+ void test_visitMapLiteral_nonEmpty() {
+ _assertSource(
+ "{'a' : a, 'b' : b, 'c' : c}",
+ AstFactory.mapLiteral2([
+ AstFactory.mapLiteralEntry("a", AstFactory.identifier3("a")),
+ AstFactory.mapLiteralEntry("b", AstFactory.identifier3("b")),
+ AstFactory.mapLiteralEntry("c", AstFactory.identifier3("c"))
+ ]));
+ }
+
+ void test_visitMapLiteralEntry() {
+ _assertSource("'a' : b",
+ AstFactory.mapLiteralEntry("a", AstFactory.identifier3("b")));
+ }
+
+ void test_visitMethodDeclaration_external() {
+ _assertSource(
+ "external m();",
+ AstFactory.methodDeclaration(null, null, null, null,
+ AstFactory.identifier3("m"), AstFactory.formalParameterList()));
+ }
+
+ void test_visitMethodDeclaration_external_returnType() {
+ _assertSource(
+ "external T m();",
+ AstFactory.methodDeclaration(
+ null,
+ AstFactory.typeName4("T"),
+ null,
+ null,
+ AstFactory.identifier3("m"),
+ AstFactory.formalParameterList()));
+ }
+
+ void test_visitMethodDeclaration_getter() {
+ _assertSource(
+ "get m {}",
+ AstFactory.methodDeclaration2(
+ null,
+ null,
+ Keyword.GET,
+ null,
+ AstFactory.identifier3("m"),
+ null,
+ AstFactory.blockFunctionBody2()));
+ }
+
+ void test_visitMethodDeclaration_getter_returnType() {
+ _assertSource(
+ "T get m {}",
+ AstFactory.methodDeclaration2(
+ null,
+ AstFactory.typeName4("T"),
+ Keyword.GET,
+ null,
+ AstFactory.identifier3("m"),
+ null,
+ AstFactory.blockFunctionBody2()));
+ }
+
+ void test_visitMethodDeclaration_getter_seturnType() {
+ _assertSource(
+ "T set m(var v) {}",
+ AstFactory.methodDeclaration2(
+ null,
+ AstFactory.typeName4("T"),
+ Keyword.SET,
+ null,
+ AstFactory.identifier3("m"),
+ AstFactory.formalParameterList(
+ [AstFactory.simpleFormalParameter(Keyword.VAR, "v")]),
+ AstFactory.blockFunctionBody2()));
+ }
+
+ void test_visitMethodDeclaration_minimal() {
+ _assertSource(
+ "m() {}",
+ AstFactory.methodDeclaration2(
+ null,
+ null,
+ null,
+ null,
+ AstFactory.identifier3("m"),
+ AstFactory.formalParameterList(),
+ AstFactory.blockFunctionBody2()));
+ }
+
+ void test_visitMethodDeclaration_multipleParameters() {
+ _assertSource(
+ "m(var a, var b) {}",
+ AstFactory.methodDeclaration2(
+ null,
+ null,
+ null,
+ null,
+ AstFactory.identifier3("m"),
+ AstFactory.formalParameterList([
+ AstFactory.simpleFormalParameter(Keyword.VAR, "a"),
+ AstFactory.simpleFormalParameter(Keyword.VAR, "b")
+ ]),
+ AstFactory.blockFunctionBody2()));
+ }
+
+ void test_visitMethodDeclaration_operator() {
+ _assertSource(
+ "operator +() {}",
+ AstFactory.methodDeclaration2(
+ null,
+ null,
+ null,
+ Keyword.OPERATOR,
+ AstFactory.identifier3("+"),
+ AstFactory.formalParameterList(),
+ AstFactory.blockFunctionBody2()));
+ }
+
+ void test_visitMethodDeclaration_operator_returnType() {
+ _assertSource(
+ "T operator +() {}",
+ AstFactory.methodDeclaration2(
+ null,
+ AstFactory.typeName4("T"),
+ null,
+ Keyword.OPERATOR,
+ AstFactory.identifier3("+"),
+ AstFactory.formalParameterList(),
+ AstFactory.blockFunctionBody2()));
+ }
+
+ void test_visitMethodDeclaration_returnType() {
+ _assertSource(
+ "T m() {}",
+ AstFactory.methodDeclaration2(
+ null,
+ AstFactory.typeName4("T"),
+ null,
+ null,
+ AstFactory.identifier3("m"),
+ AstFactory.formalParameterList(),
+ AstFactory.blockFunctionBody2()));
+ }
+
+ void test_visitMethodDeclaration_setter() {
+ _assertSource(
+ "set m(var v) {}",
+ AstFactory.methodDeclaration2(
+ null,
+ null,
+ Keyword.SET,
+ null,
+ AstFactory.identifier3("m"),
+ AstFactory.formalParameterList(
+ [AstFactory.simpleFormalParameter(Keyword.VAR, "v")]),
+ AstFactory.blockFunctionBody2()));
+ }
+
+ void test_visitMethodDeclaration_static() {
+ _assertSource(
+ "static m() {}",
+ AstFactory.methodDeclaration2(
+ Keyword.STATIC,
+ null,
+ null,
+ null,
+ AstFactory.identifier3("m"),
+ AstFactory.formalParameterList(),
+ AstFactory.blockFunctionBody2()));
+ }
+
+ void test_visitMethodDeclaration_static_returnType() {
+ _assertSource(
+ "static T m() {}",
+ AstFactory.methodDeclaration2(
+ Keyword.STATIC,
+ AstFactory.typeName4("T"),
+ null,
+ null,
+ AstFactory.identifier3("m"),
+ AstFactory.formalParameterList(),
+ AstFactory.blockFunctionBody2()));
+ }
+
+ void test_visitMethodDeclaration_typeParameters() {
+ _assertSource(
+ "m<E>() {}",
+ AstFactory.methodDeclaration3(
+ null,
+ null,
+ null,
+ null,
+ AstFactory.identifier3("m"),
+ AstFactory.typeParameterList(['E']),
+ AstFactory.formalParameterList(),
+ AstFactory.blockFunctionBody2()));
+ }
+
+ void test_visitMethodDeclaration_withMetadata() {
+ MethodDeclaration declaration = AstFactory.methodDeclaration2(
+ null,
+ null,
+ null,
+ null,
+ AstFactory.identifier3("m"),
+ AstFactory.formalParameterList(),
+ AstFactory.blockFunctionBody2());
+ declaration.metadata
+ .add(AstFactory.annotation(AstFactory.identifier3("deprecated")));
+ _assertSource("@deprecated m() {}", declaration);
+ }
+
+ void test_visitMethodInvocation_conditional() {
+ _assertSource(
+ "t?.m()",
+ AstFactory.methodInvocation(
+ AstFactory.identifier3("t"), "m", null, TokenType.QUESTION_PERIOD));
+ }
+
+ void test_visitMethodInvocation_noTarget() {
+ _assertSource("m()", AstFactory.methodInvocation2("m"));
+ }
+
+ void test_visitMethodInvocation_target() {
+ _assertSource(
+ "t.m()", AstFactory.methodInvocation(AstFactory.identifier3("t"), "m"));
+ }
+
+ void test_visitMethodInvocation_typeArguments() {
+ _assertSource(
+ "m<A>()",
+ AstFactory.methodInvocation3(null, "m",
+ AstFactory.typeArgumentList([AstFactory.typeName4('A')])));
+ }
+
+ void test_visitNamedExpression() {
+ _assertSource(
+ "a: b", AstFactory.namedExpression2("a", AstFactory.identifier3("b")));
+ }
+
+ void test_visitNamedFormalParameter() {
+ _assertSource(
+ "var a : 0",
+ AstFactory.namedFormalParameter(
+ AstFactory.simpleFormalParameter(Keyword.VAR, "a"),
+ AstFactory.integer(0)));
+ }
+
+ void test_visitNativeClause() {
+ _assertSource("native 'code'", AstFactory.nativeClause("code"));
+ }
+
+ void test_visitNativeFunctionBody() {
+ _assertSource("native 'str';", AstFactory.nativeFunctionBody("str"));
+ }
+
+ void test_visitNullLiteral() {
+ _assertSource("null", AstFactory.nullLiteral());
+ }
+
+ void test_visitParenthesizedExpression() {
+ _assertSource(
+ "(a)", AstFactory.parenthesizedExpression(AstFactory.identifier3("a")));
+ }
+
+ void test_visitPartDirective() {
+ _assertSource("part 'a.dart';", AstFactory.partDirective2("a.dart"));
+ }
+
+ void test_visitPartDirective_withMetadata() {
+ PartDirective directive = AstFactory.partDirective2("a.dart");
+ directive.metadata
+ .add(AstFactory.annotation(AstFactory.identifier3("deprecated")));
+ _assertSource("@deprecated part 'a.dart';", directive);
+ }
+
+ void test_visitPartOfDirective() {
+ _assertSource("part of l;",
+ AstFactory.partOfDirective(AstFactory.libraryIdentifier2(["l"])));
+ }
+
+ void test_visitPartOfDirective_withMetadata() {
+ PartOfDirective directive =
+ AstFactory.partOfDirective(AstFactory.libraryIdentifier2(["l"]));
+ directive.metadata
+ .add(AstFactory.annotation(AstFactory.identifier3("deprecated")));
+ _assertSource("@deprecated part of l;", directive);
+ }
+
+ void test_visitPositionalFormalParameter() {
+ _assertSource(
+ "var a = 0",
+ AstFactory.positionalFormalParameter(
+ AstFactory.simpleFormalParameter(Keyword.VAR, "a"),
+ AstFactory.integer(0)));
+ }
+
+ void test_visitPostfixExpression() {
+ _assertSource(
+ "a++",
+ AstFactory.postfixExpression(
+ AstFactory.identifier3("a"), TokenType.PLUS_PLUS));
+ }
+
+ void test_visitPrefixedIdentifier() {
+ _assertSource("a.b", AstFactory.identifier5("a", "b"));
+ }
+
+ void test_visitPrefixExpression() {
+ _assertSource(
+ "-a",
+ AstFactory.prefixExpression(
+ TokenType.MINUS, AstFactory.identifier3("a")));
+ }
+
+ void test_visitPropertyAccess() {
+ _assertSource(
+ "a.b", AstFactory.propertyAccess2(AstFactory.identifier3("a"), "b"));
+ }
+
+ void test_visitPropertyAccess_conditional() {
+ _assertSource(
+ "a?.b",
+ AstFactory.propertyAccess2(
+ AstFactory.identifier3("a"), "b", TokenType.QUESTION_PERIOD));
+ }
+
+ void test_visitRedirectingConstructorInvocation_named() {
+ _assertSource(
+ "this.c()", AstFactory.redirectingConstructorInvocation2("c"));
+ }
+
+ void test_visitRedirectingConstructorInvocation_unnamed() {
+ _assertSource("this()", AstFactory.redirectingConstructorInvocation());
+ }
+
+ void test_visitRethrowExpression() {
+ _assertSource("rethrow", AstFactory.rethrowExpression());
+ }
+
+ void test_visitReturnStatement_expression() {
+ _assertSource(
+ "return a;", AstFactory.returnStatement2(AstFactory.identifier3("a")));
+ }
+
+ void test_visitReturnStatement_noExpression() {
+ _assertSource("return;", AstFactory.returnStatement());
+ }
+
+ void test_visitScriptTag() {
+ String scriptTag = "!#/bin/dart.exe";
+ _assertSource(scriptTag, AstFactory.scriptTag(scriptTag));
+ }
+
+ void test_visitSimpleFormalParameter_annotation() {
+ SimpleFormalParameter parameter = AstFactory.simpleFormalParameter3('x');
+ parameter.metadata.add(AstFactory.annotation(AstFactory.identifier3("A")));
+ _assertSource('@A x', parameter);
+ }
+
+ void test_visitSimpleFormalParameter_keyword() {
+ _assertSource("var a", AstFactory.simpleFormalParameter(Keyword.VAR, "a"));
+ }
+
+ void test_visitSimpleFormalParameter_keyword_type() {
+ _assertSource(
+ "final A a",
+ AstFactory.simpleFormalParameter2(
+ Keyword.FINAL, AstFactory.typeName4("A"), "a"));
+ }
+
+ void test_visitSimpleFormalParameter_type() {
+ _assertSource("A a",
+ AstFactory.simpleFormalParameter4(AstFactory.typeName4("A"), "a"));
+ }
+
+ void test_visitSimpleIdentifier() {
+ _assertSource("a", AstFactory.identifier3("a"));
+ }
+
+ void test_visitSimpleStringLiteral() {
+ _assertSource("'a'", AstFactory.string2("a"));
+ }
+
+ void test_visitStringInterpolation() {
+ _assertSource(
+ "'a\${e}b'",
+ AstFactory.string([
+ AstFactory.interpolationString("'a", "a"),
+ AstFactory.interpolationExpression(AstFactory.identifier3("e")),
+ AstFactory.interpolationString("b'", "b")
+ ]));
+ }
+
+ void test_visitSuperConstructorInvocation() {
+ _assertSource("super()", AstFactory.superConstructorInvocation());
+ }
+
+ void test_visitSuperConstructorInvocation_named() {
+ _assertSource("super.c()", AstFactory.superConstructorInvocation2("c"));
+ }
+
+ void test_visitSuperExpression() {
+ _assertSource("super", AstFactory.superExpression());
+ }
+
+ void test_visitSwitchCase_multipleLabels() {
+ _assertSource(
+ "l1: l2: case a: {}",
+ AstFactory.switchCase2(
+ [AstFactory.label2("l1"), AstFactory.label2("l2")],
+ AstFactory.identifier3("a"),
+ [AstFactory.block()]));
+ }
+
+ void test_visitSwitchCase_multipleStatements() {
+ _assertSource(
+ "case a: {} {}",
+ AstFactory.switchCase(AstFactory.identifier3("a"),
+ [AstFactory.block(), AstFactory.block()]));
+ }
+
+ void test_visitSwitchCase_noLabels() {
+ _assertSource(
+ "case a: {}",
+ AstFactory
+ .switchCase(AstFactory.identifier3("a"), [AstFactory.block()]));
+ }
+
+ void test_visitSwitchCase_singleLabel() {
+ _assertSource(
+ "l1: case a: {}",
+ AstFactory.switchCase2([AstFactory.label2("l1")],
+ AstFactory.identifier3("a"), [AstFactory.block()]));
+ }
+
+ void test_visitSwitchDefault_multipleLabels() {
+ _assertSource(
+ "l1: l2: default: {}",
+ AstFactory.switchDefault(
+ [AstFactory.label2("l1"), AstFactory.label2("l2")],
+ [AstFactory.block()]));
+ }
+
+ void test_visitSwitchDefault_multipleStatements() {
+ _assertSource("default: {} {}",
+ AstFactory.switchDefault2([AstFactory.block(), AstFactory.block()]));
+ }
+
+ void test_visitSwitchDefault_noLabels() {
+ _assertSource(
+ "default: {}", AstFactory.switchDefault2([AstFactory.block()]));
+ }
+
+ void test_visitSwitchDefault_singleLabel() {
+ _assertSource(
+ "l1: default: {}",
+ AstFactory
+ .switchDefault([AstFactory.label2("l1")], [AstFactory.block()]));
+ }
+
+ void test_visitSwitchStatement() {
+ _assertSource(
+ "switch (a) {case 'b': {} default: {}}",
+ AstFactory.switchStatement(AstFactory.identifier3("a"), [
+ AstFactory.switchCase(AstFactory.string2("b"), [AstFactory.block()]),
+ AstFactory.switchDefault2([AstFactory.block()])
+ ]));
+ }
+
+ void test_visitSymbolLiteral_multiple() {
+ _assertSource("#a.b.c", AstFactory.symbolLiteral(["a", "b", "c"]));
+ }
+
+ void test_visitSymbolLiteral_single() {
+ _assertSource("#a", AstFactory.symbolLiteral(["a"]));
+ }
+
+ void test_visitThisExpression() {
+ _assertSource("this", AstFactory.thisExpression());
+ }
+
+ void test_visitThrowStatement() {
+ _assertSource(
+ "throw e", AstFactory.throwExpression2(AstFactory.identifier3("e")));
+ }
+
+ void test_visitTopLevelVariableDeclaration_multiple() {
+ _assertSource(
+ "var a;",
+ AstFactory.topLevelVariableDeclaration2(
+ Keyword.VAR, [AstFactory.variableDeclaration("a")]));
+ }
+
+ void test_visitTopLevelVariableDeclaration_single() {
+ _assertSource(
+ "var a, b;",
+ AstFactory.topLevelVariableDeclaration2(Keyword.VAR, [
+ AstFactory.variableDeclaration("a"),
+ AstFactory.variableDeclaration("b")
+ ]));
+ }
+
+ void test_visitTryStatement_catch() {
+ _assertSource(
+ "try {} on E {}",
+ AstFactory.tryStatement2(AstFactory.block(),
+ [AstFactory.catchClause3(AstFactory.typeName4("E"))]));
+ }
+
+ void test_visitTryStatement_catches() {
+ _assertSource(
+ "try {} on E {} on F {}",
+ AstFactory.tryStatement2(AstFactory.block(), [
+ AstFactory.catchClause3(AstFactory.typeName4("E")),
+ AstFactory.catchClause3(AstFactory.typeName4("F"))
+ ]));
+ }
+
+ void test_visitTryStatement_catchFinally() {
+ _assertSource(
+ "try {} on E {} finally {}",
+ AstFactory.tryStatement3(
+ AstFactory.block(),
+ [AstFactory.catchClause3(AstFactory.typeName4("E"))],
+ AstFactory.block()));
+ }
+
+ void test_visitTryStatement_finally() {
+ _assertSource("try {} finally {}",
+ AstFactory.tryStatement(AstFactory.block(), AstFactory.block()));
+ }
+
+ void test_visitTypeArgumentList_multiple() {
+ _assertSource(
+ "<E, F>",
+ AstFactory.typeArgumentList(
+ [AstFactory.typeName4("E"), AstFactory.typeName4("F")]));
+ }
+
+ void test_visitTypeArgumentList_single() {
+ _assertSource(
+ "<E>", AstFactory.typeArgumentList([AstFactory.typeName4("E")]));
+ }
+
+ void test_visitTypeName_multipleArgs() {
+ _assertSource(
+ "C<D, E>",
+ AstFactory.typeName4(
+ "C", [AstFactory.typeName4("D"), AstFactory.typeName4("E")]));
+ }
+
+ void test_visitTypeName_nestedArg() {
+ _assertSource(
+ "C<D<E>>",
+ AstFactory.typeName4("C", [
+ AstFactory.typeName4("D", [AstFactory.typeName4("E")])
+ ]));
+ }
+
+ void test_visitTypeName_noArgs() {
+ _assertSource("C", AstFactory.typeName4("C"));
+ }
+
+ void test_visitTypeName_singleArg() {
+ _assertSource(
+ "C<D>", AstFactory.typeName4("C", [AstFactory.typeName4("D")]));
+ }
+
+ void test_visitTypeParameter_withExtends() {
+ _assertSource("E extends C",
+ AstFactory.typeParameter2("E", AstFactory.typeName4("C")));
+ }
+
+ void test_visitTypeParameter_withMetadata() {
+ TypeParameter parameter = AstFactory.typeParameter("E");
+ parameter.metadata
+ .add(AstFactory.annotation(AstFactory.identifier3("deprecated")));
+ _assertSource("@deprecated E", parameter);
+ }
+
+ void test_visitTypeParameter_withoutExtends() {
+ _assertSource("E", AstFactory.typeParameter("E"));
+ }
+
+ void test_visitTypeParameterList_multiple() {
+ _assertSource("<E, F>", AstFactory.typeParameterList(["E", "F"]));
+ }
+
+ void test_visitTypeParameterList_single() {
+ _assertSource("<E>", AstFactory.typeParameterList(["E"]));
+ }
+
+ void test_visitVariableDeclaration_initialized() {
+ _assertSource("a = b",
+ AstFactory.variableDeclaration2("a", AstFactory.identifier3("b")));
+ }
+
+ void test_visitVariableDeclaration_uninitialized() {
+ _assertSource("a", AstFactory.variableDeclaration("a"));
+ }
+
+ void test_visitVariableDeclaration_withMetadata() {
+ VariableDeclaration declaration = AstFactory.variableDeclaration("a");
+ declaration.metadata
+ .add(AstFactory.annotation(AstFactory.identifier3("deprecated")));
+ _assertSource("@deprecated a", declaration);
+ }
+
+ void test_visitVariableDeclarationList_const_type() {
+ _assertSource(
+ "const C a, b",
+ AstFactory.variableDeclarationList(
+ Keyword.CONST, AstFactory.typeName4("C"), [
+ AstFactory.variableDeclaration("a"),
+ AstFactory.variableDeclaration("b")
+ ]));
+ }
+
+ void test_visitVariableDeclarationList_final_noType() {
+ _assertSource(
+ "final a, b",
+ AstFactory.variableDeclarationList2(Keyword.FINAL, [
+ AstFactory.variableDeclaration("a"),
+ AstFactory.variableDeclaration("b")
+ ]));
+ }
+
+ void test_visitVariableDeclarationList_final_withMetadata() {
+ VariableDeclarationList declarationList = AstFactory
+ .variableDeclarationList2(Keyword.FINAL, [
+ AstFactory.variableDeclaration("a"),
+ AstFactory.variableDeclaration("b")
+ ]);
+ declarationList.metadata
+ .add(AstFactory.annotation(AstFactory.identifier3("deprecated")));
+ _assertSource("@deprecated final a, b", declarationList);
+ }
+
+ void test_visitVariableDeclarationList_type() {
+ _assertSource(
+ "C a, b",
+ AstFactory.variableDeclarationList(null, AstFactory.typeName4("C"), [
+ AstFactory.variableDeclaration("a"),
+ AstFactory.variableDeclaration("b")
+ ]));
+ }
+
+ void test_visitVariableDeclarationList_var() {
+ _assertSource(
+ "var a, b",
+ AstFactory.variableDeclarationList2(Keyword.VAR, [
+ AstFactory.variableDeclaration("a"),
+ AstFactory.variableDeclaration("b")
+ ]));
+ }
+
+ void test_visitVariableDeclarationStatement() {
+ _assertSource(
+ "C c;",
+ AstFactory.variableDeclarationStatement(null, AstFactory.typeName4("C"),
+ [AstFactory.variableDeclaration("c")]));
+ }
+
+ void test_visitWhileStatement() {
+ _assertSource(
+ "while (c) {}",
+ AstFactory.whileStatement(
+ AstFactory.identifier3("c"), AstFactory.block()));
+ }
+
+ void test_visitWithClause_multiple() {
+ _assertSource(
+ "with A, B, C",
+ AstFactory.withClause([
+ AstFactory.typeName4("A"),
+ AstFactory.typeName4("B"),
+ AstFactory.typeName4("C")
+ ]));
+ }
+
+ void test_visitWithClause_single() {
+ _assertSource("with A", AstFactory.withClause([AstFactory.typeName4("A")]));
+ }
+
+ void test_visitYieldStatement() {
+ _assertSource(
+ "yield e;", AstFactory.yieldStatement(AstFactory.identifier3("e")));
+ }
+
+ void test_visitYieldStatement_each() {
+ _assertSource("yield* e;",
+ AstFactory.yieldEachStatement(AstFactory.identifier3("e")));
+ }
+
+ /**
+ * Assert that a `ToSourceVisitor2` will produce the [expectedSource] when
+ * visiting the given [node].
+ */
+ void _assertSource(String expectedSource, AstNode node) {
+ StringBuffer buffer = new StringBuffer();
+ node.accept(new ToSourceVisitor2(buffer));
+ expect(buffer.toString(), expectedSource);
+ }
+}
+
+@reflectiveTest
class ToSourceVisitorTest extends EngineTestCase {
void test_visitAdjacentStrings() {
_assertSource(
@@ -3333,12 +5569,8 @@
}
/**
- * Assert that a `ToSourceVisitor` will produce the expected source when visiting the given
- * node.
- *
- * @param expectedSource the source string that the visitor is expected to produce
- * @param node the AST node being visited to produce the actual source
- * @throws AFE if the visitor does not produce the expected source for the given node
+ * Assert that a `ToSourceVisitor` will produce the [expectedSource] when
+ * visiting the given [node].
*/
void _assertSource(String expectedSource, AstNode node) {
PrintStringWriter writer = new PrintStringWriter();
diff --git a/pkg/analyzer/test/src/task/options_test.dart b/pkg/analyzer/test/src/task/options_test.dart
index b422eba..ce4bf2e 100644
--- a/pkg/analyzer/test/src/task/options_test.dart
+++ b/pkg/analyzer/test/src/task/options_test.dart
@@ -254,10 +254,6 @@
expect(errors, hasLength(1));
expect(errors[0].errorCode,
AnalysisOptionsWarningCode.UNSUPPORTED_OPTION_WITH_LEGAL_VALUES);
- expect(
- errors[0].message,
- "The option 'not_supported' is not supported by analyzer, supported "
- "values are 'errors', 'exclude', 'language', 'plugins' and 'strong-mode'");
}
}
diff --git a/pkg/analyzer/test/src/task/strong/inferred_type_test.dart b/pkg/analyzer/test/src/task/strong/inferred_type_test.dart
index da86f94..b6e116a 100644
--- a/pkg/analyzer/test/src/task/strong/inferred_type_test.dart
+++ b/pkg/analyzer/test/src/task/strong/inferred_type_test.dart
@@ -1740,7 +1740,7 @@
build(declared: "Future", downwards: "Future", upwards: "MyFuture"));
}
- void test_futureUnion_downwardsGenericMethods() {
+ void test_futureUnion_downwardsGenericMethodWithFutureReturn() {
// Regression test for https://github.com/dart-lang/sdk/issues/27134
//
// We need to take a future union into account for both directions of
@@ -1758,6 +1758,20 @@
''');
}
+ void test_futureUnion_downwardsGenericMethodWithGenericReturn() {
+ // Regression test for https://github.com/dart-lang/sdk/issues/27284
+ checkFile(r'''
+import 'dart:async';
+
+/*=T*/ id/*<T>*/(/*=T*/ x) => x;
+
+main() async {
+ Future<String> f;
+ String s = await id(f);
+}
+ ''');
+ }
+
void test_futureUnion_upwardsGenericMethods() {
// Regression test for https://github.com/dart-lang/sdk/issues/27151
checkFile(r'''
diff --git a/pkg/analyzer_cli/test/driver_test.dart b/pkg/analyzer_cli/test/driver_test.dart
index 0a41705..b0875ab 100644
--- a/pkg/analyzer_cli/test/driver_test.dart
+++ b/pkg/analyzer_cli/test/driver_test.dart
@@ -298,7 +298,7 @@
ErrorSeverity.WARNING);
// Should not be made fatal by `--fatal-warnings`.
expect(outSink.toString(),
- contains("[warning] The function 'baz' is not defined"));
+ contains("[warning] The function 'baz' isn't defined"));
expect(
outSink.toString(), contains("1 error and 1 warning found."));
});
diff --git a/pkg/analyzer_cli/test/error_test.dart b/pkg/analyzer_cli/test/error_test.dart
index c1c7988..f71a212 100644
--- a/pkg/analyzer_cli/test/error_test.dart
+++ b/pkg/analyzer_cli/test/error_test.dart
@@ -22,21 +22,21 @@
expect(
errorsForFile('void foo;\n'),
equals(
- "Error in test.dart: Variables cannot have a type of 'void'\n"));
+ "Error in test.dart: Variables can't have a type of 'void'.\n"));
});
test("an error on the last line", () {
expect(
errorsForFile('\nvoid foo;'),
equals(
- "Error in test.dart: Variables cannot have a type of 'void'\n"));
+ "Error in test.dart: Variables can't have a type of 'void'.\n"));
});
test("an error in the middle", () {
expect(
errorsForFile('\nvoid foo;\n'),
equals(
- "Error in test.dart: Variables cannot have a type of 'void'\n"));
+ "Error in test.dart: Variables can't have a type of 'void'.\n"));
});
var veryLongString = new List.filled(107, ' ').join('');
@@ -45,21 +45,21 @@
expect(
errorsForFile('$veryLongString void foo;'),
equals(
- "Error in test.dart: Variables cannot have a type of 'void'\n"));
+ "Error in test.dart: Variables can't have a type of 'void'.\n"));
});
test("an error at the beginning of a very long line", () {
expect(
errorsForFile('void foo; $veryLongString'),
equals(
- "Error in test.dart: Variables cannot have a type of 'void'\n"));
+ "Error in test.dart: Variables can't have a type of 'void'.\n"));
});
test("an error in the middle of a very long line", () {
expect(
errorsForFile('$veryLongString void foo;$veryLongString'),
equals(
- "Error in test.dart: Variables cannot have a type of 'void'\n"));
+ "Error in test.dart: Variables can't have a type of 'void'.\n"));
});
});
}
diff --git a/pkg/analyzer_cli/test/super_mixin_test.dart b/pkg/analyzer_cli/test/super_mixin_test.dart
index 8606005..f890289 100644
--- a/pkg/analyzer_cli/test/super_mixin_test.dart
+++ b/pkg/analyzer_cli/test/super_mixin_test.dart
@@ -45,11 +45,11 @@
expect(
stdout,
contains(
- "[error] The class 'C' cannot be used as a mixin because it extends a class other than Object"));
+ "[error] The class 'C' can't be used as a mixin because it extends a class other than Object"));
expect(
stdout,
contains(
- "[error] The class 'C' cannot be used as a mixin because it references 'super'"));
+ "[error] The class 'C' can't be used as a mixin because it references 'super'"));
expect(stdout, contains('2 errors found.'));
expect(errorSink.toString(), '');
});
diff --git a/pkg/compiler/lib/src/diagnostics/messages.dart b/pkg/compiler/lib/src/diagnostics/messages.dart
index 63fa370..05ef3e7 100644
--- a/pkg/compiler/lib/src/diagnostics/messages.dart
+++ b/pkg/compiler/lib/src/diagnostics/messages.dart
@@ -430,6 +430,7 @@
TYPE_VARIABLE_IN_CONSTANT,
TYPE_VARIABLE_WITHIN_STATIC_MEMBER,
TYPE_VARIABLE_FROM_METHOD_NOT_REIFIED,
+ TYPE_VARIABLE_FROM_METHOD_CONSIDERED_DYNAMIC,
TYPEDEF_FORMAL_WITH_DEFAULT,
UNARY_OPERATOR_BAD_ARITY,
UNBOUND_LABEL,
@@ -1232,7 +1233,17 @@
bool f<T>(Object o) => o is T;
main() => f<int>(42);
-""",
+"""
+ ]),
+
+ MessageKind.TYPE_VARIABLE_FROM_METHOD_CONSIDERED_DYNAMIC:
+ const MessageTemplate(
+ MessageKind.TYPE_VARIABLE_FROM_METHOD_CONSIDERED_DYNAMIC,
+ "Method type variables are treated as `dynamic` in `as` expressions.",
+ options: const ["--generic-method-syntax"],
+ howToFix: "Try using the upper bound of the type variable, or check "
+ "that the blind success of the test does not introduce bugs.",
+ examples: const [
"""
// Method type variables are not reified, so they cannot be tested dynamically.
bool f<T>(Object o) => o as T;
diff --git a/pkg/compiler/lib/src/elements/common.dart b/pkg/compiler/lib/src/elements/common.dart
index 3e430d2..6ab5de2 100644
--- a/pkg/compiler/lib/src/elements/common.dart
+++ b/pkg/compiler/lib/src/elements/common.dart
@@ -215,20 +215,22 @@
* When called on the implementation element both members declared in the
* origin and the patch class are returned.
*/
- Element lookupByName(Name memberName) {
- return internalLookupByName(memberName, isSuperLookup: false);
+ Element lookupByName(Name memberName, {ClassElement stopAt}) {
+ return internalLookupByName(memberName,
+ isSuperLookup: false, stopAtSuperclass: stopAt);
}
Element lookupSuperByName(Name memberName) {
return internalLookupByName(memberName, isSuperLookup: true);
}
- Element internalLookupByName(Name memberName, {bool isSuperLookup}) {
+ Element internalLookupByName(Name memberName,
+ {bool isSuperLookup, ClassElement stopAtSuperclass}) {
String name = memberName.text;
bool isPrivate = memberName.isPrivate;
LibraryElement library = memberName.library;
for (ClassElement current = isSuperLookup ? superclass : this;
- current != null;
+ current != null && current != stopAtSuperclass;
current = current.superclass) {
Element member = current.lookupLocalMember(name);
if (member == null && current.isPatched) {
diff --git a/pkg/compiler/lib/src/elements/elements.dart b/pkg/compiler/lib/src/elements/elements.dart
index 29e2396..e854e4d 100644
--- a/pkg/compiler/lib/src/elements/elements.dart
+++ b/pkg/compiler/lib/src/elements/elements.dart
@@ -1555,7 +1555,13 @@
void reverseBackendMembers();
Element lookupMember(String memberName);
- Element lookupByName(Name memberName);
+
+ /// Looks up a class instance member declared or inherited in this class
+ /// using [memberName] to match the (private) name and getter/setter property.
+ ///
+ /// This method recursively visits superclasses until the member is found or
+ /// [stopAt] is reached.
+ Element lookupByName(Name memberName, {ClassElement stopAt});
Element lookupSuperByName(Name memberName);
Element lookupLocalMember(String memberName);
diff --git a/pkg/compiler/lib/src/enqueue.dart b/pkg/compiler/lib/src/enqueue.dart
index 271e3ec..12c5a42 100644
--- a/pkg/compiler/lib/src/enqueue.dart
+++ b/pkg/compiler/lib/src/enqueue.dart
@@ -600,6 +600,10 @@
case StaticUseKind.CONST_CONSTRUCTOR_INVOKE:
registerTypeUse(new TypeUse.instantiation(staticUse.type));
break;
+ case StaticUseKind.DIRECT_INVOKE:
+ invariant(
+ element, 'Direct static use is not supported for resolution.');
+ break;
}
if (addElement) {
addToWorkList(element);
diff --git a/pkg/compiler/lib/src/inferrer/inferrer_visitor.dart b/pkg/compiler/lib/src/inferrer/inferrer_visitor.dart
index bff02bd..d011dc0 100644
--- a/pkg/compiler/lib/src/inferrer/inferrer_visitor.dart
+++ b/pkg/compiler/lib/src/inferrer/inferrer_visitor.dart
@@ -958,13 +958,6 @@
}
}
- T _superType;
- T get superType {
- if (_superType != null) return _superType;
- return _superType =
- types.nonNullExact(outermostElement.enclosingClass.superclass);
- }
-
@override
T visitThisGet(Identifier node, _) {
return thisType;
@@ -974,7 +967,7 @@
if (node.isThis()) {
return thisType;
} else if (node.isSuper()) {
- return superType;
+ return internalError(node, 'Unexpected expression $node.');
} else {
Element element = elements[node];
if (Elements.isLocal(element)) {
diff --git a/pkg/compiler/lib/src/inferrer/simple_types_inferrer.dart b/pkg/compiler/lib/src/inferrer/simple_types_inferrer.dart
index f56483d..7aba120 100644
--- a/pkg/compiler/lib/src/inferrer/simple_types_inferrer.dart
+++ b/pkg/compiler/lib/src/inferrer/simple_types_inferrer.dart
@@ -6,7 +6,7 @@
import '../closure.dart' show ClosureClassMap;
import '../common.dart';
-import '../common/names.dart' show Selectors;
+import '../common/names.dart' show Identifiers, Selectors;
import '../compiler.dart' show Compiler;
import '../constants/values.dart' show ConstantValue, IntConstantValue;
import '../core_types.dart' show CoreClasses, CoreTypes;
@@ -878,23 +878,66 @@
T visitSuperIndexPrefix(ast.Send node, MethodElement getter,
MethodElement setter, ast.Node index, op.IncDecOperator operator, _) {
T indexType = visit(index);
- return handleCompoundPrefixPostfix(node, superType, indexType);
+ return handleSuperIndexPrefixPostfix(node, getter, setter, indexType);
}
@override
T visitSuperIndexPostfix(ast.Send node, MethodElement getter,
MethodElement setter, ast.Node index, op.IncDecOperator operator, _) {
T indexType = visit(index);
- return handleCompoundPrefixPostfix(node, superType, indexType);
+ return handleSuperIndexPrefixPostfix(node, getter, setter, indexType);
+ }
+
+ /// Handle compound prefix/postfix operations, like `super[0]++`.
+ T handleSuperIndexPrefixPostfix(
+ ast.Send node, Element getter, Element setter, T indexType) {
+ return _handleSuperCompoundIndexSet(
+ node, getter, setter, indexType, types.uint31Type);
}
/// Handle compound super index set, like `super[42] =+ 2`.
- T handleSuperCompoundIndexSet(
- ast.SendSet node, ast.Node index, ast.Node rhs) {
- T receiverType = superType;
+ T handleSuperCompoundIndexSet(ast.SendSet node, Element getter,
+ Element setter, ast.Node index, ast.Node rhs) {
T indexType = visit(index);
T rhsType = visit(rhs);
- return handleCompoundIndexSet(node, receiverType, indexType, rhsType);
+ return _handleSuperCompoundIndexSet(
+ node, getter, setter, indexType, rhsType);
+ }
+
+ T _handleSuperCompoundIndexSet(ast.SendSet node, Element getter,
+ Element setter, T indexType, T rhsType) {
+ Selector getterSelector = elements.getGetterSelectorInComplexSendSet(node);
+ TypeMask getterMask = elements.getGetterTypeMaskInComplexSendSet(node);
+ Selector setterSelector = elements.getSelector(node);
+ TypeMask setterMask = elements.getTypeMask(node);
+
+ T getterType = handleSuperSend(node, getterSelector, getterMask, getter,
+ new ArgumentsTypes<T>([indexType], null));
+
+ T returnType;
+ if (node.isIfNullAssignment) {
+ returnType = types.allocateDiamondPhi(getterType, rhsType);
+ } else {
+ Selector operatorSelector =
+ elements.getOperatorSelectorInComplexSendSet(node);
+ TypeMask operatorMask =
+ elements.getOperatorTypeMaskInComplexSendSet(node);
+ returnType = handleDynamicSend(node, operatorSelector, operatorMask,
+ getterType, new ArgumentsTypes<T>([rhsType], null));
+ }
+ handleSuperSend(node, setterSelector, setterMask, setter,
+ new ArgumentsTypes<T>([indexType, returnType], null));
+
+ return node.isPostfix ? getterType : returnType;
+ }
+
+ T handleSuperSend(ast.Node node, Selector selector, TypeMask mask,
+ Element element, ArgumentsTypes arguments) {
+ if (element.isMalformed) {
+ return handleSuperNoSuchMethod(node, selector, mask, arguments);
+ } else {
+ return handleStaticSend(node, selector, mask, element, arguments);
+ }
}
@override
@@ -906,25 +949,25 @@
op.AssignmentOperator operator,
ast.Node rhs,
_) {
- return handleSuperCompoundIndexSet(node, index, rhs);
+ return handleSuperCompoundIndexSet(node, getter, setter, index, rhs);
}
@override
T visitSuperIndexSetIfNull(ast.SendSet node, MethodElement getter,
MethodElement setter, ast.Node index, ast.Node rhs, _) {
- return handleSuperCompoundIndexSet(node, index, rhs);
+ return handleSuperCompoundIndexSet(node, getter, setter, index, rhs);
}
@override
T visitUnresolvedSuperCompoundIndexSet(ast.Send node, Element element,
ast.Node index, op.AssignmentOperator operator, ast.Node rhs, _) {
- return handleSuperCompoundIndexSet(node, index, rhs);
+ return handleSuperCompoundIndexSet(node, element, element, index, rhs);
}
@override
T visitUnresolvedSuperIndexSetIfNull(
ast.Send node, Element element, ast.Node index, ast.Node rhs, _) {
- return handleSuperCompoundIndexSet(node, index, rhs);
+ return handleSuperCompoundIndexSet(node, element, element, index, rhs);
}
@override
@@ -936,13 +979,13 @@
op.AssignmentOperator operator,
ast.Node rhs,
_) {
- return handleSuperCompoundIndexSet(node, index, rhs);
+ return handleSuperCompoundIndexSet(node, element, setter, index, rhs);
}
@override
T visitUnresolvedSuperGetterIndexSetIfNull(ast.SendSet node, Element element,
MethodElement setter, ast.Node index, ast.Node rhs, _) {
- return handleSuperCompoundIndexSet(node, index, rhs);
+ return handleSuperCompoundIndexSet(node, element, setter, index, rhs);
}
@override
@@ -954,27 +997,27 @@
op.AssignmentOperator operator,
ast.Node rhs,
_) {
- return handleSuperCompoundIndexSet(node, index, rhs);
+ return handleSuperCompoundIndexSet(node, getter, element, index, rhs);
}
@override
T visitUnresolvedSuperSetterIndexSetIfNull(ast.SendSet node,
MethodElement getter, Element element, ast.Node index, ast.Node rhs, _) {
- return handleSuperCompoundIndexSet(node, index, rhs);
+ return handleSuperCompoundIndexSet(node, getter, element, index, rhs);
}
@override
T visitUnresolvedSuperIndexPrefix(ast.Send node, Element element,
ast.Node index, op.IncDecOperator operator, _) {
T indexType = visit(index);
- return handleCompoundPrefixPostfix(node, superType, indexType);
+ return handleSuperIndexPrefixPostfix(node, element, element, indexType);
}
@override
T visitUnresolvedSuperGetterIndexPrefix(ast.SendSet node, Element element,
MethodElement setter, ast.Node index, op.IncDecOperator operator, _) {
T indexType = visit(index);
- return handleCompoundPrefixPostfix(node, superType, indexType);
+ return handleSuperIndexPrefixPostfix(node, element, setter, indexType);
}
@override
@@ -986,21 +1029,21 @@
op.IncDecOperator operator,
_) {
T indexType = visit(index);
- return handleCompoundPrefixPostfix(node, superType, indexType);
+ return handleSuperIndexPrefixPostfix(node, getter, element, indexType);
}
@override
T visitUnresolvedSuperIndexPostfix(ast.Send node, Element element,
ast.Node index, op.IncDecOperator operator, _) {
T indexType = visit(index);
- return handleCompoundPrefixPostfix(node, superType, indexType);
+ return handleSuperIndexPrefixPostfix(node, element, element, indexType);
}
@override
T visitUnresolvedSuperGetterIndexPostfix(ast.SendSet node, Element element,
MethodElement setter, ast.Node index, op.IncDecOperator operator, _) {
T indexType = visit(index);
- return handleCompoundPrefixPostfix(node, superType, indexType);
+ return handleSuperIndexPrefixPostfix(node, element, setter, indexType);
}
@override
@@ -1012,7 +1055,242 @@
op.IncDecOperator operator,
_) {
T indexType = visit(index);
- return handleCompoundPrefixPostfix(node, superType, indexType);
+ return handleSuperIndexPrefixPostfix(node, getter, element, indexType);
+ }
+
+ @override
+ T visitSuperFieldCompound(ast.Send node, FieldElement field,
+ op.AssignmentOperator operator, ast.Node rhs, _) {
+ return handleSuperCompound(node, field, field, rhs);
+ }
+
+ @override
+ T visitSuperFieldSetterCompound(ast.Send node, FieldElement field,
+ FunctionElement setter, op.AssignmentOperator operator, ast.Node rhs, _) {
+ return handleSuperCompound(node, field, setter, rhs);
+ }
+
+ @override
+ T visitSuperGetterFieldCompound(ast.Send node, FunctionElement getter,
+ FieldElement field, op.AssignmentOperator operator, ast.Node rhs, _) {
+ return handleSuperCompound(node, getter, field, rhs);
+ }
+
+ @override
+ T visitSuperGetterSetterCompound(ast.Send node, FunctionElement getter,
+ FunctionElement setter, op.AssignmentOperator operator, ast.Node rhs, _) {
+ return handleSuperCompound(node, getter, setter, rhs);
+ }
+
+ @override
+ T visitSuperMethodSetterCompound(ast.Send node, FunctionElement method,
+ FunctionElement setter, op.AssignmentOperator operator, ast.Node rhs, _) {
+ return handleSuperCompound(node, method, setter, rhs);
+ }
+
+ @override
+ T visitUnresolvedSuperCompound(ast.Send node, Element element,
+ op.AssignmentOperator operator, ast.Node rhs, _) {
+ return handleSuperCompound(node, element, element, rhs);
+ }
+
+ @override
+ T visitUnresolvedSuperGetterCompound(ast.Send node, Element getter,
+ SetterElement setter, op.AssignmentOperator operator, ast.Node rhs, _) {
+ return handleSuperCompound(node, getter, setter, rhs);
+ }
+
+ @override
+ T visitUnresolvedSuperSetterCompound(ast.Send node, GetterElement getter,
+ Element setter, op.AssignmentOperator operator, ast.Node rhs, _) {
+ return handleSuperCompound(node, getter, setter, rhs);
+ }
+
+ @override
+ T visitSuperFieldFieldSetIfNull(ast.Send node, FieldElement readField,
+ FieldElement writtenField, ast.Node rhs, _) {
+ return handleSuperCompound(node, readField, writtenField, rhs);
+ }
+
+ @override
+ T visitSuperFieldSetIfNull(
+ ast.Send node, FieldElement field, ast.Node rhs, _) {
+ return handleSuperCompound(node, field, field, rhs);
+ }
+
+ @override
+ T visitSuperFieldSetterSetIfNull(ast.Send node, FieldElement field,
+ FunctionElement setter, ast.Node rhs, _) {
+ return handleSuperCompound(node, field, setter, rhs);
+ }
+
+ @override
+ T visitSuperGetterFieldSetIfNull(ast.Send node, FunctionElement getter,
+ FieldElement field, ast.Node rhs, _) {
+ return handleSuperCompound(node, getter, field, rhs);
+ }
+
+ @override
+ T visitSuperGetterSetterSetIfNull(ast.Send node, FunctionElement getter,
+ FunctionElement setter, ast.Node rhs, _) {
+ return handleSuperCompound(node, getter, setter, rhs);
+ }
+
+ @override
+ T visitSuperMethodSetIfNull(
+ ast.Send node, FunctionElement method, ast.Node rhs, _) {
+ return handleSuperCompound(node, method, null, rhs);
+ }
+
+ @override
+ T visitSuperMethodSetterSetIfNull(ast.Send node, FunctionElement method,
+ FunctionElement setter, ast.Node rhs, _) {
+ return handleSuperCompound(node, method, setter, rhs);
+ }
+
+ T handleSuperCompound(
+ ast.SendSet node, Element getter, Element setter, ast.Node rhs) {
+ T rhsType = visit(rhs);
+ return _handleSuperCompound(node, getter, setter, rhsType);
+ }
+
+ @override
+ T visitSuperFieldFieldPostfix(ast.SendSet node, FieldElement readField,
+ FieldElement writtenField, op.IncDecOperator operator, _) {
+ return handleSuperPrefixPostfix(node, readField, writtenField);
+ }
+
+ @override
+ T visitSuperFieldFieldPrefix(ast.SendSet node, FieldElement readField,
+ FieldElement writtenField, op.IncDecOperator operator, _) {
+ return handleSuperPrefixPostfix(node, readField, writtenField);
+ }
+
+ @override
+ T visitSuperFieldPostfix(
+ ast.SendSet node, FieldElement field, op.IncDecOperator operator, _) {
+ return handleSuperPrefixPostfix(node, field, field);
+ }
+
+ @override
+ T visitSuperFieldPrefix(
+ ast.SendSet node, FieldElement field, op.IncDecOperator operator, _) {
+ return handleSuperPrefixPostfix(node, field, field);
+ }
+
+ @override
+ T visitSuperFieldSetterPostfix(ast.SendSet node, FieldElement field,
+ FunctionElement setter, op.IncDecOperator operator, _) {
+ return handleSuperPrefixPostfix(node, field, setter);
+ }
+
+ @override
+ T visitSuperFieldSetterPrefix(ast.SendSet node, FieldElement field,
+ FunctionElement setter, op.IncDecOperator operator, _) {
+ return handleSuperPrefixPostfix(node, field, setter);
+ }
+
+ @override
+ T visitSuperGetterFieldPostfix(ast.SendSet node, FunctionElement getter,
+ FieldElement field, op.IncDecOperator operator, _) {
+ return handleSuperPrefixPostfix(node, getter, field);
+ }
+
+ @override
+ T visitSuperGetterFieldPrefix(ast.SendSet node, FunctionElement getter,
+ FieldElement field, op.IncDecOperator operator, _) {
+ return handleSuperPrefixPostfix(node, getter, field);
+ }
+
+ @override
+ T visitSuperGetterSetterPostfix(ast.SendSet node, FunctionElement getter,
+ FunctionElement setter, op.IncDecOperator operator, _) {
+ return handleSuperPrefixPostfix(node, getter, setter);
+ }
+
+ @override
+ T visitSuperGetterSetterPrefix(ast.SendSet node, FunctionElement getter,
+ FunctionElement setter, op.IncDecOperator operator, _) {
+ return handleSuperPrefixPostfix(node, getter, setter);
+ }
+
+ @override
+ T visitSuperMethodSetterPostfix(ast.SendSet node, FunctionElement method,
+ FunctionElement setter, op.IncDecOperator operator, _) {
+ return handleSuperPrefixPostfix(node, method, setter);
+ }
+
+ @override
+ T visitSuperMethodSetterPrefix(ast.SendSet node, FunctionElement method,
+ FunctionElement setter, op.IncDecOperator operator, _) {
+ return handleSuperPrefixPostfix(node, method, setter);
+ }
+
+ @override
+ T visitUnresolvedSuperPrefix(
+ ast.SendSet node, Element element, op.IncDecOperator operator, _) {
+ return handleSuperPrefixPostfix(node, element, element);
+ }
+
+ @override
+ T visitUnresolvedSuperPostfix(
+ ast.SendSet node, Element element, op.IncDecOperator operator, _) {
+ return handleSuperPrefixPostfix(node, element, element);
+ }
+
+ @override
+ T visitUnresolvedSuperGetterPrefix(ast.SendSet node, Element getter,
+ SetterElement setter, op.IncDecOperator operator, _) {
+ return handleSuperPrefixPostfix(node, getter, setter);
+ }
+
+ @override
+ T visitUnresolvedSuperGetterPostfix(ast.SendSet node, Element getter,
+ SetterElement setter, op.IncDecOperator operator, _) {
+ return handleSuperPrefixPostfix(node, getter, setter);
+ }
+
+ @override
+ T visitUnresolvedSuperSetterPrefix(ast.SendSet node, GetterElement getter,
+ Element setter, op.IncDecOperator operator, _) {
+ return handleSuperPrefixPostfix(node, getter, setter);
+ }
+
+ @override
+ T visitUnresolvedSuperSetterPostfix(ast.SendSet node, GetterElement getter,
+ Element setter, op.IncDecOperator operator, _) {
+ return handleSuperPrefixPostfix(node, getter, setter);
+ }
+
+ T handleSuperPrefixPostfix(ast.SendSet node, Element getter, Element setter) {
+ return _handleSuperCompound(node, getter, setter, types.uint31Type);
+ }
+
+ T _handleSuperCompound(
+ ast.SendSet node, Element getter, Element setter, T rhsType) {
+ Selector getterSelector = elements.getGetterSelectorInComplexSendSet(node);
+ TypeMask getterMask = elements.getGetterTypeMaskInComplexSendSet(node);
+ Selector setterSelector = elements.getSelector(node);
+ TypeMask setterMask = elements.getTypeMask(node);
+
+ T getterType =
+ handleSuperSend(node, getterSelector, getterMask, getter, null);
+
+ T returnType;
+ if (node.isIfNullAssignment) {
+ returnType = types.allocateDiamondPhi(getterType, rhsType);
+ } else {
+ Selector operatorSelector =
+ elements.getOperatorSelectorInComplexSendSet(node);
+ TypeMask operatorMask =
+ elements.getOperatorTypeMaskInComplexSendSet(node);
+ returnType = handleDynamicSend(node, operatorSelector, operatorMask,
+ getterType, new ArgumentsTypes<T>([rhsType], null));
+ }
+ handleSuperSend(node, setterSelector, setterMask, setter,
+ new ArgumentsTypes<T>([returnType], null));
+
+ return node.isPostfix ? getterType : returnType;
}
/// Handle index set, like `foo[0] = 42`.
@@ -1034,23 +1312,27 @@
}
/// Handle super index set, like `super[42] = true`.
- T handleSuperIndexSet(ast.SendSet node, ast.Node index, ast.Node rhs) {
- T receiverType = superType;
+ T handleSuperIndexSet(
+ ast.SendSet node, Element element, ast.Node index, ast.Node rhs) {
T indexType = visit(index);
T rhsType = visit(rhs);
- return handleIndexSet(node, receiverType, indexType, rhsType);
+ Selector setterSelector = elements.getSelector(node);
+ TypeMask setterMask = elements.getTypeMask(node);
+ handleStaticSend(node, setterSelector, setterMask, element,
+ new ArgumentsTypes<T>([indexType, rhsType], null));
+ return rhsType;
}
@override
T visitSuperIndexSet(ast.SendSet node, FunctionElement function,
ast.Node index, ast.Node rhs, _) {
- return handleSuperIndexSet(node, index, rhs);
+ return handleSuperIndexSet(node, function, index, rhs);
}
@override
T visitUnresolvedSuperIndexSet(
ast.SendSet node, Element element, ast.Node index, ast.Node rhs, _) {
- return handleSuperIndexSet(node, index, rhs);
+ return handleSuperIndexSet(node, element, index, rhs);
}
T handlePlainAssignment(
@@ -1114,10 +1396,22 @@
TypeMask mask = elements.getTypeMask(node);
// TODO(herhut): We could do better here if we knew what we
// are calling does not expose this.
+ // TODO(johnniwinther): Do we still need this when calling directly?
isThisExposed = true;
+ return handleSuperNoSuchMethod(node, selector, mask, arguments);
+ }
+
+ T handleSuperNoSuchMethod(ast.Send node, Selector selector, TypeMask mask,
+ ArgumentsTypes arguments) {
// Ensure we create a node, to make explicit the call to the
// `noSuchMethod` handler.
- return handleDynamicSend(node, selector, mask, superType, arguments);
+ ClassElement cls = outermostElement.enclosingClass.declaration;
+ MethodElement element = cls.lookupSuperMember(Identifiers.noSuchMethod_);
+ if (!Selectors.noSuchMethod_.signatureApplies(element)) {
+ element = compiler.coreClasses.objectClass
+ .lookupMember(Identifiers.noSuchMethod_);
+ }
+ return handleStaticSend(node, selector, mask, element, arguments);
}
/// Handle a .call invocation on the values retrieved from the super
@@ -1162,6 +1456,28 @@
return handleStaticSend(node, selector, mask, element, null);
}
+ /// Handle update to a super field or setter [element].
+ T handleSuperSet(ast.Send node, Element element, ast.Node rhs) {
+ T rhsType = visit(rhs);
+ // TODO(herhut): We could do better here if we knew what we
+ // are calling does not expose this.
+ isThisExposed = true;
+ Selector selector = elements.getSelector(node);
+ TypeMask mask = elements.getTypeMask(node);
+ return handleStaticSend(
+ node, selector, mask, element, new ArgumentsTypes<T>([rhsType], null));
+ }
+
+ @override
+ T visitSuperFieldSet(ast.Send node, FieldElement method, ast.Node rhs, _) {
+ return handleSuperSet(node, method, rhs);
+ }
+
+ @override
+ T visitSuperSetterSet(ast.Send node, SetterElement field, ast.Node rhs, _) {
+ return handleSuperSet(node, field, rhs);
+ }
+
@override
T visitUnresolvedSuperIndex(
ast.Send node, Element element, ast.Node index, _) {
@@ -1196,6 +1512,17 @@
}
@override
+ T visitSuperMethodSet(ast.Send node, MethodElement method, ast.Node rhs, _) {
+ return handleErroneousSuperSend(node);
+ }
+
+ @override
+ T visitFinalSuperFieldSet(
+ ast.Send node, FieldElement method, ast.Node rhs, _) {
+ return handleErroneousSuperSend(node);
+ }
+
+ @override
T visitUnresolvedSuperSet(ast.Send node, Element element, ast.Node rhs, _) {
return handleErroneousSuperSend(node);
}
diff --git a/pkg/compiler/lib/src/js_backend/backend.dart b/pkg/compiler/lib/src/js_backend/backend.dart
index fe3684a..6ac1c15 100644
--- a/pkg/compiler/lib/src/js_backend/backend.dart
+++ b/pkg/compiler/lib/src/js_backend/backend.dart
@@ -2490,9 +2490,11 @@
return;
}
- if ((element.isFunction || element.isConstructor) &&
- annotations.noInline(element)) {
- inlineCache.markAsNonInlinable(element);
+ Element implementation = element.implementation;
+ if (element.isFunction || element.isConstructor) {
+ if (annotations.noInline(implementation)) {
+ inlineCache.markAsNonInlinable(implementation);
+ }
}
LibraryElement library = element.library;
diff --git a/pkg/compiler/lib/src/js_backend/enqueuer.dart b/pkg/compiler/lib/src/js_backend/enqueuer.dart
index 12872d8..a9736b8 100644
--- a/pkg/compiler/lib/src/js_backend/enqueuer.dart
+++ b/pkg/compiler/lib/src/js_backend/enqueuer.dart
@@ -25,6 +25,7 @@
LibraryElement,
Member,
MemberElement,
+ MethodElement,
Name,
TypedElement,
TypedefElement;
@@ -210,11 +211,7 @@
addToWorkList(function);
return;
}
- // Store the member in [instanceFunctionsByName] to catch
- // getters on the function.
- instanceFunctionsByName
- .putIfAbsent(memberName, () => new Set<Element>())
- .add(member);
+ _registerInstanceMethod(function);
if (_universe.hasInvocation(function, _world)) {
addToWorkList(function);
return;
@@ -246,6 +243,14 @@
.add(member);
}
+ // Store the member in [instanceFunctionsByName] to catch
+ // getters on the function.
+ void _registerInstanceMethod(MethodElement element) {
+ instanceFunctionsByName
+ .putIfAbsent(element.name, () => new Set<Element>())
+ .add(element);
+ }
+
void enableIsolateSupport() {}
void processInstantiatedClass(ClassElement cls) {
@@ -535,6 +540,9 @@
case StaticUseKind.CONST_CONSTRUCTOR_INVOKE:
registerTypeUse(new TypeUse.instantiation(staticUse.type));
break;
+ case StaticUseKind.DIRECT_INVOKE:
+ _registerInstanceMethod(staticUse.element);
+ break;
}
if (addElement) {
addToWorkList(element);
diff --git a/pkg/compiler/lib/src/resolution/members.dart b/pkg/compiler/lib/src/resolution/members.dart
index e508c83..86465be7 100644
--- a/pkg/compiler/lib/src/resolution/members.dart
+++ b/pkg/compiler/lib/src/resolution/members.dart
@@ -1151,7 +1151,7 @@
// about the error which will occur at runtime.
if (type is MethodTypeVariableType) {
reporter.reportWarningMessage(
- node, MessageKind.TYPE_VARIABLE_FROM_METHOD_NOT_REIFIED);
+ node, MessageKind.TYPE_VARIABLE_FROM_METHOD_CONSIDERED_DYNAMIC);
}
registry.registerTypeUse(new TypeUse.asCast(type));
diff --git a/pkg/compiler/lib/src/ssa/builder.dart b/pkg/compiler/lib/src/ssa/builder.dart
index f58597b..9e17d7a 100644
--- a/pkg/compiler/lib/src/ssa/builder.dart
+++ b/pkg/compiler/lib/src/ssa/builder.dart
@@ -1557,6 +1557,11 @@
assert(type != null);
type = localsHandler.substInContext(type);
HInstruction other = buildTypeConversion(original, type, kind);
+ // TODO(johnniwinther): This operation on `registry` may be inconsistent.
+ // If it is needed then it seems likely that similar invocations of
+ // `buildTypeConversion` in `SsaBuilder.visitAs` should also be followed by
+ // a similar operation on `registry`; otherwise, this one might not be
+ // needed.
registry?.registerTypeUse(new TypeUse.isCheck(type));
return other;
}
@@ -2461,15 +2466,13 @@
void visitAs(ast.Send node, ast.Node expression, DartType type, _) {
HInstruction expressionInstruction = visitAndPop(expression);
if (type.isMalformed) {
- String message;
if (type is MalformedType) {
ErroneousElement element = type.element;
- message = element.message;
+ generateTypeError(node, element.message);
} else {
assert(type is MethodTypeVariableType);
- message = "Method type variables are not reified.";
+ stack.add(expressionInstruction);
}
- generateTypeError(node, message);
} else {
HInstruction converted = buildTypeConversion(expressionInstruction,
localsHandler.substInContext(type), HTypeConversion.CAST_TYPE_CHECK);
diff --git a/pkg/compiler/lib/src/ssa/codegen.dart b/pkg/compiler/lib/src/ssa/codegen.dart
index e677afd..a50cffe 100644
--- a/pkg/compiler/lib/src/ssa/codegen.dart
+++ b/pkg/compiler/lib/src/ssa/codegen.dart
@@ -1676,7 +1676,6 @@
void registerMethodInvoke(HInvokeDynamic node) {
Selector selector = node.selector;
- TypeMask mask = getOptimizedSelectorFor(node, selector, node.mask);
// If we don't know what we're calling or if we are calling a getter,
// we need to register that fact that we may be calling a closure
@@ -1689,19 +1688,49 @@
Selector call = new Selector.callClosureFrom(selector);
registry.registerDynamicUse(new DynamicUse(call, null));
}
- registry.registerDynamicUse(new DynamicUse(selector, mask));
+ if (target != null) {
+ // This is a dynamic invocation which we have found to have a single
+ // target but for some reason haven't inlined. We are _still_ accessing
+ // the target dynamically but we don't need to enqueue more than target
+ // for this to work.
+ assert(invariant(node, selector.applies(target),
+ message: '$selector does not apply to $target'));
+ registry.registerStaticUse(
+ new StaticUse.directInvoke(target, selector.callStructure));
+ } else {
+ TypeMask mask = getOptimizedSelectorFor(node, selector, node.mask);
+ registry.registerDynamicUse(new DynamicUse(selector, mask));
+ }
}
void registerSetter(HInvokeDynamic node) {
- Selector selector = node.selector;
- TypeMask mask = getOptimizedSelectorFor(node, selector, node.mask);
- registry.registerDynamicUse(new DynamicUse(selector, mask));
+ if (node.element != null) {
+ // This is a dynamic update which we have found to have a single
+ // target but for some reason haven't inlined. We are _still_ accessing
+ // the target dynamically but we don't need to enqueue more than target
+ // for this to work.
+ registry.registerStaticUse(new StaticUse.directSet(node.element));
+ } else {
+ Selector selector = node.selector;
+ TypeMask mask = getOptimizedSelectorFor(node, selector, node.mask);
+ registry.registerDynamicUse(new DynamicUse(selector, mask));
+ }
}
void registerGetter(HInvokeDynamic node) {
- Selector selector = node.selector;
- TypeMask mask = getOptimizedSelectorFor(node, selector, node.mask);
- registry.registerDynamicUse(new DynamicUse(selector, mask));
+ if (node.element != null &&
+ (node.element.isGetter || node.element.isField)) {
+ // This is a dynamic read which we have found to have a single target but
+ // for some reason haven't inlined. We are _still_ accessing the target
+ // dynamically but we don't need to enqueue more than target for this to
+ // work. The test above excludes non-getter functions since the element
+ // represents two targets - a tearoff getter and the torn-off method.
+ registry.registerStaticUse(new StaticUse.directGet(node.element));
+ } else {
+ Selector selector = node.selector;
+ TypeMask mask = getOptimizedSelectorFor(node, selector, node.mask);
+ registry.registerDynamicUse(new DynamicUse(selector, mask));
+ }
}
visitInvokeDynamicSetter(HInvokeDynamicSetter node) {
diff --git a/pkg/compiler/lib/src/ssa/nodes.dart b/pkg/compiler/lib/src/ssa/nodes.dart
index 1b06943..adc2076 100644
--- a/pkg/compiler/lib/src/ssa/nodes.dart
+++ b/pkg/compiler/lib/src/ssa/nodes.dart
@@ -1627,6 +1627,11 @@
: super(selector, mask, element, inputs, type);
toString() => 'invoke dynamic getter: selector=$selector, mask=$mask';
accept(HVisitor visitor) => visitor.visitInvokeDynamicGetter(this);
+
+ bool get isTearOff => element != null && element.isFunction;
+
+ // There might be an interceptor input, so `inputs.last` is the dart receiver.
+ bool canThrow() => isTearOff ? inputs.last.canBeNull() : super.canThrow();
}
class HInvokeDynamicSetter extends HInvokeDynamicField {
@@ -1935,10 +1940,11 @@
int typeCode() => HInstruction.FOREIGN_CODE_TYPECODE;
bool typeEquals(other) => other is HForeignCode;
bool dataEquals(HForeignCode other) {
- return codeTemplate.source == other.codeTemplate.source;
+ return codeTemplate.source != null &&
+ codeTemplate.source == other.codeTemplate.source;
}
- String toString() => 'HForeignCode("${codeTemplate.source}", $inputs)';
+ String toString() => 'HForeignCode("${codeTemplate.source}")';
}
abstract class HInvokeBinary extends HInstruction {
diff --git a/pkg/compiler/lib/src/ssa/optimize.dart b/pkg/compiler/lib/src/ssa/optimize.dart
index e8c546a..cbc92f6 100644
--- a/pkg/compiler/lib/src/ssa/optimize.dart
+++ b/pkg/compiler/lib/src/ssa/optimize.dart
@@ -449,10 +449,10 @@
// TODO(ngeoffray): Also fold if it's a getter or variable.
if (element != null &&
element.isFunction
- // If we found out that the only target is a [:noSuchMethod:],
- // we just ignore it.
+ // If we found out that the only target is an implicitly called
+ // [:noSuchMethod:] we just ignore it.
&&
- element.name == node.selector.name) {
+ node.selector.applies(element)) {
FunctionElement method = element;
if (backend.isNative(method)) {
@@ -901,8 +901,22 @@
}
HInstruction receiver = node.getDartReceiver(compiler);
Element field = findConcreteFieldForDynamicAccess(receiver, node.selector);
- if (field == null) return node;
- return directFieldGet(receiver, field);
+ if (field != null) return directFieldGet(receiver, field);
+
+ if (node.element == null) {
+ Element element = compiler.closedWorld
+ .locateSingleElement(node.selector, receiver.instructionType);
+ if (element != null && element.name == node.selector.name) {
+ node.element = element;
+ if (element.isFunction) {
+ // A property extraction getter, aka a tear-off.
+ node.sideEffects.clearAllDependencies();
+ node.sideEffects.clearAllSideEffects();
+ node.setUseGvn(); // We don't care about identity of tear-offs.
+ }
+ }
+ }
+ return node;
}
HInstruction directFieldGet(HInstruction receiver, Element field) {
@@ -1065,10 +1079,11 @@
// be a class extending `Interceptor` then it can be called directly.
if (new TypeMask.nonNullSubclass(helpers.jsInterceptorClass, closedWorld)
.isDisjoint(input.instructionType, closedWorld)) {
+ var inputs = <HInstruction>[input, input]; // [interceptor, receiver].
HInstruction result = new HInvokeDynamicMethod(
selector,
input.instructionType, // receiver mask.
- <HInstruction>[input, input], // [interceptor, receiver].
+ inputs,
toStringType)..sourceInformation = node.sourceInformation;
return result;
}
diff --git a/pkg/compiler/lib/src/universe/class_set.dart b/pkg/compiler/lib/src/universe/class_set.dart
index 2dd892e..637fd16 100644
--- a/pkg/compiler/lib/src/universe/class_set.dart
+++ b/pkg/compiler/lib/src/universe/class_set.dart
@@ -461,6 +461,10 @@
return true;
}
+ Iterable<ClassHierarchyNode> get subtypeNodes {
+ return _subtypes ?? const <ClassHierarchyNode>[];
+ }
+
/// Returns an [Iterable] of the subclasses of [cls] possibly including [cls].
///
/// Subclasses are included if their instantiation properties intersect with
diff --git a/pkg/compiler/lib/src/universe/function_set.dart b/pkg/compiler/lib/src/universe/function_set.dart
index ac25450..677ffc5 100644
--- a/pkg/compiler/lib/src/universe/function_set.dart
+++ b/pkg/compiler/lib/src/universe/function_set.dart
@@ -51,8 +51,10 @@
return (node != null) ? node.contains(element) : false;
}
- /// Returns an object that allows iterating over all the functions
- /// that may be invoked with the given [selector].
+ /// Returns all the functions that may be invoked with the [selector] on a
+ /// receiver with the given [constraint]. The returned elements may include
+ /// noSuchMethod handlers that are potential targets indirectly through the
+ /// noSuchMethod mechanism.
Iterable<Element> filter(Selector selector, ReceiverConstraint constraint) {
return query(selector, constraint).functions;
}
diff --git a/pkg/compiler/lib/src/universe/use.dart b/pkg/compiler/lib/src/universe/use.dart
index fad9d90..7cb642e 100644
--- a/pkg/compiler/lib/src/universe/use.dart
+++ b/pkg/compiler/lib/src/universe/use.dart
@@ -73,6 +73,7 @@
CLOSURE,
CONSTRUCTOR_INVOKE,
CONST_CONSTRUCTOR_INVOKE,
+ DIRECT_INVOKE,
}
/// Statically known use of an [Element].
@@ -207,6 +208,35 @@
return new StaticUse.internal(element, StaticUseKind.GENERAL);
}
+ /// Direct invocation of a method [element] with the given [callStructure].
+ factory StaticUse.directInvoke(
+ MethodElement element, CallStructure callStructure) {
+ // TODO(johnniwinther): Use the [callStructure].
+ assert(invariant(element, element.isInstanceMember,
+ message: "Direct invoke element $element must be an instance member."));
+ assert(invariant(element, element.isFunction,
+ message: "Direct invoke element $element must be a method."));
+ return new StaticUse.internal(element, StaticUseKind.DIRECT_INVOKE);
+ }
+
+ /// Direct read access of a field or getter [element].
+ factory StaticUse.directGet(MemberElement element) {
+ assert(invariant(element, element.isInstanceMember,
+ message: "Direct get element $element must be an instance member."));
+ assert(invariant(element, element.isField || element.isGetter,
+ message: "Direct get element $element must be a field or a getter."));
+ return new StaticUse.internal(element, StaticUseKind.GENERAL);
+ }
+
+ /// Direct write access of a field [element].
+ factory StaticUse.directSet(FieldElement element) {
+ assert(invariant(element, element.isInstanceMember,
+ message: "Direct set element $element must be an instance member."));
+ assert(invariant(element, element.isField,
+ message: "Direct set element $element must be a field."));
+ return new StaticUse.internal(element, StaticUseKind.GENERAL);
+ }
+
/// Constructor invocation of [element] with the given [callStructure].
factory StaticUse.constructorInvoke(
ConstructorElement element, CallStructure callStructure) {
diff --git a/pkg/compiler/lib/src/universe/world_builder.dart b/pkg/compiler/lib/src/universe/world_builder.dart
index b697325..d574f3a 100644
--- a/pkg/compiler/lib/src/universe/world_builder.dart
+++ b/pkg/compiler/lib/src/universe/world_builder.dart
@@ -379,6 +379,10 @@
case StaticUseKind.CLOSURE:
allClosures.add(element);
break;
+ case StaticUseKind.DIRECT_INVOKE:
+ invariant(
+ element, 'Direct static use is not supported for resolution.');
+ break;
}
}
@@ -519,7 +523,7 @@
isNative
// Likewise, if this registration comes from the mirror system,
// all bets are off.
- // TODO(herhut): Track classes required by mirrors seperately.
+ // TODO(herhut): Track classes required by mirrors separately.
||
byMirrors) {
_directlyInstantiatedClasses.add(cls);
@@ -651,6 +655,7 @@
case StaticUseKind.FIELD_GET:
case StaticUseKind.CONSTRUCTOR_INVOKE:
case StaticUseKind.CONST_CONSTRUCTOR_INVOKE:
+ case StaticUseKind.DIRECT_INVOKE:
break;
}
}
diff --git a/pkg/compiler/lib/src/world.dart b/pkg/compiler/lib/src/world.dart
index 8c69bae..c6a20e0 100644
--- a/pkg/compiler/lib/src/world.dart
+++ b/pkg/compiler/lib/src/world.dart
@@ -728,16 +728,19 @@
: result.implementation == element.implementation;
}
- Element findMatchIn(ClassElement cls, Selector selector) {
+ Element findMatchIn(ClassElement cls, Selector selector,
+ {ClassElement stopAtSuperclass}) {
// Use the [:implementation] of [cls] in case the found [element]
// is in the patch class.
- var result = cls.implementation.lookupByName(selector.memberName);
+ var result = cls.implementation
+ .lookupByName(selector.memberName, stopAt: stopAtSuperclass);
return result;
}
/// Returns whether a [selector] call on an instance of [cls]
/// will hit a method at runtime, and not go through [noSuchMethod].
- bool hasConcreteMatch(ClassElement cls, Selector selector) {
+ bool hasConcreteMatch(ClassElement cls, Selector selector,
+ {ClassElement stopAtSuperclass}) {
assert(invariant(cls, isInstantiated(cls),
message: '$cls has not been instantiated.'));
Element element = findMatchIn(cls, selector);
@@ -753,35 +756,49 @@
@override
bool needsNoSuchMethod(
ClassElement base, Selector selector, ClassQuery query) {
- /// Returns `true` if [cls] is an instantiated class that does not have
- /// a concrete method matching [selector].
- bool needsNoSuchMethod(ClassElement cls) {
- // We can skip uninstantiated subclasses.
- if (!isInstantiated(cls)) {
+ /// Returns `true` if subclasses in the [rootNode] tree needs noSuchMethod
+ /// handling.
+ bool subclassesNeedNoSuchMethod(ClassHierarchyNode rootNode) {
+ if (!rootNode.isInstantiated) {
+ // No subclass needs noSuchMethod handling since they are all
+ // uninstantiated.
return false;
}
- // We can just skip abstract classes because we know no
- // instance of them will be created at runtime, and
- // therefore there is no instance that will require
- // [noSuchMethod] handling.
- return !cls.isAbstract && !hasConcreteMatch(cls, selector);
+ ClassElement rootClass = rootNode.cls;
+ if (hasConcreteMatch(rootClass, selector)) {
+ // The root subclass has a concrete implementation so no subclass needs
+ // noSuchMethod handling.
+ return false;
+ } else if (rootNode.isDirectlyInstantiated) {
+ // The root class need noSuchMethod handling.
+ return true;
+ }
+ IterationStep result = rootNode.forEachSubclass((ClassElement subclass) {
+ if (hasConcreteMatch(subclass, selector, stopAtSuperclass: rootClass)) {
+ // Found a match - skip all subclasses.
+ return IterationStep.SKIP_SUBCLASSES;
+ } else {
+ // Stop fast - we found a need for noSuchMethod handling.
+ return IterationStep.STOP;
+ }
+ }, ClassHierarchyNode.DIRECTLY_INSTANTIATED, strict: true);
+ // We stopped fast so we need noSuchMethod handling.
+ return result == IterationStep.STOP;
}
- bool baseNeedsNoSuchMethod = needsNoSuchMethod(base);
- if (query == ClassQuery.EXACT || baseNeedsNoSuchMethod) {
- return baseNeedsNoSuchMethod;
- }
-
- Iterable<ClassElement> subclassesToCheck;
- if (query == ClassQuery.SUBTYPE) {
- subclassesToCheck = strictSubtypesOf(base);
+ ClassSet classSet = getClassSet(base);
+ ClassHierarchyNode node = classSet.node;
+ if (query == ClassQuery.EXACT) {
+ return node.isDirectlyInstantiated && !hasConcreteMatch(base, selector);
+ } else if (query == ClassQuery.SUBCLASS) {
+ return subclassesNeedNoSuchMethod(node);
} else {
- assert(query == ClassQuery.SUBCLASS);
- subclassesToCheck = strictSubclassesOf(base);
+ if (subclassesNeedNoSuchMethod(node)) return true;
+ for (ClassHierarchyNode subtypeNode in classSet.subtypeNodes) {
+ if (subclassesNeedNoSuchMethod(subtypeNode)) return true;
+ }
+ return false;
}
-
- return subclassesToCheck != null &&
- subclassesToCheck.any(needsNoSuchMethod);
}
final Compiler _compiler;
diff --git a/pkg/dev_compiler/lib/js/amd/dart_sdk.js b/pkg/dev_compiler/lib/js/amd/dart_sdk.js
index b7dc69b..0fcf0ec 100644
--- a/pkg/dev_compiler/lib/js/amd/dart_sdk.js
+++ b/pkg/dev_compiler/lib/js/amd/dart_sdk.js
@@ -535,9 +535,9 @@
let ListOfTransform = () => (ListOfTransform = dart.constFn(core.List$(svg$.Transform)))();
let CompleterOfAudioBuffer = () => (CompleterOfAudioBuffer = dart.constFn(async.Completer$(web_audio.AudioBuffer)))();
let EventStreamProviderOfAudioProcessingEvent = () => (EventStreamProviderOfAudioProcessingEvent = dart.constFn(html$.EventStreamProvider$(web_audio.AudioProcessingEvent)))();
+ let dynamicTodynamic$ = () => (dynamicTodynamic$ = dart.constFn(dart.definiteFunctionType(dart.dynamic, [dart.dynamic])))();
let StringAndStringToint = () => (StringAndStringToint = dart.constFn(dart.definiteFunctionType(core.int, [core.String, core.String])))();
let VoidTo_MethodStats = () => (VoidTo_MethodStats = dart.constFn(dart.definiteFunctionType(dart._MethodStats, [])))();
- let dynamicTodynamic$ = () => (dynamicTodynamic$ = dart.constFn(dart.definiteFunctionType(dart.dynamic, [dart.dynamic])))();
let dynamicToString = () => (dynamicToString = dart.constFn(dart.definiteFunctionType(core.String, [dart.dynamic])))();
let dynamicToListOfString = () => (dynamicToListOfString = dart.constFn(dart.definiteFunctionType(ListOfString(), [dart.dynamic])))();
let dynamicToList = () => (dynamicToList = dart.constFn(dart.definiteFunctionType(core.List, [dart.dynamic])))();
@@ -1060,8 +1060,10 @@
derived.__proto__ = base;
};
dart.setExtensionBaseClass = function(derived, base) {
- derived.prototype[dart._extensionType] = derived;
- derived.prototype.__proto__ = base.prototype;
+ if (base) {
+ derived.prototype[dart._extensionType] = derived;
+ derived.prototype.__proto__ = base.prototype;
+ }
};
dart.callableClass = function(callableCtor, classExpr) {
callableCtor.prototype = classExpr.prototype;
@@ -1561,6 +1563,43 @@
dart.dgcall = function(f, typeArgs, ...args) {
return dart._checkAndCall(f, dart._getRuntimeType(f), void 0, typeArgs, args, 'call');
};
+ dart._dhelperRepl = function(object, field, callback) {
+ let rawField = field;
+ if (typeof field == 'symbol') {
+ if (field in object) return callback(field);
+ field = field.toString();
+ field = field.substring('Symbol('.length, field.length - 1);
+ } else if (field.charAt(0) != '_') {
+ return callback(field);
+ }
+ if (field in object) return callback(field);
+ let proto = object;
+ while (proto !== null) {
+ let symbols = Object.getOwnPropertySymbols(proto);
+ let target = 'Symbol(' + field + ')';
+ for (let s = 0; s < symbols.length; s++) {
+ let sym = symbols[s];
+ if (target == sym.toString()) return callback(sym);
+ }
+ proto = proto.__proto__;
+ }
+ return callback(rawField);
+ };
+ dart.dloadRepl = function(obj, field) {
+ return dart._dhelperRepl(obj, field, dart.fn(resolvedField => dart.dload(obj, resolvedField), dynamicTodynamic$()));
+ };
+ dart.dputRepl = function(obj, field, value) {
+ return dart._dhelperRepl(obj, field, dart.fn(resolvedField => dart.dput(obj, resolvedField, value), dynamicTodynamic$()));
+ };
+ dart._callMethodRepl = function(obj, method, typeArgs, args) {
+ return dart._dhelperRepl(obj, method, dart.fn(resolvedField => dart._callMethod(obj, resolvedField, typeArgs, args, method), dynamicTodynamic$()));
+ };
+ dart.dsendRepl = function(obj, method, ...args) {
+ return dart._callMethodRepl(obj, method, null, args);
+ };
+ dart.dgsendRepl = function(obj, typeArgs, method, ...args) {
+ return dart._callMethodRepl(obj, method, typeArgs, args);
+ };
dart.getDynamicStats = function() {
let ret = JSArrayOfListOfObject().of([]);
let keys = dart._callMethodStats[dartx.keys][dartx.toList]();
@@ -16290,6 +16329,7 @@
names: ['_create1', '_create2', '_create3']
});
dart.registerExtension(dart.global.Uint8ClampedArray, _native_typed_data.NativeUint8ClampedList);
+ dart.registerExtension(dart.global.CanvasPixelArray, _native_typed_data.NativeUint8ClampedList);
dart.defineExtensionNames([
'runtimeType',
'length',
@@ -39273,6 +39313,7 @@
}
});
dart.registerExtension(dart.global.IDBOpenDBRequest, indexed_db.OpenDBRequest);
+ dart.registerExtension(dart.global.IDBVersionChangeRequest, indexed_db.OpenDBRequest);
dart.defineExtensionNames([
'completed',
'abort',
@@ -39524,6 +39565,7 @@
html$.Event.BUBBLING_PHASE = 3;
html$.Event.CAPTURING_PHASE = 1;
dart.registerExtension(dart.global.Event, html$.Event);
+ dart.registerExtension(dart.global.InputEvent, html$.Event);
dart.defineExtensionNames([
'dataLoss',
'dataLossMessage',
@@ -42402,6 +42444,8 @@
}
});
dart.registerExtension(dart.global.ApplicationCache, html$.ApplicationCache);
+ dart.registerExtension(dart.global.DOMApplicationCache, html$.ApplicationCache);
+ dart.registerExtension(dart.global.OfflineResourceList, html$.ApplicationCache);
dart.defineExtensionNames([
'message',
'reason',
@@ -46221,6 +46265,8 @@
})
});
dart.registerExtension(dart.global.CSSKeyframeRule, html$.CssKeyframeRule);
+ dart.registerExtension(dart.global.MozCSSKeyframeRule, html$.CssKeyframeRule);
+ dart.registerExtension(dart.global.WebKitCSSKeyframeRule, html$.CssKeyframeRule);
dart.defineExtensionNames([
'appendRule',
'deleteRule',
@@ -46268,6 +46314,8 @@
})
});
dart.registerExtension(dart.global.CSSKeyframesRule, html$.CssKeyframesRule);
+ dart.registerExtension(dart.global.MozCSSKeyframesRule, html$.CssKeyframesRule);
+ dart.registerExtension(dart.global.WebKitCSSKeyframesRule, html$.CssKeyframesRule);
dart.defineExtensionNames([
'media'
]);
@@ -52009,6 +52057,8 @@
}
});
dart.registerExtension(dart.global.CSSStyleDeclaration, html$.CssStyleDeclaration);
+ dart.registerExtension(dart.global.MSStyleCSSProperties, html$.CssStyleDeclaration);
+ dart.registerExtension(dart.global.CSS2Properties, html$.CssStyleDeclaration);
const _elementIterable = Symbol('_elementIterable');
const _elementCssStyleDeclarationSetIterable = Symbol('_elementCssStyleDeclarationSetIterable');
const _setAll = Symbol('_setAll');
@@ -64485,6 +64535,7 @@
names: ['_create_1', '_create_2']
});
dart.registerExtension(dart.global.MouseEvent, html$.MouseEvent);
+ dart.registerExtension(dart.global.DragEvent, html$.MouseEvent);
html$.MutationCallback = dart.typedef('MutationCallback', () => dart.functionType(dart.void, [ListOfMutationRecord(), html$.MutationObserver]));
const _observe_1 = Symbol('_observe_1');
const _observe = Symbol('_observe');
@@ -64574,6 +64625,7 @@
});
html$.MutationObserver._boolKeys = dart.const(dart.map({childList: true, attributes: true, characterData: true, subtree: true, attributeOldValue: true, characterDataOldValue: true}, core.String, core.bool));
dart.registerExtension(dart.global.MutationObserver, html$.MutationObserver);
+ dart.registerExtension(dart.global.WebKitMutationObserver, html$.MutationObserver);
dart.defineExtensionNames([
'addedNodes',
'attributeName',
@@ -65379,6 +65431,7 @@
})
});
dart.registerExtension(dart.global.NodeList, html$.NodeList);
+ dart.registerExtension(dart.global.RadioNodeList, html$.NodeList);
dart.defineExtensionNames([
'nextElementSibling',
'previousElementSibling'
@@ -68297,6 +68350,7 @@
}
});
dart.registerExtension(dart.global.RTCDataChannel, html$.RtcDataChannel);
+ dart.registerExtension(dart.global.DataChannel, html$.RtcDataChannel);
dart.defineExtensionNames([
'channel'
]);
@@ -68439,6 +68493,7 @@
})
});
dart.registerExtension(dart.global.RTCIceCandidate, html$.RtcIceCandidate);
+ dart.registerExtension(dart.global.mozRTCIceCandidate, html$.RtcIceCandidate);
dart.defineExtensionNames([
'candidate'
]);
@@ -68455,6 +68510,7 @@
fields: () => ({[dartx.candidate]: html$.RtcIceCandidate})
});
dart.registerExtension(dart.global.RTCIceCandidateEvent, html$.RtcIceCandidateEvent);
+ dart.registerExtension(dart.global.RTCPeerConnectionIceEvent, html$.RtcIceCandidateEvent);
const _createOffer = Symbol('_createOffer');
const _createAnswer = Symbol('_createAnswer');
const _getStats = Symbol('_getStats');
@@ -68814,6 +68870,7 @@
}
});
dart.registerExtension(dart.global.RTCPeerConnection, html$.RtcPeerConnection);
+ dart.registerExtension(dart.global.mozRTCPeerConnection, html$.RtcPeerConnection);
dart.defineExtensionNames([
'sdp',
'type'
@@ -68850,6 +68907,7 @@
})
});
dart.registerExtension(dart.global.RTCSessionDescription, html$.RtcSessionDescription);
+ dart.registerExtension(dart.global.mozRTCSessionDescription, html$.RtcSessionDescription);
const _get_timestamp = Symbol('_get_timestamp');
dart.defineExtensionNames([
'timestamp',
@@ -71997,6 +72055,8 @@
})
});
dart.registerExtension(dart.global.HTMLTableCellElement, html$.TableCellElement);
+ dart.registerExtension(dart.global.HTMLTableDataCellElement, html$.TableCellElement);
+ dart.registerExtension(dart.global.HTMLTableHeaderCellElement, html$.TableCellElement);
dart.defineExtensionNames([
'span'
]);
@@ -73744,6 +73804,7 @@
names: ['_create_1', '_create_2']
});
dart.registerExtension(dart.global.TransitionEvent, html$.TransitionEvent);
+ dart.registerExtension(dart.global.WebKitTransitionEvent, html$.TransitionEvent);
dart.defineExtensionNames([
'firstChild',
'lastChild',
@@ -76242,6 +76303,7 @@
}
});
dart.registerExtension(dart.global.Window, html$.Window);
+ dart.registerExtension(dart.global.DOMWindow, html$.Window);
const _returnValue = Symbol('_returnValue');
html$._WrappedEvent = class _WrappedEvent extends core.Object {
new(wrapped) {
@@ -77200,6 +77262,7 @@
})
});
dart.registerExtension(dart.global.ClientRectList, html$._ClientRectList);
+ dart.registerExtension(dart.global.DOMRectList, html$._ClientRectList);
dart.defineExtensionNames([
'length',
'get',
@@ -77743,6 +77806,7 @@
})
});
dart.registerExtension(dart.global.NamedNodeMap, html$._NamedNodeMap);
+ dart.registerExtension(dart.global.MozNamedAttrMap, html$._NamedNodeMap);
html$._PagePopupController = class _PagePopupController extends _interceptors.Interceptor {
static _() {
dart.throw(new core.UnsupportedError("Not supported"));
@@ -90262,6 +90326,7 @@
})
});
dart.registerExtension(dart.global.AnalyserNode, web_audio.AnalyserNode);
+ dart.registerExtension(dart.global.RealtimeAnalyserNode, web_audio.AnalyserNode);
dart.defineExtensionNames([
'getChannelData',
'duration',
@@ -90581,6 +90646,7 @@
});
web_audio.AudioContext.completeEvent = dart.const(new (EventStreamProviderOfEvent())('complete'));
dart.registerExtension(dart.global.AudioContext, web_audio.AudioContext);
+ dart.registerExtension(dart.global.webkitAudioContext, web_audio.AudioContext);
dart.defineExtensionNames([
'maxChannelCount'
]);
@@ -90784,6 +90850,7 @@
constructors: () => ({_: dart.definiteFunctionType(web_audio.ChannelMergerNode, [])})
});
dart.registerExtension(dart.global.ChannelMergerNode, web_audio.ChannelMergerNode);
+ dart.registerExtension(dart.global.AudioChannelMerger, web_audio.ChannelMergerNode);
web_audio.ChannelSplitterNode = class ChannelSplitterNode extends web_audio.AudioNode {
static _() {
dart.throw(new core.UnsupportedError("Not supported"));
@@ -90793,6 +90860,7 @@
constructors: () => ({_: dart.definiteFunctionType(web_audio.ChannelSplitterNode, [])})
});
dart.registerExtension(dart.global.ChannelSplitterNode, web_audio.ChannelSplitterNode);
+ dart.registerExtension(dart.global.AudioChannelSplitter, web_audio.ChannelSplitterNode);
dart.defineExtensionNames([
'buffer',
'normalize'
@@ -90897,6 +90965,7 @@
fields: () => ({[dartx.gain]: web_audio.AudioParam})
});
dart.registerExtension(dart.global.GainNode, web_audio.GainNode);
+ dart.registerExtension(dart.global.AudioGainNode, web_audio.GainNode);
dart.defineExtensionNames([
'mediaElement'
]);
@@ -91046,6 +91115,7 @@
});
web_audio.OscillatorNode.endedEvent = dart.const(new (EventStreamProviderOfEvent())('ended'));
dart.registerExtension(dart.global.OscillatorNode, web_audio.OscillatorNode);
+ dart.registerExtension(dart.global.Oscillator, web_audio.OscillatorNode);
dart.defineExtensionNames([
'setOrientation',
'setPosition',
@@ -91140,6 +91210,8 @@
})
});
dart.registerExtension(dart.global.PannerNode, web_audio.PannerNode);
+ dart.registerExtension(dart.global.AudioPannerNode, web_audio.PannerNode);
+ dart.registerExtension(dart.global.webkitAudioPannerNode, web_audio.PannerNode);
web_audio.PeriodicWave = class PeriodicWave extends _interceptors.Interceptor {
static _() {
dart.throw(new core.UnsupportedError("Not supported"));
@@ -91177,6 +91249,7 @@
});
web_audio.ScriptProcessorNode.audioProcessEvent = dart.const(new (EventStreamProviderOfAudioProcessingEvent())('audioprocess'));
dart.registerExtension(dart.global.ScriptProcessorNode, web_audio.ScriptProcessorNode);
+ dart.registerExtension(dart.global.JavaScriptAudioNode, web_audio.ScriptProcessorNode);
dart.defineExtensionNames([
'curve',
'oversample'
@@ -93446,6 +93519,7 @@
})
});
dart.registerExtension(dart.global.WebGLLoseContext, web_gl.LoseContext);
+ dart.registerExtension(dart.global.WebGLExtensionLoseContext, web_gl.LoseContext);
web_gl.OesElementIndexUint = class OesElementIndexUint extends _interceptors.Interceptor {
static _() {
dart.throw(new core.UnsupportedError("Not supported"));
diff --git a/pkg/dev_compiler/lib/js/common/dart_sdk.js b/pkg/dev_compiler/lib/js/common/dart_sdk.js
index cbb4987..f10c72e 100644
--- a/pkg/dev_compiler/lib/js/common/dart_sdk.js
+++ b/pkg/dev_compiler/lib/js/common/dart_sdk.js
@@ -535,9 +535,9 @@
let ListOfTransform = () => (ListOfTransform = dart.constFn(core.List$(svg$.Transform)))();
let CompleterOfAudioBuffer = () => (CompleterOfAudioBuffer = dart.constFn(async.Completer$(web_audio.AudioBuffer)))();
let EventStreamProviderOfAudioProcessingEvent = () => (EventStreamProviderOfAudioProcessingEvent = dart.constFn(html$.EventStreamProvider$(web_audio.AudioProcessingEvent)))();
+ let dynamicTodynamic$ = () => (dynamicTodynamic$ = dart.constFn(dart.definiteFunctionType(dart.dynamic, [dart.dynamic])))();
let StringAndStringToint = () => (StringAndStringToint = dart.constFn(dart.definiteFunctionType(core.int, [core.String, core.String])))();
let VoidTo_MethodStats = () => (VoidTo_MethodStats = dart.constFn(dart.definiteFunctionType(dart._MethodStats, [])))();
- let dynamicTodynamic$ = () => (dynamicTodynamic$ = dart.constFn(dart.definiteFunctionType(dart.dynamic, [dart.dynamic])))();
let dynamicToString = () => (dynamicToString = dart.constFn(dart.definiteFunctionType(core.String, [dart.dynamic])))();
let dynamicToListOfString = () => (dynamicToListOfString = dart.constFn(dart.definiteFunctionType(ListOfString(), [dart.dynamic])))();
let dynamicToList = () => (dynamicToList = dart.constFn(dart.definiteFunctionType(core.List, [dart.dynamic])))();
@@ -1060,8 +1060,10 @@
derived.__proto__ = base;
};
dart.setExtensionBaseClass = function(derived, base) {
- derived.prototype[dart._extensionType] = derived;
- derived.prototype.__proto__ = base.prototype;
+ if (base) {
+ derived.prototype[dart._extensionType] = derived;
+ derived.prototype.__proto__ = base.prototype;
+ }
};
dart.callableClass = function(callableCtor, classExpr) {
callableCtor.prototype = classExpr.prototype;
@@ -1561,6 +1563,43 @@
dart.dgcall = function(f, typeArgs, ...args) {
return dart._checkAndCall(f, dart._getRuntimeType(f), void 0, typeArgs, args, 'call');
};
+ dart._dhelperRepl = function(object, field, callback) {
+ let rawField = field;
+ if (typeof field == 'symbol') {
+ if (field in object) return callback(field);
+ field = field.toString();
+ field = field.substring('Symbol('.length, field.length - 1);
+ } else if (field.charAt(0) != '_') {
+ return callback(field);
+ }
+ if (field in object) return callback(field);
+ let proto = object;
+ while (proto !== null) {
+ let symbols = Object.getOwnPropertySymbols(proto);
+ let target = 'Symbol(' + field + ')';
+ for (let s = 0; s < symbols.length; s++) {
+ let sym = symbols[s];
+ if (target == sym.toString()) return callback(sym);
+ }
+ proto = proto.__proto__;
+ }
+ return callback(rawField);
+ };
+ dart.dloadRepl = function(obj, field) {
+ return dart._dhelperRepl(obj, field, dart.fn(resolvedField => dart.dload(obj, resolvedField), dynamicTodynamic$()));
+ };
+ dart.dputRepl = function(obj, field, value) {
+ return dart._dhelperRepl(obj, field, dart.fn(resolvedField => dart.dput(obj, resolvedField, value), dynamicTodynamic$()));
+ };
+ dart._callMethodRepl = function(obj, method, typeArgs, args) {
+ return dart._dhelperRepl(obj, method, dart.fn(resolvedField => dart._callMethod(obj, resolvedField, typeArgs, args, method), dynamicTodynamic$()));
+ };
+ dart.dsendRepl = function(obj, method, ...args) {
+ return dart._callMethodRepl(obj, method, null, args);
+ };
+ dart.dgsendRepl = function(obj, typeArgs, method, ...args) {
+ return dart._callMethodRepl(obj, method, typeArgs, args);
+ };
dart.getDynamicStats = function() {
let ret = JSArrayOfListOfObject().of([]);
let keys = dart._callMethodStats[dartx.keys][dartx.toList]();
@@ -16290,6 +16329,7 @@
names: ['_create1', '_create2', '_create3']
});
dart.registerExtension(dart.global.Uint8ClampedArray, _native_typed_data.NativeUint8ClampedList);
+ dart.registerExtension(dart.global.CanvasPixelArray, _native_typed_data.NativeUint8ClampedList);
dart.defineExtensionNames([
'runtimeType',
'length',
@@ -39273,6 +39313,7 @@
}
});
dart.registerExtension(dart.global.IDBOpenDBRequest, indexed_db.OpenDBRequest);
+ dart.registerExtension(dart.global.IDBVersionChangeRequest, indexed_db.OpenDBRequest);
dart.defineExtensionNames([
'completed',
'abort',
@@ -39524,6 +39565,7 @@
html$.Event.BUBBLING_PHASE = 3;
html$.Event.CAPTURING_PHASE = 1;
dart.registerExtension(dart.global.Event, html$.Event);
+ dart.registerExtension(dart.global.InputEvent, html$.Event);
dart.defineExtensionNames([
'dataLoss',
'dataLossMessage',
@@ -42402,6 +42444,8 @@
}
});
dart.registerExtension(dart.global.ApplicationCache, html$.ApplicationCache);
+ dart.registerExtension(dart.global.DOMApplicationCache, html$.ApplicationCache);
+ dart.registerExtension(dart.global.OfflineResourceList, html$.ApplicationCache);
dart.defineExtensionNames([
'message',
'reason',
@@ -46221,6 +46265,8 @@
})
});
dart.registerExtension(dart.global.CSSKeyframeRule, html$.CssKeyframeRule);
+ dart.registerExtension(dart.global.MozCSSKeyframeRule, html$.CssKeyframeRule);
+ dart.registerExtension(dart.global.WebKitCSSKeyframeRule, html$.CssKeyframeRule);
dart.defineExtensionNames([
'appendRule',
'deleteRule',
@@ -46268,6 +46314,8 @@
})
});
dart.registerExtension(dart.global.CSSKeyframesRule, html$.CssKeyframesRule);
+ dart.registerExtension(dart.global.MozCSSKeyframesRule, html$.CssKeyframesRule);
+ dart.registerExtension(dart.global.WebKitCSSKeyframesRule, html$.CssKeyframesRule);
dart.defineExtensionNames([
'media'
]);
@@ -52009,6 +52057,8 @@
}
});
dart.registerExtension(dart.global.CSSStyleDeclaration, html$.CssStyleDeclaration);
+ dart.registerExtension(dart.global.MSStyleCSSProperties, html$.CssStyleDeclaration);
+ dart.registerExtension(dart.global.CSS2Properties, html$.CssStyleDeclaration);
const _elementIterable = Symbol('_elementIterable');
const _elementCssStyleDeclarationSetIterable = Symbol('_elementCssStyleDeclarationSetIterable');
const _setAll = Symbol('_setAll');
@@ -64485,6 +64535,7 @@
names: ['_create_1', '_create_2']
});
dart.registerExtension(dart.global.MouseEvent, html$.MouseEvent);
+ dart.registerExtension(dart.global.DragEvent, html$.MouseEvent);
html$.MutationCallback = dart.typedef('MutationCallback', () => dart.functionType(dart.void, [ListOfMutationRecord(), html$.MutationObserver]));
const _observe_1 = Symbol('_observe_1');
const _observe = Symbol('_observe');
@@ -64574,6 +64625,7 @@
});
html$.MutationObserver._boolKeys = dart.const(dart.map({childList: true, attributes: true, characterData: true, subtree: true, attributeOldValue: true, characterDataOldValue: true}, core.String, core.bool));
dart.registerExtension(dart.global.MutationObserver, html$.MutationObserver);
+ dart.registerExtension(dart.global.WebKitMutationObserver, html$.MutationObserver);
dart.defineExtensionNames([
'addedNodes',
'attributeName',
@@ -65379,6 +65431,7 @@
})
});
dart.registerExtension(dart.global.NodeList, html$.NodeList);
+ dart.registerExtension(dart.global.RadioNodeList, html$.NodeList);
dart.defineExtensionNames([
'nextElementSibling',
'previousElementSibling'
@@ -68297,6 +68350,7 @@
}
});
dart.registerExtension(dart.global.RTCDataChannel, html$.RtcDataChannel);
+ dart.registerExtension(dart.global.DataChannel, html$.RtcDataChannel);
dart.defineExtensionNames([
'channel'
]);
@@ -68439,6 +68493,7 @@
})
});
dart.registerExtension(dart.global.RTCIceCandidate, html$.RtcIceCandidate);
+ dart.registerExtension(dart.global.mozRTCIceCandidate, html$.RtcIceCandidate);
dart.defineExtensionNames([
'candidate'
]);
@@ -68455,6 +68510,7 @@
fields: () => ({[dartx.candidate]: html$.RtcIceCandidate})
});
dart.registerExtension(dart.global.RTCIceCandidateEvent, html$.RtcIceCandidateEvent);
+ dart.registerExtension(dart.global.RTCPeerConnectionIceEvent, html$.RtcIceCandidateEvent);
const _createOffer = Symbol('_createOffer');
const _createAnswer = Symbol('_createAnswer');
const _getStats = Symbol('_getStats');
@@ -68814,6 +68870,7 @@
}
});
dart.registerExtension(dart.global.RTCPeerConnection, html$.RtcPeerConnection);
+ dart.registerExtension(dart.global.mozRTCPeerConnection, html$.RtcPeerConnection);
dart.defineExtensionNames([
'sdp',
'type'
@@ -68850,6 +68907,7 @@
})
});
dart.registerExtension(dart.global.RTCSessionDescription, html$.RtcSessionDescription);
+ dart.registerExtension(dart.global.mozRTCSessionDescription, html$.RtcSessionDescription);
const _get_timestamp = Symbol('_get_timestamp');
dart.defineExtensionNames([
'timestamp',
@@ -71997,6 +72055,8 @@
})
});
dart.registerExtension(dart.global.HTMLTableCellElement, html$.TableCellElement);
+ dart.registerExtension(dart.global.HTMLTableDataCellElement, html$.TableCellElement);
+ dart.registerExtension(dart.global.HTMLTableHeaderCellElement, html$.TableCellElement);
dart.defineExtensionNames([
'span'
]);
@@ -73744,6 +73804,7 @@
names: ['_create_1', '_create_2']
});
dart.registerExtension(dart.global.TransitionEvent, html$.TransitionEvent);
+ dart.registerExtension(dart.global.WebKitTransitionEvent, html$.TransitionEvent);
dart.defineExtensionNames([
'firstChild',
'lastChild',
@@ -76242,6 +76303,7 @@
}
});
dart.registerExtension(dart.global.Window, html$.Window);
+ dart.registerExtension(dart.global.DOMWindow, html$.Window);
const _returnValue = Symbol('_returnValue');
html$._WrappedEvent = class _WrappedEvent extends core.Object {
new(wrapped) {
@@ -77200,6 +77262,7 @@
})
});
dart.registerExtension(dart.global.ClientRectList, html$._ClientRectList);
+ dart.registerExtension(dart.global.DOMRectList, html$._ClientRectList);
dart.defineExtensionNames([
'length',
'get',
@@ -77743,6 +77806,7 @@
})
});
dart.registerExtension(dart.global.NamedNodeMap, html$._NamedNodeMap);
+ dart.registerExtension(dart.global.MozNamedAttrMap, html$._NamedNodeMap);
html$._PagePopupController = class _PagePopupController extends _interceptors.Interceptor {
static _() {
dart.throw(new core.UnsupportedError("Not supported"));
@@ -90262,6 +90326,7 @@
})
});
dart.registerExtension(dart.global.AnalyserNode, web_audio.AnalyserNode);
+ dart.registerExtension(dart.global.RealtimeAnalyserNode, web_audio.AnalyserNode);
dart.defineExtensionNames([
'getChannelData',
'duration',
@@ -90581,6 +90646,7 @@
});
web_audio.AudioContext.completeEvent = dart.const(new (EventStreamProviderOfEvent())('complete'));
dart.registerExtension(dart.global.AudioContext, web_audio.AudioContext);
+ dart.registerExtension(dart.global.webkitAudioContext, web_audio.AudioContext);
dart.defineExtensionNames([
'maxChannelCount'
]);
@@ -90784,6 +90850,7 @@
constructors: () => ({_: dart.definiteFunctionType(web_audio.ChannelMergerNode, [])})
});
dart.registerExtension(dart.global.ChannelMergerNode, web_audio.ChannelMergerNode);
+ dart.registerExtension(dart.global.AudioChannelMerger, web_audio.ChannelMergerNode);
web_audio.ChannelSplitterNode = class ChannelSplitterNode extends web_audio.AudioNode {
static _() {
dart.throw(new core.UnsupportedError("Not supported"));
@@ -90793,6 +90860,7 @@
constructors: () => ({_: dart.definiteFunctionType(web_audio.ChannelSplitterNode, [])})
});
dart.registerExtension(dart.global.ChannelSplitterNode, web_audio.ChannelSplitterNode);
+ dart.registerExtension(dart.global.AudioChannelSplitter, web_audio.ChannelSplitterNode);
dart.defineExtensionNames([
'buffer',
'normalize'
@@ -90897,6 +90965,7 @@
fields: () => ({[dartx.gain]: web_audio.AudioParam})
});
dart.registerExtension(dart.global.GainNode, web_audio.GainNode);
+ dart.registerExtension(dart.global.AudioGainNode, web_audio.GainNode);
dart.defineExtensionNames([
'mediaElement'
]);
@@ -91046,6 +91115,7 @@
});
web_audio.OscillatorNode.endedEvent = dart.const(new (EventStreamProviderOfEvent())('ended'));
dart.registerExtension(dart.global.OscillatorNode, web_audio.OscillatorNode);
+ dart.registerExtension(dart.global.Oscillator, web_audio.OscillatorNode);
dart.defineExtensionNames([
'setOrientation',
'setPosition',
@@ -91140,6 +91210,8 @@
})
});
dart.registerExtension(dart.global.PannerNode, web_audio.PannerNode);
+ dart.registerExtension(dart.global.AudioPannerNode, web_audio.PannerNode);
+ dart.registerExtension(dart.global.webkitAudioPannerNode, web_audio.PannerNode);
web_audio.PeriodicWave = class PeriodicWave extends _interceptors.Interceptor {
static _() {
dart.throw(new core.UnsupportedError("Not supported"));
@@ -91177,6 +91249,7 @@
});
web_audio.ScriptProcessorNode.audioProcessEvent = dart.const(new (EventStreamProviderOfAudioProcessingEvent())('audioprocess'));
dart.registerExtension(dart.global.ScriptProcessorNode, web_audio.ScriptProcessorNode);
+ dart.registerExtension(dart.global.JavaScriptAudioNode, web_audio.ScriptProcessorNode);
dart.defineExtensionNames([
'curve',
'oversample'
@@ -93446,6 +93519,7 @@
})
});
dart.registerExtension(dart.global.WebGLLoseContext, web_gl.LoseContext);
+ dart.registerExtension(dart.global.WebGLExtensionLoseContext, web_gl.LoseContext);
web_gl.OesElementIndexUint = class OesElementIndexUint extends _interceptors.Interceptor {
static _() {
dart.throw(new core.UnsupportedError("Not supported"));
diff --git a/pkg/dev_compiler/lib/js/es6/dart_sdk.js b/pkg/dev_compiler/lib/js/es6/dart_sdk.js
index 5114d4a..c5e550d 100644
--- a/pkg/dev_compiler/lib/js/es6/dart_sdk.js
+++ b/pkg/dev_compiler/lib/js/es6/dart_sdk.js
@@ -533,9 +533,9 @@
let ListOfTransform = () => (ListOfTransform = dart.constFn(core.List$(svg.Transform)))();
let CompleterOfAudioBuffer = () => (CompleterOfAudioBuffer = dart.constFn(async.Completer$(web_audio.AudioBuffer)))();
let EventStreamProviderOfAudioProcessingEvent = () => (EventStreamProviderOfAudioProcessingEvent = dart.constFn(html.EventStreamProvider$(web_audio.AudioProcessingEvent)))();
+let dynamicTodynamic = () => (dynamicTodynamic = dart.constFn(dart.definiteFunctionType(dart.dynamic, [dart.dynamic])))();
let StringAndStringToint = () => (StringAndStringToint = dart.constFn(dart.definiteFunctionType(core.int, [core.String, core.String])))();
let VoidTo_MethodStats = () => (VoidTo_MethodStats = dart.constFn(dart.definiteFunctionType(dart._MethodStats, [])))();
-let dynamicTodynamic = () => (dynamicTodynamic = dart.constFn(dart.definiteFunctionType(dart.dynamic, [dart.dynamic])))();
let dynamicToString = () => (dynamicToString = dart.constFn(dart.definiteFunctionType(core.String, [dart.dynamic])))();
let dynamicToListOfString = () => (dynamicToListOfString = dart.constFn(dart.definiteFunctionType(ListOfString(), [dart.dynamic])))();
let dynamicToList = () => (dynamicToList = dart.constFn(dart.definiteFunctionType(core.List, [dart.dynamic])))();
@@ -1058,8 +1058,10 @@
derived.__proto__ = base;
};
dart.setExtensionBaseClass = function(derived, base) {
- derived.prototype[dart._extensionType] = derived;
- derived.prototype.__proto__ = base.prototype;
+ if (base) {
+ derived.prototype[dart._extensionType] = derived;
+ derived.prototype.__proto__ = base.prototype;
+ }
};
dart.callableClass = function(callableCtor, classExpr) {
callableCtor.prototype = classExpr.prototype;
@@ -1559,6 +1561,43 @@
dart.dgcall = function(f, typeArgs, ...args) {
return dart._checkAndCall(f, dart._getRuntimeType(f), void 0, typeArgs, args, 'call');
};
+dart._dhelperRepl = function(object, field, callback) {
+ let rawField = field;
+ if (typeof field == 'symbol') {
+ if (field in object) return callback(field);
+ field = field.toString();
+ field = field.substring('Symbol('.length, field.length - 1);
+ } else if (field.charAt(0) != '_') {
+ return callback(field);
+ }
+ if (field in object) return callback(field);
+ let proto = object;
+ while (proto !== null) {
+ let symbols = Object.getOwnPropertySymbols(proto);
+ let target = 'Symbol(' + field + ')';
+ for (let s = 0; s < symbols.length; s++) {
+ let sym = symbols[s];
+ if (target == sym.toString()) return callback(sym);
+ }
+ proto = proto.__proto__;
+ }
+ return callback(rawField);
+};
+dart.dloadRepl = function(obj, field) {
+ return dart._dhelperRepl(obj, field, dart.fn(resolvedField => dart.dload(obj, resolvedField), dynamicTodynamic()));
+};
+dart.dputRepl = function(obj, field, value) {
+ return dart._dhelperRepl(obj, field, dart.fn(resolvedField => dart.dput(obj, resolvedField, value), dynamicTodynamic()));
+};
+dart._callMethodRepl = function(obj, method, typeArgs, args) {
+ return dart._dhelperRepl(obj, method, dart.fn(resolvedField => dart._callMethod(obj, resolvedField, typeArgs, args, method), dynamicTodynamic()));
+};
+dart.dsendRepl = function(obj, method, ...args) {
+ return dart._callMethodRepl(obj, method, null, args);
+};
+dart.dgsendRepl = function(obj, typeArgs, method, ...args) {
+ return dart._callMethodRepl(obj, method, typeArgs, args);
+};
dart.getDynamicStats = function() {
let ret = JSArrayOfListOfObject().of([]);
let keys = dart._callMethodStats[dartx.keys][dartx.toList]();
@@ -16288,6 +16327,7 @@
names: ['_create1', '_create2', '_create3']
});
dart.registerExtension(dart.global.Uint8ClampedArray, _native_typed_data.NativeUint8ClampedList);
+dart.registerExtension(dart.global.CanvasPixelArray, _native_typed_data.NativeUint8ClampedList);
dart.defineExtensionNames([
'runtimeType',
'length',
@@ -39271,6 +39311,7 @@
}
});
dart.registerExtension(dart.global.IDBOpenDBRequest, indexed_db.OpenDBRequest);
+dart.registerExtension(dart.global.IDBVersionChangeRequest, indexed_db.OpenDBRequest);
dart.defineExtensionNames([
'completed',
'abort',
@@ -39522,6 +39563,7 @@
html.Event.BUBBLING_PHASE = 3;
html.Event.CAPTURING_PHASE = 1;
dart.registerExtension(dart.global.Event, html.Event);
+dart.registerExtension(dart.global.InputEvent, html.Event);
dart.defineExtensionNames([
'dataLoss',
'dataLossMessage',
@@ -42400,6 +42442,8 @@
}
});
dart.registerExtension(dart.global.ApplicationCache, html.ApplicationCache);
+dart.registerExtension(dart.global.DOMApplicationCache, html.ApplicationCache);
+dart.registerExtension(dart.global.OfflineResourceList, html.ApplicationCache);
dart.defineExtensionNames([
'message',
'reason',
@@ -46219,6 +46263,8 @@
})
});
dart.registerExtension(dart.global.CSSKeyframeRule, html.CssKeyframeRule);
+dart.registerExtension(dart.global.MozCSSKeyframeRule, html.CssKeyframeRule);
+dart.registerExtension(dart.global.WebKitCSSKeyframeRule, html.CssKeyframeRule);
dart.defineExtensionNames([
'appendRule',
'deleteRule',
@@ -46266,6 +46312,8 @@
})
});
dart.registerExtension(dart.global.CSSKeyframesRule, html.CssKeyframesRule);
+dart.registerExtension(dart.global.MozCSSKeyframesRule, html.CssKeyframesRule);
+dart.registerExtension(dart.global.WebKitCSSKeyframesRule, html.CssKeyframesRule);
dart.defineExtensionNames([
'media'
]);
@@ -52007,6 +52055,8 @@
}
});
dart.registerExtension(dart.global.CSSStyleDeclaration, html.CssStyleDeclaration);
+dart.registerExtension(dart.global.MSStyleCSSProperties, html.CssStyleDeclaration);
+dart.registerExtension(dart.global.CSS2Properties, html.CssStyleDeclaration);
const _elementIterable = Symbol('_elementIterable');
const _elementCssStyleDeclarationSetIterable = Symbol('_elementCssStyleDeclarationSetIterable');
const _setAll = Symbol('_setAll');
@@ -64483,6 +64533,7 @@
names: ['_create_1', '_create_2']
});
dart.registerExtension(dart.global.MouseEvent, html.MouseEvent);
+dart.registerExtension(dart.global.DragEvent, html.MouseEvent);
html.MutationCallback = dart.typedef('MutationCallback', () => dart.functionType(dart.void, [ListOfMutationRecord(), html.MutationObserver]));
const _observe_1 = Symbol('_observe_1');
const _observe = Symbol('_observe');
@@ -64572,6 +64623,7 @@
});
html.MutationObserver._boolKeys = dart.const(dart.map({childList: true, attributes: true, characterData: true, subtree: true, attributeOldValue: true, characterDataOldValue: true}, core.String, core.bool));
dart.registerExtension(dart.global.MutationObserver, html.MutationObserver);
+dart.registerExtension(dart.global.WebKitMutationObserver, html.MutationObserver);
dart.defineExtensionNames([
'addedNodes',
'attributeName',
@@ -65377,6 +65429,7 @@
})
});
dart.registerExtension(dart.global.NodeList, html.NodeList);
+dart.registerExtension(dart.global.RadioNodeList, html.NodeList);
dart.defineExtensionNames([
'nextElementSibling',
'previousElementSibling'
@@ -68295,6 +68348,7 @@
}
});
dart.registerExtension(dart.global.RTCDataChannel, html.RtcDataChannel);
+dart.registerExtension(dart.global.DataChannel, html.RtcDataChannel);
dart.defineExtensionNames([
'channel'
]);
@@ -68437,6 +68491,7 @@
})
});
dart.registerExtension(dart.global.RTCIceCandidate, html.RtcIceCandidate);
+dart.registerExtension(dart.global.mozRTCIceCandidate, html.RtcIceCandidate);
dart.defineExtensionNames([
'candidate'
]);
@@ -68453,6 +68508,7 @@
fields: () => ({[dartx.candidate]: html.RtcIceCandidate})
});
dart.registerExtension(dart.global.RTCIceCandidateEvent, html.RtcIceCandidateEvent);
+dart.registerExtension(dart.global.RTCPeerConnectionIceEvent, html.RtcIceCandidateEvent);
const _createOffer = Symbol('_createOffer');
const _createAnswer = Symbol('_createAnswer');
const _getStats = Symbol('_getStats');
@@ -68812,6 +68868,7 @@
}
});
dart.registerExtension(dart.global.RTCPeerConnection, html.RtcPeerConnection);
+dart.registerExtension(dart.global.mozRTCPeerConnection, html.RtcPeerConnection);
dart.defineExtensionNames([
'sdp',
'type'
@@ -68848,6 +68905,7 @@
})
});
dart.registerExtension(dart.global.RTCSessionDescription, html.RtcSessionDescription);
+dart.registerExtension(dart.global.mozRTCSessionDescription, html.RtcSessionDescription);
const _get_timestamp = Symbol('_get_timestamp');
dart.defineExtensionNames([
'timestamp',
@@ -71995,6 +72053,8 @@
})
});
dart.registerExtension(dart.global.HTMLTableCellElement, html.TableCellElement);
+dart.registerExtension(dart.global.HTMLTableDataCellElement, html.TableCellElement);
+dart.registerExtension(dart.global.HTMLTableHeaderCellElement, html.TableCellElement);
dart.defineExtensionNames([
'span'
]);
@@ -73742,6 +73802,7 @@
names: ['_create_1', '_create_2']
});
dart.registerExtension(dart.global.TransitionEvent, html.TransitionEvent);
+dart.registerExtension(dart.global.WebKitTransitionEvent, html.TransitionEvent);
dart.defineExtensionNames([
'firstChild',
'lastChild',
@@ -76240,6 +76301,7 @@
}
});
dart.registerExtension(dart.global.Window, html.Window);
+dart.registerExtension(dart.global.DOMWindow, html.Window);
const _returnValue = Symbol('_returnValue');
html._WrappedEvent = class _WrappedEvent extends core.Object {
new(wrapped) {
@@ -77198,6 +77260,7 @@
})
});
dart.registerExtension(dart.global.ClientRectList, html._ClientRectList);
+dart.registerExtension(dart.global.DOMRectList, html._ClientRectList);
dart.defineExtensionNames([
'length',
'get',
@@ -77741,6 +77804,7 @@
})
});
dart.registerExtension(dart.global.NamedNodeMap, html._NamedNodeMap);
+dart.registerExtension(dart.global.MozNamedAttrMap, html._NamedNodeMap);
html._PagePopupController = class _PagePopupController extends _interceptors.Interceptor {
static _() {
dart.throw(new core.UnsupportedError("Not supported"));
@@ -90260,6 +90324,7 @@
})
});
dart.registerExtension(dart.global.AnalyserNode, web_audio.AnalyserNode);
+dart.registerExtension(dart.global.RealtimeAnalyserNode, web_audio.AnalyserNode);
dart.defineExtensionNames([
'getChannelData',
'duration',
@@ -90579,6 +90644,7 @@
});
web_audio.AudioContext.completeEvent = dart.const(new (EventStreamProviderOfEvent())('complete'));
dart.registerExtension(dart.global.AudioContext, web_audio.AudioContext);
+dart.registerExtension(dart.global.webkitAudioContext, web_audio.AudioContext);
dart.defineExtensionNames([
'maxChannelCount'
]);
@@ -90782,6 +90848,7 @@
constructors: () => ({_: dart.definiteFunctionType(web_audio.ChannelMergerNode, [])})
});
dart.registerExtension(dart.global.ChannelMergerNode, web_audio.ChannelMergerNode);
+dart.registerExtension(dart.global.AudioChannelMerger, web_audio.ChannelMergerNode);
web_audio.ChannelSplitterNode = class ChannelSplitterNode extends web_audio.AudioNode {
static _() {
dart.throw(new core.UnsupportedError("Not supported"));
@@ -90791,6 +90858,7 @@
constructors: () => ({_: dart.definiteFunctionType(web_audio.ChannelSplitterNode, [])})
});
dart.registerExtension(dart.global.ChannelSplitterNode, web_audio.ChannelSplitterNode);
+dart.registerExtension(dart.global.AudioChannelSplitter, web_audio.ChannelSplitterNode);
dart.defineExtensionNames([
'buffer',
'normalize'
@@ -90895,6 +90963,7 @@
fields: () => ({[dartx.gain]: web_audio.AudioParam})
});
dart.registerExtension(dart.global.GainNode, web_audio.GainNode);
+dart.registerExtension(dart.global.AudioGainNode, web_audio.GainNode);
dart.defineExtensionNames([
'mediaElement'
]);
@@ -91044,6 +91113,7 @@
});
web_audio.OscillatorNode.endedEvent = dart.const(new (EventStreamProviderOfEvent())('ended'));
dart.registerExtension(dart.global.OscillatorNode, web_audio.OscillatorNode);
+dart.registerExtension(dart.global.Oscillator, web_audio.OscillatorNode);
dart.defineExtensionNames([
'setOrientation',
'setPosition',
@@ -91138,6 +91208,8 @@
})
});
dart.registerExtension(dart.global.PannerNode, web_audio.PannerNode);
+dart.registerExtension(dart.global.AudioPannerNode, web_audio.PannerNode);
+dart.registerExtension(dart.global.webkitAudioPannerNode, web_audio.PannerNode);
web_audio.PeriodicWave = class PeriodicWave extends _interceptors.Interceptor {
static _() {
dart.throw(new core.UnsupportedError("Not supported"));
@@ -91175,6 +91247,7 @@
});
web_audio.ScriptProcessorNode.audioProcessEvent = dart.const(new (EventStreamProviderOfAudioProcessingEvent())('audioprocess'));
dart.registerExtension(dart.global.ScriptProcessorNode, web_audio.ScriptProcessorNode);
+dart.registerExtension(dart.global.JavaScriptAudioNode, web_audio.ScriptProcessorNode);
dart.defineExtensionNames([
'curve',
'oversample'
@@ -93444,6 +93517,7 @@
})
});
dart.registerExtension(dart.global.WebGLLoseContext, web_gl.LoseContext);
+dart.registerExtension(dart.global.WebGLExtensionLoseContext, web_gl.LoseContext);
web_gl.OesElementIndexUint = class OesElementIndexUint extends _interceptors.Interceptor {
static _() {
dart.throw(new core.UnsupportedError("Not supported"));
diff --git a/pkg/dev_compiler/lib/js/legacy/dart_library.js b/pkg/dev_compiler/lib/js/legacy/dart_library.js
index 3b766c2..d8dfd96 100644
--- a/pkg/dev_compiler/lib/js/legacy/dart_library.js
+++ b/pkg/dev_compiler/lib/js/legacy/dart_library.js
@@ -135,9 +135,16 @@
// Expose constructors for DOM types dart:html needs to assume are
// available on window.
if (typeof PannerNode == "undefined") {
- let audioContext = new AudioContext();
+ let audioContext;
+ if (typeof AudioContext == "undefined" &&
+ (typeof webkitAudioContext != "undefined")) {
+ audioContext = new webkitAudioContext();
+ } else {
+ audioContext = new AudioContext();
+ window.StereoPannerNode =
+ audioContext.createStereoPanner().constructor;
+ }
window.PannerNode = audioContext.createPanner().constructor;
- window.StereoPannerNode = audioContext.createStereoPanner().constructor;
}
if (typeof AudioSourceNode == "undefined") {
window.AudioSourceNode = MediaElementAudioSourceNode.constructor;
@@ -146,14 +153,18 @@
window.FontFaceSet = document.fonts.__proto__.constructor;
}
if (typeof MemoryInfo == "undefined") {
- window.MemoryInfo = window.performance.memory.constructor;
+ if (typeof window.performance.memory != "undefined") {
+ window.MemoryInfo = window.performance.memory.constructor;
+ }
}
if (typeof Geolocation == "undefined") {
navigator.geolocation.constructor;
}
if (typeof Animation == "undefined") {
let d = document.createElement('div');
- window.Animation = d.animate(d).constructor;
+ if (typeof d.animate != "undefined") {
+ window.Animation = d.animate(d).constructor;
+ }
}
if (typeof SourceBufferList == "undefined") {
window.SourceBufferList = new MediaSource().sourceBuffers.constructor;
diff --git a/pkg/dev_compiler/lib/js/legacy/dart_sdk.js b/pkg/dev_compiler/lib/js/legacy/dart_sdk.js
index 283ffe5..ca17e4e 100644
--- a/pkg/dev_compiler/lib/js/legacy/dart_sdk.js
+++ b/pkg/dev_compiler/lib/js/legacy/dart_sdk.js
@@ -536,9 +536,9 @@
let ListOfTransform = () => (ListOfTransform = dart.constFn(core.List$(svg$.Transform)))();
let CompleterOfAudioBuffer = () => (CompleterOfAudioBuffer = dart.constFn(async.Completer$(web_audio.AudioBuffer)))();
let EventStreamProviderOfAudioProcessingEvent = () => (EventStreamProviderOfAudioProcessingEvent = dart.constFn(html$.EventStreamProvider$(web_audio.AudioProcessingEvent)))();
+ let dynamicTodynamic$ = () => (dynamicTodynamic$ = dart.constFn(dart.definiteFunctionType(dart.dynamic, [dart.dynamic])))();
let StringAndStringToint = () => (StringAndStringToint = dart.constFn(dart.definiteFunctionType(core.int, [core.String, core.String])))();
let VoidTo_MethodStats = () => (VoidTo_MethodStats = dart.constFn(dart.definiteFunctionType(dart._MethodStats, [])))();
- let dynamicTodynamic$ = () => (dynamicTodynamic$ = dart.constFn(dart.definiteFunctionType(dart.dynamic, [dart.dynamic])))();
let dynamicToString = () => (dynamicToString = dart.constFn(dart.definiteFunctionType(core.String, [dart.dynamic])))();
let dynamicToListOfString = () => (dynamicToListOfString = dart.constFn(dart.definiteFunctionType(ListOfString(), [dart.dynamic])))();
let dynamicToList = () => (dynamicToList = dart.constFn(dart.definiteFunctionType(core.List, [dart.dynamic])))();
@@ -1061,8 +1061,10 @@
derived.__proto__ = base;
};
dart.setExtensionBaseClass = function(derived, base) {
- derived.prototype[dart._extensionType] = derived;
- derived.prototype.__proto__ = base.prototype;
+ if (base) {
+ derived.prototype[dart._extensionType] = derived;
+ derived.prototype.__proto__ = base.prototype;
+ }
};
dart.callableClass = function(callableCtor, classExpr) {
callableCtor.prototype = classExpr.prototype;
@@ -1562,6 +1564,43 @@
dart.dgcall = function(f, typeArgs, ...args) {
return dart._checkAndCall(f, dart._getRuntimeType(f), void 0, typeArgs, args, 'call');
};
+ dart._dhelperRepl = function(object, field, callback) {
+ let rawField = field;
+ if (typeof field == 'symbol') {
+ if (field in object) return callback(field);
+ field = field.toString();
+ field = field.substring('Symbol('.length, field.length - 1);
+ } else if (field.charAt(0) != '_') {
+ return callback(field);
+ }
+ if (field in object) return callback(field);
+ let proto = object;
+ while (proto !== null) {
+ let symbols = Object.getOwnPropertySymbols(proto);
+ let target = 'Symbol(' + field + ')';
+ for (let s = 0; s < symbols.length; s++) {
+ let sym = symbols[s];
+ if (target == sym.toString()) return callback(sym);
+ }
+ proto = proto.__proto__;
+ }
+ return callback(rawField);
+ };
+ dart.dloadRepl = function(obj, field) {
+ return dart._dhelperRepl(obj, field, dart.fn(resolvedField => dart.dload(obj, resolvedField), dynamicTodynamic$()));
+ };
+ dart.dputRepl = function(obj, field, value) {
+ return dart._dhelperRepl(obj, field, dart.fn(resolvedField => dart.dput(obj, resolvedField, value), dynamicTodynamic$()));
+ };
+ dart._callMethodRepl = function(obj, method, typeArgs, args) {
+ return dart._dhelperRepl(obj, method, dart.fn(resolvedField => dart._callMethod(obj, resolvedField, typeArgs, args, method), dynamicTodynamic$()));
+ };
+ dart.dsendRepl = function(obj, method, ...args) {
+ return dart._callMethodRepl(obj, method, null, args);
+ };
+ dart.dgsendRepl = function(obj, typeArgs, method, ...args) {
+ return dart._callMethodRepl(obj, method, typeArgs, args);
+ };
dart.getDynamicStats = function() {
let ret = JSArrayOfListOfObject().of([]);
let keys = dart._callMethodStats[dartx.keys][dartx.toList]();
@@ -16291,6 +16330,7 @@
names: ['_create1', '_create2', '_create3']
});
dart.registerExtension(dart.global.Uint8ClampedArray, _native_typed_data.NativeUint8ClampedList);
+ dart.registerExtension(dart.global.CanvasPixelArray, _native_typed_data.NativeUint8ClampedList);
dart.defineExtensionNames([
'runtimeType',
'length',
@@ -39274,6 +39314,7 @@
}
});
dart.registerExtension(dart.global.IDBOpenDBRequest, indexed_db.OpenDBRequest);
+ dart.registerExtension(dart.global.IDBVersionChangeRequest, indexed_db.OpenDBRequest);
dart.defineExtensionNames([
'completed',
'abort',
@@ -39525,6 +39566,7 @@
html$.Event.BUBBLING_PHASE = 3;
html$.Event.CAPTURING_PHASE = 1;
dart.registerExtension(dart.global.Event, html$.Event);
+ dart.registerExtension(dart.global.InputEvent, html$.Event);
dart.defineExtensionNames([
'dataLoss',
'dataLossMessage',
@@ -42403,6 +42445,8 @@
}
});
dart.registerExtension(dart.global.ApplicationCache, html$.ApplicationCache);
+ dart.registerExtension(dart.global.DOMApplicationCache, html$.ApplicationCache);
+ dart.registerExtension(dart.global.OfflineResourceList, html$.ApplicationCache);
dart.defineExtensionNames([
'message',
'reason',
@@ -46222,6 +46266,8 @@
})
});
dart.registerExtension(dart.global.CSSKeyframeRule, html$.CssKeyframeRule);
+ dart.registerExtension(dart.global.MozCSSKeyframeRule, html$.CssKeyframeRule);
+ dart.registerExtension(dart.global.WebKitCSSKeyframeRule, html$.CssKeyframeRule);
dart.defineExtensionNames([
'appendRule',
'deleteRule',
@@ -46269,6 +46315,8 @@
})
});
dart.registerExtension(dart.global.CSSKeyframesRule, html$.CssKeyframesRule);
+ dart.registerExtension(dart.global.MozCSSKeyframesRule, html$.CssKeyframesRule);
+ dart.registerExtension(dart.global.WebKitCSSKeyframesRule, html$.CssKeyframesRule);
dart.defineExtensionNames([
'media'
]);
@@ -52010,6 +52058,8 @@
}
});
dart.registerExtension(dart.global.CSSStyleDeclaration, html$.CssStyleDeclaration);
+ dart.registerExtension(dart.global.MSStyleCSSProperties, html$.CssStyleDeclaration);
+ dart.registerExtension(dart.global.CSS2Properties, html$.CssStyleDeclaration);
const _elementIterable = Symbol('_elementIterable');
const _elementCssStyleDeclarationSetIterable = Symbol('_elementCssStyleDeclarationSetIterable');
const _setAll = Symbol('_setAll');
@@ -64486,6 +64536,7 @@
names: ['_create_1', '_create_2']
});
dart.registerExtension(dart.global.MouseEvent, html$.MouseEvent);
+ dart.registerExtension(dart.global.DragEvent, html$.MouseEvent);
html$.MutationCallback = dart.typedef('MutationCallback', () => dart.functionType(dart.void, [ListOfMutationRecord(), html$.MutationObserver]));
const _observe_1 = Symbol('_observe_1');
const _observe = Symbol('_observe');
@@ -64575,6 +64626,7 @@
});
html$.MutationObserver._boolKeys = dart.const(dart.map({childList: true, attributes: true, characterData: true, subtree: true, attributeOldValue: true, characterDataOldValue: true}, core.String, core.bool));
dart.registerExtension(dart.global.MutationObserver, html$.MutationObserver);
+ dart.registerExtension(dart.global.WebKitMutationObserver, html$.MutationObserver);
dart.defineExtensionNames([
'addedNodes',
'attributeName',
@@ -65380,6 +65432,7 @@
})
});
dart.registerExtension(dart.global.NodeList, html$.NodeList);
+ dart.registerExtension(dart.global.RadioNodeList, html$.NodeList);
dart.defineExtensionNames([
'nextElementSibling',
'previousElementSibling'
@@ -68298,6 +68351,7 @@
}
});
dart.registerExtension(dart.global.RTCDataChannel, html$.RtcDataChannel);
+ dart.registerExtension(dart.global.DataChannel, html$.RtcDataChannel);
dart.defineExtensionNames([
'channel'
]);
@@ -68440,6 +68494,7 @@
})
});
dart.registerExtension(dart.global.RTCIceCandidate, html$.RtcIceCandidate);
+ dart.registerExtension(dart.global.mozRTCIceCandidate, html$.RtcIceCandidate);
dart.defineExtensionNames([
'candidate'
]);
@@ -68456,6 +68511,7 @@
fields: () => ({[dartx.candidate]: html$.RtcIceCandidate})
});
dart.registerExtension(dart.global.RTCIceCandidateEvent, html$.RtcIceCandidateEvent);
+ dart.registerExtension(dart.global.RTCPeerConnectionIceEvent, html$.RtcIceCandidateEvent);
const _createOffer = Symbol('_createOffer');
const _createAnswer = Symbol('_createAnswer');
const _getStats = Symbol('_getStats');
@@ -68815,6 +68871,7 @@
}
});
dart.registerExtension(dart.global.RTCPeerConnection, html$.RtcPeerConnection);
+ dart.registerExtension(dart.global.mozRTCPeerConnection, html$.RtcPeerConnection);
dart.defineExtensionNames([
'sdp',
'type'
@@ -68851,6 +68908,7 @@
})
});
dart.registerExtension(dart.global.RTCSessionDescription, html$.RtcSessionDescription);
+ dart.registerExtension(dart.global.mozRTCSessionDescription, html$.RtcSessionDescription);
const _get_timestamp = Symbol('_get_timestamp');
dart.defineExtensionNames([
'timestamp',
@@ -71998,6 +72056,8 @@
})
});
dart.registerExtension(dart.global.HTMLTableCellElement, html$.TableCellElement);
+ dart.registerExtension(dart.global.HTMLTableDataCellElement, html$.TableCellElement);
+ dart.registerExtension(dart.global.HTMLTableHeaderCellElement, html$.TableCellElement);
dart.defineExtensionNames([
'span'
]);
@@ -73745,6 +73805,7 @@
names: ['_create_1', '_create_2']
});
dart.registerExtension(dart.global.TransitionEvent, html$.TransitionEvent);
+ dart.registerExtension(dart.global.WebKitTransitionEvent, html$.TransitionEvent);
dart.defineExtensionNames([
'firstChild',
'lastChild',
@@ -76243,6 +76304,7 @@
}
});
dart.registerExtension(dart.global.Window, html$.Window);
+ dart.registerExtension(dart.global.DOMWindow, html$.Window);
const _returnValue = Symbol('_returnValue');
html$._WrappedEvent = class _WrappedEvent extends core.Object {
new(wrapped) {
@@ -77201,6 +77263,7 @@
})
});
dart.registerExtension(dart.global.ClientRectList, html$._ClientRectList);
+ dart.registerExtension(dart.global.DOMRectList, html$._ClientRectList);
dart.defineExtensionNames([
'length',
'get',
@@ -77744,6 +77807,7 @@
})
});
dart.registerExtension(dart.global.NamedNodeMap, html$._NamedNodeMap);
+ dart.registerExtension(dart.global.MozNamedAttrMap, html$._NamedNodeMap);
html$._PagePopupController = class _PagePopupController extends _interceptors.Interceptor {
static _() {
dart.throw(new core.UnsupportedError("Not supported"));
@@ -90263,6 +90327,7 @@
})
});
dart.registerExtension(dart.global.AnalyserNode, web_audio.AnalyserNode);
+ dart.registerExtension(dart.global.RealtimeAnalyserNode, web_audio.AnalyserNode);
dart.defineExtensionNames([
'getChannelData',
'duration',
@@ -90582,6 +90647,7 @@
});
web_audio.AudioContext.completeEvent = dart.const(new (EventStreamProviderOfEvent())('complete'));
dart.registerExtension(dart.global.AudioContext, web_audio.AudioContext);
+ dart.registerExtension(dart.global.webkitAudioContext, web_audio.AudioContext);
dart.defineExtensionNames([
'maxChannelCount'
]);
@@ -90785,6 +90851,7 @@
constructors: () => ({_: dart.definiteFunctionType(web_audio.ChannelMergerNode, [])})
});
dart.registerExtension(dart.global.ChannelMergerNode, web_audio.ChannelMergerNode);
+ dart.registerExtension(dart.global.AudioChannelMerger, web_audio.ChannelMergerNode);
web_audio.ChannelSplitterNode = class ChannelSplitterNode extends web_audio.AudioNode {
static _() {
dart.throw(new core.UnsupportedError("Not supported"));
@@ -90794,6 +90861,7 @@
constructors: () => ({_: dart.definiteFunctionType(web_audio.ChannelSplitterNode, [])})
});
dart.registerExtension(dart.global.ChannelSplitterNode, web_audio.ChannelSplitterNode);
+ dart.registerExtension(dart.global.AudioChannelSplitter, web_audio.ChannelSplitterNode);
dart.defineExtensionNames([
'buffer',
'normalize'
@@ -90898,6 +90966,7 @@
fields: () => ({[dartx.gain]: web_audio.AudioParam})
});
dart.registerExtension(dart.global.GainNode, web_audio.GainNode);
+ dart.registerExtension(dart.global.AudioGainNode, web_audio.GainNode);
dart.defineExtensionNames([
'mediaElement'
]);
@@ -91047,6 +91116,7 @@
});
web_audio.OscillatorNode.endedEvent = dart.const(new (EventStreamProviderOfEvent())('ended'));
dart.registerExtension(dart.global.OscillatorNode, web_audio.OscillatorNode);
+ dart.registerExtension(dart.global.Oscillator, web_audio.OscillatorNode);
dart.defineExtensionNames([
'setOrientation',
'setPosition',
@@ -91141,6 +91211,8 @@
})
});
dart.registerExtension(dart.global.PannerNode, web_audio.PannerNode);
+ dart.registerExtension(dart.global.AudioPannerNode, web_audio.PannerNode);
+ dart.registerExtension(dart.global.webkitAudioPannerNode, web_audio.PannerNode);
web_audio.PeriodicWave = class PeriodicWave extends _interceptors.Interceptor {
static _() {
dart.throw(new core.UnsupportedError("Not supported"));
@@ -91178,6 +91250,7 @@
});
web_audio.ScriptProcessorNode.audioProcessEvent = dart.const(new (EventStreamProviderOfAudioProcessingEvent())('audioprocess'));
dart.registerExtension(dart.global.ScriptProcessorNode, web_audio.ScriptProcessorNode);
+ dart.registerExtension(dart.global.JavaScriptAudioNode, web_audio.ScriptProcessorNode);
dart.defineExtensionNames([
'curve',
'oversample'
@@ -93447,6 +93520,7 @@
})
});
dart.registerExtension(dart.global.WebGLLoseContext, web_gl.LoseContext);
+ dart.registerExtension(dart.global.WebGLExtensionLoseContext, web_gl.LoseContext);
web_gl.OesElementIndexUint = class OesElementIndexUint extends _interceptors.Interceptor {
static _() {
dart.throw(new core.UnsupportedError("Not supported"));
diff --git a/pkg/dev_compiler/lib/src/compiler/code_generator.dart b/pkg/dev_compiler/lib/src/compiler/code_generator.dart
index a642fe4..221d94c 100644
--- a/pkg/dev_compiler/lib/src/compiler/code_generator.dart
+++ b/pkg/dev_compiler/lib/src/compiler/code_generator.dart
@@ -31,7 +31,7 @@
import 'package:analyzer/src/summary/summary_sdk.dart';
import 'package:analyzer/src/task/strong/ast_properties.dart'
show isDynamicInvoke, setIsDynamicInvoke, getImplicitAssignmentCast;
-import 'package:path/path.dart' show separator, isWithin, fromUri;
+import 'package:path/path.dart' show separator;
import '../closure/closure_annotator.dart' show ClosureAnnotator;
import '../js_ast/js_ast.dart' as JS;
@@ -625,7 +625,7 @@
if (node.type == null) {
// TODO(jmesserly): if the type fails to resolve, should we generate code
// that throws instead?
- assert(options.unsafeForceCompile);
+ assert(options.unsafeForceCompile || options.replCompile);
return js.call('dart.dynamic');
}
return _emitType(node.type);
@@ -754,8 +754,8 @@
_defineClass(classElem, className, classExpr, isCallable, body);
// Emit things that come after the ES6 `class ... { ... }`.
- var jsPeerName = _getJSPeerName(classElem);
- _setBaseClass(classElem, className, jsPeerName, body);
+ var jsPeerNames = _getJSPeerNames(classElem);
+ _setBaseClass(classElem, className, jsPeerNames, body);
_emitClassTypeTests(classElem, className, body);
@@ -774,7 +774,9 @@
body = <JS.Statement>[classDef];
_emitStaticFields(staticFields, staticFieldOverrides, classElem, body);
- _registerExtensionType(classElem, jsPeerName, body);
+ for (var peer in jsPeerNames) {
+ _registerExtensionType(classElem, peer, body);
+ }
return _statement(body);
}
@@ -1569,16 +1571,21 @@
///
/// For example for dart:_interceptors `JSArray` this will return "Array",
/// referring to the JavaScript built-in `Array` type.
- String _getJSPeerName(ClassElement classElem) {
- var jsPeerName = getAnnotationName(
+ List<String> _getJSPeerNames(ClassElement classElem) {
+ var jsPeerNames = getAnnotationName(
classElem,
(a) =>
isJsPeerInterface(a) ||
isNativeAnnotation(a) && _extensionTypes.isNativeClass(classElem));
- if (jsPeerName != null && jsPeerName.contains(',')) {
- jsPeerName = jsPeerName.split(',')[0];
+ if (jsPeerNames != null) {
+ // Omit the special name "!nonleaf" and any future hacks starting with "!"
+ return jsPeerNames
+ .split(',')
+ .where((peer) => !peer.startsWith("!"))
+ .toList();
+ } else {
+ return [];
}
- return jsPeerName;
}
void _registerExtensionType(
@@ -1590,12 +1597,14 @@
}
void _setBaseClass(ClassElement classElem, JS.Expression className,
- String jsPeerName, List<JS.Statement> body) {
- if (jsPeerName != null && classElem.typeParameters.isNotEmpty) {
- // TODO(jmesserly): we should really just extend Array in the first place.
- var newBaseClass = js.call('dart.global.#', [jsPeerName]);
- body.add(js.statement(
- 'dart.setExtensionBaseClass(#, #);', [className, newBaseClass]));
+ List<String> jsPeerNames, List<JS.Statement> body) {
+ if (jsPeerNames.isNotEmpty && classElem.typeParameters.isNotEmpty) {
+ for (var peer in jsPeerNames) {
+ // TODO(jmesserly): we should just extend Array in the first place
+ var newBaseClass = js.call('dart.global.#', [peer]);
+ body.add(js.statement(
+ 'dart.setExtensionBaseClass(#, #);', [className, newBaseClass]));
+ }
} else if (_hasDeferredSupertype.contains(classElem)) {
var newBaseClass = _emitType(classElem.type.superclass,
nameType: false, subClass: classElem, className: className);
@@ -3065,8 +3074,12 @@
[l, l, name, name, _visit(rhs)])
]);
}
- return js.call('dart.dput(#, #, #)',
- [_visit(target), _emitMemberName(id.name), _visit(rhs)]);
+ return js.call('dart.#(#, #, #)', [
+ _emitDynamicOperationName('dput'),
+ _visit(target),
+ _emitMemberName(id.name),
+ _visit(rhs)
+ ]);
}
var accessor = id.staticElement;
@@ -3351,10 +3364,16 @@
return new JS.Call(jsTarget, args);
}
if (typeArgs != null) {
- return js.call('dart.dgsend(#, #, #, #)',
- [jsTarget, new JS.ArrayInitializer(typeArgs), memberName, args]);
+ return js.call('dart.#(#, #, #, #)', [
+ _emitDynamicOperationName('dgsend'),
+ jsTarget,
+ new JS.ArrayInitializer(typeArgs),
+ memberName,
+ args
+ ]);
} else {
- return js.call('dart.dsend(#, #, #)', [jsTarget, memberName, args]);
+ return js.call('dart.#(#, #, #)',
+ [_emitDynamicOperationName('dsend'), jsTarget, memberName, args]);
}
}
if (_isObjectMemberCall(target, name)) {
@@ -4635,6 +4654,9 @@
return _emitFunctionTypeArguments(type, instantiated);
}
+ JS.LiteralString _emitDynamicOperationName(String name) =>
+ js.string(options.replCompile ? '${name}Repl' : name);
+
JS.Expression _emitAccessInternal(Expression target, Element member,
String memberName, List<JS.Expression> typeArgs) {
bool isStatic = member is ClassMemberElement && member.isStatic;
@@ -4649,7 +4671,8 @@
[l, l, name, l, name])
]);
}
- return js.call('dart.dload(#, #)', [_visit(target), name]);
+ return js.call('dart.#(#, #)',
+ [_emitDynamicOperationName('dload'), _visit(target), name]);
}
var jsTarget = _visit(target);
@@ -5452,17 +5475,16 @@
return uri.path;
}
// TODO(vsm): This is not necessarily unique if '__' appears in a file name.
- var customSeparator = '__';
+ var separator = '__';
String qualifiedPath;
if (uri.scheme == 'package') {
// Strip the package name.
// TODO(vsm): This is not unique if an escaped '/'appears in a filename.
// E.g., "foo/bar.dart" and "foo$47bar.dart" would collide.
- qualifiedPath = uri.pathSegments.skip(1).join(customSeparator);
- } else if (isWithin(libraryRoot, uri.toFilePath())) {
- qualifiedPath = fromUri(uri)
- .substring(libraryRoot.length)
- .replaceAll(separator, customSeparator);
+ qualifiedPath = uri.pathSegments.skip(1).join(separator);
+ } else if (uri.toFilePath().startsWith(libraryRoot)) {
+ qualifiedPath =
+ uri.path.substring(libraryRoot.length).replaceAll('/', separator);
} else {
// We don't have a unique name.
throw 'Invalid library root. $libraryRoot does not contain ${uri
diff --git a/pkg/dev_compiler/lib/src/compiler/compiler.dart b/pkg/dev_compiler/lib/src/compiler/compiler.dart
index 1e57ada..c5d9387 100644
--- a/pkg/dev_compiler/lib/src/compiler/compiler.dart
+++ b/pkg/dev_compiler/lib/src/compiler/compiler.dart
@@ -16,6 +16,7 @@
show Source, SourceKind, UriResolver;
import 'package:analyzer/src/summary/package_bundle_reader.dart'
show InSummarySource, InputPackagesResultProvider, SummaryDataStore;
+import 'package:analyzer/src/error/codes.dart' show StaticTypeWarningCode;
import 'package:args/args.dart' show ArgParser, ArgResults;
import 'package:args/src/usage_exception.dart' show UsageException;
import 'package:func/func.dart' show Func1;
@@ -97,6 +98,21 @@
return new ModuleCompiler.withContext(context, summaryData);
}
+ bool _isFatalError(AnalysisError e, CompilerOptions options) {
+ if (errorSeverity(context, e) != ErrorSeverity.ERROR) return false;
+
+ // These errors are not fatal in the REPL compile mode as we
+ // allow access to private members across library boundaries
+ // and those accesses will show up as undefined members unless
+ // additional analyzer changes are made to support them.
+ // TODO(jacobr): consider checking that the identifier name
+ // referenced by the error is private.
+ return !options.replCompile ||
+ (e.errorCode != StaticTypeWarningCode.UNDEFINED_GETTER &&
+ e.errorCode != StaticTypeWarningCode.UNDEFINED_SETTER &&
+ e.errorCode != StaticTypeWarningCode.UNDEFINED_METHOD);
+ }
+
/// Compiles a single Dart build unit into a JavaScript module.
///
/// *Warning* - this may require resolving the entire world.
@@ -111,10 +127,10 @@
var compilingSdk = false;
for (var sourcePath in unit.sources) {
var sourceUri = Uri.parse(sourcePath);
- if (sourceUri.scheme == 'dart') {
- compilingSdk = true;
- } else if (sourceUri.scheme != 'package') {
+ if (sourceUri.scheme == '') {
sourceUri = path.toUri(path.absolute(sourcePath));
+ } else if (sourceUri.scheme == 'dart') {
+ compilingSdk = true;
}
Source source = context.sourceFactory.forUri2(sourceUri);
@@ -159,6 +175,7 @@
}
sortErrors(context, errors);
+
var messages = <String>[];
for (var e in errors) {
var m = formatError(context, e);
@@ -166,10 +183,9 @@
}
if (!options.unsafeForceCompile &&
- errors.any((e) => errorSeverity(context, e) == ErrorSeverity.ERROR)) {
+ errors.any((e) => _isFatalError(e, options))) {
return new JSModuleFile.invalid(unit.name, messages, options);
}
-
var codeGenerator =
new CodeGenerator(context, summaryData, options, _extensionTypes);
return codeGenerator.compile(unit, trees, messages);
@@ -204,6 +220,10 @@
/// Whether to force compilation of code with static errors.
final bool unsafeForceCompile;
+ /// Whether to compile code in a more permissive REPL mode allowing access
+ /// to private members across library boundaries.
+ final bool replCompile;
+
/// Whether to emit Closure Compiler-friendly code.
final bool closure;
@@ -248,6 +268,7 @@
this.summarizeApi: true,
this.summaryExtension: 'sum',
this.unsafeForceCompile: false,
+ this.replCompile: false,
this.emitMetadata: false,
this.closure: false,
this.destructureNamedParams: false,
@@ -265,6 +286,7 @@
summarizeApi = args['summarize'],
summaryExtension = args['summary-extension'],
unsafeForceCompile = args['unsafe-force-compile'],
+ replCompile = args['repl-compile'],
emitMetadata = args['emit-metadata'],
closure = args['closure-experimental'],
destructureNamedParams = args['destructure-named-params'],
@@ -303,6 +325,11 @@
'This has undefined behavior!',
defaultsTo: false,
hide: true)
+ ..addFlag('repl-compile',
+ help: 'Compile code more permissively when in REPL mode allowing '
+ 'access to private members across library boundaries.',
+ defaultsTo: false,
+ hide: true)
..addFlag('hoist-instance-creation',
help: 'Hoist the class type from generic instance creations',
defaultsTo: true,
@@ -503,7 +530,7 @@
if (match != null) return match;
// Fall back to a relative path.
- return path.toUri(path.relative(uri, from: dir)).toString();
+ return path.toUri(path.relative(path.fromUri(uri), from: dir)).toString();
}
for (int i = 0; i < list.length; i++) {
diff --git a/pkg/dev_compiler/tool/input_sdk/private/ddc_runtime/classes.dart b/pkg/dev_compiler/tool/input_sdk/private/ddc_runtime/classes.dart
index d6f3423..f6b12eb 100644
--- a/pkg/dev_compiler/tool/input_sdk/private/ddc_runtime/classes.dart
+++ b/pkg/dev_compiler/tool/input_sdk/private/ddc_runtime/classes.dart
@@ -501,10 +501,13 @@
/// Like [setBaseClass] but for generic extension types, e.g. `JSArray<E>`
setExtensionBaseClass(derived, base) {
- // Mark the generic type as an extension type.
- JS('', '#.prototype[#] = #', derived, _extensionType, derived);
- // Link the prototype objects
- JS('', '#.prototype.__proto__ = #.prototype', derived, base);
+ // Mark the generic type as an extension type and link the prototype objects
+ return JS('', '''(() => {
+ if ($base) {
+ $derived.prototype[$_extensionType] = $derived;
+ $derived.prototype.__proto__ = $base.prototype
+ }
+})()''');
}
/// Given a special constructor function that creates a function instances,
diff --git a/pkg/dev_compiler/tool/input_sdk/private/ddc_runtime/operations.dart b/pkg/dev_compiler/tool/input_sdk/private/ddc_runtime/operations.dart
index 913860a..ba0dbc6 100644
--- a/pkg/dev_compiler/tool/input_sdk/private/ddc_runtime/operations.dart
+++ b/pkg/dev_compiler/tool/input_sdk/private/ddc_runtime/operations.dart
@@ -19,15 +19,13 @@
this.isMethod: false,
this.isGetter: false,
this.isSetter: false})
- : memberName = _dartSymbol(memberName),
- namedArguments = _namedArgsToSymbols(namedArguments);
+ : memberName = _dartSymbol(memberName),
+ namedArguments = _namedArgsToSymbols(namedArguments);
static Map<Symbol, dynamic> _namedArgsToSymbols(namedArgs) {
if (namedArgs == null) return {};
- return new Map.fromIterable(
- getOwnPropertyNames(namedArgs),
- key: _dartSymbol,
- value: (k) => JS('', '#[#]', namedArgs, k));
+ return new Map.fromIterable(getOwnPropertyNames(namedArgs),
+ key: _dartSymbol, value: (k) => JS('', '#[#]', namedArgs, k));
}
}
@@ -38,8 +36,8 @@
if (hasMethod(obj, f)) return bind(obj, f, JS('', 'void 0'));
return JS('', '#[#]', obj, f);
}
- return noSuchMethod(obj,
- new InvocationImpl(field, JS('', '[]'), isGetter: true));
+ return noSuchMethod(
+ obj, new InvocationImpl(field, JS('', '[]'), isGetter: true));
}
dput(obj, field, value) {
@@ -48,13 +46,15 @@
if (f != null) {
return JS('', '#[#] = #', obj, f, value);
}
- return noSuchMethod(obj,
- new InvocationImpl(field, JS('', '[#]', value), isSetter: true));
+ return noSuchMethod(
+ obj, new InvocationImpl(field, JS('', '[#]', value), isSetter: true));
}
/// Check that a function of a given type can be applied to
/// actuals.
-_checkApply(type, actuals) => JS('', '''(() => {
+_checkApply(type, actuals) => JS(
+ '',
+ '''(() => {
if ($actuals.length < $type.args.length) return false;
let index = 0;
for(let i = 0; i < $type.args.length; ++i) {
@@ -97,15 +97,17 @@
extractNamedArgs(args) {
if (JS('bool', '#.length > 0', args)) {
var last = JS('', '#[#.length - 1]', args, args);
- if (JS('bool', '# != null && #.__proto__ === Object.prototype',
- last, last)) {
+ if (JS(
+ 'bool', '# != null && #.__proto__ === Object.prototype', last, last)) {
return JS('', '#.pop()', args);
}
}
return null;
}
-_checkAndCall(f, ftype, obj, typeArgs, args, name) => JS('', '''(() => {
+_checkAndCall(f, ftype, obj, typeArgs, args, name) => JS(
+ '',
+ '''(() => {
$_trackCall($obj);
let originalTarget = obj === void 0 ? f : obj;
@@ -176,12 +178,68 @@
return callNSM();
})()''');
-dcall(f, @rest args) => _checkAndCall(
- f, _getRuntimeType(f), JS('', 'void 0'), null, args, 'call');
+dcall(f, @rest args) =>
+ _checkAndCall(f, _getRuntimeType(f), JS('', 'void 0'), null, args, 'call');
dgcall(f, typeArgs, @rest args) => _checkAndCall(
f, _getRuntimeType(f), JS('', 'void 0'), typeArgs, args, 'call');
+/// Helper for REPL dynamic invocation variants that make a best effort to
+/// enable accessing private members across library boundaries.
+_dhelperRepl(object, field, callback) => JS(
+ '',
+ '''(() => {
+ let rawField = $field;
+ if (typeof(field) == 'symbol') {
+ // test if the specified field exists in which case it is safe to use it.
+ if ($field in $object) return $callback($field);
+
+ // Symbol is from a different library. Make a best effort to
+ $field = $field.toString();
+ $field = $field.substring('Symbol('.length, field.length - 1);
+
+ } else if ($field.charAt(0) != '_') {
+ // Not a private member so default call path is safe.
+ return $callback($field);
+ }
+
+ // If the exact field name is present, invoke callback with it.
+ if ($field in $object) return $callback($field);
+
+ // TODO(jacobr): warn if there are multiple private members with the same
+ // name which could happen if super classes in different libraries have
+ // the same private member name.
+ let proto = $object;
+ while (proto !== null) {
+ // Private field (indicated with "_").
+ let symbols = Object.getOwnPropertySymbols(proto);
+ let target = 'Symbol(' + $field + ')';
+
+ for (let s = 0; s < symbols.length; s++) {
+ let sym = symbols[s];
+ if (target == sym.toString()) return $callback(sym);
+ }
+ proto = proto.__proto__;
+ }
+ // We didn't find a plausible alternate private symbol so just fall back
+ // to the regular field.
+ return $callback(rawField);
+})()''');
+
+dloadRepl(obj, field) =>
+ _dhelperRepl(obj, field, (resolvedField) => dload(obj, resolvedField));
+
+dputRepl(obj, field, value) => _dhelperRepl(
+ obj, field, (resolvedField) => dput(obj, resolvedField, value));
+
+_callMethodRepl(obj, method, typeArgs, args) => _dhelperRepl(obj, method,
+ (resolvedField) => _callMethod(obj, resolvedField, typeArgs, args, method));
+
+dsendRepl(obj, method, @rest args) => _callMethodRepl(obj, method, null, args);
+
+dgsendRepl(obj, typeArgs, method, @rest args) =>
+ _callMethodRepl(obj, method, typeArgs, args);
+
class _MethodStats {
final String typeName;
final String frame;
@@ -199,8 +257,8 @@
var keys = _callMethodStats.keys.toList();
- keys.sort((a, b) => _callMethodStats[b].count.compareTo(
- _callMethodStats[a].count));
+ keys.sort(
+ (a, b) => _callMethodStats[b].count.compareTo(_callMethodStats[a].count));
for (var key in keys) {
var stats = _callMethodStats[key];
ret.add([stats.typeName, stats.frame, stats.count]);
@@ -231,16 +289,18 @@
}
var actualTypeName = typeName(actual);
- _callMethodStats.putIfAbsent("$actualTypeName <$src>",
- () => new _MethodStats(actualTypeName, src)).count++;
+ _callMethodStats
+ .putIfAbsent(
+ "$actualTypeName <$src>", () => new _MethodStats(actualTypeName, src))
+ .count++;
}
/// Shared code for dsend, dindex, and dsetindex.
_callMethod(obj, name, typeArgs, args, displayName) {
var symbol = _canonicalMember(obj, name);
if (symbol == null) {
- return noSuchMethod(obj,
- new InvocationImpl(displayName, args, isMethod: true));
+ return noSuchMethod(
+ obj, new InvocationImpl(displayName, args, isMethod: true));
}
var f = obj != null ? JS('', '#[#]', obj, symbol) : null;
var ftype = getMethodType(obj, symbol);
@@ -260,7 +320,9 @@
/// TODO(leafp): This duplicates code in types.dart.
/// I haven't found a way to factor it out that makes the
/// code generator happy though.
-_ignoreMemo(f) => JS('', '''(() => {
+_ignoreMemo(f) => JS(
+ '',
+ '''(() => {
let memo = new Map();
return (t1, t2) => {
let map = memo.get(t1);
@@ -277,7 +339,9 @@
};
})()''');
-final _ignoreTypeFailure = JS('', '''(() => {
+final _ignoreTypeFailure = JS(
+ '',
+ '''(() => {
return $_ignoreMemo((actual, type) => {
// TODO(vsm): Remove this hack ...
// This is primarily due to the lack of generic methods,
@@ -302,7 +366,9 @@
/// and strong mode
/// Returns null if [obj] is not an instance of [type] in strong mode
/// but might be in spec mode
-bool strongInstanceOf(obj, type, ignoreFromWhiteList) => JS('', '''(() => {
+bool strongInstanceOf(obj, type, ignoreFromWhiteList) => JS(
+ '',
+ '''(() => {
let actual = $getReifiedType($obj);
let result = $isSubtype(actual, $type);
if (result || actual == $jsobject ||
@@ -316,14 +382,18 @@
/// Returns true if [obj] is null or an instance of [type]
/// Returns false if [obj] is non-null and not an instance of [type]
/// in strong mode
-instanceOfOrNull(obj, type) => JS('', '''(() => {
+instanceOfOrNull(obj, type) => JS(
+ '',
+ '''(() => {
// If strongInstanceOf returns null, convert to false here.
if (($obj == null) || $strongInstanceOf($obj, $type, true)) return true;
return false;
})()''');
@JSExportName('is')
-instanceOf(obj, type) => JS('', '''(() => {
+instanceOf(obj, type) => JS(
+ '',
+ '''(() => {
let result = $strongInstanceOf($obj, $type);
if (result !== null) return result;
let actual = $getReifiedType($obj);
@@ -389,7 +459,9 @@
/// Adds type type test predicates to a constructor for a non-parameterized
/// type. Non-parameterized types can use `instanceof` for subclass checks and
/// fall through to a helper for subtype tests.
-addSimpleTypeTests(ctor) => JS('', '''(() => {
+addSimpleTypeTests(ctor) => JS(
+ '',
+ '''(() => {
$ctor.is = function is_C(object) {
// This is incorrect for classes [Null] and [Object], so we do not use
// [addSimpleTypeTests] for these classes.
@@ -409,7 +481,9 @@
/// Adds type type test predicates to a constructor. Used for parmeterized
/// types. We avoid `instanceof` for, e.g. `x is ListQueue` since there is
/// no common class for `ListQueue<int>` and `ListQueue<String>`.
-addTypeTests(ctor) => JS('', '''(() => {
+addTypeTests(ctor) => JS(
+ '',
+ '''(() => {
$ctor.as = function as_G(object) {
return dart.as(object, this);
};
@@ -421,7 +495,9 @@
};
})()''');
-equals(x, y) => JS('', '''(() => {
+equals(x, y) => JS(
+ '',
+ '''(() => {
if ($x == null || $y == null) return $x == $y;
let eq = $x['=='];
return eq ? eq.call($x, $y) : $x === $y;
@@ -449,7 +525,9 @@
// TODO(jmesserly): this could be faster
// TODO(jmesserly): we can use default values `= dynamic` once #417 is fixed.
// TODO(jmesserly): move this to classes for consistentcy with list literals?
-map(values, [K, V]) => JS('', '''(() => {
+map(values, [K, V]) => JS(
+ '',
+ '''(() => {
if ($K == null) $K = $dynamic;
if ($V == null) $V = $dynamic;
let map = ${getGenericClass(LinkedHashMap)}($K, $V).new();
@@ -468,13 +546,17 @@
})()''');
@JSExportName('assert')
-assert_(condition) => JS('', '''(() => {
+assert_(condition) => JS(
+ '',
+ '''(() => {
if (!$condition) $throwAssertionError();
})()''');
final _stack = JS('', 'new WeakMap()');
@JSExportName('throw')
-throw_(obj) => JS('', '''(() => {
+throw_(obj) => JS(
+ '',
+ '''(() => {
if ($obj != null && (typeof $obj == 'object' || typeof $obj == 'function')) {
// TODO(jmesserly): couldn't we store the most recent stack in a single
// variable? There should only be one active stack trace. That would
@@ -484,19 +566,25 @@
throw $obj;
})()''');
-getError(exception) => JS('', '''(() => {
+getError(exception) => JS(
+ '',
+ '''(() => {
var stack = $_stack.get($exception);
return stack !== void 0 ? stack : $exception;
})()''');
// This is a utility function: it is only intended to be called from dev
// tools.
-stackPrint(exception) => JS('', '''(() => {
+stackPrint(exception) => JS(
+ '',
+ '''(() => {
var error = $getError($exception);
console.log(error.stack ? error.stack : 'No stack trace for: ' + error);
})()''');
-stackTrace(exception) => JS('', '''(() => {
+stackTrace(exception) => JS(
+ '',
+ '''(() => {
var error = $getError($exception);
return $getTraceFromException(error);
})()''');
@@ -507,7 +595,9 @@
/// Will call each successive callback, unless one returns null, which stops
/// the sequence.
///
-nullSafe(obj, @rest callbacks) => JS('', '''(() => {
+nullSafe(obj, @rest callbacks) => JS(
+ '',
+ '''(() => {
if ($obj == null) return $obj;
for (let callback of $callbacks) {
$obj = callback($obj);
@@ -517,6 +607,7 @@
})()''');
final _value = JS('', 'Symbol("_value")');
+
///
/// Looks up a sequence of [keys] in [map], recursively, and
/// returns the result. If the value is not found, [valueFn] will be called to
@@ -529,7 +620,9 @@
///
/// { 1: { 2: { 'hi ': { 'there ': 'world' } } } }
///
-multiKeyPutIfAbsent(map, keys, valueFn) => JS('', '''(() => {
+multiKeyPutIfAbsent(map, keys, valueFn) => JS(
+ '',
+ '''(() => {
for (let k of $keys) {
let value = $map.get(k);
if (!value) {
@@ -561,7 +654,9 @@
/// - nested values of the object are themselves already canonicalized.
///
@JSExportName('const')
-const_(obj) => JS('', '''(() => {
+const_(obj) => JS(
+ '',
+ '''(() => {
// TODO(leafp): This table gets quite large in apps.
// Keeping the paths is probably expensive. It would probably
// be more space efficient to just use a direct hash table with
@@ -612,7 +707,9 @@
/// Canonicalize a constant list
///
@JSExportName('constList')
-constList_(elements, elementType) => JS('', '''(() => {
+constList_(elements, elementType) => JS(
+ '',
+ '''(() => {
function lookupNonTerminal(map, key) {
let result = map.get(key);
if (result !== void 0) return result;
@@ -639,7 +736,7 @@
switch (JS('String', 'typeof #', obj)) {
case "number":
- return JS('','# & 0x1FFFFFFF', obj);
+ return JS('', '# & 0x1FFFFFFF', obj);
case "boolean":
// From JSBool.hashCode, see comment there.
return JS('', '# ? (2 * 3 * 23 * 3761) : (269 * 811)', obj);
@@ -664,8 +761,8 @@
return JS('String', '#[dartx.toString]()', obj);
}
if (JS('bool', 'typeof # == "function"', obj)) {
- return JS('String', r'"Closure: " + # + " from: " + #',
- getReifiedType(obj), obj);
+ return JS(
+ 'String', r'"Closure: " + # + " from: " + #', getReifiedType(obj), obj);
}
// TODO(jmesserly): restore this faster path once ES Symbol is treated as
// an extension type (and thus hits the above code path).
@@ -677,11 +774,8 @@
// TODO(jmesserly): is the argument type verified statically?
noSuchMethod(obj, Invocation invocation) {
if (obj == null || JS('bool', 'typeof # == "function"', obj)) {
- throw new NoSuchMethodError(
- obj,
- invocation.memberName,
- invocation.positionalArguments,
- invocation.namedArguments);
+ throw new NoSuchMethodError(obj, invocation.memberName,
+ invocation.positionalArguments, invocation.namedArguments);
}
// Delegate to the (possibly user-defined) method on the object.
var extension = getExtensionType(obj);
@@ -712,7 +806,9 @@
/// Implements Dart's interpolated strings as ES2015 tagged template literals.
///
/// For example: dart.str`hello ${name}`
-String str(strings, @rest values) => JS('', '''(() => {
+String str(strings, @rest values) => JS(
+ '',
+ '''(() => {
let s = $strings[0];
for (let i = 0, len = $values.length; i < len; ) {
s += $notNull($_toString($values[i])) + $strings[++i];
@@ -720,8 +816,9 @@
return s;
})()''');
-
-final JsIterator = JS('', '''
+final JsIterator = JS(
+ '',
+ '''
class JsIterator {
constructor(dartIterator) {
this.dartIterator = dartIterator;
diff --git a/pkg/dev_compiler/tool/sdk_expected_errors.txt b/pkg/dev_compiler/tool/sdk_expected_errors.txt
index a62967e..7c083b0 100644
--- a/pkg/dev_compiler/tool/sdk_expected_errors.txt
+++ b/pkg/dev_compiler/tool/sdk_expected_errors.txt
@@ -1,175 +1,175 @@
-[error] Could not infer type parameter T, _ControllerEventSinkWrapper<dynamic> must be of type EventSink<T>. (dart:async/stream.dart, line 1346, col 16)
-[error] The argument type '_ControllerEventSinkWrapper' cannot be assigned to the parameter type 'EventSink<T>'. (dart:async/stream.dart, line 1346, col 53)
-[error] Invalid override. The type of ChunkedConverter.bind ((dynamic) → dynamic) is not a subtype of Converter<S, T>.bind ((Stream<S>) → Stream<T>). (dart:convert/chunked_conversion.dart, line 14, col 3)
-[error] Invalid override. The type of ChunkedConverter.bind ((dynamic) → dynamic) is not a subtype of StreamTransformer<S, T>.bind ((Stream<S>) → Stream<T>). (dart:convert/chunked_conversion.dart, line 14, col 3)
-[error] Invalid override. The type of ChunkedConverter.startChunkedConversion ((dynamic) → dynamic) is not a subtype of Converter<S, T>.startChunkedConversion ((Sink<T>) → Sink<S>). (dart:convert/chunked_conversion.dart, line 15, col 3)
-[error] Invalid override. The type of _EventStreamSubscription.asFuture (([dynamic]) → Future<dynamic>) is not a subtype of StreamSubscription<T>.asFuture (<E>([E]) → Future<E>). (dart:html, line 40152, col 3)
-[error] Invalid override. The type of JsArray.[]= ((Object, E) → void) is not a subtype of JsObject.[]= ((Object, dynamic) → dynamic). (dart:js, line 363, col 3)
-[warning] Unsound implicit cast from dynamic to List<String> (dart:_debugger, line 39, col 45)
-[warning] Unsound implicit cast from dynamic to List<NameValuePair> (dart:_debugger, line 750, col 43)
-[warning] Unsound implicit cast from dynamic to List<String> (dart:_isolate_helper, line 839, col 37)
-[warning] Unsound implicit cast from dynamic to List<String> (dart:_isolate_helper, line 886, col 11)
-[warning] Unsound implicit cast from dynamic to E (dart:_interceptors/js_array.dart, line 117, col 12)
-[warning] Unsound implicit cast from dynamic to E (dart:_interceptors/js_array.dart, line 159, col 17)
-[warning] Unsound implicit cast from dynamic to E (dart:_interceptors/js_array.dart, line 167, col 17)
-[warning] Unsound implicit cast from dynamic to E (dart:_interceptors/js_array.dart, line 198, col 27)
-[warning] Unsound implicit cast from dynamic to E (dart:_interceptors/js_array.dart, line 239, col 27)
-[warning] Unsound implicit cast from dynamic to E (dart:_interceptors/js_array.dart, line 252, col 27)
-[warning] Unsound implicit cast from dynamic to E (dart:_interceptors/js_array.dart, line 264, col 27)
-[warning] Unsound implicit cast from dynamic to E (dart:_interceptors/js_array.dart, line 277, col 27)
-[warning] Unsound implicit cast from dynamic to E (dart:_interceptors/js_array.dart, line 295, col 16)
-[warning] Unsound implicit cast from dynamic to E (dart:_interceptors/js_array.dart, line 300, col 17)
-[warning] Unsound implicit cast from dynamic to E (dart:_interceptors/js_array.dart, line 443, col 27)
-[warning] Unsound implicit cast from dynamic to E (dart:_interceptors/js_array.dart, line 455, col 27)
-[warning] Unsound implicit cast from dynamic to E (dart:_interceptors/js_array.dart, line 564, col 12)
-[warning] Unsound implicit cast from dynamic to JSArray<String> (dart:_js_helper, line 79, col 37)
-[warning] Unsound implicit cast from dynamic to E (dart:_js_helper, line 882, col 16)
-[warning] Unsound implicit cast from dynamic to () → List<Type> (dart:_js_mirrors, line 422, col 40)
-[warning] Unsound implicit cast from dynamic to List<String> (dart:_interceptors/js_string.dart, line 92, col 14)
-[warning] Unsound implicit cast from dynamic to List<String> (dart:_interceptors/js_string.dart, line 95, col 14)
-[warning] Unsound implicit cast from dynamic to LinkedHashMapCell<K, V> (dart:_js_helper/linked_hash_map.dart, line 119, col 40)
-[warning] Unsound implicit cast from dynamic to LinkedHashMapCell<K, V> (dart:_js_helper/linked_hash_map.dart, line 148, col 44)
-[warning] Unsound implicit cast from dynamic to LinkedHashMapCell<K, V> (dart:_js_helper/linked_hash_map.dart, line 183, col 9)
-[warning] Unsound implicit cast from dynamic to LinkedHashMapCell<K, V> (dart:_js_helper/linked_hash_map.dart, line 299, col 42)
-[warning] Unsound implicit cast from dynamic to LinkedHashMapCell<K, V> (dart:_js_helper/linked_hash_map.dart, line 308, col 12)
-[warning] Unsound implicit cast from dynamic to List<LinkedHashMapCell<K, V>> (dart:_js_helper/linked_hash_map.dart, line 312, col 12)
-[warning] Unsound implicit cast from dynamic to LinkedHashMapCell<K, V> (dart:_js_helper/linked_hash_map.dart, line 346, col 12)
-[warning] Unsound implicit cast from dynamic to List<LinkedHashMapCell<K, V>> (dart:_js_helper/linked_hash_map.dart, line 351, col 12)
-[warning] Unsound implicit cast from dynamic to List<String> (dart:_js_helper/regexp_helper.dart, line 108, col 22)
-[warning] Unsound implicit cast from List<dynamic> to List<String> (dart:_js_helper/regexp_helper.dart, line 140, col 43)
-[warning] Unsound implicit cast from List<dynamic> to List<String> (dart:_js_helper/regexp_helper.dart, line 152, col 43)
-[warning] Unsound implicit cast from dynamic to V (dart:collection, line 105, col 14)
-[warning] Unsound implicit cast from dynamic to V (dart:collection, line 108, col 14)
-[warning] Unsound implicit cast from dynamic to V (dart:collection, line 119, col 12)
-[warning] Unsound implicit cast from dynamic to V (dart:collection, line 186, col 12)
-[warning] Unsound implicit cast from dynamic to K (dart:collection, line 200, col 14)
-[warning] Unsound implicit cast from dynamic to V (dart:collection, line 268, col 17)
-[warning] Unsound implicit cast from dynamic to K (dart:collection, line 404, col 49)
-[warning] Unsound implicit cast from dynamic to K (dart:collection, line 411, col 19)
-[warning] Unsound implicit cast from Object to K (dart:collection, line 411, col 49)
-[warning] Unsound implicit cast from dynamic to E (dart:collection, line 436, col 9)
-[warning] Unsound implicit cast from dynamic to E (dart:collection, line 462, col 18)
-[warning] Unsound implicit cast from dynamic to LinkedHashMapCell<K, V> (dart:collection, line 495, col 42)
-[warning] Unsound implicit cast from dynamic to V (dart:collection, line 532, col 12)
-[warning] Unsound implicit cast from dynamic to K (dart:collection, line 569, col 14)
-[warning] Unsound implicit cast from dynamic to V (dart:collection, line 569, col 19)
-[warning] Unsound implicit cast from dynamic to E (dart:collection, line 614, col 9)
-[warning] Unsound implicit cast from dynamic to E (dart:collection, line 653, col 18)
-[warning] Unsound implicit cast from dynamic to K (dart:collection, line 689, col 49)
-[warning] Unsound implicit cast from dynamic to LinkedHashMapCell<K, V> (dart:collection, line 696, col 42)
-[warning] Unsound implicit cast from dynamic to K (dart:collection, line 697, col 40)
-[warning] Unsound implicit cast from Object to E (dart:collection, line 758, col 14)
-[warning] Unsound implicit cast from dynamic to List<E> (dart:collection, line 951, col 12)
-[warning] Unsound implicit cast from dynamic to E (dart:collection, line 1009, col 21)
-[warning] Unsound implicit cast from dynamic to E (dart:collection, line 1009, col 51)
-[warning] Unsound implicit cast from dynamic to E (dart:collection, line 1019, col 47)
-[warning] Unsound implicit cast from dynamic to E (dart:collection, line 1058, col 18)
-[warning] Unsound implicit cast from Object to E (dart:collection, line 1135, col 14)
-[warning] Unsound implicit cast from dynamic to _LinkedHashSetCell<E> (dart:collection, line 1222, col 38)
-[warning] Unsound implicit cast from dynamic to _LinkedHashSetCell<E> (dart:collection, line 1337, col 12)
-[warning] Unsound implicit cast from dynamic to List<_LinkedHashSetCell<E>> (dart:collection, line 1351, col 12)
-[warning] Unsound implicit cast from dynamic to _LinkedHashSetCell<E> (dart:collection, line 1358, col 40)
-[warning] Unsound implicit cast from dynamic to _LinkedHashSetCell<E> (dart:collection, line 1391, col 40)
-[warning] Unsound implicit cast from dynamic to _LinkedHashSetCell<E> (dart:collection, line 1412, col 40)
-[warning] Unsound implicit cast from dynamic to E (dart:collection, line 1413, col 36)
-[warning] Unsound implicit cast from dynamic to E (dart:collection, line 1423, col 47)
-[warning] Unsound implicit cast from dynamic to E (dart:collection, line 1485, col 18)
-[warning] Unsound implicit cast from dynamic to Stream<S> (dart:convert/chunked_conversion.dart, line 14, col 45)
-[warning] Unsound implicit cast from dynamic to Sink<T> (dart:convert/chunked_conversion.dart, line 16, col 36)
-[warning] Unsound implicit cast from dynamic to List<String> (dart:convert, line 311, col 12)
-[warning] Unsound implicit cast from dynamic to T (dart:core/expando.dart, line 55, col 12)
-[warning] Unsound implicit cast from dynamic to E (dart:core/list.dart, line 126, col 16)
-[warning] The final variable 'origin' must be initialized (dart:html, line 177, col 3)
-[warning] The final variable 'origin' must be initialized (dart:html, line 813, col 3)
-[warning] Unsound implicit cast from dynamic to List<String> (dart:html, line 1145, col 33)
-[warning] The final variables 'form', 'labels' and '3' more must be initialized (dart:html, line 1691, col 3)
-[warning] Unsound implicit cast from dynamic to List<num> (dart:html, line 2723, col 14)
-[warning] Unsound implicit cast from dynamic to List<num> (dart:html, line 2725, col 14)
-[warning] The final variable 'options' must be initialized (dart:html, line 8972, col 3)
-[warning] The final variables '_attributes', '_childElementCount' and '16' more must be initialized (dart:html, line 13009, col 3)
-[warning] The final variables 'elements', 'form' and '4' more must be initialized (dart:html, line 16625, col 3)
-[warning] The final variable 'length' must be initialized (dart:html, line 17555, col 3)
-[warning] The final variables '_get_contentWindow' and 'sandbox' must be initialized (dart:html, line 20113, col 3)
-[warning] The final variables 'complete', 'currentSrc' and '2' more must be initialized (dart:html, line 20246, col 3)
-[warning] The final variables '_get_valueAsDate', 'entries' and '6' more must be initialized (dart:html, line 20400, col 3)
-[warning] The final variables 'form', 'labels' and '4' more must be initialized (dart:html, line 21436, col 3)
-[warning] The final variables 'control' and 'form' must be initialized (dart:html, line 21547, col 3)
-[warning] The final variable 'form' must be initialized (dart:html, line 21581, col 3)
-[warning] The final variables 'import', 'sheet' and '1' more must be initialized (dart:html, line 21607, col 3)
-[warning] The final variable 'areas' must be initialized (dart:html, line 21759, col 3)
-[warning] The final variables 'audioDecodedByteCount', 'audioTracks' and '16' more must be initialized (dart:html, line 21985, col 3)
-[warning] The final variable 'labels' must be initialized (dart:html, line 23501, col 3)
-[warning] The final variables '_localName', '_namespaceUri' and '12' more must be initialized (dart:html, line 24939, col 3)
-[warning] The final variables 'form', 'validationMessage' and '2' more must be initialized (dart:html, line 25820, col 3)
-[warning] The final variables 'form' and 'index' must be initialized (dart:html, line 25955, col 3)
-[warning] The final variables 'form', 'htmlFor' and '5' more must be initialized (dart:html, line 26009, col 3)
-[warning] The final variables 'labels' and 'position' must be initialized (dart:html, line 27415, col 3)
-[warning] The final variables 'form', 'labels' and '4' more must be initialized (dart:html, line 29186, col 3)
-[warning] The final variable 'sheet' must be initialized (dart:html, line 31442, col 3)
-[warning] The final variable 'cellIndex' must be initialized (dart:html, line 31662, col 3)
-[warning] The final variables '_rows' and '_tBodies' must be initialized (dart:html, line 31773, col 3)
-[warning] The final variables '_cells', 'rowIndex' and '1' more must be initialized (dart:html, line 31883, col 3)
-[warning] The final variable '_rows' must be initialized (dart:html, line 31950, col 3)
-[warning] The final variable 'content' must be initialized (dart:html, line 31993, col 3)
-[warning] The final variables 'form', 'labels' and '5' more must be initialized (dart:html, line 32069, col 3)
-[warning] The final variables 'readyState' and 'track' must be initialized (dart:html, line 33056, col 3)
-[warning] The final variables 'decodedFrameCount', 'droppedFrameCount' and '2' more must be initialized (dart:html, line 33754, col 3)
-[warning] Unsound implicit cast from dynamic to Rectangle<num> (dart:html, line 37618, col 14)
-[warning] Unsound implicit cast from dynamic to Rectangle<num> (dart:html, line 37626, col 14)
-[warning] Unsound implicit cast from dynamic to Rectangle<num> (dart:html, line 37634, col 14)
-[warning] Unsound implicit cast from (T) → void to (Event) → dynamic (dart:html, line 40090, col 67)
-[warning] Unsound implicit cast from (T) → void to (Event) → dynamic (dart:html, line 40112, col 45)
-[warning] Unsound implicit cast from num to T (dart:math/rectangle.dart, line 158, col 22)
-[warning] Unsound implicit cast from num to T (dart:math/rectangle.dart, line 159, col 23)
-[warning] Unsound implicit cast from num to T (dart:math/rectangle.dart, line 282, col 10)
-[warning] The final variables 'href' and 'target' must be initialized (dart:svg, line 60, col 3)
-[warning] The final variables 'requiredExtensions', 'requiredFeatures' and '2' more must be initialized (dart:svg, line 489, col 3)
-[warning] The final variables 'cx', 'cy' and '1' more must be initialized (dart:svg, line 562, col 3)
-[warning] The final variable 'clipPathUnits' must be initialized (dart:svg, line 597, col 3)
-[warning] The final variables 'cx', 'cy' and '2' more must be initialized (dart:svg, line 689, col 3)
-[warning] The final variables 'height', 'in1' and '6' more must be initialized (dart:svg, line 732, col 3)
-[warning] The final variables 'height', 'in1' and '6' more must be initialized (dart:svg, line 820, col 3)
-[warning] The final variables 'height', 'in1' and '4' more must be initialized (dart:svg, line 904, col 3)
-[warning] The final variables 'height', 'in1' and '10' more must be initialized (dart:svg, line 952, col 3)
-[warning] The final variables 'bias', 'divisor' and '15' more must be initialized (dart:svg, line 1057, col 3)
-[warning] The final variables 'diffuseConstant', 'height' and '8' more must be initialized (dart:svg, line 1173, col 3)
-[warning] The final variables 'height', 'in1' and '8' more must be initialized (dart:svg, line 1245, col 3)
-[warning] The final variables 'azimuth' and 'elevation' must be initialized (dart:svg, line 1337, col 3)
-[warning] The final variables 'height', 'result' and '3' more must be initialized (dart:svg, line 1375, col 3)
-[warning] The final variables 'height', 'in1' and '6' more must be initialized (dart:svg, line 1547, col 3)
-[warning] The final variables 'height', 'href' and '5' more must be initialized (dart:svg, line 1615, col 3)
-[warning] The final variables 'height', 'result' and '3' more must be initialized (dart:svg, line 1677, col 3)
-[warning] The final variable 'in1' must be initialized (dart:svg, line 1729, col 3)
-[warning] The final variables 'height', 'in1' and '7' more must be initialized (dart:svg, line 1759, col 3)
-[warning] The final variables 'dx', 'dy' and '6' more must be initialized (dart:svg, line 1836, col 3)
-[warning] The final variables 'x', 'y' and '1' more must be initialized (dart:svg, line 1900, col 3)
-[warning] The final variables 'height', 'in1' and '9' more must be initialized (dart:svg, line 1942, col 3)
-[warning] The final variables 'limitingConeAngle', 'pointsAtX' and '6' more must be initialized (dart:svg, line 2020, col 3)
-[warning] The final variables 'height', 'in1' and '4' more must be initialized (dart:svg, line 2082, col 3)
-[warning] The final variables 'baseFrequencyX', 'baseFrequencyY' and '9' more must be initialized (dart:svg, line 2138, col 3)
-[warning] The final variables 'filterUnits', 'height' and '5' more must be initialized (dart:svg, line 2238, col 3)
-[warning] The final variables 'height', 'width' and '2' more must be initialized (dart:svg, line 2335, col 3)
-[warning] The final variables 'farthestViewportElement', 'nearestViewportElement' and '4' more must be initialized (dart:svg, line 2425, col 3)
-[warning] The final variables 'height', 'href' and '4' more must be initialized (dart:svg, line 2507, col 3)
-[warning] The final variables 'x1', 'x2' and '2' more must be initialized (dart:svg, line 2736, col 3)
-[warning] The final variables 'x1', 'x2' and '2' more must be initialized (dart:svg, line 2775, col 3)
-[warning] The final variables 'markerHeight', 'markerUnits' and '7' more must be initialized (dart:svg, line 2814, col 3)
-[warning] The final variables 'height', 'maskContentUnits' and '7' more must be initialized (dart:svg, line 2907, col 3)
-[warning] The final variables 'animatedNormalizedPathSegList', 'animatedPathSegList' and '3' more must be initialized (dart:svg, line 3188, col 3)
-[warning] The final variables 'height', 'href' and '11' more must be initialized (dart:svg, line 4017, col 3)
-[warning] The final variables 'animatedPoints' and 'points' must be initialized (dart:svg, line 4182, col 3)
-[warning] The final variables 'animatedPoints' and 'points' must be initialized (dart:svg, line 4213, col 3)
-[warning] The final variables 'cx', 'cy' and '4' more must be initialized (dart:svg, line 4321, col 3)
-[warning] The final variables 'height', 'rx' and '4' more must be initialized (dart:svg, line 4397, col 3)
-[warning] The final variable 'href' must be initialized (dart:svg, line 4444, col 3)
-[warning] The final variable 'gradientOffset' must be initialized (dart:svg, line 4506, col 3)
-[warning] The final variable 'sheet' must be initialized (dart:svg, line 4634, col 3)
-[warning] The final variables 'ownerSvgElement' and 'viewportElement' must be initialized (dart:svg, line 5072, col 3)
-[warning] The final variables 'currentTranslate', 'currentView' and '12' more must be initialized (dart:svg, line 5386, col 3)
-[warning] The final variables 'preserveAspectRatio' and 'viewBox' must be initialized (dart:svg, line 5605, col 3)
-[warning] The final variables 'lengthAdjust' and 'textLength' must be initialized (dart:svg, line 5677, col 3)
-[warning] The final variables 'href', 'method' and '2' more must be initialized (dart:svg, line 5775, col 3)
-[warning] The final variables 'dx', 'dy' and '3' more must be initialized (dart:svg, line 5836, col 3)
-[warning] The final variables 'height', 'href' and '3' more must be initialized (dart:svg, line 6126, col 3)
-[warning] The final variables 'preserveAspectRatio', 'viewBox' and '1' more must be initialized (dart:svg, line 6171, col 3)
-[warning] The final variables 'gradientTransform', 'gradientUnits' and '2' more must be initialized (dart:svg, line 6325, col 3)
+[error] Couldn't infer type parameter 'T'; '_ControllerEventSinkWrapper<dynamic>' must be of type 'EventSink<T>'. (dart:async/stream.dart, line 1346, col 16)
+[error] The argument type '_ControllerEventSinkWrapper' can't be assigned to the parameter type 'EventSink<T>'. (dart:async/stream.dart, line 1346, col 53)
+[error] Invalid override. The type of 'ChunkedConverter.bind' ('(dynamic) → dynamic') isn't a subtype of 'Converter<S, T>.bind' ('(Stream<S>) → Stream<T>'). (dart:convert/chunked_conversion.dart, line 14, col 3)
+[error] Invalid override. The type of 'ChunkedConverter.bind' ('(dynamic) → dynamic') isn't a subtype of 'StreamTransformer<S, T>.bind' ('(Stream<S>) → Stream<T>'). (dart:convert/chunked_conversion.dart, line 14, col 3)
+[error] Invalid override. The type of 'ChunkedConverter.startChunkedConversion' ('(dynamic) → dynamic') isn't a subtype of 'Converter<S, T>.startChunkedConversion' ('(Sink<T>) → Sink<S>'). (dart:convert/chunked_conversion.dart, line 15, col 3)
+[error] Invalid override. The type of '_EventStreamSubscription.asFuture' ('([dynamic]) → Future<dynamic>') isn't a subtype of 'StreamSubscription<T>.asFuture' ('<E>([E]) → Future<E>'). (dart:html, line 40152, col 3)
+[error] Invalid override. The type of 'JsArray.[]=' ('(Object, E) → void') isn't a subtype of 'JsObject.[]=' ('(Object, dynamic) → dynamic'). (dart:js, line 363, col 3)
+[warning] Unsound implicit cast from 'dynamic' to 'List<String>'. (dart:_debugger, line 39, col 45)
+[warning] Unsound implicit cast from 'dynamic' to 'List<NameValuePair>'. (dart:_debugger, line 750, col 43)
+[warning] Unsound implicit cast from 'dynamic' to 'List<String>'. (dart:_isolate_helper, line 839, col 37)
+[warning] Unsound implicit cast from 'dynamic' to 'List<String>'. (dart:_isolate_helper, line 886, col 11)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 117, col 12)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 159, col 17)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 167, col 17)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 198, col 27)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 239, col 27)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 252, col 27)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 264, col 27)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 277, col 27)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 295, col 16)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 300, col 17)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 443, col 27)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 455, col 27)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_interceptors/js_array.dart, line 564, col 12)
+[warning] Unsound implicit cast from 'dynamic' to 'JSArray<String>'. (dart:_js_helper, line 79, col 37)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:_js_helper, line 882, col 16)
+[warning] Unsound implicit cast from 'dynamic' to '() → List<Type>'. (dart:_js_mirrors, line 422, col 40)
+[warning] Unsound implicit cast from 'dynamic' to 'List<String>'. (dart:_interceptors/js_string.dart, line 92, col 14)
+[warning] Unsound implicit cast from 'dynamic' to 'List<String>'. (dart:_interceptors/js_string.dart, line 95, col 14)
+[warning] Unsound implicit cast from 'dynamic' to 'LinkedHashMapCell<K, V>'. (dart:_js_helper/linked_hash_map.dart, line 119, col 40)
+[warning] Unsound implicit cast from 'dynamic' to 'LinkedHashMapCell<K, V>'. (dart:_js_helper/linked_hash_map.dart, line 148, col 44)
+[warning] Unsound implicit cast from 'dynamic' to 'LinkedHashMapCell<K, V>'. (dart:_js_helper/linked_hash_map.dart, line 183, col 9)
+[warning] Unsound implicit cast from 'dynamic' to 'LinkedHashMapCell<K, V>'. (dart:_js_helper/linked_hash_map.dart, line 299, col 42)
+[warning] Unsound implicit cast from 'dynamic' to 'LinkedHashMapCell<K, V>'. (dart:_js_helper/linked_hash_map.dart, line 308, col 12)
+[warning] Unsound implicit cast from 'dynamic' to 'List<LinkedHashMapCell<K, V>>'. (dart:_js_helper/linked_hash_map.dart, line 312, col 12)
+[warning] Unsound implicit cast from 'dynamic' to 'LinkedHashMapCell<K, V>'. (dart:_js_helper/linked_hash_map.dart, line 346, col 12)
+[warning] Unsound implicit cast from 'dynamic' to 'List<LinkedHashMapCell<K, V>>'. (dart:_js_helper/linked_hash_map.dart, line 351, col 12)
+[warning] Unsound implicit cast from 'dynamic' to 'List<String>'. (dart:_js_helper/regexp_helper.dart, line 108, col 22)
+[warning] Unsound implicit cast from 'List<dynamic>' to 'List<String>'. (dart:_js_helper/regexp_helper.dart, line 140, col 43)
+[warning] Unsound implicit cast from 'List<dynamic>' to 'List<String>'. (dart:_js_helper/regexp_helper.dart, line 152, col 43)
+[warning] Unsound implicit cast from 'dynamic' to 'V'. (dart:collection, line 105, col 14)
+[warning] Unsound implicit cast from 'dynamic' to 'V'. (dart:collection, line 108, col 14)
+[warning] Unsound implicit cast from 'dynamic' to 'V'. (dart:collection, line 119, col 12)
+[warning] Unsound implicit cast from 'dynamic' to 'V'. (dart:collection, line 186, col 12)
+[warning] Unsound implicit cast from 'dynamic' to 'K'. (dart:collection, line 200, col 14)
+[warning] Unsound implicit cast from 'dynamic' to 'V'. (dart:collection, line 268, col 17)
+[warning] Unsound implicit cast from 'dynamic' to 'K'. (dart:collection, line 404, col 49)
+[warning] Unsound implicit cast from 'dynamic' to 'K'. (dart:collection, line 411, col 19)
+[warning] Unsound implicit cast from 'Object' to 'K'. (dart:collection, line 411, col 49)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:collection, line 436, col 9)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:collection, line 462, col 18)
+[warning] Unsound implicit cast from 'dynamic' to 'LinkedHashMapCell<K, V>'. (dart:collection, line 495, col 42)
+[warning] Unsound implicit cast from 'dynamic' to 'V'. (dart:collection, line 532, col 12)
+[warning] Unsound implicit cast from 'dynamic' to 'K'. (dart:collection, line 569, col 14)
+[warning] Unsound implicit cast from 'dynamic' to 'V'. (dart:collection, line 569, col 19)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:collection, line 614, col 9)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:collection, line 653, col 18)
+[warning] Unsound implicit cast from 'dynamic' to 'K'. (dart:collection, line 689, col 49)
+[warning] Unsound implicit cast from 'dynamic' to 'LinkedHashMapCell<K, V>'. (dart:collection, line 696, col 42)
+[warning] Unsound implicit cast from 'dynamic' to 'K'. (dart:collection, line 697, col 40)
+[warning] Unsound implicit cast from 'Object' to 'E'. (dart:collection, line 758, col 14)
+[warning] Unsound implicit cast from 'dynamic' to 'List<E>'. (dart:collection, line 951, col 12)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:collection, line 1009, col 21)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:collection, line 1009, col 51)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:collection, line 1019, col 47)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:collection, line 1058, col 18)
+[warning] Unsound implicit cast from 'Object' to 'E'. (dart:collection, line 1135, col 14)
+[warning] Unsound implicit cast from 'dynamic' to '_LinkedHashSetCell<E>'. (dart:collection, line 1222, col 38)
+[warning] Unsound implicit cast from 'dynamic' to '_LinkedHashSetCell<E>'. (dart:collection, line 1337, col 12)
+[warning] Unsound implicit cast from 'dynamic' to 'List<_LinkedHashSetCell<E>>'. (dart:collection, line 1351, col 12)
+[warning] Unsound implicit cast from 'dynamic' to '_LinkedHashSetCell<E>'. (dart:collection, line 1358, col 40)
+[warning] Unsound implicit cast from 'dynamic' to '_LinkedHashSetCell<E>'. (dart:collection, line 1391, col 40)
+[warning] Unsound implicit cast from 'dynamic' to '_LinkedHashSetCell<E>'. (dart:collection, line 1412, col 40)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:collection, line 1413, col 36)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:collection, line 1423, col 47)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:collection, line 1485, col 18)
+[warning] Unsound implicit cast from 'dynamic' to 'Stream<S>'. (dart:convert/chunked_conversion.dart, line 14, col 45)
+[warning] Unsound implicit cast from 'dynamic' to 'Sink<T>'. (dart:convert/chunked_conversion.dart, line 16, col 36)
+[warning] Unsound implicit cast from 'dynamic' to 'List<String>'. (dart:convert, line 311, col 12)
+[warning] Unsound implicit cast from 'dynamic' to 'T'. (dart:core/expando.dart, line 55, col 12)
+[warning] Unsound implicit cast from 'dynamic' to 'E'. (dart:core/list.dart, line 126, col 16)
+[warning] The final variable 'origin' must be initialized. (dart:html, line 177, col 3)
+[warning] The final variable 'origin' must be initialized. (dart:html, line 813, col 3)
+[warning] Unsound implicit cast from 'dynamic' to 'List<String>'. (dart:html, line 1145, col 33)
+[warning] The final variables 'form', 'labels' and '3' more must be initialized. (dart:html, line 1691, col 3)
+[warning] Unsound implicit cast from 'dynamic' to 'List<num>'. (dart:html, line 2723, col 14)
+[warning] Unsound implicit cast from 'dynamic' to 'List<num>'. (dart:html, line 2725, col 14)
+[warning] The final variable 'options' must be initialized. (dart:html, line 8972, col 3)
+[warning] The final variables '_attributes', '_childElementCount' and '16' more must be initialized. (dart:html, line 13009, col 3)
+[warning] The final variables 'elements', 'form' and '4' more must be initialized. (dart:html, line 16625, col 3)
+[warning] The final variable 'length' must be initialized. (dart:html, line 17555, col 3)
+[warning] The final variables '_get_contentWindow' and 'sandbox' must be initialized. (dart:html, line 20113, col 3)
+[warning] The final variables 'complete', 'currentSrc' and '2' more must be initialized. (dart:html, line 20246, col 3)
+[warning] The final variables '_get_valueAsDate', 'entries' and '6' more must be initialized. (dart:html, line 20400, col 3)
+[warning] The final variables 'form', 'labels' and '4' more must be initialized. (dart:html, line 21436, col 3)
+[warning] The final variables 'control' and 'form' must be initialized. (dart:html, line 21547, col 3)
+[warning] The final variable 'form' must be initialized. (dart:html, line 21581, col 3)
+[warning] The final variables 'import', 'sheet' and '1' more must be initialized. (dart:html, line 21607, col 3)
+[warning] The final variable 'areas' must be initialized. (dart:html, line 21759, col 3)
+[warning] The final variables 'audioDecodedByteCount', 'audioTracks' and '16' more must be initialized. (dart:html, line 21985, col 3)
+[warning] The final variable 'labels' must be initialized. (dart:html, line 23501, col 3)
+[warning] The final variables '_localName', '_namespaceUri' and '12' more must be initialized. (dart:html, line 24939, col 3)
+[warning] The final variables 'form', 'validationMessage' and '2' more must be initialized. (dart:html, line 25820, col 3)
+[warning] The final variables 'form' and 'index' must be initialized. (dart:html, line 25955, col 3)
+[warning] The final variables 'form', 'htmlFor' and '5' more must be initialized. (dart:html, line 26009, col 3)
+[warning] The final variables 'labels' and 'position' must be initialized. (dart:html, line 27415, col 3)
+[warning] The final variables 'form', 'labels' and '4' more must be initialized. (dart:html, line 29186, col 3)
+[warning] The final variable 'sheet' must be initialized. (dart:html, line 31442, col 3)
+[warning] The final variable 'cellIndex' must be initialized. (dart:html, line 31662, col 3)
+[warning] The final variables '_rows' and '_tBodies' must be initialized. (dart:html, line 31773, col 3)
+[warning] The final variables '_cells', 'rowIndex' and '1' more must be initialized. (dart:html, line 31883, col 3)
+[warning] The final variable '_rows' must be initialized. (dart:html, line 31950, col 3)
+[warning] The final variable 'content' must be initialized. (dart:html, line 31993, col 3)
+[warning] The final variables 'form', 'labels' and '5' more must be initialized. (dart:html, line 32069, col 3)
+[warning] The final variables 'readyState' and 'track' must be initialized. (dart:html, line 33056, col 3)
+[warning] The final variables 'decodedFrameCount', 'droppedFrameCount' and '2' more must be initialized. (dart:html, line 33754, col 3)
+[warning] Unsound implicit cast from 'dynamic' to 'Rectangle<num>'. (dart:html, line 37618, col 14)
+[warning] Unsound implicit cast from 'dynamic' to 'Rectangle<num>'. (dart:html, line 37626, col 14)
+[warning] Unsound implicit cast from 'dynamic' to 'Rectangle<num>'. (dart:html, line 37634, col 14)
+[warning] Unsound implicit cast from '(T) → void' to '(Event) → dynamic'. (dart:html, line 40090, col 67)
+[warning] Unsound implicit cast from '(T) → void' to '(Event) → dynamic'. (dart:html, line 40112, col 45)
+[warning] Unsound implicit cast from 'num' to 'T'. (dart:math/rectangle.dart, line 158, col 22)
+[warning] Unsound implicit cast from 'num' to 'T'. (dart:math/rectangle.dart, line 159, col 23)
+[warning] Unsound implicit cast from 'num' to 'T'. (dart:math/rectangle.dart, line 282, col 10)
+[warning] The final variables 'href' and 'target' must be initialized. (dart:svg, line 60, col 3)
+[warning] The final variables 'requiredExtensions', 'requiredFeatures' and '2' more must be initialized. (dart:svg, line 489, col 3)
+[warning] The final variables 'cx', 'cy' and '1' more must be initialized. (dart:svg, line 562, col 3)
+[warning] The final variable 'clipPathUnits' must be initialized. (dart:svg, line 597, col 3)
+[warning] The final variables 'cx', 'cy' and '2' more must be initialized. (dart:svg, line 689, col 3)
+[warning] The final variables 'height', 'in1' and '6' more must be initialized. (dart:svg, line 732, col 3)
+[warning] The final variables 'height', 'in1' and '6' more must be initialized. (dart:svg, line 820, col 3)
+[warning] The final variables 'height', 'in1' and '4' more must be initialized. (dart:svg, line 904, col 3)
+[warning] The final variables 'height', 'in1' and '10' more must be initialized. (dart:svg, line 952, col 3)
+[warning] The final variables 'bias', 'divisor' and '15' more must be initialized. (dart:svg, line 1057, col 3)
+[warning] The final variables 'diffuseConstant', 'height' and '8' more must be initialized. (dart:svg, line 1173, col 3)
+[warning] The final variables 'height', 'in1' and '8' more must be initialized. (dart:svg, line 1245, col 3)
+[warning] The final variables 'azimuth' and 'elevation' must be initialized. (dart:svg, line 1337, col 3)
+[warning] The final variables 'height', 'result' and '3' more must be initialized. (dart:svg, line 1375, col 3)
+[warning] The final variables 'height', 'in1' and '6' more must be initialized. (dart:svg, line 1547, col 3)
+[warning] The final variables 'height', 'href' and '5' more must be initialized. (dart:svg, line 1615, col 3)
+[warning] The final variables 'height', 'result' and '3' more must be initialized. (dart:svg, line 1677, col 3)
+[warning] The final variable 'in1' must be initialized. (dart:svg, line 1729, col 3)
+[warning] The final variables 'height', 'in1' and '7' more must be initialized. (dart:svg, line 1759, col 3)
+[warning] The final variables 'dx', 'dy' and '6' more must be initialized. (dart:svg, line 1836, col 3)
+[warning] The final variables 'x', 'y' and '1' more must be initialized. (dart:svg, line 1900, col 3)
+[warning] The final variables 'height', 'in1' and '9' more must be initialized. (dart:svg, line 1942, col 3)
+[warning] The final variables 'limitingConeAngle', 'pointsAtX' and '6' more must be initialized. (dart:svg, line 2020, col 3)
+[warning] The final variables 'height', 'in1' and '4' more must be initialized. (dart:svg, line 2082, col 3)
+[warning] The final variables 'baseFrequencyX', 'baseFrequencyY' and '9' more must be initialized. (dart:svg, line 2138, col 3)
+[warning] The final variables 'filterUnits', 'height' and '5' more must be initialized. (dart:svg, line 2238, col 3)
+[warning] The final variables 'height', 'width' and '2' more must be initialized. (dart:svg, line 2335, col 3)
+[warning] The final variables 'farthestViewportElement', 'nearestViewportElement' and '4' more must be initialized. (dart:svg, line 2425, col 3)
+[warning] The final variables 'height', 'href' and '4' more must be initialized. (dart:svg, line 2507, col 3)
+[warning] The final variables 'x1', 'x2' and '2' more must be initialized. (dart:svg, line 2736, col 3)
+[warning] The final variables 'x1', 'x2' and '2' more must be initialized. (dart:svg, line 2775, col 3)
+[warning] The final variables 'markerHeight', 'markerUnits' and '7' more must be initialized. (dart:svg, line 2814, col 3)
+[warning] The final variables 'height', 'maskContentUnits' and '7' more must be initialized. (dart:svg, line 2907, col 3)
+[warning] The final variables 'animatedNormalizedPathSegList', 'animatedPathSegList' and '3' more must be initialized. (dart:svg, line 3188, col 3)
+[warning] The final variables 'height', 'href' and '11' more must be initialized. (dart:svg, line 4017, col 3)
+[warning] The final variables 'animatedPoints' and 'points' must be initialized. (dart:svg, line 4182, col 3)
+[warning] The final variables 'animatedPoints' and 'points' must be initialized. (dart:svg, line 4213, col 3)
+[warning] The final variables 'cx', 'cy' and '4' more must be initialized. (dart:svg, line 4321, col 3)
+[warning] The final variables 'height', 'rx' and '4' more must be initialized. (dart:svg, line 4397, col 3)
+[warning] The final variable 'href' must be initialized. (dart:svg, line 4444, col 3)
+[warning] The final variable 'gradientOffset' must be initialized. (dart:svg, line 4506, col 3)
+[warning] The final variable 'sheet' must be initialized. (dart:svg, line 4634, col 3)
+[warning] The final variables 'ownerSvgElement' and 'viewportElement' must be initialized. (dart:svg, line 5072, col 3)
+[warning] The final variables 'currentTranslate', 'currentView' and '12' more must be initialized. (dart:svg, line 5386, col 3)
+[warning] The final variables 'preserveAspectRatio' and 'viewBox' must be initialized. (dart:svg, line 5605, col 3)
+[warning] The final variables 'lengthAdjust' and 'textLength' must be initialized. (dart:svg, line 5677, col 3)
+[warning] The final variables 'href', 'method' and '2' more must be initialized. (dart:svg, line 5775, col 3)
+[warning] The final variables 'dx', 'dy' and '3' more must be initialized. (dart:svg, line 5836, col 3)
+[warning] The final variables 'height', 'href' and '3' more must be initialized. (dart:svg, line 6126, col 3)
+[warning] The final variables 'preserveAspectRatio', 'viewBox' and '1' more must be initialized. (dart:svg, line 6171, col 3)
+[warning] The final variables 'gradientTransform', 'gradientUnits' and '2' more must be initialized. (dart:svg, line 6325, col 3)
diff --git a/pkg/dev_compiler/web/main.dart b/pkg/dev_compiler/web/main.dart
index 3ec8888..70f8440 100755
--- a/pkg/dev_compiler/web/main.dart
+++ b/pkg/dev_compiler/web/main.dart
@@ -17,7 +17,7 @@
external set setUpCompilerInBrowser(Function function);
Future main() async {
- var args = ['compile'];
+ var args = ['compile', '--repl-compile'];
_runCommand(args);
}
@@ -61,7 +61,7 @@
messageHandler("We're sorry, you've found a bug in our compiler.");
messageHandler("You can report this bug at:");
messageHandler(
- " https://github.com/dart-lang/sdk/issues/labels/area-dev-compiler");
+ " https://github.com/dart-lang/sdk/issues/labels/area-dev-compiler");
messageHandler("");
messageHandler(
"Please include the information below in your report, along with");
diff --git a/pkg/dev_compiler/web/web_command.dart b/pkg/dev_compiler/web/web_command.dart
index 5f6514a..68b216a 100644
--- a/pkg/dev_compiler/web/web_command.dart
+++ b/pkg/dev_compiler/web/web_command.dart
@@ -5,9 +5,15 @@
library dev_compiler.web.web_command;
import 'dart:async';
+import 'dart:convert';
import 'dart:html' show HttpRequest;
-import 'dart:convert' show BASE64;
+import 'package:analyzer/dart/element/element.dart'
+ show
+ LibraryElement,
+ ImportElement,
+ ShowElementCombinator,
+ HideElementCombinator;
import 'package:analyzer/file_system/file_system.dart' show ResourceUriResolver;
import 'package:analyzer/file_system/memory_file_system.dart'
show MemoryResourceProvider;
@@ -20,6 +26,7 @@
InSummaryUriResolver,
InputPackagesResultProvider,
InSummarySource;
+import 'package:analyzer/src/dart/resolver/scope.dart' show Scope;
import 'package:analyzer/src/summary/summary_sdk.dart' show SummaryBasedDartSdk;
import 'package:args/command_runner.dart';
@@ -30,6 +37,7 @@
import 'package:dev_compiler/src/compiler/module_builder.dart';
import 'package:js/js.dart';
+import 'package:path/path.dart' as path;
typedef void MessageHandler(Object message);
@@ -40,8 +48,8 @@
{String code, List<String> errors, bool isValid});
}
-typedef CompileResult CompileModule(
- String code, String libraryName, String fileName);
+typedef CompileModule(String imports, String body, String libraryName,
+ String existingLibrary, String fileName);
/// The command for invoking the modular compiler.
class WebCompileCommand extends Command {
@@ -102,7 +110,8 @@
var summaryBundle = new PackageBundle.fromBuffer(bytes);
summaryDataStore.addBundle(url, summaryBundle);
}
- var summaryResolver = new InSummaryUriResolver(resourceProvider, summaryDataStore);
+ var summaryResolver =
+ new InSummaryUriResolver(resourceProvider, summaryDataStore);
var fileResolvers = [summaryResolver, resourceUriResolver];
@@ -112,24 +121,85 @@
fileResolvers: fileResolvers,
resourceProvider: resourceProvider);
- (compiler.context as AnalysisContextImpl).resultProvider =
+ var context = compiler.context as AnalysisContextImpl;
+ context.resultProvider =
new InputPackagesResultProvider(compiler.context, summaryDataStore);
var compilerOptions = new CompilerOptions.fromArguments(argResults);
- CompileModule compileFn =
- (String sourceCode, String libraryName, String fileName) {
+ CompileModule compileFn = (String imports, String body, String libraryName,
+ String existingLibrary, String fileName) {
// Create a new virtual File that contains the given Dart source.
- resourceProvider.newFile("/$fileName", sourceCode);
+ String sourceCode;
+ if (existingLibrary == null) {
+ sourceCode = imports + body;
+ } else {
+ var dir = path.dirname(existingLibrary);
+ // Need to pull in all the imports from the existing library and
+ // re-export all privates as privates in this library.
+ var source = context.sourceFactory.forUri(existingLibrary);
+ if (source == null) {
+ throw "Unable to load source for library $existingLibrary";
+ }
- var unit = new BuildUnit(
- libraryName, "", ["file:///$fileName"], _moduleForLibrary);
+ LibraryElement libraryElement = context.computeLibraryElement(source);
+ if (libraryElement == null) {
+ throw "Unable to get library element.";
+ }
+ var sb = new StringBuffer(imports);
+ sb.write('\n');
+
+ // TODO(jacobr): we need to add a proper Analyzer flag specifing that
+ // cross-library privates should be in scope instead of this hack.
+ // We set the private name prefix for scope resolution to an invalid
+ // character code so that the analyzer ignores normal Dart private
+ // scoping rules for top level names allowing REPL users to access
+ // privates in arbitrary libraries. The downside of this scheme is it is
+ // possible to get errors if privates in the current library and
+ // imported libraries happen to have exactly the same name.
+ Scope.PRIVATE_NAME_PREFIX = -1;
+
+ // We emulate running code in the context of an existing library by
+ // importing that library and all libraries it imports.
+ sb.write('import ${JSON.encode(existingLibrary)};\n');
+
+ for (ImportElement importElement in libraryElement.imports) {
+ if (importElement.uri == null) continue;
+ var uri = importElement.uri;
+ // dart: and package: uris are not relative but the path package
+ // thinks they are. We have to provide absolute uris as our library
+ // has a different directory than the library we are pretending to be.
+ if (path.isRelative(uri) &&
+ !uri.startsWith('package:') &&
+ !uri.startsWith('dart:')) {
+ uri = path.normalize(path.join(dir, uri));
+ }
+ sb.write('import ${JSON.encode(uri)}');
+ if (importElement.prefix != null)
+ sb.write(' as ${importElement.prefix.name}');
+ for (var combinator in importElement.combinators) {
+ if (combinator is ShowElementCombinator) {
+ sb.write(' show ${combinator.shownNames.join(', ')}');
+ } else if (combinator is HideElementCombinator) {
+ sb.write(' hide ${combinator.hiddenNames.join(', ')}');
+ } else {
+ throw 'Unexpected element combinator';
+ }
+ }
+ sb.write(';\n');
+ }
+ sb.write(body);
+ sourceCode = sb.toString();
+ }
+ resourceProvider.newFile(fileName, sourceCode);
+
+ var unit = new BuildUnit(libraryName, "", [fileName], _moduleForLibrary);
JSModuleFile module = compiler.compile(unit, compilerOptions);
var moduleCode = module.isValid
? module
- .getCode(ModuleFormat.legacy, false, unit.name, unit.name + '.map')
+ .getCode(ModuleFormat.legacy, true, unit.name, unit.name + '.map')
.code
: '';
diff --git a/pkg/front_end/LICENSE b/pkg/front_end/LICENSE
new file mode 100644
index 0000000..82e9b52
--- /dev/null
+++ b/pkg/front_end/LICENSE
@@ -0,0 +1,26 @@
+Copyright 2016, the Dart project authors. All rights reserved.
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+ * Neither the name of Google Inc. nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/pkg/front_end/README.md b/pkg/front_end/README.md
new file mode 100644
index 0000000..2b5ed61
--- /dev/null
+++ b/pkg/front_end/README.md
@@ -0,0 +1,13 @@
+# Front end for Dart
+
+This package provides a low-level API for use by compiler back ends that wish to
+implement the Dart language. It is intended for eventual use by dev_compiler,
+dart2js, and the Dart VM. In addition, it will share implementation details
+with the analyzer package--this will be accomplished by having the analyzer
+package import (and re-export) parts of this package's private implementation.
+
+End-users should use the [dartanalyzer][analyzercli] command-line tool to
+analyze their Dart code.
+
+Integrators that want to write tools that analyze Dart code should use the
+[analyzer] package.
diff --git a/pkg/front_end/lib/compilation_error.dart b/pkg/front_end/lib/compilation_error.dart
new file mode 100644
index 0000000..2211ae9
--- /dev/null
+++ b/pkg/front_end/lib/compilation_error.dart
@@ -0,0 +1,26 @@
+// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+/// Defines the API for the front end to communicate information about
+/// compilation errors to clients.
+library front_end.compilation_error;
+
+import 'package:source_span/source_span.dart' show SourceSpan;
+
+/// A single error that occurred during compilation, and information about where
+/// it occurred.
+///
+/// TODO(paulberry): add a reference to the analyzer error code.
+///
+/// TODO(paulberry): add a correction message, once most analyzer errors have
+/// one.
+///
+/// Not intended to be implemented or extended by clients.
+abstract class CompilationError {
+ /// A text description of the compile error.
+ String get message;
+
+ /// The source location where the error occurred.
+ SourceSpan get location;
+}
diff --git a/pkg/front_end/lib/compiler_options.dart b/pkg/front_end/lib/compiler_options.dart
new file mode 100644
index 0000000..f9f2f29
--- /dev/null
+++ b/pkg/front_end/lib/compiler_options.dart
@@ -0,0 +1,102 @@
+// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+library front_end.compiler_options;
+
+import 'compilation_error.dart';
+import 'file_system.dart';
+
+/// Callback used to report errors encountered during compilation.
+typedef void ErrorHandler(CompilationError error);
+
+/// Front-end options relevant to compiler back ends.
+///
+/// Not intended to be implemented or extended by clients.
+class CompilerOptions {
+ /// The path to the Dart SDK.
+ ///
+ /// If `null`, the SDK will be searched for using
+ /// [Platform.resolvedExecutable] as a starting point.
+ ///
+ /// This option is mutually exclusive with [sdkSummary].
+ String sdkPath;
+
+ /// Callback to which compilation errors should be delivered.
+ ///
+ /// If `null`, the first error will be reported by throwing an exception of
+ /// type [CompilationError].
+ ErrorHandler onError;
+
+ /// Path to the ".packages" file.
+ ///
+ /// If `null`, the ".packages" file will be found via the standard
+ /// package_config search algorithm.
+ String packagesFilePath;
+
+ /// Paths to the input summary files (excluding the SDK summary). These files
+ /// should all be linked summaries. They should also be closed, in the sense
+ /// that any libraries they reference should also appear in [inputSummaries]
+ /// or [sdkSummary].
+ List<String> inputSummaries = [];
+
+ /// Path to the SDK summary file.
+ ///
+ /// This should be a linked summary. If `null`, the SDK summary will be
+ /// searched for at a default location within [sdkPath].
+ ///
+ /// This option is mutually exclusive with [sdkPath]. TODO(paulberry): if the
+ /// VM does not contain a pickled copy of the SDK, we might need to change
+ /// this.
+ String sdkSummary;
+
+ /// URI override map.
+ ///
+ /// This is a map from Uri to file path. Any URI override listed in this map
+ /// takes precedence over the URI resolution that would be implied by the
+ /// packages file (see [packagesFilePath]) and/or [bazelRoots].
+ ///
+ /// If a URI is not listed in this map, then the normal URI resolution
+ /// algorithm will be used.
+ ///
+ /// TODO(paulberry): transition analyzer and dev_compiler to use the
+ /// "file:///bazel-root" mechanism, and then remove this.
+ @deprecated
+ Map<Uri, String> uriOverride = {};
+
+ /// Bazel roots.
+ ///
+ /// Any Uri that resolves to "file:///bazel-root/$rest" will be searched for
+ /// at "$root/$rest" ("$root\\$rest" in Windows), where "$root" is drawn from
+ /// this list. If the file is not found at any of those locations, the URI
+ /// "file:///bazel-root/$rest" will be used directly.
+ ///
+ /// Intended use: if the Bazel workspace is located at path "$workspace", this
+ /// could be set to `['$workspace', '$workspace/bazel-bin',
+ /// '$workspace/bazel-genfiles']`, effectively overlaying source and generated
+ /// files.
+ List<String> bazelRoots = [];
+
+ /// Sets the platform bit, which determines which patch files should be
+ /// applied to the SDK.
+ ///
+ /// The value should be a power of two, and should match the `PLATFORM` bit
+ /// flags in sdk/lib/_internal/sdk_library_metadata/lib/libraries.dart. If
+ /// zero, no patch files will be applied.
+ int platformBit;
+
+ /// The declared variables for use by configurable imports and constant
+ /// evaluation.
+ Map<String, String> declaredVariables;
+
+ /// The [FileSystem] which should be used by the front end to access files.
+ ///
+ /// TODO(paulberry): once an implementation of [FileSystem] has been created
+ /// which uses the actual physical file system, make that the default.
+ ///
+ /// All file system access performed by the front end goes through this
+ /// mechanism, with one exception: if no value is specified for
+ /// [packagesFilePath], the packages file is located using the actual physical
+ /// file system. TODO(paulberry): fix this.
+ FileSystem fileSystem;
+}
diff --git a/pkg/front_end/lib/file_system.dart b/pkg/front_end/lib/file_system.dart
new file mode 100644
index 0000000..404f7f6
--- /dev/null
+++ b/pkg/front_end/lib/file_system.dart
@@ -0,0 +1,73 @@
+// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+library front_end.file_system;
+
+import 'dart:async';
+
+import 'package:path/path.dart' as path;
+
+/// Abstract interface to file system operations.
+///
+/// All front end interaction with the file system goes through this interface;
+/// this makes it possible for clients to use the front end in a way that
+/// doesn't require file system access (e.g. to run unit tests, or to run
+/// inside a browser).
+///
+/// Not intended to be implemented or extended by clients.
+abstract class FileSystem {
+ /// Returns a path context suitable for use with this [FileSystem].
+ path.Context get context;
+
+ /// Returns a [FileSystemEntity] corresponding to the given [path].
+ ///
+ /// Uses of `..` and `.` in path are normalized before returning (so, for
+ /// example, `entityForPath('./foo')` and `entityForPath('foo')` are
+ /// equivalent). Relative paths are also converted to absolute paths.
+ ///
+ /// Does not check whether a file or folder exists at the given location.
+ FileSystemEntity entityForPath(String path);
+
+ /// Returns a [FileSystemEntity] corresponding to the given [uri].
+ ///
+ /// Uses of `..` and `.` in the URI are normalized before returning. Relative
+ /// paths are also converted to absolute paths.
+ ///
+ /// If [uri] is not a `file:` URI, an [Error] will be thrown.
+ ///
+ /// Does not check whether a file or folder exists at the given location.
+ FileSystemEntity entityForUri(Uri uri);
+}
+
+/// Abstract representation of a file system entity that may or may not exist.
+///
+/// Not intended to be implemented or extended by clients.
+abstract class FileSystemEntity {
+ /// Returns the absolute normalized path represented by this file system
+ /// entity.
+ ///
+ /// Note: if the [FileSystemEntity] was created using
+ /// [FileSystem.entityForPath], this is not necessarily the same as the path
+ /// that was used to create the object, since the path might have been
+ /// normalized.
+ String get path;
+
+ /// Attempts to access this file system entity as a file and read its contents
+ /// as raw bytes.
+ ///
+ /// If an error occurs while attempting to read the file (e.g. because no such
+ /// file exists, or the entity is a directory), the future is completed with
+ /// an [Exception].
+ Future<List<int>> readAsBytes();
+
+ /// Attempts to access this file system entity as a file and read its contents
+ /// as a string.
+ ///
+ /// The file is assumed to be UTF-8 encoded.
+ ///
+ /// If an error occurs while attempting to read the file (e.g. because no such
+ /// file exists, or the entity is a directory), the future is completed with
+ /// an [Exception].
+ Future<String> readAsString();
+}
diff --git a/pkg/front_end/lib/kernel_generator.dart b/pkg/front_end/lib/kernel_generator.dart
new file mode 100644
index 0000000..3b35086
--- /dev/null
+++ b/pkg/front_end/lib/kernel_generator.dart
@@ -0,0 +1,58 @@
+// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+/// Defines the front-end API for converting source code to Dart Kernel objects.
+library front_end.kernel_generator;
+
+import 'dart:async';
+import 'compiler_options.dart';
+import 'package:kernel/kernel.dart' as kernel;
+
+/// Generates a kernel representation of the program whose main library is in
+/// the given [source].
+///
+/// Intended for whole program (non-modular) compilation.
+///
+/// Given the Uri of a file containing a program's `main` method, this function
+/// follows `import`, `export`, and `part` declarations to discover the whole
+/// program, and converts the result to Dart Kernel format.
+///
+/// If summaries are provided in [options], they may be used to speed up
+/// analysis, but they will not take the place of Dart source code (since the
+/// Dart source code is still needed to access the contents of method bodies).
+///
+/// TODO(paulberry): will the VM have a pickled version of the SDK inside it? If
+/// so, then maybe this method should not convert SDK libraries to kernel.
+Future<kernel.Program> kernelForProgram(Uri source, CompilerOptions options) =>
+ throw new UnimplementedError();
+
+/// Generates a kernel representation of the build unit whose source files are
+/// in [sources].
+///
+/// Intended for modular compilation.
+///
+/// [sources] should be the complete set of source files for a build unit
+/// (including both library and part files). All of the library files are
+/// transformed into Dart Kernel Library objects.
+///
+/// The compilation process is hermetic, meaning that the only files which will
+/// be read are those listed in [sources], [CompilerOptions.inputSummaries], and
+/// [CompilerOptions.sdkSummary]. If a source file attempts to refer to a file
+/// which is not obtainable from these paths, that will result in an error, even
+/// if the file exists on the filesystem.
+///
+/// Any `part` declarations found in [sources] must refer to part files which
+/// are also listed in [sources], otherwise an error results. (It is not
+/// permitted to refer to a part file declared in another build unit).
+///
+/// The return value is a [kernel.Program] object with no main method set.
+/// TODO(paulberry): would it be better to define a data type in kernel to
+/// represent a bundle of all the libraries in a given build unit?
+///
+/// TODO(paulberry): does additional information need to be output to allow the
+/// caller to match up referenced elements to the summary files they were
+/// obtained from?
+Future<kernel.Program> kernelForBuildUnit(
+ List<Uri> sources, CompilerOptions options) =>
+ throw new UnimplementedError();
diff --git a/pkg/front_end/lib/resolved_ast_generator.dart b/pkg/front_end/lib/resolved_ast_generator.dart
new file mode 100644
index 0000000..4b37d38
--- /dev/null
+++ b/pkg/front_end/lib/resolved_ast_generator.dart
@@ -0,0 +1,61 @@
+// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+/// Defines a front-end API for converting source code to resolved ASTs.
+///
+/// Note: this entire library is deprecated. It is provided as a migration path
+/// until dev_compiler supports Dart Kernel. Once dev_compiler has been
+/// converted to use Dart Kernel, this functionality will be removed.
+@deprecated
+library front_end.resolved_ast_generator;
+
+import 'dart:async';
+import 'compiler_options.dart';
+import 'package:analyzer/dart/ast/ast.dart' show CompilationUnit;
+import 'package:analyzer/dart/element/element.dart' show LibraryElement;
+
+/// Processes the build unit whose source files are in [sources].
+///
+/// Intended for modular compilation.
+///
+/// [sources] should be the complete set of source files for a build unit
+/// (including both library and part files). All of the library files are
+/// compiled to resolved ASTs.
+///
+/// The compilation process is hermetic, meaning that the only files which will
+/// be read are those listed in [sources], [CompilerOptions.inputSummaries], and
+/// [CompilerOptions.sdkSummary]. If a source file attempts to refer to a file
+/// which is not obtainable from these paths, that will result in an error, even
+/// if the file exists on the filesystem.
+///
+/// Any `part` declarations found in [sources] must refer to part files which
+/// are also listed in [sources], otherwise an error results. (It is not
+/// permitted to refer to a part file declared in another build unit).
+@deprecated
+Future<ResolvedAsts> resolvedAstsFor(
+ List<Uri> sources, CompilerOptions options) =>
+ throw new UnimplementedError();
+
+/// Representation of the resolved ASTs of a build unit.
+///
+/// Not intended to be implemented or extended by clients.
+@deprecated
+abstract class ResolvedAsts {
+ /// The resolved ASTs of the build unit's source libraries.
+ ///
+ /// There is one sub-list per source library; each sub-list consists of the
+ /// resolved AST for the library's defining compilation unit, followed by the
+ /// resolved ASTs for any of the library's part files.
+ List<List<CompilationUnit>> get compilationUnits;
+
+ /// Given a [LibraryElement] referred to by [compilationUnits], determine the
+ /// path to the summary that the library originated from. If the
+ /// [LibraryElement] did not originate from a summary (i.e. because it
+ /// originated from one of the source files of *this* build unit), return
+ /// `null`.
+ ///
+ /// This can be used by the client to determine which build unit any
+ /// referenced element originated from.
+ String getOriginatingSummary(LibraryElement element);
+}
diff --git a/pkg/front_end/lib/summary_generator.dart b/pkg/front_end/lib/summary_generator.dart
new file mode 100644
index 0000000..0c494c4
--- /dev/null
+++ b/pkg/front_end/lib/summary_generator.dart
@@ -0,0 +1,32 @@
+// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+/// Defines the front-end API for converting source code to summaries.
+library front_end.summary_generator;
+
+import 'dart:async';
+import 'compiler_options.dart';
+
+/// Creates a summary representation of the build unit whose source files are in
+/// [sources].
+///
+/// Intended to be a part of a modular compilation process.
+///
+/// [sources] should be the complete set of source files for a build unit
+/// (including both library and part files).
+///
+/// The summarization process is hermetic, meaning that the only files which
+/// will be read are those listed in [sources],
+/// [CompilerOptions.inputSummaries], and [CompilerOptions.sdkSummary]. If a
+/// source file attempts to refer to a file which is not obtainable from these
+/// paths, that will result in an error, even if the file exists on the
+/// filesystem.
+///
+/// Any `part` declarations found in [sources] must refer to part files which
+/// are also listed in [sources], otherwise an error results. (It is not
+/// permitted to refer to a part file declared in another build unit).
+///
+/// The return value is a list of bytes to write to the summary file.
+Future<List<int>> summaryFor(List<Uri> sources, CompilerOptions options) =>
+ throw new UnimplementedError();
diff --git a/pkg/front_end/pubspec.yaml b/pkg/front_end/pubspec.yaml
new file mode 100644
index 0000000..1c8fdd8
--- /dev/null
+++ b/pkg/front_end/pubspec.yaml
@@ -0,0 +1,11 @@
+name: front_end
+version: 0.1.0
+author: Dart Team <misc@dartlang.org>
+description: Front end for compilation of Dart code.
+homepage: https://github.com/dart-lang/sdk/tree/master/pkg/front_end
+environment:
+ sdk: '>=1.12.0 <2.0.0'
+dependencies:
+ analyzer: '^0.29.0'
+ path: '^1.3.9'
+ source_span: '^1.2.3'
diff --git a/runtime/bin/BUILD.gn b/runtime/bin/BUILD.gn
index df8d405..81cd6b1 100644
--- a/runtime/bin/BUILD.gn
+++ b/runtime/bin/BUILD.gn
@@ -643,7 +643,6 @@
libs = [
"launchpad",
"magenta",
- "runtime",
]
}
}
diff --git a/runtime/bin/eventhandler_fuchsia.cc b/runtime/bin/eventhandler_fuchsia.cc
index ff947ea..2a61164 100644
--- a/runtime/bin/eventhandler_fuchsia.cc
+++ b/runtime/bin/eventhandler_fuchsia.cc
@@ -10,8 +10,8 @@
#include "bin/eventhandler.h"
#include "bin/eventhandler_fuchsia.h"
+#include <magenta/status.h>
#include <magenta/syscalls.h>
-#include <runtime/status.h>
#include "bin/thread.h"
#include "bin/utils.h"
@@ -22,7 +22,7 @@
EventHandlerImplementation::EventHandlerImplementation() {
mx_status_t status = mx_msgpipe_create(interrupt_handles_, 0);
if (status != NO_ERROR) {
- FATAL1("mx_msgpipe_create failed: %s\n", mx_strstatus(status));
+ FATAL1("mx_msgpipe_create failed: %s\n", mx_status_get_string(status));
}
shutdown_ = false;
}
@@ -31,11 +31,11 @@
EventHandlerImplementation::~EventHandlerImplementation() {
mx_status_t status = mx_handle_close(interrupt_handles_[0]);
if (status != NO_ERROR) {
- FATAL1("mx_handle_close failed: %s\n", mx_strstatus(status));
+ FATAL1("mx_handle_close failed: %s\n", mx_status_get_string(status));
}
status = mx_handle_close(interrupt_handles_[1]);
if (status != NO_ERROR) {
- FATAL1("mx_handle_close failed: %s\n", mx_strstatus(status));
+ FATAL1("mx_handle_close failed: %s\n", mx_status_get_string(status));
}
}
@@ -51,7 +51,7 @@
mx_status_t status =
mx_msgpipe_write(interrupt_handles_[1], &msg, sizeof(msg), NULL, 0, 0);
if (status != NO_ERROR) {
- FATAL1("mx_msgpipe_write failed: %s\n", mx_strstatus(status));
+ FATAL1("mx_msgpipe_write failed: %s\n", mx_status_get_string(status));
}
}
@@ -78,7 +78,7 @@
// status == ERR_BAD_STATE when we try to read and there are no messages
// available, so it is an error if we get here and status != ERR_BAD_STATE.
if (status != ERR_BAD_STATE) {
- FATAL1("mx_msgpipe_read failed: %s\n", mx_strstatus(status));
+ FATAL1("mx_msgpipe_read failed: %s\n", mx_status_get_string(status));
}
}
@@ -130,7 +130,7 @@
timeout,
&signals_state);
if ((status != NO_ERROR) && (status != ERR_TIMED_OUT)) {
- FATAL1("mx_handle_wait_one failed: %s\n", mx_strstatus(status));
+ FATAL1("mx_handle_wait_one failed: %s\n", mx_status_get_string(status));
} else {
handler_impl->HandleTimeout();
if ((signals_state.satisfied & MX_SIGNAL_READABLE) != 0) {
diff --git a/runtime/bin/extensions_win.cc b/runtime/bin/extensions_win.cc
index da626f1..17bb58f 100644
--- a/runtime/bin/extensions_win.cc
+++ b/runtime/bin/extensions_win.cc
@@ -19,7 +19,16 @@
void* Extensions::LoadExtensionLibrary(const char* library_file) {
SetLastError(0);
- return LoadLibraryW(StringUtilsWin::Utf8ToWide(library_file));
+
+ // Convert to wchar_t string.
+ int name_len = MultiByteToWideChar(CP_UTF8, 0, library_file, -1, NULL, 0);
+ wchar_t* name;
+ name = new wchar_t[name_len];
+ MultiByteToWideChar(CP_UTF8, 0, library_file, -1, name, name_len);
+
+ void* ext = LoadLibraryW(name);
+ delete[] name;
+ return ext;
}
void* Extensions::ResolveSymbol(void* lib_handle, const char* symbol) {
diff --git a/runtime/bin/file.h b/runtime/bin/file.h
index c30c02d..cef6f0a 100644
--- a/runtime/bin/file.h
+++ b/runtime/bin/file.h
@@ -162,6 +162,10 @@
// Like ScopedOpen(), but no API scope is needed.
static File* Open(const char* path, FileOpenMode mode);
+ // Caution! On Windows, the static functions below may call
+ // Dart_ScopeAllocate() to do string conversions! If you call these functions
+ // without a scope, they will fail on Windows!
+
// Create a file object for the specified stdio file descriptor
// (stdin, stout or stderr).
static File* OpenStdio(int fd);
diff --git a/runtime/bin/file_win.cc b/runtime/bin/file_win.cc
index c9f98b5..d1e7719 100644
--- a/runtime/bin/file_win.cc
+++ b/runtime/bin/file_win.cc
@@ -74,9 +74,43 @@
}
-void* File::Map(MapType type, int64_t position, int64_t length) {
- UNIMPLEMENTED();
- return NULL;
+void* File::Map(File::MapType type, int64_t position, int64_t length) {
+ DWORD prot_alloc;
+ DWORD prot_final;
+ switch (type) {
+ case File::kReadOnly:
+ prot_alloc = PAGE_READWRITE;
+ prot_final = PAGE_READONLY;
+ break;
+ case File::kReadExecute:
+ prot_alloc = PAGE_EXECUTE_READWRITE;
+ prot_final = PAGE_EXECUTE_READ;
+ break;
+ default:
+ return NULL;
+ }
+
+ void* addr = VirtualAlloc(NULL, length, MEM_COMMIT | MEM_RESERVE, prot_alloc);
+ if (addr == NULL) {
+ Log::PrintErr("VirtualAlloc failed %d\n", GetLastError());
+ return NULL;
+ }
+
+ SetPosition(position);
+ if (!ReadFully(addr, length)) {
+ Log::PrintErr("ReadFully failed %d\n", GetLastError());
+ VirtualFree(addr, 0, MEM_RELEASE);
+ return NULL;
+ }
+
+ DWORD old_prot;
+ bool result = VirtualProtect(addr, length, prot_final, &old_prot);
+ if (!result) {
+ Log::PrintErr("VirtualProtect failed %d\n", GetLastError());
+ VirtualFree(addr, 0, MEM_RELEASE);
+ return NULL;
+ }
+ return addr;
}
@@ -635,7 +669,12 @@
File::Type File::GetType(const char* pathname, bool follow_links) {
- const wchar_t* name = StringUtilsWin::Utf8ToWide(pathname);
+ // Convert to wchar_t string.
+ int name_len = MultiByteToWideChar(CP_UTF8, 0, pathname, -1, NULL, 0);
+ wchar_t* name;
+ name = new wchar_t[name_len];
+ MultiByteToWideChar(CP_UTF8, 0, pathname, -1, name, name_len);
+
DWORD attributes = GetFileAttributesW(name);
File::Type result = kIsFile;
if (attributes == INVALID_FILE_ATTRIBUTES) {
@@ -662,6 +701,7 @@
} else if ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0) {
result = kIsDirectory;
}
+ delete[] name;
return result;
}
diff --git a/runtime/bin/isolate_data.h b/runtime/bin/isolate_data.h
index a5e8bfb..bb60740 100644
--- a/runtime/bin/isolate_data.h
+++ b/runtime/bin/isolate_data.h
@@ -16,6 +16,8 @@
class EventHandler;
class Loader;
+typedef void (*ExitHook)(int64_t exit_code);
+
// Data associated with every isolate in the standalone VM
// embedding. This is used to free external resources for each isolate
// when the isolate shuts down.
@@ -29,7 +31,8 @@
packages_file(NULL),
udp_receive_buffer(NULL),
builtin_lib_(NULL),
- loader_(NULL) {
+ loader_(NULL),
+ exit_hook_(NULL) {
if (package_root != NULL) {
ASSERT(packages_file == NULL);
this->package_root = strdup(package_root);
@@ -64,6 +67,9 @@
builtin_lib_ = Dart_NewPersistentHandle(lib);
}
+ ExitHook exit_hook() const { return exit_hook_; }
+ void set_exit_hook(ExitHook hook) { exit_hook_ = hook; }
+
char* script_url;
char* package_root;
char* packages_file;
@@ -83,6 +89,7 @@
private:
Dart_Handle builtin_lib_;
Loader* loader_;
+ ExitHook exit_hook_;
DISALLOW_COPY_AND_ASSIGN(IsolateData);
};
diff --git a/runtime/bin/main.cc b/runtime/bin/main.cc
index 1086134..4126cbc 100644
--- a/runtime/bin/main.cc
+++ b/runtime/bin/main.cc
@@ -44,14 +44,12 @@
/**
* Global state used to control and store generation of application snapshots
- * (script/full).
- * A full application snapshot can be generated and run using the following
- * commands
- * - Generating a full application snapshot :
- * dart_bootstrap --full-snapshot-after-run=<filename> --package-root=<dirs>
- * <script_uri> [<script_options>]
- * - Running the full application snapshot generated above :
- * dart --run-full-snapshot=<filename> <script_uri> [<script_options>]
+ * An application snapshot can be generated and run using the following
+ * command
+ * dart --snapshot-kind=app-jit --snapshot=<app_snapshot_filename>
+ * <script_uri> [<script_options>]
+ * To Run the application snapshot generated above, use :
+ * dart <app_snapshot_filename> [<script_options>]
*/
static bool run_app_snapshot = false;
static const char* snapshot_filename = NULL;
@@ -59,8 +57,7 @@
kNone,
kScript,
kAppAOT,
- kAppJITAfterRun,
- kAppAfterRun,
+ kAppJIT,
};
static SnapshotKind gen_snapshot_kind = kNone;
@@ -360,15 +357,12 @@
} else if (strcmp(kind, "app-aot") == 0) {
gen_snapshot_kind = kAppAOT;
return true;
- } else if (strcmp(kind, "app-jit-after-run") == 0) {
- gen_snapshot_kind = kAppJITAfterRun;
- return true;
- } else if (strcmp(kind, "app-after-run") == 0) {
- gen_snapshot_kind = kAppAfterRun;
+ } else if (strcmp(kind, "app-jit") == 0) {
+ gen_snapshot_kind = kAppJIT;
return true;
}
Log::PrintErr("Unrecognized snapshot kind: '%s'\nValid kinds are: "
- "script, app-aot, app-jit-after-run, app-after-run\n", kind);
+ "script, app-aot, app-jit\n", kind);
return false;
}
@@ -775,6 +769,9 @@
} \
+static void SnapshotOnExitHook(int64_t exit_code);
+
+
// Returns true on success, false on failure.
static Dart_Isolate CreateIsolateAndSetupHelper(const char* script_uri,
const char* main,
@@ -801,6 +798,9 @@
IsolateData* isolate_data = new IsolateData(script_uri,
package_root,
packages_config);
+ if (gen_snapshot_kind == kAppJIT) {
+ isolate_data->set_exit_hook(SnapshotOnExitHook);
+ }
Dart_Isolate isolate = Dart_CreateIsolate(script_uri,
main,
isolate_snapshot_buffer,
@@ -1152,27 +1152,16 @@
}
-static void WriteSnapshotFile(const char* snapshot_directory,
- const char* filename,
+static void WriteSnapshotFile(const char* filename,
bool write_magic_number,
const uint8_t* buffer,
const intptr_t size) {
char* concat = NULL;
- const char* qualified_filename;
- if ((snapshot_directory != NULL) && (strlen(snapshot_directory) > 0)) {
- intptr_t len = snprintf(NULL, 0, "%s/%s", snapshot_directory, filename);
- concat = new char[len + 1];
- snprintf(concat, len + 1, "%s/%s", snapshot_directory, filename);
- qualified_filename = concat;
- } else {
- qualified_filename = filename;
- }
-
- File* file = File::Open(qualified_filename, File::kWriteTruncate);
+ File* file = File::Open(filename, File::kWriteTruncate);
if (file == NULL) {
ErrorExit(kErrorExitCode,
"Unable to open file %s for writing snapshot\n",
- qualified_filename);
+ filename);
}
if (write_magic_number) {
@@ -1183,7 +1172,7 @@
if (!file->WriteFully(buffer, size)) {
ErrorExit(kErrorExitCode,
"Unable to write file %s for writing snapshot\n",
- qualified_filename);
+ filename);
}
file->Release();
if (concat != NULL) {
@@ -1234,7 +1223,8 @@
file->Map(File::kReadOnly, vmisolate_position,
instructions_position - vmisolate_position);
if (read_only_buffer == NULL) {
- ErrorExit(kErrorExitCode, "Failed to memory map snapshot\n");
+ Log::PrintErr("Failed to memory map snapshot\n");
+ Platform::Exit(kErrorExitCode);
}
*vmisolate_buffer = reinterpret_cast<const uint8_t*>(read_only_buffer)
@@ -1254,7 +1244,8 @@
*instructions_buffer = reinterpret_cast<const uint8_t*>(
file->Map(File::kReadExecute, instructions_position, header[4]));
if (*instructions_buffer == NULL) {
- ErrorExit(kErrorExitCode, "Failed to memory map snapshot2\n");
+ Log::PrintErr("Failed to memory map snapshot\n");
+ Platform::Exit(kErrorExitCode);
}
}
@@ -1276,29 +1267,33 @@
*vmisolate_buffer = reinterpret_cast<const uint8_t*>(
Extensions::ResolveSymbol(library, kPrecompiledVMIsolateSymbolName));
if (*vmisolate_buffer == NULL) {
- ErrorExit(kErrorExitCode, "Failed to resolve symbol '%s'\n",
- kPrecompiledVMIsolateSymbolName);
+ Log::PrintErr("Failed to resolve symbol '%s'\n",
+ kPrecompiledVMIsolateSymbolName);
+ Platform::Exit(kErrorExitCode);
}
*isolate_buffer = reinterpret_cast<const uint8_t*>(
Extensions::ResolveSymbol(library, kPrecompiledIsolateSymbolName));
if (*isolate_buffer == NULL) {
- ErrorExit(kErrorExitCode, "Failed to resolve symbol '%s'\n",
- kPrecompiledIsolateSymbolName);
+ Log::PrintErr("Failed to resolve symbol '%s'\n",
+ kPrecompiledIsolateSymbolName);
+ Platform::Exit(kErrorExitCode);
}
*instructions_buffer = reinterpret_cast<const uint8_t*>(
Extensions::ResolveSymbol(library, kPrecompiledInstructionsSymbolName));
if (*instructions_buffer == NULL) {
- ErrorExit(kErrorExitCode, "Failed to resolve symbol '%s'\n",
- kPrecompiledInstructionsSymbolName);
+ Log::PrintErr("Failed to resolve symbol '%s'\n",
+ kPrecompiledInstructionsSymbolName);
+ Platform::Exit(kErrorExitCode);
}
*rodata_buffer = reinterpret_cast<const uint8_t*>(
Extensions::ResolveSymbol(library, kPrecompiledDataSymbolName));
if (*rodata_buffer == NULL) {
- ErrorExit(kErrorExitCode, "Failed to resolve symbol '%s'\n",
- kPrecompiledDataSymbolName);
+ Log::PrintErr("Failed to resolve symbol '%s'\n",
+ kPrecompiledDataSymbolName);
+ Platform::Exit(kErrorExitCode);
}
return true;
@@ -1397,7 +1392,7 @@
ErrorExit(kErrorExitCode, "%s\n", Dart_GetError(result));
}
- WriteSnapshotFile(NULL, snapshot_filename, true, buffer, size);
+ WriteSnapshotFile(snapshot_filename, true, buffer, size);
}
@@ -1442,7 +1437,7 @@
rodata_blob_buffer,
rodata_blob_size);
} else {
- WriteSnapshotFile(NULL, snapshot_filename,
+ WriteSnapshotFile(snapshot_filename,
false,
assembly_buffer,
assembly_size);
@@ -1450,6 +1445,7 @@
}
+#if defined(TARGET_ARCH_X64)
static void GeneratePrecompiledJITSnapshot() {
uint8_t* vm_isolate_buffer = NULL;
intptr_t vm_isolate_size = 0;
@@ -1481,11 +1477,19 @@
rodata_blob_buffer,
rodata_blob_size);
}
+#endif // defined(TARGET_ARCH_X64)
-static void GenerateFullSnapshot() {
- // Create a full snapshot of the script.
+static void GenerateAppSnapshot() {
Dart_Handle result;
+#if defined(TARGET_ARCH_X64)
+ result = Dart_PrecompileJIT();
+ if (Dart_IsError(result)) {
+ ErrorExit(kErrorExitCode, "%s\n", Dart_GetError(result));
+ }
+ GeneratePrecompiledJITSnapshot();
+#else
+ // Create an application snapshot of the script.
uint8_t* vm_isolate_buffer = NULL;
intptr_t vm_isolate_size = 0;
uint8_t* isolate_buffer = NULL;
@@ -1505,9 +1509,11 @@
isolate_buffer,
isolate_size,
NULL, 0, NULL, 0);
+#endif // defined(TARGET_ARCH_X64)
}
+
#define CHECK_RESULT(result) \
if (Dart_IsError(result)) { \
if (Dart_IsVMRestartRequest(result)) { \
@@ -1521,6 +1527,13 @@
}
+static void SnapshotOnExitHook(int64_t exit_code) {
+ if (exit_code == 0) {
+ GenerateAppSnapshot();
+ }
+}
+
+
bool RunMainIsolate(const char* script_name,
CommandLineOptions* dart_options) {
// Call CreateIsolateAndSetup which creates an isolate and loads up
@@ -1574,9 +1587,8 @@
result = Dart_LibraryImportLibrary(
isolate_data->builtin_lib(), root_lib, Dart_Null());
if (is_noopt ||
- (gen_snapshot_kind == kAppAfterRun) ||
(gen_snapshot_kind == kAppAOT) ||
- (gen_snapshot_kind == kAppJITAfterRun)) {
+ (gen_snapshot_kind == kAppJIT)) {
// Load the embedder's portion of the VM service's Dart code so it will
// be included in the app snapshot.
if (!VmService::LoadForGenPrecompiled()) {
@@ -1678,17 +1690,10 @@
// Keep handling messages until the last active receive port is closed.
result = Dart_RunLoop();
// Generate an app snapshot after execution if specified.
- if ((gen_snapshot_kind == kAppAfterRun) ||
- (gen_snapshot_kind == kAppJITAfterRun)) {
+ if (gen_snapshot_kind == kAppJIT) {
if (!Dart_IsCompilationError(result) &&
!Dart_IsVMRestartRequest(result)) {
- if (gen_snapshot_kind == kAppAfterRun) {
- GenerateFullSnapshot();
- } else {
- Dart_Handle prepare_result = Dart_PrecompileJIT();
- CHECK_RESULT(prepare_result);
- GeneratePrecompiledJITSnapshot();
- }
+ GenerateAppSnapshot();
}
}
CHECK_RESULT(result);
@@ -1866,7 +1871,7 @@
}
#endif
- if (gen_snapshot_kind == kAppJITAfterRun) {
+ if (gen_snapshot_kind == kAppJIT) {
vm_options.AddArgument("--fields_may_be_reset");
}
if ((gen_snapshot_kind == kAppAOT) || is_noopt) {
diff --git a/runtime/bin/process.cc b/runtime/bin/process.cc
index 672b3e3..ff88201 100644
--- a/runtime/bin/process.cc
+++ b/runtime/bin/process.cc
@@ -246,6 +246,11 @@
int64_t status = 0;
// Ignore result if passing invalid argument and just exit 0.
DartUtils::GetInt64Value(Dart_GetNativeArgument(args, 0), &status);
+ IsolateData* isolate_data =
+ reinterpret_cast<IsolateData*>(Dart_CurrentIsolateData());
+ if (isolate_data->exit_hook() != NULL) {
+ isolate_data->exit_hook()(status);
+ }
Dart_ExitIsolate();
Platform::Exit(static_cast<int>(status));
}
diff --git a/runtime/bin/run_vm_tests_fuchsia.cc b/runtime/bin/run_vm_tests_fuchsia.cc
index 8137a59..a974860 100644
--- a/runtime/bin/run_vm_tests_fuchsia.cc
+++ b/runtime/bin/run_vm_tests_fuchsia.cc
@@ -5,11 +5,11 @@
#include <fcntl.h>
#include <launchpad/launchpad.h>
#include <launchpad/vmo.h>
+#include <magenta/status.h>
#include <magenta/syscalls.h>
+#include <magenta/syscalls/object.h>
#include <mxio/util.h>
#include <pthread.h>
-#include <runtime/status.h>
-#include <runtime/sysinfo.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
@@ -140,15 +140,13 @@
return contains(kBugs, sizeof(kBugs) / sizeof(kBugs[0]), test);
}
-
#define RETURN_IF_ERROR(status) \
if (status < 0) { \
- fprintf(stderr, "%s:%d: Magenta call failed: %s\n", \
- __FILE__, __LINE__, mx_strstatus(static_cast<mx_status_t>(status))); \
+ fprintf(stderr, "%s:%d: Magenta call failed: %s\n", __FILE__, __LINE__, \
+ mx_status_get_string(static_cast<mx_status_t>(status))); \
fflush(0); \
return status; \
- } \
-
+ }
// This is mostly taken from //magenta/system/uapp/mxsh with the addtion of
// launchpad_add_pipe calls to setup pipes for stdout and stderr.
diff --git a/runtime/bin/socket_patch.dart b/runtime/bin/socket_patch.dart
index 4850827..cd02b29 100644
--- a/runtime/bin/socket_patch.dart
+++ b/runtime/bin/socket_patch.dart
@@ -449,7 +449,12 @@
connectNext();
} else {
// Query the local port, for error messages.
- socket.port;
+ try {
+ socket.port;
+ } catch (e) {
+ error = createError(e, "Connection failed", address, port);
+ connectNext();
+ }
// Set up timer for when we should retry the next address
// (if any).
var duration = address.isLoopback ?
diff --git a/runtime/observatory/lib/src/service/object.dart b/runtime/observatory/lib/src/service/object.dart
index 32df1b2..e0f6e05 100644
--- a/runtime/observatory/lib/src/service/object.dart
+++ b/runtime/observatory/lib/src/service/object.dart
@@ -3254,6 +3254,7 @@
Script._empty(ServiceObjectOwner owner) : super._empty(owner);
+ /// Retrieves line number [line] if it exists.
ScriptLine getLine(int line) {
assert(_loaded);
assert(line >= 1);
@@ -3261,10 +3262,12 @@
}
/// This function maps a token position to a line number.
+ /// The VM considers the first line to be line 1.
int tokenToLine(int tokenPos) => _tokenToLine[tokenPos];
Map _tokenToLine = {};
/// This function maps a token position to a column number.
+ /// The VM considers the first column to be column 1.
int tokenToCol(int tokenPos) => _tokenToCol[tokenPos];
Map _tokenToCol = {};
@@ -3327,7 +3330,7 @@
static bool _isIdentifierChar(int c) {
if (_isInitialIdentifierChar(c)) return true;
- return c >= 48 && c <= 75; // Digit
+ return c >= 48 && c <= 57; // Digit
}
void _update(Map map, bool mapIsRef) {
@@ -3408,6 +3411,28 @@
}
}
+ // Note, this may return source beyond the token length if [guessTokenLength]
+ // fails.
+ String getToken(int tokenPos) {
+ final int line = tokenToLine(tokenPos);
+ int column = tokenToCol(tokenPos);
+ if ((line == null) || (column == null)) {
+ return null;
+ }
+ // Line and column numbers start at 1 in the VM.
+ column -= 1;
+ String sourceLine = getLine(line).text;
+ if (sourceLine == null) {
+ return null;
+ }
+ final int length = guessTokenLength(line, column);
+ if (length == null) {
+ return sourceLine.substring(column);
+ } else {
+ return sourceLine.substring(column, column + length);
+ }
+ }
+
void _addBreakpoint(Breakpoint bpt) {
var line;
if (bpt.location.tokenPos != null) {
@@ -3610,13 +3635,20 @@
final String id;
final String name;
final int index;
+ final int declarationPos;
final int beginPos;
final int endPos;
final int scopeId;
final String kind;
- LocalVarDescriptor(this.id, this.name, this.index, this.beginPos, this.endPos,
- this.scopeId, this.kind);
+ LocalVarDescriptor(this.id,
+ this.name,
+ this.index,
+ this.declarationPos,
+ this.beginPos,
+ this.endPos,
+ this.scopeId,
+ this.kind);
}
class LocalVarDescriptors extends ServiceObject {
@@ -3638,12 +3670,13 @@
var id = descriptor['name'];
var name = descriptor['name'];
var index = descriptor['index'];
- var beginPos = descriptor['beginPos'];
- var endPos = descriptor['endPos'];
+ var declarationPos = descriptor['declarationTokenPos'];
+ var beginPos = descriptor['scopeStartTokenPos'];
+ var endPos = descriptor['scopeEndTokenPos'];
var scopeId = descriptor['scopeId'];
var kind = descriptor['kind'].trim();
descriptors.add(new LocalVarDescriptor(
- id, name, index, beginPos, endPos, scopeId, kind));
+ id, name, index, declarationPos, beginPos, endPos, scopeId, kind));
}
}
}
diff --git a/runtime/observatory/tests/service/local_variable_declaration_test.dart b/runtime/observatory/tests/service/local_variable_declaration_test.dart
new file mode 100644
index 0000000..3425bab
--- /dev/null
+++ b/runtime/observatory/tests/service/local_variable_declaration_test.dart
@@ -0,0 +1,101 @@
+// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+// VMOptions=--error_on_bad_type --error_on_bad_override --verbose_debug
+
+import 'package:observatory/service_io.dart';
+import 'package:unittest/unittest.dart';
+import 'service_test_common.dart';
+import 'test_helper.dart';
+import 'dart:developer';
+
+testParameters(int jjjj, int oooo, [int hhhh, int nnnn]) {
+ debugger();
+}
+
+testMain() {
+ int xxx, yyyy, zzzzz;
+ for (int i = 0; i < 1; i++) {
+ var foo = () {
+ };
+ debugger();
+ }
+ var bar = () {
+ print(xxx);
+ print(yyyy);
+ debugger();
+ };
+ bar();
+ testParameters(0, 0);
+}
+
+var tests = [
+ hasStoppedAtBreakpoint,
+ stoppedInFunction('testMain'),
+ (Isolate isolate) async {
+ var stack = await isolate.getStack();
+ expect(stack.type, equals('Stack'));
+ expect(stack['frames'].length, greaterThanOrEqualTo(1));
+ // Grab the top frame.
+ Frame frame = stack['frames'][0];
+ // Grab the script.
+ Script script = frame.location.script;
+ await script.load();
+
+ // Ensure that the token at each declaration position is the name of the
+ // variable.
+ for (var variable in frame.variables) {
+ final int declarationTokenPos = variable['declarationTokenPos'];
+ final String name = variable['name'];
+ final String token = script.getToken(declarationTokenPos);
+ expect(name, token);
+ }
+ },
+ resumeIsolate,
+ hasStoppedAtBreakpoint,
+ // We have stopped in the anonymous closure assigned to bar. Verify that
+ // variables captured in the context have valid declaration positions.
+ (Isolate isolate) async {
+ var stack = await isolate.getStack();
+ expect(stack.type, equals('Stack'));
+ expect(stack['frames'].length, greaterThanOrEqualTo(1));
+ // Grab the top frame.
+ Frame frame = stack['frames'][0];
+ // Grab the script.
+ Script script = frame.location.script;
+ await script.load();
+ print(frame);
+ expect(frame.variables.length, greaterThanOrEqualTo(1));
+ for (var variable in frame.variables) {
+ final int declarationTokenPos = variable['declarationTokenPos'];
+ final String name = variable['name'];
+ final String token = script.getToken(declarationTokenPos);
+ expect(name, token);
+ }
+ },
+ resumeIsolate,
+ hasStoppedAtBreakpoint,
+ stoppedInFunction('testParameters'),
+ (Isolate isolate) async {
+ var stack = await isolate.getStack();
+ expect(stack.type, equals('Stack'));
+ expect(stack['frames'].length, greaterThanOrEqualTo(1));
+ // Grab the top frame.
+ Frame frame = stack['frames'][0];
+ // Grab the script.
+ Script script = frame.location.script;
+ await script.load();
+
+ // Ensure that the token at each declaration position is the name of the
+ // variable.
+ expect(frame.variables.length, greaterThanOrEqualTo(1));
+ for (var variable in frame.variables) {
+ final int declarationTokenPos = variable['declarationTokenPos'];
+ final String name = variable['name'];
+ final String token = script.getToken(declarationTokenPos);
+ expect(name, token);
+ }
+ }
+];
+
+main(args) => runIsolateTests(args, tests, testeeConcurrent: testMain);
diff --git a/runtime/platform/assert.h b/runtime/platform/assert.h
index 9c810c5..81cb7f1 100644
--- a/runtime/platform/assert.h
+++ b/runtime/platform/assert.h
@@ -254,6 +254,9 @@
#define UNREACHABLE() \
FATAL("unreachable code")
+#define OUT_OF_MEMORY() \
+ FATAL("Out of memory.")
+
#if defined(DEBUG)
// DEBUG binaries use assertions in the code.
diff --git a/runtime/platform/globals.h b/runtime/platform/globals.h
index 114c47d..cd01fc5 100644
--- a/runtime/platform/globals.h
+++ b/runtime/platform/globals.h
@@ -298,6 +298,14 @@
#error Automatic compiler detection failed.
#endif
+#ifdef _MSC_VER
+#define DART_PRETTY_FUNCTION __FUNCSIG__
+#elif __GNUC__
+#define DART_PRETTY_FUNCTION __PRETTY_FUNCTION__
+#else
+#error Automatic compiler detection failed.
+#endif
+
#if !defined(TARGET_ARCH_MIPS)
#if !defined(TARGET_ARCH_ARM)
#if !defined(TARGET_ARCH_X64)
diff --git a/runtime/platform/hashmap.cc b/runtime/platform/hashmap.cc
index 34f7ea1..4611533 100644
--- a/runtime/platform/hashmap.cc
+++ b/runtime/platform/hashmap.cc
@@ -166,9 +166,7 @@
ASSERT(dart::Utils::IsPowerOfTwo(capacity));
map_ = new Entry[capacity];
if (map_ == NULL) {
- // TODO(sgjesse): Handle out of memory.
- FATAL("Cannot allocate memory for hashmap");
- return;
+ OUT_OF_MEMORY();
}
capacity_ = capacity;
occupancy_ = 0;
diff --git a/runtime/platform/text_buffer.cc b/runtime/platform/text_buffer.cc
index 44152e6..b06c49f 100644
--- a/runtime/platform/text_buffer.cc
+++ b/runtime/platform/text_buffer.cc
@@ -15,6 +15,9 @@
TextBuffer::TextBuffer(intptr_t buf_size) {
ASSERT(buf_size > 0);
buf_ = reinterpret_cast<char*>(malloc(buf_size));
+ if (buf_ == NULL) {
+ OUT_OF_MEMORY();
+ }
buf_size_ = buf_size;
Clear();
}
@@ -152,7 +155,9 @@
// the debugger front-end.
intptr_t new_size = buf_size_ + len + kBufferSpareCapacity;
char* new_buf = reinterpret_cast<char*>(realloc(buf_, new_size));
- ASSERT(new_buf != NULL);
+ if (new_buf == NULL) {
+ OUT_OF_MEMORY();
+ }
buf_ = new_buf;
buf_size_ = new_size;
}
diff --git a/runtime/vm/BUILD.gn b/runtime/vm/BUILD.gn
index 01dd5e9..d7edae6 100644
--- a/runtime/vm/BUILD.gn
+++ b/runtime/vm/BUILD.gn
@@ -6,7 +6,6 @@
if (defined(is_fuchsia) && is_fuchsia) {
libs = [
"magenta",
- "runtime",
]
} else if (is_win) {
libs = [
diff --git a/runtime/vm/ast.cc b/runtime/vm/ast.cc
index 2ba8dc1..cfe1637 100644
--- a/runtime/vm/ast.cc
+++ b/runtime/vm/ast.cc
@@ -111,7 +111,8 @@
OS::SNPrint(name, sizeof(name), ":lt%s_%" Pd "",
token_pos().ToCString(), vars_.length());
LocalVariable* temp_var =
- new LocalVariable(token_pos(),
+ new LocalVariable(TokenPosition::kNoSource,
+ token_pos(),
String::ZoneHandle(zone, Symbols::New(thread, name)),
Object::dynamic_type());
vars_.Add(temp_var);
diff --git a/runtime/vm/ast_printer_test.cc b/runtime/vm/ast_printer_test.cc
index 888fdda..f3f7fd6 100644
--- a/runtime/vm/ast_printer_test.cc
+++ b/runtime/vm/ast_printer_test.cc
@@ -18,6 +18,7 @@
const TokenPosition kPos = TokenPosition::kNoSource;
LocalVariable* v =
new LocalVariable(kPos,
+ kPos,
String::ZoneHandle(Symbols::New(thread, "wurscht")),
Type::ZoneHandle(Type::DynamicType()));
v->set_index(5);
diff --git a/runtime/vm/ast_test.cc b/runtime/vm/ast_test.cc
index 90513c2..7b49c9c 100644
--- a/runtime/vm/ast_test.cc
+++ b/runtime/vm/ast_test.cc
@@ -15,6 +15,7 @@
TEST_CASE(Ast) {
LocalVariable* v = new LocalVariable(
TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
String::ZoneHandle(Symbols::New(thread, "v")),
Type::ZoneHandle(Type::DynamicType()));
AstNode* ll = new LoadLocalNode(TokenPosition::kNoSource, v);
@@ -27,6 +28,7 @@
LocalVariable* p = new LocalVariable(
TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
String::ZoneHandle(Symbols::New(thread, "p")),
Type::ZoneHandle(Type::DynamicType()));
EXPECT(!p->HasIndex());
diff --git a/runtime/vm/ast_transformer.cc b/runtime/vm/ast_transformer.cc
index 28861ef..a137674 100644
--- a/runtime/vm/ast_transformer.cc
+++ b/runtime/vm/ast_transformer.cc
@@ -77,7 +77,10 @@
if (await_tmp == NULL) {
// We need a new temp variable; add it to the function's top scope.
await_tmp = new(Z) LocalVariable(
- TokenPosition::kNoSource, symbol, Object::dynamic_type());
+ TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
+ symbol,
+ Object::dynamic_type());
async_temp_scope_->AddVariable(await_tmp);
// After adding it to the top scope, we can look it up from the preamble.
// The following call includes an ASSERT check.
diff --git a/runtime/vm/clustered_snapshot.cc b/runtime/vm/clustered_snapshot.cc
index 1799db8..baff543 100644
--- a/runtime/vm/clustered_snapshot.cc
+++ b/runtime/vm/clustered_snapshot.cc
@@ -28,7 +28,7 @@
uword address = old_space->TryAllocateDataBumpLocked(size,
PageSpace::kForceGrowth);
if (address == 0) {
- FATAL("Out of memory");
+ OUT_OF_MEMORY();
}
return reinterpret_cast<RawObject*>(address + kHeapObjectTag);
}
diff --git a/runtime/vm/code_generator.cc b/runtime/vm/code_generator.cc
index 1d101b9..85a5bce 100644
--- a/runtime/vm/code_generator.cc
+++ b/runtime/vm/code_generator.cc
@@ -1728,7 +1728,7 @@
FLAG_precompiled_runtime ? 0 : frame->NumLocalVariables();
TokenPosition unused = TokenPosition::kNoSource;
for (intptr_t v = 0; v < num_vars; v++) {
- frame->VariableAt(v, &var_name, &unused, &unused, &var_value);
+ frame->VariableAt(v, &var_name, &unused, &unused, &unused, &var_value);
}
}
FLAG_stacktrace_every = saved_stacktrace_every;
diff --git a/runtime/vm/code_generator_test.cc b/runtime/vm/code_generator_test.cc
index 54a9174..df97482 100644
--- a/runtime/vm/code_generator_test.cc
+++ b/runtime/vm/code_generator_test.cc
@@ -50,7 +50,7 @@
const String& variable_name = String::ZoneHandle(
Symbols::New(Thread::Current(), name));
const Type& variable_type = Type::ZoneHandle(Type::DynamicType());
- return new LocalVariable(kPos, variable_name, variable_type);
+ return new LocalVariable(kPos, kPos, variable_name, variable_type);
}
diff --git a/runtime/vm/constant_propagator.cc b/runtime/vm/constant_propagator.cc
index 1f5290d..06f8dd5 100644
--- a/runtime/vm/constant_propagator.cc
+++ b/runtime/vm/constant_propagator.cc
@@ -1168,6 +1168,27 @@
}
+void ConstantPropagator::VisitDoubleTestOp(DoubleTestOpInstr* instr) {
+ const Object& value = instr->value()->definition()->constant_value();
+ if (value.IsInteger()) {
+ SetValue(instr, Bool::False());
+ } else if (IsIntegerOrDouble(value)) {
+ switch (instr->op_kind()) {
+ case MethodRecognizer::kDouble_getIsNaN:
+ SetValue(instr, Bool::Get(isnan(ToDouble(value))));
+ break;
+ case MethodRecognizer::kDouble_getIsInfinite:
+ SetValue(instr, Bool::Get(isinf(ToDouble(value))));
+ break;
+ default:
+ UNREACHABLE();
+ }
+ } else {
+ SetValue(instr, non_constant_);
+ }
+}
+
+
void ConstantPropagator::VisitBinaryFloat32x4Op(
BinaryFloat32x4OpInstr* instr) {
const Object& left = instr->left()->definition()->constant_value();
diff --git a/runtime/vm/constants_dbc.h b/runtime/vm/constants_dbc.h
index f274ebb..44e5026 100644
--- a/runtime/vm/constants_dbc.h
+++ b/runtime/vm/constants_dbc.h
@@ -230,6 +230,16 @@
// Convert the unboxed float or double in FP[rD] as indicated, and store the
// result in FP[rA].
//
+// - DoubleIsNaN rA, rD
+//
+// If the unboxed double in FP[rD] is a NaN, then writes Bool::True().raw()
+// into FP[rA], and Bool::False().raw() otherwise.
+//
+// - DoubleIsInfinite rA, rD
+//
+// If the unboxed double in FP[rD] is + or - infinity, then
+// writes Bool::True().raw() into FP[rA], and Bool::False().raw() otherwise.
+//
// - BitOr, BitAnd, BitXor rA, rB, rC
//
// FP[rA] <- FP[rB] op FP[rC]. These instructions expect their operands to be
@@ -719,6 +729,8 @@
V(DCeil, A_D, reg, reg, ___) \
V(DoubleToFloat, A_D, reg, reg, ___) \
V(FloatToDouble, A_D, reg, reg, ___) \
+ V(DoubleIsNaN, A_D, reg, reg, ___) \
+ V(DoubleIsInfinite, A_D, reg, reg, ___) \
V(StoreStaticTOS, D, lit, ___, ___) \
V(PushStatic, D, lit, ___, ___) \
V(InitStaticTOS, 0, ___, ___, ___) \
diff --git a/runtime/vm/dart.cc b/runtime/vm/dart.cc
index 05d8d14..b4534c9 100644
--- a/runtime/vm/dart.cc
+++ b/runtime/vm/dart.cc
@@ -92,7 +92,6 @@
// These offsets are embedded in precompiled instructions. We need simarm
// (compiler) and arm (runtime) to agree.
CHECK_OFFSET(Heap::TopOffset(Heap::kNew), 8);
- CHECK_OFFSET(Isolate::heap_offset(), 8);
CHECK_OFFSET(Thread::stack_limit_offset(), 4);
CHECK_OFFSET(Thread::object_null_offset(), 36);
CHECK_OFFSET(SingleTargetCache::upper_limit_offset(), 14);
@@ -102,7 +101,6 @@
// These offsets are embedded in precompiled instructions. We need simmips
// (compiler) and mips (runtime) to agree.
CHECK_OFFSET(Heap::TopOffset(Heap::kNew), 8);
- CHECK_OFFSET(Isolate::heap_offset(), 8);
CHECK_OFFSET(Thread::stack_limit_offset(), 4);
CHECK_OFFSET(Thread::object_null_offset(), 36);
CHECK_OFFSET(SingleTargetCache::upper_limit_offset(), 14);
@@ -112,7 +110,6 @@
// These offsets are embedded in precompiled instructions. We need simarm64
// (compiler) and arm64 (runtime) to agree.
CHECK_OFFSET(Heap::TopOffset(Heap::kNew), 8);
- CHECK_OFFSET(Isolate::heap_offset(), 16);
CHECK_OFFSET(Thread::stack_limit_offset(), 8);
CHECK_OFFSET(Thread::object_null_offset(), 72);
CHECK_OFFSET(SingleTargetCache::upper_limit_offset(), 28);
diff --git a/runtime/vm/debugger.cc b/runtime/vm/debugger.cc
index 16bb50f..5176eff 100644
--- a/runtime/vm/debugger.cc
+++ b/runtime/vm/debugger.cc
@@ -896,8 +896,9 @@
void ActivationFrame::VariableAt(intptr_t i,
String* name,
- TokenPosition* token_pos,
- TokenPosition* end_pos,
+ TokenPosition* declaration_token_pos,
+ TokenPosition* visible_start_token_pos,
+ TokenPosition* visible_end_token_pos,
Object* value) {
GetDescIndices();
ASSERT(i < desc_indices_.length());
@@ -908,10 +909,12 @@
RawLocalVarDescriptors::VarInfo var_info;
var_descriptors_.GetInfo(desc_index, &var_info);
- ASSERT(token_pos != NULL);
- *token_pos = var_info.begin_pos;
- ASSERT(end_pos != NULL);
- *end_pos = var_info.end_pos;
+ ASSERT(declaration_token_pos != NULL);
+ *declaration_token_pos = var_info.declaration_pos;
+ ASSERT(visible_start_token_pos != NULL);
+ *visible_start_token_pos = var_info.begin_pos;
+ ASSERT(visible_end_token_pos != NULL);
+ *visible_end_token_pos = var_info.end_pos;
ASSERT(value != NULL);
const int8_t kind = var_info.kind();
if (kind == RawLocalVarDescriptors::kStackVar) {
@@ -966,7 +969,7 @@
const Array& list = Array::Handle(Array::New(2 * num_variables));
for (intptr_t i = 0; i < num_variables; i++) {
TokenPosition ignore;
- VariableAt(i, &var_name, &ignore, &ignore, &value);
+ VariableAt(i, &var_name, &ignore, &ignore, &ignore, &value);
list.SetAt(2 * i, var_name);
list.SetAt((2 * i) + 1, value);
}
@@ -981,7 +984,7 @@
Instance& value = Instance::Handle();
for (intptr_t i = 0; i < num_variables; i++) {
TokenPosition ignore;
- VariableAt(i, &var_name, &ignore, &ignore, &value);
+ VariableAt(i, &var_name, &ignore, &ignore, &ignore, &value);
if (var_name.Equals(Symbols::This())) {
return value.raw();
}
@@ -1011,7 +1014,7 @@
intptr_t num_variables = desc_indices_.length();
for (intptr_t i = 0; i < num_variables; i++) {
TokenPosition ignore;
- VariableAt(i, &name, &ignore, &ignore, &value);
+ VariableAt(i, &name, &ignore, &ignore, &ignore, &value);
if (!name.Equals(Symbols::This()) && !IsSyntheticVariableName(name)) {
if (IsPrivateVariableName(name)) {
name = String::ScrubName(name);
@@ -1087,20 +1090,27 @@
for (intptr_t v = 0; v < num_vars; v++) {
String& var_name = String::Handle();
Instance& var_value = Instance::Handle();
- TokenPosition token_pos;
- TokenPosition end_token_pos;
- VariableAt(v, &var_name, &token_pos, &end_token_pos, &var_value);
+ TokenPosition declaration_token_pos;
+ TokenPosition visible_start_token_pos;
+ TokenPosition visible_end_token_pos;
+ VariableAt(v,
+ &var_name,
+ &declaration_token_pos,
+ &visible_start_token_pos,
+ &visible_end_token_pos,
+ &var_value);
if (var_name.raw() != Symbols::AsyncOperation().raw()) {
JSONObject jsvar(&jsvars);
jsvar.AddProperty("type", "BoundVariable");
var_name = String::ScrubName(var_name);
jsvar.AddProperty("name", var_name.ToCString());
jsvar.AddProperty("value", var_value, !full);
- // TODO(turnidge): Do we really want to provide this on every
- // stack dump? Should be associated with the function object, I
- // think, and not the stack frame.
- jsvar.AddProperty("_tokenPos", token_pos);
- jsvar.AddProperty("_endTokenPos", end_token_pos);
+ // Where was the variable declared?
+ jsvar.AddProperty("declarationTokenPos", declaration_token_pos);
+ // When the variable becomes visible to the scope.
+ jsvar.AddProperty("scopeStartTokenPos", visible_start_token_pos);
+ // When the variable stops being visible to the scope.
+ jsvar.AddProperty("scopeEndTokenPos", visible_end_token_pos);
}
}
}
diff --git a/runtime/vm/debugger.h b/runtime/vm/debugger.h
index f3536c7..4338275 100644
--- a/runtime/vm/debugger.h
+++ b/runtime/vm/debugger.h
@@ -285,8 +285,9 @@
void VariableAt(intptr_t i,
String* name,
- TokenPosition* token_pos,
- TokenPosition* end_pos,
+ TokenPosition* declaration_token_pos,
+ TokenPosition* visible_start_token_pos,
+ TokenPosition* visible_end_token_pos,
Object* value);
RawArray* GetLocalVariables();
diff --git a/runtime/vm/flow_graph_builder.cc b/runtime/vm/flow_graph_builder.cc
index 333257f..d6871ae 100644
--- a/runtime/vm/flow_graph_builder.cc
+++ b/runtime/vm/flow_graph_builder.cc
@@ -2294,6 +2294,7 @@
OS::SNPrint(name, 64, ":tmp_local%" Pd, index);
LocalVariable* var =
new(Z) LocalVariable(TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
String::ZoneHandle(Z, Symbols::New(T, name)),
*value->Type()->ToAbstractType());
var->set_index(index);
@@ -4027,6 +4028,7 @@
const String& temp_name = Symbols::TempParam();
LocalVariable* temp_local = new(Z) LocalVariable(
TokenPosition::kNoSource, // Token index.
+ TokenPosition::kNoSource, // Token index.
temp_name,
Object::dynamic_type()); // Type.
temp_local->set_index(param_frame_index);
diff --git a/runtime/vm/flow_graph_inliner.cc b/runtime/vm/flow_graph_inliner.cc
index 726f6e8..05f6579 100644
--- a/runtime/vm/flow_graph_inliner.cc
+++ b/runtime/vm/flow_graph_inliner.cc
@@ -2402,6 +2402,34 @@
}
+static bool InlineDoubleTestOp(FlowGraph* flow_graph,
+ Instruction* call,
+ MethodRecognizer::Kind kind,
+ TargetEntryInstr** entry,
+ Definition** last) {
+ if (!CanUnboxDouble()) {
+ return false;
+ }
+ Definition* d = call->ArgumentAt(0);
+
+ *entry = new(Z) TargetEntryInstr(flow_graph->allocate_block_id(),
+ call->GetBlock()->try_index());
+ (*entry)->InheritDeoptTarget(Z, call);
+ // Arguments are checked. No need for class check.
+
+ DoubleTestOpInstr* double_test_op =
+ new(Z) DoubleTestOpInstr(kind,
+ new(Z) Value(d),
+ call->deopt_id(),
+ call->token_pos());
+ flow_graph->AppendTo(
+ *entry, double_test_op, call->env(), FlowGraph::kValue);
+ *last = double_test_op;
+
+ return true;
+}
+
+
static bool InlineSmiBitAndFromSmi(FlowGraph* flow_graph,
Instruction* call,
TargetEntryInstr** entry,
@@ -3649,6 +3677,9 @@
return InlineDoubleOp(flow_graph, Token::kMUL, call, entry, last);
case MethodRecognizer::kDoubleDiv:
return InlineDoubleOp(flow_graph, Token::kDIV, call, entry, last);
+ case MethodRecognizer::kDouble_getIsNaN:
+ case MethodRecognizer::kDouble_getIsInfinite:
+ return InlineDoubleTestOp(flow_graph, call, kind, entry, last);
case MethodRecognizer::kGrowableArraySetData:
ASSERT(receiver_cid == kGrowableObjectArrayCid);
ASSERT(ic_data.NumberOfChecks() == 1);
diff --git a/runtime/vm/flow_graph_type_propagator.cc b/runtime/vm/flow_graph_type_propagator.cc
index d0dd61b..4b953752 100644
--- a/runtime/vm/flow_graph_type_propagator.cc
+++ b/runtime/vm/flow_graph_type_propagator.cc
@@ -1152,6 +1152,11 @@
}
+CompileType DoubleTestOpInstr::ComputeType() const {
+ return CompileType::FromCid(kBoolCid);
+}
+
+
CompileType BinaryFloat32x4OpInstr::ComputeType() const {
return CompileType::FromCid(kFloat32x4Cid);
}
diff --git a/runtime/vm/il_printer.cc b/runtime/vm/il_printer.cc
index d8d18f3..7a6874f 100644
--- a/runtime/vm/il_printer.cc
+++ b/runtime/vm/il_printer.cc
@@ -726,6 +726,21 @@
}
+void DoubleTestOpInstr::PrintOperandsTo(BufferFormatter* f) const {
+ switch (op_kind()) {
+ case MethodRecognizer::kDouble_getIsNaN:
+ f->Print("IsNaN ");
+ break;
+ case MethodRecognizer::kDouble_getIsInfinite:
+ f->Print("IsInfinite ");
+ break;
+ default:
+ UNREACHABLE();
+ }
+ value()->PrintTo(f);
+}
+
+
void BinaryFloat32x4OpInstr::PrintOperandsTo(BufferFormatter* f) const {
f->Print("%s, ", Token::Str(op_kind()));
left()->PrintTo(f);
diff --git a/runtime/vm/intermediate_language.cc b/runtime/vm/intermediate_language.cc
index ab7c878..c3359f1 100644
--- a/runtime/vm/intermediate_language.cc
+++ b/runtime/vm/intermediate_language.cc
@@ -1497,6 +1497,11 @@
}
+Definition* DoubleTestOpInstr::Canonicalize(FlowGraph* flow_graph) {
+ return HasUses() ? this : NULL;
+}
+
+
static bool IsCommutative(Token::Kind op) {
switch (op) {
case Token::kMUL:
diff --git a/runtime/vm/intermediate_language.h b/runtime/vm/intermediate_language.h
index 1fe4377..2876be7 100644
--- a/runtime/vm/intermediate_language.h
+++ b/runtime/vm/intermediate_language.h
@@ -497,6 +497,7 @@
M(UnboxedConstant) \
M(CheckEitherNonSmi) \
M(BinaryDoubleOp) \
+ M(DoubleTestOp) \
M(MathUnary) \
M(MathMinMax) \
M(Box) \
@@ -5343,6 +5344,56 @@
};
+class DoubleTestOpInstr : public TemplateDefinition<1, NoThrow, Pure> {
+ public:
+ DoubleTestOpInstr(MethodRecognizer::Kind op_kind,
+ Value* d,
+ intptr_t deopt_id,
+ TokenPosition token_pos)
+ : TemplateDefinition(deopt_id),
+ op_kind_(op_kind),
+ token_pos_(token_pos) {
+ SetInputAt(0, d);
+ }
+
+ Value* value() const { return inputs_[0]; }
+
+ MethodRecognizer::Kind op_kind() const { return op_kind_; }
+
+ virtual TokenPosition token_pos() const { return token_pos_; }
+
+ virtual bool CanDeoptimize() const { return false; }
+
+ virtual Representation RequiredInputRepresentation(intptr_t idx) const {
+ ASSERT(idx == 0);
+ return kUnboxedDouble;
+ }
+
+ virtual intptr_t DeoptimizationTarget() const {
+ // Direct access since this instruction cannot deoptimize, and the deopt-id
+ // was inherited from another instruction that could deoptimize.
+ return GetDeoptId();
+ }
+
+ PRINT_OPERANDS_TO_SUPPORT
+
+ DECLARE_INSTRUCTION(DoubleTestOp)
+ virtual CompileType ComputeType() const;
+
+ virtual Definition* Canonicalize(FlowGraph* flow_graph);
+
+ virtual bool AttributesEqual(Instruction* other) const {
+ return op_kind_ == other->AsDoubleTestOp()->op_kind();
+ }
+
+ private:
+ const MethodRecognizer::Kind op_kind_;
+ const TokenPosition token_pos_;
+
+ DISALLOW_COPY_AND_ASSIGN(DoubleTestOpInstr);
+};
+
+
class BinaryFloat32x4OpInstr : public TemplateDefinition<2, NoThrow, Pure> {
public:
BinaryFloat32x4OpInstr(Token::Kind op_kind,
diff --git a/runtime/vm/intermediate_language_arm.cc b/runtime/vm/intermediate_language_arm.cc
index f92bbf4..6550738 100644
--- a/runtime/vm/intermediate_language_arm.cc
+++ b/runtime/vm/intermediate_language_arm.cc
@@ -4142,6 +4142,49 @@
}
+LocationSummary* DoubleTestOpInstr::MakeLocationSummary(Zone* zone,
+ bool opt) const {
+ const intptr_t kNumInputs = 1;
+ const intptr_t kNumTemps = 0;
+ LocationSummary* summary = new(zone) LocationSummary(
+ zone, kNumInputs, kNumTemps, LocationSummary::kNoCall);
+ summary->set_in(0, Location::RequiresFpuRegister());
+ summary->set_out(0, Location::RequiresRegister());
+ return summary;
+}
+
+
+void DoubleTestOpInstr::EmitNativeCode(FlowGraphCompiler* compiler) {
+ ASSERT(compiler->is_optimizing());
+ const DRegister value = EvenDRegisterOf(locs()->in(0).fpu_reg());
+ const Register result = locs()->out(0).reg();
+ if (op_kind() == MethodRecognizer::kDouble_getIsNaN) {
+ __ LoadObject(result, Bool::False());
+ __ vcmpd(value, value);
+ __ vmstat();
+ __ LoadObject(result, Bool::True(), VS);
+ } else {
+ ASSERT(op_kind() == MethodRecognizer::kDouble_getIsInfinite);
+ Label done;
+ // TMP <- value[0:31], result <- value[32:63]
+ __ vmovrrd(TMP, result, value);
+ __ cmp(TMP, Operand(0));
+ __ LoadObject(result, Bool::False(), NE);
+ __ b(&done, NE);
+
+ // Mask off the sign bit.
+ __ AndImmediate(result, result, 0x7FFFFFFF);
+ // Compare with +infinity.
+ __ CompareImmediate(result, 0x7FF00000);
+ __ LoadObject(result, Bool::False(), NE);
+ __ b(&done, NE);
+
+ __ LoadObject(result, Bool::True());
+ __ Bind(&done);
+ }
+}
+
+
LocationSummary* BinaryFloat32x4OpInstr::MakeLocationSummary(Zone* zone,
bool opt) const {
const intptr_t kNumInputs = 2;
@@ -5783,6 +5826,7 @@
__ b(&skip_call, EQ); // base is 1.0, result is 1.0.
__ vcmpd(saved_base, exp);
+ __ vmstat();
__ b(&try_sqrt, VC); // // Neither 'exp' nor 'base' is NaN.
__ Bind(&return_nan);
@@ -5797,15 +5841,18 @@
// base == -Infinity -> call pow;
__ vcmpd(saved_base, result);
+ __ vmstat();
__ b(&do_pow, EQ);
// exponent == 0.5 ?
__ LoadDImmediate(result, 0.5, temp);
__ vcmpd(exp, result);
+ __ vmstat();
__ b(&do_pow, NE);
// base == 0 -> return 0;
__ vcmpdz(saved_base);
+ __ vmstat();
__ b(&return_zero, EQ);
__ vsqrtd(result, saved_base);
diff --git a/runtime/vm/intermediate_language_arm64.cc b/runtime/vm/intermediate_language_arm64.cc
index 1eabe23..3503a99 100644
--- a/runtime/vm/intermediate_language_arm64.cc
+++ b/runtime/vm/intermediate_language_arm64.cc
@@ -3482,6 +3482,41 @@
}
+LocationSummary* DoubleTestOpInstr::MakeLocationSummary(Zone* zone,
+ bool opt) const {
+ const intptr_t kNumInputs = 1;
+ const intptr_t kNumTemps = 0;
+ LocationSummary* summary = new(zone) LocationSummary(
+ zone, kNumInputs, kNumTemps, LocationSummary::kNoCall);
+ summary->set_in(0, Location::RequiresFpuRegister());
+ summary->set_out(0, Location::RequiresRegister());
+ return summary;
+}
+
+
+void DoubleTestOpInstr::EmitNativeCode(FlowGraphCompiler* compiler) {
+ ASSERT(compiler->is_optimizing());
+ const VRegister value = locs()->in(0).fpu_reg();
+ const Register result = locs()->out(0).reg();
+ if (op_kind() == MethodRecognizer::kDouble_getIsNaN) {
+ __ fcmpd(value, value);
+ __ LoadObject(result, Bool::False());
+ __ LoadObject(TMP, Bool::True());
+ __ csel(result, TMP, result, VS);
+ } else {
+ ASSERT(op_kind() == MethodRecognizer::kDouble_getIsInfinite);
+ __ vmovrd(result, value, 0);
+ // Mask off the sign.
+ __ AndImmediate(result, result, 0x7FFFFFFFFFFFFFFFLL);
+ // Compare with +infinity.
+ __ CompareImmediate(result, 0x7FF0000000000000LL);
+ __ LoadObject(result, Bool::False());
+ __ LoadObject(TMP, Bool::True());
+ __ csel(result, TMP, result, EQ);
+ }
+}
+
+
LocationSummary* BinaryFloat32x4OpInstr::MakeLocationSummary(Zone* zone,
bool opt) const {
const intptr_t kNumInputs = 2;
diff --git a/runtime/vm/intermediate_language_dbc.cc b/runtime/vm/intermediate_language_dbc.cc
index 6bde28b..26c8fec 100644
--- a/runtime/vm/intermediate_language_dbc.cc
+++ b/runtime/vm/intermediate_language_dbc.cc
@@ -1649,6 +1649,23 @@
}
+EMIT_NATIVE_CODE(DoubleTestOp, 1, Location::RequiresRegister()) {
+ ASSERT(compiler->is_optimizing());
+ const Register value = locs()->in(0).reg();
+ const Register result = locs()->out(0).reg();
+ switch (op_kind()) {
+ case MethodRecognizer::kDouble_getIsNaN:
+ __ DoubleIsNaN(result, value);
+ break;
+ case MethodRecognizer::kDouble_getIsInfinite:
+ __ DoubleIsInfinite(result, value);
+ break;
+ default:
+ UNREACHABLE();
+ }
+}
+
+
EMIT_NATIVE_CODE(UnaryDoubleOp, 1, Location::RequiresRegister()) {
const Register value = locs()->in(0).reg();
const Register result = locs()->out(0).reg();
diff --git a/runtime/vm/intermediate_language_ia32.cc b/runtime/vm/intermediate_language_ia32.cc
index 5002712..965cbeb 100644
--- a/runtime/vm/intermediate_language_ia32.cc
+++ b/runtime/vm/intermediate_language_ia32.cc
@@ -3899,6 +3899,56 @@
}
+LocationSummary* DoubleTestOpInstr::MakeLocationSummary(Zone* zone,
+ bool opt) const {
+ const intptr_t kNumInputs = 1;
+ const intptr_t kNumTemps = 0;
+ LocationSummary* summary = new(zone) LocationSummary(
+ zone, kNumInputs, kNumTemps, LocationSummary::kNoCall);
+ summary->set_in(0, Location::RequiresFpuRegister());
+ summary->set_out(0, Location::RequiresRegister());
+ return summary;
+}
+
+
+void DoubleTestOpInstr::EmitNativeCode(FlowGraphCompiler* compiler) {
+ ASSERT(compiler->is_optimizing());
+ const XmmRegister value = locs()->in(0).fpu_reg();
+ const Register result = locs()->out(0).reg();
+ if (op_kind() == MethodRecognizer::kDouble_getIsNaN) {
+ Label is_nan;
+ __ LoadObject(result, Bool::True());
+ __ comisd(value, value);
+ __ j(PARITY_EVEN, &is_nan, Assembler::kNearJump);
+ __ LoadObject(result, Bool::False());
+ __ Bind(&is_nan);
+ } else {
+ ASSERT(op_kind() == MethodRecognizer::kDouble_getIsInfinite);
+ Label not_inf, done;
+ __ AddImmediate(ESP, Immediate(-kDoubleSize));
+ __ movsd(Address(ESP, 0), value);
+ __ movl(result, Address(ESP, 0));
+ // If the low word isn't zero, then it isn't infinity.
+ __ cmpl(result, Immediate(0));
+ __ j(NOT_EQUAL, ¬_inf, Assembler::kNearJump);
+ // Check the high word.
+ __ movl(result, Address(ESP, kWordSize));
+ // Mask off sign bit.
+ __ andl(result, Immediate(0x7FFFFFFF));
+ // Compare with +infinity.
+ __ cmpl(result, Immediate(0x7FF00000));
+ __ j(NOT_EQUAL, ¬_inf, Assembler::kNearJump);
+ __ LoadObject(result, Bool::True());
+ __ jmp(&done);
+
+ __ Bind(¬_inf);
+ __ LoadObject(result, Bool::False());
+ __ Bind(&done);
+ __ AddImmediate(ESP, Immediate(kDoubleSize));
+ }
+}
+
+
LocationSummary* BinaryFloat32x4OpInstr::MakeLocationSummary(Zone* zone,
bool opt) const {
const intptr_t kNumInputs = 2;
diff --git a/runtime/vm/intermediate_language_mips.cc b/runtime/vm/intermediate_language_mips.cc
index e824df1..793c1b4 100644
--- a/runtime/vm/intermediate_language_mips.cc
+++ b/runtime/vm/intermediate_language_mips.cc
@@ -3692,6 +3692,51 @@
}
+LocationSummary* DoubleTestOpInstr::MakeLocationSummary(Zone* zone,
+ bool opt) const {
+ const intptr_t kNumInputs = 1;
+ const intptr_t kNumTemps = 0;
+ LocationSummary* summary = new(zone) LocationSummary(
+ zone, kNumInputs, kNumTemps, LocationSummary::kNoCall);
+ summary->set_in(0, Location::RequiresFpuRegister());
+ summary->set_out(0, Location::RequiresRegister());
+ return summary;
+}
+
+
+void DoubleTestOpInstr::EmitNativeCode(FlowGraphCompiler* compiler) {
+ ASSERT(compiler->is_optimizing());
+ const DRegister value = locs()->in(0).fpu_reg();
+ const Register result = locs()->out(0).reg();
+ if (op_kind() == MethodRecognizer::kDouble_getIsNaN) {
+ Label is_not_nan;
+ __ LoadObject(result, Bool::False());
+ __ cund(value, value);
+ __ bc1f(&is_not_nan);
+ __ LoadObject(result, Bool::True());
+ __ Bind(&is_not_nan);
+ } else {
+ ASSERT(op_kind() == MethodRecognizer::kDouble_getIsInfinite);
+ Label not_inf, done;
+ __ mfc1(TMP, EvenFRegisterOf(value));
+ __ mfc1(result, OddFRegisterOf(value));
+ // If the low word isn't zero, then it isn't infinity.
+ __ bne(TMP, ZR, ¬_inf);
+ // Mask off the sign bit.
+ __ AndImmediate(result, result, 0x7FFFFFFF);
+ // Compare with +infinity.
+ __ BranchNotEqual(result, Immediate(0x7FF00000), ¬_inf);
+
+ __ LoadObject(result, Bool::True());
+ __ b(&done);
+
+ __ Bind(¬_inf);
+ __ LoadObject(result, Bool::False());
+ __ Bind(&done);
+ }
+}
+
+
LocationSummary* BinaryFloat32x4OpInstr::MakeLocationSummary(Zone* zone,
bool opt) const {
UNIMPLEMENTED();
@@ -4535,15 +4580,15 @@
__ Bind(&try_sqrt);
// Before calling pow, check if we could use sqrt instead of pow.
- __ LoadImmediate(result, kPosInfinity);
+ __ LoadImmediate(result, kNegInfinity);
// base == -Infinity -> call pow;
__ ceqd(base, result);
Label do_pow;
- __ b(&do_pow);
+ __ bc1t(&do_pow);
// exponent == 0.5 ?
__ LoadImmediate(result, 0.5);
- __ ceqd(base, result);
+ __ ceqd(exp, result);
__ bc1f(&do_pow);
// base == 0 -> return 0;
diff --git a/runtime/vm/intermediate_language_x64.cc b/runtime/vm/intermediate_language_x64.cc
index 6e17709..2b75b2a 100644
--- a/runtime/vm/intermediate_language_x64.cc
+++ b/runtime/vm/intermediate_language_x64.cc
@@ -3760,6 +3760,52 @@
}
+LocationSummary* DoubleTestOpInstr::MakeLocationSummary(Zone* zone,
+ bool opt) const {
+ const intptr_t kNumInputs = 1;
+ const intptr_t kNumTemps = 0;
+ LocationSummary* summary = new(zone) LocationSummary(
+ zone, kNumInputs, kNumTemps, LocationSummary::kNoCall);
+ summary->set_in(0, Location::RequiresFpuRegister());
+ summary->set_out(0, Location::RequiresRegister());
+ return summary;
+}
+
+
+void DoubleTestOpInstr::EmitNativeCode(FlowGraphCompiler* compiler) {
+ ASSERT(compiler->is_optimizing());
+ const XmmRegister value = locs()->in(0).fpu_reg();
+ const Register result = locs()->out(0).reg();
+ if (op_kind() == MethodRecognizer::kDouble_getIsNaN) {
+ Label is_nan;
+ __ LoadObject(result, Bool::True());
+ __ comisd(value, value);
+ __ j(PARITY_EVEN, &is_nan, Assembler::kNearJump);
+ __ LoadObject(result, Bool::False());
+ __ Bind(&is_nan);
+ } else {
+ ASSERT(op_kind() == MethodRecognizer::kDouble_getIsInfinite);
+ Label is_inf, done;
+ __ AddImmediate(RSP, Immediate(-kDoubleSize));
+ __ movsd(Address(RSP, 0), value);
+ __ movq(result, Address(RSP, 0));
+ // Mask off the sign.
+ __ AndImmediate(result, Immediate(0x7FFFFFFFFFFFFFFFLL));
+ // Compare with +infinity.
+ __ CompareImmediate(result, Immediate(0x7FF0000000000000LL));
+ __ j(EQUAL, &is_inf, Assembler::kNearJump);
+ __ LoadObject(result, Bool::False());
+ __ jmp(&done);
+
+ __ Bind(&is_inf);
+ __ LoadObject(result, Bool::True());
+
+ __ Bind(&done);
+ __ AddImmediate(RSP, Immediate(kDoubleSize));
+ }
+}
+
+
LocationSummary* BinaryFloat32x4OpInstr::MakeLocationSummary(Zone* zone,
bool opt) const {
const intptr_t kNumInputs = 2;
diff --git a/runtime/vm/intrinsifier_arm.cc b/runtime/vm/intrinsifier_arm.cc
index 7e9dc7c..80756ef 100644
--- a/runtime/vm/intrinsifier_arm.cc
+++ b/runtime/vm/intrinsifier_arm.cc
@@ -1422,6 +1422,31 @@
}
+void Intrinsifier::Double_getIsInfinite(Assembler* assembler) {
+ if (TargetCPUFeatures::vfp_supported()) {
+ __ ldr(R0, Address(SP, 0 * kWordSize));
+ // R1 <- value[0:31], R2 <- value[32:63]
+ __ LoadFieldFromOffset(kWord, R1, R0, Double::value_offset());
+ __ LoadFieldFromOffset(kWord, R2, R0, Double::value_offset() + kWordSize);
+
+ // If the low word isn't 0, then it isn't infinity.
+ __ cmp(R1, Operand(0));
+ __ LoadObject(R0, Bool::False(), NE);
+ __ bx(LR, NE); // Return if NE.
+
+ // Mask off the sign bit.
+ __ AndImmediate(R2, R2, 0x7FFFFFFF);
+ // Compare with +infinity.
+ __ CompareImmediate(R2, 0x7FF00000);
+ __ LoadObject(R0, Bool::False(), NE);
+ __ bx(LR, NE);
+
+ __ LoadObject(R0, Bool::True());
+ __ Ret();
+ }
+}
+
+
void Intrinsifier::Double_getIsNegative(Assembler* assembler) {
if (TargetCPUFeatures::vfp_supported()) {
Label is_false, is_true, is_zero;
diff --git a/runtime/vm/intrinsifier_arm64.cc b/runtime/vm/intrinsifier_arm64.cc
index f9cade2..050ae73 100644
--- a/runtime/vm/intrinsifier_arm64.cc
+++ b/runtime/vm/intrinsifier_arm64.cc
@@ -1507,7 +1507,6 @@
void Intrinsifier::Double_getIsNaN(Assembler* assembler) {
- Label is_true;
__ ldr(R0, Address(SP, 0 * kWordSize));
__ LoadDFieldFromOffset(V0, R0, Double::value_offset());
__ fcmpd(V0, V0);
@@ -1518,6 +1517,20 @@
}
+void Intrinsifier::Double_getIsInfinite(Assembler* assembler) {
+ __ ldr(R0, Address(SP, 0 * kWordSize));
+ __ LoadFieldFromOffset(R0, R0, Double::value_offset());
+ // Mask off the sign.
+ __ AndImmediate(R0, R0, 0x7FFFFFFFFFFFFFFFLL);
+ // Compare with +infinity.
+ __ CompareImmediate(R0, 0x7FF0000000000000LL);
+ __ LoadObject(R0, Bool::False());
+ __ LoadObject(TMP, Bool::True());
+ __ csel(R0, TMP, R0, EQ);
+ __ ret();
+}
+
+
void Intrinsifier::Double_getIsNegative(Assembler* assembler) {
const Register false_reg = R0;
const Register true_reg = R2;
diff --git a/runtime/vm/intrinsifier_ia32.cc b/runtime/vm/intrinsifier_ia32.cc
index b9ea3a1..a114996 100644
--- a/runtime/vm/intrinsifier_ia32.cc
+++ b/runtime/vm/intrinsifier_ia32.cc
@@ -1566,6 +1566,30 @@
}
+void Intrinsifier::Double_getIsInfinite(Assembler* assembler) {
+ Label not_inf;
+ __ movl(EAX, Address(ESP, +1 * kWordSize));
+ __ movl(EBX, FieldAddress(EAX, Double::value_offset()));
+
+ // If the low word isn't zero, then it isn't infinity.
+ __ cmpl(EBX, Immediate(0));
+ __ j(NOT_EQUAL, ¬_inf, Assembler::kNearJump);
+ // Check the high word.
+ __ movl(EBX, FieldAddress(EAX, Double::value_offset() + kWordSize));
+ // Mask off sign bit.
+ __ andl(EBX, Immediate(0x7FFFFFFF));
+ // Compare with +infinity.
+ __ cmpl(EBX, Immediate(0x7FF00000));
+ __ j(NOT_EQUAL, ¬_inf, Assembler::kNearJump);
+ __ LoadObject(EAX, Bool::True());
+ __ ret();
+
+ __ Bind(¬_inf);
+ __ LoadObject(EAX, Bool::False());
+ __ ret();
+}
+
+
void Intrinsifier::Double_getIsNegative(Assembler* assembler) {
Label is_false, is_true, is_zero;
__ movl(EAX, Address(ESP, +1 * kWordSize));
diff --git a/runtime/vm/intrinsifier_mips.cc b/runtime/vm/intrinsifier_mips.cc
index 748f06d..ff354af 100644
--- a/runtime/vm/intrinsifier_mips.cc
+++ b/runtime/vm/intrinsifier_mips.cc
@@ -1530,6 +1530,27 @@
}
+void Intrinsifier::Double_getIsInfinite(Assembler* assembler) {
+ Label not_inf;
+ __ lw(T0, Address(SP, 0 * kWordSize));
+ __ lw(T1, FieldAddress(T0, Double::value_offset()));
+ __ lw(T2, FieldAddress(T0, Double::value_offset() + kWordSize));
+ // If the low word isn't zero, then it isn't infinity.
+ __ bne(T1, ZR, ¬_inf);
+ // Mask off the sign bit.
+ __ AndImmediate(T2, T2, 0x7FFFFFFF);
+ // Compare with +infinity.
+ __ BranchNotEqual(T2, Immediate(0x7FF00000), ¬_inf);
+
+ __ LoadObject(V0, Bool::True());
+ __ Ret();
+
+ __ Bind(¬_inf);
+ __ LoadObject(V0, Bool::False());
+ __ Ret();
+}
+
+
void Intrinsifier::Double_getIsNegative(Assembler* assembler) {
Label is_false, is_true, is_zero;
__ lw(T0, Address(SP, 0 * kWordSize));
diff --git a/runtime/vm/intrinsifier_x64.cc b/runtime/vm/intrinsifier_x64.cc
index cdb11df..0810847 100644
--- a/runtime/vm/intrinsifier_x64.cc
+++ b/runtime/vm/intrinsifier_x64.cc
@@ -1434,6 +1434,26 @@
}
+void Intrinsifier::Double_getIsInfinite(Assembler* assembler) {
+ Label is_inf, done;
+ __ movq(RAX, Address(RSP, +1 * kWordSize));
+ __ movq(RAX, FieldAddress(RAX, Double::value_offset()));
+ // Mask off the sign.
+ __ AndImmediate(RAX, Immediate(0x7FFFFFFFFFFFFFFFLL));
+ // Compare with +infinity.
+ __ CompareImmediate(RAX, Immediate(0x7FF0000000000000LL));
+ __ j(EQUAL, &is_inf, Assembler::kNearJump);
+ __ LoadObject(RAX, Bool::False());
+ __ jmp(&done);
+
+ __ Bind(&is_inf);
+ __ LoadObject(RAX, Bool::True());
+
+ __ Bind(&done);
+ __ ret();
+}
+
+
void Intrinsifier::Double_getIsNegative(Assembler* assembler) {
Label is_false, is_true, is_zero;
__ movq(RAX, Address(RSP, +1 * kWordSize));
diff --git a/runtime/vm/isolate.cc b/runtime/vm/isolate.cc
index 7ede2f5..96af2b6 100644
--- a/runtime/vm/isolate.cc
+++ b/runtime/vm/isolate.cc
@@ -2188,7 +2188,7 @@
RawField* Isolate::GetDeoptimizingBoxedField() {
ASSERT(Thread::Current()->IsMutatorThread());
- MutexLocker ml(field_list_mutex_);
+ SafepointMutexLocker ml(field_list_mutex_);
if (boxed_field_list_ == GrowableObjectArray::null()) {
return Field::null();
}
diff --git a/runtime/vm/isolate.h b/runtime/vm/isolate.h
index 98b4188..e85d4da 100644
--- a/runtime/vm/isolate.h
+++ b/runtime/vm/isolate.h
@@ -221,7 +221,6 @@
Heap* heap() const { return heap_; }
void set_heap(Heap* value) { heap_ = value; }
- static intptr_t heap_offset() { return OFFSET_OF(Isolate, heap_); }
ObjectStore* object_store() const { return object_store_; }
void set_object_store(ObjectStore* value) { object_store_ = value; }
diff --git a/runtime/vm/kernel_binary.cc b/runtime/vm/kernel_binary.cc
index 407e1a6..6cb8d36 100644
--- a/runtime/vm/kernel_binary.cc
+++ b/runtime/vm/kernel_binary.cc
@@ -5,6 +5,7 @@
#include <map>
#include <vector>
+#include "platform/globals.h"
#include "vm/flags.h"
#include "vm/kernel.h"
#include "vm/os.h"
@@ -12,11 +13,11 @@
#if defined(DEBUG)
#define TRACE_READ_OFFSET() do { \
if (FLAG_trace_kernel_binary) \
- reader->DumpOffset(__PRETTY_FUNCTION__); \
+ reader->DumpOffset(DART_PRETTY_FUNCTION); \
} while (0)
#define TRACE_WRITE_OFFSET() do { \
if (FLAG_trace_kernel_binary) \
- writer->DumpOffset(__PRETTY_FUNCTION__); \
+ writer->DumpOffset(DART_PRETTY_FUNCTION); \
} while (0)
#else
#define TRACE_READ_OFFSET()
diff --git a/runtime/vm/kernel_to_il.cc b/runtime/vm/kernel_to_il.cc
index e3320ef..0aff92b 100644
--- a/runtime/vm/kernel_to_il.cc
+++ b/runtime/vm/kernel_to_il.cc
@@ -41,13 +41,19 @@
LocalVariable* ScopeBuilder::MakeVariable(const dart::String& name) {
return new (Z)
- LocalVariable(TokenPosition::kNoSource, name, Object::dynamic_type());
+ LocalVariable(TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
+ name,
+ Object::dynamic_type());
}
LocalVariable* ScopeBuilder::MakeVariable(const dart::String& name,
const Type& type) {
- return new (Z) LocalVariable(TokenPosition::kNoSource, name, type);
+ return new (Z) LocalVariable(TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
+ name,
+ type);
}
@@ -2503,7 +2509,10 @@
intptr_t index = stack_->definition()->temp_index();
OS::SNPrint(name, 64, ":temp%" Pd, index);
LocalVariable* variable = new (Z) LocalVariable(
- TokenPosition::kNoSource, H.DartSymbol(name), Object::dynamic_type());
+ TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
+ H.DartSymbol(name),
+ Object::dynamic_type());
// Set the index relative to the base of the expression stack including
// outgoing arguments.
variable->set_index(parsed_function_->first_stack_local_index() -
@@ -2764,7 +2773,9 @@
// create one directly.
LocalVariable* parameter =
new (Z) LocalVariable(TokenPosition::kNoSource,
- Symbols::TempParam(), Object::dynamic_type());
+ TokenPosition::kNoSource,
+ Symbols::TempParam(),
+ Object::dynamic_type());
parameter->set_index(parameter_index);
// Mark the stack variable so it will be ignored by the code for
// try/catch.
diff --git a/runtime/vm/method_recognizer.h b/runtime/vm/method_recognizer.h
index 651ee3c..04f49ed 100644
--- a/runtime/vm/method_recognizer.h
+++ b/runtime/vm/method_recognizer.h
@@ -156,6 +156,7 @@
V(_Double, *, Double_mul, Double, 0x23d068d8) \
V(_Double, /, Double_div, Double, 0x48bac1dc) \
V(_Double, get:isNaN, Double_getIsNaN, Bool, 0x0af8ebeb) \
+ V(_Double, get:isInfinite, Double_getIsInfinite, Bool, 0x0f79e289) \
V(_Double, get:isNegative, Double_getIsNegative, Bool, 0x3a58ff36) \
V(_Double, _mulFromInteger, Double_mulFromInteger, Double, 0x330e9a36) \
V(_Double, .fromInteger, DoubleFromInteger, Double, 0x7ef45843) \
diff --git a/runtime/vm/object.cc b/runtime/vm/object.cc
index d958643..58213ac 100644
--- a/runtime/vm/object.cc
+++ b/runtime/vm/object.cc
@@ -14811,6 +14811,21 @@
}
+TokenPosition ContextScope::DeclarationTokenIndexAt(
+ intptr_t scope_index) const {
+ return TokenPosition(
+ Smi::Value(VariableDescAddr(scope_index)->declaration_token_pos));
+}
+
+
+void ContextScope::SetDeclarationTokenIndexAt(
+ intptr_t scope_index,
+ TokenPosition declaration_token_pos) const {
+ StoreSmi(&VariableDescAddr(scope_index)->declaration_token_pos,
+ Smi::New(declaration_token_pos.value()));
+}
+
+
RawString* ContextScope::NameAt(intptr_t scope_index) const {
return VariableDescAddr(scope_index)->name;
}
diff --git a/runtime/vm/object.h b/runtime/vm/object.h
index 8358380..5f8ddbf 100644
--- a/runtime/vm/object.h
+++ b/runtime/vm/object.h
@@ -5151,6 +5151,10 @@
TokenPosition TokenIndexAt(intptr_t scope_index) const;
void SetTokenIndexAt(intptr_t scope_index, TokenPosition token_pos) const;
+ TokenPosition DeclarationTokenIndexAt(intptr_t scope_index) const;
+ void SetDeclarationTokenIndexAt(intptr_t scope_index,
+ TokenPosition declaration_token_pos) const;
+
RawString* NameAt(intptr_t scope_index) const;
void SetNameAt(intptr_t scope_index, const String& name) const;
diff --git a/runtime/vm/object_service.cc b/runtime/vm/object_service.cc
index 578d97a..b1a87ab 100644
--- a/runtime/vm/object_service.cc
+++ b/runtime/vm/object_service.cc
@@ -736,8 +736,9 @@
JSONObject var(&members);
var.AddProperty("name", var_name.ToCString());
var.AddProperty("index", static_cast<intptr_t>(info.index()));
- var.AddProperty("beginPos", info.begin_pos);
- var.AddProperty("endPos", info.end_pos);
+ var.AddProperty("declarationTokenPos", info.declaration_pos);
+ var.AddProperty("scopeStartTokenPos", info.begin_pos);
+ var.AddProperty("scopeEndTokenPos", info.end_pos);
var.AddProperty("scopeId", static_cast<intptr_t>(info.scope_id));
var.AddProperty("kind", KindToCString(info.kind()));
}
diff --git a/runtime/vm/object_test.cc b/runtime/vm/object_test.cc
index d4594d6..86852f4 100644
--- a/runtime/vm/object_test.cc
+++ b/runtime/vm/object_test.cc
@@ -2535,17 +2535,26 @@
const Type& dynamic_type = Type::ZoneHandle(Type::DynamicType());
const String& a = String::ZoneHandle(Symbols::New(thread, "a"));
LocalVariable* var_a =
- new LocalVariable(TokenPosition::kNoSource, a, dynamic_type);
+ new LocalVariable(TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
+ a,
+ dynamic_type);
parent_scope->AddVariable(var_a);
const String& b = String::ZoneHandle(Symbols::New(thread, "b"));
LocalVariable* var_b =
- new LocalVariable(TokenPosition::kNoSource, b, dynamic_type);
+ new LocalVariable(TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
+ b,
+ dynamic_type);
local_scope->AddVariable(var_b);
const String& c = String::ZoneHandle(Symbols::New(thread, "c"));
LocalVariable* var_c =
- new LocalVariable(TokenPosition::kNoSource, c, dynamic_type);
+ new LocalVariable(TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
+ c,
+ dynamic_type);
parent_scope->AddVariable(var_c);
bool test_only = false; // Please, insert alias.
diff --git a/runtime/vm/parser.cc b/runtime/vm/parser.cc
index b41e0ef..868c27b 100644
--- a/runtime/vm/parser.cc
+++ b/runtime/vm/parser.cc
@@ -244,6 +244,7 @@
if (!has_expression_temp_var()) {
LocalVariable* temp =
new (Z) LocalVariable(function_.token_pos(),
+ function_.token_pos(),
Symbols::ExprTemp(),
Object::dynamic_type());
ASSERT(temp != NULL);
@@ -258,6 +259,7 @@
if (!has_finally_return_temp_var()) {
LocalVariable* temp = new(Z) LocalVariable(
function_.token_pos(),
+ function_.token_pos(),
Symbols::FinallyRetVal(),
Object::dynamic_type());
ASSERT(temp != NULL);
@@ -3114,7 +3116,13 @@
const Function& redirect_ctor = Function::ZoneHandle(Z,
cls.LookupConstructor(ctor_name));
if (redirect_ctor.IsNull()) {
- ReportError(call_pos, "constructor '%s' not found", ctor_name.ToCString());
+ ReportError(call_pos, "constructor '%s' not found",
+ String::Handle(Z, redirect_ctor.UserVisibleName()).ToCString());
+ }
+ if (current_function().is_const() && !redirect_ctor.is_const()) {
+ ReportError(call_pos,
+ "redirection constructor '%s' must be const",
+ String::Handle(Z, redirect_ctor.UserVisibleName()).ToCString());
}
String& error_message = String::Handle(Z);
if (!redirect_ctor.AreValidArguments(arguments->length(),
@@ -3122,7 +3130,7 @@
&error_message)) {
ReportError(call_pos,
"invalid arguments passed to constructor '%s': %s",
- ctor_name.ToCString(),
+ String::Handle(Z, redirect_ctor.UserVisibleName()).ToCString(),
error_message.ToCString());
}
current_block_->statements->Add(
@@ -3138,6 +3146,7 @@
LocalVariable* receiver = new LocalVariable(
TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
Symbols::This(),
*ReceiverType(current_class()));
current_block_->scope->InsertParameterAt(0, receiver);
@@ -3186,6 +3195,7 @@
for (int i = 1; i < func.NumParameters(); i++) {
LocalVariable* param = new LocalVariable(
TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
String::ZoneHandle(Z, func.ParameterNameAt(i)),
Object::dynamic_type());
current_block_->scope->InsertParameterAt(i, param);
@@ -7102,11 +7112,13 @@
// var :await_ctx_var;
LocalVariable* await_jump_var = new (Z) LocalVariable(
TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
Symbols::AwaitJumpVar(),
Object::dynamic_type());
current_block_->scope->AddVariable(await_jump_var);
LocalVariable* await_ctx_var = new (Z) LocalVariable(
TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
Symbols::AwaitContextVar(),
Object::dynamic_type());
current_block_->scope->AddVariable(await_ctx_var);
@@ -7121,21 +7133,25 @@
// var :async_completer;
LocalVariable* async_op_var = new(Z) LocalVariable(
TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
Symbols::AsyncOperation(),
Object::dynamic_type());
current_block_->scope->AddVariable(async_op_var);
LocalVariable* async_then_callback_var = new(Z) LocalVariable(
TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
Symbols::AsyncThenCallback(),
Object::dynamic_type());
current_block_->scope->AddVariable(async_then_callback_var);
LocalVariable* async_catch_error_callback_var = new(Z) LocalVariable(
TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
Symbols::AsyncCatchErrorCallback(),
Object::dynamic_type());
current_block_->scope->AddVariable(async_catch_error_callback_var);
LocalVariable* async_completer = new(Z) LocalVariable(
TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
Symbols::AsyncCompleter(),
Object::dynamic_type());
current_block_->scope->AddVariable(async_completer);
@@ -7155,21 +7171,25 @@
// the body of the async* function. They are used by the await operator.
LocalVariable* controller_var = new(Z) LocalVariable(
TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
Symbols::Controller(),
Object::dynamic_type());
current_block_->scope->AddVariable(controller_var);
LocalVariable* async_op_var = new(Z) LocalVariable(
TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
Symbols::AsyncOperation(),
Object::dynamic_type());
current_block_->scope->AddVariable(async_op_var);
LocalVariable* async_then_callback_var = new(Z) LocalVariable(
TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
Symbols::AsyncThenCallback(),
Object::dynamic_type());
current_block_->scope->AddVariable(async_then_callback_var);
LocalVariable* async_catch_error_callback_var = new(Z) LocalVariable(
TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
Symbols::AsyncCatchErrorCallback(),
Object::dynamic_type());
current_block_->scope->AddVariable(async_catch_error_callback_var);
@@ -7658,7 +7678,10 @@
ASSERT(!is_top_level_ || param_desc.type->IsResolved());
const String* name = param_desc.name;
LocalVariable* parameter = new(Z) LocalVariable(
- param_desc.name_pos, *name, *param_desc.type);
+ param_desc.name_pos,
+ param_desc.name_pos,
+ *name,
+ *param_desc.type);
if (!scope->InsertParameterAt(i, parameter)) {
ReportError(param_desc.name_pos,
"name '%s' already exists in scope",
@@ -7770,7 +7793,10 @@
is_const, kConsumeCascades, await_preamble);
const TokenPosition expr_end_pos = TokenPos();
variable = new(Z) LocalVariable(
- expr_end_pos, ident, type);
+ ident_pos,
+ expr_end_pos,
+ ident,
+ type);
initialization = new(Z) StoreLocalNode(
assign_pos, variable, expr);
if (is_const) {
@@ -7783,7 +7809,10 @@
} else {
// Initialize variable with null.
variable = new(Z) LocalVariable(
- assign_pos, ident, type);
+ ident_pos,
+ assign_pos,
+ ident,
+ type);
AstNode* null_expr = new(Z) LiteralNode(ident_pos, Object::null_instance());
initialization = new(Z) StoreLocalNode(
ident_pos, variable, null_expr);
@@ -7920,6 +7949,7 @@
result_type = Type::DynamicType();
const TokenPosition function_pos = TokenPos();
+ TokenPosition function_name_pos = TokenPosition::kNoSource;
TokenPosition metadata_pos = TokenPosition::kNoSource;
if (is_literal) {
ASSERT(CurrentToken() == Token::kLPAREN || CurrentToken() == Token::kLT);
@@ -7934,7 +7964,7 @@
// referring to a not yet declared function type parameter.
result_type = ParseType(ClassFinalizer::kDoNotResolve);
}
- const TokenPosition name_pos = TokenPos();
+ function_name_pos = TokenPos();
variable_name = ExpectIdentifier("function name expected");
function_name = variable_name;
@@ -7947,7 +7977,7 @@
ASSERT(!script_.IsNull());
intptr_t line_number;
script_.GetTokenLocation(previous_pos, &line_number, NULL);
- ReportError(name_pos,
+ ReportError(function_name_pos,
"identifier '%s' previously used in line %" Pd "",
function_name->ToCString(),
line_number);
@@ -8026,7 +8056,8 @@
// Add the function variable to the scope before parsing the function in
// order to allow self reference from inside the function.
- function_variable = new(Z) LocalVariable(function_pos,
+ function_variable = new(Z) LocalVariable(function_name_pos,
+ function_pos,
*variable_name,
function_type);
function_variable->set_is_final();
@@ -8838,7 +8869,7 @@
expr_pos));
temp_var_type.SetIsFinalized();
LocalVariable* temp_variable = new(Z) LocalVariable(
- expr_pos, Symbols::SwitchExpr(), temp_var_type);
+ expr_pos, expr_pos, Symbols::SwitchExpr(), temp_var_type);
current_block_->scope->AddVariable(temp_variable);
AstNode* save_switch_expr = new(Z) StoreLocalNode(
expr_pos, temp_variable, switch_expr);
@@ -9128,7 +9159,7 @@
ctor_args);
const AbstractType& iterator_type = Object::dynamic_type();
LocalVariable* iterator_var = new(Z) LocalVariable(
- stream_expr_pos, Symbols::ForInIter(), iterator_type);
+ stream_expr_pos, stream_expr_pos, Symbols::ForInIter(), iterator_type);
current_block_->scope->AddVariable(iterator_var);
AstNode* iterator_init =
new(Z) StoreLocalNode(stream_expr_pos, iterator_var, ctor_call);
@@ -9213,6 +9244,7 @@
// loop block, so it gets put in the loop context level.
LocalVariable* loop_var =
new(Z) LocalVariable(loop_var_assignment_pos,
+ loop_var_assignment_pos,
*loop_var_name,
loop_var_type);;
if (loop_var_is_final) {
@@ -9388,6 +9420,7 @@
loop_var_type = ParseConstFinalVarOrType(
I->type_checks() ? ClassFinalizer::kCanonicalize :
ClassFinalizer::kIgnore);
+ loop_var_pos = TokenPos();
loop_var_name = ExpectIdentifier("variable name expected");
}
ExpectToken(Token::kIN);
@@ -9411,6 +9444,7 @@
// until the loop variable is assigned to.
const AbstractType& iterator_type = Object::dynamic_type();
LocalVariable* iterator_var = new(Z) LocalVariable(
+ collection_pos,
collection_pos, Symbols::ForInIter(), iterator_type);
current_block_->scope->AddVariable(iterator_var);
@@ -9448,7 +9482,8 @@
// The for loop variable is new for each iteration.
// Create a variable and add it to the loop body scope.
LocalVariable* loop_var =
- new(Z) LocalVariable(loop_var_assignment_pos,
+ new(Z) LocalVariable(loop_var_pos,
+ loop_var_assignment_pos,
*loop_var_name,
loop_var_type);;
if (loop_var_is_final) {
@@ -9615,6 +9650,7 @@
if (exception_param->name != NULL) {
LocalVariable* var = new(Z) LocalVariable(
exception_param->token_pos,
+ exception_param->token_pos,
*exception_param->name,
*exception_param->type);
var->set_is_final();
@@ -9625,6 +9661,7 @@
if (stack_trace_param->name != NULL) {
LocalVariable* var = new(Z) LocalVariable(
stack_trace_param->token_pos,
+ stack_trace_param->token_pos,
*stack_trace_param->name,
*stack_trace_param->type);
var->set_is_final();
@@ -10034,6 +10071,7 @@
last_used_try_index_ - 1));
LocalVariable* async_saved_try_ctx = new (Z) LocalVariable(
TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
async_saved_try_ctx_name,
Object::dynamic_type());
ASSERT(async_temp_scope_ != NULL);
@@ -10075,6 +10113,7 @@
if (*context_var == NULL) {
*context_var = new(Z) LocalVariable(
TokenPos(),
+ TokenPos(),
Symbols::SavedTryContextVar(),
Object::dynamic_type());
try_scope->AddVariable(*context_var);
@@ -10083,6 +10122,7 @@
if (*exception_var == NULL) {
*exception_var = new(Z) LocalVariable(
TokenPos(),
+ TokenPos(),
Symbols::ExceptionVar(),
Object::dynamic_type());
try_scope->AddVariable(*exception_var);
@@ -10091,6 +10131,7 @@
if (*stack_trace_var == NULL) {
*stack_trace_var = new(Z) LocalVariable(
TokenPos(),
+ TokenPos(),
Symbols::StackTraceVar(),
Object::dynamic_type());
try_scope->AddVariable(*stack_trace_var);
@@ -10101,6 +10142,7 @@
if (*saved_exception_var == NULL) {
*saved_exception_var = new(Z) LocalVariable(
TokenPos(),
+ TokenPos(),
Symbols::SavedExceptionVar(),
Object::dynamic_type());
try_scope->AddVariable(*saved_exception_var);
@@ -10110,6 +10152,7 @@
if (*saved_stack_trace_var == NULL) {
*saved_stack_trace_var = new(Z) LocalVariable(
TokenPos(),
+ TokenPos(),
Symbols::SavedStackTraceVar(),
Object::dynamic_type());
try_scope->AddVariable(*saved_stack_trace_var);
@@ -11090,6 +11133,7 @@
OS::SNPrint(name, 64, ":%s%" Pd "", s, token_pos.value());
LocalVariable* temp = new(Z) LocalVariable(
token_pos,
+ token_pos,
String::ZoneHandle(Z, Symbols::New(T, name)),
Object::dynamic_type());
temp->set_is_final();
diff --git a/runtime/vm/parser.h b/runtime/vm/parser.h
index 0756cba..0b37e12 100644
--- a/runtime/vm/parser.h
+++ b/runtime/vm/parser.h
@@ -115,6 +115,7 @@
// Every function has a local variable for the current context.
LocalVariable* temp = new(zone()) LocalVariable(
function.token_pos(),
+ function.token_pos(),
Symbols::CurrentContextVar(),
Object::dynamic_type());
ASSERT(temp != NULL);
diff --git a/runtime/vm/precompiler.cc b/runtime/vm/precompiler.cc
index 22348eb..de1f353 100644
--- a/runtime/vm/precompiler.cc
+++ b/runtime/vm/precompiler.cc
@@ -1721,8 +1721,7 @@
bool top_level = cls.IsTopLevel();
if (top_level) {
name = field.DictionaryName();
- bool removed = lib.RemoveObject(field, name);
- ASSERT(removed);
+ lib.RemoveObject(field, name);
}
dropped_field_count_++;
if (FLAG_trace_precompiler) {
diff --git a/runtime/vm/raw_object.h b/runtime/vm/raw_object.h
index 4f0a768f..dcf3992 100644
--- a/runtime/vm/raw_object.h
+++ b/runtime/vm/raw_object.h
@@ -1355,6 +1355,7 @@
struct VarInfo {
int32_t index_kind; // Bitfield for slot index on stack or in context,
// and Entry kind of type VarInfoKind.
+ TokenPosition declaration_pos; // Token position of declaration.
TokenPosition begin_pos; // Token position of scope start.
TokenPosition end_pos; // Token position of scope end.
int16_t scope_id; // Scope to which the variable belongs.
@@ -1457,6 +1458,7 @@
// TODO(iposva): Switch to conventional enum offset based structure to avoid
// alignment mishaps.
struct VariableDesc {
+ RawSmi* declaration_token_pos;
RawSmi* token_pos;
RawString* name;
RawBool* is_final;
diff --git a/runtime/vm/raw_object_snapshot.cc b/runtime/vm/raw_object_snapshot.cc
index c8ea0f2..91a752e 100644
--- a/runtime/vm/raw_object_snapshot.cc
+++ b/runtime/vm/raw_object_snapshot.cc
@@ -1485,6 +1485,7 @@
// Create a descriptor for 'this' variable.
context_scope.SetTokenIndexAt(0, TokenPosition::kMinSource);
+ context_scope.SetDeclarationTokenIndexAt(0, TokenPosition::kMinSource);
context_scope.SetNameAt(0, Symbols::This());
context_scope.SetIsFinalAt(0, true);
context_scope.SetIsConstAt(0, false);
diff --git a/runtime/vm/regexp_assembler_ir.cc b/runtime/vm/regexp_assembler_ir.cc
index aac090e..24a1468 100644
--- a/runtime/vm/regexp_assembler_ir.cc
+++ b/runtime/vm/regexp_assembler_ir.cc
@@ -385,7 +385,10 @@
LocalVariable* IRRegExpMacroAssembler::Parameter(const String& name,
intptr_t index) const {
LocalVariable* local = new(Z) LocalVariable(
- TokenPosition::kNoSource, name, Object::dynamic_type());
+ TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
+ name,
+ Object::dynamic_type());
intptr_t param_frame_index = kParamEndSlotFromFp + kParamCount - index;
local->set_index(param_frame_index);
@@ -396,7 +399,10 @@
LocalVariable* IRRegExpMacroAssembler::Local(const String& name) {
LocalVariable* local = new(Z) LocalVariable(
- TokenPosition::kNoSource, name, Object::dynamic_type());
+ TokenPosition::kNoSource,
+ TokenPosition::kNoSource,
+ name,
+ Object::dynamic_type());
local->set_index(GetNextLocalIndex());
return local;
diff --git a/runtime/vm/scavenger.cc b/runtime/vm/scavenger.cc
index 5031909..e5e21e1 100644
--- a/runtime/vm/scavenger.cc
+++ b/runtime/vm/scavenger.cc
@@ -347,7 +347,7 @@
(FLAG_new_gen_growth_factor * FLAG_new_gen_growth_factor);
to_ = SemiSpace::New(initial_semi_capacity_in_words);
if (to_ == NULL) {
- FATAL("Out of memory.\n");
+ OUT_OF_MEMORY();
}
// Setup local fields.
top_ = FirstObjectStart();
@@ -393,7 +393,7 @@
if (to_ == NULL) {
// TODO(koda): We could try to recover (collect old space, wait for another
// isolate to finish scavenge, etc.).
- FATAL("Out of memory.\n");
+ OUT_OF_MEMORY();
}
UpdateMaxHeapCapacity();
top_ = FirstObjectStart();
diff --git a/runtime/vm/scopes.cc b/runtime/vm/scopes.cc
index 9acac1f..834ad1b 100644
--- a/runtime/vm/scopes.cc
+++ b/runtime/vm/scopes.cc
@@ -288,6 +288,7 @@
desc.name = &name;
desc.info.set_kind(kind);
desc.info.scope_id = context_scope.ContextLevelAt(i);
+ desc.info.declaration_pos = context_scope.DeclarationTokenIndexAt(i);
desc.info.begin_pos = begin_token_pos();
desc.info.end_pos = end_token_pos();
ASSERT(desc.info.begin_pos <= desc.info.end_pos);
@@ -336,6 +337,7 @@
desc.name = &var->name();
desc.info.set_kind(RawLocalVarDescriptors::kSavedCurrentContext);
desc.info.scope_id = 0;
+ desc.info.declaration_pos = TokenPosition::kMinSource;
desc.info.begin_pos = TokenPosition::kMinSource;
desc.info.end_pos = TokenPosition::kMinSource;
desc.info.set_index(var->index());
@@ -353,6 +355,7 @@
desc.info.set_kind(RawLocalVarDescriptors::kStackVar);
desc.info.scope_id = *scope_id;
}
+ desc.info.declaration_pos = var->declaration_token_pos();
desc.info.begin_pos = var->token_pos();
desc.info.end_pos = var->owner()->end_token_pos();
desc.info.set_index(var->index());
@@ -551,6 +554,8 @@
// Preserve the aliases of captured variables belonging to outer scopes.
if (variable->owner()->function_level() != 1) {
context_scope.SetTokenIndexAt(captured_idx, variable->token_pos());
+ context_scope.SetDeclarationTokenIndexAt(
+ captured_idx, variable->declaration_token_pos());
context_scope.SetNameAt(captured_idx, variable->name());
context_scope.SetIsFinalAt(captured_idx, variable->is_final());
context_scope.SetIsConstAt(captured_idx, variable->IsConst());
@@ -582,13 +587,17 @@
for (int i = 0; i < context_scope.num_variables(); i++) {
LocalVariable* variable;
if (context_scope.IsConstAt(i)) {
- variable = new LocalVariable(context_scope.TokenIndexAt(i),
+ variable = new LocalVariable(
+ context_scope.DeclarationTokenIndexAt(i),
+ context_scope.TokenIndexAt(i),
String::ZoneHandle(context_scope.NameAt(i)),
Object::dynamic_type());
variable->SetConstValue(
Instance::ZoneHandle(context_scope.ConstValueAt(i)));
} else {
- variable = new LocalVariable(context_scope.TokenIndexAt(i),
+ variable = new LocalVariable(
+ context_scope.DeclarationTokenIndexAt(i),
+ context_scope.TokenIndexAt(i),
String::ZoneHandle(context_scope.NameAt(i)),
AbstractType::ZoneHandle(context_scope.TypeAt(i)));
}
@@ -640,6 +649,7 @@
// Create a descriptor for 'this' variable.
context_scope.SetTokenIndexAt(0, func.token_pos());
+ context_scope.SetDeclarationTokenIndexAt(0, func.token_pos());
context_scope.SetNameAt(0, Symbols::This());
context_scope.SetIsFinalAt(0, true);
context_scope.SetIsConstAt(0, false);
diff --git a/runtime/vm/scopes.h b/runtime/vm/scopes.h
index 9b1877e..c3b7611 100644
--- a/runtime/vm/scopes.h
+++ b/runtime/vm/scopes.h
@@ -21,10 +21,12 @@
class LocalVariable : public ZoneAllocated {
public:
- LocalVariable(TokenPosition token_pos,
+ LocalVariable(TokenPosition declaration_pos,
+ TokenPosition token_pos,
const String& name,
const AbstractType& type)
- : token_pos_(token_pos),
+ : declaration_pos_(declaration_pos),
+ token_pos_(token_pos),
name_(name),
owner_(NULL),
type_(type),
@@ -41,6 +43,7 @@
}
TokenPosition token_pos() const { return token_pos_; }
+ TokenPosition declaration_token_pos() const { return declaration_pos_; }
const String& name() const { return name_; }
LocalScope* owner() const { return owner_; }
void set_owner(LocalScope* owner) {
@@ -117,6 +120,7 @@
private:
static const int kUninitializedIndex = INT_MIN;
+ const TokenPosition declaration_pos_;
const TokenPosition token_pos_;
const String& name_;
LocalScope* owner_; // Local scope declaring this variable.
diff --git a/runtime/vm/scopes_test.cc b/runtime/vm/scopes_test.cc
index 807f9f9..fb6e438 100644
--- a/runtime/vm/scopes_test.cc
+++ b/runtime/vm/scopes_test.cc
@@ -14,15 +14,19 @@
const Type& dynamic_type = Type::ZoneHandle(Type::DynamicType());
const String& a = String::ZoneHandle(Symbols::New(thread, "a"));
LocalVariable* var_a =
- new LocalVariable(TokenPosition::kNoSource, a, dynamic_type);
+ new LocalVariable(TokenPosition::kNoSource,
+ TokenPosition::kNoSource, a, dynamic_type);
LocalVariable* inner_var_a =
- new LocalVariable(TokenPosition::kNoSource, a, dynamic_type);
+ new LocalVariable(TokenPosition::kNoSource,
+ TokenPosition::kNoSource, a, dynamic_type);
const String& b = String::ZoneHandle(Symbols::New(thread, "b"));
LocalVariable* var_b =
- new LocalVariable(TokenPosition::kNoSource, b, dynamic_type);
+ new LocalVariable(TokenPosition::kNoSource,
+ TokenPosition::kNoSource, b, dynamic_type);
const String& c = String::ZoneHandle(Symbols::New(thread, "c"));
LocalVariable* var_c =
- new LocalVariable(TokenPosition::kNoSource, c, dynamic_type);
+ new LocalVariable(TokenPosition::kNoSource,
+ TokenPosition::kNoSource, c, dynamic_type);
const String& L = String::ZoneHandle(Symbols::New(thread, "L"));
SourceLabel* label_L =
new SourceLabel(TokenPosition::kNoSource, L, SourceLabel::kFor);
diff --git a/runtime/vm/service.cc b/runtime/vm/service.cc
index abd4271..c01256e 100644
--- a/runtime/vm/service.cc
+++ b/runtime/vm/service.cc
@@ -222,6 +222,9 @@
static uint8_t* allocator(uint8_t* ptr, intptr_t old_size, intptr_t new_size) {
void* new_ptr = realloc(reinterpret_cast<void*>(ptr), new_size);
+ if (new_ptr == NULL) {
+ OUT_OF_MEMORY();
+ }
return reinterpret_cast<uint8_t*>(new_ptr);
}
@@ -1038,6 +1041,9 @@
const intptr_t total_bytes = sizeof(uint64_t) + metadata_size + data_size;
uint8_t* message = static_cast<uint8_t*>(malloc(total_bytes));
+ if (message == NULL) {
+ OUT_OF_MEMORY();
+ }
intptr_t offset = 0;
// Metadata size.
diff --git a/runtime/vm/service/service.md b/runtime/vm/service/service.md
index 7aab061..7975456 100644
--- a/runtime/vm/service/service.md
+++ b/runtime/vm/service/service.md
@@ -895,6 +895,15 @@
class BoundVariable {
string name;
@Instance|Sentinel value;
+
+ // The token position where this variable was declared.
+ int declarationTokenPos;
+
+ // The first token position where this variable is visible to the scope.
+ int scopeStartTokenPos;
+
+ // The last token position where this variable is visible to the scope.
+ int scopeEndTokenPos;
}
```
@@ -2528,4 +2537,6 @@
3.3 | Pause event now indicates if the isolate is paused at an await, yield, or yield* suspension point via the 'atAsyncSuspension' field. Resume command now supports the step parameter 'OverAsyncSuspension'. A Breakpoint added synthetically by an 'OverAsyncSuspension' resume command identifies itself as such via the 'isSyntheticAsyncContinuation' field.
3.4 | Add the superType and mixin fields to Class. Added new pause event 'None'.
3.5 | Add the error field to SourceReportRange. Clarify definition of token position. Add "Isolate must be paused" error code.
+3.6 (unreleased) | Add 'scopeStartTokenPos', 'scopeEndTokenPos', and 'declarationTokenPos' to BoundVariable.
+
[discuss-list]: https://groups.google.com/a/dartlang.org/forum/#!forum/observatory-discuss
diff --git a/runtime/vm/simulator_dbc.cc b/runtime/vm/simulator_dbc.cc
index 6c7112e..c3998af 100644
--- a/runtime/vm/simulator_dbc.cc
+++ b/runtime/vm/simulator_dbc.cc
@@ -37,6 +37,8 @@
DEFINE_FLAG(uint64_t, stop_sim_at, ULLONG_MAX,
"Instruction address or instruction count to stop simulator at.");
+#define LIKELY(cond) __builtin_expect((cond), 1)
+
// SimulatorSetjmpBuffer are linked together, and the last created one
// is referenced by the Simulator. When an exception is thrown, the exception
// runtime looks at where to jump and finds the corresponding
@@ -239,6 +241,202 @@
return false;
}
+ static bool Double_getIsNan(Thread* thread,
+ RawObject** FP,
+ RawObject** result) {
+ RawObject** args = FrameArguments(FP, 1);
+ RawDouble* d = static_cast<RawDouble*>(args[0]);
+ *result = isnan(d->ptr()->value_)
+ ? Bool::True().raw()
+ : Bool::False().raw();
+ return true;
+ }
+
+ static bool Double_getIsInfinite(Thread* thread,
+ RawObject** FP,
+ RawObject** result) {
+ RawObject** args = FrameArguments(FP, 1);
+ RawDouble* d = static_cast<RawDouble*>(args[0]);
+ *result = isinf(d->ptr()->value_)
+ ? Bool::True().raw()
+ : Bool::False().raw();
+ return true;
+ }
+
+ static bool ObjectEquals(Thread* thread,
+ RawObject** FP,
+ RawObject** result) {
+ RawObject** args = FrameArguments(FP, 2);
+ *result = args[0] == args[1] ? Bool::True().raw() : Bool::False().raw();
+ return true;
+ }
+
+ static bool ObjectRuntimeType(Thread* thread,
+ RawObject** FP,
+ RawObject** result) {
+ RawObject** args = FrameArguments(FP, 1);
+ const intptr_t cid = GetClassId(args[0]);
+ if (cid == kClosureCid) {
+ return false;
+ }
+ RawClass* cls = thread->isolate()->class_table()->At(cid);
+ if (cls->ptr()->num_type_arguments_ != 0) {
+ return false;
+ }
+ RawType* typ = cls->ptr()->canonical_type_;
+ if (typ == Object::null()) {
+ return false;
+ }
+ *result = static_cast<RawObject*>(typ);
+ return true;
+ }
+
+ static bool GetDoubleOperands(RawObject** args, double* d1, double* d2) {
+ RawObject* obj2 = args[1];
+ if (!obj2->IsHeapObject()) {
+ *d2 = static_cast<double>(
+ reinterpret_cast<intptr_t>(obj2) >> kSmiTagSize);
+ } else if (obj2->GetClassId() == kDoubleCid) {
+ RawDouble* obj2d = static_cast<RawDouble*>(obj2);
+ *d2 = obj2d->ptr()->value_;
+ } else {
+ return false;
+ }
+ RawDouble* obj1 = static_cast<RawDouble*>(args[0]);
+ *d1 = obj1->ptr()->value_;
+ return true;
+ }
+
+ static RawObject* AllocateDouble(Thread* thread, double value) {
+ const intptr_t instance_size = Double::InstanceSize();
+ const uword start =
+ thread->heap()->new_space()->TryAllocate(instance_size);
+ if (LIKELY(start != 0)) {
+ uword tags = 0;
+ tags = RawObject::ClassIdTag::update(kDoubleCid, tags);
+ tags = RawObject::SizeTag::update(instance_size, tags);
+ *reinterpret_cast<uword*>(start + Double::tags_offset()) = tags;
+ *reinterpret_cast<double*>(start + Double::value_offset()) = value;
+ return reinterpret_cast<RawObject*>(start + kHeapObjectTag);
+ }
+ return NULL;
+ }
+
+ static bool Double_add(Thread* thread,
+ RawObject** FP,
+ RawObject** result) {
+ double d1, d2;
+ if (!GetDoubleOperands(FrameArguments(FP, 2), &d1, &d2)) {
+ return false;
+ }
+ RawObject* new_double = AllocateDouble(thread, d1 + d2);
+ if (new_double != NULL) {
+ *result = new_double;
+ return true;
+ }
+ return false;
+ }
+
+ static bool Double_mul(Thread* thread,
+ RawObject** FP,
+ RawObject** result) {
+ double d1, d2;
+ if (!GetDoubleOperands(FrameArguments(FP, 2), &d1, &d2)) {
+ return false;
+ }
+ RawObject* new_double = AllocateDouble(thread, d1 * d2);
+ if (new_double != NULL) {
+ *result = new_double;
+ return true;
+ }
+ return false;
+ }
+
+ static bool Double_sub(Thread* thread,
+ RawObject** FP,
+ RawObject** result) {
+ double d1, d2;
+ if (!GetDoubleOperands(FrameArguments(FP, 2), &d1, &d2)) {
+ return false;
+ }
+ RawObject* new_double = AllocateDouble(thread, d1 - d2);
+ if (new_double != NULL) {
+ *result = new_double;
+ return true;
+ }
+ return false;
+ }
+
+ static bool Double_div(Thread* thread,
+ RawObject** FP,
+ RawObject** result) {
+ double d1, d2;
+ if (!GetDoubleOperands(FrameArguments(FP, 2), &d1, &d2)) {
+ return false;
+ }
+ RawObject* new_double = AllocateDouble(thread, d1 / d2);
+ if (new_double != NULL) {
+ *result = new_double;
+ return true;
+ }
+ return false;
+ }
+
+ static bool Double_greaterThan(Thread* thread,
+ RawObject** FP,
+ RawObject** result) {
+ double d1, d2;
+ if (!GetDoubleOperands(FrameArguments(FP, 2), &d1, &d2)) {
+ return false;
+ }
+ *result = d1 > d2 ? Bool::True().raw() : Bool::False().raw();
+ return true;
+ }
+
+ static bool Double_greaterEqualThan(Thread* thread,
+ RawObject** FP,
+ RawObject** result) {
+ double d1, d2;
+ if (!GetDoubleOperands(FrameArguments(FP, 2), &d1, &d2)) {
+ return false;
+ }
+ *result = d1 >= d2 ? Bool::True().raw() : Bool::False().raw();
+ return true;
+ }
+
+ static bool Double_lessThan(Thread* thread,
+ RawObject** FP,
+ RawObject** result) {
+ double d1, d2;
+ if (!GetDoubleOperands(FrameArguments(FP, 2), &d1, &d2)) {
+ return false;
+ }
+ *result = d1 < d2 ? Bool::True().raw() : Bool::False().raw();
+ return true;
+ }
+
+ static bool Double_equal(Thread* thread,
+ RawObject** FP,
+ RawObject** result) {
+ double d1, d2;
+ if (!GetDoubleOperands(FrameArguments(FP, 2), &d1, &d2)) {
+ return false;
+ }
+ *result = d1 == d2 ? Bool::True().raw() : Bool::False().raw();
+ return true;
+ }
+
+ static bool Double_lessEqualThan(Thread* thread,
+ RawObject** FP,
+ RawObject** result) {
+ double d1, d2;
+ if (!GetDoubleOperands(FrameArguments(FP, 2), &d1, &d2)) {
+ return false;
+ }
+ *result = d1 <= d2 ? Bool::True().raw() : Bool::False().raw();
+ return true;
+ }
+
DART_FORCE_INLINE static RawCode* FrameCode(RawObject** FP) {
ASSERT(GetClassId(FP[kPcMarkerSlotFromFp]) == kCodeCid);
return static_cast<RawCode*>(FP[kPcMarkerSlotFromFp]);
@@ -290,6 +488,33 @@
SimulatorHelpers::GrowableArraySetIndexed;
intrinsics_[kGrowableArrayGetIndexedIntrinsic] =
SimulatorHelpers::GrowableArrayGetIndexed;
+ intrinsics_[kObjectEqualsIntrinsic] =
+ SimulatorHelpers::ObjectEquals;
+ intrinsics_[kObjectRuntimeTypeIntrinsic] =
+ SimulatorHelpers::ObjectRuntimeType;
+
+ intrinsics_[kDouble_getIsNaNIntrinsic] =
+ SimulatorHelpers::Double_getIsNan;
+ intrinsics_[kDouble_getIsInfiniteIntrinsic] =
+ SimulatorHelpers::Double_getIsInfinite;
+ intrinsics_[kDouble_addIntrinsic] =
+ SimulatorHelpers::Double_add;
+ intrinsics_[kDouble_mulIntrinsic] =
+ SimulatorHelpers::Double_mul;
+ intrinsics_[kDouble_subIntrinsic] =
+ SimulatorHelpers::Double_sub;
+ intrinsics_[kDouble_divIntrinsic] =
+ SimulatorHelpers::Double_div;
+ intrinsics_[kDouble_greaterThanIntrinsic] =
+ SimulatorHelpers::Double_greaterThan;
+ intrinsics_[kDouble_greaterEqualThanIntrinsic] =
+ SimulatorHelpers::Double_greaterEqualThan;
+ intrinsics_[kDouble_lessThanIntrinsic] =
+ SimulatorHelpers::Double_lessThan;
+ intrinsics_[kDouble_equalIntrinsic] =
+ SimulatorHelpers::Double_equal;
+ intrinsics_[kDouble_lessEqualThanIntrinsic] =
+ SimulatorHelpers::Double_lessEqualThan;
}
@@ -482,9 +707,6 @@
}
-#define LIKELY(cond) __builtin_expect((cond), 1)
-
-
DART_FORCE_INLINE static bool AreBothSmis(intptr_t a, intptr_t b) {
return ((a | b) & kHeapObjectTag) == 0;
}
@@ -2007,6 +2229,20 @@
}
{
+ BYTECODE(DoubleIsNaN, A_D);
+ const double v = bit_cast<double, RawObject*>(FP[rD]);
+ FP[rA] = isnan(v) ? true_value : false_value;
+ DISPATCH();
+ }
+
+ {
+ BYTECODE(DoubleIsInfinite, A_D);
+ const double v = bit_cast<double, RawObject*>(FP[rD]);
+ FP[rA] = isinf(v) ? true_value : false_value;
+ DISPATCH();
+ }
+
+ {
BYTECODE(LoadIndexedFloat32, A_B_C);
uint8_t* data = SimulatorHelpers::GetTypedData(FP[rB], FP[rC]);
const uint32_t value = *reinterpret_cast<uint32_t*>(data);
@@ -2238,6 +2474,18 @@
}
{
+ BYTECODE(DoubleIsNaN, A_D);
+ UNREACHABLE();
+ DISPATCH();
+ }
+
+ {
+ BYTECODE(DoubleIsInfinite, A_D);
+ UNREACHABLE();
+ DISPATCH();
+ }
+
+ {
BYTECODE(LoadIndexedFloat32, A_B_C);
UNREACHABLE();
DISPATCH();
@@ -2882,10 +3130,6 @@
pc++;
break;
}
- // The cids are sorted in descending order.
- if (cid > desired_cid) {
- break;
- }
}
pc += cids_length;
} else {
diff --git a/runtime/vm/stub_code_arm.cc b/runtime/vm/stub_code_arm.cc
index b7c2346..49dcfab 100644
--- a/runtime/vm/stub_code_arm.cc
+++ b/runtime/vm/stub_code_arm.cc
@@ -673,8 +673,7 @@
// R9: Allocation size.
Heap::Space space = Heap::kNew;
- __ LoadIsolate(R8);
- __ ldr(R8, Address(R8, Isolate::heap_offset()));
+ __ ldr(R8, Address(THR, Thread::heap_offset()));
// Potential new object start.
__ ldr(R0, Address(R8, Heap::TopOffset(space)));
__ adds(NOTFP, R0, Operand(R9)); // Potential next object start.
@@ -902,8 +901,7 @@
// R2: object size.
const intptr_t cid = kContextCid;
Heap::Space space = Heap::kNew;
- __ LoadIsolate(R9);
- __ ldr(R9, Address(R9, Isolate::heap_offset()));
+ __ ldr(R9, Address(THR, Thread::heap_offset()));
__ ldr(R0, Address(R9, Heap::TopOffset(space)));
__ add(R3, R2, Operand(R0));
// Check if the allocation fits into the remaining space.
diff --git a/runtime/vm/stub_code_arm64.cc b/runtime/vm/stub_code_arm64.cc
index 1e3c78c..7211745 100644
--- a/runtime/vm/stub_code_arm64.cc
+++ b/runtime/vm/stub_code_arm64.cc
@@ -692,8 +692,7 @@
NOT_IN_PRODUCT(__ MaybeTraceAllocation(kArrayCid, R4, &slow_case));
Heap::Space space = Heap::kNew;
- __ LoadIsolate(R8);
- __ ldr(R8, Address(R8, Isolate::heap_offset()));
+ __ ldr(R8, Address(THR, Thread::heap_offset()));
// Calculate and align allocation size.
// Load new object start and calculate next object start.
@@ -960,8 +959,7 @@
// R2: object size.
const intptr_t cid = kContextCid;
Heap::Space space = Heap::kNew;
- __ LoadIsolate(R5);
- __ ldr(R5, Address(R5, Isolate::heap_offset()));
+ __ ldr(R5, Address(THR, Thread::heap_offset()));
__ ldr(R0, Address(R5, Heap::TopOffset(space)));
__ add(R3, R2, Operand(R0));
// Check if the allocation fits into the remaining space.
diff --git a/runtime/vm/stub_code_mips.cc b/runtime/vm/stub_code_mips.cc
index 6df0642..5c99655 100644
--- a/runtime/vm/stub_code_mips.cc
+++ b/runtime/vm/stub_code_mips.cc
@@ -699,8 +699,7 @@
// T2: Allocation size.
Heap::Space space = Heap::kNew;
- __ LoadIsolate(T3);
- __ lw(T3, Address(T3, Isolate::heap_offset()));
+ __ lw(T3, Address(THR, Thread::heap_offset()));
// Potential new object start.
__ lw(T0, Address(T3, Heap::TopOffset(space)));
@@ -970,8 +969,7 @@
// T2: object size.
const intptr_t cid = kContextCid;
Heap::Space space = Heap::kNew;
- __ LoadIsolate(T5);
- __ lw(T5, Address(T5, Isolate::heap_offset()));
+ __ lw(T5, Address(THR, Thread::heap_offset()));
__ lw(V0, Address(T5, Heap::TopOffset(space)));
__ addu(T3, T2, V0);
diff --git a/runtime/vm/zone.cc b/runtime/vm/zone.cc
index ac79f35..bace1f3 100644
--- a/runtime/vm/zone.cc
+++ b/runtime/vm/zone.cc
@@ -59,7 +59,7 @@
ASSERT(size >= 0);
Segment* result = reinterpret_cast<Segment*>(malloc(size));
if (result == NULL) {
- FATAL("Out of memory.\n");
+ OUT_OF_MEMORY();
}
ASSERT(Utils::IsAligned(result->start(), Zone::kAlignment));
#ifdef DEBUG
diff --git a/sdk/lib/_internal/js_runtime/lib/core_patch.dart b/sdk/lib/_internal/js_runtime/lib/core_patch.dart
index 5d84791..5c5ec25 100644
--- a/sdk/lib/_internal/js_runtime/lib/core_patch.dart
+++ b/sdk/lib/_internal/js_runtime/lib/core_patch.dart
@@ -464,6 +464,7 @@
@patch
class RegExp {
+ @NoInline()
@patch
factory RegExp(String source,
{bool multiLine: false,
diff --git a/sdk/lib/_internal/js_runtime/lib/js_helper.dart b/sdk/lib/_internal/js_runtime/lib/js_helper.dart
index 011e45e..4b21b3d 100644
--- a/sdk/lib/_internal/js_runtime/lib/js_helper.dart
+++ b/sdk/lib/_internal/js_runtime/lib/js_helper.dart
@@ -1036,7 +1036,8 @@
}
static String flattenString(String str) {
- return JS('String', "#.charCodeAt(0) == 0 ? # : #", str, str, str);
+ return JS('returns:String;depends:none;effects:none;throws:never;gvn:true',
+ "#.charCodeAt(0) == 0 ? # : #", str, str, str);
}
static String getTimeZoneName(DateTime receiver) {
diff --git a/sdk/lib/_internal/js_runtime/lib/regexp_helper.dart b/sdk/lib/_internal/js_runtime/lib/regexp_helper.dart
index 35a42d1c..f756868 100644
--- a/sdk/lib/_internal/js_runtime/lib/regexp_helper.dart
+++ b/sdk/lib/_internal/js_runtime/lib/regexp_helper.dart
@@ -18,7 +18,7 @@
*/
regExpGetGlobalNative(JSSyntaxRegExp regexp) {
var nativeRegexp = regexp._nativeGlobalVersion;
- JS("void", "#.lastIndex = 0", nativeRegexp);
+ JS('void', '#.lastIndex = 0', nativeRegexp);
return nativeRegexp;
}
@@ -34,7 +34,7 @@
*/
int regExpCaptureCount(JSSyntaxRegExp regexp) {
var nativeAnchoredRegExp = regexp._nativeAnchoredVersion;
- var match = JS('JSExtendableArray', "#.exec('')", nativeAnchoredRegExp);
+ var match = JS('JSExtendableArray', '#.exec("")', nativeAnchoredRegExp);
// The native-anchored regexp always have one capture more than the original,
// and always matches the empty string.
return match.length - 2;
@@ -46,7 +46,7 @@
var _nativeGlobalRegExp;
var _nativeAnchoredRegExp;
- String toString() => "RegExp/$pattern/";
+ String toString() => 'RegExp/$pattern/';
JSSyntaxRegExp(String source,
{ bool multiLine: false,
@@ -70,14 +70,14 @@
// that it tries, and you can see if the original regexp matched, or it
// was the added zero-width match that matched, by looking at the last
// capture. If it is a String, the match participated, otherwise it didn't.
- return _nativeAnchoredRegExp = makeNative("$pattern|()",
+ return _nativeAnchoredRegExp = makeNative('$pattern|()',
_isMultiLine,
_isCaseSensitive,
true);
}
- bool get _isMultiLine => JS("bool", "#.multiline", _nativeRegExp);
- bool get _isCaseSensitive => JS("bool", "!#.ignoreCase", _nativeRegExp);
+ bool get _isMultiLine => JS('bool', '#.multiline', _nativeRegExp);
+ bool get _isCaseSensitive => JS('bool', '!#.ignoreCase', _nativeRegExp);
static makeNative(
String source, bool multiLine, bool caseSensitive, bool global) {
@@ -135,21 +135,20 @@
Match _execGlobal(String string, int start) {
Object regexp = _nativeGlobalVersion;
- JS("void", "#.lastIndex = #", regexp, start);
- List match = JS("JSExtendableArray|Null", "#.exec(#)", regexp, string);
+ JS('void', '#.lastIndex = #', regexp, start);
+ List match = JS('JSExtendableArray|Null', '#.exec(#)', regexp, string);
if (match == null) return null;
return new _MatchImplementation(this, match);
}
Match _execAnchored(String string, int start) {
Object regexp = _nativeAnchoredVersion;
- JS("void", "#.lastIndex = #", regexp, start);
- List match = JS("JSExtendableArray|Null", "#.exec(#)", regexp, string);
+ JS('void', '#.lastIndex = #', regexp, start);
+ List match = JS('JSExtendableArray|Null', '#.exec(#)', regexp, string);
if (match == null) return null;
// If the last capture group participated, the original regexp did not
// match at the start position.
- if (match[match.length - 1] != null) return null;
- match.length -= 1;
+ if (match.removeLast() != null) return null;
return new _MatchImplementation(this, match);
}
@@ -167,17 +166,23 @@
class _MatchImplementation implements Match {
final Pattern pattern;
// Contains a JS RegExp match object.
- // It is an Array of String values with extra "index" and "input" properties.
+ // It is an Array of String values with extra 'index' and 'input' properties.
final List<String> _match;
_MatchImplementation(this.pattern, this._match) {
- assert(JS("var", "#.input", _match) is String);
- assert(JS("var", "#.index", _match) is int);
+ assert(JS('var', '#.input', _match) is String);
+ assert(JS('var', '#.index', _match) is int);
}
- String get input => JS("String", "#.input", _match);
- int get start => JS("int", "#.index", _match);
- int get end => start + _match[0].length;
+ String get input => JS('String', '#.input', _match);
+
+ int get start =>
+ JS('returns:int;depends:none;effects:none;gvn:true', '#.index', _match);
+
+ int get end =>
+ start +
+ JS('returns:int;depends:none;effects:none;gvn:true', '#[0].length',
+ _match);
String group(int index) => _match[index];
String operator [](int index) => group(index);
diff --git a/sdk/lib/core/date_time.dart b/sdk/lib/core/date_time.dart
index b792ac2..0453704 100644
--- a/sdk/lib/core/date_time.dart
+++ b/sdk/lib/core/date_time.dart
@@ -572,7 +572,14 @@
* Returns a new [DateTime] instance with [duration] added to [this].
*
* DateTime today = new DateTime.now();
- * DateTime sixtyDaysFromNow = today.add(new Duration(days: 60));
+ * DateTime fiftyDaysFromNow = today.add(new Duration(days: 50));
+ *
+ * Notice that the duration being added is actually 50 * 24 * 60 * 60
+ * seconds. If the resulting `DateTime` has a different daylight saving offset
+ * than `this`, then the result won't have the same time-of-day as `this`, and
+ * may not even hit the calendar date 50 days later.
+ *
+ * Be careful when working with dates in local time.
*/
external DateTime add(Duration duration);
@@ -580,13 +587,14 @@
* Returns a new [DateTime] instance with [duration] subtracted from [this].
*
* DateTime today = new DateTime.now();
- * DateTime sixtyDaysAgo = today.subtract(new Duration(days: 30));
+ * DateTime fiftyDaysAgo = today.subtract(new Duration(days: 50));
*
- * Notice that duration being subtracted is actually 30 * 24 * 60 * 60 seconds
- * and if that crosses a daylight saving time change, the resulting `DateTime`
- * won't have the same time of day as `today`, and may not actually hit the
- * calendar date 30 days earlier. Be careful when working with dates in local
- * time.
+ * Notice that the duration being subtracted is actually 50 * 24 * 60 * 60
+ * seconds. If the resulting `DateTime` has a different daylight saving offset
+ * than `this`, then the result won't have the same time-of-day as `this`, and
+ * may not even hit the calendar date 50 days earlier.
+ *
+ * Be careful when working with dates in local time.
*/
external DateTime subtract(Duration duration);
diff --git a/sdk/lib/core/duration.dart b/sdk/lib/core/duration.dart
index c5b73a2..f2dd01b 100644
--- a/sdk/lib/core/duration.dart
+++ b/sdk/lib/core/duration.dart
@@ -11,6 +11,16 @@
* duration may be "negative" if the difference is from a later time to an
* earlier.
*
+ * Durations are context independent. For example, a duration of 2 days is
+ * always 48 hours, even when it is added to a `DateTime` just when the
+ * time zone is about to do a daylight-savings switch. (See [DateTime.add]).
+ *
+ * Despite the same name, a `Duration` object does not implement "Durations"
+ * as specified by ISO 8601. In particular, a duration object does not keep
+ * track of the individually provided members (such as "days" or "hours"), but
+ * only uses these arguments to compute the length of the corresponding time
+ * interval.
+ *
* To create a new Duration object, use this class's single constructor
* giving the appropriate arguments:
*
diff --git a/sdk/lib/html/dart2js/html_dart2js.dart b/sdk/lib/html/dart2js/html_dart2js.dart
index 7a937b3..3d4792d 100644
--- a/sdk/lib/html/dart2js/html_dart2js.dart
+++ b/sdk/lib/html/dart2js/html_dart2js.dart
@@ -89,7 +89,8 @@
/**
* Root node for all content in a web page.
*/
-HtmlDocument get document => JS('HtmlDocument', 'document');
+HtmlDocument get document =>
+ JS('returns:HtmlDocument;depends:none;effects:none;gvn:true', 'document');
// Workaround for tags like <cite> that lack their own Element subclass --
// Dart issue 1990.
@@ -3069,10 +3070,8 @@
@Native("Comment")
class Comment extends CharacterData {
factory Comment([String data]) {
- if (data != null) {
- return JS('Comment', '#.createComment(#)', document, data);
- }
- return JS('Comment', '#.createComment("")', document);
+ return JS('returns:Comment;depends:none;effects:none;new:true',
+ '#.createComment(#)', document, data == null ? "" : data);
}
// To suppress missing implicit constructor warnings.
factory Comment._() { throw new UnsupportedError("Not supported"); }
@@ -31999,7 +31998,9 @@
@DomName('Text')
@Native("Text")
class Text extends CharacterData {
- factory Text(String data) => document._createTextNode(data);
+ factory Text(String data) =>
+ JS('returns:Text;depends:none;effects:none;new:true',
+ '#.createTextNode(#)', document, data);
// To suppress missing implicit constructor warnings.
factory Text._() { throw new UnsupportedError("Not supported"); }
diff --git a/tests/co19/co19-co19.status b/tests/co19/co19-co19.status
index 0934228..f1ccde4 100644
--- a/tests/co19/co19-co19.status
+++ b/tests/co19/co19-co19.status
@@ -80,7 +80,7 @@
[ $runtime == dartium || $compiler == dart2js ]
LibTest/async/Future/Future.delayed_A01_t02: Pass, Fail # Issue 15524
-[ ($compiler == none || $compiler == precompiler || $compiler == dart2appjit) && ($runtime == vm || $runtime == drt || $runtime == dartium || $runtime == dart_precompiled || $runtime == dart_app) ]
+[ ($compiler == none || $compiler == precompiler || $compiler == dart2app || $compiler == dart2appjit) && ($runtime == vm || $runtime == drt || $runtime == dartium || $runtime == dart_precompiled || $runtime == dart_app) ]
# Optional trailing commas for argument and parameter lists added to language.
# https://github.com/dart-lang/co19/issues/68
Language/Expressions/Function_Invocation/Actual_Argument_List_Evaluation/syntax_t05: Fail, OK
diff --git a/tests/co19/co19-dart2js.status b/tests/co19/co19-dart2js.status
index cc8930b..7edabe0 100644
--- a/tests/co19/co19-dart2js.status
+++ b/tests/co19/co19-dart2js.status
@@ -541,7 +541,10 @@
Language/Metadata/compilation_t11: Pass # mirrors not supported, fails for the wrong reason
WebPlatformTest/shadow-dom/testcommon: Fail # mirrors not supported
-[ $compiler == dart2js && ($runtime == jsshell || ($fast_startup && ($runtime == safari || ($minified && $runtime == d8))))]
+[ $compiler == dart2js && $runtime == jsshell ]
+LibTest/isolate/Isolate/spawn_A04_t04: Fail # Issue 27558
+
+[ $compiler == dart2js && $fast_startup && $runtime == d8]
LibTest/isolate/Isolate/spawn_A04_t04: Fail # Issue 27558
[ $compiler == dart2js && $fast_startup && $runtime == jsshell ]
@@ -584,10 +587,6 @@
WebPlatformTest/custom-elements/instantiating/createElement_A04_t01: RuntimeError # Please triage this failure
WebPlatformTest/custom-elements/instantiating/isAttribute_A02_t01: RuntimeError # Please triage this failure
-[ $compiler == dart2js && $runtime == drt && $fast_startup && $checked ]
-WebPlatformTest/custom-elements/instantiating/createElementNS_A05_t01: RuntimeError # Please triage this failure
-WebPlatformTest/custom-elements/instantiating/createElement_A05_t01: RuntimeError # Please triage this failure
-
[ $compiler == dart2js && $fast_startup && $browser && $runtime != chrome && $runtime != drt]
WebPlatformTest/shadow-dom/elements-and-dom-objects/extensions-to-element-interface/attributes/test-005_t01: Fail # please triage
WebPlatformTest/shadow-dom/elements-and-dom-objects/extensions-to-element-interface/methods/test-001_t01: Fail # please triage
@@ -971,6 +970,7 @@
LayoutTests/fast/canvas/2d.text.draw.fill.maxWidth.negative_t01: RuntimeError # Please triage this failure
LayoutTests/fast/canvas/2d.text.draw.fill.maxWidth.veryLarge_t01: RuntimeError # Please triage this failure
LayoutTests/fast/canvas/2d.text.draw.fill.maxWidth.verySmall_t01: RuntimeError # Please triage this failure
+LayoutTests/fast/canvas/DrawImageSinglePixelStretch_t01: Pass, RuntimeError # Please triage this failure
LayoutTests/fast/canvas/alpha_t01: RuntimeError # Please triage this failure
LayoutTests/fast/canvas/canvas-arc-negative-radius_t01: RuntimeError # Please triage this failure
LayoutTests/fast/canvas/canvas-as-image-incremental-repaint_t01: Skip # Times out. Please triage this failure
@@ -1006,6 +1006,7 @@
LayoutTests/fast/canvas/webgl/webgl-depth-texture_t01: RuntimeError # Please triage this failure
LayoutTests/fast/canvas/webgl/webgl-large-texture_t01: RuntimeError # Please triage this failure
LayoutTests/fast/canvas/webgl/webgl-layer-update_t01: Skip # Times out. Please triage this failure
+LayoutTests/fast/canvas/webgl/webgl-specific_t01: RuntimeError # Please triage this failure
LayoutTests/fast/css-generated-content/hit-test-generated-content_t01: Pass, RuntimeError # Please triage this failure
LayoutTests/fast/css-generated-content/malformed-url_t01: Skip # Times out. Please triage this failure
LayoutTests/fast/css-generated-content/pseudo-animation-before-onload_t01: Pass, RuntimeError # Please triage this failure
@@ -1060,6 +1061,7 @@
LayoutTests/fast/css/aspect-ratio-inheritance_t01: Pass, RuntimeError # Please triage this failure
LayoutTests/fast/css/aspect-ratio-parsing-tests_t01: Pass, RuntimeError # Please triage this failure
LayoutTests/fast/css/auto-min-size_t01: RuntimeError # Please triage this failure
+LayoutTests/fast/css/background-serialize_t01: RuntimeError # Please triage this failure
LayoutTests/fast/css/checked-pseudo-selector_t01: RuntimeError # Please triage this failure
LayoutTests/fast/css/content/content-none_t01: RuntimeError # Please triage this failure
LayoutTests/fast/css/content/content-normal_t01: RuntimeError # Please triage this failure
@@ -1088,6 +1090,7 @@
LayoutTests/fast/css/getComputedStyle/computed-style-border-image_t01: RuntimeError # co19 issue 14
LayoutTests/fast/css/getComputedStyle/computed-style-cross-fade_t01: RuntimeError # co19 issue 14
LayoutTests/fast/css/getComputedStyle/font-family-fallback-reset_t01: RuntimeError # Please triage this failure
+LayoutTests/fast/css/getComputedStyle/getComputedStyle-zIndex-auto_t01: RuntimeError # Please triage this failure
LayoutTests/fast/css/getPropertyValue-border_t01: RuntimeError # Please triage this failure
LayoutTests/fast/css/html-attr-case-sensitivity_t01: RuntimeError # Please triage this failure
LayoutTests/fast/css/id-or-class-before-stylesheet_t01: RuntimeError # Please triage this failure
@@ -1172,6 +1175,8 @@
LayoutTests/fast/dom/HTMLImageElement/image-alt-text_t01: RuntimeError # Please triage this failure
LayoutTests/fast/dom/HTMLImageElement/parse-src_t01: RuntimeError # Please triage this failure
LayoutTests/fast/dom/HTMLInputElement/input-image-alt-text_t01: RuntimeError # Please triage this failure
+LayoutTests/fast/dom/HTMLLabelElement/click-label_t01: RuntimeError # Please triage this failure
+LayoutTests/fast/dom/HTMLLabelElement/form/test1_t01: RuntimeError # Please triage this failure
LayoutTests/fast/dom/HTMLLinkElement/link-beforeload-recursive_t01: Skip # Times out. Please triage this failure
LayoutTests/fast/dom/HTMLLinkElement/resolve-url-on-insertion_t01: RuntimeError # Issue 18010
LayoutTests/fast/dom/HTMLObjectElement/beforeload-set-text-crash_t01: Skip # Times out. Please triage this failure
@@ -1253,6 +1258,7 @@
LayoutTests/fast/dom/shadow/event-path_t01: RuntimeError # Please triage this failure
LayoutTests/fast/dom/shadow/host-context-pseudo-class-css-text_t01: RuntimeError # https://github.com/dart-lang/co19/issues/49
LayoutTests/fast/dom/shadow/host-pseudo-class-css-text_t01: RuntimeError # https://github.com/dart-lang/co19/issues/49
+LayoutTests/fast/dom/shadow/link-in-shadow-tree_t01: RuntimeError # Please triage this failure
LayoutTests/fast/dom/shadow/olderShadowRoot_t01: RuntimeError # Issue 26729
LayoutTests/fast/dom/shadow/pseudoclass-update-checked-option_t01: RuntimeError # Please triage this failure
LayoutTests/fast/dom/shadow/pseudoclass-update-disabled-optgroup_t01: RuntimeError # Please triage this failure
@@ -1333,6 +1339,7 @@
LayoutTests/fast/forms/file/file-input-capture_t01: RuntimeError # Please triage this failure
LayoutTests/fast/forms/focus-style-pending_t01: Skip # Times out. Please triage this failure
LayoutTests/fast/forms/focus_t01: Pass, RuntimeError # Please triage this failure
+LayoutTests/fast/forms/form-attribute-nonexistence-form-id_t01: RuntimeError # Please triage this failure
LayoutTests/fast/forms/form-attribute_t01: RuntimeError # Issue 25155
LayoutTests/fast/forms/input-appearance-elementFromPoint_t01: RuntimeError # Please triage this failure
LayoutTests/fast/forms/input-hit-test-border_t01: Pass, RuntimeError # Please triage this failure
@@ -1343,9 +1350,11 @@
LayoutTests/fast/forms/menulist-selection-reset_t01: RuntimeError # Please triage this failure
LayoutTests/fast/forms/menulist-submit-without-selection_t01: RuntimeError # Please triage this failure
LayoutTests/fast/forms/multiple-selected-options-innerHTML_t01: RuntimeError # Please triage this failure
+LayoutTests/fast/forms/onchange-change-type_t01: RuntimeError # Please triage this failure
LayoutTests/fast/forms/option-change-single-selected_t01: RuntimeError # Please triage this failure
LayoutTests/fast/forms/option-strip-unicode-spaces_t01: RuntimeError # Please triage this failure
LayoutTests/fast/forms/parser-associated-form-removal_t01: RuntimeError # Please triage this failure
+LayoutTests/fast/forms/paste-into-textarea_t01: RuntimeError # Please triage this failure
LayoutTests/fast/forms/plaintext-mode-1_t01: RuntimeError # Please triage this failure
LayoutTests/fast/forms/search-popup-crasher_t01: RuntimeError # Please triage this failure
LayoutTests/fast/forms/select-change-popup-to-listbox-in-event-handler_t01: Skip # Times out. Please triage this failure
@@ -1361,6 +1370,7 @@
LayoutTests/fast/forms/validationMessage_t01: RuntimeError # Please triage this failure
LayoutTests/fast/forms/validity-property_t01: RuntimeError # Issue 25155
LayoutTests/fast/forms/willvalidate_t01: RuntimeError # Issue 25155
+LayoutTests/fast/html/empty-fragment-id-goto-top_t01: RuntimeError # Please triage this failure
LayoutTests/fast/html/hidden-attr_t01: RuntimeError # Please triage this failure
LayoutTests/fast/html/imports/import-element-removed-flag_t01: RuntimeError # Please triage this failure
LayoutTests/fast/html/imports/import-events_t01: RuntimeError # Please triage this failure
@@ -1372,7 +1382,6 @@
LayoutTests/fast/inline/parent-inline-element-padding-contributes-width_t01: RuntimeError # Please triage this failure
LayoutTests/fast/inline/positioned-element-padding-contributes-width_t01: RuntimeError # Please triage this failure
LayoutTests/fast/innerHTML/innerHTML-uri-resolution_t01: RuntimeError # co19 issue 14
-LayoutTests/fast/innerHTML/innerHTML-uri-resolution_t01: RuntimeError # co19 issue 14
LayoutTests/fast/layers/zindex-hit-test_t01: Pass, RuntimeError # Please triage this failure
LayoutTests/fast/loader/about-blank-hash-change_t01: Skip # Times out. Please triage this failure
LayoutTests/fast/loader/about-blank-hash-kept_t01: Skip # Times out. Please triage this failure
@@ -1544,8 +1553,6 @@
LibTest/html/Element/focus_A01_t01: Skip # Times out. Please triage this failure
LibTest/html/Element/getAttributeNS_A01_t01: RuntimeError # Issue 16395
LibTest/html/Element/getNamespacedAttributes_A01_t01: RuntimeError # Issue 16395
-LibTest/html/Element/isContentEditable_A01_t01: RuntimeError # Please triage this failure
-LibTest/html/Element/isContentEditable_A02_t01: RuntimeError # Please triage this failure
LibTest/html/Element/isTagSupported_A01_t01: RuntimeError # Issue 25155
LibTest/html/Element/marginEdge_A01_t01: RuntimeError # Issue 16574
LibTest/html/Element/mouseWheelEvent_A01_t01: Skip # Times out. Please triage this failure
@@ -1584,7 +1591,6 @@
LibTest/html/IFrameElement/focus_A01_t01: Skip # Times out. Please triage this failure
LibTest/html/IFrameElement/getNamespacedAttributes_A01_t01: RuntimeError # Please triage this failure
LibTest/html/IFrameElement/innerHtml_A01_t01: RuntimeError # Please triage this failure
-LibTest/html/IFrameElement/isContentEditable_A01_t01: RuntimeError # Please triage this failure
LibTest/html/IFrameElement/leftView_A01_t01: Skip # Times out. Please triage this failure
LibTest/html/IFrameElement/marginEdge_A01_t01: RuntimeError # Issue 16574
LibTest/html/IFrameElement/offsetTo_A01_t01: RuntimeError # Please triage this failure
@@ -1622,6 +1628,7 @@
WebPlatformTest/Utils/test/asyncTestFail_t01: RuntimeError # Please triage this failure
WebPlatformTest/Utils/test/asyncTestFail_t02: RuntimeError # Please triage this failure
WebPlatformTest/Utils/test/asyncTestTimeout_t01: Skip # Times out. Please triage this failure
+WebPlatformTest/custom-elements/concepts/type_A03_t01: RuntimeError # Please triage this failure
WebPlatformTest/custom-elements/concepts/type_A05_t01: RuntimeError # Please triage this failure
WebPlatformTest/custom-elements/concepts/type_A06_t01: RuntimeError # Please triage this failure
WebPlatformTest/custom-elements/instantiating/createElementNS_A02_t01: RuntimeError # Issue 25155
@@ -1783,9 +1790,6 @@
WebPlatformTest/webstorage/event_constructor_t01: RuntimeError # Please triage this failure
WebPlatformTest/webstorage/event_constructor_t02: RuntimeError # Please triage this failure
-[ $compiler == dart2js && $runtime == chrome ]
-WebPlatformTest/custom-elements/concepts/type_A03_t01: RuntimeError # Please triage this failure
-
[ $compiler == dart2js && $runtime == chrome && $checked ]
LayoutTests/fast/css-intrinsic-dimensions/css-tables_t01: RuntimeError # Please triage this failure
LayoutTests/fast/css-intrinsic-dimensions/intrinsic-sized-absolutes_t01: RuntimeError # Please triage this failure
@@ -1862,12 +1866,13 @@
[ $compiler == dart2js && $runtime == chrome && $system == macos ]
Language/Expressions/Function_Invocation/async_invokation_t04: RuntimeError # Please triage this failure
LayoutTests/fast/canvas/webgl/canvas-test_t01: Skip # Times out. Please triage this failure
-LayoutTests/fast/canvas/webgl/tex-image-and-sub-image-2d-with-video-rgba5551_t01: Skip # Times out flakily.
LayoutTests/fast/canvas/webgl/context-lost-restored_t01: Skip # Times out. Please triage this failure.
LayoutTests/fast/canvas/webgl/draw-webgl-to-canvas-2d_t01: Pass, RuntimeError # Please triage this failure
LayoutTests/fast/canvas/webgl/oes-vertex-array-object_t01: RuntimeError # Please triage this failure
+LayoutTests/fast/canvas/webgl/tex-image-and-sub-image-2d-with-video-rgba5551_t01: Skip # Times out flakily.
LayoutTests/fast/dom/HTMLOutputElement/htmloutputelement_t01: RuntimeError # Please triage this failure
LayoutTests/fast/dom/MutationObserver/observe-attributes_t01: Skip # Times out. Please triage this failure
+LayoutTests/fast/forms/percent-height-auto-width-form-controls_t01: RuntimeError # Please triage this failure
LayoutTests/fast/multicol/newmulticol/balance_t04: RuntimeError # Please triage this failure
LayoutTests/fast/shapes/shape-outside-floats/shape-outside-floats-inset-rounded-different-writing-modes-left_t01: RuntimeError # Please triage this failure
LayoutTests/fast/shapes/shape-outside-floats/shape-outside-rounded-boxes_t02: RuntimeError # Please triage this failure
@@ -1875,6 +1880,7 @@
LayoutTests/fast/text/line-break-after-question-mark_t01: RuntimeError # Please triage this failure
LayoutTests/fast/text/text-combine-shrink-to-fit_t01: RuntimeError # Please triage this failure
LibTest/async/Timer/Timer.periodic_A01_t01: Skip # Times out. Please triage this failure
+LibTest/isolate/Isolate/spawn_A01_t05: Skip # Times out. Please triage this failure
WebPlatformTest/shadow-dom/events/retargeting-focus-events/test-002_t01: Skip # Times out. Please triage this failure
[ $compiler == dart2js && $runtime == chrome && $system != macos ]
@@ -1972,7 +1978,6 @@
LayoutTests/fast/canvas/webgl/webgl-composite-modes_t01: RuntimeError # Please triage this failure
LayoutTests/fast/canvas/webgl/webgl-exceptions_t01: RuntimeError # Please triage this failure
LayoutTests/fast/canvas/webgl/webgl-layer-update_t01: RuntimeError # Please triage this failure
-LayoutTests/fast/canvas/webgl/webgl-specific_t01: RuntimeError # Please triage this failure
LayoutTests/fast/canvas/webgl/webgl-texture-binding-preserved_t01: RuntimeError # Please triage this failure
LayoutTests/fast/canvas/webgl/webgl-unprefixed-context-id_t01: RuntimeError # Please triage this failure
LayoutTests/fast/canvas/webgl/webgl-viewport-parameters-preserved_t01: RuntimeError # Please triage this failure
@@ -1986,21 +1991,9 @@
[ $compiler == dart2js && $runtime == chrome && $system == windows ]
Language/Classes/Constructors/Generative_Constructors/execution_of_an_initializer_t04: Pass, Slow # Issue 25940
Language/Expressions/Bitwise_Expressions/method_invocation_super_t01: Pass, Slow # Issue 25940
-LayoutTests/fast/css/background-serialize_t01: RuntimeError # Please triage this failure
-LayoutTests/fast/dom/HTMLLabelElement/click-label_t01: RuntimeError # Please triage this failure
-LayoutTests/fast/dom/HTMLLabelElement/form/test1_t01: RuntimeError # Please triage this failure
-LayoutTests/fast/forms/form-attribute-nonexistence-form-id_t01: RuntimeError # Please triage this failure
-LayoutTests/fast/forms/onchange-change-type_t01: RuntimeError # Please triage this failure
-LayoutTests/fast/html/empty-fragment-id-goto-top_t01: RuntimeError # Please triage this failure
LibTest/isolate/Isolate/spawn_A04_t04: Skip # Times out. Please triage this failure
[ $compiler == dart2js && $runtime == chrome && $system == linux]
-LayoutTests/fast/css/background-serialize_t01: RuntimeError # Please triage this failure
-LayoutTests/fast/dom/HTMLLabelElement/click-label_t01: RuntimeError # Please triage this failure
-LayoutTests/fast/dom/HTMLLabelElement/form/test1_t01: RuntimeError # Please triage this failure
-LayoutTests/fast/forms/form-attribute-nonexistence-form-id_t01: RuntimeError # Please triage this failure
-LayoutTests/fast/forms/onchange-change-type_t01: RuntimeError # Please triage this failure
-LayoutTests/fast/html/empty-fragment-id-goto-top_t01: RuntimeError # Please triage this failure
LayoutTests/fast/text/international/combining-marks-position_t01: RuntimeError # Please triage this failure
LibTest/math/log_A01_t01: RuntimeError # Please triage this failure
@@ -2223,8 +2216,8 @@
LayoutTests/fast/dom/HTMLOutputElement/dom-settable-token-list_t01: RuntimeError # Please triage this failure
LayoutTests/fast/dom/HTMLScriptElement/async-onbeforeload_t01: RuntimeError # Please triage this failure
LayoutTests/fast/dom/HTMLScriptElement/defer-onbeforeload_t01: RuntimeError # Please triage this failure
+LayoutTests/fast/dom/HTMLScriptElement/isURLAttribute_t01: Skip # Times out. Please triage this failure
LayoutTests/fast/dom/HTMLScriptElement/remove-in-beforeload_t01: RuntimeError # Please triage this failure
-LayoutTests/fast/dom/HTMLScriptElement/remove-source_t01: RuntimeError # Please triage this failure
LayoutTests/fast/dom/HTMLSelectElement/remove-element-from-within-focus-handler-crash_t01: RuntimeError # Please triage this failure
LayoutTests/fast/dom/HTMLSelectElement/selected-index-preserved-when-option-text-changes_t01: RuntimeError # Please triage this failure
LayoutTests/fast/dom/HTMLTemplateElement/custom-element-wrapper-gc_t01: RuntimeError # Please triage this failure
@@ -2280,7 +2273,6 @@
LayoutTests/fast/events/change-overflow-on-overflow-change_t01: Skip # Times out.
LayoutTests/fast/events/document-elementFromPoint_t01: RuntimeError # Please triage this failure
LayoutTests/fast/events/event-creation_t01: RuntimeError # Please triage this failure
-LayoutTests/fast/events/event-listener-html-non-html-confusion_t01: RuntimeError # Please triage this failure
LayoutTests/fast/events/event-trace_t01: RuntimeError # Please triage this failure
LayoutTests/fast/events/initkeyboardevent-crash_t01: RuntimeError # Please triage this failure
LayoutTests/fast/events/invalid-003_t01: RuntimeError # Please triage this failure
@@ -2321,7 +2313,7 @@
LayoutTests/fast/loader/about-blank-hash-kept_t01: Skip # Times out.
LayoutTests/fast/loader/hashchange-event-properties_t01: RuntimeError # Please triage this failure
LayoutTests/fast/loader/onhashchange-attribute-listeners_t01: Skip # Times out.
-LayoutTests/fast/loader/scroll-position-restored-on-back_t01: RuntimeError # Please triage this failure
+LayoutTests/fast/loader/scroll-position-restored-on-back_t01: Skip # Times out. Please triage this failure
LayoutTests/fast/loader/scroll-position-restored-on-reload-at-load-event_t01: RuntimeError # Please triage this failure
LayoutTests/fast/loader/stateobjects/replacestate-in-onunload_t01: RuntimeError # Please triage this failure
LayoutTests/fast/masking/parsing-clip-path-shape_t01: RuntimeError # Please triage this failure
@@ -2531,6 +2523,7 @@
WebPlatformTest/Utils/test/asyncTestFail_t01: RuntimeError # Please triage this failure
WebPlatformTest/Utils/test/asyncTestFail_t02: RuntimeError # Please triage this failure
WebPlatformTest/Utils/test/asyncTestTimeout_t01: Skip # Times out.
+WebPlatformTest/custom-elements/concepts/type_A03_t01: RuntimeError # Please triage this failure
WebPlatformTest/custom-elements/concepts/type_A05_t01: RuntimeError # Please triage this failure
WebPlatformTest/custom-elements/concepts/type_A06_t01: RuntimeError # Please triage this failure
WebPlatformTest/dom/EventTarget/dispatchEvent_A02_t01: RuntimeError # Please triage this failure
@@ -2660,12 +2653,28 @@
WebPlatformTest/shadow-dom/shadow-trees/upper-boundary-encapsulation/test-009_t01: RuntimeError # Please triage this failure
WebPlatformTest/webstorage/event_constructor_t01: RuntimeError # Please triage this failure
WebPlatformTest/webstorage/event_constructor_t02: RuntimeError # Please triage this failure
+WebPlatformTest/webstorage/event_local_key_t01: Skip # Times out. Please triage this failure
+WebPlatformTest/webstorage/event_local_newvalue_t01: Skip # Times out. Please triage this failure
+WebPlatformTest/webstorage/event_local_oldvalue_t01: Skip # Times out. Please triage this failure
+WebPlatformTest/webstorage/event_local_storagearea_t01: Skip # Times out. Please triage this failure
+WebPlatformTest/webstorage/event_local_url_t01: Skip # Times out. Please triage this failure
+WebPlatformTest/webstorage/event_session_key_t01: Skip # Times out. Please triage this failure
+WebPlatformTest/webstorage/event_session_newvalue_t01: Skip # Times out. Please triage this failure
+WebPlatformTest/webstorage/event_session_oldvalue_t01: Skip # Times out. Please triage this failure
+WebPlatformTest/webstorage/event_session_storagearea_t01: Skip # Times out. Please triage this failure
+WebPlatformTest/webstorage/event_session_url_t01: Skip # Times out. Please triage this failure
-[ $compiler == dart2js && $runtime == drt ]
-WebPlatformTest/custom-elements/concepts/type_A03_t01: RuntimeError # Please triage this failure
+[ $compiler == dart2js && $runtime == drt && $minified && $csp ]
+LayoutTests/fast/dom/HTMLScriptElement/script-for-attribute-unexpected-execution_t01: RuntimeError # Please triage this failure
+LayoutTests/fast/dom/HTMLScriptElement/script-reexecution_t01: RuntimeError # Please triage this failure
+LayoutTests/fast/dom/HTMLTemplateElement/inertContents_t01: RuntimeError # Please triage this failure
+LayoutTests/fast/dom/Range/create-contextual-fragment-script-unmark-already-started_t01: RuntimeError # Please triage this failure
+
+[ $compiler == dart2js && $runtime == drt && $minified != true && $csp != true]
+LayoutTests/fast/dom/HTMLScriptElement/remove-source_t01: RuntimeError # Please triage this failure
+LayoutTests/fast/events/event-listener-html-non-html-confusion_t01: RuntimeError # Please triage this failure
[ $compiler == dart2js && $runtime == drt && $fast_startup && $checked ]
-WebPlatformTest/shadow-dom/shadow-trees/upper-boundary-encapsulation/ownerdocument-001_t01: RuntimeError # Please triage this failure
LayoutTests/fast/css-grid-layout/auto-content-resolution-rows_t01: RuntimeError # Please triage this failure
LayoutTests/fast/css-grid-layout/breadth-size-resolution-grid_t01: RuntimeError # Please triage this failure
LayoutTests/fast/css-grid-layout/calc-resolution-grid-item_t01: RuntimeError # Please triage this failure
@@ -2745,11 +2754,14 @@
LayoutTests/fast/xpath/xpath-result-eventlistener-crash_t01: RuntimeError # Please triage this failure
LibTest/html/Node/ownerDocument_A01_t01: RuntimeError # Please triage this failure
WebPlatformTest/DOMEvents/approved/Propagation.path.target.removed_t01: RuntimeError # Please triage this failure
+WebPlatformTest/custom-elements/instantiating/createElementNS_A05_t01: RuntimeError # Please triage this failure
+WebPlatformTest/custom-elements/instantiating/createElement_A05_t01: RuntimeError # Please triage this failure
WebPlatformTest/dom/nodes/DOMImplementation-createDocumentType_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/parsing-html-templates/clearing-the-stack-back-to-a-given-context/clearing-stack-back-to-a-table-body-context_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/parsing-html-templates/clearing-the-stack-back-to-a-given-context/clearing-stack-back-to-a-table-context_t01: RuntimeError # Please triage this failure
WebPlatformTest/html-templates/parsing-html-templates/clearing-the-stack-back-to-a-given-context/clearing-stack-back-to-a-table-row-context_t01: RuntimeError # Please triage this failure
WebPlatformTest/html/dom/elements/global-attributes/dataset-enumeration_t01: RuntimeError # Please triage this failure
+WebPlatformTest/shadow-dom/shadow-trees/upper-boundary-encapsulation/ownerdocument-001_t01: RuntimeError # Please triage this failure
[ $compiler == dart2js && $runtime == drt && $checked == false ]
LayoutTests/fast/xpath/invalid-resolver_t01: RuntimeError # Please triage this failure
diff --git a/tests/co19/co19-runtime.status b/tests/co19/co19-runtime.status
index 743ccfa..d78deae 100644
--- a/tests/co19/co19-runtime.status
+++ b/tests/co19/co19-runtime.status
@@ -164,7 +164,7 @@
Language/Metadata/*: SkipByDesign # Uses dart:mirrors
Language/Expressions/Null/instance_of_class_null_t01: Skip # Uses dart:mirrors
-[ $noopt || $compiler == precompiler || $compiler == dart2appjit || $mode == product ]
+[ $noopt || $compiler == precompiler || $compiler == dart2app || $compiler == dart2appjit || $mode == product ]
Language/Libraries_and_Scripts/Imports/deferred_import_t01: Skip # Eager loading
Language/Libraries_and_Scripts/Imports/deferred_import_t02: Skip # Eager loading
Language/Libraries_and_Scripts/Imports/invalid_uri_deferred_t01: Skip # Eager loading
@@ -179,7 +179,7 @@
LibTest/core/Map/Map_class_A01_t04: Pass, Timeout
LibTest/core/Uri/encodeQueryComponent_A01_t02: Pass, Timeout
-[ $noopt || $compiler == precompiler || $compiler == dart2appjit ]
+[ $noopt || $compiler == precompiler || $compiler == dart2app || $compiler == dart2appjit ]
Language/Mixins/Mixin_Application/error_t01: Pass
Language/Mixins/Mixin_Application/error_t02: Pass
Language/Mixins/declaring_constructor_t01: Pass
diff --git a/tests/compiler/dart2js/needs_no_such_method_test.dart b/tests/compiler/dart2js/needs_no_such_method_test.dart
index 3dadbb7..892087e 100644
--- a/tests/compiler/dart2js/needs_no_such_method_test.dart
+++ b/tests/compiler/dart2js/needs_no_such_method_test.dart
@@ -35,6 +35,7 @@
Selector foo, bar, baz;
ClosedWorld closedWorld;
ClassElement superclass, subclass, subtype;
+ String testMode;
Future run(List<String> instantiated) async {
StringBuffer main = new StringBuffer();
@@ -43,6 +44,7 @@
main.write('new $cls();');
}
main.write('}');
+ testMode = '$instantiated';
var env = await TypeEnvironment.create(CLASSES,
mainSource: main.toString(), useMockCompiler: false);
@@ -59,8 +61,11 @@
void check(ClassElement cls, ClassQuery query, Selector selector,
bool expectedResult) {
bool result = closedWorld.needsNoSuchMethod(cls, selector, query);
- Expect.equals(expectedResult, result,
- 'Unexpected result for $selector in $cls ($query)');
+ Expect.equals(
+ expectedResult,
+ result,
+ 'Unexpected result for $selector in $cls ($query)'
+ 'for instantiations $testMode');
}
await run([]);
@@ -166,17 +171,13 @@
Expect.isFalse(closedWorld.isImplemented(subtype));
check(superclass, ClassQuery.EXACT, foo, false);
- // Should be false since the class is not directly instantiated:
- check(superclass, ClassQuery.EXACT, bar, true);
- // Should be false since the class is not directly instantiated:
- check(superclass, ClassQuery.EXACT, baz, true);
+ check(superclass, ClassQuery.EXACT, bar, false);
+ check(superclass, ClassQuery.EXACT, baz, false);
check(superclass, ClassQuery.SUBCLASS, foo, false);
- // Should be false since all live subclasses have a concrete implementation:
- check(superclass, ClassQuery.SUBCLASS, bar, true);
+ check(superclass, ClassQuery.SUBCLASS, bar, false);
check(superclass, ClassQuery.SUBCLASS, baz, true);
check(superclass, ClassQuery.SUBTYPE, foo, false);
- // Should be false since all live subtypes have a concrete implementation:
- check(superclass, ClassQuery.SUBTYPE, bar, true);
+ check(superclass, ClassQuery.SUBTYPE, bar, false);
check(superclass, ClassQuery.SUBTYPE, baz, true);
check(subclass, ClassQuery.EXACT, foo, false);
@@ -258,17 +259,13 @@
Expect.isTrue(closedWorld.isImplemented(subtype));
check(superclass, ClassQuery.EXACT, foo, false);
- // Should be false since the class is not directly instantiated:
- check(superclass, ClassQuery.EXACT, bar, true);
- // Should be false since the class is not directly instantiated:
- check(superclass, ClassQuery.EXACT, baz, true);
+ check(superclass, ClassQuery.EXACT, bar, false);
+ check(superclass, ClassQuery.EXACT, baz, false);
check(superclass, ClassQuery.SUBCLASS, foo, false);
- // Should be false since all live subclasses have a concrete implementation:
- check(superclass, ClassQuery.SUBCLASS, bar, true);
+ check(superclass, ClassQuery.SUBCLASS, bar, false);
check(superclass, ClassQuery.SUBCLASS, baz, true);
check(superclass, ClassQuery.SUBTYPE, foo, true);
- // Should be false since all live subtypes have a concrete implementation:
- check(superclass, ClassQuery.SUBTYPE, bar, true);
+ check(superclass, ClassQuery.SUBTYPE, bar, false);
check(superclass, ClassQuery.SUBTYPE, baz, true);
check(subclass, ClassQuery.EXACT, foo, false);
diff --git a/tests/html/html.status b/tests/html/html.status
index 4180e62..419e7bb 100644
--- a/tests/html/html.status
+++ b/tests/html/html.status
@@ -75,6 +75,11 @@
[ $compiler == none && $runtime == drt && $system == windows ]
worker_test/functional: Pass, Crash # Issue 9929.
+[ $compiler == dart2js && $runtime == chrome ]
+fileapi_test/entry: Fail # TODO(dart2js-team): Please triage this failure.
+fileapi_test/getDirectory: Fail # TODO(dart2js-team): Please triage this failure.
+fileapi_test/getFile: Fail # TODO(dart2js-team): Please triage this failure.
+
[ $compiler == dart2js && $runtime == chromeOnAndroid ]
crypto_test/functional: Pass, Slow # TODO(dart2js-team): Please triage this failure.
input_element_test/supported_datetime-local: Pass, Slow # TODO(dart2js-team): Please triage this failure.
diff --git a/tests/language/generic_methods_type_expression_test.dart b/tests/language/generic_methods_type_expression_test.dart
index dd98c7a..fadd7e9 100644
--- a/tests/language/generic_methods_type_expression_test.dart
+++ b/tests/language/generic_methods_type_expression_test.dart
@@ -51,8 +51,8 @@
Expect.throws(() => f3<String>(42), (e) => e is TypeError);
Expect.equals(f4<int>(<int>[42]), false);
Expect.equals(f4<String>(<int>[42]), false); // `is! List<dynamic>` is false.
- Expect.throws(() => f5<String>(s), (e) => e is TypeError);
- Expect.throws(() => f5<int>(s), (e) => e is TypeError);
+ Expect.equals(f5<String>(s), s); // `s as dynamic == s`
+ Expect.equals(f5<int>(s), s); // `s as dynamic == s`
Expect.equals(f6<String>(ss), ss);
Expect.equals(f6<int>(ss), ss); // `as List<dynamic>` succeeds.
Expect.throws(() => f7<int>(), (e) => e is TypeError);
diff --git a/tests/language/language.status b/tests/language/language.status
index 6b43cef..3eb4aba 100644
--- a/tests/language/language.status
+++ b/tests/language/language.status
@@ -48,6 +48,9 @@
async_star_regression_2238_test: CompileTimeError, RuntimeError # drt only runtime-errs.
async_star_cancel_while_paused_test: RuntimeError
+# Fails because `as T` is an error rather than being treated like `as dynamic`.
+generic_methods_type_expression_test: RuntimeError # Issue 27460
+
[ ($compiler == none || $compiler == precompiler || $compiler == dart2app || $compiler == dart2appjit) && $checked ]
# These generic functions tests pass for the wrong reason in checked mode,
# because the parsed type parameters are mapped to dynamic type.
diff --git a/tests/language/language_analyzer2.status b/tests/language/language_analyzer2.status
index a064488..be27119 100644
--- a/tests/language/language_analyzer2.status
+++ b/tests/language/language_analyzer2.status
@@ -5,6 +5,7 @@
[ $compiler == dart2analyzer ]
regress_26668_test: Fail # Issue 26678
+regress_27617_test/1: MissingCompileTimeError
# Runtime negative test. No static errors or warnings.
closure_call_wrong_argument_count_negative_test: skip
diff --git a/tests/language/language_dart2js.status b/tests/language/language_dart2js.status
index d4b7189..b9e66f6 100644
--- a/tests/language/language_dart2js.status
+++ b/tests/language/language_dart2js.status
@@ -288,8 +288,6 @@
generic_field_mixin5_test: Crash # Issue 18651
many_method_calls_test: Crash # Stack overflow in HGraphVisitor.visitPostDominatorTree.visitBasicBlockAndSuccessors
method_override5_test: RuntimeError # Issue 12809
-super_no_such_method4_test/01: RuntimeError # Issue 25716
-super_no_such_method5_test/01: RuntimeError # Issue 25716
[ $compiler == dart2js && $runtime != drt && $runtime != dartium ]
issue23244_test: RuntimeError # 23244
diff --git a/tests/language/regress_27617_test.dart b/tests/language/regress_27617_test.dart
new file mode 100644
index 0000000..9a0fdbd
--- /dev/null
+++ b/tests/language/regress_27617_test.dart
@@ -0,0 +1,16 @@
+// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+
+class Foo {
+ final String greeting;
+ Foo._(this.greeting) { }
+
+ // Const constructor must not redirect to non-const constructor.
+ const Foo.hi() : this._('hi'); /// 1: compile-time error
+}
+
+main() {
+ const h = const Foo.hi(); /// 1: continued
+}
diff --git a/tests/lib/lib.status b/tests/lib/lib.status
index f4114a2..f5bfade 100644
--- a/tests/lib/lib.status
+++ b/tests/lib/lib.status
@@ -139,7 +139,7 @@
typed_data/setRange_2_test: RuntimeError # TODO(dart2js-team): Please triage this failure.
typed_data/setRange_3_test: RuntimeError # TODO(dart2js-team): Please triage this failure.
-[ $compiler == dart2js && ($runtime == d8 || $runtime == drt || $runtime == ie11 || ($runtime == chrome && $system == macos)) ]
+[ $compiler == dart2js && ($runtime == d8 || $runtime == drt || $runtime == ie11) ]
math/math_test: RuntimeError
math/math2_test: RuntimeError
diff --git a/tests/standalone/standalone.status b/tests/standalone/standalone.status
index 5281b37..cd95358 100644
--- a/tests/standalone/standalone.status
+++ b/tests/standalone/standalone.status
@@ -229,7 +229,7 @@
map_insert_remove_oom_test: Skip # Heap limit too low. Increasing iteration count to make a higher limit a meaningful test makes it too slow for simarm[64] bots.
io/web_socket_test: Pass, RuntimeError # Issue 24674
-[ $noopt || $compiler == precompiler || $compiler == dart2appjit ]
+[ $noopt || $compiler == precompiler || $compiler == dart2app || $compiler == dart2appjit ]
io/test_extension_test: Skip # Platform.executable
io/test_extension_fail_test: Skip # Platform.executable
io/platform_test: Skip # Platform.executable
@@ -326,16 +326,6 @@
# SIMDBC interpreter doesn't support --no_lazy_dispatchers
no_lazy_dispatchers_test: SkipByDesign
-[ $compiler == precompiler && $runtime == dart_precompiled && $system == android ]
-io/*: Skip # Issue #26376
-
-typed_data_isolate_test: Skip # Issue #26376
-typed_array_test: Skip # Issue #26376
-typed_array_int64_uint64_test: Skip # Issue #26376
-
-oom_error_stacktrace_test: Skip # Issue #26377
-out_of_memory_test: Skip # Issue #26377
-
[ $runtime == vm || $runtime == dart_app || $runtime == dart_precompiled ]
deferred_transitive_import_error_test: Skip # Contains intentional errors.
diff --git a/tools/VERSION b/tools/VERSION
index 9cb94bc..ba2e5eb 100644
--- a/tools/VERSION
+++ b/tools/VERSION
@@ -28,5 +28,5 @@
MAJOR 1
MINOR 21
PATCH 0
-PRERELEASE 0
+PRERELEASE 1
PRERELEASE_PATCH 0
diff --git a/tools/dom/templates/html/dart2js/html_dart2js.darttemplate b/tools/dom/templates/html/dart2js/html_dart2js.darttemplate
index a2bd1e8..d15ba93 100644
--- a/tools/dom/templates/html/dart2js/html_dart2js.darttemplate
+++ b/tools/dom/templates/html/dart2js/html_dart2js.darttemplate
@@ -116,7 +116,8 @@
/**
* Root node for all content in a web page.
*/
-HtmlDocument get document => JS('HtmlDocument', 'document');
+HtmlDocument get document =>
+ JS('returns:HtmlDocument;depends:none;effects:none;gvn:true', 'document');
// Workaround for tags like <cite> that lack their own Element subclass --
// Dart issue 1990.
diff --git a/tools/dom/templates/html/impl/impl_Comment.darttemplate b/tools/dom/templates/html/impl/impl_Comment.darttemplate
index dc6e574..9934bb0 100644
--- a/tools/dom/templates/html/impl/impl_Comment.darttemplate
+++ b/tools/dom/templates/html/impl/impl_Comment.darttemplate
@@ -8,10 +8,8 @@
$(ANNOTATIONS)$(NATIVESPEC)$(CLASS_MODIFIERS)class $CLASSNAME$EXTENDS$MIXINS$IMPLEMENTS {
$if DART2JS
factory Comment([String data]) {
- if (data != null) {
- return JS('Comment', '#.createComment(#)', document, data);
- }
- return JS('Comment', '#.createComment("")', document);
+ return JS('returns:Comment;depends:none;effects:none;new:true',
+ '#.createComment(#)', document, data == null ? "" : data);
}
$endif
$!MEMBERS}
diff --git a/tools/dom/templates/html/impl/impl_Text.darttemplate b/tools/dom/templates/html/impl/impl_Text.darttemplate
index 8c53058..a459077 100644
--- a/tools/dom/templates/html/impl/impl_Text.darttemplate
+++ b/tools/dom/templates/html/impl/impl_Text.darttemplate
@@ -7,6 +7,12 @@
part of $LIBRARYNAME;
$(ANNOTATIONS)$(NATIVESPEC)$(CLASS_MODIFIERS)class $CLASSNAME$EXTENDS$IMPLEMENTS {
+$if DART2JS
+ factory $CLASSNAME(String data) =>
+ JS('returns:Text;depends:none;effects:none;new:true',
+ '#.createTextNode(#)', document, data);
+$else
factory $CLASSNAME(String data) => document._createTextNode(data);
+$endif
$!MEMBERS
}
diff --git a/tools/testing/dart/compiler_configuration.dart b/tools/testing/dart/compiler_configuration.dart
index 6cada5b..49368ce 100644
--- a/tools/testing/dart/compiler_configuration.dart
+++ b/tools/testing/dart/compiler_configuration.dart
@@ -78,11 +78,9 @@
useFastStartup: useFastStartup,
extraDart2jsOptions:
TestUtils.getExtraOptions(configuration, 'dart2js_options'));
+ case 'dart2appjit':
case 'dart2app':
return new Dart2AppSnapshotCompilerConfiguration(
- isDebug: isDebug, isChecked: isChecked);
- case 'dart2appjit':
- return new Dart2AppJitSnapshotCompilerConfiguration(
isDebug: isDebug, isChecked: isChecked, useBlobs: useBlobs);
case 'precompiler':
return new PrecompilerCompilerConfiguration(
@@ -502,8 +500,9 @@
}
class Dart2AppSnapshotCompilerConfiguration extends CompilerConfiguration {
- Dart2AppSnapshotCompilerConfiguration({bool isDebug, bool isChecked})
- : super._subclass(isDebug: isDebug, isChecked: isChecked);
+ final bool useBlobs;
+ Dart2AppSnapshotCompilerConfiguration({bool isDebug, bool isChecked, bool useBlobs})
+ : super._subclass(isDebug: isDebug, isChecked: isChecked), this.useBlobs = useBlobs;
int computeTimeoutMultiplier() {
int multiplier = 2;
@@ -530,10 +529,13 @@
CommandBuilder commandBuilder,
List arguments,
Map<String, String> environmentOverrides) {
- var exec = "$buildDir/dart_bootstrap";
+ var exec = "$buildDir/dart";
var args = new List();
args.add("--snapshot=$tempDir/out.jitsnapshot");
- args.add("--snapshot-kind=app-after-run");
+ args.add("--snapshot-kind=app-jit");
+ if (useBlobs) {
+ args.add("--use-blobs");
+ }
args.addAll(arguments);
return commandBuilder.getCompilationCommand(
@@ -579,37 +581,6 @@
}
}
-class Dart2AppJitSnapshotCompilerConfiguration extends Dart2AppSnapshotCompilerConfiguration {
- final bool useBlobs;
- Dart2AppJitSnapshotCompilerConfiguration({bool isDebug, bool isChecked, bool useBlobs})
- : super(isDebug: isDebug, isChecked: isChecked), this.useBlobs = useBlobs;
-
- CompilationCommand computeCompilationCommand(
- String tempDir,
- String buildDir,
- CommandBuilder commandBuilder,
- List arguments,
- Map<String, String> environmentOverrides) {
- var exec = "$buildDir/dart";
- var args = new List();
- args.add("--snapshot=$tempDir/out.jitsnapshot");
- args.add("--snapshot-kind=app-jit-after-run");
- if (useBlobs) {
- args.add("--use-blobs");
- }
- args.addAll(arguments);
-
- return commandBuilder.getCompilationCommand(
- 'dart2snapshot',
- tempDir,
- !useSdk,
- bootstrapDependencies(buildDir),
- exec,
- args,
- environmentOverrides);
- }
-}
-
class AnalyzerCompilerConfiguration extends CompilerConfiguration {
AnalyzerCompilerConfiguration(
{bool isDebug, bool isChecked, bool isStrong, bool isHostChecked, bool
diff --git a/tools/testing/dart/test_options.dart b/tools/testing/dart/test_options.dart
index 936bb39..255564a 100644
--- a/tools/testing/dart/test_options.dart
+++ b/tools/testing/dart/test_options.dart
@@ -73,8 +73,9 @@
dart2analyzer: Perform static analysis on Dart code by running the analyzer
(only valid with the following runtimes: none)
- dart2app: Compile the Dart code into an app snapshot before running the test
- (only valid with the following runtimes: dart_app)''',
+ dart2app:
+ dart2appjit: Compile the Dart code into an app snapshot before running test
+ (only valid with dart_app runtime)''',
['-c', '--compiler'],
['none', 'precompiler', 'dart2js', 'dart2analyzer', 'dart2app', 'dart2appjit'],
'none'),
@@ -670,8 +671,6 @@
validRuntimes = const ['none'];
break;
case 'dart2app':
- validRuntimes = const ['dart_app'];
- break;
case 'dart2appjit':
validRuntimes = const ['dart_app'];
break;
diff --git a/tools/testing/dart/test_runner.dart b/tools/testing/dart/test_runner.dart
index 05f06a2..00a2ebb 100644
--- a/tools/testing/dart/test_runner.dart
+++ b/tools/testing/dart/test_runner.dart
@@ -2582,7 +2582,6 @@
// directory.
List<String> files = new io.Directory(testdir)
.listSync()
- .where((fse) => fse is io.File)
.map((file) => file.path)
.map((path) => path.substring(path.lastIndexOf('/') + 1))
.toList();