Fix #32227 export dynamic from dart:core in analyzer.

Assign dynamic to dart:core in NamespaceBuilder & LibraryScope

This seems to be the best two places to hit up all cases. We need two to
handle the case of where code imports dart:core, vs code that is itself
the definition of dart:core.

Includes a member sort of compile_time_error_code_kernel_test, so that
pollutes the diff a bit, but not importantly so and its good to get that
sorted.

Bug: 32227
Change-Id: Ibe620f4b66a35d088355f36da042a5d82380772c
Reviewed-on: https://dart-review.googlesource.com/62730
Commit-Queue: Mike Fairhurst <mfairhurst@google.com>
Reviewed-by: Brian Wilkerson <brianwilkerson@google.com>
diff --git a/pkg/analyzer/lib/src/dart/element/element.dart b/pkg/analyzer/lib/src/dart/element/element.dart
index 204b22f..d38993a 100644
--- a/pkg/analyzer/lib/src/dart/element/element.dart
+++ b/pkg/analyzer/lib/src/dart/element/element.dart
@@ -1213,9 +1213,8 @@
         visitedClasses.add(this);
       }
       try {
-        ClassElementImpl superElement =
-            AbstractClassElementImpl.getImpl(supertype.element)
-                as ClassElementImpl;
+        ClassElementImpl superElement = AbstractClassElementImpl
+            .getImpl(supertype.element) as ClassElementImpl;
         constructorsToForward =
             superElement._computeMixinAppConstructors(visitedClasses);
       } finally {
@@ -2811,6 +2810,8 @@
   @override
   DynamicTypeImpl type;
 
+  LibraryElement _library;
+
   /**
    * Initialize a newly created instance of this class. Instances of this class
    * should <b>not</b> be created except as part of creating the type associated
@@ -2825,6 +2826,13 @@
   ElementKind get kind => ElementKind.DYNAMIC;
 
   @override
+  LibraryElement get library => _library;
+  set library(LibraryElement library) {
+    assert(library.name == 'dart.core');
+    _library = library;
+  }
+
+  @override
   T accept<T>(ElementVisitor<T> visitor) => null;
 }
 
@@ -4593,8 +4601,8 @@
             ImportElementImpl._buildCombinatorsForKernel(_kernel.combinators);
       }
       if (_unlinkedExportPublic != null) {
-        _combinators = ImportElementImpl._buildCombinators(
-            _unlinkedExportPublic.combinators);
+        _combinators = ImportElementImpl
+            ._buildCombinators(_unlinkedExportPublic.combinators);
       }
     }
     return _combinators ?? const <NamespaceCombinator>[];
@@ -5146,9 +5154,8 @@
 
   @override
   List<ParameterElement> get parameters {
-    return _parameters ??= ParameterElementImpl.resynthesizeList(
-        _entityRef.syntheticParams, this,
-        synthetic: true);
+    return _parameters ??= ParameterElementImpl
+        .resynthesizeList(_entityRef.syntheticParams, this, synthetic: true);
   }
 
   @override
diff --git a/pkg/analyzer/lib/src/dart/resolver/scope.dart b/pkg/analyzer/lib/src/dart/resolver/scope.dart
index a5533a8..87a6197 100644
--- a/pkg/analyzer/lib/src/dart/resolver/scope.dart
+++ b/pkg/analyzer/lib/src/dart/resolver/scope.dart
@@ -585,6 +585,14 @@
   LibraryScope(LibraryElement definingLibrary)
       : super(new LibraryImportScope(definingLibrary)) {
     _defineTopLevelNames(definingLibrary);
+
+    // For `dart:core` to be able to pass analysis, it has to have `dynamic`
+    // added to its library scope. Note that this is not true of, for instance,
+    // `Object`, because `Object` has a source definition which is not possible
+    // for `dynamic`.
+    if (definingLibrary.isDartCore) {
+      define(DynamicElementImpl.instance);
+    }
   }
 
   @override
@@ -749,6 +757,16 @@
     for (CompilationUnitElement compilationUnit in library.parts) {
       _addPublicNames(definedNames, compilationUnit);
     }
+
+    // For libraries that import `dart:core` with a prefix, we have to add
+    // `dynamic` to the `dart:core` [Namespace] specially. Note that this is not
+    // true of, for instance, `Object`, because `Object` has a source definition
+    // which is not possible for `dynamic`.
+    if (library.isDartCore) {
+      DynamicElementImpl.instance.library = library;
+      definedNames['dynamic'] = DynamicElementImpl.instance;
+    }
+
     return new Namespace(definedNames);
   }
 
diff --git a/pkg/analyzer/lib/src/generated/resolver.dart b/pkg/analyzer/lib/src/generated/resolver.dart
index 86b7b5f..1371020 100644
--- a/pkg/analyzer/lib/src/generated/resolver.dart
+++ b/pkg/analyzer/lib/src/generated/resolver.dart
@@ -8284,16 +8284,6 @@
       // neither of which are in the name scope and hence will not be found by
       // normal means.
       //
-      if (typeName.name == dynamicType.name) {
-        _setElement(typeName, dynamicType.element);
-//        if (argumentList != null) {
-//          // TODO(brianwilkerson) Report this error
-//          reporter.reportError(StaticTypeWarningCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS, node, dynamicType.getName(), 0, argumentList.getArguments().size());
-//        }
-        typeName.staticType = dynamicType;
-        node.type = dynamicType;
-        return;
-      }
       VoidTypeImpl voidType = VoidTypeImpl.instance;
       if (typeName.name == voidType.name) {
         // There is no element for 'void'.
@@ -8464,6 +8454,17 @@
         return;
       }
       _setElement(typeName, element);
+    } else if (element is TypeDefiningElement &&
+        element.kind == ElementKind.DYNAMIC) {
+//      if (argumentList != null) {
+//        // Type parameters cannot have type arguments.
+//        // TODO(mfairhurst) Report this error.
+//        resolver.reportError(ResolverErrorCode.?, keyType);
+//      }
+      _setElement(typeName, element);
+      typeName.staticType = element.type;
+      node.type = element.type;
+      return;
     } else if (element is FunctionTypeAliasElement) {
       _setElement(typeName, element);
       type = element.type;
@@ -10521,6 +10522,10 @@
     // If the type is not an InterfaceType, then visitTypeName() sets the type
     // to be a DynamicTypeImpl
     Identifier name = typeName.name;
+    // TODO(mfairhurst) differentiate between dynamic via clean path, and error
+    // types, and then check `type.isDynamic`. However, if we do that now, then
+    // [nonTypeError] will never be reported because non types are resolved to
+    // dynamic.
     if (name.name == Keyword.DYNAMIC.lexeme) {
       errorReporter.reportErrorForNode(dynamicTypeError, name, [name.name]);
     } else if (!nameScope.shouldIgnoreUndefined(name)) {
diff --git a/pkg/analyzer/test/generated/compile_time_error_code_kernel_test.dart b/pkg/analyzer/test/generated/compile_time_error_code_kernel_test.dart
index 1fca424..a025360 100644
--- a/pkg/analyzer/test/generated/compile_time_error_code_kernel_test.dart
+++ b/pkg/analyzer/test/generated/compile_time_error_code_kernel_test.dart
@@ -76,6 +76,14 @@
 
   @override
   @failingTest
+  @potentialAnalyzerProblem
+  test_builtInIdentifierAsType_dynamicMissingPrefix() async {
+    // Kernel and analyzer report different errors. Which is the correct one?
+    await super.test_builtInIdentifierAsType_dynamicMissingPrefix();
+  }
+
+  @override
+  @failingTest
   test_builtInIdentifierAsType_formalParameter_field() async {
     // Expected 1 errors of type CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE, found 0;
     //          0 errors of type ParserErrorCode.EXTRANEOUS_MODIFIER, found 1 (23)
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 93be0e7..3edfff2 100644
--- a/pkg/analyzer/test/generated/compile_time_error_code_test.dart
+++ b/pkg/analyzer/test/generated/compile_time_error_code_test.dart
@@ -586,6 +586,16 @@
     verify([source]);
   }
 
+  test_builtInIdentifierAsType_dynamicMissingPrefix() async {
+    Source source = addSource(r"""
+import 'dart:core' as core;
+
+dynamic x;
+""");
+    await computeAnalysisResult(source);
+    assertErrors(source, [CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE]);
+  }
+
   test_builtInIdentifierAsMixinName_classTypeAlias() async {
     Source source = addSource(r'''
 class A {}
diff --git a/pkg/analyzer/test/generated/non_error_resolver_test.dart b/pkg/analyzer/test/generated/non_error_resolver_test.dart
index 66226b3..679a8d5 100644
--- a/pkg/analyzer/test/generated/non_error_resolver_test.dart
+++ b/pkg/analyzer/test/generated/non_error_resolver_test.dart
@@ -6409,6 +6409,17 @@
     verify([source]);
   }
 
+  Future test_useDynamicWithPrefix() async {
+    final Source source = addSource('''
+import 'dart:core' as core;
+
+core.dynamic dynamicVariable;
+''');
+    await computeAnalysisResult(source);
+    assertNoErrors(source);
+    verify([source]);
+  }
+
   Future<Null> _check_wrongNumberOfParametersForOperator(
       String name, String parameters) async {
     Source source = addSource("""
diff --git a/tests/compiler/dart2js/sourcemaps/data/invokes.dart b/tests/compiler/dart2js/sourcemaps/data/invokes.dart
index 53e84d3..a48a4ae 100644
--- a/tests/compiler/dart2js/sourcemaps/data/invokes.dart
+++ b/tests/compiler/dart2js/sourcemaps/data/invokes.dart
@@ -124,7 +124,7 @@
   invalidInvokes() {
     // ignore: not_enough_required_arguments
     C();
-    // ignore: undefined_method
+    // ignore: invocation_of_non_function
     dynamic();
     // ignore: invocation_of_non_function
     F();
diff --git a/tests/language_2/language_2_analyzer.status b/tests/language_2/language_2_analyzer.status
index 3079a5a..530aaec 100644
--- a/tests/language_2/language_2_analyzer.status
+++ b/tests/language_2/language_2_analyzer.status
@@ -100,7 +100,6 @@
 deferred_inheritance_constraints_test/redirecting_constructor: MissingCompileTimeError
 dynamic_field_test/01: MissingCompileTimeError
 dynamic_field_test/02: MissingCompileTimeError
-dynamic_prefix_core_test/01: MissingCompileTimeError
 emit_const_fields_test: Pass
 empty_block_case_test: MissingCompileTimeError
 enum_private_test/02: MissingCompileTimeError
@@ -499,7 +498,6 @@
 deferred_inheritance_constraints_test/redirecting_constructor: MissingCompileTimeError
 dynamic_field_test/01: MissingCompileTimeError
 dynamic_field_test/02: MissingCompileTimeError
-dynamic_prefix_core_test/01: MissingCompileTimeError
 emit_const_fields_test: Pass
 empty_block_case_test: MissingCompileTimeError
 enum_private_test/02: MissingCompileTimeError
@@ -848,6 +846,7 @@
 deep_nesting2_negative_test: CompileTimeError # Issue 25558
 duplicate_export_negative_test: CompileTimeError
 duplicate_interface_negative_test: CompileTimeError
+dynamic_prefix_core_test/01: MissingCompileTimeError
 emit_const_fields_test: CompileTimeError
 enum_syntax_test/05: Fail # Issue 21649
 enum_syntax_test/06: Fail # Issue 21649
@@ -869,7 +868,6 @@
 implicit_creation/implicit_const_context_constructor_generic_test: CompileTimeError
 implicit_creation/implicit_const_context_prefix_constructor_generic_named_test: CompileTimeError
 implicit_creation/implicit_const_context_prefix_constructor_generic_test: CompileTimeError
-import_core_prefix_test: StaticWarning
 index_assign_operator_infer_return_type_test: StaticWarning
 initializing_formal_final_test: MissingCompileTimeError
 inst_field_initializer1_negative_test: CompileTimeError
@@ -1138,7 +1136,6 @@
 generic_methods_generic_function_result_test/none: CompileTimeError # Issue #30207
 generic_no_such_method_dispatcher_test: CompileTimeError
 generic_tearoff_test: CompileTimeError
-import_core_prefix_test: CompileTimeError # "dynamic" should be defined in core.
 interceptor6_test: CompileTimeError
 issue13673_test: StaticWarning # Issue 31925
 issue15606_test/none: CompileTimeError # invalid use of void for dart 2
diff --git a/tests/language_2/language_2_dartdevc.status b/tests/language_2/language_2_dartdevc.status
index 580b5cd..bd43f56 100644
--- a/tests/language_2/language_2_dartdevc.status
+++ b/tests/language_2/language_2_dartdevc.status
@@ -43,6 +43,7 @@
 default_implementation2_test: CompileTimeError # Issue 30855
 deferred_load_library_wrong_args_test/01: MissingRuntimeError, RuntimeError # Issue 29920
 double_identical_test: RuntimeError # Negative and positive zero are distinct, but not in ddc
+dynamic_prefix_core_test/01: MissingCompileTimeError
 emit_const_fields_test: CompileTimeError
 enum_syntax_test/05: MissingCompileTimeError
 enum_syntax_test/06: MissingCompileTimeError
@@ -72,7 +73,6 @@
 implicit_downcast_during_compound_assignment_test: RuntimeError
 implicit_downcast_during_indexed_compound_assignment_test: RuntimeError
 implicit_downcast_during_indexed_if_null_assignment_test: RuntimeError
-import_core_prefix_test: CompileTimeError
 import_private_test/01: MissingCompileTimeError # Issue 29920
 initializing_formal_final_test: MissingCompileTimeError
 instantiate_tearoff_after_contravariance_check_test: RuntimeError