Version 2.16.0-80.1.beta

Merge '2.16.0-80.0.dev' into beta
diff --git a/.dart_tool/package_config.json b/.dart_tool/package_config.json
index 981de4b..d50d6f5 100644
--- a/.dart_tool/package_config.json
+++ b/.dart_tool/package_config.json
@@ -11,7 +11,7 @@
     "constraint, update this by running tools/generate_package_config.dart."
   ],
   "configVersion": 2,
-  "generated": "2021-10-26T10:20:01.277340",
+  "generated": "2021-11-15T17:34:02.415038",
   "generator": "tools/generate_package_config.dart",
   "packages": [
     {
@@ -88,7 +88,7 @@
       "name": "analyzer_cli",
       "rootUri": "../pkg/analyzer_cli",
       "packageUri": "lib/",
-      "languageVersion": "2.7"
+      "languageVersion": "2.14"
     },
     {
       "name": "analyzer_plugin",
@@ -124,7 +124,7 @@
       "name": "bazel_worker",
       "rootUri": "../third_party/pkg/bazel_worker",
       "packageUri": "lib/",
-      "languageVersion": "2.12"
+      "languageVersion": "2.14"
     },
     {
       "name": "benchmark_harness",
@@ -659,7 +659,7 @@
       "name": "stream_channel",
       "rootUri": "../third_party/pkg/stream_channel",
       "packageUri": "lib/",
-      "languageVersion": "2.10"
+      "languageVersion": "2.14"
     },
     {
       "name": "string_scanner",
@@ -710,6 +710,11 @@
       "languageVersion": "2.12"
     },
     {
+      "name": "test_package",
+      "rootUri": "../pkg/vm_service/test/test_package",
+      "languageVersion": "2.12"
+    },
+    {
       "name": "test_process",
       "rootUri": "../third_party/pkg/test_process",
       "packageUri": "lib/",
diff --git a/.packages b/.packages
index 568fa66..f5ea5bc 100644
--- a/.packages
+++ b/.packages
@@ -105,6 +105,7 @@
 test_api:third_party/pkg/test/pkgs/test_api/lib
 test_core:third_party/pkg/test/pkgs/test_core/lib
 test_descriptor:third_party/pkg/test_descriptor/lib
+test_package:pkg/vm_service/test/test_package
 test_process:third_party/pkg/test_process/lib
 test_reflective_loader:third_party/pkg/test_reflective_loader/lib
 test_runner:pkg/test_runner/lib
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 68af803..2c48329 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,41 @@
+## 2.16.0
+
+### Core libraries
+
+#### `dart:core`
+
+- **Breaking Change** [#47653](https://github.com/dart-lang/sdk/issues/47653):
+  On Windows, `Directory.rename` will no longer delete a directory if
+  `newPath` specifies one. Instead, a `FileSystemException` will be thrown.
+
+- Add `Error.throwWithStackTrace` which can `throw` an
+  error with an existing stack trace, instead of creating
+  a new stack trace.
+
+### Tools
+
+#### Dart command line
+
+- **Breaking Change** [#46100](https://github.com/dart-lang/sdk/issues/46100):
+  The standalone `dartanalyzer` tool has been
+  marked deprecated as previously announced.
+  Its replacement is the `dart analyze` command.
+  Should you find any issues, or missing features, in the replacement
+  command, kindly file [an issue][].
+
+[an issue]: https://github.com/dart-lang/sdk/issues/new
+
+#### Linter
+
+Updated the Linter to `1.15.0`, which includes changes that
+- adds new lint: `use_decorated_box`.
+- adds new lint: `no_leading_underscores_for_library_prefixes`.
+- adds new lint: `no_leading_underscores_for_local_identifiers`.
+- adds new lint: `secure_pubspec_urls`.
+- adds new lint: `sized_box_shrink_expand`.
+- adds new lint: `avoid_final_parameters`.
+- improves docs for `omit_local_variable_types`.
+
 ## 2.15.0
 
 ### Language
diff --git a/DEPS b/DEPS
index cb395cc..cec2977 100644
--- a/DEPS
+++ b/DEPS
@@ -39,21 +39,22 @@
 
   # Checked-in SDK version. The checked-in SDK is a Dart SDK distribution in a
   # cipd package used to run Dart scripts in the build and test infrastructure.
-  "sdk_tag": "version:2.15.0-82.0.dev",
+  "sdk_tag": "version:2.15.0-268.8.beta",
 
   # co19 is a cipd package. Use update.sh in tests/co19[_2] to update these
   # hashes. It requires access to the dart-build-access group, which EngProd
   # has.
-  "co19_rev": "73545b2bf6c7f8e4eb931bb04d86e38d6485deee",
+  "co19_rev": "4ef349830b971c22d8ddb2970c4ba9002806fd85",
   # This line prevents conflicts when both packages are rolled simultaneously.
-  "co19_2_rev": "52d3d2a6d2550ccd69c8facf8a36099be66f1493",
+  "co19_2_rev": "995745937abffe9fc3a6441f9f0db27b2d706e4c",
 
   # The internal benchmarks to use. See go/dart-benchmarks-internal
   "benchmarks_internal_rev": "076df10d9b77af337f2d8029725787155eb1cd52",
   "checkout_benchmarks_internal": False,
 
   # Checkout Android dependencies only on Mac and Linux.
-  "download_android_deps": 'host_os == "mac" or host_os == "linux"',
+  "download_android_deps":
+    "(host_os == mac or host_os == linux) and host_cpu == x64",
 
   # Checkout extra javascript engines for testing or benchmarking.
   # d8, the V8 shell, is always checked out.
@@ -64,8 +65,8 @@
   # The list of revisions for these tools comes from Fuchsia, here:
   # https://fuchsia.googlesource.com/integration/+/HEAD/prebuilts
   # If there are problems with the toolchain, contact fuchsia-toolchain@.
-  "clang_revision": "f37e8b0b831e61d3b6033829fff05d6d193ab735",
-  "gn_revision": "693f9fb87e4febdd4299db9f73d8d2c958e63148",
+  "clang_revision": "e3a7f0e2f9ab566bd9b71fb54fe77e947b061a12",
+  "gn_revision": "b79031308cc878488202beb99883ec1f2efd9a6d",
 
   # Scripts that make 'git cl format' work.
   "clang_format_scripts_rev": "c09c8deeac31f05bd801995c475e7c8070f9ecda",
@@ -75,11 +76,11 @@
   # Revisions of /third_party/* dependencies.
   "args_rev": "3b3f55766af13d895d2020ec001a28e8dc147f91",
   "async_rev": "80886150a5e6c58006c8ae5a6c2aa7108638e2a9",
-  "bazel_worker_rev": "0885637b037979afbf5bcd05fd748b309fd669c0",
+  "bazel_worker_rev": "ceeba0982d4ff40d32371c9d35f3d2dc1868de20",
   "benchmark_harness_rev": "c546dbd9f639f75cd2f75de8df2eb9f8ea15e8e7",
   "boolean_selector_rev": "665e6921ab246569420376f827bff4585dff0b14",
-  "boringssl_gen_rev": "7322fc15cc065d8d2957fccce6b62a509dc4d641",
-  "boringssl_rev" : "1607f54fed72c6589d560254626909a64124f091",
+  "boringssl_gen_rev": "ced85ef0a00bbca77ce5a91261a5f2ae61b1e62f",
+  "boringssl_rev" : "87f316d7748268eb56f2dc147bd593254ae93198",
   "browser-compat-data_tag": "v1.0.22",
   "browser_launcher_rev": "c6cc1025d6901926cf022e144ba109677e3548f1",
   "characters_rev": "6ec389c4dfa8fce14820dc5cbf6e693202e7e052",
@@ -90,7 +91,7 @@
   "collection_rev": "a4c941ab94044d118b2086a3f261c30377604127",
   "convert_rev": "e063fdca4bebffecbb5e6aa5525995120982d9ce",
   "crypto_rev": "b5024e4de2b1c474dd558bef593ddbf0bfade152",
-  "csslib_rev": "6f35da3d93eb56eb25925779d235858d4090ce6f",
+  "csslib_rev": "02abc1ddf93092efef2be365300f15504d23cd23",
 
   # Note: Updates to dart_style have to be coordinated with the infrastructure
   # team so that the internal formatter `tools/sdks/dart-sdk/bin/dart format`
@@ -106,8 +107,8 @@
   # For more details, see https://github.com/dart-lang/sdk/issues/30164
   "dart_style_rev": "08b0294d0a500d5c02168ef57dcb8868d0c3cb48",
 
-  "dartdoc_rev" : "520e64977de7a87b2fd5be56e5c2e1a58d55bdad",
-  "devtools_rev" : "3a2f570813200e6dee141f3e7a9edcae5f31c2e8",
+  "dartdoc_rev" : "ff0d94bdb87f11c04a7e0ddab811bf94211b08a4",
+  "devtools_rev" : "f2ede24a4ea666d4832d78b813c7d4e376aa77d0",
   "jsshell_tag": "version:88.0",
   "ffi_rev": "4dd32429880a57b64edaf54c9d5af8a9fa9a4ffb",
   "fixnum_rev": "16d3890c6dc82ca629659da1934e412292508bba",
@@ -122,11 +123,11 @@
   "intl_tag": "0.17.0-nullsafety",
   "jinja2_rev": "2222b31554f03e62600cd7e383376a7c187967a1",
   "json_rpc_2_rev": "7e00f893440a72de0637970325e4ea44bd1e8c8e",
-  "linter_tag": "1.14.0",
+  "linter_tag": "1.15.0",
   "lints_tag": "f9670df2a66e0ec12eb51554e70c1cbf56c8f5d0",
   "logging_rev": "575781ef196e4fed4fb737e38fb4b73d62727187",
   "markupsafe_rev": "8f45f5cfa0009d2a70589bcda0349b8cb2b72783",
-  "markdown_rev": "9c4beaac96d8f008078e00b027915f81b665d2de",
+  "markdown_rev": "7479783f0493f6717e1d7ae31cb37d39a91026b2",
   "matcher_rev": "6ba4a6d68bdfacff3d572c9ea98333dfc66fd6bf",
   "mime_rev": "c931f4bed87221beaece356494b43731445ce7b8",
   "mockito_rev": "d39ac507483b9891165e422ec98d9fb480037c8b",
@@ -139,7 +140,7 @@
   "pool_rev": "7abe634002a1ba8a0928eded086062f1307ccfae",
   "process_rev": "56ece43b53b64c63ae51ec184b76bd5360c28d0b",
   "protobuf_rev": "c1eb6cb51af39ccbaa1a8e19349546586a5c8e31",
-  "pub_rev": "96404e0749864c9fbf8b12e1d424e8078809e00a",
+  "pub_rev": "dcb6abac2d7d43258c03b348be42bf4aab9529b1",
   "pub_semver_rev": "a43ad72fb6b7869607581b5fedcb186d1e74276a",
   "root_certificates_rev": "692f6d6488af68e0121317a9c2c9eb393eb0ee50",
   "rust_revision": "b7856f695d65a8ebc846754f97d15814bcb1c244",
@@ -153,8 +154,8 @@
   "source_maps_rev": "6499ee3adac8d469e2953e2e8ba4bdb4c2fbef90",
   "source_span_rev": "1be3c44045a06dff840d2ed3a13e6082d7a03a23",
   "sse_rev": "9084339389eb441d0c0518cddac211a097e78657",
-  "stack_trace_rev": "6788afc61875079b71b3d1c3e65aeaa6a25cbc2f",
-  "stream_channel_rev": "d7251e61253ec389ee6e045ee1042311bced8f1d",
+  "stack_trace_rev": "5220580872625ddee41e9ca9a5f3364789b2f0f6",
+  "stream_channel_rev": "3fa3e40c75c210d617b8b943b9b8f580e9866a89",
   "string_scanner_rev": "1b63e6e5db5933d7be0a45da6e1129fe00262734",
   "sync_http_rev": "b59c134f2e34d12acac110d4f17f83e5a7db4330",
   "test_descriptor_rev": "ead23c1e7df079ac0f6457a35f7a71432892e527",
@@ -655,6 +656,15 @@
       ],
           "dep_type": "cipd",
   },
+  Var("dart_root") + "/benchmarks/NativeCall/native/out/": {
+      "packages": [
+          {
+              "package": "dart/benchmarks/nativecall",
+              "version": "w1JKzCIHSfDNIjqnioMUPq0moCXKwX67aUfhyrvw4E0C",
+          },
+      ],
+          "dep_type": "cipd",
+  },
   Var("dart_root") + "/third_party/browsers/chrome": {
       "packages": [
           {
diff --git a/benchmarks/FfiAsTypedList/dart/FfiAsTypedList.dart b/benchmarks/FfiAsTypedList/dart/FfiAsTypedList.dart
new file mode 100644
index 0000000..f32f5d0
--- /dev/null
+++ b/benchmarks/FfiAsTypedList/dart/FfiAsTypedList.dart
@@ -0,0 +1,49 @@
+// Copyright (c) 2021, the Dart project authors.  Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+// Micro-benchmark for creating TypeData lists from Pointers.
+//
+// The FfiMemory benchmark tests accessing memory through TypedData.
+
+import 'dart:ffi';
+
+import 'package:benchmark_harness/benchmark_harness.dart';
+import 'package:ffi/ffi.dart';
+
+//
+// Benchmark fixture.
+//
+
+// Number of repeats: 1000
+const N = 1000;
+
+class FromPointerInt8 extends BenchmarkBase {
+  Pointer<Int8> pointer = nullptr;
+  FromPointerInt8() : super('FfiAsTypedList.FromPointerInt8');
+
+  @override
+  void setup() => pointer = calloc(1);
+  @override
+  void teardown() => calloc.free(pointer);
+
+  @override
+  void run() {
+    for (var i = 0; i < N; i++) {
+      pointer.asTypedList(1);
+    }
+  }
+}
+
+//
+// Main driver.
+//
+
+void main() {
+  final benchmarks = [
+    () => FromPointerInt8(),
+  ];
+  for (final benchmark in benchmarks) {
+    benchmark().report();
+  }
+}
diff --git a/benchmarks/FfiAsTypedList/dart2/FfiAsTypedList.dart b/benchmarks/FfiAsTypedList/dart2/FfiAsTypedList.dart
new file mode 100644
index 0000000..bab621d
--- /dev/null
+++ b/benchmarks/FfiAsTypedList/dart2/FfiAsTypedList.dart
@@ -0,0 +1,51 @@
+// Copyright (c) 2021, the Dart project authors.  Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+// Micro-benchmark for creating TypeData lists from Pointers.
+//
+// The FfiMemory benchmark tests accessing memory through TypedData.
+
+// @dart=2.9
+
+import 'dart:ffi';
+
+import 'package:benchmark_harness/benchmark_harness.dart';
+import 'package:ffi/ffi.dart';
+
+//
+// Benchmark fixture.
+//
+
+// Number of repeats: 1000
+const N = 1000;
+
+class FromPointerInt8 extends BenchmarkBase {
+  Pointer<Int8> pointer = nullptr;
+  FromPointerInt8() : super('FfiAsTypedList.FromPointerInt8');
+
+  @override
+  void setup() => pointer = calloc(1);
+  @override
+  void teardown() => calloc.free(pointer);
+
+  @override
+  void run() {
+    for (var i = 0; i < N; i++) {
+      pointer.asTypedList(1);
+    }
+  }
+}
+
+//
+// Main driver.
+//
+
+void main() {
+  final benchmarks = [
+    () => FromPointerInt8(),
+  ];
+  for (final benchmark in benchmarks) {
+    benchmark().report();
+  }
+}
diff --git a/benchmarks/IsolateFibonacci/dart/IsolateFibonacci.dart b/benchmarks/IsolateFibonacci/dart/IsolateFibonacci.dart
index 84b7572..4af3028 100644
--- a/benchmarks/IsolateFibonacci/dart/IsolateFibonacci.dart
+++ b/benchmarks/IsolateFibonacci/dart/IsolateFibonacci.dart
@@ -34,8 +34,7 @@
   final rpRun = ReceivePort();
   final int nWarmup = 17; // enough runs to trigger optimized compilation
   final int nWarmupFactorial = 2584;
-  // With --enable-isolate-groups runs for about 8 seconds.
-  // Should not be run witout --enable-isolate-groups as it would be too slow.
+  // Runs for about 8 seconds.
   final int n = 21;
   final int nFactorial = 17711;
   final beforeRss = ProcessInfo.currentRss;
@@ -48,8 +47,7 @@
   final watch = Stopwatch();
   watch.start();
 
-  // For the benefit of enable-isolate-groups configuration, warm up target
-  // isolate code by running couple iterations in the main isolate.
+  // Warm up code by running a couple iterations in the main isolate.
   await Isolate.spawn(fibonacciRecursive, [rpWarmup.sendPort, nWarmup]);
   Expect.equals(nWarmupFactorial, await rpWarmup.first);
 
@@ -60,7 +58,7 @@
 
   final done = watch.elapsedMicroseconds;
 
-  print('IsolateFibonacci_$n.Calculation(RunTimeRaw): ${done-warmup} us.');
-  print('IsolateFibonacci_$n.DeltaPeak(MemoryUse): ${maxRss-beforeRss}');
+  print('IsolateFibonacci_$n.Calculation(RunTimeRaw): ${done - warmup} us.');
+  print('IsolateFibonacci_$n.DeltaPeak(MemoryUse): ${maxRss - beforeRss}');
   rssTimer.cancel();
 }
diff --git a/benchmarks/IsolateFibonacci/dart2/IsolateFibonacci.dart b/benchmarks/IsolateFibonacci/dart2/IsolateFibonacci.dart
index 84b7572..4af3028 100644
--- a/benchmarks/IsolateFibonacci/dart2/IsolateFibonacci.dart
+++ b/benchmarks/IsolateFibonacci/dart2/IsolateFibonacci.dart
@@ -34,8 +34,7 @@
   final rpRun = ReceivePort();
   final int nWarmup = 17; // enough runs to trigger optimized compilation
   final int nWarmupFactorial = 2584;
-  // With --enable-isolate-groups runs for about 8 seconds.
-  // Should not be run witout --enable-isolate-groups as it would be too slow.
+  // Runs for about 8 seconds.
   final int n = 21;
   final int nFactorial = 17711;
   final beforeRss = ProcessInfo.currentRss;
@@ -48,8 +47,7 @@
   final watch = Stopwatch();
   watch.start();
 
-  // For the benefit of enable-isolate-groups configuration, warm up target
-  // isolate code by running couple iterations in the main isolate.
+  // Warm up code by running a couple iterations in the main isolate.
   await Isolate.spawn(fibonacciRecursive, [rpWarmup.sendPort, nWarmup]);
   Expect.equals(nWarmupFactorial, await rpWarmup.first);
 
@@ -60,7 +58,7 @@
 
   final done = watch.elapsedMicroseconds;
 
-  print('IsolateFibonacci_$n.Calculation(RunTimeRaw): ${done-warmup} us.');
-  print('IsolateFibonacci_$n.DeltaPeak(MemoryUse): ${maxRss-beforeRss}');
+  print('IsolateFibonacci_$n.Calculation(RunTimeRaw): ${done - warmup} us.');
+  print('IsolateFibonacci_$n.DeltaPeak(MemoryUse): ${maxRss - beforeRss}');
   rssTimer.cancel();
 }
diff --git a/benchmarks/IsolateSpawnMemory/dart/IsolateSpawnMemory.dart b/benchmarks/IsolateSpawnMemory/dart/IsolateSpawnMemory.dart
index 1f7b009..0160c03 100644
--- a/benchmarks/IsolateSpawnMemory/dart/IsolateSpawnMemory.dart
+++ b/benchmarks/IsolateSpawnMemory/dart/IsolateSpawnMemory.dart
@@ -158,16 +158,6 @@
 }
 
 // Returns the set of isolate groups for which we should count the heap usage.
-//
-// We have two cases
-//
-//   a) --enable-isolate-groups: All isolates will be within the same isolate
-//   group.
-//
-//   b) --no-enable-isolate-groups: All isolates will be within their own,
-//   separate isolate group.
-//
-// In both cases we want to sum up the heap sizes of all isolate groups.
 Future<List<String>> getGroupIds(vm_service.VmService vmService) async {
   final groupIds = <String>{};
   final vm = await vmService.getVM();
diff --git a/benchmarks/IsolateSpawnMemory/dart2/IsolateSpawnMemory.dart b/benchmarks/IsolateSpawnMemory/dart2/IsolateSpawnMemory.dart
index 115e705..28fee38 100644
--- a/benchmarks/IsolateSpawnMemory/dart2/IsolateSpawnMemory.dart
+++ b/benchmarks/IsolateSpawnMemory/dart2/IsolateSpawnMemory.dart
@@ -160,16 +160,6 @@
 }
 
 // Returns the set of isolate groups for which we should count the heap usage.
-//
-// We have two cases
-//
-//   a) --enable-isolate-groups: All isolates will be within the same isolate
-//   group.
-//
-//   b) --no-enable-isolate-groups: All isolates will be within their own,
-//   separate isolate group.
-//
-// In both cases we want to sum up the heap sizes of all isolate groups.
 Future<List<String>> getGroupIds(vm_service.VmService vmService) async {
   final groupIds = <String>{};
   final vm = await vmService.getVM();
diff --git a/benchmarks/NativeCall/dart/NativeCall.dart b/benchmarks/NativeCall/dart/NativeCall.dart
new file mode 100644
index 0000000..c453038
--- /dev/null
+++ b/benchmarks/NativeCall/dart/NativeCall.dart
@@ -0,0 +1,277 @@
+// Copyright (c) 2021, the Dart project authors.  Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+// These micro benchmarks track the speed of native calls.
+
+import 'dart:ffi';
+import 'dart:io';
+
+import 'package:benchmark_harness/benchmark_harness.dart';
+
+import 'dlopen_helper.dart';
+
+// Number of benchmark iterations per function.
+const N = 1000;
+
+// The native library that holds all the native functions being called.
+final nativeFunctionsLib = dlopenPlatformSpecific('native_functions',
+    path: Platform.script.resolve('../native/out/').path);
+
+final getRootLibraryUrl = nativeFunctionsLib
+    .lookupFunction<Handle Function(), Object Function()>('GetRootLibraryUrl');
+
+final setNativeResolverForTest = nativeFunctionsLib.lookupFunction<
+    Void Function(Handle), void Function(Object)>('SetNativeResolverForTest');
+
+//
+// Benchmark fixtures.
+//
+
+abstract class NativeCallBenchmarkBase extends BenchmarkBase {
+  NativeCallBenchmarkBase(String name) : super(name);
+
+  void expectEquals(actual, expected) {
+    if (actual != expected) {
+      throw Exception('$name: Unexpected result: $actual, expected $expected');
+    }
+  }
+
+  void expectApprox(actual, expected) {
+    if (0.999 * expected > actual || actual > 1.001 * expected) {
+      throw Exception('$name: Unexpected result: $actual, expected $expected');
+    }
+  }
+
+  void expectIdentical(actual, expected) {
+    if (!identical(actual, expected)) {
+      throw Exception('$name: Unexpected result: $actual, expected $expected');
+    }
+  }
+}
+
+class Uint8x01 extends NativeCallBenchmarkBase {
+  Uint8x01() : super('NativeCall.Uint8x01');
+
+  @pragma('vm:external-name', 'Function1Uint8')
+  external static int f(int a);
+
+  @override
+  void run() {
+    int x = 0;
+    for (int i = 0; i < N; i++) {
+      x += f(17);
+    }
+    expectEquals(x, N * 17 + N * 42);
+  }
+}
+
+class Int64x20 extends NativeCallBenchmarkBase {
+  Int64x20() : super('NativeCall.Int64x20');
+
+  @pragma('vm:external-name', 'Function20Int64')
+  external static int f(
+      int a,
+      int b,
+      int c,
+      int d,
+      int e,
+      int f,
+      int g,
+      int h,
+      int i,
+      int j,
+      int k,
+      int l,
+      int m,
+      int n,
+      int o,
+      int p,
+      int q,
+      int r,
+      int s,
+      int t);
+
+  @override
+  void run() {
+    int x = 0;
+    for (int i = 0; i < N; i++) {
+      x += f(i, i, i, i, i, i, i, i, i, i, i, i, i, i, i, i, i, i, i, i);
+    }
+    expectEquals(x, N * (N - 1) * 20 / 2);
+  }
+}
+
+class Doublex01 extends NativeCallBenchmarkBase {
+  Doublex01() : super('NativeCall.Doublex01');
+
+  @pragma('vm:external-name', 'Function1Double')
+  external static double f(double a);
+
+  @override
+  void run() {
+    double x = 0.0;
+    for (int i = 0; i < N; i++) {
+      x += f(17.0);
+    }
+    final double expected = N * (17.0 + 42.0);
+    expectApprox(x, expected);
+  }
+}
+
+class Doublex20 extends NativeCallBenchmarkBase {
+  Doublex20() : super('NativeCall.Doublex20');
+
+  @pragma('vm:external-name', 'Function20Double')
+  external static double f(
+      double a,
+      double b,
+      double c,
+      double d,
+      double e,
+      double f,
+      double g,
+      double h,
+      double i,
+      double j,
+      double k,
+      double l,
+      double m,
+      double n,
+      double o,
+      double p,
+      double q,
+      double r,
+      double s,
+      double t);
+
+  @override
+  void run() {
+    double x = 0;
+    for (int i = 0; i < N; i++) {
+      x += f(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0,
+          13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0);
+    }
+    final double expected = N *
+        (1.0 +
+            2.0 +
+            3.0 +
+            4.0 +
+            5.0 +
+            6.0 +
+            7.0 +
+            8.0 +
+            9.0 +
+            10.0 +
+            11.0 +
+            12.0 +
+            13.0 +
+            14.0 +
+            15.0 +
+            16.0 +
+            17.0 +
+            18.0 +
+            19.0 +
+            20.0);
+    expectApprox(x, expected);
+  }
+}
+
+class MyClass {
+  int a;
+  MyClass(this.a);
+}
+
+class Handlex01 extends NativeCallBenchmarkBase {
+  Handlex01() : super('NativeCall.Handlex01');
+
+  @pragma('vm:external-name', 'Function1Handle')
+  external static Object f(Object a);
+
+  @override
+  void run() {
+    final p1 = MyClass(123);
+    Object x = p1;
+    for (int i = 0; i < N; i++) {
+      x = f(x);
+    }
+    expectIdentical(x, p1);
+  }
+}
+
+class Handlex20 extends NativeCallBenchmarkBase {
+  Handlex20() : super('NativeCall.Handlex20');
+
+  @pragma('vm:external-name', 'Function20Handle')
+  external static Object f(
+      Object a,
+      Object b,
+      Object c,
+      Object d,
+      Object e,
+      Object f,
+      Object g,
+      Object h,
+      Object i,
+      Object j,
+      Object k,
+      Object l,
+      Object m,
+      Object n,
+      Object o,
+      Object p,
+      Object q,
+      Object r,
+      Object s,
+      Object t);
+
+  @override
+  void run() {
+    final p1 = MyClass(123);
+    final p2 = MyClass(2);
+    final p3 = MyClass(3);
+    final p4 = MyClass(4);
+    final p5 = MyClass(5);
+    final p6 = MyClass(6);
+    final p7 = MyClass(7);
+    final p8 = MyClass(8);
+    final p9 = MyClass(9);
+    final p10 = MyClass(10);
+    final p11 = MyClass(11);
+    final p12 = MyClass(12);
+    final p13 = MyClass(13);
+    final p14 = MyClass(14);
+    final p15 = MyClass(15);
+    final p16 = MyClass(16);
+    final p17 = MyClass(17);
+    final p18 = MyClass(18);
+    final p19 = MyClass(19);
+    final p20 = MyClass(20);
+    Object x = p1;
+    for (int i = 0; i < N; i++) {
+      x = f(x, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15,
+          p16, p17, p18, p19, p20);
+    }
+    expectIdentical(x, p1);
+  }
+}
+
+//
+// Main driver.
+//
+
+void main() {
+  setNativeResolverForTest(getRootLibraryUrl());
+
+  final benchmarks = [
+    () => Uint8x01(),
+    () => Int64x20(),
+    () => Doublex01(),
+    () => Doublex20(),
+    () => Handlex01(),
+    () => Handlex20(),
+  ];
+  for (final benchmark in benchmarks) {
+    benchmark().report();
+  }
+}
diff --git a/benchmarks/NativeCall/dart/dlopen_helper.dart b/benchmarks/NativeCall/dart/dlopen_helper.dart
new file mode 100644
index 0000000..7e6129e
--- /dev/null
+++ b/benchmarks/NativeCall/dart/dlopen_helper.dart
@@ -0,0 +1,61 @@
+// Copyright (c) 2021, the Dart project authors.  Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'dart:ffi';
+import 'dart:io';
+
+const arm = 'arm';
+const arm64 = 'arm64';
+const ia32 = 'ia32';
+const x64 = 'x64';
+
+// https://stackoverflow.com/questions/45125516/possible-values-for-uname-m
+final _unames = {
+  'arm': arm,
+  'aarch64_be': arm64,
+  'aarch64': arm64,
+  'armv8b': arm64,
+  'armv8l': arm64,
+  'i386': ia32,
+  'i686': ia32,
+  'x86_64': x64,
+};
+
+String _checkRunningMode(String architecture) {
+  // Check if we're running in 32bit mode.
+  final int pointerSize = sizeOf<IntPtr>();
+  if (pointerSize == 4 && architecture == x64) return ia32;
+  if (pointerSize == 4 && architecture == arm64) return arm;
+
+  return architecture;
+}
+
+String _architecture() {
+  final String uname = Process.runSync('uname', ['-m']).stdout.trim();
+  final String? architecture = _unames[uname];
+  if (architecture == null) {
+    throw Exception('Unrecognized architecture: "$uname"');
+  }
+
+  // Check if we're running in 32bit mode.
+  return _checkRunningMode(architecture);
+}
+
+String _platformPath(String name, String path) {
+  if (Platform.isMacOS || Platform.isIOS) {
+    return '${path}mac/${_architecture()}/lib$name.dylib';
+  }
+
+  if (Platform.isWindows) {
+    return '${path}win/${_checkRunningMode(x64)}/$name.dll';
+  }
+
+  // Unknown platforms default to Unix implementation.
+  return '${path}linux/${_architecture()}/lib$name.so';
+}
+
+DynamicLibrary dlopenPlatformSpecific(String name, {String path = ''}) {
+  final String fullPath = _platformPath(name, path);
+  return DynamicLibrary.open(fullPath);
+}
diff --git a/benchmarks/NativeCall/dart2/NativeCall.dart b/benchmarks/NativeCall/dart2/NativeCall.dart
new file mode 100644
index 0000000..c2dbf13
--- /dev/null
+++ b/benchmarks/NativeCall/dart2/NativeCall.dart
@@ -0,0 +1,279 @@
+// Copyright (c) 2021, the Dart project authors.  Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+// These micro benchmarks track the speed of native calls.
+
+// @dart=2.9
+
+import 'dart:ffi';
+import 'dart:io';
+
+import 'package:benchmark_harness/benchmark_harness.dart';
+
+import 'dlopen_helper.dart';
+
+// Number of benchmark iterations per function.
+const N = 1000;
+
+// The native library that holds all the native functions being called.
+final nativeFunctionsLib = dlopenPlatformSpecific('native_functions',
+    path: Platform.script.resolve('../native/out/').path);
+
+final getRootLibraryUrl = nativeFunctionsLib
+    .lookupFunction<Handle Function(), Object Function()>('GetRootLibraryUrl');
+
+final setNativeResolverForTest = nativeFunctionsLib.lookupFunction<
+    Void Function(Handle), void Function(Object)>('SetNativeResolverForTest');
+
+//
+// Benchmark fixtures.
+//
+
+abstract class NativeCallBenchmarkBase extends BenchmarkBase {
+  NativeCallBenchmarkBase(String name) : super(name);
+
+  void expectEquals(actual, expected) {
+    if (actual != expected) {
+      throw Exception('$name: Unexpected result: $actual, expected $expected');
+    }
+  }
+
+  void expectApprox(actual, expected) {
+    if (0.999 * expected > actual || actual > 1.001 * expected) {
+      throw Exception('$name: Unexpected result: $actual, expected $expected');
+    }
+  }
+
+  void expectIdentical(actual, expected) {
+    if (!identical(actual, expected)) {
+      throw Exception('$name: Unexpected result: $actual, expected $expected');
+    }
+  }
+}
+
+class Uint8x01 extends NativeCallBenchmarkBase {
+  Uint8x01() : super('NativeCall.Uint8x01');
+
+  @pragma('vm:external-name', 'Function1Uint8')
+  external static int f(int a);
+
+  @override
+  void run() {
+    int x = 0;
+    for (int i = 0; i < N; i++) {
+      x += f(17);
+    }
+    expectEquals(x, N * 17 + N * 42);
+  }
+}
+
+class Int64x20 extends NativeCallBenchmarkBase {
+  Int64x20() : super('NativeCall.Int64x20');
+
+  @pragma('vm:external-name', 'Function20Int64')
+  external static int f(
+      int a,
+      int b,
+      int c,
+      int d,
+      int e,
+      int f,
+      int g,
+      int h,
+      int i,
+      int j,
+      int k,
+      int l,
+      int m,
+      int n,
+      int o,
+      int p,
+      int q,
+      int r,
+      int s,
+      int t);
+
+  @override
+  void run() {
+    int x = 0;
+    for (int i = 0; i < N; i++) {
+      x += f(i, i, i, i, i, i, i, i, i, i, i, i, i, i, i, i, i, i, i, i);
+    }
+    expectEquals(x, N * (N - 1) * 20 / 2);
+  }
+}
+
+class Doublex01 extends NativeCallBenchmarkBase {
+  Doublex01() : super('NativeCall.Doublex01');
+
+  @pragma('vm:external-name', 'Function1Double')
+  external static double f(double a);
+
+  @override
+  void run() {
+    double x = 0.0;
+    for (int i = 0; i < N; i++) {
+      x += f(17.0);
+    }
+    final double expected = N * (17.0 + 42.0);
+    expectApprox(x, expected);
+  }
+}
+
+class Doublex20 extends NativeCallBenchmarkBase {
+  Doublex20() : super('NativeCall.Doublex20');
+
+  @pragma('vm:external-name', 'Function20Double')
+  external static double f(
+      double a,
+      double b,
+      double c,
+      double d,
+      double e,
+      double f,
+      double g,
+      double h,
+      double i,
+      double j,
+      double k,
+      double l,
+      double m,
+      double n,
+      double o,
+      double p,
+      double q,
+      double r,
+      double s,
+      double t);
+
+  @override
+  void run() {
+    double x = 0;
+    for (int i = 0; i < N; i++) {
+      x += f(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0,
+          13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0);
+    }
+    final double expected = N *
+        (1.0 +
+            2.0 +
+            3.0 +
+            4.0 +
+            5.0 +
+            6.0 +
+            7.0 +
+            8.0 +
+            9.0 +
+            10.0 +
+            11.0 +
+            12.0 +
+            13.0 +
+            14.0 +
+            15.0 +
+            16.0 +
+            17.0 +
+            18.0 +
+            19.0 +
+            20.0);
+    expectApprox(x, expected);
+  }
+}
+
+class MyClass {
+  int a;
+  MyClass(this.a);
+}
+
+class Handlex01 extends NativeCallBenchmarkBase {
+  Handlex01() : super('NativeCall.Handlex01');
+
+  @pragma('vm:external-name', 'Function1Handle')
+  external static Object f(Object a);
+
+  @override
+  void run() {
+    final p1 = MyClass(123);
+    Object x = p1;
+    for (int i = 0; i < N; i++) {
+      x = f(x);
+    }
+    expectIdentical(x, p1);
+  }
+}
+
+class Handlex20 extends NativeCallBenchmarkBase {
+  Handlex20() : super('NativeCall.Handlex20');
+
+  @pragma('vm:external-name', 'Function20Handle')
+  external static Object f(
+      Object a,
+      Object b,
+      Object c,
+      Object d,
+      Object e,
+      Object f,
+      Object g,
+      Object h,
+      Object i,
+      Object j,
+      Object k,
+      Object l,
+      Object m,
+      Object n,
+      Object o,
+      Object p,
+      Object q,
+      Object r,
+      Object s,
+      Object t);
+
+  @override
+  void run() {
+    final p1 = MyClass(123);
+    final p2 = MyClass(2);
+    final p3 = MyClass(3);
+    final p4 = MyClass(4);
+    final p5 = MyClass(5);
+    final p6 = MyClass(6);
+    final p7 = MyClass(7);
+    final p8 = MyClass(8);
+    final p9 = MyClass(9);
+    final p10 = MyClass(10);
+    final p11 = MyClass(11);
+    final p12 = MyClass(12);
+    final p13 = MyClass(13);
+    final p14 = MyClass(14);
+    final p15 = MyClass(15);
+    final p16 = MyClass(16);
+    final p17 = MyClass(17);
+    final p18 = MyClass(18);
+    final p19 = MyClass(19);
+    final p20 = MyClass(20);
+    Object x = p1;
+    for (int i = 0; i < N; i++) {
+      x = f(x, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15,
+          p16, p17, p18, p19, p20);
+    }
+    expectIdentical(x, p1);
+  }
+}
+
+//
+// Main driver.
+//
+
+void main() {
+  setNativeResolverForTest(getRootLibraryUrl());
+
+  final benchmarks = [
+    () => Uint8x01(),
+    () => Int64x20(),
+    () => Doublex01(),
+    () => Doublex20(),
+    () => Handlex01(),
+    () => Handlex20(),
+  ];
+  for (final benchmark in benchmarks) {
+    benchmark().report();
+  }
+}
diff --git a/benchmarks/NativeCall/dart2/dlopen_helper.dart b/benchmarks/NativeCall/dart2/dlopen_helper.dart
new file mode 100644
index 0000000..e6e3bfa
--- /dev/null
+++ b/benchmarks/NativeCall/dart2/dlopen_helper.dart
@@ -0,0 +1,63 @@
+// Copyright (c) 2021, the Dart project authors.  Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+// @dart=2.9
+
+import 'dart:ffi';
+import 'dart:io';
+
+const arm = 'arm';
+const arm64 = 'arm64';
+const ia32 = 'ia32';
+const x64 = 'x64';
+
+// https://stackoverflow.com/questions/45125516/possible-values-for-uname-m
+final _unames = {
+  'arm': arm,
+  'aarch64_be': arm64,
+  'aarch64': arm64,
+  'armv8b': arm64,
+  'armv8l': arm64,
+  'i386': ia32,
+  'i686': ia32,
+  'x86_64': x64,
+};
+
+String _checkRunningMode(String architecture) {
+  // Check if we're running in 32bit mode.
+  final int pointerSize = sizeOf<IntPtr>();
+  if (pointerSize == 4 && architecture == x64) return ia32;
+  if (pointerSize == 4 && architecture == arm64) return arm;
+
+  return architecture;
+}
+
+String _architecture() {
+  final String uname = Process.runSync('uname', ['-m']).stdout.trim();
+  final String architecture = _unames[uname];
+  if (architecture == null) {
+    throw Exception('Unrecognized architecture: "$uname"');
+  }
+
+  // Check if we're running in 32bit mode.
+  return _checkRunningMode(architecture);
+}
+
+String _platformPath(String name, {String path = ''}) {
+  if (Platform.isMacOS || Platform.isIOS) {
+    return '${path}mac/${_architecture()}/lib$name.dylib';
+  }
+
+  if (Platform.isWindows) {
+    return '${path}win/${_checkRunningMode(x64)}/$name.dll';
+  }
+
+  // Unknown platforms default to Unix implementation.
+  return '${path}linux/${_architecture()}/lib$name.so';
+}
+
+DynamicLibrary dlopenPlatformSpecific(String name, {String path}) {
+  final String fullPath = _platformPath(name, path: path);
+  return DynamicLibrary.open(fullPath);
+}
diff --git a/benchmarks/NativeCall/native/.gitignore b/benchmarks/NativeCall/native/.gitignore
new file mode 100644
index 0000000..e778c6f
--- /dev/null
+++ b/benchmarks/NativeCall/native/.gitignore
@@ -0,0 +1,5 @@
+# Copyright (c) 2021, the Dart project authors.  Please see the AUTHORS file
+# for details. All rights reserved. Use of this source code is governed by a
+# BSD-style license that can be found in the LICENSE file.
+
+out/
diff --git a/benchmarks/NativeCall/native/Makefile b/benchmarks/NativeCall/native/Makefile
new file mode 100644
index 0000000..9a2eb44
--- /dev/null
+++ b/benchmarks/NativeCall/native/Makefile
@@ -0,0 +1,57 @@
+# Copyright (c) 2021, the Dart project authors.  Please see the AUTHORS file
+# for details. All rights reserved. Use of this source code is governed by a
+# BSD-style license that can be found in the LICENSE file.
+
+# TODO(37531): Remove this makefile and build with sdk instead when
+# benchmark runner gets support for that.
+
+CC=gcc
+CCARM=arm-linux-gnueabihf-gcc
+CCARM64=aarch64-linux-gnu-gcc
+CFLAGS=-Wall -g -O -fPIC -I../../../runtime/
+
+.PHONY: all clean
+
+all: out/linux/x64/libnative_functions.so out/linux/ia32/libnative_functions.so out/linux/arm64/libnative_functions.so out/linux/arm/libnative_functions.so
+
+cipd:
+	cipd create -name dart/benchmarks/nativecall -in out -install-mode copy
+
+clean:
+	rm -rf *.o *.so out
+
+out/linux/x64:
+	mkdir -p out/linux/x64
+
+out/linux/x64/native_functions.o: native_functions.c | out/linux/x64
+	$(CC) $(CFLAGS) -c -o $@ native_functions.c
+
+out/linux/x64/libnative_functions.so: out/linux/x64/native_functions.o
+	$(CC) $(CFLAGS) -s -shared -o $@ out/linux/x64/native_functions.o
+
+out/linux/ia32:
+	mkdir -p out/linux/ia32
+
+out/linux/ia32/native_functions.o: native_functions.c | out/linux/ia32
+	$(CC) $(CFLAGS) -m32 -c -o $@ native_functions.c
+
+out/linux/ia32/libnative_functions.so: out/linux/ia32/native_functions.o
+	$(CC) $(CFLAGS) -m32 -s -shared -o $@ out/linux/ia32/native_functions.o
+
+out/linux/arm64:
+	mkdir -p out/linux/arm64
+
+out/linux/arm64/native_functions.o: native_functions.c | out/linux/arm64
+	$(CCARM64) $(CFLAGS) -c -o $@ native_functions.c
+
+out/linux/arm64/libnative_functions.so: out/linux/arm64/native_functions.o
+	$(CCARM64) $(CFLAGS) -s -shared -o $@ out/linux/arm64/native_functions.o
+
+out/linux/arm:
+	mkdir -p out/linux/arm
+
+out/linux/arm/native_functions.o: native_functions.c | out/linux/arm
+	$(CCARM) $(CFLAGS) -c -o $@ native_functions.c
+
+out/linux/arm/libnative_functions.so: out/linux/arm/native_functions.o
+	$(CCARM) $(CFLAGS) -s -shared -o $@ out/linux/arm/native_functions.o
diff --git a/benchmarks/NativeCall/native/native_functions.c b/benchmarks/NativeCall/native/native_functions.c
new file mode 100644
index 0000000..c19251d
--- /dev/null
+++ b/benchmarks/NativeCall/native/native_functions.c
@@ -0,0 +1,119 @@
+// Copyright (c) 2021, the Dart project authors.  Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+// TODO(dartbug.com/40579): This requires static linking to either link
+// dart.exe or dart_precompiled_runtime.exe on Windows.
+// The sample currently fails on Windows in AOT mode.
+#include "include/dart_api.h"
+
+#define ENSURE(X)                                                              \
+  if (!(X)) {                                                                  \
+    fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, "Check failed: " #X);   \
+    exit(1);                                                                   \
+  }
+
+#define ENSURE_VALID(X) ENSURE(!Dart_IsError(X))
+
+//
+// Functions under test.
+//
+
+void Function1Uint8(Dart_NativeArguments args) {
+  int64_t arg = 0;
+  Dart_GetNativeIntegerArgument(args, /*index=*/0, &arg);
+  Dart_SetIntegerReturnValue(args, arg + 42);
+}
+
+void Function20Int64(Dart_NativeArguments args) {
+  int64_t arg = 0;
+  int64_t result = 0;
+  for (int i = 0; i < 20; i++) {
+    Dart_GetNativeIntegerArgument(args, /*index=*/i, &arg);
+    result += arg;
+  }
+  Dart_SetIntegerReturnValue(args, result);
+}
+
+void Function1Double(Dart_NativeArguments args) {
+  double arg = 0.0;
+  Dart_GetNativeDoubleArgument(args, /*index=*/0, &arg);
+  Dart_SetDoubleReturnValue(args, arg + 42.0);
+}
+
+void Function20Double(Dart_NativeArguments args) {
+  double arg = 0;
+  double result = 0;
+  for (int i = 0; i < 20; i++) {
+    Dart_GetNativeDoubleArgument(args, /*index=*/i, &arg);
+    result += arg;
+  }
+  Dart_SetDoubleReturnValue(args, result);
+}
+
+void Function1Handle(Dart_NativeArguments args) {
+  Dart_Handle arg = Dart_GetNativeArgument(args, /*index=*/0);
+  Dart_SetReturnValue(args, arg);
+}
+
+void Function20Handle(Dart_NativeArguments args) {
+  Dart_Handle arg = Dart_GetNativeArgument(args, /*index=*/0);
+  Dart_SetReturnValue(args, arg);
+}
+
+//
+// Test helpers.
+//
+
+DART_EXPORT Dart_Handle GetRootLibraryUrl() {
+  Dart_Handle root_lib = Dart_RootLibrary();
+  Dart_Handle lib_url = Dart_LibraryUrl(root_lib);
+  ENSURE_VALID(lib_url);
+  return lib_url;
+}
+
+Dart_NativeFunction NativeEntryResolver(Dart_Handle name,
+                                        int num_of_arguments,
+                                        bool* auto_setup_scope) {
+  ENSURE(Dart_IsString(name));
+
+  ENSURE(auto_setup_scope != NULL);
+  *auto_setup_scope = true;
+
+  const char* name_str = NULL;
+  ENSURE_VALID(Dart_StringToCString(name, &name_str));
+
+  if (strcmp(name_str, "Function1Uint8") == 0 && num_of_arguments == 1) {
+    return &Function1Uint8;
+  } else if (strcmp(name_str, "Function20Int64") == 0 &&
+             num_of_arguments == 20) {
+    return &Function20Int64;
+  } else if (strcmp(name_str, "Function1Double") == 0 &&
+             num_of_arguments == 1) {
+    return &Function1Double;
+  } else if (strcmp(name_str, "Function20Double") == 0 &&
+             num_of_arguments == 20) {
+    return &Function20Double;
+  } else if (strcmp(name_str, "Function1Handle") == 0 &&
+             num_of_arguments == 1) {
+    return &Function1Handle;
+  } else if (strcmp(name_str, "Function20Handle") == 0 &&
+             num_of_arguments == 20) {
+    return &Function20Handle;
+  }
+
+  // Unreachable in benchmark.
+  ENSURE(false);
+}
+
+DART_EXPORT void SetNativeResolverForTest(Dart_Handle url) {
+  Dart_Handle library = Dart_LookupLibrary(url);
+  ENSURE_VALID(library);
+  Dart_Handle result =
+      Dart_SetNativeResolver(library, &NativeEntryResolver, NULL);
+  ENSURE_VALID(result);
+}
diff --git a/build/mac/find_sdk.py b/build/mac/find_sdk.py
index d2bf424..e28244a 100755
--- a/build/mac/find_sdk.py
+++ b/build/mac/find_sdk.py
@@ -96,19 +96,16 @@
     if job.returncode != 0:
         print(out, file=sys.stderr)
         print(err, file=sys.stderr)
-        raise Exception((
-            'Error %d running xcode-select, you might have to run '
-            '|sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer| '
-            'if you are using Xcode 4.') % job.returncode)
-    # The Developer folder moved in Xcode 4.3.
-    xcode43_sdk_path = os.path.join(out.rstrip(),
-                                    'Platforms/MacOSX.platform/Developer/SDKs')
-    if os.path.isdir(xcode43_sdk_path):
-        sdk_dir = xcode43_sdk_path
-    else:
-        sdk_dir = os.path.join(out.rstrip(), 'SDKs')
+        raise Exception('Error %d running xcode-select' % job.returncode)
+    sdk_dir = os.path.join(out.rstrip(),
+                           'Platforms/MacOSX.platform/Developer/SDKs')
+    if not os.path.isdir(sdk_dir):
+        raise Exception(
+            'Install Xcode, launch it, accept the license ' +
+            'agreement, and run `sudo xcode-select -s /path/to/Xcode.app` ' +
+            'to continue.')
     sdks = [
-        re.findall('^MacOSX(1[01]\.\d+)\.sdk$', s) for s in os.listdir(sdk_dir)
+        re.findall('^MacOSX(\d+\.\d+)\.sdk$', s) for s in os.listdir(sdk_dir)
     ]
     sdks = [s[0] for s in sdks if s]  # [['10.5'], ['10.6']] => ['10.5', '10.6']
     sdks = [
diff --git a/docs/process/breaking-changes.md b/docs/process/breaking-changes.md
index 64a0df4..4ea8bda 100644
--- a/docs/process/breaking-changes.md
+++ b/docs/process/breaking-changes.md
@@ -53,7 +53,8 @@
 
 ### Step 1: Announcement
 
-* Create an issue in the Dart SDK issue tracker labelled
+* Create an issue in the
+  [Dart SDK issue tracker](https://github.com/dart-lang/sdk/issues) labelled
   `breaking-change-request` containing the following:
 
   * The intended change in behavior.
@@ -64,8 +65,6 @@
 
   * Clear steps for mitigating the change.
 
-[TODO: Link to an issue template for this]
-
 * Email Dart Announce (`announce@dartlang.org`):
 
   * Subject: 'Breaking change [bug ID]: [short summary]'
@@ -77,7 +76,7 @@
   * A request that developers may leave comments in the linked issue, if this
     breaking change poses a severe problem.
 
-Once you have sent the announce email, please let @devoncarew know in order
+Once you have sent the announce email, please let devoncarew@ know in order
 to start the review and approval process.
 
 ### Step 2: Approval
@@ -119,7 +118,7 @@
   * The impact of the change was significantly larger than described in the
     breaking change announcement
 
-, then they may file a 'request for roll-back' using the following steps:
+Then they may file a 'request for roll-back' using the following steps:
 
 * Create an issue in the Dart SDK issue tracker labelled
   `roll-back-request` containing the following:
@@ -132,8 +131,6 @@
   * A link to the program that was affected, or another program that illustrated
     the same effect.
 
-[TODO: Link to an issue template for this]
-
 Upon receiving such an issue the Dart SDK team will either:
 
   * Roll-back the change, or
diff --git a/pkg/_fe_analyzer_shared/lib/src/messages/codes_generated.dart b/pkg/_fe_analyzer_shared/lib/src/messages/codes_generated.dart
index 5e5e650..7cfb915 100644
--- a/pkg/_fe_analyzer_shared/lib/src/messages/codes_generated.dart
+++ b/pkg/_fe_analyzer_shared/lib/src/messages/codes_generated.dart
@@ -2768,6 +2768,16 @@
     problemMessage: r"""An enum declaration can't be empty.""");
 
 // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE.
+const Code<Null> codeEnumDeclaresFactory = messageEnumDeclaresFactory;
+
+// DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE.
+const MessageCode messageEnumDeclaresFactory = const MessageCode(
+    "EnumDeclaresFactory",
+    problemMessage: r"""Enums can't declare factory constructors.""",
+    correctionMessage:
+        r"""Try removing the factory constructor declaration.""");
+
+// DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE.
 const Code<Null> codeEnumInClass = messageEnumInClass;
 
 // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE.
@@ -5661,6 +5671,17 @@
 }
 
 // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE.
+const Code<Null> codeInternalProblemOmittedTypeNameInConstructorReference =
+    messageInternalProblemOmittedTypeNameInConstructorReference;
+
+// DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE.
+const MessageCode messageInternalProblemOmittedTypeNameInConstructorReference =
+    const MessageCode("InternalProblemOmittedTypeNameInConstructorReference",
+        severity: Severity.internalProblem,
+        problemMessage:
+            r"""Unsupported omission of the type name in a constructor reference outside of an enum element declaration.""");
+
+// DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE.
 const Code<Null> codeInternalProblemPreviousTokenNotFound =
     messageInternalProblemPreviousTokenNotFound;
 
@@ -9387,7 +9408,7 @@
 // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE.
 const MessageCode messageSuperInitializerNotLast = const MessageCode(
     "SuperInitializerNotLast",
-    analyzerCodes: <String>["INVALID_SUPER_INVOCATION"],
+    analyzerCodes: <String>["SUPER_INVOCATION_NOT_LAST"],
     problemMessage: r"""Can't have initializers after 'super'.""");
 
 // DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE.
diff --git a/pkg/_fe_analyzer_shared/lib/src/parser/declaration_kind.dart b/pkg/_fe_analyzer_shared/lib/src/parser/declaration_kind.dart
index 7037020..1efc9da 100644
--- a/pkg/_fe_analyzer_shared/lib/src/parser/declaration_kind.dart
+++ b/pkg/_fe_analyzer_shared/lib/src/parser/declaration_kind.dart
@@ -14,4 +14,7 @@
 
   /// An extension declaration.
   Extension,
+
+  /// An enum.
+  Enum,
 }
diff --git a/pkg/_fe_analyzer_shared/lib/src/parser/forwarding_listener.dart b/pkg/_fe_analyzer_shared/lib/src/parser/forwarding_listener.dart
index 042507d..c60aa80 100644
--- a/pkg/_fe_analyzer_shared/lib/src/parser/forwarding_listener.dart
+++ b/pkg/_fe_analyzer_shared/lib/src/parser/forwarding_listener.dart
@@ -636,8 +636,66 @@
   }
 
   @override
-  void endEnum(Token enumKeyword, Token leftBrace, int count) {
-    listener?.endEnum(enumKeyword, leftBrace, count);
+  void endEnum(Token enumKeyword, Token leftBrace, int memberCount) {
+    listener?.endEnum(enumKeyword, leftBrace, memberCount);
+  }
+
+  @override
+  void endEnumConstructor(Token? getOrSet, Token beginToken, Token beginParam,
+      Token? beginInitializers, Token endToken) {
+    listener?.endEnumConstructor(
+        getOrSet, beginToken, beginParam, beginInitializers, endToken);
+  }
+
+  @override
+  void handleEnumElement(Token beginToken) {
+    listener?.handleEnumElement(beginToken);
+  }
+
+  @override
+  void handleEnumElements(Token elementsEndToken, int elementsCount) {
+    listener?.handleEnumElements(elementsEndToken, elementsCount);
+  }
+
+  @override
+  void handleEnumHeader(Token enumKeyword, Token leftBrace) {
+    listener?.handleEnumHeader(enumKeyword, leftBrace);
+  }
+
+  @override
+  void endEnumFactoryMethod(
+      Token beginToken, Token factoryKeyword, Token endToken) {
+    listener?.endEnumFactoryMethod(beginToken, factoryKeyword, endToken);
+  }
+
+  @override
+  void endEnumFields(
+      Token? abstractToken,
+      Token? externalToken,
+      Token? staticToken,
+      Token? covariantToken,
+      Token? lateToken,
+      Token? varFinalOrConst,
+      int count,
+      Token beginToken,
+      Token endToken) {
+    listener?.endClassFields(
+        abstractToken,
+        externalToken,
+        staticToken,
+        covariantToken,
+        lateToken,
+        varFinalOrConst,
+        count,
+        beginToken,
+        endToken);
+  }
+
+  @override
+  void endEnumMethod(Token? getOrSet, Token beginToken, Token beginParam,
+      Token? beginInitializers, Token endToken) {
+    listener?.endEnumMethod(
+        getOrSet, beginToken, beginParam, beginInitializers, endToken);
   }
 
   @override
@@ -728,14 +786,22 @@
   @override
   void endFormalParameter(
       Token? thisKeyword,
-      Token? periodAfterThis,
+      Token? superKeyword,
+      Token? periodAfterThisOrSuper,
       Token nameToken,
       Token? initializerStart,
       Token? initializerEnd,
       FormalParameterKind kind,
       MemberKind memberKind) {
-    listener?.endFormalParameter(thisKeyword, periodAfterThis, nameToken,
-        initializerStart, initializerEnd, kind, memberKind);
+    listener?.endFormalParameter(
+        thisKeyword,
+        superKeyword,
+        periodAfterThisOrSuper,
+        nameToken,
+        initializerStart,
+        initializerEnd,
+        kind,
+        memberKind);
   }
 
   @override
@@ -1165,9 +1231,13 @@
   }
 
   @override
-  void handleClassOrMixinImplements(
-      Token? implementsKeyword, int interfacesCount) {
-    listener?.handleClassOrMixinImplements(implementsKeyword, interfacesCount);
+  void handleEnumNoWithClause() {
+    listener?.handleEnumNoWithClause();
+  }
+
+  @override
+  void handleImplements(Token? implementsKeyword, int interfacesCount) {
+    listener?.handleImplements(implementsKeyword, interfacesCount);
   }
 
   @override
@@ -1183,6 +1253,11 @@
   }
 
   @override
+  void handleEnumWithClause(Token withKeyword) {
+    listener?.handleEnumWithClause(withKeyword);
+  }
+
+  @override
   void handleCommentReference(
       Token? newKeyword, Token? prefix, Token? period, Token token) {
     listener?.handleCommentReference(newKeyword, prefix, period, token);
@@ -1540,6 +1615,11 @@
   }
 
   @override
+  void handleNoTypeNameInConstructorReference(Token token) {
+    listener?.handleNoTypeNameInConstructorReference(token);
+  }
+
+  @override
   void handleNoTypeVariables(Token token) {
     listener?.handleNoTypeVariables(token);
   }
diff --git a/pkg/_fe_analyzer_shared/lib/src/parser/listener.dart b/pkg/_fe_analyzer_shared/lib/src/parser/listener.dart
index 63a247f..332225f 100644
--- a/pkg/_fe_analyzer_shared/lib/src/parser/listener.dart
+++ b/pkg/_fe_analyzer_shared/lib/src/parser/listener.dart
@@ -137,12 +137,11 @@
     logEvent("ClassExtends");
   }
 
-  /// Handle an implements clause in a class or mixin declaration.
+  /// Handle an implements clause in a class, mixin or enum declaration.
   /// Substructures:
   /// - implemented types
-  void handleClassOrMixinImplements(
-      Token? implementsKeyword, int interfacesCount) {
-    logEvent("ClassImplements");
+  void handleImplements(Token? implementsKeyword, int interfacesCount) {
+    logEvent("Implements");
   }
 
   /// Handle a show clause in an extension declaration.
@@ -306,12 +305,55 @@
   void beginEnum(Token enumKeyword) {}
 
   /// Handle the end of an enum declaration.  Substructures:
+  /// - [memberCount] times:
+  ///   - Enum member
+  void endEnum(Token enumKeyword, Token leftBrace, int memberCount) {
+    logEvent("Enum");
+  }
+
+  /// Handle the end of an enum constructor declaration.  Substructures:
+  /// - metadata
+  /// - return type
+  /// - method name (identifier, possibly qualified)
+  /// - type variables
+  /// - formal parameters
+  /// - initializers
+  /// - async marker
+  /// - body
+  void endEnumConstructor(Token? getOrSet, Token beginToken, Token beginParam,
+      Token? beginInitializers, Token endToken) {
+    // TODO(danrubel): push implementation into subclasses
+    endClassMethod(
+        getOrSet, beginToken, beginParam, beginInitializers, endToken);
+  }
+
+  /// Handle the enum elements. Substructures:
+  /// - [elementsCount] times:
+  ///   - Enum element
+  void handleEnumElements(Token elementsEndToken, int elementsCount) {
+    logEvent("EnumElements");
+  }
+
+  /// Handle the header of an enum declaration.  Substructures:
   /// - Metadata
   /// - Enum name (identifier)
-  /// - [count] times:
-  ///   - Enum value (identifier)
-  void endEnum(Token enumKeyword, Token leftBrace, int count) {
-    logEvent("Enum");
+  /// - type variables
+  /// - with clause
+  /// - implemented types
+  void handleEnumHeader(Token enumKeyword, Token leftBrace) {
+    logEvent("EnumHeader");
+  }
+
+  /// Handle the enum element. Substructures:
+  /// - Metadata
+  /// - Enum value (identifier)
+  void handleEnumElement(Token beginToken) {
+    logEvent("EnumElement");
+  }
+
+  void endEnumFactoryMethod(
+      Token beginToken, Token factoryKeyword, Token endToken) {
+    endClassFactoryMethod(beginToken, factoryKeyword, endToken);
   }
 
   void beginExport(Token token) {}
@@ -363,7 +405,8 @@
 
   void endFormalParameter(
       Token? thisKeyword,
-      Token? periodAfterThis,
+      Token? superKeyword,
+      Token? periodAfterThisOrSuper,
       Token nameToken,
       Token? initializerStart,
       Token? initializerEnd,
@@ -447,6 +490,42 @@
         lateToken, varFinalOrConst, count, beginToken, endToken);
   }
 
+  /// Handle the end of an enum field declaration.  Substructures:
+  /// - Metadata
+  /// - Modifiers
+  /// - Type
+  /// - Variable declarations (count times)
+  ///
+  /// Started by [beginFields].
+  void endEnumFields(
+      Token? abstractToken,
+      Token? externalToken,
+      Token? staticToken,
+      Token? covariantToken,
+      Token? lateToken,
+      Token? varFinalOrConst,
+      int count,
+      Token beginToken,
+      Token endToken) {
+    endClassFields(abstractToken, externalToken, staticToken, covariantToken,
+        lateToken, varFinalOrConst, count, beginToken, endToken);
+  }
+
+  /// Handle the end of an enum method declaration.  Substructures:
+  /// - metadata
+  /// - return type
+  /// - method name (identifier, possibly qualified)
+  /// - type variables
+  /// - formal parameters
+  /// - initializers
+  /// - async marker
+  /// - body
+  void endEnumMethod(Token? getOrSet, Token beginToken, Token beginParam,
+      Token? beginInitializers, Token endToken) {
+    endClassMethod(
+        getOrSet, beginToken, beginParam, beginInitializers, endToken);
+  }
+
   /// Marks that the grammar term `forInitializerStatement` has been parsed and
   /// it was an empty statement.
   void handleForInitializerEmptyStatement(Token token) {
@@ -608,18 +687,33 @@
     logEvent("FunctionTypeAlias");
   }
 
-  /// Handle the end of a with clause (e.g. "with B, C").
+  /// Handle the end of a class with clause (e.g. "with B, C").
   /// Substructures:
   /// - mixin types (TypeList)
   void handleClassWithClause(Token withKeyword) {
     logEvent("ClassWithClause");
   }
 
-  /// Handle the absence of a with clause.
+  /// Handle the absence of a class with clause.
   void handleClassNoWithClause() {
     logEvent("ClassNoWithClause");
   }
 
+  /// Handle the end of an enum with clause (e.g. "with B, C").
+  /// Substructures:
+  /// - mixin types (TypeList)
+  ///
+  /// This method is separated from [handleClassWithClause] to simplify
+  /// handling the different objects in the context.
+  void handleEnumWithClause(Token withKeyword) {
+    logEvent("EnumWithClause");
+  }
+
+  /// Handle the absence of an enum with clause.
+  void handleEnumNoWithClause() {
+    logEvent("EnumNoWithClause");
+  }
+
   /// Handle the beginning of a named mixin application.
   /// [beginToken] may be the same as [name], or may point to modifiers
   /// (or extraneous modifiers in the case of recovery) preceding [name].
@@ -1566,6 +1660,10 @@
     logEvent("NoConstructorReferenceContinuationAfterTypeArguments");
   }
 
+  void handleNoTypeNameInConstructorReference(Token token) {
+    logEvent("NoTypeNameInConstructorReference");
+  }
+
   void handleNoType(Token lastConsumed) {
     logEvent("NoType");
   }
diff --git a/pkg/_fe_analyzer_shared/lib/src/parser/parser_impl.dart b/pkg/_fe_analyzer_shared/lib/src/parser/parser_impl.dart
index cb1ef21..fac9391 100644
--- a/pkg/_fe_analyzer_shared/lib/src/parser/parser_impl.dart
+++ b/pkg/_fe_analyzer_shared/lib/src/parser/parser_impl.dart
@@ -1286,7 +1286,7 @@
     return token;
   }
 
-  Token parseWithClauseOpt(Token token) {
+  Token parseClassWithClauseOpt(Token token) {
     // <mixins> ::= with <typeNotVoidList>
     Token withKeyword = token.next!;
     if (optional('with', withKeyword)) {
@@ -1298,6 +1298,18 @@
     return token;
   }
 
+  Token parseEnumWithClauseOpt(Token token) {
+    // <mixins> ::= with <typeNotVoidList>
+    Token withKeyword = token.next!;
+    if (optional('with', withKeyword)) {
+      token = parseTypeList(withKeyword);
+      listener.handleEnumWithClause(withKeyword);
+    } else {
+      listener.handleEnumNoWithClause();
+    }
+    return token;
+  }
+
   /// Parse the formal parameters of a getter (which shouldn't have parameters)
   /// or function or method.
   Token parseGetterOrFormalParameters(
@@ -1612,13 +1624,19 @@
         parameterKind == FormalParameterKind.optionalNamed;
 
     Token? thisKeyword;
-    Token? periodAfterThis;
+    Token? superKeyword;
+    Token? periodAfterThisOrSuper;
     IdentifierContext nameContext =
         IdentifierContext.formalParameterDeclaration;
 
-    if (!inFunctionType && optional('this', next)) {
+    if (!inFunctionType &&
+        (optional('this', next) || optional('super', next))) {
       Token originalToken = token;
-      thisKeyword = token = next;
+      if (optional('this', next)) {
+        thisKeyword = token = next;
+      } else {
+        superKeyword = token = next;
+      }
       next = token.next!;
       if (!optional('.', next)) {
         if (isOneOf(next, okNextValueInFormalParameter)) {
@@ -1626,7 +1644,7 @@
           // later that it's not an allowed identifier.
           token = originalToken;
           next = token.next!;
-          thisKeyword = null;
+          thisKeyword = superKeyword = null;
         } else {
           // Recover from a missing period by inserting one.
           next = rewriteAndRecover(
@@ -1634,13 +1652,13 @@
               codes.templateExpectedButGot.withArguments('.'),
               new SyntheticToken(TokenType.PERIOD, next.charOffset));
           // These 3 lines are duplicated here and below.
-          periodAfterThis = token = next;
+          periodAfterThisOrSuper = token = next;
           next = token.next!;
           nameContext = IdentifierContext.fieldInitializer;
         }
       } else {
         // These 3 lines are duplicated here and above.
-        periodAfterThis = token = next;
+        periodAfterThisOrSuper = token = next;
         next = token.next!;
         nameContext = IdentifierContext.fieldInitializer;
       }
@@ -1711,8 +1729,8 @@
     }
 
     Token nameToken;
-    if (periodAfterThis != null) {
-      token = periodAfterThis;
+    if (periodAfterThisOrSuper != null) {
+      token = periodAfterThisOrSuper;
     }
     next = token.next!;
     if (inFunctionType &&
@@ -1759,8 +1777,15 @@
     } else {
       listener.handleFormalParameterWithoutValue(next);
     }
-    listener.endFormalParameter(thisKeyword, periodAfterThis, nameToken,
-        initializerStart, initializerEnd, parameterKind, memberKind);
+    listener.endFormalParameter(
+        thisKeyword,
+        superKeyword,
+        periodAfterThisOrSuper,
+        nameToken,
+        initializerStart,
+        initializerEnd,
+        parameterKind,
+        memberKind);
     return token;
   }
 
@@ -1917,35 +1942,45 @@
 
   /// ```
   /// enumType:
-  ///   metadata 'enum' id '{' metadata id [',' metadata id]* [','] '}'
-  /// ;
+  ///   metadata 'enum' id typeParameters? mixins? interfaces? '{'
+  ///      enumEntry (',' enumEntry)* (',')? (';'
+  ///      (metadata classMemberDefinition)*
+  ///      )?
+  ///   '}'
+  ///
+  /// enumEntry:
+  ///     metadata id argumentPart?
+  ///   | metadata id typeArguments? '.' id arguments
   /// ```
   Token parseEnum(Token enumKeyword) {
     assert(optional('enum', enumKeyword));
     listener.beginUncategorizedTopLevelDeclaration(enumKeyword);
-    listener.beginEnum(enumKeyword);
     Token token =
         ensureIdentifier(enumKeyword, IdentifierContext.enumDeclaration);
+    String name = token.lexeme;
+    listener.beginEnum(enumKeyword);
+    token = parseEnumHeaderOpt(token, enumKeyword);
     Token leftBrace = token.next!;
-    int count = 0;
+    int elementCount = 0;
+    int memberCount = 0;
     if (optional('{', leftBrace)) {
+      listener.handleEnumHeader(enumKeyword, leftBrace);
       token = leftBrace;
       while (true) {
         Token next = token.next!;
-        if (optional('}', next)) {
+        if (optional('}', next) || optional(';', next)) {
           token = next;
-          if (count == 0) {
+          if (elementCount == 0) {
             reportRecoverableError(token, codes.messageEnumDeclarationEmpty);
           }
           break;
         }
-        token = parseMetadataStar(token);
-        token = ensureIdentifier(token, IdentifierContext.enumValueDeclaration);
+        token = parseEnumElement(token);
         next = token.next!;
-        count++;
+        elementCount++;
         if (optional(',', next)) {
           token = next;
-        } else if (optional('}', next)) {
+        } else if (optional('}', next) || optional(';', next)) {
           token = next;
           break;
         } else {
@@ -1971,14 +2006,51 @@
           }
         }
       }
+      listener.handleEnumElements(token, elementCount);
+      if (optional(';', token)) {
+        while (notEofOrValue('}', token.next!)) {
+          token = parseClassOrMixinOrExtensionOrEnumMemberImpl(
+              token, DeclarationKind.Enum, name);
+          ++memberCount;
+        }
+        token = token.next!;
+        assert(token.isEof || optional('}', token));
+      }
     } else {
       // TODO(danrubel): merge this error message with missing class/mixin body
       leftBrace = ensureBlock(
           token, codes.templateExpectedEnumBody, /* missingBlockName = */ null);
+      listener.handleEnumHeader(enumKeyword, leftBrace);
+      listener.handleEnumElements(token, elementCount);
       token = leftBrace.endGroup!;
     }
     assert(optional('}', token));
-    listener.endEnum(enumKeyword, leftBrace, count);
+    listener.endEnum(enumKeyword, leftBrace, memberCount);
+    return token;
+  }
+
+  Token parseEnumHeaderOpt(Token token, Token enumKeyword) {
+    token = computeTypeParamOrArg(
+            token, /* inDeclaration = */ true, /* allowsVariance = */ true)
+        .parseVariables(token, this);
+    token = parseEnumWithClauseOpt(token);
+    token = parseClassOrMixinOrEnumImplementsOpt(token);
+    return token;
+  }
+
+  Token parseEnumElement(Token token) {
+    Token beginToken = token;
+    token = parseMetadataStar(token);
+    token = ensureIdentifier(token, IdentifierContext.enumValueDeclaration);
+    token = parseConstructorReference(token, ConstructorReferenceContext.Const,
+        /* typeArg = */ null, /* isImplicitTypeName = */ true);
+    Token next = token.next!;
+    if (optional('(', next) || optional('<', next)) {
+      token = parseConstructorInvocationArguments(token);
+    } else {
+      listener.handleNoArguments(token);
+    }
+    listener.handleEnumElement(beginToken);
     return token;
   }
 
@@ -2047,8 +2119,8 @@
 
   Token parseClassHeaderOpt(Token token, Token begin, Token classKeyword) {
     token = parseClassExtendsOpt(token);
-    token = parseWithClauseOpt(token);
-    token = parseClassOrMixinImplementsOpt(token);
+    token = parseClassWithClauseOpt(token);
+    token = parseClassOrMixinOrEnumImplementsOpt(token);
     Token? nativeToken;
     if (optional('native', token.next!)) {
       nativeToken = token.next!;
@@ -2114,7 +2186,7 @@
         }
       }
 
-      token = parseWithClauseOpt(token);
+      token = parseClassWithClauseOpt(token);
 
       if (recoveryListener.withKeyword != null) {
         if (hasWith) {
@@ -2129,7 +2201,7 @@
         }
       }
 
-      token = parseClassOrMixinImplementsOpt(token);
+      token = parseClassOrMixinOrEnumImplementsOpt(token);
 
       if (recoveryListener.implementsKeyword != null) {
         if (hasImplements) {
@@ -2191,7 +2263,7 @@
   ///   'implements' typeName (',' typeName)*
   /// ;
   /// ```
-  Token parseClassOrMixinImplementsOpt(Token token) {
+  Token parseClassOrMixinOrEnumImplementsOpt(Token token) {
     Token? implementsKeyword;
     int interfacesCount = 0;
     if (optional('implements', token.next!)) {
@@ -2202,7 +2274,7 @@
         ++interfacesCount;
       } while (optional(',', token.next!));
     }
-    listener.handleClassOrMixinImplements(implementsKeyword, interfacesCount);
+    listener.handleImplements(implementsKeyword, interfacesCount);
     return token;
   }
 
@@ -2237,7 +2309,7 @@
 
   Token parseMixinHeaderOpt(Token token, Token mixinKeyword) {
     token = parseMixinOnOpt(token);
-    token = parseClassOrMixinImplementsOpt(token);
+    token = parseClassOrMixinOrEnumImplementsOpt(token);
     listener.handleMixinHeader(mixinKeyword);
     return token;
   }
@@ -2294,7 +2366,7 @@
         }
       }
 
-      token = parseClassOrMixinImplementsOpt(token);
+      token = parseClassOrMixinOrEnumImplementsOpt(token);
 
       if (recoveryListener.implementsKeyword != null) {
         if (hasImplements) {
@@ -2993,6 +3065,18 @@
             beforeStart.next!,
             token);
         break;
+      case DeclarationKind.Enum:
+        listener.endEnumFields(
+            abstractToken,
+            externalToken,
+            staticToken,
+            covariantToken,
+            lateToken,
+            varFinalOrConst,
+            fieldCount,
+            beforeStart.next!,
+            token);
+        break;
     }
     return token;
   }
@@ -3537,7 +3621,7 @@
     listener.beginClassOrMixinOrExtensionBody(kind, token);
     int count = 0;
     while (notEofOrValue('}', token.next!)) {
-      token = parseClassOrMixinOrExtensionMemberImpl(
+      token = parseClassOrMixinOrExtensionOrEnumMemberImpl(
           token, kind, enclosingDeclarationName);
       ++count;
     }
@@ -3559,7 +3643,7 @@
   /// token and returns the token after the last consumed token rather than the
   /// last consumed token.
   Token parseClassMember(Token token, String? className) {
-    return parseClassOrMixinOrExtensionMemberImpl(
+    return parseClassOrMixinOrExtensionOrEnumMemberImpl(
             syntheticPreviousToken(token), DeclarationKind.Class, className)
         .next!;
   }
@@ -3571,7 +3655,7 @@
   /// token and returns the token after the last consumed token rather than the
   /// last consumed token.
   Token parseMixinMember(Token token, String mixinName) {
-    return parseClassOrMixinOrExtensionMemberImpl(
+    return parseClassOrMixinOrExtensionOrEnumMemberImpl(
             syntheticPreviousToken(token), DeclarationKind.Mixin, mixinName)
         .next!;
   }
@@ -3583,8 +3667,10 @@
   /// token and returns the token after the last consumed token rather than the
   /// last consumed token.
   Token parseExtensionMember(Token token, String extensionName) {
-    return parseClassOrMixinOrExtensionMemberImpl(syntheticPreviousToken(token),
-            DeclarationKind.Extension, extensionName)
+    return parseClassOrMixinOrExtensionOrEnumMemberImpl(
+            syntheticPreviousToken(token),
+            DeclarationKind.Extension,
+            extensionName)
         .next!;
   }
 
@@ -3623,7 +3709,7 @@
   ///   methodDeclaration
   /// ;
   /// ```
-  Token parseClassOrMixinOrExtensionMemberImpl(
+  Token parseClassOrMixinOrExtensionOrEnumMemberImpl(
       Token token, DeclarationKind kind, String? enclosingDeclarationName) {
     Token beforeStart = token = parseMetadataStar(token);
 
@@ -4147,6 +4233,10 @@
           break;
         case DeclarationKind.TopLevel:
           throw "Internal error: TopLevel constructor.";
+        case DeclarationKind.Enum:
+          listener.endEnumConstructor(getOrSet, beforeStart.next!,
+              beforeParam.next!, beforeInitializers?.next, token);
+          break;
       }
     } else {
       //
@@ -4176,6 +4266,10 @@
           break;
         case DeclarationKind.TopLevel:
           throw "Internal error: TopLevel method.";
+        case DeclarationKind.Enum:
+          listener.endEnumMethod(getOrSet, beforeStart.next!, beforeParam.next!,
+              beforeInitializers?.next, token);
+          break;
       }
     }
     return token;
@@ -4268,6 +4362,11 @@
         break;
       case DeclarationKind.TopLevel:
         throw "Internal error: TopLevel factory.";
+      case DeclarationKind.Enum:
+        reportRecoverableError(
+            factoryKeyword, codes.messageEnumDeclaresFactory);
+        listener.endEnumFactoryMethod(beforeStart.next!, factoryKeyword, token);
+        break;
     }
     return token;
   }
@@ -4391,12 +4490,19 @@
 
   Token parseConstructorReference(
       Token token, ConstructorReferenceContext constructorReferenceContext,
-      [TypeParamOrArgInfo? typeArg]) {
-    Token start =
-        ensureIdentifier(token, IdentifierContext.constructorReference);
+      [TypeParamOrArgInfo? typeArg, bool isImplicitTypeName = false]) {
+    Token start;
+    if (isImplicitTypeName) {
+      listener.handleNoTypeNameInConstructorReference(token.next!);
+      start = token;
+    } else {
+      start = ensureIdentifier(token, IdentifierContext.constructorReference);
+    }
     listener.beginConstructorReference(start);
-    token = parseQualifiedRestOpt(
-        start, IdentifierContext.constructorReferenceContinuation);
+    if (!isImplicitTypeName) {
+      token = parseQualifiedRestOpt(
+          start, IdentifierContext.constructorReferenceContinuation);
+    }
     typeArg ??= computeTypeParamOrArg(token);
     token = typeArg.parseArguments(token, this);
     Token? period = null;
@@ -6050,8 +6156,8 @@
     }
 
     listener.beginNewExpression(newKeyword);
-    token = parseConstructorReference(
-        newKeyword, ConstructorReferenceContext.New, potentialTypeArg);
+    token = parseConstructorReference(newKeyword,
+        ConstructorReferenceContext.New, /* typeArg = */ potentialTypeArg);
     token = parseConstructorInvocationArguments(token);
     listener.endNewExpression(newKeyword);
     return token;
@@ -6062,7 +6168,7 @@
     Token begin = token.next!; // This is the class name.
     listener.beginImplicitCreationExpression(begin);
     token = parseConstructorReference(
-        token, ConstructorReferenceContext.Implicit, typeArg);
+        token, ConstructorReferenceContext.Implicit, /* typeArg = */ typeArg);
     token = parseConstructorInvocationArguments(token);
     listener.endImplicitCreationExpression(begin, openAngleBracket);
     return token;
@@ -6178,8 +6284,8 @@
       }
     }
     listener.beginConstExpression(constKeyword);
-    token = parseConstructorReference(
-        token, ConstructorReferenceContext.Const, potentialTypeArg);
+    token = parseConstructorReference(token, ConstructorReferenceContext.Const,
+        /* typeArg = */ potentialTypeArg);
     token = parseConstructorInvocationArguments(token);
     listener.endConstExpression(constKeyword);
     return token;
diff --git a/pkg/_fe_analyzer_shared/lib/src/parser/recovery_listeners.dart b/pkg/_fe_analyzer_shared/lib/src/parser/recovery_listeners.dart
index 5c24c53..7936de0 100644
--- a/pkg/_fe_analyzer_shared/lib/src/parser/recovery_listeners.dart
+++ b/pkg/_fe_analyzer_shared/lib/src/parser/recovery_listeners.dart
@@ -24,10 +24,9 @@
   }
 
   @override
-  void handleClassOrMixinImplements(
-      Token? implementsKeyword, int interfacesCount) {
+  void handleImplements(Token? implementsKeyword, int interfacesCount) {
     this.implementsKeyword = implementsKeyword;
-    super.handleClassOrMixinImplements(implementsKeyword, interfacesCount);
+    super.handleImplements(implementsKeyword, interfacesCount);
   }
 
   @override
@@ -82,10 +81,9 @@
   }
 
   @override
-  void handleClassOrMixinImplements(
-      Token? implementsKeyword, int interfacesCount) {
+  void handleImplements(Token? implementsKeyword, int interfacesCount) {
     this.implementsKeyword = implementsKeyword;
-    super.handleClassOrMixinImplements(implementsKeyword, interfacesCount);
+    super.handleImplements(implementsKeyword, interfacesCount);
   }
 
   @override
diff --git a/pkg/_fe_analyzer_shared/lib/src/parser/stack_listener.dart b/pkg/_fe_analyzer_shared/lib/src/parser/stack_listener.dart
index 245bef3..fbc3ab3 100644
--- a/pkg/_fe_analyzer_shared/lib/src/parser/stack_listener.dart
+++ b/pkg/_fe_analyzer_shared/lib/src/parser/stack_listener.dart
@@ -37,6 +37,7 @@
   ConditionallySelectedImport,
   ConstructorInitializerSeparator,
   ConstructorInitializers,
+  ConstructorReference,
   ConstructorReferenceContinuationAfterTypeArguments,
   ContinueTarget,
   Deferred,
@@ -346,9 +347,8 @@
   }
 
   @override
-  void handleClassOrMixinImplements(
-      Token? implementsKeyword, int interfacesCount) {
-    debugEvent("ClassImplements");
+  void handleImplements(Token? implementsKeyword, int interfacesCount) {
+    debugEvent("Implements");
   }
 
   @override
diff --git a/pkg/_fe_analyzer_shared/pubspec.yaml b/pkg/_fe_analyzer_shared/pubspec.yaml
index 41a87a0..445f314 100644
--- a/pkg/_fe_analyzer_shared/pubspec.yaml
+++ b/pkg/_fe_analyzer_shared/pubspec.yaml
@@ -1,5 +1,5 @@
 name: _fe_analyzer_shared
-version: 30.0.0
+version: 31.0.0
 description: Logic that is shared between the front_end and analyzer packages.
 homepage: https://github.com/dart-lang/sdk/tree/master/pkg/_fe_analyzer_shared
 
diff --git a/pkg/_js_interop_checks/lib/src/transformations/js_util_optimizer.dart b/pkg/_js_interop_checks/lib/src/transformations/js_util_optimizer.dart
index 2e4f847..4a20a40 100644
--- a/pkg/_js_interop_checks/lib/src/transformations/js_util_optimizer.dart
+++ b/pkg/_js_interop_checks/lib/src/transformations/js_util_optimizer.dart
@@ -139,11 +139,10 @@
           VariableGet(function.positionalParameters.first),
           StringLiteral(_getExtensionMemberName(node))
         ], types: [
-          DynamicType()
+          function.returnType
         ]))
       ..fileOffset = node.fileOffset;
-    return ReturnStatement(
-        AsExpression(getPropertyInvocation, function.returnType));
+    return ReturnStatement(getPropertyInvocation);
   }
 
   /// Returns a new function body for the given [node] external setter.
@@ -153,18 +152,18 @@
   ReturnStatement _getExternalSetterBody(Procedure node) {
     var function = node.function;
     assert(function.positionalParameters.length == 2);
+    var value = function.positionalParameters.last;
     var setPropertyInvocation = StaticInvocation(
         _setPropertyTarget,
         Arguments([
           VariableGet(function.positionalParameters.first),
           StringLiteral(_getExtensionMemberName(node)),
-          VariableGet(function.positionalParameters.last)
+          VariableGet(value)
         ], types: [
-          DynamicType()
+          value.type
         ]))
       ..fileOffset = node.fileOffset;
-    return ReturnStatement(AsExpression(
-        _lowerSetProperty(setPropertyInvocation), function.returnType));
+    return ReturnStatement(_lowerSetProperty(setPropertyInvocation));
   }
 
   /// Returns a new function body for the given [node] external method.
@@ -183,11 +182,10 @@
               .map((argument) => VariableGet(argument))
               .toList())
         ], types: [
-          DynamicType()
+          function.returnType
         ]))
       ..fileOffset = node.fileOffset;
-    return ReturnStatement(AsExpression(
-        _lowerCallMethod(callMethodInvocation), function.returnType));
+    return ReturnStatement(_lowerCallMethod(callMethodInvocation));
   }
 
   /// Returns the extension member name.
diff --git a/pkg/analysis_server/analysis_options.yaml b/pkg/analysis_server/analysis_options.yaml
index 90f1d22..e737f27 100644
--- a/pkg/analysis_server/analysis_options.yaml
+++ b/pkg/analysis_server/analysis_options.yaml
@@ -2,6 +2,7 @@
 
 analyzer:
   # This currently finds ~1,200 implicit-casts issues when enabled.
+  # TODO(srawlins): Switch to strict-casts
   # strong-mode:
   #   implicit-casts: false
   exclude:
diff --git a/pkg/analysis_server/benchmark/benchmarks.dart b/pkg/analysis_server/benchmark/benchmarks.dart
index c6b391f..78a1b36 100644
--- a/pkg/analysis_server/benchmark/benchmarks.dart
+++ b/pkg/analysis_server/benchmark/benchmarks.dart
@@ -222,16 +222,20 @@
 
   @override
   Future run() async {
-    if (argResults!.rest.isEmpty) {
+    var args = argResults;
+    if (args == null) {
+      throw StateError('argResults have not been set');
+    }
+    if (args.rest.isEmpty) {
       printUsage();
       exit(1);
     }
 
-    var benchmarkId = argResults!.rest.first;
-    var repeatCount = int.parse(argResults!['repeat'] as String);
-    var flutterRepository = argResults!['flutter-repository'] as String?;
-    var quick = argResults!['quick'];
-    var verbose = argResults!['verbose'];
+    var benchmarkId = args.rest.first;
+    var repeatCount = int.parse(args['repeat'] as String);
+    var flutterRepository = args['flutter-repository'] as String?;
+    var quick = args['quick'] as bool;
+    var verbose = args['verbose'] as bool;
 
     var benchmark =
         benchmarks.firstWhere((b) => b.id == benchmarkId, orElse: () {
@@ -241,8 +245,14 @@
 
     if (benchmark is FlutterBenchmark) {
       if (flutterRepository != null) {
-        (benchmark as FlutterBenchmark).flutterRepositoryPath =
-            flutterRepository;
+        if (path.isAbsolute(flutterRepository) &&
+            path.normalize(flutterRepository) == flutterRepository) {
+          (benchmark as FlutterBenchmark).flutterRepositoryPath =
+              flutterRepository;
+        } else {
+          print('The path must be absolute and normalized: $flutterRepository');
+          exit(1);
+        }
       } else {
         print('The option --flutter-repository is required to '
             "run '$benchmarkId'.");
diff --git a/pkg/analysis_server/benchmark/integration/input_converter.dart b/pkg/analysis_server/benchmark/integration/input_converter.dart
index da47e28..aec8d14 100644
--- a/pkg/analysis_server/benchmark/integration/input_converter.dart
+++ b/pkg/analysis_server/benchmark/integration/input_converter.dart
@@ -62,7 +62,7 @@
 
   /// Return an operation for the notification or `null` if none.
   Operation? convertNotification(Map<String, dynamic> json) {
-    String event = json['event'];
+    var event = json['event'] as String;
     if (event == SERVER_NOTIFICATION_STATUS) {
       // {"event":"server.status","params":{"analysis":{"isAnalyzing":false}}}
       var params = asMap2(json['params']);
@@ -214,21 +214,21 @@
   /// Recursively translate source paths in the specified JSON to reference
   /// the temporary source used during performance measurement rather than
   /// the original source when the instrumentation or log file was generated.
-  dynamic translateSrcPaths(json) {
+  Object? translateSrcPaths(Object? json) {
     if (json is String) {
       return srcPathMap.translate(json);
     }
     if (json is List) {
-      var result = [];
+      var result = <Object?>[];
       for (var i = 0; i < json.length; ++i) {
-        result.add(translateSrcPaths(json[i]));
+        result.add(translateSrcPaths(json[i] as Object?));
       }
       return result;
     }
     if (json is Map) {
       var result = <String, Object?>{};
       json.forEach((origKey, value) {
-        result[translateSrcPaths(origKey)] = translateSrcPaths(value);
+        result[translateSrcPaths(origKey) as String] = translateSrcPaths(value);
       });
       return result;
     }
diff --git a/pkg/analysis_server/benchmark/integration/main.dart b/pkg/analysis_server/benchmark/integration/main.dart
index b63675e..07ce8bb 100644
--- a/pkg/analysis_server/benchmark/integration/main.dart
+++ b/pkg/analysis_server/benchmark/integration/main.dart
@@ -130,8 +130,8 @@
     printHelp();
     exit(1);
   }
-
-  var showHelp = args[HELP_CMDLINE_OPTION] || args.rest.isNotEmpty;
+  var helpArg = args[HELP_CMDLINE_OPTION] as bool;
+  var showHelp = helpArg || args.rest.isNotEmpty;
 
   var inputArg = args[INPUT_CMDLINE_OPTION];
   if (inputArg is! String || inputArg.isEmpty) {
@@ -141,7 +141,8 @@
     perfArgs.inputPath = inputArg;
   }
 
-  for (var pair in args[MAP_OPTION]) {
+  var mapArg = args[MAP_OPTION] as List<Object?>;
+  for (var pair in mapArg) {
     if (pair is String) {
       var index = pair.indexOf(',');
       if (index != -1 && !pair.contains(',', index + 1)) {
@@ -175,9 +176,10 @@
     }
   }
 
-  if (args[VERY_VERBOSE_CMDLINE_OPTION] || rawArgs.contains('-vv')) {
+  var verboseArg = args[VERY_VERBOSE_CMDLINE_OPTION] as bool;
+  if (verboseArg || rawArgs.contains('-vv')) {
     Logger.root.level = Level.FINE;
-  } else if (args[VERBOSE_CMDLINE_OPTION]) {
+  } else if (verboseArg) {
     Logger.root.level = Level.INFO;
   } else {
     Logger.root.level = Level.WARNING;
diff --git a/pkg/analysis_server/benchmark/integration/operation.dart b/pkg/analysis_server/benchmark/integration/operation.dart
index 311e979..db0bfcf 100644
--- a/pkg/analysis_server/benchmark/integration/operation.dart
+++ b/pkg/analysis_server/benchmark/integration/operation.dart
@@ -70,8 +70,8 @@
   @override
   Future<void>? perform(Driver driver) {
     var stopwatch = Stopwatch();
-    String originalId = json['id'];
-    String method = json['method'];
+    var originalId = json['id'] as String;
+    var method = json['method'] as String;
     json['clientRequestTime'] = DateTime.now().millisecondsSinceEpoch;
     driver.logger.log(Level.FINE, 'Sending request: $method\n  $json');
     stopwatch.start();
diff --git a/pkg/analysis_server/benchmark/perf/flutter_completion_benchmark.dart b/pkg/analysis_server/benchmark/perf/flutter_completion_benchmark.dart
index e2bac08..78497cb 100644
--- a/pkg/analysis_server/benchmark/perf/flutter_completion_benchmark.dart
+++ b/pkg/analysis_server/benchmark/perf/flutter_completion_benchmark.dart
@@ -77,8 +77,10 @@
     // time analyzing, and do apply the filter.
     // Total number of suggestions: 2322.
     // Filtered to: 82.
+    // Long name: completion-smallFile-body
+    var name = 'completion-1';
     result.add(
-      'completion-smallFile-body',
+      name,
       BenchMarkResult(
         'micros',
         await _completionTiming(
@@ -86,7 +88,7 @@
           filePath: '$flutterPkgPath/lib/src/material/flutter_logo.dart',
           uniquePrefix: 'Widget build(BuildContext context) {',
           insertStringGenerator: () => 'M',
-          name: 'completion-smallFile-body',
+          name: name,
         ),
       ),
     );
@@ -98,8 +100,10 @@
       // JSON in the server, and deserializing on the client.
       // Total number of suggestions: 2322.
       // Filtered to: 2322.
+      // Long name: completion-smallFile-body-withoutPrefix
+      name = 'completion-2';
       result.add(
-        'completion-smallFile-body-withoutPrefix',
+        name,
         BenchMarkResult(
           'micros',
           await _completionTiming(
@@ -107,7 +111,7 @@
             filePath: '$flutterPkgPath/lib/src/material/flutter_logo.dart',
             uniquePrefix: 'Widget build(BuildContext context) {',
             insertStringGenerator: null,
-            name: 'completion-smallFile-body-withoutPrefix',
+            name: name,
           ),
         ),
       );
@@ -118,8 +122,10 @@
       // The target method body is small, so something could be optimized.
       // Total number of suggestions: 4654.
       // Filtered to: 182.
+      // Long name: completion-smallLibraryCycle-largeFile-smallBody
+      name = 'completion-3';
       result.add(
-        'completion-smallLibraryCycle-largeFile-smallBody',
+        name,
         BenchMarkResult(
           'micros',
           await _completionTiming(
@@ -127,7 +133,7 @@
             filePath: '$flutterPkgPath/test/material/text_field_test.dart',
             uniquePrefix: 'getOpacity(WidgetTester tester, Finder finder) {',
             insertStringGenerator: () => 'M',
-            name: 'completion-smallLibraryCycle-largeFile-smallBody',
+            name: name,
           ),
         ),
       );
@@ -143,8 +149,10 @@
       // TODO(scheglov) Remove the previous sentence when improved.
       // Total number of suggestions: 3429.
       // Filtered to: 133.
+      // Long name: completion-mediumLibraryCycle-mediumFile-smallBody
+      name = 'completion-4';
       result.add(
-        'completion-mediumLibraryCycle-mediumFile-smallBody',
+        name,
         BenchMarkResult(
           'micros',
           await _completionTiming(
@@ -152,7 +160,7 @@
             filePath: '$flutterPkgPath/lib/src/material/app_bar.dart',
             uniquePrefix: 'computeDryLayout(BoxConstraints constraints) {',
             insertStringGenerator: () => 'M',
-            name: 'completion-mediumLibraryCycle-mediumFile-smallBody',
+            name: name,
           ),
         ),
       );
@@ -163,8 +171,10 @@
       // cycle. This is expensive.
       // Total number of suggestions: 1510.
       // Filtered to: 0.
+      // Long name: completion-mediumLibraryCycle-mediumFile-api-parameterType
+      name = 'completion-5';
       result.add(
-        'completion-mediumLibraryCycle-mediumFile-api-parameterType',
+        name,
         BenchMarkResult(
           'micros',
           await _completionTiming(
@@ -172,7 +182,7 @@
             filePath: '$flutterPkgPath/lib/src/material/app_bar.dart',
             uniquePrefix: 'computeDryLayout(BoxConstraints',
             insertStringGenerator: _IncrementingStringGenerator(),
-            name: 'completion-mediumLibraryCycle-mediumFile-api-parameterType',
+            name: name,
           ),
         ),
       );
diff --git a/pkg/analysis_server/benchmark/perf/memory_tests.dart b/pkg/analysis_server/benchmark/perf/memory_tests.dart
index 528f672..1837834 100644
--- a/pkg/analysis_server/benchmark/perf/memory_tests.dart
+++ b/pkg/analysis_server/benchmark/perf/memory_tests.dart
@@ -230,7 +230,7 @@
   Map<String, List<Diagnostic>> currentAnalysisErrors = {};
 
   @override
-  void expect(actual, matcher, {String? reason}) =>
+  void expect(Object? actual, Matcher matcher, {String? reason}) =>
       outOfTestExpect(actual, matcher, reason: reason);
 
   /// The server is automatically started before every test.
@@ -265,8 +265,8 @@
 
     var total = 0;
 
-    List isolateGroupsRefs = vm['isolateGroups'];
-    for (Map isolateGroupRef in isolateGroupsRefs) {
+    var isolateGroupsRefs = vm['isolateGroups'] as List<Object?>;
+    for (var isolateGroupRef in isolateGroupsRefs.cast<Map>()) {
       final heapUsage = await service.call('getIsolateGroupMemoryUsage',
           {'isolateGroupId': isolateGroupRef['id']});
       total += heapUsage['heapUsage'] + heapUsage['externalUsage'] as int;
@@ -312,10 +312,10 @@
     }
 
     try {
-      dynamic json = jsonDecode(message);
+      var json = jsonDecode(message) as Map<Object?, Object?>;
       if (json.containsKey('id')) {
-        dynamic id = json['id'];
-        _completers[id]?.complete(json['result']);
+        var id = json['id'];
+        _completers[id]?.complete(json['result'] as Map<Object?, Object?>);
         _completers.remove(id);
       }
     } catch (e) {
diff --git a/pkg/analysis_server/lib/plugin/edit/assist/assist_core.dart b/pkg/analysis_server/lib/plugin/edit/assist/assist_core.dart
index c4469ea..c56e634 100644
--- a/pkg/analysis_server/lib/plugin/edit/assist/assist_core.dart
+++ b/pkg/analysis_server/lib/plugin/edit/assist/assist_core.dart
@@ -15,7 +15,9 @@
   /// Assists with the same relevance are sorted alphabetically.
   static final Comparator<Assist> SORT_BY_RELEVANCE = (Assist a, Assist b) {
     if (a.kind.priority != b.kind.priority) {
-      return a.kind.priority - b.kind.priority;
+      // A higher priority indicates a higher relevance
+      // and should be sorted before a lower priority.
+      return b.kind.priority - a.kind.priority;
     }
     return a.change.message.compareTo(b.change.message);
   };
diff --git a/pkg/analysis_server/lib/protocol/protocol.dart b/pkg/analysis_server/lib/protocol/protocol.dart
index 9d15dac..263083a 100644
--- a/pkg/analysis_server/lib/protocol/protocol.dart
+++ b/pkg/analysis_server/lib/protocol/protocol.dart
@@ -37,7 +37,7 @@
 
   /// Initialize a newly created instance based on the given JSON data.
   factory Notification.fromJson(Map json) {
-    return Notification(json[Notification.EVENT],
+    return Notification(json[Notification.EVENT] as String,
         json[Notification.PARAMS] as Map<String, Object>?);
   }
 
diff --git a/pkg/analysis_server/lib/protocol/protocol_constants.dart b/pkg/analysis_server/lib/protocol/protocol_constants.dart
index 2689506..85a4474 100644
--- a/pkg/analysis_server/lib/protocol/protocol_constants.dart
+++ b/pkg/analysis_server/lib/protocol/protocol_constants.dart
@@ -141,6 +141,7 @@
 const String COMPLETION_REQUEST_GET_SUGGESTIONS2_FILE = 'file';
 const String COMPLETION_REQUEST_GET_SUGGESTIONS2_MAX_RESULTS = 'maxResults';
 const String COMPLETION_REQUEST_GET_SUGGESTIONS2_OFFSET = 'offset';
+const String COMPLETION_REQUEST_GET_SUGGESTIONS2_TIMEOUT = 'timeout';
 const String COMPLETION_REQUEST_GET_SUGGESTIONS_FILE = 'file';
 const String COMPLETION_REQUEST_GET_SUGGESTIONS_OFFSET = 'offset';
 const String COMPLETION_REQUEST_GET_SUGGESTION_DETAILS =
diff --git a/pkg/analysis_server/lib/protocol/protocol_generated.dart b/pkg/analysis_server/lib/protocol/protocol_generated.dart
index 8cd904d..bfdf408 100644
--- a/pkg/analysis_server/lib/protocol/protocol_generated.dart
+++ b/pkg/analysis_server/lib/protocol/protocol_generated.dart
@@ -4698,7 +4698,14 @@
   /// to true.
   int maxResults;
 
-  CompletionGetSuggestions2Params(this.file, this.offset, this.maxResults);
+  /// The approximate time in milliseconds that the server should spend. The
+  /// server will perform some steps anyway, even if it takes longer than the
+  /// specified timeout. This field is intended to be used for benchmarking,
+  /// and usually should not be provided, so that the default timeout is used.
+  int? timeout;
+
+  CompletionGetSuggestions2Params(this.file, this.offset, this.maxResults,
+      {this.timeout});
 
   factory CompletionGetSuggestions2Params.fromJson(
       JsonDecoder jsonDecoder, String jsonPath, Object? json) {
@@ -4723,7 +4730,12 @@
       } else {
         throw jsonDecoder.mismatch(jsonPath, 'maxResults');
       }
-      return CompletionGetSuggestions2Params(file, offset, maxResults);
+      int? timeout;
+      if (json.containsKey('timeout')) {
+        timeout = jsonDecoder.decodeInt(jsonPath + '.timeout', json['timeout']);
+      }
+      return CompletionGetSuggestions2Params(file, offset, maxResults,
+          timeout: timeout);
     } else {
       throw jsonDecoder.mismatch(
           jsonPath, 'completion.getSuggestions2 params', json);
@@ -4741,6 +4753,10 @@
     result['file'] = file;
     result['offset'] = offset;
     result['maxResults'] = maxResults;
+    var timeout = this.timeout;
+    if (timeout != null) {
+      result['timeout'] = timeout;
+    }
     return result;
   }
 
@@ -4757,7 +4773,8 @@
     if (other is CompletionGetSuggestions2Params) {
       return file == other.file &&
           offset == other.offset &&
-          maxResults == other.maxResults;
+          maxResults == other.maxResults &&
+          timeout == other.timeout;
     }
     return false;
   }
@@ -4767,6 +4784,7 @@
         file,
         offset,
         maxResults,
+        timeout,
       );
 }
 
@@ -11547,7 +11565,7 @@
       double? doubleValue;
       if (json.containsKey('doubleValue')) {
         doubleValue = jsonDecoder.decodeDouble(
-            jsonPath + '.doubleValue', json['doubleValue']);
+            jsonPath + '.doubleValue', json['doubleValue'] as Object);
       }
       int? intValue;
       if (json.containsKey('intValue')) {
diff --git a/pkg/analysis_server/lib/src/analysis_server.dart b/pkg/analysis_server/lib/src/analysis_server.dart
index fd9daec..bbe634a 100644
--- a/pkg/analysis_server/lib/src/analysis_server.dart
+++ b/pkg/analysis_server/lib/src/analysis_server.dart
@@ -33,6 +33,7 @@
 import 'package:analysis_server/src/protocol_server.dart' as server;
 import 'package:analysis_server/src/search/search_domain.dart';
 import 'package:analysis_server/src/server/crash_reporting_attachments.dart';
+import 'package:analysis_server/src/server/debounce_requests.dart';
 import 'package:analysis_server/src/server/detachable_filesystem_manager.dart';
 import 'package:analysis_server/src/server/diagnostic_server.dart';
 import 'package:analysis_server/src/server/error_notifier.dart';
@@ -55,6 +56,7 @@
 import 'package:analyzer_plugin/src/utilities/navigation/navigation.dart';
 import 'package:analyzer_plugin/utilities/navigation/navigation_dart.dart';
 import 'package:http/http.dart' as http;
+import 'package:meta/meta.dart';
 import 'package:telemetry/crash_reporting.dart';
 import 'package:telemetry/telemetry.dart' as telemetry;
 import 'package:watcher/watcher.dart';
@@ -115,6 +117,12 @@
 
   final DetachableFileSystemManager? detachableFileSystemManager;
 
+  /// The broadcast stream of requests that were discarded because there
+  /// was another request that made this one irrelevant.
+  @visibleForTesting
+  final StreamController<Request> discardedRequests =
+      StreamController.broadcast(sync: true);
+
   /// Initialize a newly created server to receive requests from and send
   /// responses to the given [channel].
   ///
@@ -161,10 +169,14 @@
         performance = performanceAfterStartup = ServerPerformance();
       });
     });
-    var notification =
-        ServerConnectedParams(PROTOCOL_VERSION, io.pid).toNotification();
-    channel.sendNotification(notification);
-    channel.listen(handleRequest, onDone: done, onError: error);
+    channel.sendNotification(
+      ServerConnectedParams(
+        options.reportProtocolVersion ?? PROTOCOL_VERSION,
+        io.pid,
+      ).toNotification(),
+    );
+    debounceRequests(channel, discardedRequests)
+        .listen(handleRequest, onDone: done, onError: error);
     handlers = <server.RequestHandler>[
       ServerDomainHandler(this),
       AnalysisDomainHandler(this),
@@ -635,6 +647,9 @@
 
   /// The set of enabled features.
   FeatureSet featureSet = FeatureSet();
+
+  /// If set, this string will be reported as the protocol version.
+  String? reportProtocolVersion;
 }
 
 class ServerContextManagerCallbacks extends ContextManagerCallbacks {
diff --git a/pkg/analysis_server/lib/src/analysis_server_abstract.dart b/pkg/analysis_server/lib/src/analysis_server_abstract.dart
index 9e758b6..7724107 100644
--- a/pkg/analysis_server/lib/src/analysis_server_abstract.dart
+++ b/pkg/analysis_server/lib/src/analysis_server_abstract.dart
@@ -44,12 +44,14 @@
     show EvictingFileByteStore;
 import 'package:analyzer/src/dart/analysis/file_content_cache.dart';
 import 'package:analyzer/src/dart/analysis/performance_logger.dart';
+import 'package:analyzer/src/dart/analysis/results.dart';
 import 'package:analyzer/src/dart/ast/element_locator.dart';
 import 'package:analyzer/src/dart/ast/utilities.dart';
 import 'package:analyzer/src/dartdoc/dartdoc_directive_info.dart';
 import 'package:analyzer/src/generated/sdk.dart';
 import 'package:analyzer/src/services/available_declarations.dart';
 import 'package:analyzer/src/util/file_paths.dart' as file_paths;
+import 'package:analyzer/src/util/performance/operation_performance.dart';
 import 'package:collection/collection.dart';
 import 'package:http/http.dart' as http;
 import 'package:meta/meta.dart';
@@ -302,8 +304,14 @@
   }
 
   DartdocDirectiveInfo getDartdocDirectiveInfoFor(ResolvedUnitResult result) {
+    return getDartdocDirectiveInfoForSession(result.session);
+  }
+
+  DartdocDirectiveInfo getDartdocDirectiveInfoForSession(
+    AnalysisSession session,
+  ) {
     return declarationsTracker
-            ?.getContext(result.session.analysisContext)
+            ?.getContext(session.analysisContext)
             ?.dartdocDirectiveInfo ??
         DartdocDirectiveInfo();
   }
@@ -312,7 +320,14 @@
   /// context that produced the [result], or `null` if there is no cache for the
   /// context.
   DocumentationCache? getDocumentationCacheFor(ResolvedUnitResult result) {
-    var context = result.session.analysisContext;
+    return getDocumentationCacheForSession(result.session);
+  }
+
+  /// Return the object used to cache the documentation for elements in the
+  /// context that produced the [session], or `null` if there is no cache for
+  /// the context.
+  DocumentationCache? getDocumentationCacheForSession(AnalysisSession session) {
+    var context = session.analysisContext;
     var tracker = declarationsTracker?.getContext(context);
     if (tracker == null) {
       return null;
@@ -416,7 +431,7 @@
     return driver
         .getResult(path, sendCachedToStream: sendCachedToStream)
         .then((value) => value is ResolvedUnitResult ? value : null)
-        .catchError((e, st) {
+        .catchError((Object e, StackTrace st) {
       instrumentationService.logException(e, st);
       return null;
     });
@@ -462,11 +477,36 @@
     contextManager.refresh();
   }
 
+  ResolvedForCompletionResultImpl? resolveForCompletion({
+    required String path,
+    required int offset,
+    required OperationPerformanceImpl performance,
+  }) {
+    if (!file_paths.isDart(resourceProvider.pathContext, path)) {
+      return null;
+    }
+
+    var driver = getAnalysisDriver(path);
+    if (driver == null) {
+      return null;
+    }
+
+    try {
+      return driver.resolveForCompletion(
+        path: path,
+        offset: offset,
+        performance: performance,
+      );
+    } catch (e, st) {
+      instrumentationService.logException(e, st);
+    }
+  }
+
   /// Sends an error notification to the user.
   void sendServerErrorNotification(
     String message,
-    dynamic exception,
-    /*StackTrace*/ stackTrace, {
+    Object exception,
+    StackTrace? stackTrace, {
     bool fatal = false,
   });
 
diff --git a/pkg/analysis_server/lib/src/channel/byte_stream_channel.dart b/pkg/analysis_server/lib/src/channel/byte_stream_channel.dart
index bfbc6ba..955e547 100644
--- a/pkg/analysis_server/lib/src/channel/byte_stream_channel.dart
+++ b/pkg/analysis_server/lib/src/channel/byte_stream_channel.dart
@@ -73,7 +73,6 @@
 /// standard input and standard output) to communicate with clients.
 class ByteStreamServerChannel implements ServerCommunicationChannel {
   final Stream _input;
-
   final IOSink _output;
 
   /// The instrumentation service that is to be used by this analysis server.
@@ -88,6 +87,20 @@
   /// True if [close] has been called.
   bool _closeRequested = false;
 
+  @override
+  late final Stream<Request> requests = _input
+      .transform(const Utf8Decoder())
+      .transform(const LineSplitter())
+      .transform(
+        StreamTransformer.fromHandlers(
+          handleData: _readRequest,
+          handleDone: (sink) {
+            close();
+            sink.close();
+          },
+        ),
+      );
+
   ByteStreamServerChannel(
       this._input, this._output, this._instrumentationService,
       {RequestStatisticsHelper? requestStatistics})
@@ -110,17 +123,6 @@
   }
 
   @override
-  void listen(void Function(Request request) onRequest,
-      {Function? onError, void Function()? onDone}) {
-    _input.transform(const Utf8Decoder()).transform(LineSplitter()).listen(
-        (String data) => _readRequest(data, onRequest),
-        onError: onError, onDone: () {
-      close();
-      onDone?.call();
-    });
-  }
-
-  @override
   void sendNotification(Notification notification) {
     // Don't send any further notifications after the communication channel is
     // closed.
@@ -159,7 +161,7 @@
 
   /// Read a request from the given [data] and use the given function to handle
   /// the request.
-  void _readRequest(String data, void Function(Request request) onRequest) {
+  void _readRequest(String data, Sink<Request> sink) {
     // Ignore any further requests after the communication channel is closed.
     if (_closed.isCompleted) {
       return;
@@ -173,6 +175,6 @@
       return;
     }
     _requestStatistics?.addRequest(request);
-    onRequest(request);
+    sink.add(request);
   }
 }
diff --git a/pkg/analysis_server/lib/src/channel/channel.dart b/pkg/analysis_server/lib/src/channel/channel.dart
index 6b5e95f..37a6e86 100644
--- a/pkg/analysis_server/lib/src/channel/channel.dart
+++ b/pkg/analysis_server/lib/src/channel/channel.dart
@@ -98,17 +98,12 @@
 /// objects that allow an [AnalysisServer] to receive [Request]s and to return
 /// both [Response]s and [Notification]s.
 abstract class ServerCommunicationChannel {
+  /// The single-subscription stream of requests.
+  Stream<Request> get requests;
+
   /// Close the communication channel.
   void close();
 
-  /// Listen to the channel for requests. If a request is received, invoke the
-  /// [onRequest] function. If an error is encountered while trying to read from
-  /// the socket, invoke the [onError] function. If the socket is closed by the
-  /// client, invoke the [onDone] function.
-  /// Only one listener is allowed per channel.
-  void listen(void Function(Request request) onRequest,
-      {Function onError, void Function() onDone});
-
   /// Send the given [notification] to the client.
   void sendNotification(Notification notification);
 
diff --git a/pkg/analysis_server/lib/src/cider/completion.dart b/pkg/analysis_server/lib/src/cider/completion.dart
index 17f00da..4f6aaaa 100644
--- a/pkg/analysis_server/lib/src/cider/completion.dart
+++ b/pkg/analysis_server/lib/src/cider/completion.dart
@@ -70,7 +70,7 @@
       var lineInfo = resolvedUnit.lineInfo;
       var offset = lineInfo.getOffsetOfLine(line) + column;
 
-      _dartCompletionRequest = DartCompletionRequest(
+      _dartCompletionRequest = DartCompletionRequest.forResolvedUnit(
         resolvedUnit: resolvedUnit,
         offset: offset,
       );
diff --git a/pkg/analysis_server/lib/src/cider/rename.dart b/pkg/analysis_server/lib/src/cider/rename.dart
index 6ff6528..4c38533 100644
--- a/pkg/analysis_server/lib/src/cider/rename.dart
+++ b/pkg/analysis_server/lib/src/cider/rename.dart
@@ -14,17 +14,46 @@
 class CanRenameResponse {
   final LineInfo lineInfo;
   final RenameRefactoringElement refactoringElement;
-  final String oldName;
+  final FileResolver _fileResolver;
+  final String filePath;
 
-  CanRenameResponse(this.lineInfo, this.refactoringElement, this.oldName);
+  CanRenameResponse(this.lineInfo, this.refactoringElement, this._fileResolver,
+      this.filePath);
+
+  String get oldName => refactoringElement.element.displayName;
+
+  CheckNameResponse? checkNewName(String name) {
+    var element = refactoringElement.element;
+    RefactoringStatus? status;
+    if (element is LocalVariableElement) {
+      status = validateVariableName(name);
+    } else if (element is ParameterElement) {
+      status = validateParameterName(name);
+    } else if (element is FunctionElement) {
+      status = validateFunctionName(name);
+    }
+    if (status == null) {
+      return null;
+    }
+    return CheckNameResponse(status, this);
+  }
 }
 
 class CheckNameResponse {
-  final LineInfo lineInfo;
   final RefactoringStatus status;
-  final String oldName;
+  final CanRenameResponse canRename;
 
-  CheckNameResponse(this.lineInfo, this.status, this.oldName);
+  CheckNameResponse(this.status, this.canRename);
+
+  LineInfo get lineInfo => canRename.lineInfo;
+
+  String get oldName => canRename.refactoringElement.element.displayName;
+
+  RenameResponse? computeRenameRanges() {
+    var matches = canRename._fileResolver
+        .findReferences(canRename.refactoringElement.element);
+    return RenameResponse(matches, this);
+  }
 }
 
 class CiderRenameComputer {
@@ -45,7 +74,7 @@
     if (node == null || element == null) {
       return null;
     }
-    if (element.source != null && element.source!.isInSystemLibrary) {
+    if (element.source != null && element.source!.uri.isScheme('dart')) {
       return null;
     }
     if (element is MethodElement && element.isOperator) {
@@ -56,11 +85,12 @@
     }
     var refactoring = RenameRefactoring.getElementToRename(node, element);
     if (refactoring != null) {
-      return CanRenameResponse(lineInfo, refactoring, element.displayName);
+      return CanRenameResponse(lineInfo, refactoring, _fileResolver, filePath);
     }
     return null;
   }
 
+  @deprecated
   CheckNameResponse? checkNewName(
       String filePath, int line, int column, String name) {
     var resolvedUnit = _fileResolver.resolve(path: filePath);
@@ -74,6 +104,10 @@
       return null;
     }
 
+    var refactoring = RenameRefactoring.getElementToRename(node, element);
+    if (refactoring == null) {
+      return null;
+    }
     RefactoringStatus? status;
     if (element is LocalVariableElement) {
       status = validateVariableName(name);
@@ -85,7 +119,9 @@
     if (status == null) {
       return null;
     }
-    return CheckNameResponse(lineInfo, status, element.displayName);
+
+    return CheckNameResponse(status,
+        CanRenameResponse(lineInfo, refactoring, _fileResolver, filePath));
   }
 
   bool _canRenameElement(Element element) {
@@ -103,3 +139,10 @@
     return false;
   }
 }
+
+class RenameResponse {
+  final List<CiderSearchMatch> matches;
+  final CheckNameResponse checkName;
+
+  RenameResponse(this.matches, this.checkName);
+}
diff --git a/pkg/analysis_server/lib/src/computer/computer_color.dart b/pkg/analysis_server/lib/src/computer/computer_color.dart
new file mode 100644
index 0000000..56352d1
--- /dev/null
+++ b/pkg/analysis_server/lib/src/computer/computer_color.dart
@@ -0,0 +1,361 @@
+// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'package:analysis_server/src/utilities/flutter.dart';
+import 'package:analyzer/dart/analysis/results.dart';
+import 'package:analyzer/dart/ast/ast.dart';
+import 'package:analyzer/dart/ast/visitor.dart';
+import 'package:analyzer/dart/constant/value.dart';
+import 'package:analyzer/dart/element/element.dart';
+import 'package:analyzer/dart/element/type.dart';
+import 'package:analyzer/src/dart/constant/value.dart' show GenericState;
+import 'package:analyzer/src/dart/element/inheritance_manager3.dart';
+import 'package:analyzer/src/dart/element/type_system.dart';
+import 'package:analyzer/src/lint/linter.dart';
+import 'package:collection/collection.dart';
+
+/// Computer for dart:ui/Flutter Color references.
+class ColorComputer {
+  final ResolvedUnitResult resolvedUnit;
+  final LinterContext _linterContext;
+  final List<ColorReference> _colors = [];
+  final Flutter _flutter = Flutter.instance;
+
+  ColorComputer(this.resolvedUnit)
+      : _linterContext = LinterContextImpl(
+          [], // unused
+          LinterContextUnit(resolvedUnit.content, resolvedUnit.unit),
+          resolvedUnit.session.declaredVariables,
+          resolvedUnit.typeProvider,
+          resolvedUnit.typeSystem as TypeSystemImpl,
+          InheritanceManager3(), // unused
+          resolvedUnit.session.analysisContext.analysisOptions,
+          null,
+        );
+
+  /// Returns information about the color references in [resolvedUnit].
+  ///
+  /// This method should only be called once for any instance of this class.
+  List<ColorReference> compute() {
+    final visitor = _ColorBuilder(this);
+    resolvedUnit.unit.accept(visitor);
+    return _colors;
+  }
+
+  /// Tries to add a color for the [expression].
+  ///
+  /// If [target] is supplied, will be used instead of [expression] allowing
+  /// a value to be read from the member [memberName] or from a swatch value
+  /// with index [index].
+  bool tryAddColor(
+    Expression expression, {
+    Expression? target,
+    String? memberName,
+    int? index,
+  }) {
+    if (!_isColor(expression.staticType)) return false;
+
+    target ??= expression;
+
+    // Try to evaluate the constant target.
+    final colorConstResult = _linterContext.evaluateConstant(target);
+    var colorConst = colorConstResult.value;
+    if (colorConstResult.errors.isNotEmpty || colorConst == null) return false;
+
+    // If we want a specific member or swatch index, read that.
+    if (memberName != null) {
+      colorConst = _getMember(colorConst, memberName);
+    } else if (index != null) {
+      colorConst = _getSwatchValue(colorConst, index);
+    }
+
+    return _tryRecordColor(expression, colorConst);
+  }
+
+  /// Tries to add a color for the instance creation [expression].
+  ///
+  /// This handles constructor calls that cannot be evaluated (for example
+  /// because they are not const) but are simple well-known dart:ui/Flutter
+  /// color constructors that we can manually parse.
+  bool tryAddKnownColorConstructor(InstanceCreationExpression expression) {
+    if (!_isColor(expression.staticType)) return false;
+
+    final constructor = expression.constructorName;
+    final staticElement = constructor.staticElement;
+    final classElement = staticElement?.enclosingElement;
+    final className = classElement?.name;
+    final constructorName = constructor.name?.name;
+    final constructorArgs = expression.argumentList.arguments
+        .map((e) => e is Literal ? e : null)
+        .toList();
+
+    int? colorValue;
+    if (_isDartUi(classElement) && className == 'Color') {
+      colorValue = _getDartUiColorValue(constructorName, constructorArgs);
+    } else if (_isFlutterPainting(classElement) && className == 'ColorSwatch') {
+      colorValue =
+          _getFlutterSwatchColorValue(constructorName, constructorArgs);
+    } else if (_isFlutterMaterial(classElement) &&
+        className == 'MaterialAccentColor') {
+      colorValue =
+          _getFlutterMaterialAccentColorValue(constructorName, constructorArgs);
+    }
+
+    return _tryRecordColorValue(expression, colorValue);
+  }
+
+  /// Creates a [ColorInformation] by extracting the argb values from
+  /// [value] encoded as 0xAARRGGBB as in the dart:ui Color class.
+  ColorInformation _colorInformationForColorValue(int value) {
+    // Extract color information according to dart:ui Color values.
+    final alpha = (0xff000000 & value) >> 24;
+    final red = (0x00ff0000 & value) >> 16;
+    final blue = (0x000000ff & value) >> 0;
+    final green = (0x0000ff00 & value) >> 8;
+
+    return ColorInformation(alpha, red, green, blue);
+  }
+
+  /// Extracts the integer color value from the dart:ui Color constant [color].
+  int? _colorValueForColorConst(DartObject? color) {
+    if (color == null || color.isNull) return null;
+
+    // If the object has a "color" field, walk down to that, because some colors
+    // like CupertinoColors have a "value=0" with an overridden getter that
+    // would always result in a value representing black.
+    color = color.getFieldFromHierarchy('color') ?? color;
+
+    return color.getFieldFromHierarchy('value')?.toIntValue();
+  }
+
+  /// Converts ARGB values into a single int value as 0xAARRGGBB as used by
+  /// the dart:ui Color class.
+  int _colorValueForComponents(int alpha, int red, int green, int blue) {
+    return (alpha << 24) | (red << 16) | (green << 8) | (blue << 0);
+  }
+
+  /// Extracts the color value from dart:ui Color constructor args.
+  int? _getDartUiColorValue(String? name, List<Literal?> args) {
+    if (name == null && args.length == 1) {
+      final arg0 = args[0];
+      return arg0 is IntegerLiteral ? arg0.value : null;
+    } else if (name == 'fromARGB' && args.length == 4) {
+      final arg0 = args[0];
+      final arg1 = args[1];
+      final arg2 = args[2];
+      final arg3 = args[3];
+
+      final alpha = arg0 is IntegerLiteral ? arg0.value : null;
+      final red = arg1 is IntegerLiteral ? arg1.value : null;
+      final green = arg2 is IntegerLiteral ? arg2.value : null;
+      final blue = arg3 is IntegerLiteral ? arg3.value : null;
+
+      return alpha != null && red != null && green != null && blue != null
+          ? _colorValueForComponents(alpha, red, green, blue)
+          : null;
+    } else if (name == 'fromRGBO' && args.length == 4) {
+      final arg0 = args[0];
+      final arg1 = args[1];
+      final arg2 = args[2];
+      final arg3 = args[3];
+
+      final red = arg0 is IntegerLiteral ? arg0.value : null;
+      final green = arg1 is IntegerLiteral ? arg1.value : null;
+      final blue = arg2 is IntegerLiteral ? arg2.value : null;
+      final opacity = arg3 is IntegerLiteral
+          ? arg3.value
+          : arg3 is DoubleLiteral
+              ? arg3.value
+              : null;
+      final alpha = opacity != null ? (opacity * 255).toInt() : null;
+
+      return alpha != null && red != null && green != null && blue != null
+          ? _colorValueForComponents(alpha, red, green, blue)
+          : null;
+    }
+  }
+
+  /// Extracts the color value from Flutter MaterialAccentColor constructor args.
+  int? _getFlutterMaterialAccentColorValue(String? name, List<Literal?> args) =>
+      // MaterialAccentColor is a subclass of SwatchColor and has the same
+      // constructor.
+      _getFlutterSwatchColorValue(name, args);
+
+  /// Extracts the color value from Flutter ColorSwatch constructor args.
+  int? _getFlutterSwatchColorValue(String? name, List<Literal?> args) {
+    if (name == null && args.isNotEmpty) {
+      final arg0 = args[0];
+      return arg0 is IntegerLiteral ? arg0.value : null;
+    }
+  }
+
+  /// Extracts a named member from a color.
+  ///
+  /// Well-known getters like `shade500` will be mapped onto the swatch value
+  /// with a matching index.
+  DartObject? _getMember(DartObject target, String memberName) {
+    final colorValue = target.getFieldFromHierarchy(memberName);
+    if (colorValue != null) {
+      return colorValue;
+    }
+
+    // If we didn't get a value but it's a getter we know how to read from a
+    // swatch, try that.
+    if (memberName.startsWith('shade')) {
+      final shadeNumber = int.tryParse(memberName.substring(5));
+      if (shadeNumber != null) {
+        return _getSwatchValue(target, shadeNumber);
+      }
+    }
+  }
+
+  /// Extracts a specific shade index from a Flutter SwatchColor.
+  DartObject? _getSwatchValue(DartObject target, int swatchValue) {
+    final swatch = target.getFieldFromHierarchy('_swatch')?.toMapValue();
+    if (swatch == null) return null;
+
+    final key = swatch.keys.firstWhereOrNull(
+      (key) => key?.toIntValue() == swatchValue,
+    );
+    if (key == null) return null;
+
+    return swatch[key];
+  }
+
+  /// Checks whether [type] is - or extends - the dart:ui Color class.
+  bool _isColor(DartType? type) => type != null && _flutter.isColor(type);
+
+  /// Checks whether this elements library is dart:ui.
+  bool _isDartUi(Element? element) => element?.library?.name == 'dart.ui';
+
+  /// Checks whether this elements library is Flutter Material colors.
+  bool _isFlutterMaterial(Element? element) =>
+      element?.library?.identifier ==
+      'package:flutter/src/material/colors.dart';
+
+  /// Checks whether this elements library is Flutter Painting colors.
+  bool _isFlutterPainting(Element? element) =>
+      element?.library?.identifier ==
+      'package:flutter/src/painting/colors.dart';
+
+  /// Tries to record a color value from [colorConst] for [expression].
+  ///
+  /// Returns whether a valid color was found and recorded.
+  bool _tryRecordColor(Expression expression, DartObject? colorConst) =>
+      _tryRecordColorValue(expression, _colorValueForColorConst(colorConst));
+
+  /// Tries to record the [colorValue] for [expression].
+  ///
+  /// Returns whether a valid color was found and recorded.
+  bool _tryRecordColorValue(Expression expression, int? colorValue) {
+    if (colorValue == null) return false;
+
+    // Build color information from the Color value.
+    final color = _colorInformationForColorValue(colorValue);
+
+    // Record the color against the original entire expression.
+    _colors.add(ColorReference(expression.offset, expression.length, color));
+    return true;
+  }
+}
+
+/// Information about a color that is present in a document.
+class ColorInformation {
+  final int alpha;
+  final int red;
+  final int green;
+  final int blue;
+
+  ColorInformation(this.alpha, this.red, this.green, this.blue);
+}
+
+/// Information about a specific known location of a [ColorInformation]
+/// reference in a document.
+class ColorReference {
+  final int offset;
+  final int length;
+  final ColorInformation color;
+
+  ColorReference(this.offset, this.length, this.color);
+}
+
+class _ColorBuilder extends RecursiveAstVisitor<void> {
+  final ColorComputer computer;
+
+  _ColorBuilder(this.computer);
+
+  @override
+  void visitIndexExpression(IndexExpression node) {
+    // Colors.redAccent[500].
+    final index = node.index;
+    final indexValue = index is IntegerLiteral ? index.value : null;
+    if (indexValue != null) {
+      if (computer.tryAddColor(
+        node,
+        target: node.realTarget,
+        index: indexValue,
+      )) {
+        return;
+      }
+    }
+    super.visitIndexExpression(node);
+  }
+
+  @override
+  void visitInstanceCreationExpression(InstanceCreationExpression node) {
+    // Usually we return after finding a color, but constructors can
+    // have nested colors in their arguments so we walk all the way down.
+    if (!computer.tryAddColor(node)) {
+      // If we couldn't evaluate the constant, try the well-known color
+      // constructors for dart:ui/Flutter.
+      computer.tryAddKnownColorConstructor(node);
+    }
+
+    super.visitInstanceCreationExpression(node);
+  }
+
+  @override
+  void visitPrefixedIdentifier(PrefixedIdentifier node) {
+    // Try the whole node as a constant (eg. `MyThemeClass.staticField`).
+    if (computer.tryAddColor(node)) {
+      return;
+    }
+
+    // Try a field of a static, (eg. `const MyThemeClass().instanceField`).
+    if (computer.tryAddColor(
+      node,
+      target: node.prefix,
+      memberName: node.identifier.name,
+    )) {
+      return;
+    }
+
+    super.visitPrefixedIdentifier(node);
+  }
+
+  @override
+  void visitPropertyAccess(PropertyAccess node) {
+    // Handle things like CupterinoColors.activeBlue.darkColor where we can't
+    // evaluate the whole expression, but can evaluate CupterinoColors.activeBlue
+    // and read the darkColor.
+    if (computer.tryAddColor(
+      node,
+      target: node.realTarget,
+      memberName: node.propertyName.name,
+    )) {
+      return;
+    }
+
+    super.visitPropertyAccess(node);
+  }
+}
+
+extension _DartObjectExtensions on DartObject {
+  /// Reads the value of the field [field] from this object.
+  ///
+  /// If the field is not found, recurses up the super classes.
+  DartObject? getFieldFromHierarchy(String fieldName) =>
+      getField(fieldName) ??
+      getField(GenericState.SUPERCLASS_FIELD)?.getFieldFromHierarchy(fieldName);
+}
diff --git a/pkg/analysis_server/lib/src/context_manager.dart b/pkg/analysis_server/lib/src/context_manager.dart
index 1f568f7..b6df480 100644
--- a/pkg/analysis_server/lib/src/context_manager.dart
+++ b/pkg/analysis_server/lib/src/context_manager.dart
@@ -18,7 +18,6 @@
 import 'package:analyzer/src/generated/java_engine.dart';
 import 'package:analyzer/src/generated/sdk.dart';
 import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer/src/generated/source_io.dart';
 import 'package:analyzer/src/lint/linter.dart';
 import 'package:analyzer/src/lint/pub.dart';
 import 'package:analyzer/src/manifest/manifest_validator.dart';
@@ -222,7 +221,7 @@
       this._performanceLog,
       this._scheduler,
       this._instrumentationService,
-      {required enableBazelWatcher})
+      {required bool enableBazelWatcher})
       : pathContext = resourceProvider.pathContext {
     if (enableBazelWatcher) {
       bazelWatcherService = BazelFileWatcherService(_instrumentationService);
diff --git a/pkg/analysis_server/lib/src/domain_completion.dart b/pkg/analysis_server/lib/src/domain_completion.dart
index b1b2b36..60c81b6 100644
--- a/pkg/analysis_server/lib/src/domain_completion.dart
+++ b/pkg/analysis_server/lib/src/domain_completion.dart
@@ -3,6 +3,7 @@
 // BSD-style license that can be found in the LICENSE file.
 
 import 'dart:async';
+import 'dart:collection';
 
 import 'package:analysis_server/protocol/protocol.dart';
 import 'package:analysis_server/protocol/protocol_constants.dart';
@@ -16,6 +17,7 @@
 import 'package:analysis_server/src/services/completion/completion_performance.dart';
 import 'package:analysis_server/src/services/completion/dart/completion_manager.dart';
 import 'package:analysis_server/src/services/completion/dart/fuzzy_filter_sort.dart';
+import 'package:analysis_server/src/services/completion/dart/suggestion_builder.dart';
 import 'package:analysis_server/src/services/completion/yaml/analysis_options_generator.dart';
 import 'package:analysis_server/src/services/completion/yaml/fix_data_generator.dart';
 import 'package:analysis_server/src/services/completion/yaml/pubspec_generator.dart';
@@ -29,6 +31,7 @@
 import 'package:analyzer_plugin/protocol/protocol_common.dart';
 import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plugin;
 import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
+import 'package:collection/collection.dart';
 
 /// Instances of the class [CompletionDomainHandler] implement a
 /// [RequestHandler] that handles requests in the completion domain.
@@ -45,9 +48,6 @@
   /// The next completion response id.
   int _nextCompletionId = 0;
 
-  /// Code completion performance for the last completion operation.
-  CompletionPerformance? performance;
-
   /// A list of code completion performance measurements for the latest
   /// completion operation up to [performanceListMaxLength] measurements.
   final RecentBuffer<CompletionPerformance> performanceList =
@@ -75,7 +75,7 @@
     Set<ElementKind>? includedElementKinds,
     Set<String>? includedElementNames,
     List<IncludedSuggestionRelevanceTag>? includedSuggestionRelevanceTags,
-    List<Uri>? librariesToImport,
+    Map<CompletionSuggestion, Uri>? notImportedSuggestions,
   }) async {
     //
     // Allow plugins to start computing fixes.
@@ -94,7 +94,7 @@
         includedElementKinds: includedElementKinds,
         includedElementNames: includedElementNames,
         includedSuggestionRelevanceTags: includedSuggestionRelevanceTags,
-        librariesToImport: librariesToImport,
+        notImportedSuggestions: notImportedSuggestions,
       );
 
       suggestions.addAll(
@@ -267,16 +267,34 @@
 
   /// Implement the 'completion.getSuggestions2' request.
   void getSuggestions2(Request request) async {
-    var budget = CompletionBudget(budgetDuration);
-
     var params = CompletionGetSuggestions2Params.fromRequest(request);
     var file = params.file;
     var offset = params.offset;
 
+    var timeoutMilliseconds = params.timeout;
+    var budget = CompletionBudget(
+      timeoutMilliseconds != null
+          ? Duration(milliseconds: timeoutMilliseconds)
+          : budgetDuration,
+    );
+
     var provider = server.resourceProvider;
     var pathContext = provider.pathContext;
 
-    // TODO(scheglov) Support non-Dart files.
+    if (file.endsWith('.yaml')) {
+      final suggestions = computeYamlSuggestions(file, offset);
+      server.sendResponse(
+        CompletionGetSuggestions2Result(
+          suggestions.replacementOffset,
+          suggestions.replacementLength,
+          suggestions.suggestions,
+          [],
+          false,
+        ).toResponse(request.id),
+      );
+      return;
+    }
+
     if (!file_paths.isDart(pathContext, file)) {
       server.sendResponse(
         CompletionGetSuggestions2Result(offset, 0, [], [], false)
@@ -285,81 +303,125 @@
       return;
     }
 
-    var resolvedUnit = await server.getResolvedUnit(file);
-    if (resolvedUnit == null) {
-      server.sendResponse(Response.fileNotAnalyzed(request, file));
-      return;
-    }
-
-    server.requestStatistics?.addItemTimeNow(request, 'resolvedUnit');
-
-    if (offset < 0 || offset > resolvedUnit.content.length) {
-      server.sendResponse(Response.invalidParameter(
-          request,
-          'params.offset',
-          'Expected offset between 0 and source length inclusive,'
-              ' but found $offset'));
-      return;
-    }
-
-    final completionPerformance = CompletionPerformance();
-    recordRequest(completionPerformance, file, resolvedUnit.content, offset);
-
-    await completionPerformance.runRequestOperation((performance) async {
-      var completionRequest = DartCompletionRequest(
-        resolvedUnit: resolvedUnit,
-        offset: offset,
-        dartdocDirectiveInfo: server.getDartdocDirectiveInfoFor(
-          resolvedUnit,
-        ),
-        documentationCache: server.getDocumentationCacheFor(resolvedUnit),
-      );
-      setNewRequest(completionRequest);
-
-      var librariesToImport = <Uri>[];
-      var suggestions = <CompletionSuggestion>[];
-      try {
-        suggestions = await computeSuggestions(
-          budget: budget,
-          performance: performance,
-          request: completionRequest,
-          librariesToImport: librariesToImport,
+    var performance = OperationPerformanceImpl('<root>');
+    performance.runAsync(
+      'request',
+      (performance) async {
+        var resolvedUnit = performance.run(
+          'resolveForCompletion',
+          (performance) {
+            return server.resolveForCompletion(
+              path: file,
+              offset: offset,
+              performance: performance,
+            );
+          },
         );
-      } on AbortCompletion {
-        return server.sendResponse(
-          CompletionGetSuggestions2Result(
-            completionRequest.replacementOffset,
-            completionRequest.replacementLength,
-            [],
-            [],
-            true,
-          ).toResponse(request.id),
+        if (resolvedUnit == null) {
+          server.sendResponse(Response.fileNotAnalyzed(request, file));
+          return;
+        }
+
+        if (offset < 0 || offset > resolvedUnit.content.length) {
+          server.sendResponse(Response.invalidParameter(
+              request,
+              'params.offset',
+              'Expected offset between 0 and source length inclusive,'
+                  ' but found $offset'));
+          return;
+        }
+
+        final completionPerformance = CompletionPerformance(
+          operation: performance,
+          path: file,
+          content: resolvedUnit.content,
+          offset: offset,
         );
-      }
+        performanceList.add(completionPerformance);
 
-      performance.run('filter', (performance) {
-        performance.getDataInt('count').add(suggestions.length);
-        suggestions = fuzzyFilterSort(
-          pattern: completionRequest.targetPrefix,
-          suggestions: suggestions,
+        var analysisSession = resolvedUnit.analysisSession;
+        var enclosingNode =
+            resolvedUnit.resolvedNodes.lastOrNull ?? resolvedUnit.parsedUnit;
+
+        var completionRequest = DartCompletionRequest(
+          analysisSession: analysisSession,
+          filePath: resolvedUnit.path,
+          fileContent: resolvedUnit.content,
+          unitElement: resolvedUnit.unitElement,
+          enclosingNode: enclosingNode,
+          offset: offset,
+          dartdocDirectiveInfo:
+              server.getDartdocDirectiveInfoForSession(analysisSession),
+          documentationCache:
+              server.getDocumentationCacheForSession(analysisSession),
         );
-        performance.getDataInt('matchCount').add(suggestions.length);
-      });
+        setNewRequest(completionRequest);
 
-      var lengthRestricted = suggestions.take(params.maxResults).toList();
-      var isIncomplete = lengthRestricted.length < suggestions.length;
-      completionPerformance.suggestionCount = lengthRestricted.length;
+        var notImportedSuggestions =
+            HashMap<CompletionSuggestion, Uri>.identity();
+        var suggestions = <CompletionSuggestion>[];
+        try {
+          suggestions = await computeSuggestions(
+            budget: budget,
+            performance: performance,
+            request: completionRequest,
+            notImportedSuggestions: notImportedSuggestions,
+          );
+        } on AbortCompletion {
+          return server.sendResponse(
+            CompletionGetSuggestions2Result(
+              completionRequest.replacementOffset,
+              completionRequest.replacementLength,
+              [],
+              [],
+              true,
+            ).toResponse(request.id),
+          );
+        }
 
-      server.sendResponse(
-        CompletionGetSuggestions2Result(
-          completionRequest.replacementOffset,
-          completionRequest.replacementLength,
-          lengthRestricted,
-          librariesToImport.map((e) => '$e').toList(),
-          isIncomplete,
-        ).toResponse(request.id),
-      );
-    });
+        performance.run('filter', (performance) {
+          performance.getDataInt('count').add(suggestions.length);
+          suggestions = fuzzyFilterSort(
+            pattern: completionRequest.targetPrefix,
+            suggestions: suggestions,
+          );
+          performance.getDataInt('matchCount').add(suggestions.length);
+        });
+
+        var lengthRestricted = suggestions.take(params.maxResults).toList();
+        var isIncomplete = lengthRestricted.length < suggestions.length;
+        completionPerformance.suggestionCount = lengthRestricted.length;
+
+        // Update `libraryUriToImportIndex` for not yet imported.
+        // Gather referenced unique libraries to import.
+        var librariesToImport = <Uri, int>{};
+        for (var i = 0; i < lengthRestricted.length; i++) {
+          var suggestion = lengthRestricted[i];
+          var libraryToImport = notImportedSuggestions[suggestion];
+          if (libraryToImport != null) {
+            var index = librariesToImport.putIfAbsent(
+              libraryToImport,
+              () => librariesToImport.length,
+            );
+            lengthRestricted[i] = suggestion.copyWith(
+              libraryUriToImportIndex: CopyWithValue(index),
+            );
+          }
+        }
+
+        performance.run('sendResponse', (_) {
+          server.sendResponse(
+            CompletionGetSuggestions2Result(
+              completionRequest.replacementOffset,
+              completionRequest.replacementLength,
+              lengthRestricted,
+              librariesToImport.keys.map((e) => '$e').toList(),
+              isIncomplete,
+            ).toResponse(request.id),
+          );
+        });
+      },
+    );
   }
 
   @override
@@ -410,161 +472,160 @@
   Future<void> processRequest(Request request) async {
     var budget = CompletionBudget(budgetDuration);
 
-    final performance = this.performance = CompletionPerformance();
+    // extract and validate params
+    var params = CompletionGetSuggestionsParams.fromRequest(request);
+    var file = params.file;
+    var offset = params.offset;
 
-    await performance.runRequestOperation((perf) async {
-      // extract and validate params
-      var params = CompletionGetSuggestionsParams.fromRequest(request);
-      var file = params.file;
-      var offset = params.offset;
-
-      if (server.sendResponseErrorIfInvalidFilePath(request, file)) {
-        return;
-      }
-      if (file.endsWith('.yaml')) {
-        // Return the response without results.
-        var completionId = (_nextCompletionId++).toString();
-        server.sendResponse(CompletionGetSuggestionsResult(completionId)
-            .toResponse(request.id));
-        // Send a notification with results.
-        final suggestions = computeYamlSuggestions(file, offset);
-        sendCompletionNotification(
-          completionId,
-          suggestions.replacementOffset,
-          suggestions.replacementLength,
-          suggestions.suggestions,
-          null,
-          null,
-          null,
-          null,
-        );
-        return;
-      } else if (!file.endsWith('.dart')) {
-        // Return the response without results.
-        var completionId = (_nextCompletionId++).toString();
-        server.sendResponse(CompletionGetSuggestionsResult(completionId)
-            .toResponse(request.id));
-        // Send a notification with results.
-        sendCompletionNotification(
-            completionId, offset, 0, [], null, null, null, null);
-        return;
-      }
-
-      var resolvedUnit = await server.getResolvedUnit(file);
-      if (resolvedUnit == null) {
-        server.sendResponse(Response.fileNotAnalyzed(request, 'params.offset'));
-        return;
-      }
-
-      server.requestStatistics?.addItemTimeNow(request, 'resolvedUnit');
-
-      if (offset < 0 || offset > resolvedUnit.content.length) {
-        server.sendResponse(Response.invalidParameter(
-            request,
-            'params.offset',
-            'Expected offset between 0 and source length inclusive,'
-                ' but found $offset'));
-        return;
-      }
-
-      recordRequest(performance, file, resolvedUnit.content, offset);
-
-      var declarationsTracker = server.declarationsTracker;
-      if (declarationsTracker == null) {
-        server.sendResponse(Response.unsupportedFeature(
-            request.id, 'Completion is not enabled.'));
-        return;
-      }
-
-      var completionRequest = DartCompletionRequest(
-        resolvedUnit: resolvedUnit,
-        offset: offset,
-        dartdocDirectiveInfo: server.getDartdocDirectiveInfoFor(
-          resolvedUnit,
-        ),
-        documentationCache: server.getDocumentationCacheFor(resolvedUnit),
-      );
-
-      var completionId = (_nextCompletionId++).toString();
-
-      setNewRequest(completionRequest);
-
-      // initial response without results
-      server.sendResponse(
-          CompletionGetSuggestionsResult(completionId).toResponse(request.id));
-
-      // If the client opted into using available suggestion sets,
-      // create the kinds set, so signal the completion manager about opt-in.
-      Set<ElementKind>? includedElementKinds;
-      Set<String>? includedElementNames;
-      List<IncludedSuggestionRelevanceTag>? includedSuggestionRelevanceTags;
-      if (subscriptions.contains(CompletionService.AVAILABLE_SUGGESTION_SETS)) {
-        includedElementKinds = <ElementKind>{};
-        includedElementNames = <String>{};
-        includedSuggestionRelevanceTags = <IncludedSuggestionRelevanceTag>[];
-      }
-
-      // Compute suggestions in the background
-      try {
-        var suggestions = <CompletionSuggestion>[];
-        try {
-          suggestions = await computeSuggestions(
-            budget: budget,
-            performance: perf,
-            request: completionRequest,
-            includedElementKinds: includedElementKinds,
-            includedElementNames: includedElementNames,
-            includedSuggestionRelevanceTags: includedSuggestionRelevanceTags,
-          );
-        } on AbortCompletion {
-          // Continue with empty suggestions list.
-        }
-        String? libraryFile;
-        var includedSuggestionSets = <IncludedSuggestionSet>[];
-        if (includedElementKinds != null && includedElementNames != null) {
-          libraryFile = resolvedUnit.libraryElement.source.fullName;
-          server.sendNotification(
-            createExistingImportsNotification(resolvedUnit),
-          );
-          computeIncludedSetList(
-            declarationsTracker,
-            resolvedUnit,
-            includedSuggestionSets,
-            includedElementNames,
-          );
-        }
-
-        const SEND_NOTIFICATION_TAG = 'send notification';
-        perf.run(SEND_NOTIFICATION_TAG, (_) {
-          sendCompletionNotification(
-            completionId,
-            completionRequest.replacementOffset,
-            completionRequest.replacementLength,
-            suggestions,
-            libraryFile,
-            includedSuggestionSets,
-            includedElementKinds?.toList(),
-            includedSuggestionRelevanceTags,
-          );
-        });
-
-        performance.suggestionCount = suggestions.length;
-      } finally {
-        ifMatchesRequestClear(completionRequest);
-      }
-    });
-  }
-
-  /// If tracking code completion performance over time, then
-  /// record addition information about the request in the performance record.
-  void recordRequest(CompletionPerformance performance, String path,
-      String content, int offset) {
-    performance.path = path;
-    if (performanceListMaxLength == 0) {
+    if (server.sendResponseErrorIfInvalidFilePath(request, file)) {
       return;
     }
-    performance.setContentsAndOffset(content, offset);
-    performanceList.add(performance);
+
+    var performance = OperationPerformanceImpl('<root>');
+    performance.runAsync(
+      'request',
+      (performance) async {
+        if (file.endsWith('.yaml')) {
+          // Return the response without results.
+          var completionId = (_nextCompletionId++).toString();
+          server.sendResponse(CompletionGetSuggestionsResult(completionId)
+              .toResponse(request.id));
+          // Send a notification with results.
+          final suggestions = computeYamlSuggestions(file, offset);
+          sendCompletionNotification(
+            completionId,
+            suggestions.replacementOffset,
+            suggestions.replacementLength,
+            suggestions.suggestions,
+            null,
+            null,
+            null,
+            null,
+          );
+          return;
+        } else if (!file.endsWith('.dart')) {
+          // Return the response without results.
+          var completionId = (_nextCompletionId++).toString();
+          server.sendResponse(CompletionGetSuggestionsResult(completionId)
+              .toResponse(request.id));
+          // Send a notification with results.
+          sendCompletionNotification(
+              completionId, offset, 0, [], null, null, null, null);
+          return;
+        }
+
+        var resolvedUnit = await server.getResolvedUnit(file);
+        if (resolvedUnit == null) {
+          server
+              .sendResponse(Response.fileNotAnalyzed(request, 'params.offset'));
+          return;
+        }
+
+        server.requestStatistics?.addItemTimeNow(request, 'resolvedUnit');
+
+        if (offset < 0 || offset > resolvedUnit.content.length) {
+          server.sendResponse(Response.invalidParameter(
+              request,
+              'params.offset',
+              'Expected offset between 0 and source length inclusive,'
+                  ' but found $offset'));
+          return;
+        }
+
+        final completionPerformance = CompletionPerformance(
+          operation: performance,
+          path: file,
+          content: resolvedUnit.content,
+          offset: offset,
+        );
+        performanceList.add(completionPerformance);
+
+        var declarationsTracker = server.declarationsTracker;
+        if (declarationsTracker == null) {
+          server.sendResponse(Response.unsupportedFeature(
+              request.id, 'Completion is not enabled.'));
+          return;
+        }
+
+        var completionRequest = DartCompletionRequest.forResolvedUnit(
+          resolvedUnit: resolvedUnit,
+          offset: offset,
+          dartdocDirectiveInfo: server.getDartdocDirectiveInfoFor(
+            resolvedUnit,
+          ),
+          documentationCache: server.getDocumentationCacheFor(resolvedUnit),
+        );
+
+        var completionId = (_nextCompletionId++).toString();
+
+        setNewRequest(completionRequest);
+
+        // initial response without results
+        server.sendResponse(CompletionGetSuggestionsResult(completionId)
+            .toResponse(request.id));
+
+        // If the client opted into using available suggestion sets,
+        // create the kinds set, so signal the completion manager about opt-in.
+        Set<ElementKind>? includedElementKinds;
+        Set<String>? includedElementNames;
+        List<IncludedSuggestionRelevanceTag>? includedSuggestionRelevanceTags;
+        if (subscriptions
+            .contains(CompletionService.AVAILABLE_SUGGESTION_SETS)) {
+          includedElementKinds = <ElementKind>{};
+          includedElementNames = <String>{};
+          includedSuggestionRelevanceTags = <IncludedSuggestionRelevanceTag>[];
+        }
+
+        // Compute suggestions in the background
+        try {
+          var suggestions = <CompletionSuggestion>[];
+          try {
+            suggestions = await computeSuggestions(
+              budget: budget,
+              performance: performance,
+              request: completionRequest,
+              includedElementKinds: includedElementKinds,
+              includedElementNames: includedElementNames,
+              includedSuggestionRelevanceTags: includedSuggestionRelevanceTags,
+            );
+          } on AbortCompletion {
+            // Continue with empty suggestions list.
+          }
+          String? libraryFile;
+          var includedSuggestionSets = <IncludedSuggestionSet>[];
+          if (includedElementKinds != null && includedElementNames != null) {
+            libraryFile = resolvedUnit.libraryElement.source.fullName;
+            server.sendNotification(
+              createExistingImportsNotification(resolvedUnit),
+            );
+            computeIncludedSetList(
+              declarationsTracker,
+              completionRequest,
+              includedSuggestionSets,
+              includedElementNames,
+            );
+          }
+
+          const SEND_NOTIFICATION_TAG = 'send notification';
+          performance.run(SEND_NOTIFICATION_TAG, (_) {
+            sendCompletionNotification(
+              completionId,
+              completionRequest.replacementOffset,
+              completionRequest.replacementLength,
+              suggestions,
+              libraryFile,
+              includedSuggestionSets,
+              includedElementKinds?.toList(),
+              includedSuggestionRelevanceTags,
+            );
+          });
+
+          completionPerformance.suggestionCount = suggestions.length;
+        } finally {
+          ifMatchesRequestClear(completionRequest);
+        }
+      },
+    );
   }
 
   /// Send completion notification results.
@@ -670,11 +731,8 @@
   _RequestToPlugins? _sendRequestToPlugins(
     DartCompletionRequest completionRequest,
   ) {
-    var resolvedUnit = completionRequest.result;
-    var analysisContext = resolvedUnit.session.analysisContext;
-
     var pluginRequestParameters = plugin.CompletionGetSuggestionsParams(
-      resolvedUnit.path,
+      completionRequest.path,
       completionRequest.offset,
     );
 
@@ -683,7 +741,7 @@
       parameters: pluginRequestParameters,
       futures: server.pluginManager.broadcastRequest(
         pluginRequestParameters,
-        contextRoot: analysisContext.contextRoot,
+        contextRoot: completionRequest.analysisContext.contextRoot,
       ),
     );
   }
diff --git a/pkg/analysis_server/lib/src/domain_execution.dart b/pkg/analysis_server/lib/src/domain_execution.dart
index f047af1..5550f0b 100644
--- a/pkg/analysis_server/lib/src/domain_execution.dart
+++ b/pkg/analysis_server/lib/src/domain_execution.dart
@@ -8,7 +8,6 @@
 import 'package:analysis_server/src/analysis_server.dart';
 import 'package:analysis_server/src/protocol_server.dart';
 import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer/src/generated/source.dart';
 
 /// Instances of the class [ExecutionDomainHandler] implement a [RequestHandler]
 /// that handles requests in the `execution` domain.
@@ -122,10 +121,10 @@
       }
 
       var source = driver.fsState.getFileForPath(file).source;
-      if (source.uriKind != UriKind.FILE_URI) {
+      if (!source.uri.isScheme('file')) {
         uri = source.uri.toString();
       } else {
-        uri = sourceFactory.restoreUri(source).toString();
+        uri = sourceFactory.pathToUri(file).toString();
       }
       return ExecutionMapUriResult(uri: uri).toResponse(request.id);
     } else if (uri != null) {
diff --git a/pkg/analysis_server/lib/src/domain_server.dart b/pkg/analysis_server/lib/src/domain_server.dart
index 5dca197..559f3b8 100644
--- a/pkg/analysis_server/lib/src/domain_server.dart
+++ b/pkg/analysis_server/lib/src/domain_server.dart
@@ -19,7 +19,9 @@
 
   /// Return the version number of the analysis server.
   Response getVersion(Request request) {
-    return ServerGetVersionResult(PROTOCOL_VERSION).toResponse(request.id);
+    return ServerGetVersionResult(
+      server.options.reportProtocolVersion ?? PROTOCOL_VERSION,
+    ).toResponse(request.id);
   }
 
   @override
diff --git a/pkg/analysis_server/lib/src/domains/completion/available_suggestions.dart b/pkg/analysis_server/lib/src/domains/completion/available_suggestions.dart
index 1d4b4b5..e8838ce 100644
--- a/pkg/analysis_server/lib/src/domains/completion/available_suggestions.dart
+++ b/pkg/analysis_server/lib/src/domains/completion/available_suggestions.dart
@@ -3,29 +3,29 @@
 // BSD-style license that can be found in the LICENSE file.
 
 import 'package:analysis_server/src/protocol_server.dart' as protocol;
+import 'package:analysis_server/src/services/completion/dart/completion_manager.dart';
 import 'package:analyzer/dart/analysis/results.dart';
 import 'package:analyzer/dart/element/element.dart';
 import 'package:analyzer/src/dart/analysis/driver.dart';
 import 'package:analyzer/src/services/available_declarations.dart';
 
-/// Compute which suggestion sets should be included into completion inside
-/// the given [resolvedUnit] of a file.  Depending on the file path, it might
+/// Compute which suggestion sets should be included into completion for
+/// the given completion [request].  Depending on the file path, it might
 /// include different sets, e.g. inside the `lib/` directory of a `Pub` package
 /// only regular dependencies can be referenced, but `test/` can reference
 /// both regular and "dev" dependencies.
 void computeIncludedSetList(
   DeclarationsTracker tracker,
-  ResolvedUnitResult resolvedUnit,
+  DartCompletionRequest request,
   List<protocol.IncludedSuggestionSet> includedSetList,
   Set<String> includedElementNames,
 ) {
-  var analysisContext = resolvedUnit.session.analysisContext;
-  var context = tracker.getContext(analysisContext);
+  var context = tracker.getContext(request.analysisContext);
   if (context == null) return;
 
-  var librariesObject = context.getLibraries(resolvedUnit.path);
+  var librariesObject = context.getLibraries(request.path);
 
-  var importedUriSet = resolvedUnit.libraryElement.importedLibraries
+  var importedUriSet = request.libraryElement.importedLibraries
       .map((importedLibrary) => importedLibrary.source.uri)
       .toSet();
 
@@ -48,7 +48,7 @@
       protocol.IncludedSuggestionSet(
         library.id,
         relevance,
-        displayUri: _getRelativeFileUri(resolvedUnit, library.uri),
+        displayUri: _getRelativeFileUri(request, library.uri),
       ),
     );
 
@@ -172,11 +172,11 @@
 }
 
 /// Computes the best URI to import [what] into the [unit] library.
-String? _getRelativeFileUri(ResolvedUnitResult unit, Uri what) {
+String? _getRelativeFileUri(DartCompletionRequest request, Uri what) {
   if (what.scheme == 'file') {
-    var pathContext = unit.session.resourceProvider.pathContext;
+    var pathContext = request.analysisSession.resourceProvider.pathContext;
 
-    var libraryPath = unit.libraryElement.source.fullName;
+    var libraryPath = request.libraryElement.source.fullName;
     var libraryFolder = pathContext.dirname(libraryPath);
 
     var whatPath = pathContext.fromUri(what);
diff --git a/pkg/analysis_server/lib/src/domains/execution/completion.dart b/pkg/analysis_server/lib/src/domains/execution/completion.dart
index a2f6ea6..e0eedc4 100644
--- a/pkg/analysis_server/lib/src/domains/execution/completion.dart
+++ b/pkg/analysis_server/lib/src/domains/execution/completion.dart
@@ -69,7 +69,7 @@
       return RuntimeCompletionResult([], []);
     }
 
-    var dartRequest = DartCompletionRequest(
+    var dartRequest = DartCompletionRequest.forResolvedUnit(
       resolvedUnit: targetResult,
       offset: targetOffset,
     );
diff --git a/pkg/analysis_server/lib/src/lsp/channel/lsp_byte_stream_channel.dart b/pkg/analysis_server/lib/src/lsp/channel/lsp_byte_stream_channel.dart
index ed1ea21..a86e794 100644
--- a/pkg/analysis_server/lib/src/lsp/channel/lsp_byte_stream_channel.dart
+++ b/pkg/analysis_server/lib/src/lsp/channel/lsp_byte_stream_channel.dart
@@ -80,7 +80,7 @@
       return;
     }
     _instrumentationService.logRequest(data);
-    final Map<String, Object?> json = jsonDecode(data);
+    final json = jsonDecode(data) as Map<String, Object?>;
     if (RequestMessage.canParse(json, nullLspJsonReporter)) {
       onMessage(RequestMessage.fromJson(json));
     } else if (NotificationMessage.canParse(json, nullLspJsonReporter)) {
diff --git a/pkg/analysis_server/lib/src/lsp/handlers/commands/perform_refactor.dart b/pkg/analysis_server/lib/src/lsp/handlers/commands/perform_refactor.dart
index 20c4d27..4de8bfe 100644
--- a/pkg/analysis_server/lib/src/lsp/handlers/commands/perform_refactor.dart
+++ b/pkg/analysis_server/lib/src/lsp/handlers/commands/perform_refactor.dart
@@ -120,7 +120,7 @@
         final refactor = ExtractMethodRefactoring(
             server.searchEngine, result, offset, length);
 
-        var preferredName = options != null ? options['name'] : null;
+        var preferredName = options != null ? options['name'] as String : null;
         // checkInitialConditions will populate names with suggestions.
         if (preferredName == null) {
           await refactor.checkInitialConditions();
@@ -138,7 +138,7 @@
       case RefactoringKind.EXTRACT_LOCAL_VARIABLE:
         final refactor = ExtractLocalRefactoring(result, offset, length);
 
-        var preferredName = options != null ? options['name'] : null;
+        var preferredName = options != null ? options['name'] as String : null;
         // checkInitialConditions will populate names with suggestions.
         if (preferredName == null) {
           await refactor.checkInitialConditions();
@@ -162,7 +162,7 @@
         // to handle this better.
         // https://github.com/microsoft/language-server-protocol/issues/764
         refactor.name =
-            (options != null ? options['name'] : null) ?? 'NewWidget';
+            options != null ? options['name'] as String : 'NewWidget';
         return success(refactor);
 
       case RefactoringKind.INLINE_LOCAL_VARIABLE:
diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_code_actions.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_code_actions.dart
index 9f7152c..ecc14cc 100644
--- a/pkg/analysis_server/lib/src/lsp/handlers/handler_code_actions.dart
+++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_code_actions.dart
@@ -36,10 +36,11 @@
   // CodeAction class).
   final codeActionPriorities = Expando<int>();
 
-  /// A comparator that can be used to sort [CodeActions]s using priorties
-  /// in [codeActionPriorities]. The highest number priority will be sorted
-  /// before lower number priorityies. Items with the same relevance are sorted
-  /// alphabetically by their title.
+  /// A comparator that can be used to sort [CodeActions]s using priorities
+  /// in [codeActionPriorities].
+  ///
+  /// The highest number priority will be sorted before lower number priorities.
+  /// Items with the same priority are sorted alphabetically by their title.
   late final Comparator<CodeAction> _codeActionComparator =
       (CodeAction a, CodeAction b) {
     // We should never be sorting actions without priorities.
diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_completion.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_completion.dart
index 85f3765..10e4cf9 100644
--- a/pkg/analysis_server/lib/src/lsp/handlers/handler_completion.dart
+++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_completion.dart
@@ -26,6 +26,7 @@
 import 'package:analyzer/source/line_info.dart';
 import 'package:analyzer/src/services/available_declarations.dart';
 import 'package:analyzer/src/util/file_paths.dart' as file_paths;
+import 'package:analyzer/src/util/performance/operation_performance.dart';
 import 'package:analyzer_plugin/protocol/protocol_common.dart';
 import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plugin;
 import 'package:analyzer_plugin/src/utilities/completion/completion_target.dart';
@@ -202,216 +203,223 @@
     String? triggerCharacter,
     CancellationToken token,
   ) async {
-    final performance = CompletionPerformance();
-    performance.path = unit.path;
-    performance.setContentsAndOffset(unit.content, offset);
-    server.performanceStats.completion.add(performance);
-
-    return await performance.runRequestOperation((perf) async {
-      final completionRequest = DartCompletionRequest(
-        resolvedUnit: unit,
-        offset: offset,
-        dartdocDirectiveInfo: server.getDartdocDirectiveInfoFor(unit),
-        completionPreference: CompletionPreference.replace,
-      );
-      final target = completionRequest.target;
-
-      if (triggerCharacter != null) {
-        if (!_triggerCharacterValid(offset, triggerCharacter, target)) {
-          return success([]);
-        }
-      }
-
-      Set<ElementKind>? includedElementKinds;
-      Set<String>? includedElementNames;
-      List<IncludedSuggestionRelevanceTag>? includedSuggestionRelevanceTags;
-      if (includeSuggestionSets) {
-        includedElementKinds = <ElementKind>{};
-        includedElementNames = <String>{};
-        includedSuggestionRelevanceTags = <IncludedSuggestionRelevanceTag>[];
-      }
-
-      try {
-        var contributor = DartCompletionManager(
-          budget: CompletionBudget(CompletionBudget.defaultDuration),
-          includedElementKinds: includedElementKinds,
-          includedElementNames: includedElementNames,
-          includedSuggestionRelevanceTags: includedSuggestionRelevanceTags,
+    var performance = OperationPerformanceImpl('<root>');
+    return await performance.runAsync(
+      'request',
+      (performance) async {
+        final completionPerformance = CompletionPerformance(
+          operation: performance,
+          path: unit.path,
+          content: unit.content,
+          offset: offset,
         );
+        server.performanceStats.completion.add(completionPerformance);
 
-        final serverSuggestions = await contributor.computeSuggestions(
-          completionRequest,
-          perf,
+        final completionRequest = DartCompletionRequest.forResolvedUnit(
+          resolvedUnit: unit,
+          offset: offset,
+          dartdocDirectiveInfo: server.getDartdocDirectiveInfoFor(unit),
+          completionPreference: CompletionPreference.replace,
         );
+        final target = completionRequest.target;
 
-        final insertLength = _computeInsertLength(
-          offset,
-          completionRequest.replacementOffset,
-          completionRequest.replacementLength,
-        );
-
-        if (token.isCancellationRequested) {
-          return cancelled();
+        if (triggerCharacter != null) {
+          if (!_triggerCharacterValid(offset, triggerCharacter, target)) {
+            return success([]);
+          }
         }
 
-        /// completeFunctionCalls should be suppressed if the target is an
-        /// invocation that already has an argument list, otherwise we would
-        /// insert dupes.
-        final completeFunctionCalls = _hasExistingArgList(target.entity)
-            ? false
-            : server.clientConfiguration.global.completeFunctionCalls;
+        Set<ElementKind>? includedElementKinds;
+        Set<String>? includedElementNames;
+        List<IncludedSuggestionRelevanceTag>? includedSuggestionRelevanceTags;
+        if (includeSuggestionSets) {
+          includedElementKinds = <ElementKind>{};
+          includedElementNames = <String>{};
+          includedSuggestionRelevanceTags = <IncludedSuggestionRelevanceTag>[];
+        }
 
-        final results = serverSuggestions.map(
-          (item) {
-            var itemReplacementOffset =
-                item.replacementOffset ?? completionRequest.replacementOffset;
-            var itemReplacementLength =
-                item.replacementLength ?? completionRequest.replacementLength;
-            var itemInsertLength = insertLength;
-
-            // Recompute the insert length if it may be affected by the above.
-            if (item.replacementOffset != null ||
-                item.replacementLength != null) {
-              itemInsertLength = _computeInsertLength(
-                  offset, itemReplacementOffset, itemInsertLength);
-            }
-
-            return toCompletionItem(
-              capabilities,
-              unit.lineInfo,
-              item,
-              itemReplacementOffset,
-              itemInsertLength,
-              itemReplacementLength,
-              // TODO(dantup): Including commit characters in every completion
-              // increases the payload size. The LSP spec is ambigious
-              // about how this should be handled (and VS Code requires it) but
-              // this should be removed (or made conditional based on a capability)
-              // depending on how the spec is updated.
-              // https://github.com/microsoft/vscode-languageserver-node/issues/673
-              includeCommitCharacters:
-                  server.clientConfiguration.global.previewCommitCharacters,
-              completeFunctionCalls: completeFunctionCalls,
-            );
-          },
-        ).toList();
-
-        // Now compute items in suggestion sets.
-        var includedSuggestionSets = <IncludedSuggestionSet>[];
-        final declarationsTracker = server.declarationsTracker;
-        if (declarationsTracker != null &&
-            includedElementKinds != null &&
-            includedElementNames != null &&
-            includedSuggestionRelevanceTags != null) {
-          computeIncludedSetList(
-            declarationsTracker,
-            unit,
-            includedSuggestionSets,
-            includedElementNames,
+        try {
+          var contributor = DartCompletionManager(
+            budget: CompletionBudget(CompletionBudget.defaultDuration),
+            includedElementKinds: includedElementKinds,
+            includedElementNames: includedElementNames,
+            includedSuggestionRelevanceTags: includedSuggestionRelevanceTags,
           );
 
-          // Build a fast lookup for imported symbols so that we can filter out
-          // duplicates.
-          final alreadyImportedSymbols = _buildLookupOfImportedSymbols(unit);
+          final serverSuggestions = await contributor.computeSuggestions(
+            completionRequest,
+            performance,
+          );
 
-          includedSuggestionSets.forEach((includedSet) {
-            final library = declarationsTracker.getLibrary(includedSet.id);
-            if (library == null) {
-              return;
-            }
+          final insertLength = _computeInsertLength(
+            offset,
+            completionRequest.replacementOffset,
+            completionRequest.replacementLength,
+          );
 
-            // Make a fast lookup for tag relevance.
-            final tagBoosts = <String, int>{};
-            includedSuggestionRelevanceTags!
-                .forEach((t) => tagBoosts[t.tag] = t.relevanceBoost);
+          if (token.isCancellationRequested) {
+            return cancelled();
+          }
 
-            // Only specific types of child declarations should be included.
-            // This list matches what's in _protocolAvailableSuggestion in
-            // the DAS implementation.
-            bool shouldIncludeChild(Declaration child) =>
-                child.kind == DeclarationKind.CONSTRUCTOR ||
-                child.kind == DeclarationKind.ENUM_CONSTANT ||
-                (child.kind == DeclarationKind.GETTER && child.isStatic) ||
-                (child.kind == DeclarationKind.FIELD && child.isStatic);
+          /// completeFunctionCalls should be suppressed if the target is an
+          /// invocation that already has an argument list, otherwise we would
+          /// insert dupes.
+          final completeFunctionCalls = _hasExistingArgList(target.entity)
+              ? false
+              : server.clientConfiguration.global.completeFunctionCalls;
 
-            // Collect declarations and their children.
-            final allDeclarations = library.declarations
-                .followedBy(library.declarations
-                    .expand((decl) => decl.children.where(shouldIncludeChild)))
-                .toList();
+          final results = serverSuggestions.map(
+            (item) {
+              var itemReplacementOffset =
+                  item.replacementOffset ?? completionRequest.replacementOffset;
+              var itemReplacementLength =
+                  item.replacementLength ?? completionRequest.replacementLength;
+              var itemInsertLength = insertLength;
 
-            final setResults = allDeclarations
-                // Filter to only the kinds we should return.
-                .where((item) => includedElementKinds!
-                    .contains(protocolElementKind(item.kind)))
-                .where((item) {
-              // Check existing imports to ensure we don't already import
-              // this element (this exact element from its declaring
-              // library, not just something with the same name). If we do
-              // we'll want to skip it.
-              final declaringUri =
-                  item.parent?.locationLibraryUri ?? item.locationLibraryUri!;
+              // Recompute the insert length if it may be affected by the above.
+              if (item.replacementOffset != null ||
+                  item.replacementLength != null) {
+                itemInsertLength = _computeInsertLength(
+                    offset, itemReplacementOffset, itemInsertLength);
+              }
 
-              // For enums and named constructors, only the parent enum/class is in
-              // the list of imported symbols so we use the parents name.
-              final nameKey = item.kind == DeclarationKind.ENUM_CONSTANT ||
-                      item.kind == DeclarationKind.CONSTRUCTOR
-                  ? item.parent!.name
-                  : item.name;
-              final key = _createImportedSymbolKey(nameKey, declaringUri);
-              final importingUris = alreadyImportedSymbols[key];
+              return toCompletionItem(
+                capabilities,
+                unit.lineInfo,
+                item,
+                itemReplacementOffset,
+                itemInsertLength,
+                itemReplacementLength,
+                // TODO(dantup): Including commit characters in every completion
+                // increases the payload size. The LSP spec is ambigious
+                // about how this should be handled (and VS Code requires it) but
+                // this should be removed (or made conditional based on a capability)
+                // depending on how the spec is updated.
+                // https://github.com/microsoft/vscode-languageserver-node/issues/673
+                includeCommitCharacters:
+                    server.clientConfiguration.global.previewCommitCharacters,
+                completeFunctionCalls: completeFunctionCalls,
+              );
+            },
+          ).toList();
 
-              // Keep it only if:
-              // - no existing imports include it
-              //     (in which case all libraries will be offered as
-              //     auto-imports)
-              // - this is the first imported URI that includes it
-              //     (we don't want to repeat it for each imported library that
-              //     includes it)
-              return importingUris == null ||
-                  importingUris.first == '${library.uri}';
-            }).map((item) => declarationToCompletionItem(
-                      capabilities,
-                      unit.path,
-                      offset,
-                      includedSet,
-                      library,
-                      tagBoosts,
-                      unit.lineInfo,
-                      item,
-                      completionRequest.replacementOffset,
-                      insertLength,
-                      completionRequest.replacementLength,
-                      // TODO(dantup): Including commit characters in every completion
-                      // increases the payload size. The LSP spec is ambigious
-                      // about how this should be handled (and VS Code requires it) but
-                      // this should be removed (or made conditional based on a capability)
-                      // depending on how the spec is updated.
-                      // https://github.com/microsoft/vscode-languageserver-node/issues/673
-                      includeCommitCharacters: server
-                          .clientConfiguration.global.previewCommitCharacters,
-                      completeFunctionCalls: completeFunctionCalls,
-                    ));
-            results.addAll(setResults);
-          });
+          // Now compute items in suggestion sets.
+          var includedSuggestionSets = <IncludedSuggestionSet>[];
+          final declarationsTracker = server.declarationsTracker;
+          if (declarationsTracker != null &&
+              includedElementKinds != null &&
+              includedElementNames != null &&
+              includedSuggestionRelevanceTags != null) {
+            computeIncludedSetList(
+              declarationsTracker,
+              completionRequest,
+              includedSuggestionSets,
+              includedElementNames,
+            );
+
+            // Build a fast lookup for imported symbols so that we can filter out
+            // duplicates.
+            final alreadyImportedSymbols = _buildLookupOfImportedSymbols(unit);
+
+            includedSuggestionSets.forEach((includedSet) {
+              final library = declarationsTracker.getLibrary(includedSet.id);
+              if (library == null) {
+                return;
+              }
+
+              // Make a fast lookup for tag relevance.
+              final tagBoosts = <String, int>{};
+              includedSuggestionRelevanceTags!
+                  .forEach((t) => tagBoosts[t.tag] = t.relevanceBoost);
+
+              // Only specific types of child declarations should be included.
+              // This list matches what's in _protocolAvailableSuggestion in
+              // the DAS implementation.
+              bool shouldIncludeChild(Declaration child) =>
+                  child.kind == DeclarationKind.CONSTRUCTOR ||
+                  child.kind == DeclarationKind.ENUM_CONSTANT ||
+                  (child.kind == DeclarationKind.GETTER && child.isStatic) ||
+                  (child.kind == DeclarationKind.FIELD && child.isStatic);
+
+              // Collect declarations and their children.
+              final allDeclarations = library.declarations
+                  .followedBy(library.declarations.expand(
+                      (decl) => decl.children.where(shouldIncludeChild)))
+                  .toList();
+
+              final setResults = allDeclarations
+                  // Filter to only the kinds we should return.
+                  .where((item) => includedElementKinds!
+                      .contains(protocolElementKind(item.kind)))
+                  .where((item) {
+                // Check existing imports to ensure we don't already import
+                // this element (this exact element from its declaring
+                // library, not just something with the same name). If we do
+                // we'll want to skip it.
+                final declaringUri =
+                    item.parent?.locationLibraryUri ?? item.locationLibraryUri!;
+
+                // For enums and named constructors, only the parent enum/class is in
+                // the list of imported symbols so we use the parents name.
+                final nameKey = item.kind == DeclarationKind.ENUM_CONSTANT ||
+                        item.kind == DeclarationKind.CONSTRUCTOR
+                    ? item.parent!.name
+                    : item.name;
+                final key = _createImportedSymbolKey(nameKey, declaringUri);
+                final importingUris = alreadyImportedSymbols[key];
+
+                // Keep it only if:
+                // - no existing imports include it
+                //     (in which case all libraries will be offered as
+                //     auto-imports)
+                // - this is the first imported URI that includes it
+                //     (we don't want to repeat it for each imported library that
+                //     includes it)
+                return importingUris == null ||
+                    importingUris.first == '${library.uri}';
+              }).map((item) => declarationToCompletionItem(
+                        capabilities,
+                        unit.path,
+                        offset,
+                        includedSet,
+                        library,
+                        tagBoosts,
+                        unit.lineInfo,
+                        item,
+                        completionRequest.replacementOffset,
+                        insertLength,
+                        completionRequest.replacementLength,
+                        // TODO(dantup): Including commit characters in every completion
+                        // increases the payload size. The LSP spec is ambigious
+                        // about how this should be handled (and VS Code requires it) but
+                        // this should be removed (or made conditional based on a capability)
+                        // depending on how the spec is updated.
+                        // https://github.com/microsoft/vscode-languageserver-node/issues/673
+                        includeCommitCharacters: server
+                            .clientConfiguration.global.previewCommitCharacters,
+                        completeFunctionCalls: completeFunctionCalls,
+                      ));
+              results.addAll(setResults);
+            });
+          }
+
+          // Perform fuzzy matching based on the identifier in front of the caret to
+          // reduce the size of the payload.
+          final fuzzyPattern = completionRequest.targetPrefix;
+          final fuzzyMatcher =
+              FuzzyMatcher(fuzzyPattern, matchStyle: MatchStyle.TEXT);
+
+          final matchingResults =
+              results.where((e) => fuzzyMatcher.score(e.label) > 0).toList();
+
+          completionPerformance.suggestionCount = results.length;
+
+          return success(matchingResults);
+        } on AbortCompletion {
+          return success([]);
         }
-
-        // Perform fuzzy matching based on the identifier in front of the caret to
-        // reduce the size of the payload.
-        final fuzzyPattern = completionRequest.targetPrefix;
-        final fuzzyMatcher =
-            FuzzyMatcher(fuzzyPattern, matchStyle: MatchStyle.TEXT);
-
-        final matchingResults =
-            results.where((e) => fuzzyMatcher.score(e.label) > 0).toList();
-
-        performance.suggestionCount = results.length;
-
-        return success(matchingResults);
-      } on AbortCompletion {
-        return success([]);
-      }
-    });
+      },
+    );
   }
 
   Future<ErrorOr<List<CompletionItem>>> _getServerYamlItems(
@@ -474,7 +482,9 @@
     return (node is ast.InvocationExpression &&
             !node.argumentList.beginToken.isSynthetic) ||
         (node is ast.InstanceCreationExpression &&
-            !node.argumentList.beginToken.isSynthetic);
+            !node.argumentList.beginToken.isSynthetic) ||
+        // "ClassName.^()" will appear as accessing a property named '('.
+        (node is ast.PropertyAccess && node.propertyName.name.startsWith('('));
   }
 
   Iterable<CompletionItem> _pluginResultsToItems(
diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_completion_resolve.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_completion_resolve.dart
index 30935d6..72903a8 100644
--- a/pkg/analysis_server/lib/src/lsp/handlers/handler_completion_resolve.dart
+++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_completion_resolve.dart
@@ -60,11 +60,12 @@
           'Requests not before server is initilized');
     }
 
-    final lineInfo = server.getLineInfo(data.file);
+    final file = data.file;
+    final lineInfo = server.getLineInfo(file);
     if (lineInfo == null) {
       return error(
         ErrorCodes.InternalError,
-        'Line info not available for ${data.file}',
+        'Line info not available for $file',
         null,
       );
     }
@@ -99,7 +100,7 @@
     _latestCompletionItem = item;
     while (item == _latestCompletionItem && timer.elapsed < timeout) {
       try {
-        final analysisDriver = server.getAnalysisDriver(data.file);
+        final analysisDriver = server.getAnalysisDriver(file);
         final session = analysisDriver?.currentSession;
 
         // We shouldn't not get a driver/session, but if we did perhaps the file
@@ -139,7 +140,7 @@
 
         var newInsertText = item.insertText ?? item.label;
         final builder = ChangeBuilder(session: session);
-        await builder.addDartFileEdit(data.file, (builder) {
+        await builder.addDartFileEdit(file, (builder) {
           final result = builder.importLibraryElement(library.uri);
           if (result.prefix != null) {
             newInsertText = '${result.prefix}.$newInsertText';
@@ -152,9 +153,9 @@
 
         final changes = builder.sourceChange;
         final thisFilesChanges =
-            changes.edits.where((e) => e.file == data.file).toList();
+            changes.edits.where((e) => e.file == file).toList();
         final otherFilesChanges =
-            changes.edits.where((e) => e.file != data.file).toList();
+            changes.edits.where((e) => e.file != file).toList();
 
         // If this completion involves editing other files, we'll need to build
         // a command that the client will call to apply those edits later.
diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_document_color.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_document_color.dart
new file mode 100644
index 0000000..07bf25b
--- /dev/null
+++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_document_color.dart
@@ -0,0 +1,62 @@
+// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'package:analysis_server/lsp_protocol/protocol_generated.dart';
+import 'package:analysis_server/lsp_protocol/protocol_special.dart';
+import 'package:analysis_server/src/computer/computer_color.dart'
+    show ColorComputer, ColorReference;
+import 'package:analysis_server/src/lsp/handlers/handlers.dart';
+import 'package:analysis_server/src/lsp/lsp_analysis_server.dart';
+import 'package:analysis_server/src/lsp/mapping.dart';
+import 'package:analyzer/dart/analysis/results.dart';
+
+/// Handles textDocument/documentColor requests.
+///
+/// This request is sent by the client to the server to request the locations
+/// of any colors in the document so that it can render color previews. If the
+/// editor has a color picker, it may also call textDocument/colorPresentation
+/// to obtain the code to insert when a new color is selected (see
+/// [DocumentColorPresentationHandler]).
+class DocumentColorHandler
+    extends MessageHandler<DocumentColorParams, List<ColorInformation>> {
+  DocumentColorHandler(LspAnalysisServer server) : super(server);
+  @override
+  Method get handlesMessage => Method.textDocument_documentColor;
+
+  @override
+  LspJsonHandler<DocumentColorParams> get jsonHandler =>
+      DocumentColorParams.jsonHandler;
+
+  @override
+  Future<ErrorOr<List<ColorInformation>>> handle(
+      DocumentColorParams params, CancellationToken token) async {
+    if (!isDartDocument(params.textDocument)) {
+      return success([]);
+    }
+
+    final path = pathOfDoc(params.textDocument);
+    final unit = await path.mapResult(requireResolvedUnit);
+    return unit.mapResult((unit) => _getColors(unit));
+  }
+
+  ErrorOr<List<ColorInformation>> _getColors(ResolvedUnitResult unit) {
+    ColorInformation _toColorInformation(ColorReference reference) {
+      return ColorInformation(
+        range: toRange(unit.lineInfo, reference.offset, reference.length),
+        color: Color(
+          // LSP colors are decimal in the range 0-1 but our internal references
+          // are 0-255, so divide them.
+          alpha: reference.color.alpha / 255,
+          red: reference.color.red / 255,
+          green: reference.color.green / 255,
+          blue: reference.color.blue / 255,
+        ),
+      );
+    }
+
+    final computer = ColorComputer(unit);
+    final colors = computer.compute();
+    return success(colors.map(_toColorInformation).toList());
+  }
+}
diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_document_color_presentation.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_document_color_presentation.dart
new file mode 100644
index 0000000..06fdd44
--- /dev/null
+++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_document_color_presentation.dart
@@ -0,0 +1,169 @@
+// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'package:analysis_server/lsp_protocol/protocol_generated.dart';
+import 'package:analysis_server/lsp_protocol/protocol_special.dart';
+import 'package:analysis_server/src/lsp/handlers/handlers.dart';
+import 'package:analysis_server/src/lsp/lsp_analysis_server.dart';
+import 'package:analysis_server/src/lsp/mapping.dart';
+import 'package:analysis_server/src/utilities/flutter.dart';
+import 'package:analyzer/dart/analysis/results.dart';
+import 'package:analyzer/dart/element/element.dart';
+import 'package:analyzer/source/source_range.dart';
+import 'package:analyzer/src/dart/analysis/session_helper.dart';
+import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
+
+/// Handles textDocument/colorPresentation.
+///
+/// This request is sent by the client if it allowed the user to pick a color
+/// using a color picker (in a location returned by textDocument/documentColor)
+/// and needs a representation of this color, including the edits to insert it
+/// into the source file.
+class DocumentColorPresentationHandler
+    extends MessageHandler<ColorPresentationParams, List<ColorPresentation>> {
+  DocumentColorPresentationHandler(LspAnalysisServer server) : super(server);
+  @override
+  Method get handlesMessage => Method.textDocument_colorPresentation;
+
+  @override
+  LspJsonHandler<ColorPresentationParams> get jsonHandler =>
+      ColorPresentationParams.jsonHandler;
+
+  @override
+  Future<ErrorOr<List<ColorPresentation>>> handle(
+    ColorPresentationParams params,
+    CancellationToken token,
+  ) async {
+    if (!isDartDocument(params.textDocument)) {
+      return success([]);
+    }
+
+    final path = pathOfDoc(params.textDocument);
+    final unit = await path.mapResult(requireResolvedUnit);
+    return unit.mapResult((unit) => _getPresentations(params, unit));
+  }
+
+  /// Converts individual 0-255 ARGB values into a single int value as
+  /// 0xAARRGGBB as used by the dart:ui Color class.
+  int _colorValueForComponents(int alpha, int red, int green, int blue) {
+    return (alpha << 24) | (red << 16) | (green << 8) | (blue << 0);
+  }
+
+  /// Creates a [ColorPresentation] for inserting code to produce a dart:ui
+  /// or Flutter Color at [editRange].
+  ///
+  /// [colorType] is the Type of the Color class whose constructor will be
+  /// called. This will be replaced into [editRange] and any required import
+  /// statement will produce additional edits.
+  ///
+  /// [label] is the visible label shown to the user and should roughly reflect
+  /// the code that will be inserted.
+  ///
+  /// [invocationString] is written immediately after [colorType] in [editRange].
+  Future<ColorPresentation> _createColorPresentation(
+    ResolvedUnitResult unit,
+    SourceRange editRange,
+    ClassElement colorType,
+    String label,
+    String invocationString,
+  ) async {
+    final builder = ChangeBuilder(session: unit.session);
+    await builder.addDartFileEdit(unit.path, (builder) {
+      builder.addReplacement(editRange, (builder) {
+        builder.writeType(colorType.thisType);
+        builder.write(invocationString);
+      });
+    });
+
+    // We can only apply changes to the same file, so filter any change from the
+    // builder to only include this file, otherwise we may corrupt the users
+    // source (although hopefully we don't produce edits for other files).
+    final editsForThisFile = builder.sourceChange.edits
+        .where((edit) => edit.file == unit.path)
+        .expand((edit) => edit.edits)
+        .toList();
+
+    // LSP requires that we separate the main edit (changing the color code)
+    // from anything else (imports).
+    final mainEdit =
+        editsForThisFile.singleWhere((edit) => edit.offset == editRange.offset);
+    final otherEdits =
+        editsForThisFile.where((edit) => edit.offset != editRange.offset);
+
+    return ColorPresentation(
+      label: label,
+      textEdit: toTextEdit(unit.lineInfo, mainEdit),
+      additionalTextEdits: otherEdits.isNotEmpty
+          ? otherEdits.map((edit) => toTextEdit(unit.lineInfo, edit)).toList()
+          : null,
+    );
+  }
+
+  /// Builds a list of valid color presentations for the requested color.
+  Future<ErrorOr<List<ColorPresentation>>> _getPresentations(
+    ColorPresentationParams params,
+    ResolvedUnitResult unit,
+  ) async {
+    // The values in LSP are decimals 0-1 so should be scaled up to 255 that
+    // we use internally (except for opacity is which 0-1).
+    final alpha = (params.color.alpha * 255).toInt();
+    final red = (params.color.red * 255).toInt();
+    final green = (params.color.green * 255).toInt();
+    final blue = (params.color.blue * 255).toInt();
+    final opacity = params.color.alpha;
+
+    final editStart = toOffset(unit.lineInfo, params.range.start);
+    final editEnd = toOffset(unit.lineInfo, params.range.end);
+
+    if (editStart.isError) return failure(editStart);
+    if (editEnd.isError) return failure(editEnd);
+
+    final editRange =
+        SourceRange(editStart.result, editEnd.result - editStart.result);
+
+    final sessionHelper = AnalysisSessionHelper(unit.session);
+    final flutter = Flutter.instance;
+    final colorType = await sessionHelper.getClass(flutter.widgetsUri, 'Color');
+    if (colorType == null) {
+      // If we can't find the class (perhaps because this isn't a Flutter
+      // project) we will not include any results. In theory the client should
+      // not be calling this request in that case.
+      return success([]);
+    }
+
+    final colorValue = _colorValueForComponents(alpha, red, green, blue);
+    final colorValueHex =
+        '0x${colorValue.toRadixString(16).toUpperCase().padLeft(8, '0')}';
+
+    final colorFromARGB = await _createColorPresentation(
+      unit,
+      editRange,
+      colorType,
+      'Color.fromARGB($alpha, $red, $green, $blue)',
+      '.fromARGB($alpha, $red, $green, $blue)',
+    );
+
+    final colorFromRGBO = await _createColorPresentation(
+      unit,
+      editRange,
+      colorType,
+      'Color.fromRGBO($red, $green, $blue, $opacity)',
+      '.fromRGBO($red, $green, $blue, $opacity)',
+    );
+
+    final colorDefault = await _createColorPresentation(
+      unit,
+      editRange,
+      colorType,
+      'Color($colorValueHex)',
+      '($colorValueHex)',
+    );
+
+    return success([
+      colorFromARGB,
+      colorFromRGBO,
+      colorDefault,
+    ]);
+  }
+}
diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_states.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_states.dart
index c0e413d..0d9eb19 100644
--- a/pkg/analysis_server/lib/src/lsp/handlers/handler_states.dart
+++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_states.dart
@@ -15,6 +15,8 @@
 import 'package:analysis_server/src/lsp/handlers/handler_completion.dart';
 import 'package:analysis_server/src/lsp/handlers/handler_completion_resolve.dart';
 import 'package:analysis_server/src/lsp/handlers/handler_definition.dart';
+import 'package:analysis_server/src/lsp/handlers/handler_document_color.dart';
+import 'package:analysis_server/src/lsp/handlers/handler_document_color_presentation.dart';
 import 'package:analysis_server/src/lsp/handlers/handler_document_highlights.dart';
 import 'package:analysis_server/src/lsp/handlers/handler_document_symbols.dart';
 import 'package:analysis_server/src/lsp/handlers/handler_execute_command.dart';
@@ -77,6 +79,8 @@
       server,
       server.initializationOptions.suggestFromUnimportedLibraries,
     ));
+    registerHandler(DocumentColorHandler(server));
+    registerHandler(DocumentColorPresentationHandler(server));
     registerHandler(CompletionResolveHandler(server));
     registerHandler(SignatureHelpHandler(server));
     registerHandler(DefinitionHandler(server));
diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_workspace_symbols.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_workspace_symbols.dart
index 96a2cae..435013c 100644
--- a/pkg/analysis_server/lib/src/lsp/handlers/handler_workspace_symbols.dart
+++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_workspace_symbols.dart
@@ -7,7 +7,7 @@
 import 'package:analysis_server/src/lsp/handlers/handlers.dart';
 import 'package:analysis_server/src/lsp/lsp_analysis_server.dart';
 import 'package:analysis_server/src/lsp/mapping.dart';
-import 'package:analysis_server/src/search/workspace_symbols.dart' as search;
+import 'package:analyzer/src/dart/analysis/search.dart' as search;
 
 class WorkspaceSymbolHandler
     extends MessageHandler<WorkspaceSymbolParams, List<SymbolInformation>> {
@@ -52,24 +52,19 @@
     // huge numbers on large projects.
     var remainingResults = 500;
 
-    final filePathsHashSet = <String>{};
-    final tracker = server.declarationsTracker!;
-    final declarations = search.WorkspaceSymbols(tracker).declarations(
-      regex,
-      remainingResults,
-      filePathsHashSet,
-    );
-
-    // Convert the file paths to something we can quickly index into since
-    // we'll be looking things up by index a lot.
-    final filePaths = filePathsHashSet.toList();
+    var workspaceSymbols = search.WorkspaceSymbols();
+    var analysisDrivers = server.driverMap.values.toList();
+    for (var analysisDriver in analysisDrivers) {
+      await analysisDriver.search
+          .declarations(workspaceSymbols, regex, remainingResults);
+    }
 
     // Map the results to SymbolInformations and flatten the list of lists.
-    final symbols = declarations
+    final symbols = workspaceSymbols.declarations
         .map((declaration) => _asSymbolInformation(
               declaration,
               supportedSymbolKinds,
-              filePaths,
+              workspaceSymbols.files,
             ))
         .toList();
 
diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handlers.dart b/pkg/analysis_server/lib/src/lsp/handlers/handlers.dart
index 6b87d05..6b2ed52 100644
--- a/pkg/analysis_server/lib/src/lsp/handlers/handlers.dart
+++ b/pkg/analysis_server/lib/src/lsp/handlers/handlers.dart
@@ -134,7 +134,8 @@
   FutureOr<ErrorOr<R>> handleMessage(
       IncomingMessage message, CancellationToken token) {
     final reporter = LspJsonReporter('params');
-    if (!jsonHandler.validateParams(message.params, reporter)) {
+    final paramsJson = message.params as Map<String, Object?>?;
+    if (!jsonHandler.validateParams(paramsJson, reporter)) {
       return error(
         ErrorCodes.InvalidParams,
         'Invalid params for ${message.method}:\n'
@@ -144,9 +145,8 @@
       );
     }
 
-    final params = message.params != null
-        ? jsonHandler.convertParams(message.params)
-        : null as P;
+    final params =
+        paramsJson != null ? jsonHandler.convertParams(paramsJson) : null as P;
     return handle(params, token);
   }
 }
diff --git a/pkg/analysis_server/lib/src/lsp/lsp_analysis_server.dart b/pkg/analysis_server/lib/src/lsp/lsp_analysis_server.dart
index d33a96e..cf22460 100644
--- a/pkg/analysis_server/lib/src/lsp/lsp_analysis_server.dart
+++ b/pkg/analysis_server/lib/src/lsp/lsp_analysis_server.dart
@@ -374,17 +374,18 @@
 
   /// Logs an exception by sending it to the client (window/logMessage) and
   /// recording it in a buffer on the server for diagnostics.
-  void logException(String message, exception, stackTrace) {
+  void logException(String message, Object exception, StackTrace? stackTrace) {
     var fullMessage = message;
     if (exception is CaughtException) {
       stackTrace ??= exception.stackTrace;
       fullMessage = '$fullMessage: ${exception.exception}';
-    } else if (exception != null) {
+    } else {
       fullMessage = '$fullMessage: $exception';
     }
 
     final fullError =
         stackTrace == null ? fullMessage : '$fullMessage\n$stackTrace';
+    stackTrace ??= StackTrace.current;
 
     // Log the full message since showMessage above may be truncated or
     // formatted badly (eg. VS Code takes the newlines out).
@@ -394,7 +395,7 @@
     exceptions.add(ServerException(
       message,
       exception,
-      stackTrace is StackTrace ? stackTrace : StackTrace.current,
+      stackTrace,
       false,
     ));
 
@@ -550,9 +551,10 @@
   }
 
   @override
-  void sendServerErrorNotification(String message, exception, stackTrace,
+  void sendServerErrorNotification(
+      String message, Object exception, StackTrace? stackTrace,
       {bool fatal = false}) {
-    message = exception == null ? message : '$message: $exception';
+    message = '$message: $exception';
 
     // Show message (without stack) to the user.
     showErrorMessageToUser(message);
@@ -652,9 +654,9 @@
 
   /// There was an error related to the socket from which messages are being
   /// read.
-  void socketError(error, stack) {
+  void socketError(Object error, StackTrace? stackTrace) {
     // Don't send to instrumentation service; not an internal error.
-    sendServerErrorNotification('Socket error', error, stack);
+    sendServerErrorNotification('Socket error', error, stackTrace);
   }
 
   Future<void> updateWorkspaceFolders(
@@ -670,7 +672,7 @@
     _refreshAnalysisRoots();
   }
 
-  void _afterOverlayChanged(String path, dynamic changeForPlugins) {
+  void _afterOverlayChanged(String path, plugin.HasToJson changeForPlugins) {
     driverMap.values.forEach((driver) => driver.changeFile(path));
     pluginManager.setAnalysisUpdateContentParams(
       plugin.AnalysisUpdateContentParams({path: changeForPlugins}),
diff --git a/pkg/analysis_server/lib/src/lsp/mapping.dart b/pkg/analysis_server/lib/src/lsp/mapping.dart
index 3a3e421..ffabd19 100644
--- a/pkg/analysis_server/lib/src/lsp/mapping.dart
+++ b/pkg/analysis_server/lib/src/lsp/mapping.dart
@@ -20,12 +20,12 @@
 import 'package:analysis_server/src/lsp/source_edits.dart';
 import 'package:analysis_server/src/protocol_server.dart' as server
     hide AnalysisError;
-import 'package:analysis_server/src/search/workspace_symbols.dart' as server
-    show DeclarationKind;
 import 'package:analyzer/dart/analysis/results.dart' as server;
 import 'package:analyzer/error/error.dart' as server;
 import 'package:analyzer/source/line_info.dart' as server;
 import 'package:analyzer/source/source_range.dart' as server;
+import 'package:analyzer/src/dart/analysis/search.dart' as server
+    show DeclarationKind;
 import 'package:analyzer/src/error/codes.dart';
 import 'package:analyzer/src/services/available_declarations.dart';
 import 'package:analyzer/src/services/available_declarations.dart' as dec;
@@ -1225,12 +1225,12 @@
 ErrorOr<int> toOffset(
   server.LineInfo lineInfo,
   lsp.Position pos, {
-  failureIsCritial = false,
+  bool failureIsCritical = false,
 }) {
   // line is zero-based so cannot equal lineCount
   if (pos.line >= lineInfo.lineCount) {
     return ErrorOr<int>.error(lsp.ResponseError(
-        code: failureIsCritial
+        code: failureIsCritical
             ? lsp.ServerErrorCodes.ClientServerInconsistentState
             : lsp.ServerErrorCodes.InvalidFileLineCol,
         message: 'Invalid line number',
diff --git a/pkg/analysis_server/lib/src/lsp/server_capabilities_computer.dart b/pkg/analysis_server/lib/src/lsp/server_capabilities_computer.dart
index 36bff9b..5a009f5 100644
--- a/pkg/analysis_server/lib/src/lsp/server_capabilities_computer.dart
+++ b/pkg/analysis_server/lib/src/lsp/server_capabilities_computer.dart
@@ -30,6 +30,7 @@
     Method.textDocument_signatureHelp,
     Method.textDocument_references,
     Method.textDocument_documentHighlight,
+    Method.textDocument_documentColor,
     Method.textDocument_formatting,
     Method.textDocument_onTypeFormatting,
     Method.textDocument_rangeFormatting,
@@ -52,6 +53,9 @@
   bool get codeActions =>
       _capabilities.textDocument?.foldingRange?.dynamicRegistration ?? false;
 
+  bool get colorProvider =>
+      _capabilities.textDocument?.colorProvider?.dynamicRegistration ?? false;
+
   bool get completion =>
       _capabilities.textDocument?.completion?.dynamicRegistration ?? false;
 
@@ -130,8 +134,15 @@
   Set<Registration> currentRegistrations = {};
   var _lastRegistrationId = 0;
 
-  ServerCapabilitiesComputer(this._server);
+  final dartFiles = DocumentFilter(language: 'dart', scheme: 'file');
+  final pubspecFile = DocumentFilter(
+      language: 'yaml', scheme: 'file', pattern: '**/pubspec.yaml');
+  final analysisOptionsFile = DocumentFilter(
+      language: 'yaml', scheme: 'file', pattern: '**/analysis_options.yaml');
+  final fixDataFile = DocumentFilter(
+      language: 'yaml', scheme: 'file', pattern: '**/lib/fix_data.yaml');
 
+  ServerCapabilitiesComputer(this._server);
   ServerCapabilities computeServerCapabilities(
       LspClientCapabilities clientCapabilities) {
     final codeActionLiteralSupport = clientCapabilities.literalCodeActions;
@@ -210,6 +221,11 @@
                   codeActionKinds: DartCodeActionKind.serverSupportedKinds,
                 ))
               : Either2<bool, CodeActionOptions>.t1(true),
+      colorProvider: dynamicRegistrations.colorProvider
+          ? null
+          : Either3<bool, DocumentColorOptions,
+                  DocumentColorRegistrationOptions>.t3(
+              DocumentColorRegistrationOptions(documentSelector: [dartFiles])),
       documentFormattingProvider: dynamicRegistrations.formatting
           ? null
           : Either2<bool, DocumentFormattingOptions>.t1(enableFormatter),
@@ -279,14 +295,6 @@
   /// support and it will be up to them to decide which file types they will
   /// send requests for.
   Future<void> performDynamicRegistration() async {
-    final dartFiles = DocumentFilter(language: 'dart', scheme: 'file');
-    final pubspecFile = DocumentFilter(
-        language: 'yaml', scheme: 'file', pattern: '**/pubspec.yaml');
-    final analysisOptionsFile = DocumentFilter(
-        language: 'yaml', scheme: 'file', pattern: '**/analysis_options.yaml');
-    final fixDataFile = DocumentFilter(
-        language: 'yaml', scheme: 'file', pattern: '**/lib/fix_data.yaml');
-
     final pluginTypes = _server.pluginManager.plugins
         .expand((plugin) => plugin.currentSession?.interestingFiles ?? const [])
         // All published plugins use something like `*.extension` as
@@ -410,6 +418,12 @@
       TextDocumentRegistrationOptions(documentSelector: fullySupportedTypes),
     );
     register(
+      dynamicRegistrations.colorProvider,
+      // This registration covers both documentColor and colorPresentation.
+      Method.textDocument_documentColor,
+      DocumentColorRegistrationOptions(documentSelector: [dartFiles]),
+    );
+    register(
       enableFormatter && dynamicRegistrations.formatting,
       Method.textDocument_formatting,
       TextDocumentRegistrationOptions(documentSelector: fullySupportedTypes),
diff --git a/pkg/analysis_server/lib/src/lsp/source_edits.dart b/pkg/analysis_server/lib/src/lsp/source_edits.dart
index 2a5834e..1e2b464 100644
--- a/pkg/analysis_server/lib/src/lsp/source_edits.dart
+++ b/pkg/analysis_server/lib/src/lsp/source_edits.dart
@@ -31,7 +31,7 @@
           Either2<TextDocumentContentChangeEvent1,
               TextDocumentContentChangeEvent2>>
       changes, {
-  failureIsCritical = false,
+  bool failureIsCritical = false,
 }) {
   var newContent = oldContent;
   final serverEdits = <server.SourceEdit>[];
@@ -45,9 +45,9 @@
       (change) {
         final lines = LineInfo.fromContent(newContent);
         final offsetStart = toOffset(lines, change.range.start,
-            failureIsCritial: failureIsCritical);
+            failureIsCritical: failureIsCritical);
         final offsetEnd = toOffset(lines, change.range.end,
-            failureIsCritial: failureIsCritical);
+            failureIsCritical: failureIsCritical);
         if (offsetStart.isError) {
           return ErrorOr.error(offsetStart.error);
         }
@@ -180,7 +180,10 @@
       // To handle this, if both unformatted/formatted contain at least one
       // newline, split this change into two around the last newline so that the
       // final part (likely leading whitespace) can be included without
-      // including the whole change.
+      // including the whole change. This cannot be done if the newline is at
+      // the end of the source whitespace though, as this would create a split
+      // where the first part is the same and the second part is empty,
+      // resulting in an infinite loop/stack overflow.
       //
       // Without this, functionality like VS Code's "format modified lines"
       // (which uses Git status to know which lines are edited) may appear to
@@ -188,7 +191,8 @@
       if (unformattedStart < rangeStart.result &&
           unformattedEnd > rangeStart.result &&
           unformattedWhitespace.contains('\n') &&
-          formattedWhitespace.contains('\n')) {
+          formattedWhitespace.contains('\n') &&
+          !unformattedWhitespace.endsWith('\n')) {
         // Find the offsets of the character after the last newlines.
         final unformattedOffset = unformattedWhitespace.lastIndexOf('\n') + 1;
         final formattedOffset = formattedWhitespace.lastIndexOf('\n') + 1;
diff --git a/pkg/analysis_server/lib/src/search/search_domain.dart b/pkg/analysis_server/lib/src/search/search_domain.dart
index 632f7f8..04542a8 100644
--- a/pkg/analysis_server/lib/src/search/search_domain.dart
+++ b/pkg/analysis_server/lib/src/search/search_domain.dart
@@ -5,12 +5,14 @@
 import 'package:analysis_server/protocol/protocol.dart';
 import 'package:analysis_server/protocol/protocol_constants.dart';
 import 'package:analysis_server/src/analysis_server.dart';
+import 'package:analysis_server/src/protocol/protocol_internal.dart'
+    show ResponseResult;
 import 'package:analysis_server/src/protocol_server.dart' as protocol;
 import 'package:analysis_server/src/search/element_references.dart';
 import 'package:analysis_server/src/search/type_hierarchy.dart';
-import 'package:analysis_server/src/search/workspace_symbols.dart' as search;
 import 'package:analysis_server/src/services/search/search_engine.dart';
 import 'package:analyzer/dart/element/element.dart';
+import 'package:analyzer/src/dart/analysis/search.dart' as search;
 
 /// Instances of the class [SearchDomainHandler] implement a [RequestHandler]
 /// that handles requests in the search domain.
@@ -161,21 +163,21 @@
       }
     }
 
-    var tracker = server.declarationsTracker;
-    if (tracker == null) {
+    if (!server.options.featureSet.completion) {
       server.sendResponse(Response.unsupportedFeature(
           request.id, 'Completion is not enabled.'));
       return;
     }
-    var files = <String>{};
-    var remainingMaxResults = params.maxResults;
-    var declarations = search.WorkspaceSymbols(tracker).declarations(
-      regExp,
-      remainingMaxResults,
-      files,
-      onlyForFile: params.file,
-    );
 
+    var workspaceSymbols = search.WorkspaceSymbols();
+    var analysisDrivers = server.driverMap.values.toList();
+    for (var analysisDriver in analysisDrivers) {
+      await analysisDriver.search.declarations(
+          workspaceSymbols, regExp, params.maxResults,
+          onlyForFile: params.file);
+    }
+
+    var declarations = workspaceSymbols.declarations;
     var elementDeclarations = declarations.map((declaration) {
       return protocol.ElementDeclaration(
           declaration.name,
@@ -192,7 +194,7 @@
     }).toList();
 
     server.sendResponse(protocol.SearchGetElementDeclarationsResult(
-            elementDeclarations, files.toList())
+            elementDeclarations, workspaceSymbols.files)
         .toResponse(request.id));
   }
 
@@ -262,8 +264,8 @@
   }
 
   /// Send a search response with the given [result] to the given [request].
-  void _sendSearchResult(protocol.Request request, result) {
-    protocol.Response response = result.toResponse(request.id);
+  void _sendSearchResult(protocol.Request request, ResponseResult result) {
+    var response = result.toResponse(request.id);
     server.sendResponse(response);
   }
 
diff --git a/pkg/analysis_server/lib/src/search/workspace_symbols.dart b/pkg/analysis_server/lib/src/search/workspace_symbols.dart
deleted file mode 100644
index bbcf5ac..0000000
--- a/pkg/analysis_server/lib/src/search/workspace_symbols.dart
+++ /dev/null
@@ -1,203 +0,0 @@
-// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/source/line_info.dart';
-import 'package:analyzer/src/services/available_declarations.dart';
-import 'package:analyzer/src/services/available_declarations.dart' as ad;
-
-class Declaration {
-  final int fileIndex;
-  final LineInfo lineInfo;
-  final String name;
-  final DeclarationKind kind;
-  final int offset;
-  final int line;
-  final int column;
-  final int codeOffset;
-  final int codeLength;
-  final String? className;
-  final String? mixinName;
-  final String? parameters;
-
-  Declaration(
-    this.fileIndex,
-    this.lineInfo,
-    this.name,
-    this.kind,
-    this.offset,
-    this.line,
-    this.column,
-    this.codeOffset,
-    this.codeLength,
-    this.className,
-    this.mixinName,
-    this.parameters,
-  );
-}
-
-enum DeclarationKind {
-  CLASS,
-  CLASS_TYPE_ALIAS,
-  CONSTRUCTOR,
-  ENUM,
-  ENUM_CONSTANT,
-  EXTENSION,
-  FIELD,
-  FUNCTION,
-  FUNCTION_TYPE_ALIAS,
-  GETTER,
-  METHOD,
-  MIXIN,
-  SETTER,
-  TYPE_ALIAS,
-  VARIABLE
-}
-
-class WorkspaceSymbols {
-  final DeclarationsTracker tracker;
-
-  WorkspaceSymbols(this.tracker);
-
-  List<Declaration> declarations(
-      RegExp? regExp, int? maxResults, Set<String> files,
-      {String? onlyForFile}) {
-    _doTrackerWork();
-
-    var declarations = <Declaration>[];
-
-    var pathToIndex = <String, int>{};
-
-    int getPathIndex(String path) {
-      var index = pathToIndex[path];
-      if (index == null) {
-        index = files.length;
-        files.add(path);
-        pathToIndex[path] = index;
-      }
-      return index;
-    }
-
-    if (maxResults != null && declarations.length >= maxResults) {
-      throw const _MaxNumberOfDeclarationsError();
-    }
-
-    void addDeclaration(ad.Declaration declaration) {
-      if (maxResults != null && declarations.length >= maxResults) {
-        throw const _MaxNumberOfDeclarationsError();
-      }
-
-      var path = declaration.locationPath;
-      if (onlyForFile != null && path != onlyForFile) {
-        return;
-      }
-
-      declaration.children.forEach(addDeclaration);
-
-      var name = declaration.name;
-      if (name.isEmpty) {
-        return;
-      }
-      if (name.endsWith('=')) {
-        name = name.substring(0, name.length - 1);
-      }
-      if (regExp != null && !regExp.hasMatch(name)) {
-        return;
-      }
-
-      var parent = declaration.parent;
-
-      String? className;
-      if (parent != null && parent.kind == ad.DeclarationKind.CLASS) {
-        className = parent.name;
-      }
-
-      String? mixinName;
-      if (parent != null && parent.kind == ad.DeclarationKind.MIXIN) {
-        mixinName = parent.name;
-      }
-
-      var topKind = _getTopKind(declaration.kind);
-      if (topKind == null) {
-        return;
-      }
-
-      declarations.add(
-        Declaration(
-          getPathIndex(path),
-          declaration.lineInfo,
-          name,
-          topKind,
-          declaration.locationOffset,
-          declaration.locationStartLine,
-          declaration.locationStartColumn,
-          declaration.codeOffset,
-          declaration.codeLength,
-          className,
-          mixinName,
-          declaration.parameters,
-        ),
-      );
-    }
-
-    var libraries = tracker.allLibraries;
-    try {
-      for (var library in libraries) {
-        library.declarations.forEach(addDeclaration);
-      }
-    } on _MaxNumberOfDeclarationsError {
-      // Uses an exception to short circuit the recursion when there are too
-      // many declarations.
-    }
-
-    return declarations;
-  }
-
-  void _doTrackerWork() {
-    while (tracker.hasWork) {
-      tracker.doWork();
-    }
-  }
-
-  static DeclarationKind? _getTopKind(ad.DeclarationKind kind) {
-    switch (kind) {
-      case ad.DeclarationKind.CLASS:
-        return DeclarationKind.CLASS;
-      case ad.DeclarationKind.CLASS_TYPE_ALIAS:
-        return DeclarationKind.CLASS_TYPE_ALIAS;
-      case ad.DeclarationKind.CONSTRUCTOR:
-        return DeclarationKind.CONSTRUCTOR;
-      case ad.DeclarationKind.ENUM:
-        return DeclarationKind.ENUM;
-      case ad.DeclarationKind.ENUM_CONSTANT:
-        return DeclarationKind.ENUM_CONSTANT;
-      case ad.DeclarationKind.EXTENSION:
-        return DeclarationKind.EXTENSION;
-      case ad.DeclarationKind.FIELD:
-        return DeclarationKind.FIELD;
-      case ad.DeclarationKind.FUNCTION_TYPE_ALIAS:
-        return DeclarationKind.FUNCTION_TYPE_ALIAS;
-      case ad.DeclarationKind.METHOD:
-        return DeclarationKind.METHOD;
-      case ad.DeclarationKind.MIXIN:
-        return DeclarationKind.MIXIN;
-      case ad.DeclarationKind.FUNCTION:
-        return DeclarationKind.FUNCTION;
-      case ad.DeclarationKind.GETTER:
-        return DeclarationKind.GETTER;
-      case ad.DeclarationKind.SETTER:
-        return DeclarationKind.SETTER;
-      case ad.DeclarationKind.TYPE_ALIAS:
-        return DeclarationKind.TYPE_ALIAS;
-      case ad.DeclarationKind.VARIABLE:
-        return DeclarationKind.VARIABLE;
-      default:
-        return null;
-    }
-  }
-}
-
-/// The marker class that is thrown to stop adding declarations.
-class _MaxNumberOfDeclarationsError {
-  const _MaxNumberOfDeclarationsError();
-}
diff --git a/pkg/analysis_server/lib/src/server/debounce_requests.dart b/pkg/analysis_server/lib/src/server/debounce_requests.dart
new file mode 100644
index 0000000..4ee01d6
--- /dev/null
+++ b/pkg/analysis_server/lib/src/server/debounce_requests.dart
@@ -0,0 +1,83 @@
+// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'dart:async';
+
+import 'package:analysis_server/protocol/protocol.dart';
+import 'package:analysis_server/protocol/protocol_constants.dart';
+import 'package:analysis_server/protocol/protocol_generated.dart';
+import 'package:analysis_server/src/channel/channel.dart';
+
+/// Return the stream of requests that is filtered to exclude requests for
+/// which the client does not need actual responses.
+///
+/// If there is one completion request, and then another completion request,
+/// then most probably the user continued typing, and there is no need to
+/// compute results for the first request. But we will have to respond, an
+/// empty response is enough.
+///
+/// Discarded requests are reported into [discardedRequests].
+Stream<Request> debounceRequests(
+  ServerCommunicationChannel channel,
+  StreamController<Request> discardedRequests,
+) {
+  return _DebounceRequests(channel, discardedRequests).requests;
+}
+
+class _DebounceRequests {
+  final ServerCommunicationChannel channel;
+  final StreamController<Request> discardedRequests;
+  late final Stream<Request> requests;
+
+  _DebounceRequests(this.channel, this.discardedRequests) {
+    var buffer = <Request>[];
+    Timer? timer;
+
+    requests = channel.requests.transform(
+      StreamTransformer.fromHandlers(
+        handleData: (request, sink) {
+          buffer.add(request);
+          // Accumulate requests for a short period of time.
+          // When we were busy processing a request, the client could put
+          // multiple requests into the event queue. So, when we look, we will
+          // quickly get all of them. So, even 1 ms should be enough.
+          timer ??= Timer(const Duration(milliseconds: 1), () {
+            timer = null;
+            var filtered = _filterCompletion(buffer);
+            buffer = [];
+            for (var request in filtered) {
+              sink.add(request);
+            }
+          });
+        },
+      ),
+    );
+  }
+
+  List<Request> _filterCompletion(List<Request> requests) {
+    var reversed = <Request>[];
+    var abortCompletionRequests = false;
+    for (var request in requests.reversed) {
+      if (request.method == ANALYSIS_REQUEST_UPDATE_CONTENT) {
+        abortCompletionRequests = true;
+      }
+      if (request.method == COMPLETION_REQUEST_GET_SUGGESTIONS2) {
+        if (abortCompletionRequests) {
+          discardedRequests.add(request);
+          var params = CompletionGetSuggestions2Params.fromRequest(request);
+          var offset = params.offset;
+          channel.sendResponse(
+            CompletionGetSuggestions2Result(offset, 0, [], [], true)
+                .toResponse(request.id),
+          );
+          continue;
+        } else {
+          abortCompletionRequests = true;
+        }
+      }
+      reversed.add(request);
+    }
+    return reversed.reversed.toList();
+  }
+}
diff --git a/pkg/analysis_server/lib/src/server/dev_server.dart b/pkg/analysis_server/lib/src/server/dev_server.dart
index 62886da6..b11c418 100644
--- a/pkg/analysis_server/lib/src/server/dev_server.dart
+++ b/pkg/analysis_server/lib/src/server/dev_server.dart
@@ -165,21 +165,11 @@
   Stream<Notification> get onNotification => _notificationController.stream;
 
   @override
-  void close() {
-    _notificationController.close();
-  }
+  Stream<Request> get requests => _requestController.stream;
 
   @override
-  void listen(
-    void Function(Request request) onRequest, {
-    Function? onError,
-    void Function()? onDone,
-  }) {
-    _requestController.stream.listen(
-      onRequest,
-      onError: onError,
-      onDone: onDone,
-    );
+  void close() {
+    _notificationController.close();
   }
 
   @override
diff --git a/pkg/analysis_server/lib/src/server/driver.dart b/pkg/analysis_server/lib/src/server/driver.dart
index 025eb5b..5016f76 100644
--- a/pkg/analysis_server/lib/src/server/driver.dart
+++ b/pkg/analysis_server/lib/src/server/driver.dart
@@ -101,6 +101,9 @@
   /// The path to the package config file override.
   static const String PACKAGES_FILE = 'packages';
 
+  /// The forced protocol version that the server will report to the client.
+  static const String REPORT_PROTOCOL_VERSION = 'report-protocol-version';
+
   /// The name of the flag specifying the server protocol to use.
   static const String SERVER_PROTOCOL = 'protocol';
   static const String PROTOCOL_ANALYZER = 'analyzer';
@@ -160,6 +163,8 @@
     analysisServerOptions.clientVersion = results[CLIENT_VERSION];
     analysisServerOptions.cacheFolder = results[CACHE_FOLDER];
     analysisServerOptions.packagesFile = results[PACKAGES_FILE];
+    analysisServerOptions.reportProtocolVersion =
+        results[REPORT_PROTOCOL_VERSION];
 
     // Read in any per-SDK overrides specified in <sdk>/config/settings.json.
     var sdkConfig = SdkConfiguration.readFromSdk();
@@ -688,6 +693,14 @@
         defaultsTo: false,
         negatable: false,
         hide: true);
+    parser.addOption(
+      REPORT_PROTOCOL_VERSION,
+      valueHelp: 'version',
+      help: 'The protocol version that the server will report to the client, '
+          'can be used to temporary enabling features that we expect to be '
+          'available in future versions.',
+      hide: true,
+    );
 
     //
     // Hidden; these are deprecated and no longer read from.
diff --git a/pkg/analysis_server/lib/src/services/completion/completion_performance.dart b/pkg/analysis_server/lib/src/services/completion/completion_performance.dart
index b0c2ac4..7815def 100644
--- a/pkg/analysis_server/lib/src/services/completion/completion_performance.dart
+++ b/pkg/analysis_server/lib/src/services/completion/completion_performance.dart
@@ -35,16 +35,19 @@
 
 /// Overall performance of a code completion operation.
 class CompletionPerformance {
-  String? path;
-  String snippet = '';
+  final OperationPerformance operation;
+  final String path;
+  final String snippet;
   int suggestionCount = -1;
-  OperationPerformance? _operation;
+
+  CompletionPerformance({
+    required this.operation,
+    required this.path,
+    required String content,
+    required int offset,
+  }) : snippet = _computeCompletionSnippet(content, offset);
 
   int get elapsedInMilliseconds {
-    var operation = _operation;
-    if (operation == null) {
-      throw StateError('Access of elapsed time before the operation is run');
-    }
     return operation.elapsed.inMilliseconds;
   }
 
@@ -52,21 +55,4 @@
     if (suggestionCount < 1) return '';
     return '$suggestionCount';
   }
-
-  Future<T> runRequestOperation<T>(
-    Future<T> Function(OperationPerformanceImpl) operation,
-  ) async {
-    var rootOperation = OperationPerformanceImpl('<root>');
-    try {
-      return rootOperation.runAsync('<request>', (performance) async {
-        return await operation(performance);
-      });
-    } finally {
-      _operation = rootOperation.children.first;
-    }
-  }
-
-  void setContentsAndOffset(String contents, int offset) {
-    snippet = _computeCompletionSnippet(contents, offset);
-  }
 }
diff --git a/pkg/analysis_server/lib/src/services/completion/dart/completion_manager.dart b/pkg/analysis_server/lib/src/services/completion/dart/completion_manager.dart
index 78fef2f..90da0ef 100644
--- a/pkg/analysis_server/lib/src/services/completion/dart/completion_manager.dart
+++ b/pkg/analysis_server/lib/src/services/completion/dart/completion_manager.dart
@@ -37,6 +37,7 @@
 import 'package:analyzer/dart/element/type.dart';
 import 'package:analyzer/file_system/file_system.dart';
 import 'package:analyzer/src/dart/analysis/driver_based_analysis_context.dart';
+import 'package:analyzer/src/dart/analysis/session.dart';
 import 'package:analyzer/src/dartdoc/dartdoc_directive_info.dart';
 import 'package:analyzer/src/generated/source.dart';
 import 'package:analyzer/src/util/file_paths.dart' as file_paths;
@@ -90,10 +91,11 @@
   /// suggestions, or `null` if no notification should occur.
   final SuggestionListener? listener;
 
-  /// If specified, will be filled with URIs of libraries that are not yet
-  /// imported, but could be imported into the requested target. Corresponding
-  /// [CompletionSuggestion] will have the import index into this list.
-  final List<Uri>? librariesToImport;
+  /// If specified, will be filled with suggestions and URIs from libraries
+  /// that are not yet imported, but could be imported into the requested
+  /// target. It is up to the client to make copies of [CompletionSuggestion]s
+  /// with the import index property updated.
+  final Map<protocol.CompletionSuggestion, Uri>? notImportedSuggestions;
 
   /// Initialize a newly created completion manager. The parameters
   /// [includedElementKinds], [includedElementNames], and
@@ -105,7 +107,7 @@
     this.includedElementNames,
     this.includedSuggestionRelevanceTags,
     this.listener,
-    this.librariesToImport,
+    this.notImportedSuggestions,
   }) : assert((includedElementKinds != null &&
                 includedElementNames != null &&
                 includedSuggestionRelevanceTags != null) ||
@@ -121,7 +123,7 @@
   }) async {
     request.checkAborted();
     var pathContext = request.resourceProvider.pathContext;
-    if (!file_paths.isDart(pathContext, request.result.path)) {
+    if (!file_paths.isDart(pathContext, request.path)) {
       return const <CompletionSuggestion>[];
     }
 
@@ -163,10 +165,11 @@
       );
     }
 
-    final librariesToImport = this.librariesToImport;
-    if (librariesToImport != null) {
+    final notImportedSuggestions = this.notImportedSuggestions;
+    if (notImportedSuggestions != null) {
       contributors.add(
-        NotImportedContributor(request, builder, budget, librariesToImport),
+        NotImportedContributor(
+            request, builder, budget, notImportedSuggestions),
       );
     }
 
@@ -274,8 +277,14 @@
 
 /// The information about a requested list of completions within a Dart file.
 class DartCompletionRequest {
+  /// The analysis session that produced the elements of the request.
+  final AnalysisSessionImpl analysisSession;
+
   final CompletionPreference completionPreference;
 
+  /// The content of the file in which completion is requested.
+  final String content;
+
   /// Return the type imposed on the target's `containingNode` based on its
   /// context, or `null` if the context does not impose any type.
   final DartType? contextType;
@@ -289,6 +298,9 @@
   /// compute relevance scores for suggestions.
   final FeatureComputer featureComputer;
 
+  /// The library element of the file in which completion is requested.
+  final LibraryElement libraryElement;
+
   /// Return the offset within the source at which the completion is being
   /// requested.
   final int offset;
@@ -297,14 +309,13 @@
   /// request.
   final OpType opType;
 
+  /// The absolute path of the file where completion is requested.
+  final String path;
+
   /// The source range that represents the region of text that should be
   /// replaced when a suggestion is selected.
   final SourceRange replacementRange;
 
-  /// The analysis result for the file in which the completion is being
-  /// requested.
-  final ResolvedUnitResult result;
-
   /// Return the source in which the completion is being requested.
   final Source source;
 
@@ -317,17 +328,22 @@
   bool _aborted = false;
 
   factory DartCompletionRequest({
-    required ResolvedUnitResult resolvedUnit,
+    required AnalysisSession analysisSession,
+    required String filePath,
+    required String fileContent,
+    required CompilationUnitElement unitElement,
+    required AstNode enclosingNode,
     required int offset,
     DartdocDirectiveInfo? dartdocDirectiveInfo,
     CompletionPreference completionPreference = CompletionPreference.insert,
     DocumentationCache? documentationCache,
   }) {
-    var target = CompletionTarget.forOffset(resolvedUnit.unit, offset);
+    var target = CompletionTarget.forOffset(enclosingNode, offset);
 
+    var libraryElement = unitElement.library;
     var featureComputer = FeatureComputer(
-      resolvedUnit.typeSystem,
-      resolvedUnit.typeProvider,
+      libraryElement.typeSystem,
+      libraryElement.typeProvider,
     );
 
     var contextType = featureComputer.computeContextType(
@@ -341,34 +357,65 @@
     }
 
     return DartCompletionRequest._(
+      analysisSession: analysisSession as AnalysisSessionImpl,
       completionPreference: completionPreference,
+      content: fileContent,
       contextType: contextType,
       dartdocDirectiveInfo: dartdocDirectiveInfo ?? DartdocDirectiveInfo(),
       documentationCache: documentationCache,
       featureComputer: featureComputer,
+      libraryElement: libraryElement,
       offset: offset,
       opType: opType,
+      path: filePath,
       replacementRange: target.computeReplacementRange(offset),
-      result: resolvedUnit,
-      source: resolvedUnit.unit.declaredElement!.source,
+      source: unitElement.source,
       target: target,
     );
   }
 
+  factory DartCompletionRequest.forResolvedUnit({
+    required ResolvedUnitResult resolvedUnit,
+    required int offset,
+    DartdocDirectiveInfo? dartdocDirectiveInfo,
+    CompletionPreference completionPreference = CompletionPreference.insert,
+    DocumentationCache? documentationCache,
+  }) {
+    return DartCompletionRequest(
+      analysisSession: resolvedUnit.session,
+      filePath: resolvedUnit.path,
+      fileContent: resolvedUnit.content,
+      unitElement: resolvedUnit.unit.declaredElement!,
+      enclosingNode: resolvedUnit.unit,
+      offset: offset,
+      dartdocDirectiveInfo: dartdocDirectiveInfo,
+      completionPreference: completionPreference,
+      documentationCache: documentationCache,
+    );
+  }
+
   DartCompletionRequest._({
+    required this.analysisSession,
     required this.completionPreference,
+    required this.content,
     required this.contextType,
     required this.dartdocDirectiveInfo,
     required this.documentationCache,
     required this.featureComputer,
+    required this.libraryElement,
     required this.offset,
     required this.opType,
+    required this.path,
     required this.replacementRange,
-    required this.result,
     required this.source,
     required this.target,
   });
 
+  DriverBasedAnalysisContext get analysisContext {
+    var analysisContext = analysisSession.analysisContext;
+    return analysisContext as DriverBasedAnalysisContext;
+  }
+
   /// Return the feature set that was used to analyze the compilation unit in
   /// which suggestions are being made.
   FeatureSet get featureSet => libraryElement.featureSet;
@@ -384,10 +431,6 @@
     return entity is Expression && entity.inConstantContext;
   }
 
-  /// Return the library element which contains the unit in which the completion
-  /// is occurring.
-  LibraryElement get libraryElement => result.libraryElement;
-
   /// Answer the [DartType] for Object in dart:core
   DartType get objectType => libraryElement.typeProvider.objectType;
 
@@ -406,16 +449,11 @@
   int get replacementOffset => replacementRange.offset;
 
   /// Return the resource provider associated with this request.
-  ResourceProvider get resourceProvider => result.session.resourceProvider;
-
-  /// Return the content of the [source] in which the completion is being
-  /// requested, or `null` if the content could not be accessed.
-  String? get sourceContents => result.content;
+  ResourceProvider get resourceProvider => analysisSession.resourceProvider;
 
   /// Return the [SourceFactory] of the request.
   SourceFactory get sourceFactory {
-    var context = result.session.analysisContext as DriverBasedAnalysisContext;
-    return context.driver.sourceFactory;
+    return analysisContext.driver.sourceFactory;
   }
 
   /// Return prefix that already exists in the document for [target] or empty
diff --git a/pkg/analysis_server/lib/src/services/completion/dart/local_library_contributor.dart b/pkg/analysis_server/lib/src/services/completion/dart/local_library_contributor.dart
index 734a36e..2441362 100644
--- a/pkg/analysis_server/lib/src/services/completion/dart/local_library_contributor.dart
+++ b/pkg/analysis_server/lib/src/services/completion/dart/local_library_contributor.dart
@@ -163,13 +163,8 @@
       return;
     }
 
-    var libraryUnits = request.result.unit.declaredElement?.library.units;
-    if (libraryUnits == null) {
-      return;
-    }
-
     var visitor = LibraryElementSuggestionBuilder(request, builder);
-    for (var unit in libraryUnits) {
+    for (var unit in request.libraryElement.units) {
       if (unit.source != request.source) {
         unit.accept(visitor);
       }
diff --git a/pkg/analysis_server/lib/src/services/completion/dart/not_imported_contributor.dart b/pkg/analysis_server/lib/src/services/completion/dart/not_imported_contributor.dart
index 629fe475..53550d8 100644
--- a/pkg/analysis_server/lib/src/services/completion/dart/not_imported_contributor.dart
+++ b/pkg/analysis_server/lib/src/services/completion/dart/not_imported_contributor.dart
@@ -4,40 +4,33 @@
 
 import 'dart:async';
 
+import 'package:analysis_server/src/protocol_server.dart' as protocol;
 import 'package:analysis_server/src/provisional/completion/dart/completion_dart.dart';
 import 'package:analysis_server/src/services/completion/dart/completion_manager.dart';
 import 'package:analysis_server/src/services/completion/dart/extension_member_contributor.dart';
 import 'package:analysis_server/src/services/completion/dart/local_library_contributor.dart';
 import 'package:analysis_server/src/services/completion/dart/suggestion_builder.dart';
-import 'package:analyzer/dart/analysis/results.dart';
 import 'package:analyzer/dart/element/element.dart';
 import 'package:analyzer/src/dart/analysis/file_state.dart';
-import 'package:analyzer/src/dart/analysis/session.dart';
 import 'package:analyzer/src/lint/pub.dart';
 import 'package:analyzer/src/workspace/pub.dart';
 import 'package:collection/collection.dart';
-import 'package:meta/meta.dart';
 
 /// A contributor of suggestions from not yet imported libraries.
 class NotImportedContributor extends DartCompletionContributor {
-  /// Tests set this function to abort the current request.
-  @visibleForTesting
-  static void Function(FileState)? onFile;
-
   final CompletionBudget budget;
-  final List<Uri> librariesToImport;
+  final Map<protocol.CompletionSuggestion, Uri> notImportedSuggestions;
 
   NotImportedContributor(
     DartCompletionRequest request,
     SuggestionBuilder builder,
     this.budget,
-    this.librariesToImport,
+    this.notImportedSuggestions,
   ) : super(request, builder);
 
   @override
   Future<void> computeSuggestions() async {
-    var session = request.result.session as AnalysisSessionImpl;
-    var analysisDriver = session.getDriver(); // ignore: deprecated_member_use
+    var analysisDriver = request.analysisContext.driver;
 
     var fsState = analysisDriver.fsState;
     var filter = _buildFilter(fsState);
@@ -53,9 +46,6 @@
 
     var knownFiles = fsState.knownFiles.toList();
     for (var file in knownFiles) {
-      onFile?.call(file);
-      request.checkAborted();
-
       if (budget.isEmpty) {
         return;
       }
@@ -64,15 +54,18 @@
         continue;
       }
 
-      var elementResult = await session.getLibraryByUri(file.uriStr);
-      if (elementResult is! LibraryElementResult) {
+      var element = analysisDriver.getLibraryByFile(file);
+      if (element == null) {
         continue;
       }
 
-      var exportNamespace = elementResult.element.exportNamespace;
+      var exportNamespace = element.exportNamespace;
       var exportElements = exportNamespace.definedNames.values.toList();
 
-      var newSuggestions = builder.markSuggestions();
+      builder.laterReplacesEarlier = false;
+      builder.suggestionAdded = (suggestion) {
+        notImportedSuggestions[suggestion] = file.uri;
+      };
 
       if (request.includeIdentifiers) {
         _buildSuggestions(exportElements);
@@ -81,16 +74,14 @@
       extensionContributor.addExtensions(
         exportElements.whereType<ExtensionElement>().toList(),
       );
-
-      newSuggestions.setLibraryUriToImportIndex(() {
-        librariesToImport.add(file.uri);
-        return librariesToImport.length - 1;
-      });
     }
+
+    builder.laterReplacesEarlier = true;
+    builder.suggestionAdded = null;
   }
 
   _Filter _buildFilter(FileSystemState fsState) {
-    var file = fsState.getFileForPath(request.result.path);
+    var file = fsState.getFileForPath(request.path);
     var workspacePackage = file.workspacePackage;
     if (workspacePackage is PubWorkspacePackage) {
       return _PubFilter(workspacePackage, file.path);
@@ -154,14 +145,15 @@
 
   @override
   bool shouldInclude(FileState file) {
-    var uri = file.uri;
-    if (uri.isScheme('dart')) {
+    var uri = file.uriProperties;
+    if (uri.isDart) {
       return true;
     }
 
     // Normally only package URIs are available.
     // But outside of lib/ we allow any files of this package.
-    if (!uri.isScheme('package')) {
+    var packageName = uri.packageName;
+    if (packageName == null) {
       if (targetInLib) {
         return false;
       } else {
@@ -171,20 +163,13 @@
       }
     }
 
-    // Sanity check.
-    var uriPathSegments = uri.pathSegments;
-    if (uriPathSegments.length < 2) {
-      return false;
-    }
-
     // Any `package:` library from the same package.
-    var packageName = uriPathSegments[0];
     if (packageName == targetPackageName) {
       return true;
     }
 
     // If not the same package, must be public.
-    if (uriPathSegments[1] == 'src') {
+    if (uri.isSrc) {
       return false;
     }
 
diff --git a/pkg/analysis_server/lib/src/services/completion/dart/suggestion_builder.dart b/pkg/analysis_server/lib/src/services/completion/dart/suggestion_builder.dart
index 7de9949..8ffc7d4 100644
--- a/pkg/analysis_server/lib/src/services/completion/dart/suggestion_builder.dart
+++ b/pkg/analysis_server/lib/src/services/completion/dart/suggestion_builder.dart
@@ -25,6 +25,16 @@
 import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
 import 'package:analyzer_plugin/utilities/range_factory.dart';
 
+/// Wrapper around a potentially nullable value.
+///
+/// When the wrapper instance is provided for a property, the property
+/// value is replaced, even if the value to set is `null` itself.
+class CopyWithValue<T> {
+  final T value;
+
+  CopyWithValue(this.value);
+}
+
 /// This class provides suggestions based upon the visible instance members in
 /// an interface type.
 class MemberSuggestionBuilder {
@@ -138,54 +148,6 @@
   }
 }
 
-class NewSuggestionsProcessor {
-  final SuggestionBuilder _builder;
-  final Set<protocol.CompletionSuggestion> _current = Set.identity();
-
-  NewSuggestionsProcessor._(this._builder) {
-    _current.addAll(_builder._suggestionMap.values);
-  }
-
-  /// Update suggestions added since this marker was created.
-  void setLibraryUriToImportIndex(int Function() produce) {
-    int? libraryUriToImportIndex;
-    var suggestionMap = _builder._suggestionMap;
-    for (var entry in suggestionMap.entries.toList()) {
-      var suggestion = entry.value;
-      if (!_current.contains(suggestion)) {
-        libraryUriToImportIndex ??= produce();
-        suggestionMap[entry.key] = protocol.CompletionSuggestion(
-          suggestion.kind,
-          suggestion.relevance,
-          suggestion.completion,
-          suggestion.selectionOffset,
-          suggestion.selectionLength,
-          suggestion.isDeprecated,
-          suggestion.isPotential,
-          displayText: suggestion.displayText,
-          replacementOffset: suggestion.replacementOffset,
-          replacementLength: suggestion.replacementLength,
-          docSummary: suggestion.docSummary,
-          docComplete: suggestion.docComplete,
-          declaringType: suggestion.declaringType,
-          defaultArgumentListString: suggestion.defaultArgumentListString,
-          defaultArgumentListTextRanges:
-              suggestion.defaultArgumentListTextRanges,
-          element: suggestion.element,
-          returnType: suggestion.returnType,
-          parameterNames: suggestion.parameterNames,
-          parameterTypes: suggestion.parameterTypes,
-          requiredParameterCount: suggestion.requiredParameterCount,
-          hasNamedParameters: suggestion.hasNamedParameters,
-          parameterName: suggestion.parameterName,
-          parameterType: suggestion.parameterType,
-          libraryUriToImportIndex: libraryUriToImportIndex,
-        );
-      }
-    }
-  }
-}
-
 /// An object used to build a list of suggestions in response to a single
 /// completion request.
 class SuggestionBuilder {
@@ -212,6 +174,9 @@
   /// suggestions, or `null` if no notification should occur.
   final SuggestionListener? listener;
 
+  /// The function to be invoked when a new suggestion is added.
+  void Function(protocol.CompletionSuggestion)? suggestionAdded;
+
   /// A map from a completion identifier to a completion suggestion.
   final Map<String, CompletionSuggestion> _suggestionMap =
       <String, CompletionSuggestion>{};
@@ -264,11 +229,6 @@
   bool get _isNonNullableByDefault =>
       request.libraryElement.isNonNullableByDefault;
 
-  /// Return an object that knows which suggestions exist, and which are new.
-  NewSuggestionsProcessor markSuggestions() {
-    return NewSuggestionsProcessor._(this);
-  }
-
   /// Add a suggestion for an [accessor] declared within a class or extension.
   /// If the accessor is being invoked with a target of `super`, then the
   /// [containingMemberName] should be the name of the member containing the
@@ -778,8 +738,8 @@
   Future<void> suggestOverride(SimpleIdentifier targetId,
       ExecutableElement element, bool invokeSuper) async {
     var displayTextBuffer = StringBuffer();
-    var builder = ChangeBuilder(session: request.result.session);
-    await builder.addDartFileEdit(request.result.path, (builder) {
+    var builder = ChangeBuilder(session: request.analysisSession);
+    await builder.addDartFileEdit(request.path, (builder) {
       builder.addReplacement(range.node(targetId), (builder) {
         builder.writeOverride(
           element,
@@ -979,10 +939,9 @@
         key = '$key()';
       }
       listener?.builtSuggestion(suggestion);
-      if (laterReplacesEarlier) {
+      if (laterReplacesEarlier || !_suggestionMap.containsKey(key)) {
         _suggestionMap[key] = suggestion;
-      } else {
-        _suggestionMap.putIfAbsent(key, () => suggestion);
+        suggestionAdded?.call(suggestion);
       }
     }
   }
@@ -1314,3 +1273,45 @@
         other.prefix == prefix;
   }
 }
+
+extension CompletionSuggestionExtension on CompletionSuggestion {
+  CompletionSuggestion copyWith({
+    CopyWithValue<int?>? libraryUriToImportIndex,
+  }) {
+    return protocol.CompletionSuggestion(
+      kind,
+      relevance,
+      completion,
+      selectionOffset,
+      selectionLength,
+      isDeprecated,
+      isPotential,
+      displayText: displayText,
+      replacementOffset: replacementOffset,
+      replacementLength: replacementLength,
+      docSummary: docSummary,
+      docComplete: docComplete,
+      declaringType: declaringType,
+      defaultArgumentListString: defaultArgumentListString,
+      defaultArgumentListTextRanges: defaultArgumentListTextRanges,
+      element: element,
+      returnType: returnType,
+      parameterNames: parameterNames,
+      parameterTypes: parameterTypes,
+      requiredParameterCount: requiredParameterCount,
+      hasNamedParameters: hasNamedParameters,
+      parameterName: parameterName,
+      parameterType: parameterType,
+      libraryUriToImportIndex: libraryUriToImportIndex.orElse(
+        this.libraryUriToImportIndex,
+      ),
+    );
+  }
+}
+
+extension _CopyWithValueExtension<T> on CopyWithValue<T>? {
+  T orElse(T defaultValue) {
+    final self = this;
+    return self != null ? self.value : defaultValue;
+  }
+}
diff --git a/pkg/analysis_server/lib/src/services/completion/dart/uri_contributor.dart b/pkg/analysis_server/lib/src/services/completion/dart/uri_contributor.dart
index 703acf8..4a11a87 100644
--- a/pkg/analysis_server/lib/src/services/completion/dart/uri_contributor.dart
+++ b/pkg/analysis_server/lib/src/services/completion/dart/uri_contributor.dart
@@ -57,7 +57,7 @@
             // Quoted empty string
             visitSimpleStringLiteral(uri);
           } else {
-            var data = request.sourceContents!;
+            var data = request.content;
             if (end == data.length) {
               var ch = data[end - 1];
               if (ch != '"' && ch != "'") {
@@ -69,7 +69,7 @@
           }
         }
       } else if (offset == start && offset == end) {
-        var data = request.sourceContents!;
+        var data = request.content;
         if (end == data.length) {
           var ch = data[end - 1];
           if (ch == '"' || ch == "'") {
diff --git a/pkg/analysis_server/lib/src/services/completion/dart/utilities.dart b/pkg/analysis_server/lib/src/services/completion/dart/utilities.dart
index 19d86b0..33d20fe 100644
--- a/pkg/analysis_server/lib/src/services/completion/dart/utilities.dart
+++ b/pkg/analysis_server/lib/src/services/completion/dart/utilities.dart
@@ -197,7 +197,7 @@
 }
 
 String getRequestLineIndent(DartCompletionRequest request) {
-  var content = request.result.content;
+  var content = request.content;
   var lineStartOffset = request.offset;
   var notWhitespaceOffset = request.offset;
   for (; lineStartOffset > 0; lineStartOffset--) {
diff --git a/pkg/analysis_server/lib/src/services/completion/yaml/fix_data_generator.dart b/pkg/analysis_server/lib/src/services/completion/yaml/fix_data_generator.dart
index 15ef594..d57592a 100644
--- a/pkg/analysis_server/lib/src/services/completion/yaml/fix_data_generator.dart
+++ b/pkg/analysis_server/lib/src/services/completion/yaml/fix_data_generator.dart
@@ -16,27 +16,7 @@
       'title': EmptyProducer(),
       'date': EmptyProducer(),
       'bulkApply': BooleanProducer(),
-      'element': MapProducer({
-        // TODO(brianwilkerson) Support suggesting uris.
-        'uris': EmptyProducer(),
-        'class': EmptyProducer(),
-        'constant': EmptyProducer(),
-        'constructor': EmptyProducer(),
-        'enum': EmptyProducer(),
-        'extension': EmptyProducer(),
-        'field': EmptyProducer(),
-        'function': EmptyProducer(),
-        'getter': EmptyProducer(),
-        'method': EmptyProducer(),
-        'mixin': EmptyProducer(),
-        'setter': EmptyProducer(),
-        'typedef': EmptyProducer(),
-        'variable': EmptyProducer(),
-        'inClass': EmptyProducer(),
-        'inEnum': EmptyProducer(),
-        'inExtension': EmptyProducer(),
-        'inMixin': EmptyProducer(),
-      }),
+      'element': _elementProducer,
       'changes': _changesProducer,
       'oneOf': ListProducer(MapProducer({
         'if': EmptyProducer(),
@@ -56,6 +36,7 @@
       'removeParameter',
       'rename',
       'renameParameter',
+      'replacedBy',
     ]),
     'index': EmptyProducer(),
     'name': EmptyProducer(),
@@ -69,8 +50,32 @@
     'extends': EmptyProducer(),
     'oldName': EmptyProducer(),
     'newName': EmptyProducer(),
+    'newElement': _elementProducer,
   }));
 
+  /// The producer representing the known valid structure of an element.
+  static const MapProducer _elementProducer = MapProducer({
+    // TODO(brianwilkerson) Support suggesting uris.
+    'uris': EmptyProducer(),
+    'class': EmptyProducer(),
+    'constant': EmptyProducer(),
+    'constructor': EmptyProducer(),
+    'enum': EmptyProducer(),
+    'extension': EmptyProducer(),
+    'field': EmptyProducer(),
+    'function': EmptyProducer(),
+    'getter': EmptyProducer(),
+    'method': EmptyProducer(),
+    'mixin': EmptyProducer(),
+    'setter': EmptyProducer(),
+    'typedef': EmptyProducer(),
+    'variable': EmptyProducer(),
+    'inClass': EmptyProducer(),
+    'inEnum': EmptyProducer(),
+    'inExtension': EmptyProducer(),
+    'inMixin': EmptyProducer(),
+  });
+
   /// Initialize a newly created suggestion generator for fix data files.
   FixDataGenerator(ResourceProvider resourceProvider)
       : super(resourceProvider, null);
diff --git a/pkg/analysis_server/lib/src/services/correction/assist.dart b/pkg/analysis_server/lib/src/services/correction/assist.dart
index 47624e2..c7233ba 100644
--- a/pkg/analysis_server/lib/src/services/correction/assist.dart
+++ b/pkg/analysis_server/lib/src/services/correction/assist.dart
@@ -73,7 +73,7 @@
   );
   static const CONVERT_INTO_ASYNC_BODY = AssistKind(
     'dart.assist.convert.bodyToAsync',
-    29,
+    31,
     'Convert to async function body',
   );
   static const CONVERT_INTO_BLOCK_BODY = AssistKind(
@@ -222,77 +222,77 @@
   // Flutter wrap specific assists
   static const FLUTTER_WRAP_GENERIC = AssistKind(
     'dart.assist.flutter.wrap.generic',
-    31,
+    29,
     'Wrap with widget...',
   );
 
   static const FLUTTER_WRAP_BUILDER = AssistKind(
     'dart.assist.flutter.wrap.builder',
-    32,
+    28,
     'Wrap with Builder',
   );
   static const FLUTTER_WRAP_CENTER = AssistKind(
     'dart.assist.flutter.wrap.center',
-    32,
+    28,
     'Wrap with Center',
   );
   static const FLUTTER_WRAP_COLUMN = AssistKind(
     'dart.assist.flutter.wrap.column',
-    32,
+    28,
     'Wrap with Column',
   );
   static const FLUTTER_WRAP_CONTAINER = AssistKind(
     'dart.assist.flutter.wrap.container',
-    32,
+    28,
     'Wrap with Container',
   );
   static const FLUTTER_WRAP_PADDING = AssistKind(
     'dart.assist.flutter.wrap.padding',
-    32,
+    28,
     'Wrap with Padding',
   );
   static const FLUTTER_WRAP_ROW = AssistKind(
     'dart.assist.flutter.wrap.row',
-    32,
+    28,
     'Wrap with Row',
   );
   static const FLUTTER_WRAP_SIZED_BOX = AssistKind(
     'dart.assist.flutter.wrap.sizedBox',
-    32,
+    28,
     'Wrap with SizedBox',
   );
   static const FLUTTER_WRAP_STREAM_BUILDER = AssistKind(
     'dart.assist.flutter.wrap.streamBuilder',
-    32,
+    28,
     'Wrap with StreamBuilder',
   );
 
   // Flutter re-order assists
   static const FLUTTER_SWAP_WITH_CHILD = AssistKind(
     'dart.assist.flutter.swap.withChild',
-    33,
+    27,
     'Swap with child',
   );
   static const FLUTTER_SWAP_WITH_PARENT = AssistKind(
     'dart.assist.flutter.swap.withParent',
-    33,
+    27,
     'Swap with parent',
   );
   static const FLUTTER_MOVE_DOWN = AssistKind(
     'dart.assist.flutter.move.down',
-    34,
+    26,
     'Move widget down',
   );
   static const FLUTTER_MOVE_UP = AssistKind(
     'dart.assist.flutter.move.up',
-    34,
+    26,
     'Move widget up',
   );
 
   // Flutter remove assist
   static const FLUTTER_REMOVE_WIDGET = AssistKind(
     'dart.assist.flutter.removeWidget',
-    35,
+    25,
     'Remove this widget',
   );
 
@@ -334,7 +334,7 @@
   static const REMOVE_TYPE_ANNOTATION = AssistKind(
     // todo (pq): unify w/ fix
     'dart.assist.remove.typeAnnotation',
-    29,
+    31,
     'Remove type annotation',
   );
   static const REPLACE_CONDITIONAL_WITH_IF_ELSE = AssistKind(
@@ -374,47 +374,47 @@
   );
   static const SURROUND_WITH_BLOCK = AssistKind(
     'dart.assist.surround.block',
-    22,
+    38,
     'Surround with block',
   );
   static const SURROUND_WITH_DO_WHILE = AssistKind(
     'dart.assist.surround.doWhile',
-    27,
+    33,
     "Surround with 'do-while'",
   );
   static const SURROUND_WITH_FOR = AssistKind(
     'dart.assist.surround.forEach',
-    26,
+    34,
     "Surround with 'for'",
   );
   static const SURROUND_WITH_FOR_IN = AssistKind(
     'dart.assist.surround.forIn',
-    25,
+    35,
     "Surround with 'for-in'",
   );
   static const SURROUND_WITH_IF = AssistKind(
     'dart.assist.surround.if',
-    23,
+    37,
     "Surround with 'if'",
   );
   static const SURROUND_WITH_SET_STATE = AssistKind(
     'dart.assist.surround.setState',
-    27,
+    33,
     "Surround with 'setState'",
   );
   static const SURROUND_WITH_TRY_CATCH = AssistKind(
     'dart.assist.surround.tryCatch',
-    28,
+    32,
     "Surround with 'try-catch'",
   );
   static const SURROUND_WITH_TRY_FINALLY = AssistKind(
     'dart.assist.surround.tryFinally',
-    29,
+    31,
     "Surround with 'try-finally'",
   );
   static const SURROUND_WITH_WHILE = AssistKind(
     'dart.assist.surround.while',
-    24,
+    36,
     "Surround with 'while'",
   );
   static const USE_CURLY_BRACES = AssistKind(
diff --git a/pkg/analysis_server/lib/src/services/correction/bulk_fix_processor.dart b/pkg/analysis_server/lib/src/services/correction/bulk_fix_processor.dart
index a09c3b7..0b6145c 100644
--- a/pkg/analysis_server/lib/src/services/correction/bulk_fix_processor.dart
+++ b/pkg/analysis_server/lib/src/services/correction/bulk_fix_processor.dart
@@ -7,10 +7,13 @@
 import 'package:analysis_server/src/services/correction/change_workspace.dart';
 import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
 import 'package:analysis_server/src/services/correction/dart/data_driven.dart';
+import 'package:analysis_server/src/services/correction/dart/organize_imports.dart';
+import 'package:analysis_server/src/services/correction/dart/remove_unused_import.dart';
 import 'package:analysis_server/src/services/correction/fix.dart';
 import 'package:analysis_server/src/services/correction/fix/data_driven/transform_override_set.dart';
 import 'package:analysis_server/src/services/correction/fix/data_driven/transform_override_set_parser.dart';
 import 'package:analysis_server/src/services/correction/fix_internal.dart';
+import 'package:analysis_server/src/services/linter/lint_names.dart';
 import 'package:analyzer/dart/analysis/analysis_context.dart';
 import 'package:analyzer/dart/analysis/results.dart';
 import 'package:analyzer/error/error.dart';
@@ -226,28 +229,109 @@
     return builder;
   }
 
+  Future<void> _applyProducer(
+      CorrectionProducerContext context, CorrectionProducer producer) async {
+    producer.configure(context);
+    try {
+      var localBuilder = builder.copy();
+      await producer.compute(localBuilder);
+      builder = localBuilder;
+    } on ConflictingEditException {
+      // If a conflicting edit was added in [compute], then the [localBuilder]
+      // is discarded and we revert to the previous state of the builder.
+    }
+  }
+
   /// Use the change [builder] to create fixes for the diagnostics in the
   /// library associated with the analysis [result].
   Future<void> _fixErrorsInLibrary(ResolvedLibraryResult result) async {
     var analysisOptions = result.session.analysisContext.analysisOptions;
-    for (var unitResult in result.units) {
-      var overrideSet = _readOverrideSet(unitResult);
 
-      var errors = List.from(unitResult.errors, growable: false);
+    Iterable<AnalysisError> filteredErrors(ResolvedUnitResult result) sync* {
+      var errors = result.errors.toList();
       errors.sort((a, b) => a.offset.compareTo(b.offset));
-
+      // Only fix errors not filtered out in analysis options.
       for (var error in errors) {
         var processor = ErrorProcessor.getProcessor(analysisOptions, error);
-        // Only fix errors not filtered out in analysis options.
         if (processor == null || processor.severity != null) {
-          final fixContext = DartFixContextImpl(
-            instrumentationService,
-            workspace,
-            unitResult,
-            error,
-            (name) => [],
-          );
-          await _fixSingleError(fixContext, unitResult, error, overrideSet);
+          yield error;
+        }
+      }
+    }
+
+    DartFixContextImpl fixContext(
+        ResolvedUnitResult result, AnalysisError diagnostic) {
+      return DartFixContextImpl(
+        instrumentationService,
+        workspace,
+        result,
+        diagnostic,
+        (name) => [],
+      );
+    }
+
+    CorrectionProducerContext? correctionContext(
+        ResolvedUnitResult result, AnalysisError diagnostic) {
+      var overrideSet = _readOverrideSet(result);
+      return CorrectionProducerContext.create(
+        applyingBulkFixes: true,
+        dartFixContext: fixContext(result, diagnostic),
+        diagnostic: diagnostic,
+        overrideSet: overrideSet,
+        resolvedResult: result,
+        selectionOffset: diagnostic.offset,
+        selectionLength: diagnostic.length,
+        workspace: workspace,
+      );
+    }
+
+    //
+    // Attempt to apply the fixes that aren't related to directives.
+    //
+    for (var unitResult in result.units) {
+      var overrideSet = _readOverrideSet(unitResult);
+      for (var error in filteredErrors(unitResult)) {
+        await _fixSingleError(
+            fixContext(unitResult, error), unitResult, error, overrideSet);
+      }
+    }
+    //
+    // If there are no such fixes in the defining compilation unit, then apply
+    // the fixes related to directives.
+    //
+    var definingUnit = result.units[0];
+    AnalysisError? directivesOrderingError;
+    var unusedImportErrors = <AnalysisError>[];
+    if (!builder.hasEditsFor(definingUnit.path)) {
+      for (var error in filteredErrors(definingUnit)) {
+        var errorCode = error.errorCode;
+        if (errorCode is LintCode) {
+          var lintName = errorCode.name;
+          if (lintName == LintNames.directives_ordering) {
+            directivesOrderingError = error;
+            break;
+          }
+        } else if (errorCode == HintCode.DUPLICATE_IMPORT ||
+            errorCode == HintCode.UNNECESSARY_IMPORT ||
+            errorCode == HintCode.UNUSED_IMPORT) {
+          unusedImportErrors.add(error);
+        }
+      }
+      if (directivesOrderingError != null) {
+        // `OrganizeImports` will also remove some of the unused imports, so we
+        // apply it first.
+        var context = correctionContext(definingUnit, directivesOrderingError);
+        if (context != null) {
+          await _generateFix(context, OrganizeImports.newInstance(),
+              directivesOrderingError.errorCode.name);
+        }
+      } else {
+        for (var error in unusedImportErrors) {
+          var context = correctionContext(definingUnit, error);
+          if (context != null) {
+            await _generateFix(context, RemoveUnusedImport.newInstance(),
+                error.errorCode.name);
+          }
         }
       }
     }
@@ -275,44 +359,21 @@
       return;
     }
 
-    Future<void> compute(CorrectionProducer producer) async {
-      producer.configure(context);
-      try {
-        var localBuilder = builder.copy();
-        await producer.compute(localBuilder);
-        builder = localBuilder;
-      } on ConflictingEditException {
-        // If a conflicting edit was added in [compute], then the [localBuilder]
-        // is discarded and we revert to the previous state of the builder.
-      }
-    }
-
-    int computeChangeHash() => (builder as ChangeBuilderImpl).changeHash;
-
-    Future<void> generate(CorrectionProducer producer, String code) async {
-      var oldHash = computeChangeHash();
-      await compute(producer);
-      var newHash = computeChangeHash();
-      if (newHash != oldHash) {
-        changeMap.add(result.path, code);
-      }
-    }
-
     Future<void> bulkApply(
         List<ProducerGenerator> generators, String codeName) async {
       for (var generator in generators) {
         var producer = generator();
         if (producer.canBeAppliedInBulk) {
-          await generate(producer, codeName);
+          await _generateFix(context, producer, codeName);
         }
       }
     }
 
     var errorCode = diagnostic.errorCode;
+    var codeName = errorCode.name;
     try {
-      var codeName = errorCode.name;
       if (errorCode is LintCode) {
-        var generators = FixProcessor.lintProducerMap[errorCode.name] ?? [];
+        var generators = FixProcessor.lintProducerMap[codeName] ?? [];
         await bulkApply(generators, codeName);
       } else {
         var generators = FixProcessor.nonLintProducerMap[errorCode] ?? [];
@@ -323,16 +384,26 @@
             var multiProducer = multiGenerator();
             multiProducer.configure(context);
             for (var producer in multiProducer.producers) {
-              await generate(producer, codeName);
+              await _generateFix(context, producer, codeName);
             }
           }
         }
       }
     } catch (e, s) {
       throw CaughtException.withMessage(
-          'Exception generating fix for ${errorCode.name} in ${result.path}',
-          e,
-          s);
+          'Exception generating fix for $codeName in ${result.path}', e, s);
+    }
+  }
+
+  Future<void> _generateFix(CorrectionProducerContext context,
+      CorrectionProducer producer, String code) async {
+    int computeChangeHash() => (builder as ChangeBuilderImpl).changeHash;
+
+    var oldHash = computeChangeHash();
+    await _applyProducer(context, producer);
+    var newHash = computeChangeHash();
+    if (newHash != oldHash) {
+      changeMap.add(context.resolvedResult.path, code.toLowerCase());
     }
   }
 
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/create_field.dart b/pkg/analysis_server/lib/src/services/correction/dart/create_field.dart
index ec42942..3073989 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/create_field.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/create_field.dart
@@ -96,7 +96,7 @@
     if (targetClassElement == null) {
       return;
     }
-    if (targetClassElement.librarySource.isInSystemLibrary) {
+    if (targetClassElement.librarySource.uri.isScheme('dart')) {
       return;
     }
     utils.targetClassElement = targetClassElement;
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/create_getter.dart b/pkg/analysis_server/lib/src/services/correction/dart/create_getter.dart
index 3c9c661..cdc8339 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/create_getter.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/create_getter.dart
@@ -74,7 +74,7 @@
       return;
     }
     var targetSource = targetElement.source;
-    if (targetSource == null || targetSource.isInSystemLibrary) {
+    if (targetSource == null || targetSource.uri.isScheme('dart')) {
       return;
     }
     // prepare target declaration
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/create_method.dart b/pkg/analysis_server/lib/src/services/correction/dart/create_method.dart
index 9009561..1774efe 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/create_method.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/create_method.dart
@@ -139,7 +139,7 @@
         return;
       }
       targetElement = targetClassElement;
-      if (targetClassElement.librarySource.isInSystemLibrary) {
+      if (targetClassElement.librarySource.uri.isScheme('dart')) {
         return;
       }
       // prepare target ClassDeclaration
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/create_setter.dart b/pkg/analysis_server/lib/src/services/correction/dart/create_setter.dart
index 8958731..569e134 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/create_setter.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/create_setter.dart
@@ -73,7 +73,7 @@
       return;
     }
     var targetSource = targetElement.source;
-    if (targetSource == null || targetSource.isInSystemLibrary) {
+    if (targetSource == null || targetSource.uri.isScheme('dart')) {
       return;
     }
     // prepare target declaration
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/import_library.dart b/pkg/analysis_server/lib/src/services/correction/dart/import_library.dart
index 415f155..4a949c4 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/import_library.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/import_library.dart
@@ -16,6 +16,7 @@
 import 'package:analyzer/dart/element/type.dart';
 import 'package:analyzer/source/source_range.dart';
 import 'package:analyzer_plugin/src/utilities/change_builder/change_builder_dart.dart';
+import 'package:analyzer_plugin/src/utilities/library.dart';
 import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
 import 'package:analyzer_plugin/utilities/fixes/fixes.dart';
 import 'package:analyzer_plugin/utilities/range_factory.dart';
@@ -150,22 +151,6 @@
     return false;
   }
 
-  /// Returns the relative URI from the passed [library] to the given [path].
-  ///
-  /// If the [path] is not in the [library]'s directory, `null` is returned.
-  String? _getRelativeUriFromLibrary(LibraryElement library, String path) {
-    var librarySource = library.librarySource;
-    var pathContext = resourceProvider.pathContext;
-    var libraryDirectory = pathContext.dirname(librarySource.fullName);
-    var sourceDirectory = pathContext.dirname(path);
-    if (pathContext.isWithin(libraryDirectory, path) ||
-        pathContext.isWithin(sourceDirectory, libraryDirectory)) {
-      var relativeFile = pathContext.relative(path, from: libraryDirectory);
-      return pathContext.split(relativeFile).join('/');
-    }
-    return null;
-  }
-
   Iterable<CorrectionProducer> _importExtensionInLibrary(
       Uri uri, DartType targetType, String memberName) sync* {
     // Look to see whether the library at the [uri] is already imported. If it
@@ -207,25 +192,28 @@
 
   /// Returns a list of one or two import corrections.
   ///
-  /// If [relativeUri] is `null`, only one correction, with an absolute import
-  /// path, is returned. Otherwise, a correction with an absolute import path
-  /// and a correction with a relative path are returned. If the
+  /// If [includeRelativeFix] is `false`, only one correction, with an absolute
+  /// import path, is returned. Otherwise, a correction with an absolute import
+  /// path and a correction with a relative path are returned. If the
   /// `prefer_relative_imports` lint rule is enabled, the relative path is
   /// returned first.
-  Iterable<CorrectionProducer> _importLibrary(FixKind fixKind, Uri library,
-      [String? relativeUri]) {
-    if (relativeUri == null || relativeUri.isEmpty) {
+  Iterable<CorrectionProducer> _importLibrary(
+    FixKind fixKind,
+    Uri library, {
+    bool includeRelativeFix = false,
+  }) {
+    if (!includeRelativeFix) {
       return [_ImportAbsoluteLibrary(fixKind, library)];
     }
     if (isLintEnabled(LintNames.prefer_relative_imports)) {
       return [
-        _ImportRelativeLibrary(fixKind, relativeUri),
+        _ImportRelativeLibrary(fixKind, library),
         _ImportAbsoluteLibrary(fixKind, library),
       ];
     } else {
       return [
         _ImportAbsoluteLibrary(fixKind, library),
-        _ImportRelativeLibrary(fixKind, relativeUri),
+        _ImportRelativeLibrary(fixKind, library),
       ];
     }
   }
@@ -312,10 +300,13 @@
         // Good: direct declaration.
         fixKind = DartFixKind.IMPORT_LIBRARY_PROJECT1;
       }
-      // Add the fix.
-      var relativeUri =
-          _getRelativeUriFromLibrary(libraryElement, declaration.path);
-      yield* _importLibrary(fixKind, declaration.uri, relativeUri);
+      // If both files are in the same package's lib folder, also include a
+      // relative import.
+      var includeRelativeUri = canBeRelativeImport(
+          declaration.uri, libraryElement.librarySource.uri);
+      // Add the fix(es).
+      yield* _importLibrary(fixKind, declaration.uri,
+          includeRelativeFix: includeRelativeUri);
     }
   }
 
@@ -415,7 +406,9 @@
   @override
   Future<void> compute(ChangeBuilder builder) async {
     await builder.addDartFileEdit(file, (builder) {
-      _uriText = builder.importLibrary(_library);
+      if (builder is DartFileEditBuilderImpl) {
+        _uriText = builder.importLibraryWithAbsoluteUri(_library);
+      }
     });
   }
 }
@@ -532,12 +525,14 @@
 class _ImportRelativeLibrary extends CorrectionProducer {
   final FixKind _fixKind;
 
-  final String _relativeURI;
+  final Uri _library;
 
-  _ImportRelativeLibrary(this._fixKind, this._relativeURI);
+  String _uriText = '';
+
+  _ImportRelativeLibrary(this._fixKind, this._library);
 
   @override
-  List<Object> get fixArguments => [_relativeURI];
+  List<Object> get fixArguments => [_uriText];
 
   @override
   FixKind get fixKind => _fixKind;
@@ -546,7 +541,7 @@
   Future<void> compute(ChangeBuilder builder) async {
     await builder.addDartFileEdit(file, (builder) {
       if (builder is DartFileEditBuilderImpl) {
-        builder.importLibraryWithRelativeUri(_relativeURI);
+        _uriText = builder.importLibraryWithRelativeUri(_library);
       }
     });
   }
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/organize_imports.dart b/pkg/analysis_server/lib/src/services/correction/dart/organize_imports.dart
index d5cf7c0..d655cc3 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/organize_imports.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/organize_imports.dart
@@ -11,7 +11,8 @@
 
 class OrganizeImports extends CorrectionProducer {
   @override
-  bool get canBeAppliedInBulk => true;
+  // Bulk application is supported by a distinct import cleanup fix phase.
+  bool get canBeAppliedInBulk => false;
 
   @override
   // The fix is to sort all the directives, which will already fix all of the
diff --git a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/element_kind.dart b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/element_kind.dart
index a3fb8b1..4da8683 100644
--- a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/element_kind.dart
+++ b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/element_kind.dart
@@ -20,6 +20,38 @@
 }
 
 extension ElementKindUtilities on ElementKind {
+  /// Return a human readable name for the kind.
+  String get displayName {
+    switch (this) {
+      case ElementKind.classKind:
+        return 'class';
+      case ElementKind.constantKind:
+        return 'constant';
+      case ElementKind.constructorKind:
+        return 'constructor';
+      case ElementKind.enumKind:
+        return 'enum';
+      case ElementKind.extensionKind:
+        return 'extension';
+      case ElementKind.fieldKind:
+        return 'field';
+      case ElementKind.functionKind:
+        return 'function';
+      case ElementKind.getterKind:
+        return 'getter';
+      case ElementKind.methodKind:
+        return 'method';
+      case ElementKind.mixinKind:
+        return 'mixin';
+      case ElementKind.setterKind:
+        return 'setter';
+      case ElementKind.typedefKind:
+        return 'typedef';
+      case ElementKind.variableKind:
+        return 'variable';
+    }
+  }
+
   /// Return the element kind corresponding to the given [name].
   static ElementKind? fromName(String name) {
     for (var kind in ElementKind.values) {
diff --git a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/element_matcher.dart b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/element_matcher.dart
index 49751f1..837025a 100644
--- a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/element_matcher.dart
+++ b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/element_matcher.dart
@@ -342,20 +342,27 @@
           // If the old class has been removed then this might have been a
           // constructor invocation.
           ElementKind.constructorKind,
+          ElementKind.functionKind, // tear-off
           ElementKind.getterKind,
           ElementKind.setterKind,
           ElementKind.variableKind
         ];
       }
       return const [
+        ElementKind.constantKind,
         ElementKind.fieldKind,
+        ElementKind.functionKind, // tear-off
         ElementKind.getterKind,
+        ElementKind.methodKind, // tear-off
         ElementKind.setterKind
       ];
     } else if (node is PropertyAccess) {
       return const [
+        ElementKind.constantKind,
         ElementKind.fieldKind,
+        ElementKind.functionKind, // tear-off, prefixed
         ElementKind.getterKind,
+        ElementKind.methodKind, // tear-off, prefixed
         ElementKind.setterKind
       ];
     } else if (node is SimpleIdentifier) {
diff --git a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/replaced_by.dart b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/replaced_by.dart
new file mode 100644
index 0000000..92e23b9
--- /dev/null
+++ b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/replaced_by.dart
@@ -0,0 +1,140 @@
+// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'package:analysis_server/src/services/correction/dart/data_driven.dart';
+import 'package:analysis_server/src/services/correction/fix/data_driven/change.dart';
+import 'package:analysis_server/src/services/correction/fix/data_driven/element_descriptor.dart';
+import 'package:analyzer/dart/ast/ast.dart';
+import 'package:analyzer/dart/element/element.dart';
+import 'package:analyzer/source/source_range.dart';
+import 'package:analyzer_plugin/utilities/change_builder/change_builder_dart.dart';
+import 'package:analyzer_plugin/utilities/range_factory.dart';
+
+/// The data related to an element that has been replaced by another element.
+class ReplacedBy extends Change<_Data> {
+  /// The replacing element.
+  final ElementDescriptor newElement;
+
+  /// Initialize a newly created transform to describe a replacement of an old
+  /// element by a [newElement].
+  ReplacedBy({required this.newElement});
+
+  @override
+  void apply(DartFileEditBuilder builder, DataDrivenFix fix, _Data data) {
+    var referenceRange = data.referenceRange;
+    builder.addSimpleReplacement(referenceRange, _referenceTo(newElement));
+  }
+
+  @override
+  _Data? validate(DataDrivenFix fix) {
+    var node = fix.node;
+    if (node is SimpleIdentifier) {
+      var components = fix.element.components;
+      if (components.isEmpty) {
+        return null;
+      } else if (components.length == 1) {
+        if (components[0] != node.name) {
+          return null;
+        }
+        // We have an '<element>' pattern, so we replace the name.
+        return _Data(range.node(node));
+      }
+      // The element being replaced is a member in a top-level element.
+      var containerName = components[1];
+      if (components[0].isEmpty && containerName == node.name) {
+        // We have a '<className>()' pattern, so we replace the class name.
+        return _Data(range.node(node));
+      }
+      var parent = node.parent;
+      if (parent is MethodInvocation) {
+        var target = parent.target;
+        if (target == null) {
+          // We have a '<member>()' pattern, so we replace the member name.
+          return _Data(range.node(node));
+        } else if (target is SimpleIdentifier && target.name == containerName) {
+          // We have a '<container>.<member>()' pattern, so we replace both parts.
+          return _Data(range.startEnd(target, node));
+        } else if (target is PrefixedIdentifier) {
+          if (target.prefix.staticElement is PrefixElement &&
+              target.identifier.name == containerName) {
+            // We have a '<prefix>.<container>.<member>()' pattern so we leave
+            // the prefix while replacing the rest.
+            return _Data(range.startEnd(target.identifier, node));
+          }
+          // We shouldn't get here.
+          return null;
+        }
+      } else if (parent is PrefixedIdentifier) {
+        if (parent.prefix.staticElement is PrefixElement) {
+          // We have a '<prefix>.<topLevel>' pattern so we leave the prefix
+          // while replacing the rest.
+          return _Data(range.node(node));
+        }
+        // We have a '<container>.<member>' pattern so we replace both parts.
+        return _Data(range.node(parent));
+      } else if (parent is PropertyAccess) {
+        var target = parent.target;
+        if (target is PrefixedIdentifier) {
+          // We have a '<prefix>.<container>.<member>' pattern so we leave the
+          // prefix while replacing the rest.
+          return _Data(range.startEnd(target.identifier, node));
+        }
+        // We have a '<container>.<member>' pattern so we replace both parts.
+        return _Data(range.node(parent));
+      }
+      // We have a '<member>' pattern so we replace the member name.
+      return _Data(range.node(node));
+    } else if (node is PrefixedIdentifier) {
+      var parent = node.parent;
+      if (parent is NamedType) {
+        var identifier = node.identifier;
+        var components = fix.element.components;
+        if (components.length > 1 &&
+            components[0].isEmpty &&
+            components[1] == identifier.name) {
+          // We have a '<prefix>.<className>' pattern, so we replace only the
+          // class name.
+          return _Data(range.node(identifier));
+        }
+      }
+    } else if (node is ConstructorName) {
+      var typeName = node.type2.name;
+      SimpleIdentifier classNameNode;
+      if (typeName is SimpleIdentifier) {
+        classNameNode = typeName;
+      } else if (typeName is PrefixedIdentifier) {
+        classNameNode = typeName.identifier;
+      } else {
+        return null;
+      }
+      var constructorNameNode = node.name;
+      var constructorName = constructorNameNode?.name ?? '';
+      var components = fix.element.components;
+      if (components.length == 2 &&
+          constructorName == components[0] &&
+          classNameNode.name == components[1]) {
+        if (constructorNameNode != null) {
+          return _Data(range.startEnd(classNameNode, constructorNameNode));
+        }
+        return _Data(range.node(classNameNode));
+      }
+    }
+    return null;
+  }
+
+  String _referenceTo(ElementDescriptor element) {
+    var components = element.components;
+    if (components[0].isEmpty) {
+      return components[1];
+    }
+    return components.reversed.join('.');
+  }
+}
+
+/// The data about a reference to an element that's been replaced.
+class _Data {
+  final SourceRange referenceRange;
+
+  _Data(this.referenceRange);
+}
diff --git a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/transform_set_error_code.dart b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/transform_set_error_code.dart
index 1c992e0..42aeba2 100644
--- a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/transform_set_error_code.dart
+++ b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/transform_set_error_code.dart
@@ -25,6 +25,26 @@
 
   /**
    * Parameters:
+   * 0: the old kind
+   * 1: the new kind
+   */
+  static const TransformSetErrorCode incompatibleElementKind =
+      TransformSetErrorCode(
+          'incompatible_element_kind',
+          "An element of kind '{0}' can't be replaced by "
+              "an element of kind '{1}'.");
+
+  /**
+   * Parameters:
+   * 0: the change kind that is invalid
+   * 1: the element kind for the transform
+   */
+  static const TransformSetErrorCode invalidChangeForKind =
+      TransformSetErrorCode('invalid_change_for_kind',
+          "A change of type '{0}' can't be used for an element of kind '{1}'.");
+
+  /**
+   * Parameters:
    * 0: the character that is invalid
    */
   static const TransformSetErrorCode invalidCharacter =
@@ -136,6 +156,14 @@
   /**
    * No parameters.
    */
+  static const TransformSetErrorCode unsupportedUriChange = TransformSetErrorCode(
+      'unsupported_uri_change',
+      "The set of URIs for the replacement element must match the transformed "
+          "element.");
+
+  /**
+   * No parameters.
+   */
   static const TransformSetErrorCode unsupportedVersion = TransformSetErrorCode(
       'unsupported_version', "Only version '1' is supported at this time.");
 
diff --git a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/transform_set_parser.dart b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/transform_set_parser.dart
index 4605bd6..dc8184c 100644
--- a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/transform_set_parser.dart
+++ b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/transform_set_parser.dart
@@ -14,6 +14,7 @@
 import 'package:analysis_server/src/services/correction/fix/data_driven/parameter_reference.dart';
 import 'package:analysis_server/src/services/correction/fix/data_driven/rename.dart';
 import 'package:analysis_server/src/services/correction/fix/data_driven/rename_parameter.dart';
+import 'package:analysis_server/src/services/correction/fix/data_driven/replaced_by.dart';
 import 'package:analysis_server/src/services/correction/fix/data_driven/transform.dart';
 import 'package:analysis_server/src/services/correction/fix/data_driven/transform_set.dart';
 import 'package:analysis_server/src/services/correction/fix/data_driven/transform_set_error_code.dart';
@@ -64,6 +65,7 @@
   static const String _methodKey = 'method';
   static const String _mixinKey = 'mixin';
   static const String _nameKey = 'name';
+  static const String _newElementKey = 'newElement';
   static const String _newNameKey = 'newName';
   static const String _oldNameKey = 'oldName';
   static const String _oneOfKey = 'oneOf';
@@ -97,6 +99,7 @@
   static const String _removeParameterKind = 'removeParameter';
   static const String _renameKind = 'rename';
   static const String _renameParameterKind = 'renameParameter';
+  static const String _replacedByKind = 'replacedBy';
 
   /// The valid values for the [_styleKey] in an [_addParameterKind] change.
   static const List<String> validStyles = [
@@ -106,6 +109,11 @@
     'required_positional'
   ];
 
+  /// A table mapping the kinds of elements that can be replaced by a different
+  /// element to a set of the kinds of elements with which they can be replaced.
+  static final Map<ElementKind, Set<ElementKind>> compatibleReplacementTypes =
+      _createCompatibleReplacementTypes();
+
   static const String _openComponent = '{%';
   static const String _closeComponent = '%}';
 
@@ -125,6 +133,12 @@
   /// found.
   final String packageName;
 
+  /// The description of the element that is being transformed by the current
+  /// transformation, or `null` if we are not in the process of parsing a
+  /// transformation or if the element associated with the transformation is not
+  /// valid.
+  ElementDescriptor? elementBeingTransformed;
+
   /// The variable scope defined for the current transform.
   VariableScope transformVariableScope = VariableScope.empty;
 
@@ -147,6 +161,13 @@
     return _translateTransformSet(map);
   }
 
+  bool _equalUris(List<Uri> oldUris, List<Uri> newUris) {
+    var oldSet = oldUris.toSet();
+    var newSet = newUris.toSet();
+    return oldSet.difference(newSet).isEmpty &&
+        newSet.difference(oldSet).isEmpty;
+  }
+
   /// Convert the given [template] into a list of components. Variable
   /// references in the template are looked up in the map of [generators].
   List<TemplateComponent> _extractTemplateComponents(
@@ -446,6 +467,8 @@
         return _translateRenameChange(node);
       } else if (kind == _renameParameterKind) {
         return _translateRenameParameterChange(node);
+      } else if (kind == _replacedByKind) {
+        return _translateReplacedByChange(node);
       }
       return _reportInvalidValueOneOf(kindNode, kindContext, [
         _addParameterKind,
@@ -453,6 +476,7 @@
         _removeParameterKind,
         _renameKind,
         _renameParameterKind,
+        _replacedByKind,
       ]);
     } else {
       return _reportInvalidValue(node, context, 'Map');
@@ -821,6 +845,41 @@
     return RenameParameter(newName: newName, oldName: oldName);
   }
 
+  /// Translate the [node] into a replaced_by change. Return the resulting
+  /// change, or `null` if the [node] does not represent a valid replaced_by
+  /// change.
+  ReplacedBy? _translateReplacedByChange(YamlMap node) {
+    _reportUnsupportedKeys(node, const {_kindKey, _newElementKey});
+    var newElement = _translateElement(node.valueAt(_newElementKey),
+        ErrorContext(key: _newElementKey, parentNode: node));
+    if (newElement == null) {
+      // The error has already been reported.
+      return null;
+    }
+    var oldElement = elementBeingTransformed;
+    if (oldElement != null) {
+      if (!_equalUris(oldElement.libraryUris, newElement.libraryUris)) {
+        _reportError(TransformSetErrorCode.unsupportedUriChange,
+            (node.valueAt(_newElementKey) as YamlMap).valueAt(_urisKey)!);
+      }
+      var compatibleTypes = compatibleReplacementTypes[oldElement.kind];
+      if (compatibleTypes == null) {
+        _reportError(
+            TransformSetErrorCode.invalidChangeForKind,
+            node.valueAt(_newElementKey)!,
+            [_replacedByKind, oldElement.kind.displayName]);
+        return null;
+      } else if (!compatibleTypes.contains(newElement.kind)) {
+        _reportError(
+            TransformSetErrorCode.incompatibleElementKind,
+            node.valueAt(_newElementKey)!,
+            [oldElement.kind.displayName, newElement.kind.displayName]);
+        return null;
+      }
+    }
+    return ReplacedBy(newElement: newElement);
+  }
+
   /// Translate the [node] into a string. Return the resulting string, or `null`
   /// if the [node] doesn't represent a valid string. If the [node] isn't valid,
   /// use the [context] to report the error. If the [node] doesn't exist and
@@ -893,6 +952,7 @@
           true;
       var element = _translateElement(node.valueAt(_elementKey),
           ErrorContext(key: _elementKey, parentNode: node));
+      elementBeingTransformed = element;
       transformVariableScope = _translateTemplateVariables(
           node.valueAt(_variablesKey),
           ErrorContext(key: _variablesKey, parentNode: node));
@@ -1032,4 +1092,43 @@
       return _reportInvalidValue(node, context, 'Map');
     }
   }
+
+  static Map<ElementKind, Set<ElementKind>>
+      _createCompatibleReplacementTypes() {
+    var types = <ElementKind, Set<ElementKind>>{};
+
+    void addSet(Set<ElementKind> set) {
+      for (var kind in set) {
+        types.putIfAbsent(kind, () => {}).addAll(set);
+      }
+    }
+
+    // Constructors can replace constructors.
+    addSet({
+      ElementKind.constructorKind,
+    });
+    // Static methods and top-level functions can replace each other.
+    addSet({
+      ElementKind.functionKind,
+      ElementKind.methodKind,
+    });
+    // Static getters and getter-inducing elements can replace each other.
+    addSet({
+      ElementKind.constantKind,
+      ElementKind.fieldKind,
+      ElementKind.getterKind,
+      ElementKind.variableKind,
+    });
+    // Static setters and setter-inducing elements can replace each other.
+    // TODO(brianwilkerson) We can't currently distinguish between final and
+    //  non-final elements, but we don't support replacing setters with final
+    //  elements, nor vice versa. We need a way to distinguish these cases if we
+    //  want to be able to report an error.
+    addSet({
+      ElementKind.fieldKind,
+      ElementKind.setterKind,
+      ElementKind.variableKind,
+    });
+    return types;
+  }
 }
diff --git a/pkg/analysis_server/lib/src/services/correction/organize_imports.dart b/pkg/analysis_server/lib/src/services/correction/organize_imports.dart
index 3708b48..e4438f2 100644
--- a/pkg/analysis_server/lib/src/services/correction/organize_imports.dart
+++ b/pkg/analysis_server/lib/src/services/correction/organize_imports.dart
@@ -2,15 +2,20 @@
 // for details. All rights reserved. Use of this source code is governed by a
 // BSD-style license that can be found in the LICENSE file.
 
+import 'dart:math' as math;
+
 import 'package:analysis_server/src/utilities/strings.dart';
 import 'package:analyzer/dart/ast/ast.dart';
 import 'package:analyzer/dart/ast/token.dart';
 import 'package:analyzer/error/error.dart';
 import 'package:analyzer/source/line_info.dart';
+import 'package:analyzer/src/dart/element/extensions.dart';
 import 'package:analyzer/src/error/codes.dart';
 import 'package:analyzer/src/ignore_comments/ignore_info.dart';
 import 'package:analyzer_plugin/protocol/protocol_common.dart'
     hide AnalysisError, Element;
+import 'package:collection/collection.dart';
+import 'package:meta/meta_meta.dart';
 
 /// Organizer of imports (and other directives) in the [unit].
 class ImportOrganizer {
@@ -67,6 +72,13 @@
     var lineInfo = unit.lineInfo ?? LineInfo.fromContent(code);
     var hasLibraryDirective = false;
     var directives = <_DirectiveInfo>[];
+    // Track the end offset of any library-level comment/annotations that should
+    // remain at the top of the file regardless of whether it was attached to a
+    // directive that's moved/removed.
+    // Code up to this offset will be excluded from the comment/docs/annotation
+    // text for the computed DirectiveInfo and also its range for replacement
+    // in the document.
+    int? libraryDocsAndAnnotationsEndOffset;
     for (var directive in unit.directives) {
       if (directive is LibraryDirective) {
         hasLibraryDirective = true;
@@ -77,15 +89,60 @@
           var offset = directive.offset;
           var end = directive.end;
 
-          final leadingComment = getLeadingComment(unit, directive, lineInfo);
-          final trailingComment =
-              getTrailingComment(unit, directive, lineInfo, end);
+          final isPsuedoLibraryDirective = directive == unit.directives.first;
+          Annotation? lastLibraryAnnotation;
+          if (isPsuedoLibraryDirective) {
+            // Find the last library-level annotation that does not come
+            // after any non-library annotation. If there are already
+            // non-library annotations before library annotations, we will not
+            // try to correct those.
+            lastLibraryAnnotation = directive.metadata
+                .takeWhile(_isLibraryTargetAnnotation)
+                .lastOrNull;
+            if (lastLibraryAnnotation != null) {
+              libraryDocsAndAnnotationsEndOffset =
+                  lineInfo.getOffsetOfLineAfter(lastLibraryAnnotation.end);
+              // In the case of a blank line after the last library annotation
+              // we should include that in the library part. Otherwise it will
+              // be included in the top of the following directive and may
+              // result in an extra blank line in the annotation block if it
+              // is moved.
+              final nextLineOffset = lineInfo
+                  .getOffsetOfLineAfter(libraryDocsAndAnnotationsEndOffset);
+              if (code
+                  .substring(libraryDocsAndAnnotationsEndOffset, nextLineOffset)
+                  .trim()
+                  .isEmpty) {
+                libraryDocsAndAnnotationsEndOffset = nextLineOffset;
+              }
+            }
+          }
+
+          // Usually we look for leading comments on the directive. However if
+          // some library annotations were trimmed off, those comments are part
+          // of that and should not also be included here.
+          final leadingToken =
+              lastLibraryAnnotation == null ? directive.beginToken : null;
+          final leadingComment = leadingToken != null
+              ? getLeadingComment(unit, leadingToken, lineInfo)
+              : null;
+          final trailingComment = getTrailingComment(unit, directive, lineInfo);
+
+          /// Computes the offset to use for the start of directive-specific
+          /// code below taking into account code already included by
+          /// [libraryDocsAndAnnotationsEndOffset].
+          final clampedOffset = libraryDocsAndAnnotationsEndOffset == null
+              ? (int offset) => offset
+              : (int offset) =>
+                  math.max(libraryDocsAndAnnotationsEndOffset!, offset);
 
           String? leadingCommentText;
-          if (leadingComment != null) {
-            leadingCommentText =
-                code.substring(leadingComment.offset, directive.offset);
-            offset = leadingComment.offset;
+          if (leadingComment != null && leadingToken != null) {
+            offset = clampedOffset(leadingComment.offset);
+            leadingCommentText = code.substring(
+              offset,
+              clampedOffset(leadingToken.offset),
+            );
           }
           String? trailingCommentText;
           if (trailingComment != null) {
@@ -97,13 +154,33 @@
           var documentationComment = directive.documentationComment;
           if (documentationComment != null) {
             documentationText = code.substring(
-                documentationComment.offset, documentationComment.end);
+              clampedOffset(documentationComment.offset),
+              clampedOffset(documentationComment.end),
+            );
           }
           String? annotationText;
+          String? postAnnotationCommentText;
           var beginToken = directive.metadata.beginToken;
           var endToken = directive.metadata.endToken;
           if (beginToken != null && endToken != null) {
-            annotationText = code.substring(beginToken.offset, endToken.end);
+            var annotationOffset = clampedOffset(beginToken.offset);
+            var annotationEnd = clampedOffset(endToken.end);
+            if (annotationOffset != annotationEnd) {
+              annotationText = code.substring(
+                annotationOffset,
+                annotationEnd,
+              );
+            }
+            // Capture text between the end of the annotation and the directive
+            // text as there may be end-of line or line comments between.
+            // If not, this will capture the newline between the two, as it
+            // cannot be assumed there is a newline after annotationText because
+            // of the possibility of comments.
+            if (annotationEnd <
+                directive.firstTokenAfterCommentAndMetadata.offset) {
+              postAnnotationCommentText = code.substring(annotationEnd,
+                  directive.firstTokenAfterCommentAndMetadata.offset);
+            }
           }
           var text = code.substring(
               directive.firstTokenAfterCommentAndMetadata.offset,
@@ -116,9 +193,12 @@
               leadingCommentText,
               documentationText,
               annotationText,
+              postAnnotationCommentText,
               uriContent,
               trailingCommentText,
-              offset,
+              isPsuedoLibraryDirective
+                  ? (libraryDocsAndAnnotationsEndOffset ?? offset)
+                  : offset,
               end,
               text,
             ),
@@ -151,7 +231,7 @@
         sb.write(libraryDocumentationDirective.documentationText);
         sb.write(endOfLine);
       }
-      var currentPriority = directives.first.priority;
+      _DirectivePriority? currentPriority;
       for (var directiveInfo in directives) {
         if (!hasUnresolvedIdentifierError) {
           var directive = directiveInfo.directive;
@@ -160,7 +240,9 @@
           }
         }
         if (currentPriority != directiveInfo.priority) {
-          sb.write(endOfLine);
+          if (currentPriority != null) {
+            sb.write(endOfLine);
+          }
           currentPriority = directiveInfo.priority;
         }
         if (directiveInfo.leadingCommentText != null) {
@@ -173,7 +255,9 @@
         }
         if (directiveInfo.annotationText != null) {
           sb.write(directiveInfo.annotationText);
-          sb.write(endOfLine);
+        }
+        if (directiveInfo.postAnnotationCommentText != null) {
+          sb.write(directiveInfo.postAnnotationCommentText);
         }
         sb.write(directiveInfo.text);
         if (directiveInfo.trailingCommentText != null) {
@@ -230,7 +314,7 @@
   }
 
   /// Gets the first comment token considered to be the leading comment for this
-  /// directive.
+  /// token.
   ///
   /// Leading comments for the first directive in a file are considered library
   /// comments and not returned unless they contain blank lines, in which case
@@ -239,12 +323,12 @@
   /// '// ignore:' comment which should always be treated as attached to the
   /// import.
   static Token? getLeadingComment(
-      CompilationUnit unit, UriBasedDirective directive, LineInfo lineInfo) {
-    if (directive.beginToken.precedingComments == null) {
+      CompilationUnit unit, Token beginToken, LineInfo lineInfo) {
+    if (beginToken.precedingComments == null) {
       return null;
     }
 
-    Token? firstComment = directive.beginToken.precedingComments;
+    Token? firstComment = beginToken.precedingComments;
     var comment = firstComment;
     var nextComment = comment?.next;
     // Don't connect comments that have a blank line between them
@@ -274,7 +358,7 @@
     // Skip over any comments on the same line as the previous directive
     // as they will be attached to the end of it.
     var previousDirectiveLine =
-        lineInfo.getLocation(directive.beginToken.previous!.end).lineNumber;
+        lineInfo.getLocation(beginToken.previous!.end).lineNumber;
     comment = firstComment;
     while (comment != null &&
         previousDirectiveLine ==
@@ -289,9 +373,9 @@
   ///
   /// To be considered a trailing comment, the comment must be on the same line
   /// as the directive.
-  static Token? getTrailingComment(CompilationUnit unit,
-      UriBasedDirective directive, LineInfo lineInfo, int end) {
-    var line = lineInfo.getLocation(end).lineNumber;
+  static Token? getTrailingComment(
+      CompilationUnit unit, UriBasedDirective directive, LineInfo lineInfo) {
+    var line = lineInfo.getLocation(directive.end).lineNumber;
     Token? comment = directive.endToken.next!.precedingComments;
     while (comment != null) {
       if (lineInfo.getLocation(comment.offset).lineNumber == line) {
@@ -306,6 +390,10 @@
   /// '// ignore_for_file:' comment).
   static bool _isIgnoreComment(Token token) =>
       IgnoreInfo.IGNORE_MATCHER.matchAsPrefix(token.lexeme) != null;
+
+  static bool _isLibraryTargetAnnotation(Annotation annotation) =>
+      annotation.elementAnnotation?.targetKinds.contains(TargetKind.library) ??
+      false;
 }
 
 class _DirectiveInfo implements Comparable<_DirectiveInfo> {
@@ -314,6 +402,7 @@
   final String? leadingCommentText;
   final String? documentationText;
   final String? annotationText;
+  final String? postAnnotationCommentText;
   final String uri;
   final String? trailingCommentText;
 
@@ -332,6 +421,7 @@
     this.leadingCommentText,
     this.documentationText,
     this.annotationText,
+    this.postAnnotationCommentText,
     this.uri,
     this.trailingCommentText,
     this.offset,
diff --git a/pkg/analysis_server/lib/src/services/refactoring/move_file.dart b/pkg/analysis_server/lib/src/services/refactoring/move_file.dart
index 6e97072..f3cae42 100644
--- a/pkg/analysis_server/lib/src/services/refactoring/move_file.dart
+++ b/pkg/analysis_server/lib/src/services/refactoring/move_file.dart
@@ -158,9 +158,7 @@
     var refDir = pathContext.dirname(reference.file);
     // Try to keep package: URI
     if (_isPackageReference(reference)) {
-      Source newSource =
-          NonExistingSource(newFile, pathos.toUri(newFile), UriKind.FILE_URI);
-      var restoredUri = driver.sourceFactory.restoreUri(newSource);
+      var restoredUri = driver.sourceFactory.pathToUri(newFile);
       // If the new URI is not a package: URI, fall back to computing a relative
       // URI below.
       if (restoredUri?.isScheme('package') ?? false) {
diff --git a/pkg/analysis_server/lib/src/services/refactoring/rename.dart b/pkg/analysis_server/lib/src/services/refactoring/rename.dart
index 3ca9d77..8fbe15a 100644
--- a/pkg/analysis_server/lib/src/services/refactoring/rename.dart
+++ b/pkg/analysis_server/lib/src/services/refactoring/rename.dart
@@ -73,7 +73,7 @@
   @override
   Future<RefactoringStatus> checkInitialConditions() {
     var result = RefactoringStatus();
-    if (element.source!.isInSystemLibrary) {
+    if (element.source!.uri.isScheme('dart')) {
       var message = format(
           "The {0} '{1}' is defined in the SDK, so cannot be renamed.",
           getElementKindName(element),
diff --git a/pkg/analysis_server/lib/src/socket_server.dart b/pkg/analysis_server/lib/src/socket_server.dart
index 59cafe6..8e938ef 100644
--- a/pkg/analysis_server/lib/src/socket_server.dart
+++ b/pkg/analysis_server/lib/src/socket_server.dart
@@ -62,7 +62,7 @@
       var error = RequestError(
           RequestErrorCode.SERVER_ALREADY_STARTED, 'Server already started');
       serverChannel.sendResponse(Response('', error: error));
-      serverChannel.listen((Request request) {
+      serverChannel.requests.listen((Request request) {
         serverChannel.sendResponse(Response(request.id, error: error));
       });
       return;
diff --git a/pkg/analysis_server/lib/src/status/diagnostics.dart b/pkg/analysis_server/lib/src/status/diagnostics.dart
index 0d4629c..5ab8cff 100644
--- a/pkg/analysis_server/lib/src/status/diagnostics.dart
+++ b/pkg/analysis_server/lib/src/status/diagnostics.dart
@@ -206,7 +206,7 @@
     buf.writeln(
         '<tr><th>Time</th><th>Results</th><th>Source</th><th>Snippet</th></tr>');
     for (var completion in completions) {
-      var shortName = pathContext.basename(completion.path ?? '<missing path>');
+      var shortName = pathContext.basename(completion.path);
       buf.writeln('<tr>'
           '<td class="pre right">${printMilliseconds(completion.elapsedInMilliseconds)}</td>'
           '<td class="right">${completion.suggestionCountStr}</td>'
diff --git a/pkg/analysis_server/lib/src/utilities/mocks.dart b/pkg/analysis_server/lib/src/utilities/mocks.dart
index 9c581cd..bef5102 100644
--- a/pkg/analysis_server/lib/src/utilities/mocks.dart
+++ b/pkg/analysis_server/lib/src/utilities/mocks.dart
@@ -36,6 +36,9 @@
   MockServerChannel();
 
   @override
+  Stream<Request> get requests => requestController.stream;
+
+  @override
   void close() {
     _closed = true;
   }
@@ -46,13 +49,6 @@
   }
 
   @override
-  void listen(void Function(Request request) onRequest,
-      {Function? onError, void Function()? onDone}) {
-    requestController.stream
-        .listen(onRequest, onError: onError, onDone: onDone);
-  }
-
-  @override
   void sendNotification(Notification notification) {
     // Don't deliver notifications after the connection is closed.
     if (_closed) {
diff --git a/pkg/analysis_server/test/abstract_context.dart b/pkg/analysis_server/test/abstract_context.dart
index d727774..09fdeee 100644
--- a/pkg/analysis_server/test/abstract_context.dart
+++ b/pkg/analysis_server/test/abstract_context.dart
@@ -5,8 +5,6 @@
 import 'package:analyzer/dart/analysis/analysis_context.dart';
 import 'package:analyzer/dart/analysis/results.dart';
 import 'package:analyzer/dart/analysis/session.dart';
-import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer/dart/element/visitor.dart';
 import 'package:analyzer/file_system/file_system.dart';
 import 'package:analyzer/src/dart/analysis/analysis_context_collection.dart';
 import 'package:analyzer/src/dart/analysis/byte_store.dart';
@@ -23,24 +21,6 @@
 
 import 'src/utilities/mock_packages.dart';
 
-/// Finds an [Element] with the given [name].
-Element? findChildElement(Element root, String name, [ElementKind? kind]) {
-  Element? result;
-  root.accept(_ElementVisitorFunctionWrapper((Element element) {
-    if (element.name != name) {
-      return;
-    }
-    if (kind != null && element.kind != kind) {
-      return;
-    }
-    result = element;
-  }));
-  return result;
-}
-
-/// A function to be called for every [Element].
-typedef _ElementVisitorFunction = void Function(Element element);
-
 class AbstractContextTest with ResourceProviderMixin {
   static bool _lintRulesAreRegistered = false;
 
@@ -65,6 +45,13 @@
     throw 0;
   }
 
+  /// Return a list of the experiments that are to be enabled for tests in this
+  /// class, an empty list if there are no experiments that should be enabled.
+  List<String> get experiments => [
+        EnableString.constructor_tearoffs,
+        EnableString.named_arguments_anywhere,
+      ];
+
   String get latestLanguageVersion =>
       '${ExperimentStatus.currentVersion.major}.'
       '${ExperimentStatus.currentVersion.minor}';
@@ -192,6 +179,10 @@
     );
 
     writeTestPackageConfig();
+
+    createAnalysisOptionsFile(
+      experiments: experiments,
+    );
   }
 
   void setupResourceProvider() {}
@@ -302,16 +293,3 @@
     verifyCreatedCollection();
   }
 }
-
-/// Wraps the given [_ElementVisitorFunction] into an instance of
-/// [engine.GeneralizingElementVisitor].
-class _ElementVisitorFunctionWrapper extends GeneralizingElementVisitor<void> {
-  final _ElementVisitorFunction function;
-  _ElementVisitorFunctionWrapper(this.function);
-
-  @override
-  void visitElement(Element element) {
-    function(element);
-    super.visitElement(element);
-  }
-}
diff --git a/pkg/analysis_server/test/abstract_single_unit.dart b/pkg/analysis_server/test/abstract_single_unit.dart
index b18416c..67aa683 100644
--- a/pkg/analysis_server/test/abstract_single_unit.dart
+++ b/pkg/analysis_server/test/abstract_single_unit.dart
@@ -94,6 +94,6 @@
   @override
   void setUp() {
     super.setUp();
-    testFile = convertPath('/home/test/lib/test.dart');
+    testFile = convertPath('$testPackageLibPath/test.dart');
   }
 }
diff --git a/pkg/analysis_server/test/channel/byte_stream_channel_test.dart b/pkg/analysis_server/test/channel/byte_stream_channel_test.dart
index 0724bfe..d89741d 100644
--- a/pkg/analysis_server/test/channel/byte_stream_channel_test.dart
+++ b/pkg/analysis_server/test/channel/byte_stream_channel_test.dart
@@ -135,7 +135,7 @@
     errorStream = errorStreamController.stream;
     var doneCompleter = Completer();
     doneFuture = doneCompleter.future;
-    channel.listen((Request request) {
+    channel.requests.listen((Request request) {
       requestStreamController.add(request);
     }, onError: (error) {
       errorStreamController.add(error);
diff --git a/pkg/analysis_server/test/domain_analysis_test.dart b/pkg/analysis_server/test/domain_analysis_test.dart
index 8ea43c3..317cc59 100644
--- a/pkg/analysis_server/test/domain_analysis_test.dart
+++ b/pkg/analysis_server/test/domain_analysis_test.dart
@@ -18,6 +18,8 @@
 import 'package:analyzer/src/test_utilities/resource_provider_mixin.dart';
 import 'package:analyzer_plugin/protocol/protocol_common.dart';
 import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plugin;
+import 'package:analyzer_plugin/src/protocol/protocol_internal.dart'
+    show HasToJson;
 import 'package:test/test.dart';
 import 'package:test_reflective_loader/test_reflective_loader.dart';
 
@@ -1580,7 +1582,7 @@
   }
 
   /// Send an `updateContent` request for [testFile].
-  void sendContentChange(dynamic contentChange) {
+  void sendContentChange(HasToJson contentChange) {
     var request =
         AnalysisUpdateContentParams({testFile: contentChange}).toRequest('0');
     handleSuccessfulRequest(request);
diff --git a/pkg/analysis_server/test/domain_completion_test.dart b/pkg/analysis_server/test/domain_completion_test.dart
index 2a46330..c3ec9c3 100644
--- a/pkg/analysis_server/test/domain_completion_test.dart
+++ b/pkg/analysis_server/test/domain_completion_test.dart
@@ -11,7 +11,6 @@
 import 'package:analysis_server/src/protocol_server.dart';
 import 'package:analysis_server/src/provisional/completion/dart/completion_dart.dart';
 import 'package:analysis_server/src/server/crash_reporting_attachments.dart';
-import 'package:analysis_server/src/services/completion/dart/not_imported_contributor.dart';
 import 'package:analysis_server/src/utilities/mocks.dart';
 import 'package:analyzer/file_system/file_system.dart';
 import 'package:analyzer/instrumentation/service.dart';
@@ -21,12 +20,15 @@
 import 'package:analyzer/src/test_utilities/resource_provider_mixin.dart';
 import 'package:analyzer_plugin/protocol/protocol.dart' as plugin;
 import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plugin;
+import 'package:analyzer_utilities/check/check.dart';
+import 'package:meta/meta.dart';
 import 'package:test/test.dart';
 import 'package:test_reflective_loader/test_reflective_loader.dart';
 
 import 'domain_completion_util.dart';
 import 'mocks.dart';
 import 'src/plugin/plugin_manager_test.dart';
+import 'utils/change_check.dart';
 
 void main() {
   defineReflectiveSuite(() {
@@ -42,30 +44,31 @@
   Future<void> test_alreadyImported() async {
     await _configureWithWorkspaceRoot();
 
-    var validator = await _getTestCodeDetails('''
+    var details = await _getTestCodeDetails('''
 import 'dart:math';
 void f() {
   Rand^
 }
 ''', completion: 'Random', libraryUri: 'dart:math');
-    validator
-      ..hasCompletion('Random')
-      ..hasChange().assertNoFileEdits();
+    check(details)
+      ..completion.isEqualTo('Random')
+      ..change.edits.isEmpty;
   }
 
   Future<void> test_import_dart() async {
     await _configureWithWorkspaceRoot();
 
-    var validator = await _getTestCodeDetails('''
+    var details = await _getTestCodeDetails('''
 void f() {
   R^
 }
 ''', completion: 'Random', libraryUri: 'dart:math');
-    validator
-      ..hasCompletion('Random')
-      ..hasChange()
+    check(details)
+      ..completion.isEqualTo('Random')
+      ..change
           .hasFileEdit(testFilePathPlatform)
-          .whenApplied(testFileContent, r'''
+          .appliedTo(testFileContent)
+          .isEqualTo(r'''
 import 'dart:math';
 
 void f() {
@@ -75,8 +78,7 @@
   }
 
   Future<void> test_import_package_dependencies() async {
-    // TODO(scheglov) Switch to PubspecYamlFileConfig
-    newPubspecYamlFile(testPackageRootPath, r'''
+    writeTestPackagePubspecYamlFile(r'''
 name: test
 dependencies:
   aaa: any
@@ -94,16 +96,17 @@
 
     await _configureWithWorkspaceRoot();
 
-    var validator = await _getTestCodeDetails('''
+    var details = await _getTestCodeDetails('''
 void f() {
   T^
 }
 ''', completion: 'Test', libraryUri: 'package:aaa/a.dart');
-    validator
-      ..hasCompletion('Test')
-      ..hasChange()
+    check(details)
+      ..completion.isEqualTo('Test')
+      ..change
           .hasFileEdit(testFilePathPlatform)
-          .whenApplied(testFileContent, r'''
+          .appliedTo(testFileContent)
+          .isEqualTo(r'''
 import 'package:aaa/a.dart';
 
 void f() {
@@ -119,16 +122,17 @@
 
     await _configureWithWorkspaceRoot();
 
-    var validator = await _getTestCodeDetails('''
+    var details = await _getTestCodeDetails('''
 void f() {
   T^
 }
 ''', completion: 'Test', libraryUri: 'package:test/a.dart');
-    validator
-      ..hasCompletion('Test')
-      ..hasChange()
+    check(details)
+      ..completion.isEqualTo('Test')
+      ..change
           .hasFileEdit(testFilePathPlatform)
-          .whenApplied(testFileContent, r'''
+          .appliedTo(testFileContent)
+          .isEqualTo(r'''
 import 'package:test/a.dart';
 
 void f() {
@@ -160,7 +164,7 @@
     expect(response.error?.code, RequestErrorCode.INVALID_FILE_PATH_FORMAT);
   }
 
-  Future<GetSuggestionDetails2Validator> _getCodeDetails({
+  Future<CompletionGetSuggestionDetails2Result> _getCodeDetails({
     required String path,
     required String content,
     required String completion,
@@ -184,7 +188,7 @@
     );
   }
 
-  Future<GetSuggestionDetails2Validator> _getDetails({
+  Future<CompletionGetSuggestionDetails2Result> _getDetails({
     required String path,
     required int completionOffset,
     required String completion,
@@ -198,11 +202,10 @@
     ).toRequest('0');
 
     var response = await _handleSuccessfulRequest(request);
-    var result = CompletionGetSuggestionDetails2Result.fromResponse(response);
-    return GetSuggestionDetails2Validator(result);
+    return CompletionGetSuggestionDetails2Result.fromResponse(response);
   }
 
-  Future<GetSuggestionDetails2Validator> _getTestCodeDetails(
+  Future<CompletionGetSuggestionDetails2Result> _getTestCodeDetails(
     String content, {
     required String completion,
     required String libraryUri,
@@ -225,24 +228,75 @@
     completionDomain.budgetDuration = const Duration(seconds: 30);
   }
 
-  void tearDown() {
-    NotImportedContributor.onFile = null;
-  }
+  Future<void> test_abort_onAnotherCompletionRequest() async {
+    var abortedIdSet = <String>{};
+    server.discardedRequests.stream.listen((request) {
+      abortedIdSet.add(request.id);
+    });
 
-  Future<void> test_notImported_abort() async {
+    newFile(testFilePath, content: '');
+
     await _configureWithWorkspaceRoot();
 
-    NotImportedContributor.onFile = (file) {
-      if (file.uriStr == 'dart:math') {
-        unawaited(
-          _getSuggestions(
-            path: convertPath(testFilePath),
-            completionOffset: 0,
-            maxResults: 100,
-          ),
-        );
-      }
-    };
+    // Send three requests, the first two should be aborted.
+    var response0 = _sendTestCompletionRequest('0', 0);
+    var response1 = _sendTestCompletionRequest('1', 0);
+    var response2 = _sendTestCompletionRequest('2', 0);
+
+    // Wait for all three.
+    var validator0 = await response0.toResult();
+    var validator1 = await response1.toResult();
+    var validator2 = await response2.toResult();
+
+    // The first two should be aborted.
+    expect(abortedIdSet, {'0', '1'});
+
+    validator0
+      ..assertIncomplete()
+      ..suggestions.assertEmpty();
+
+    validator1
+      ..assertIncomplete()
+      ..suggestions.assertEmpty();
+
+    validator2
+      ..assertComplete()
+      ..suggestions.assertCompletionsContainsAll(
+        ['int', 'double', 'Future', 'Directory'],
+      );
+  }
+
+  Future<void> test_abort_onUpdateContent() async {
+    var abortedIdSet = <String>{};
+    server.discardedRequests.stream.listen((request) {
+      abortedIdSet.add(request.id);
+    });
+
+    newFile(testFilePath, content: '');
+
+    await _configureWithWorkspaceRoot();
+
+    // Schedule a completion request.
+    var response = _sendTestCompletionRequest('0', 0);
+
+    // Simulate typing in the IDE.
+    await _handleSuccessfulRequest(
+      AnalysisUpdateContentParams({
+        testFilePathPlatform: AddContentOverlay('void f() {}'),
+      }).toRequest('1'),
+    );
+
+    // The request should be aborted.
+    var validator = await response.toResult();
+    expect(abortedIdSet, {'0'});
+
+    validator
+      ..assertIncomplete()
+      ..suggestions.assertEmpty();
+  }
+
+  Future<void> test_notImported_dart() async {
+    await _configureWithWorkspaceRoot();
 
     var responseValidator = await _getTestCodeSuggestions('''
 void f() {
@@ -251,14 +305,21 @@
 ''');
 
     responseValidator
-      ..assertIncomplete()
+      ..assertComplete()
       ..assertReplacementBack(4)
-      ..assertLibrariesToImport(includes: [], excludes: [
-        'dart:core',
+      ..assertLibrariesToImport(includes: [
         'dart:math',
+      ], excludes: [
+        'dart:async',
+        'dart:core',
+        'package:test/test.dart',
       ]);
 
-    responseValidator.suggestions.assertEmpty();
+    var classes = responseValidator.suggestions.withElementClass();
+    classes.assertCompletions(['Random']);
+    classes.withCompletion('Random').assertSingle()
+      ..assertClass()
+      ..assertLibraryToImport('dart:math');
   }
 
   Future<void> test_notImported_emptyBudget() async {
@@ -285,8 +346,7 @@
   }
 
   Future<void> test_notImported_pub_dependencies_inLib() async {
-    // TODO(scheglov) Switch to PubspecYamlFileConfig
-    newPubspecYamlFile(testPackageRootPath, r'''
+    writeTestPackagePubspecYamlFile(r'''
 name: test
 dependencies:
   aaa: any
@@ -343,8 +403,7 @@
   }
 
   Future<void> test_notImported_pub_dependencies_inTest() async {
-    // TODO(scheglov) Switch to PubspecYamlFileConfig
-    newPubspecYamlFile(testPackageRootPath, r'''
+    writeTestPackagePubspecYamlFile(r'''
 name: test
 dependencies:
   aaa: any
@@ -407,8 +466,6 @@
       ..assertLibraryToImport('package:bbb/f.dart');
   }
 
-  /// TODO(scheglov) Only lib/ libraries in lib/, no test/.
-  /// TODO(scheglov) Suggestions from available Pub packages.
   Future<void> test_notImported_pub_this() async {
     newFile('$testPackageLibPath/a.dart', content: '''
 class A01 {}
@@ -430,12 +487,12 @@
       ..assertComplete()
       ..assertReplacementBack(2)
       ..assertLibrariesToImport(includes: [
-        'dart:async',
-        'dart:math',
         'package:test/a.dart',
         'package:test/b.dart',
       ], excludes: [
+        'dart:async',
         'dart:core',
+        'dart:math',
         'package:test/test.dart',
       ]);
 
@@ -473,11 +530,11 @@
       ..assertComplete()
       ..assertReplacementBack(2)
       ..assertLibrariesToImport(includes: [
-        'dart:async',
-        'dart:math',
         'package:test/b.dart',
       ], excludes: [
+        'dart:async',
         'dart:core',
+        'dart:math',
         'package:test/a.dart',
         'package:test/test.dart',
       ]);
@@ -519,12 +576,12 @@
       ..assertComplete()
       ..assertReplacementBack(2)
       ..assertLibrariesToImport(includes: [
-        'dart:async',
-        'dart:math',
         'package:test/a.dart',
         'package:test/b.dart',
       ], excludes: [
+        'dart:async',
         'dart:core',
+        'dart:math',
         'package:test/test.dart',
       ]);
 
@@ -542,8 +599,7 @@
   }
 
   Future<void> test_notImported_pub_this_inLib_excludesTest() async {
-    // TODO(scheglov) Switch to PubspecYamlFileConfig
-    newPubspecYamlFile(testPackageRootPath, r'''
+    writeTestPackagePubspecYamlFile(r'''
 name: test
 ''');
 
@@ -582,8 +638,7 @@
   }
 
   Future<void> test_notImported_pub_this_inLib_includesThisSrc() async {
-    // TODO(scheglov) Switch to PubspecYamlFileConfig
-    newPubspecYamlFile(testPackageRootPath, r'''
+    writeTestPackagePubspecYamlFile(r'''
 name: test
 ''');
 
@@ -625,8 +680,7 @@
   }
 
   Future<void> test_notImported_pub_this_inTest_includesTest() async {
-    // TODO(scheglov) Switch to PubspecYamlFileConfig
-    newPubspecYamlFile(testPackageRootPath, r'''
+    writeTestPackagePubspecYamlFile(r'''
 name: test
 ''');
 
@@ -673,8 +727,7 @@
   }
 
   Future<void> test_notImported_pub_this_inTest_includesThisSrc() async {
-    // TODO(scheglov) Switch to PubspecYamlFileConfig
-    newPubspecYamlFile(testPackageRootPath, r'''
+    writeTestPackagePubspecYamlFile(r'''
 name: test
 ''');
 
@@ -1398,6 +1451,71 @@
     suggestionsValidator.assertCompletions(['foo02', 'foo01']);
   }
 
+  Future<void> test_yaml_analysisOptions_root() async {
+    await _configureWithWorkspaceRoot();
+
+    var path = convertPath('$testPackageRootPath/analysis_options.yaml');
+    var responseValidator = await _getCodeSuggestions(
+      path: path,
+      content: '^',
+    );
+
+    responseValidator
+      ..assertComplete()
+      ..assertEmptyReplacement();
+
+    responseValidator.suggestions
+        .withKindIdentifier()
+        .assertCompletionsContainsAll([
+      'analyzer: ',
+      'include: ',
+      'linter: ',
+    ]);
+  }
+
+  Future<void> test_yaml_fixData_root() async {
+    await _configureWithWorkspaceRoot();
+
+    var path = convertPath('$testPackageRootPath/fix_data.yaml');
+    var responseValidator = await _getCodeSuggestions(
+      path: path,
+      content: '^',
+    );
+
+    responseValidator
+      ..assertComplete()
+      ..assertEmptyReplacement();
+
+    responseValidator.suggestions
+        .withKindIdentifier()
+        .assertCompletionsContainsAll([
+      'version: ',
+      'transforms:',
+    ]);
+  }
+
+  Future<void> test_yaml_pubspec_root() async {
+    await _configureWithWorkspaceRoot();
+
+    var path = convertPath('$testPackageRootPath/pubspec.yaml');
+    var responseValidator = await _getCodeSuggestions(
+      path: path,
+      content: '^',
+    );
+
+    responseValidator
+      ..assertComplete()
+      ..assertEmptyReplacement();
+
+    responseValidator.suggestions
+        .withKindIdentifier()
+        .assertCompletionsContainsAll([
+      'name: ',
+      'dependencies: ',
+      'dev_dependencies: ',
+    ]);
+  }
+
   Future<CompletionGetSuggestions2ResponseValidator> _getCodeSuggestions({
     required String path,
     required String content,
@@ -1446,6 +1564,16 @@
       maxResults: maxResults,
     );
   }
+
+  RequestWithFutureResponse _sendTestCompletionRequest(String id, int offset) {
+    var request = CompletionGetSuggestions2Params(
+      testFilePathPlatform,
+      0,
+      1 << 10,
+    ).toRequest(id);
+    var futureResponse = _handleRequest(request);
+    return RequestWithFutureResponse(offset, request, futureResponse);
+  }
 }
 
 @reflectiveTest
@@ -2387,20 +2515,6 @@
   }
 }
 
-class GetSuggestionDetails2Validator {
-  final CompletionGetSuggestionDetails2Result result;
-
-  GetSuggestionDetails2Validator(this.result);
-
-  SourceChangeValidator hasChange() {
-    return SourceChangeValidator(result.change);
-  }
-
-  void hasCompletion(Object completion) {
-    expect(result.completion, completion);
-  }
-}
-
 class PubPackageAnalysisServerTest with ResourceProviderMixin {
   late final MockServerChannel serverChannel;
   late final AnalysisServer server;
@@ -2493,6 +2607,10 @@
     writePackageConfig(testPackageRoot, config);
   }
 
+  void writeTestPackagePubspecYamlFile(String content) {
+    newPubspecYamlFile(testPackageRootPath, content);
+  }
+
   Future<void> _configureWithWorkspaceRoot() async {
     await setRoots(included: [workspaceRootPath], excluded: []);
     await server.onAnalysisComplete;
@@ -2510,6 +2628,21 @@
   }
 }
 
+class RequestWithFutureResponse {
+  final int offset;
+  final Request request;
+  final Future<Response> futureResponse;
+
+  RequestWithFutureResponse(this.offset, this.request, this.futureResponse);
+
+  Future<CompletionGetSuggestions2ResponseValidator> toResult() async {
+    var response = await futureResponse;
+    expect(response, isResponseSuccess(request.id));
+    var result = CompletionGetSuggestions2Result.fromResponse(response);
+    return CompletionGetSuggestions2ResponseValidator(offset, result);
+  }
+}
+
 class SingleSuggestionValidator {
   final CompletionSuggestion suggestion;
   final List<String>? libraryUrisToImport;
@@ -2559,32 +2692,6 @@
   }
 }
 
-class SourceChangeValidator {
-  final SourceChange change;
-
-  SourceChangeValidator(this.change);
-
-  void assertNoFileEdits() {
-    expect(change.edits, isEmpty);
-  }
-
-  SourceFileEditValidator hasFileEdit(String path) {
-    var edit = change.edits.singleWhere((e) => e.file == path);
-    return SourceFileEditValidator(edit);
-  }
-}
-
-class SourceFileEditValidator {
-  final SourceFileEdit edit;
-
-  SourceFileEditValidator(this.edit);
-
-  void whenApplied(String applyTo, Object expected) {
-    var actual = SourceEdit.applySequence(applyTo, edit.edits);
-    expect(actual, expected);
-  }
-}
-
 class SuggestionsValidator {
   final List<CompletionSuggestion> suggestions;
   final List<String>? libraryUrisToImport;
@@ -2605,8 +2712,17 @@
     expect(actual, completions);
   }
 
+  /// Assert that this has suggestions with all [expected] completions.
+  /// There might be more suggestions, with other completions.
+  ///
+  /// Does not check the order, kinds, elements, etc.
+  void assertCompletionsContainsAll(Iterable<String> expected) {
+    var actual = suggestions.map((e) => e.completion).toSet();
+    expect(actual, containsAll(expected));
+  }
+
   void assertEmpty() {
-    expect(suggestions, isEmpty);
+    check(suggestions).isEmpty;
   }
 
   void assertLength(Object matcher) {
@@ -2650,4 +2766,35 @@
       libraryUrisToImport: libraryUrisToImport,
     );
   }
+
+  SuggestionsValidator withKind(CompletionSuggestionKind kind) {
+    return SuggestionsValidator(
+      suggestions.where((suggestion) {
+        return suggestion.kind == kind;
+      }).toList(),
+      libraryUrisToImport: libraryUrisToImport,
+    );
+  }
+
+  SuggestionsValidator withKindIdentifier() {
+    return withKind(CompletionSuggestionKind.IDENTIFIER);
+  }
+}
+
+extension on CheckTarget<CompletionGetSuggestionDetails2Result> {
+  @useResult
+  CheckTarget<String> get completion {
+    return nest(
+      value.completion,
+      (selected) => 'has completion ${valueStr(selected)}',
+    );
+  }
+
+  @useResult
+  CheckTarget<SourceChange> get change {
+    return nest(
+      value.change,
+      (selected) => 'has change ${valueStr(selected)}',
+    );
+  }
 }
diff --git a/pkg/analysis_server/test/integration/support/integration_test_methods.dart b/pkg/analysis_server/test/integration/support/integration_test_methods.dart
index 9a707cf..aa0d470 100644
--- a/pkg/analysis_server/test/integration/support/integration_test_methods.dart
+++ b/pkg/analysis_server/test/integration/support/integration_test_methods.dart
@@ -1020,9 +1020,11 @@
   ///   True if the number of suggestions after filtering was greater than the
   ///   requested maxResults.
   Future<CompletionGetSuggestions2Result> sendCompletionGetSuggestions2(
-      String file, int offset, int maxResults) async {
-    var params =
-        CompletionGetSuggestions2Params(file, offset, maxResults).toJson();
+      String file, int offset, int maxResults,
+      {int? timeout}) async {
+    var params = CompletionGetSuggestions2Params(file, offset, maxResults,
+            timeout: timeout)
+        .toJson();
     var result = await server.send('completion.getSuggestions2', params);
     var decoder = ResponseDecoder(null);
     return CompletionGetSuggestions2Result.fromJson(decoder, 'result', result);
diff --git a/pkg/analysis_server/test/integration/support/integration_tests.dart b/pkg/analysis_server/test/integration/support/integration_tests.dart
index 6ca048e..3ef73c2 100644
--- a/pkg/analysis_server/test/integration/support/integration_tests.dart
+++ b/pkg/analysis_server/test/integration/support/integration_tests.dart
@@ -41,7 +41,7 @@
 Matcher isOneOf(List<Matcher> choiceMatchers) => _OneOf(choiceMatchers);
 
 /// Assert that [actual] matches [matcher].
-void outOfTestExpect(actual, Matcher matcher,
+void outOfTestExpect(Object? actual, Matcher matcher,
     {String? reason, skip, bool verbose = false}) {
   var matchState = {};
   try {
@@ -377,8 +377,8 @@
       description.add(this.description);
 
   @override
-  void populateMismatches(item, List<MismatchDescriber> mismatches) {
-    if (item is! Map) {
+  void populateMismatches(Object? item, List<MismatchDescriber> mismatches) {
+    if (item is! Map<String, Object?>) {
       mismatches.add(simpleDescription('is not a map'));
       return;
     }
@@ -535,7 +535,7 @@
       _recordStdio('<== $trimmedLine');
       Map message;
       try {
-        message = json.decoder.convert(trimmedLine);
+        message = json.decoder.convert(trimmedLine) as Map<Object?, Object?>;
       } catch (exception) {
         _badDataFromServer('JSON decode failure: $exception');
         return;
@@ -543,7 +543,7 @@
       outOfTestExpect(message, isMap);
       if (message.containsKey('id')) {
         outOfTestExpect(message['id'], isString);
-        String id = message['id'];
+        var id = message['id'] as String;
         var completer = _pendingCommands[id];
         if (completer == null) {
           fail('Unexpected response from server: id=$id');
@@ -553,7 +553,7 @@
         if (message.containsKey('error')) {
           completer.completeError(ServerErrorMessage(message));
         } else {
-          completer.complete(message['result']);
+          completer.complete(message['result'] as Map<String, Object?>?);
         }
         // Check that the message is well-formed.  We do this after calling
         // completer.complete() or completer.completeError() so that we don't
@@ -564,7 +564,8 @@
         // params.
         outOfTestExpect(message, contains('event'));
         outOfTestExpect(message['event'], isString);
-        notificationProcessor(message['event'], message['params']);
+        notificationProcessor(message['event'] as String,
+            message['params'] as Map<Object?, Object?>);
         // Check that the message is well-formed.  We do this after calling
         // notificationController.add() so that we don't stall the test in the
         // event of an error.
diff --git a/pkg/analysis_server/test/integration/support/protocol_matchers.dart b/pkg/analysis_server/test/integration/support/protocol_matchers.dart
index 5fd8c3c..70848d4 100644
--- a/pkg/analysis_server/test/integration/support/protocol_matchers.dart
+++ b/pkg/analysis_server/test/integration/support/protocol_matchers.dart
@@ -2139,7 +2139,8 @@
 /// }
 final Matcher isCompletionGetSuggestions2Params = LazyMatcher(() =>
     MatchesJsonObject('completion.getSuggestions2 params',
-        {'file': isFilePath, 'offset': isInt, 'maxResults': isInt}));
+        {'file': isFilePath, 'offset': isInt, 'maxResults': isInt},
+        optionalFields: {'timeout': isInt}));
 
 /// completion.getSuggestions2 result
 ///
diff --git a/pkg/analysis_server/test/lsp/code_actions_assists_test.dart b/pkg/analysis_server/test/lsp/code_actions_assists_test.dart
index 2797109..cf67637f 100644
--- a/pkg/analysis_server/test/lsp/code_actions_assists_test.dart
+++ b/pkg/analysis_server/test/lsp/code_actions_assists_test.dart
@@ -393,6 +393,39 @@
     }
   }
 
+  Future<void> test_sort() async {
+    const content = '''
+    import 'package:flutter/widgets.dart';
+
+    build() => Contai^ner(child: Container());
+    ''';
+
+    newFile(mainFilePath, content: withoutMarkers(content));
+    await initialize(
+      textDocumentCapabilities: withCodeActionKinds(
+          emptyTextDocumentClientCapabilities, [CodeActionKind.Refactor]),
+      workspaceCapabilities:
+          withDocumentChangesSupport(emptyWorkspaceClientCapabilities),
+    );
+
+    final codeActions = await getCodeActions(mainFileUri.toString(),
+        position: positionFromMarker(content));
+    final names = codeActions.map(
+      (e) => e.map((command) => command.title, (action) => action.title),
+    );
+
+    expect(
+      names,
+      containsAllInOrder([
+        // Check the ordering for two well-known assists that should always be
+        // sorted this way.
+        // https://github.com/Dart-Code/Dart-Code/issues/3646
+        'Wrap with widget...',
+        'Remove this widget',
+      ]),
+    );
+  }
+
   List<TextDocumentEdit> _extractTextDocumentEdits(
           Either2<
                   List<TextDocumentEdit>,
@@ -424,5 +457,5 @@
   _RawParams(this._json);
 
   @override
-  Object toJson() => jsonDecode(_json);
+  Object toJson() => jsonDecode(_json) as Object;
 }
diff --git a/pkg/analysis_server/test/lsp/completion_dart_test.dart b/pkg/analysis_server/test/lsp/completion_dart_test.dart
index 9ccf020..cbacc55 100644
--- a/pkg/analysis_server/test/lsp/completion_dart_test.dart
+++ b/pkg/analysis_server/test/lsp/completion_dart_test.dart
@@ -4,9 +4,11 @@
 
 import 'package:analysis_server/lsp_protocol/protocol_generated.dart';
 import 'package:analysis_server/src/lsp/constants.dart';
+import 'package:analysis_server/src/services/linter/lint_names.dart';
 import 'package:analyzer_plugin/protocol/protocol_common.dart' as plugin;
 import 'package:analyzer_plugin/protocol/protocol_generated.dart' as plugin;
 import 'package:collection/collection.dart';
+import 'package:linter/src/rules.dart';
 import 'package:test/test.dart';
 import 'package:test_reflective_loader/test_reflective_loader.dart';
 
@@ -234,6 +236,21 @@
         insertText: 'myFunction',
       );
 
+  Future<void> test_completeFunctionCalls_existingArgList_member_noPrefix() =>
+      // https://github.com/Dart-Code/Dart-Code/issues/3672
+      checkCompleteFunctionCallInsertText(
+        '''
+        class Aaaaa {
+          static foo(int a) {}
+        }
+        void f() {
+          Aaaaa.[[^]]()
+        }
+        ''',
+        'foo(…)',
+        insertText: 'foo',
+      );
+
   Future<void> test_completeFunctionCalls_existingArgList_namedConstructor() =>
       checkCompleteFunctionCallInsertText(
         '''
@@ -1606,6 +1623,36 @@
     expect(resolved.detail, isNull);
   }
 
+  Future<void> test_suggestionSets_importsPackageUri() async {
+    newFile(
+      join(projectFolderPath, 'lib', 'my_class.dart'),
+      content: 'class MyClass {}',
+    );
+
+    final content = '''
+void f() {
+  MyClas^
+}
+    ''';
+
+    final expectedContent = '''
+import 'package:test/my_class.dart';
+
+void f() {
+  MyClass
+}
+    ''';
+
+    final completionLabel = 'MyClass';
+
+    await _checkCompletionEdits(
+      mainFileUri,
+      content,
+      completionLabel,
+      expectedContent,
+    );
+  }
+
   Future<void>
       test_suggestionSets_includesReexportedSymbolsForEachFile() async {
     newFile(
@@ -2003,6 +2050,78 @@
     '''));
   }
 
+  Future<void> test_suggestionSets_preferRelativeImportsLib_insideLib() async {
+    _enableLints([LintNames.prefer_relative_imports]);
+    final importingFilePath =
+        join(projectFolderPath, 'lib', 'nested1', 'main.dart');
+    final importingFileUri = Uri.file(importingFilePath);
+    final importedFilePath =
+        join(projectFolderPath, 'lib', 'nested2', 'imported.dart');
+
+    // Create a file that will be auto-imported from completion.
+    newFile(importedFilePath, content: 'class MyClass {}');
+
+    final content = '''
+void f() {
+  MyClas^
+}
+    ''';
+
+    final expectedContent = '''
+import '../nested2/imported.dart';
+
+void f() {
+  MyClass
+}
+    ''';
+
+    final completionLabel = 'MyClass';
+
+    await _checkCompletionEdits(
+      importingFileUri,
+      content,
+      completionLabel,
+      expectedContent,
+    );
+  }
+
+  Future<void> test_suggestionSets_preferRelativeImportsLib_outsideLib() async {
+    // Files outside of the lib folder should still get absolute imports to
+    // files inside lib, even with the lint enabled.
+    _enableLints([LintNames.prefer_relative_imports]);
+    final importingFilePath =
+        join(projectFolderPath, 'bin', 'nested1', 'main.dart');
+    final importingFileUri = Uri.file(importingFilePath);
+    final importedFilePath =
+        join(projectFolderPath, 'lib', 'nested2', 'imported.dart');
+
+    // Create a file that will be auto-imported from completion.
+    newFile(importedFilePath, content: 'class MyClass {}');
+
+    final content = '''
+void f() {
+  MyClas^
+}
+    ''';
+
+    final expectedContent = '''
+import 'package:test/nested2/imported.dart';
+
+void f() {
+  MyClass
+}
+    ''';
+
+    final completionLabel = 'MyClass';
+
+    await _checkCompletionEdits(
+      importingFileUri,
+      content,
+      completionLabel,
+      expectedContent,
+    );
+  }
+
   Future<void> test_suggestionSets_unavailableIfDisabled() async {
     newFile(
       join(projectFolderPath, 'other_file.dart'),
@@ -2085,6 +2204,39 @@
     expect(updated, contains('a.abcdefghij'));
   }
 
+  /// Sets up the server with a file containing [content] and checks that
+  /// accepting a specific completion produces [expectedContent].
+  ///
+  /// [content] should contain a `^` at the location where completion should be
+  /// invoked/accepted.
+  Future<void> _checkCompletionEdits(
+    Uri fileUri,
+    String content,
+    String completionLabel,
+    String expectedContent,
+  ) async {
+    final initialAnalysis = waitForAnalysisComplete();
+    await initialize(
+        workspaceCapabilities:
+            withApplyEditSupport(emptyWorkspaceClientCapabilities));
+    await openFile(fileUri, withoutMarkers(content));
+    await initialAnalysis;
+    final res = await getCompletion(fileUri, positionFromMarker(content));
+
+    final completion = res.where((c) => c.label == completionLabel).single;
+    final resolvedCompletion = await resolveCompletion(completion);
+
+    // Apply both the main completion edit and the additionalTextEdits atomically.
+    final newContent = applyTextEdits(
+      withoutMarkers(content),
+      [toTextEdit(resolvedCompletion.textEdit!)]
+          .followedBy(resolvedCompletion.additionalTextEdits!)
+          .toList(),
+    );
+
+    expect(newContent, equals(expectedContent));
+  }
+
   Future<void> _checkResultsForTriggerCharacters(String content,
       List<String> triggerCharacters, Matcher expectedResults) async {
     await initialize();
@@ -2099,6 +2251,16 @@
       expect(res, expectedResults);
     }
   }
+
+  void _enableLints(List<String> lintNames) {
+    registerLintRules();
+    final lintsYaml = lintNames.map((name) => '    - $name\n').join();
+    newFile(analysisOptionsPath, content: '''
+linter:
+  rules:
+$lintsYaml
+''');
+  }
 }
 
 @reflectiveTest
diff --git a/pkg/analysis_server/test/lsp/diagnostic_test.dart b/pkg/analysis_server/test/lsp/diagnostic_test.dart
index fc6dffe..3b7fc18 100644
--- a/pkg/analysis_server/test/lsp/diagnostic_test.dart
+++ b/pkg/analysis_server/test/lsp/diagnostic_test.dart
@@ -88,7 +88,7 @@
 linter:
   rules:
     - invalid_lint_rule_name
-''').path;
+''');
 
     final firstDiagnosticsUpdate = waitForDiagnostics(analysisOptionsUri);
     await initialize();
@@ -102,7 +102,7 @@
   Future<void> test_analysisOptionsFile_packageInclude() async {
     newFile(analysisOptionsPath, content: '''
 include: package:pedantic/analysis_options.yaml
-''').path;
+''');
 
     // Verify there's an error for the import.
     final firstDiagnosticsUpdate = waitForDiagnostics(analysisOptionsUri);
diff --git a/pkg/analysis_server/test/lsp/document_color_test.dart b/pkg/analysis_server/test/lsp/document_color_test.dart
new file mode 100644
index 0000000..55dbf74
--- /dev/null
+++ b/pkg/analysis_server/test/lsp/document_color_test.dart
@@ -0,0 +1,158 @@
+// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'package:analysis_server/lsp_protocol/protocol_generated.dart';
+import 'package:test/test.dart';
+import 'package:test_reflective_loader/test_reflective_loader.dart';
+
+import 'server_abstract.dart';
+
+void main() {
+  defineReflectiveSuite(() {
+    defineReflectiveTests(DocumentColorTest);
+    defineReflectiveTests(DocumentColorPresentationTest);
+  });
+}
+
+@reflectiveTest
+class DocumentColorPresentationTest extends AbstractLspAnalysisServerTest {
+  late Range colorRange, importRange;
+  final uiImportUri = 'package:ui/ui.dart';
+
+  @override
+  void setUp() {
+    super.setUp();
+    writePackageConfig(projectFolderPath, flutter: true);
+  }
+
+  Future<void> test_includesImportEdit() async {
+    // Create a file that doesn't already import the required library.
+    //
+    // We don't need a real color reference in the file right now, as we're
+    // calling colorPresentation directly to get the new code (and not fetching
+    // colors already in the file).
+    const content = '''
+[[]]const white = [[]];
+''';
+
+    final ranges = rangesFromMarkers(content);
+    importRange = ranges[0];
+    colorRange = ranges[1];
+
+    newFile(mainFilePath, content: withoutMarkers(content));
+    await initialize();
+
+    final colorPresentations = await getColorPresentation(
+      mainFileUri.toString(),
+      colorRange,
+      Color(alpha: 1, red: 1, green: 1, blue: 1),
+    );
+
+    expect(
+      colorPresentations,
+      equals([
+        _color('Color.fromARGB(255, 255, 255, 255)', importUri: uiImportUri),
+        _color('Color.fromRGBO(255, 255, 255, 1)', importUri: uiImportUri),
+        _color('Color(0xFFFFFFFF)', importUri: uiImportUri),
+      ]),
+    );
+  }
+
+  Future<void> test_nonDartFile() async {
+    newFile(pubspecFilePath, content: simplePubspecContent);
+    await initialize();
+
+    final colors = await getColorPresentation(
+      pubspecFileUri.toString(),
+      startOfDocRange,
+      Color(alpha: 1, red: 1, green: 1, blue: 1),
+    );
+    expect(colors, isEmpty);
+  }
+
+  Future<void> test_simpleColor() async {
+    const content = '''
+    import 'package:flutter/material.dart';
+
+    const white = [[Color(0xFFFFFFFF)]];
+    ''';
+    colorRange = rangeFromMarkers(content);
+
+    newFile(mainFilePath, content: withoutMarkers(content));
+    await initialize();
+
+    final colorPresentations = await getColorPresentation(
+      mainFileUri.toString(),
+      colorRange,
+      // Send a different color to what's in the source to simulate the user
+      // having changed in the color picker. This is the one that we should be
+      // creating a presentation for, not the one in the source.
+      Color(alpha: 1, red: 1, green: 0, blue: 0),
+    );
+
+    expect(
+      colorPresentations,
+      equals([
+        _color('Color.fromARGB(255, 255, 0, 0)'),
+        _color('Color.fromRGBO(255, 0, 0, 1)'),
+        _color('Color(0xFFFF0000)'),
+      ]),
+    );
+  }
+
+  /// Creates a [ColorPresentation] for comparing against actual results.
+  ColorPresentation _color(
+    String label, {
+    String? colorCode,
+    String? importUri,
+  }) {
+    final edit = TextEdit(range: colorRange, newText: colorCode ?? label);
+    final additionalEdits = importUri != null
+        ? [TextEdit(range: importRange, newText: "import '$importUri';\n\n")]
+        : null;
+
+    return ColorPresentation(
+      label: label,
+      textEdit: edit,
+      additionalTextEdits: additionalEdits,
+    );
+  }
+}
+
+@reflectiveTest
+class DocumentColorTest extends AbstractLspAnalysisServerTest {
+  @override
+  void setUp() {
+    super.setUp();
+    writePackageConfig(projectFolderPath, flutter: true);
+  }
+
+  Future<void> test_nonDartFile() async {
+    newFile(pubspecFilePath, content: simplePubspecContent);
+    await initialize();
+
+    final colors = await getDocumentColors(pubspecFileUri.toString());
+    expect(colors, isEmpty);
+  }
+
+  Future<void> test_simpleColor() async {
+    const content = '''
+    import 'package:flutter/material.dart';
+
+    const red = [[Colors.red]];
+    ''';
+    newFile(mainFilePath, content: withoutMarkers(content));
+    await initialize();
+
+    final colors = await getDocumentColors(mainFileUri.toString());
+    expect(colors, hasLength(1));
+
+    final color = colors[0];
+    expect(color.range, rangeFromMarkers(content));
+    expect(color.color.alpha, equals(1));
+    expect(color.color.red, equals(1));
+    expect(color.color.green, equals(0));
+    expect(color.color.blue, equals(0));
+  }
+}
diff --git a/pkg/analysis_server/test/lsp/format_test.dart b/pkg/analysis_server/test/lsp/format_test.dart
index 61bac2e..7ffff8a 100644
--- a/pkg/analysis_server/test/lsp/format_test.dart
+++ b/pkg/analysis_server/test/lsp/format_test.dart
@@ -295,6 +295,26 @@
     await expectRangeFormattedContents(mainFileUri, contents, expected);
   }
 
+  Future<void> test_formatRange_trailingNewline_47702() async {
+    // Check we complete when a formatted block ends with a newline.
+    // https://github.com/dart-lang/sdk/issues/47702
+    const contents = '''
+int a;
+[[
+    int b;
+]]
+''';
+    final expected = '''
+int a;
+
+int b;
+
+''';
+    await initialize();
+    await openFile(mainFileUri, withoutMarkers(contents));
+    await expectRangeFormattedContents(mainFileUri, contents, expected);
+  }
+
   Future<void> test_invalidSyntax() async {
     const contents = '''void f(((( {
   print('test');
diff --git a/pkg/analysis_server/test/lsp/initialization_test.dart b/pkg/analysis_server/test/lsp/initialization_test.dart
index b6bbc58..4d006be 100644
--- a/pkg/analysis_server/test/lsp/initialization_test.dart
+++ b/pkg/analysis_server/test/lsp/initialization_test.dart
@@ -230,6 +230,7 @@
     expect(initResult.capabilities.hoverProvider, isNotNull);
     expect(initResult.capabilities.signatureHelpProvider, isNotNull);
     expect(initResult.capabilities.referencesProvider, isNotNull);
+    expect(initResult.capabilities.colorProvider, isNotNull);
     expect(initResult.capabilities.documentHighlightProvider, isNotNull);
     expect(initResult.capabilities.documentFormattingProvider, isNotNull);
     expect(initResult.capabilities.documentOnTypeFormattingProvider, isNotNull);
@@ -289,6 +290,7 @@
     expect(initResult.capabilities.hoverProvider, isNull);
     expect(initResult.capabilities.signatureHelpProvider, isNull);
     expect(initResult.capabilities.referencesProvider, isNull);
+    expect(initResult.capabilities.colorProvider, isNull);
     expect(initResult.capabilities.documentHighlightProvider, isNull);
     expect(initResult.capabilities.documentFormattingProvider, isNull);
     expect(initResult.capabilities.documentOnTypeFormattingProvider, isNull);
diff --git a/pkg/analysis_server/test/lsp/server_abstract.dart b/pkg/analysis_server/test/lsp/server_abstract.dart
index 6b8ba52..851966e 100644
--- a/pkg/analysis_server/test/lsp/server_abstract.dart
+++ b/pkg/analysis_server/test/lsp/server_abstract.dart
@@ -261,9 +261,11 @@
 
   void mergeJson(Map<String, dynamic> source, Map<String, dynamic> dest) {
     source.keys.forEach((key) {
-      if (source[key] is Map<String, dynamic> &&
-          dest[key] is Map<String, dynamic>) {
-        mergeJson(source[key], dest[key]);
+      var sourceValue = source[key];
+      var destValue = dest[key];
+      if (sourceValue is Map<String, dynamic> &&
+          destValue is Map<String, dynamic>) {
+        mergeJson(sourceValue, destValue);
       } else {
         dest[key] = source[key];
       }
@@ -284,6 +286,7 @@
       'references': {'dynamicRegistration': true},
       'documentHighlight': {'dynamicRegistration': true},
       'documentSymbol': {'dynamicRegistration': true},
+      'colorProvider': {'dynamicRegistration': true},
       'formatting': {'dynamicRegistration': true},
       'onTypeFormatting': {'dynamicRegistration': true},
       'rangeFormatting': {'dynamicRegistration': true},
@@ -877,7 +880,7 @@
     return expectSuccessfulResponseTo(request, (result) => result);
   }
 
-  void expect(actual, matcher, {String? reason}) =>
+  void expect(Object? actual, Matcher matcher, {String? reason}) =>
       test.expect(actual, matcher, reason: reason);
 
   void expectDocumentVersion(
@@ -1035,6 +1038,22 @@
     );
   }
 
+  Future<List<ColorPresentation>> getColorPresentation(
+      String fileUri, Range range, Color color) {
+    final request = makeRequest(
+      Method.textDocument_colorPresentation,
+      ColorPresentationParams(
+        textDocument: TextDocumentIdentifier(uri: fileUri),
+        range: range,
+        color: color,
+      ),
+    );
+    return expectSuccessfulResponseTo(
+      request,
+      _fromJsonList(ColorPresentation.fromJson),
+    );
+  }
+
   Future<List<CompletionItem>> getCompletion(Uri uri, Position pos,
       {CompletionContext? context}) {
     final request = makeRequest(
@@ -1093,6 +1112,19 @@
     return expectSuccessfulResponseTo(request, DartDiagnosticServer.fromJson);
   }
 
+  Future<List<ColorInformation>> getDocumentColors(String fileUri) {
+    final request = makeRequest(
+      Method.textDocument_documentColor,
+      DocumentColorParams(
+        textDocument: TextDocumentIdentifier(uri: fileUri),
+      ),
+    );
+    return expectSuccessfulResponseTo(
+      request,
+      _fromJsonList(ColorInformation.fromJson),
+    );
+  }
+
   Future<List<DocumentHighlight>?> getDocumentHighlights(
       Uri uri, Position pos) {
     final request = makeRequest(
@@ -1164,7 +1196,7 @@
   Future<List<Location>> getReferences(
     Uri uri,
     Position pos, {
-    includeDeclarations = false,
+    bool includeDeclarations = false,
   }) {
     final request = makeRequest(
       Method.textDocument_references,
diff --git a/pkg/analysis_server/test/lsp/test_all.dart b/pkg/analysis_server/test/lsp/test_all.dart
index 752d3f1..bd22081 100644
--- a/pkg/analysis_server/test/lsp/test_all.dart
+++ b/pkg/analysis_server/test/lsp/test_all.dart
@@ -20,6 +20,7 @@
 import 'definition_test.dart' as definition;
 import 'diagnostic_test.dart' as diagnostic;
 import 'document_changes_test.dart' as document_changes;
+import 'document_color_test.dart' as document_color;
 import 'document_highlights_test.dart' as document_highlights;
 import 'document_symbols_test.dart' as document_symbols;
 import 'file_modification_test.dart' as file_modification;
@@ -63,6 +64,7 @@
     document_changes.main();
     document_highlights.main();
     document_symbols.main();
+    document_color.main();
     file_modification.main();
     flutter_outline.main();
     folding.main();
diff --git a/pkg/analysis_server/test/mock_packages/flutter/lib/cupertino.dart b/pkg/analysis_server/test/mock_packages/flutter/lib/cupertino.dart
new file mode 100644
index 0000000..828a456
--- /dev/null
+++ b/pkg/analysis_server/test/mock_packages/flutter/lib/cupertino.dart
@@ -0,0 +1,5 @@
+// Copyright 2021 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+export 'src/cupertino/colors.dart';
diff --git a/pkg/analysis_server/test/mock_packages/flutter/lib/material.dart b/pkg/analysis_server/test/mock_packages/flutter/lib/material.dart
index 466ed8e..a1cecbd 100644
--- a/pkg/analysis_server/test/mock_packages/flutter/lib/material.dart
+++ b/pkg/analysis_server/test/mock_packages/flutter/lib/material.dart
@@ -3,6 +3,7 @@
 // found in the LICENSE file.
 
 export 'src/material/app_bar.dart';
+export 'src/material/colors.dart';
 export 'src/material/icons.dart';
 export 'src/material/scaffold.dart';
 export 'widgets.dart';
diff --git a/pkg/analysis_server/test/mock_packages/flutter/lib/painting.dart b/pkg/analysis_server/test/mock_packages/flutter/lib/painting.dart
index a3323f6..6eec7c5 100644
--- a/pkg/analysis_server/test/mock_packages/flutter/lib/painting.dart
+++ b/pkg/analysis_server/test/mock_packages/flutter/lib/painting.dart
@@ -5,6 +5,7 @@
 export 'src/painting/alignment.dart';
 export 'src/painting/basic_types.dart';
 export 'src/painting/box_decoration.dart';
+export 'src/painting/colors.dart';
 export 'src/painting/decoration.dart';
 export 'src/painting/edge_insets.dart';
 export 'src/painting/text_painter.dart';
diff --git a/pkg/analysis_server/test/mock_packages/flutter/lib/src/cupertino/colors.dart b/pkg/analysis_server/test/mock_packages/flutter/lib/src/cupertino/colors.dart
new file mode 100644
index 0000000..62356d5
--- /dev/null
+++ b/pkg/analysis_server/test/mock_packages/flutter/lib/src/cupertino/colors.dart
@@ -0,0 +1,102 @@
+// Copyright 2021 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+import 'package:flutter/painting.dart';
+
+class CupertinoColors {
+  CupertinoColors._();
+
+  static const CupertinoDynamicColor activeBlue = systemBlue;
+
+  static const Color black = Color(0xFF000000);
+  static const Color white = Color(0xFFFFFFFF);
+
+  static const CupertinoDynamicColor systemBlue =
+      CupertinoDynamicColor.withBrightnessAndContrast(
+    color: Color.fromARGB(255, 0, 0, 0xFF),
+    darkColor: Color.fromARGB(255, 0, 0, 0x99),
+    highContrastColor: Color.fromARGB(255, 0, 0, 0x66),
+    darkHighContrastColor: Color.fromARGB(255, 0, 0, 0x33),
+  );
+}
+
+class CupertinoDynamicColor extends Color {
+  const CupertinoDynamicColor({
+    Color color,
+    Color darkColor,
+    Color highContrastColor,
+    Color darkHighContrastColor,
+    Color elevatedColor,
+    Color darkElevatedColor,
+    Color highContrastElevatedColor,
+    Color darkHighContrastElevatedColor,
+  }) : this._(
+          color,
+          color,
+          darkColor,
+          highContrastColor,
+          darkHighContrastColor,
+          elevatedColor,
+          darkElevatedColor,
+          highContrastElevatedColor,
+          darkHighContrastElevatedColor,
+          null,
+        );
+
+  const CupertinoDynamicColor.withBrightnessAndContrast({
+    Color color,
+    Color darkColor,
+    Color highContrastColor,
+    Color darkHighContrastColor,
+  }) : this(
+          color: color,
+          darkColor: darkColor,
+          highContrastColor: highContrastColor,
+          darkHighContrastColor: darkHighContrastColor,
+          elevatedColor: color,
+          darkElevatedColor: darkColor,
+          highContrastElevatedColor: highContrastColor,
+          darkHighContrastElevatedColor: darkHighContrastColor,
+        );
+
+  const CupertinoDynamicColor.withBrightness({
+    Color color,
+    Color darkColor,
+  }) : this(
+          color: color,
+          darkColor: darkColor,
+          highContrastColor: color,
+          darkHighContrastColor: darkColor,
+          elevatedColor: color,
+          darkElevatedColor: darkColor,
+          highContrastElevatedColor: color,
+          darkHighContrastElevatedColor: darkColor,
+        );
+
+  const CupertinoDynamicColor._(
+    this._effectiveColor,
+    this.color,
+    this.darkColor,
+    this.highContrastColor,
+    this.darkHighContrastColor,
+    this.elevatedColor,
+    this.darkElevatedColor,
+    this.highContrastElevatedColor,
+    this.darkHighContrastElevatedColor,
+  ) : super(0);
+
+  final Color _effectiveColor;
+
+  @override
+  int get value => _effectiveColor.value;
+
+  final Color color;
+  final Color darkColor;
+  final Color highContrastColor;
+  final Color darkHighContrastColor;
+  final Color elevatedColor;
+  final Color darkElevatedColor;
+  final Color highContrastElevatedColor;
+  final Color darkHighContrastElevatedColor;
+}
diff --git a/pkg/analysis_server/test/mock_packages/flutter/lib/src/material/colors.dart b/pkg/analysis_server/test/mock_packages/flutter/lib/src/material/colors.dart
new file mode 100644
index 0000000..803f7a5
--- /dev/null
+++ b/pkg/analysis_server/test/mock_packages/flutter/lib/src/material/colors.dart
@@ -0,0 +1,71 @@
+// Copyright 2021 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+import 'package:flutter/painting.dart';
+
+class MaterialColor extends ColorSwatch<int> {
+  const MaterialColor(int primary, Map<int, Color> swatch)
+      : super(primary, swatch);
+
+  Color get shade100 => this[100];
+  Color get shade200 => this[200];
+  Color get shade300 => this[300];
+  Color get shade400 => this[400];
+  Color get shade50 => this[50];
+  Color get shade500 => this[500];
+  Color get shade600 => this[600];
+  Color get shade700 => this[700];
+  Color get shade800 => this[800];
+  Color get shade900 => this[900];
+}
+
+class MaterialAccentColor extends ColorSwatch<int> {
+  const MaterialAccentColor(int primary, Map<int, Color> swatch)
+      : super(primary, swatch);
+
+  Color get shade50 => this[50];
+  Color get shade100 => this[100];
+  Color get shade200 => this[200];
+  Color get shade400 => this[400];
+  Color get shade700 => this[700];
+}
+
+class Colors {
+  Colors._();
+
+  static const Color black = Color(0xFF000000);
+  static const Color white = Color(0xFFFFFFFF);
+
+  static const MaterialColor red = MaterialColor(
+    _redPrimaryValue,
+    <int, Color>{
+      // For simpler testing, these values are not the real Flutter values
+      // but just varying alphas on a primary value.
+      50: Color(0x05FF0000),
+      100: Color(0x10FF0000),
+      200: Color(0x20FF0000),
+      300: Color(0x30FF0000),
+      400: Color(0x40FF0000),
+      500: Color(0x50FF0000),
+      600: Color(0x60FF0000),
+      700: Color(0x70FF0000),
+      800: Color(0x80FF0000),
+      900: Color(0x90FF0000),
+    },
+  );
+  static const int _redPrimaryValue = 0xFFFF0000;
+
+  static const MaterialAccentColor redAccent = MaterialAccentColor(
+    _redAccentValue,
+    <int, Color>{
+      // For simpler testing, these values are not the real Flutter values
+      // but just varying alphas on a primary value.
+      100: Color(0x10FFAA00),
+      200: Color(0x20FFAA00),
+      400: Color(0x40FFAA00),
+      700: Color(0x70FFAA00),
+    },
+  );
+  static const int _redAccentValue = 0xFFFFAA00;
+}
diff --git a/pkg/analysis_server/test/mock_packages/flutter/lib/src/painting/colors.dart b/pkg/analysis_server/test/mock_packages/flutter/lib/src/painting/colors.dart
new file mode 100644
index 0000000..f0dbfae
--- /dev/null
+++ b/pkg/analysis_server/test/mock_packages/flutter/lib/src/painting/colors.dart
@@ -0,0 +1,16 @@
+// Copyright 2021 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/painting.dart';
+
+@immutable
+class ColorSwatch<T> extends Color {
+  const ColorSwatch(int primary, this._swatch) : super(primary);
+
+  @protected
+  final Map<T, Color> _swatch;
+
+  Color operator [](T index) => _swatch[index];
+}
diff --git a/pkg/analysis_server/test/mock_packages/meta/lib/meta_meta.dart b/pkg/analysis_server/test/mock_packages/meta/lib/meta_meta.dart
new file mode 100644
index 0000000..18902be
--- /dev/null
+++ b/pkg/analysis_server/test/mock_packages/meta/lib/meta_meta.dart
@@ -0,0 +1,123 @@
+// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+/// Annotations that describe the intended use of other annotations.
+library meta_meta;
+
+/// An annotation used on classes that are intended to be used as annotations
+/// to indicate the kinds of declarations and directives for which the
+/// annotation is appropriate.
+///
+/// The kinds are represented by the constants defined in [TargetKind].
+///
+/// Tools, such as the analyzer, can provide feedback if
+///
+/// * the annotation is associated with anything other than a class, where the
+///   class must be usable as an annotation (that is, contain at least one
+///   `const` constructor).
+/// * the annotated annotation is associated with anything other than the kinds
+///   of declarations listed as valid targets.
+@Target({TargetKind.classType})
+class Target {
+  /// The kinds of declarations with which the annotated annotation can be
+  /// associated.
+  final Set<TargetKind> kinds;
+
+  const Target(this.kinds);
+}
+
+/// An enumeration of the kinds of targets to which an annotation can be
+/// applied.
+enum TargetKind {
+  /// Indicates that an annotation is valid on any class declaration.
+  classType,
+
+  /// Indicates that an annotation is valid on any enum declaration.
+  enumType,
+
+  /// Indicates that an annotation is valid on any extension declaration.
+  extension,
+
+  /// Indicates that an annotation is valid on any field declaration, both
+  /// instance and static fields, whether it's in a class, mixin or extension.
+  field,
+
+  /// Indicates that an annotation is valid on any top-level function
+  /// declaration.
+  function,
+
+  /// Indicates that an annotation is valid on the first directive in a library,
+  /// whether that's a `library`, `import`, `export` or `part` directive. This
+  /// doesn't include the `part of` directive in a part file.
+  library,
+
+  /// Indicates that an annotation is valid on any getter declaration, both
+  /// instance or static getters, whether it's in a class, mixin, extension, or
+  /// at the top-level of a library.
+  getter,
+
+  /// Indicates that an annotation is valid on any method declaration, both
+  /// instance and static methods, whether it's in a class, mixin or extension.
+  method,
+
+  /// Indicates that an annotation is valid on any mixin declaration.
+  mixinType,
+
+  /// Indicates that an annotation is valid on any formal parameter declaration,
+  /// whether it's in a function, method, constructor, or closure.
+  parameter,
+
+  /// Indicates that an annotation is valid on any setter declaration, both
+  /// instance or static setters, whether it's in a class, mixin, extension, or
+  /// at the top-level of a library.
+  setter,
+
+  /// Indicates that an annotation is valid on any top-level variable
+  /// declaration.
+  topLevelVariable,
+
+  /// Indicates that an annotation is valid on any declaration that introduces a
+  /// type. This includes classes, enums, mixins and typedefs, but does not
+  /// include extensions because extensions don't introduce a type.
+  type,
+
+  /// Indicates that an annotation is valid on any typedef declaration.
+  typedefType,
+}
+
+extension TargetKindExtension on TargetKind {
+  /// Return a user visible string used to describe this target kind.
+  String get displayString {
+    switch (this) {
+      case TargetKind.classType:
+        return 'classes';
+      case TargetKind.enumType:
+        return 'enums';
+      case TargetKind.extension:
+        return 'extensions';
+      case TargetKind.field:
+        return 'fields';
+      case TargetKind.function:
+        return 'top-level functions';
+      case TargetKind.library:
+        return 'libraries';
+      case TargetKind.getter:
+        return 'getters';
+      case TargetKind.method:
+        return 'methods';
+      case TargetKind.mixinType:
+        return 'mixins';
+      case TargetKind.parameter:
+        return 'parameters';
+      case TargetKind.setter:
+        return 'setters';
+      case TargetKind.topLevelVariable:
+        return 'top-level variables';
+      case TargetKind.type:
+        return 'types (classes, enums, mixins, or typedefs)';
+      case TargetKind.typedefType:
+        return 'typedefs';
+    }
+  }
+}
diff --git a/pkg/analysis_server/test/search/declarations_test.dart b/pkg/analysis_server/test/search/declarations_test.dart
index 3d64012..3c0a02f 100644
--- a/pkg/analysis_server/test/search/declarations_test.dart
+++ b/pkg/analysis_server/test/search/declarations_test.dart
@@ -208,8 +208,8 @@
     assertHas('s', ElementKind.SETTER);
     assertHas('f', ElementKind.FUNCTION);
     assertHas('v', ElementKind.TOP_LEVEL_VARIABLE);
-    assertHas('tf1', ElementKind.FUNCTION_TYPE_ALIAS);
-    assertHas('tf2', ElementKind.FUNCTION_TYPE_ALIAS);
+    assertHas('tf1', ElementKind.TYPE_ALIAS);
+    assertHas('tf2', ElementKind.TYPE_ALIAS);
     assertHas('td3', ElementKind.TYPE_ALIAS);
   }
 
diff --git a/pkg/analysis_server/test/services/completion/dart/arglist_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/arglist_contributor_test.dart
index 690b251..4c2e182 100644
--- a/pkg/analysis_server/test/services/completion/dart/arglist_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/arglist_contributor_test.dart
@@ -123,7 +123,7 @@
 class ArgListContributorTest extends DartCompletionContributorTest
     with ArgListContributorMixin {
   Future<void> test_Annotation_imported_constructor_named_param() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 library libA; class A { const A({int one, String two: 'defaultValue'}); }''');
     addTestSource('import "a.dart"; @A(^) main() { }');
     await computeSuggestions();
@@ -132,7 +132,7 @@
   }
 
   Future<void> test_Annotation_importedConstructor_prefixed() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 class A {
   const A({int value});
 }
@@ -581,7 +581,8 @@
 
   Future<void> test_ArgumentList_imported_constructor_named_param() async {
     // ArgumentList  InstanceCreationExpression  ExpressionStatement
-    addSource('/home/test/lib/a.dart', 'library libA; class A{A({int one}); }');
+    addSource(
+        '$testPackageLibPath/a.dart', 'library libA; class A{A({int one}); }');
     addTestSource('import "a.dart"; main() { new A(^);}');
     await computeSuggestions();
     assertSuggestArgumentsAndTypes(namedArgumentsWithTypes: {'one': 'int'});
@@ -589,8 +590,8 @@
 
   Future<void> test_ArgumentList_imported_constructor_named_param2() async {
     // ArgumentList  InstanceCreationExpression  ExpressionStatement
-    addSource(
-        '/home/test/lib/a.dart', 'library libA; class A{A.foo({int one}); }');
+    addSource('$testPackageLibPath/a.dart',
+        'library libA; class A{A.foo({int one}); }');
     addTestSource('import "a.dart"; main() { new A.foo(^);}');
     await computeSuggestions();
     assertSuggestArgumentsAndTypes(namedArgumentsWithTypes: {'one': 'int'});
@@ -599,7 +600,7 @@
   Future<void>
       test_ArgumentList_imported_constructor_named_typed_param() async {
     // ArgumentList  InstanceCreationExpression  VariableDeclaration
-    addSource('/home/test/lib/a.dart',
+    addSource('$testPackageLibPath/a.dart',
         'library libA; class A { A({int i, String s, d}) {} }}');
     addTestSource('import "a.dart"; main() { var a = new A(^);}');
     await computeSuggestions();
@@ -609,7 +610,7 @@
 
   Future<void> test_ArgumentList_imported_factory_named_param() async {
     // ArgumentList  InstanceCreationExpression  ExpressionStatement
-    addSource('/home/test/lib/a.dart',
+    addSource('$testPackageLibPath/a.dart',
         'library libA; class A{factory A({int one}) => throw 0;}');
     addTestSource('import "a.dart"; main() { new A(^);}');
     await computeSuggestions();
@@ -618,7 +619,7 @@
 
   Future<void> test_ArgumentList_imported_factory_named_param2() async {
     // ArgumentList  InstanceCreationExpression  ExpressionStatement
-    addSource('/home/test/lib/a.dart',
+    addSource('$testPackageLibPath/a.dart',
         'library libA; abstract class A{factory A.foo({int one});}');
     addTestSource('import "a.dart"; main() { new A.foo(^);}');
     await computeSuggestions();
@@ -627,7 +628,7 @@
 
   Future<void> test_ArgumentList_imported_factory_named_typed_param() async {
     // ArgumentList  InstanceCreationExpression  VariableDeclaration
-    addSource('/home/test/lib/a.dart',
+    addSource('$testPackageLibPath/a.dart',
         'library libA; class A {factory A({int i, String s, d}) {} }}');
     addTestSource('import "a.dart"; main() { var a = new A(^);}');
     await computeSuggestions();
@@ -637,7 +638,7 @@
 
   Future<void> test_ArgumentList_imported_function_0() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
       library A;
       bool hasLength(int expected) { }
       expect() { }
@@ -653,7 +654,7 @@
 
   Future<void> test_ArgumentList_imported_function_3a() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
       library A;
       bool hasLength(int expected) { }
       expect(String arg1, int arg2, {bool arg3}) { }
@@ -669,7 +670,7 @@
 
   Future<void> test_ArgumentList_imported_function_3b() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
       library A;
       bool hasLength(int expected) { }
       expect(String arg1, int arg2, {bool arg3}) { }
@@ -685,7 +686,7 @@
 
   Future<void> test_ArgumentList_imported_function_3c() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
       library A;
       bool hasLength(int expected) { }
       expect(String arg1, int arg2, {bool arg3}) { }
@@ -701,7 +702,7 @@
 
   Future<void> test_ArgumentList_imported_function_3d() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
       library A;
       bool hasLength(int expected) { }
       expect(String arg1, int arg2, {bool arg3}) { }
@@ -1084,7 +1085,7 @@
 
   Future<void> test_ArgumentList_local_method_0() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
       library A;
       bool hasLength(int expected) { }
       void baz() { }''');
@@ -1111,7 +1112,7 @@
   }
 
   Future<void> test_ArgumentList_nnbd_function_named_param_imported() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 f({int? nullable, int nonnullable}) {}''');
     createAnalysisOptionsFile(experiments: [EnableString.non_nullable]);
     addTestSource(r'''
@@ -1126,7 +1127,7 @@
   }
 
   Future<void> test_ArgumentList_nnbd_function_named_param_legacy() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 // @dart = 2.8
 f({int named}) {}''');
     addTestSource(r'''
diff --git a/pkg/analysis_server/test/services/completion/dart/combinator_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/combinator_contributor_test.dart
index 3099fcf..a04f0be 100644
--- a/pkg/analysis_server/test/services/completion/dart/combinator_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/combinator_contributor_test.dart
@@ -41,17 +41,17 @@
 
   Future<void> test_Combinator_hide() async {
     // SimpleIdentifier  HideCombinator  ImportDirective
-    addSource('/home/test/lib/ab.dart', '''
+    addSource('$testPackageLibPath/ab.dart', '''
       library libAB;
       part "ab_part.dart";
       class A { }
       class B { }''');
-    addSource('/home/test/lib/ab_part.dart', '''
+    addSource('$testPackageLibPath/ab_part.dart', '''
       part of libAB;
       var T1;
       PB F1() => new PB();
       class PB { }''');
-    addSource('/home/test/lib/cd.dart', '''
+    addSource('$testPackageLibPath/cd.dart', '''
       class C { }
       class D { }''');
     addTestSource('''
@@ -81,20 +81,20 @@
 
   Future<void> test_Combinator_show() async {
     // SimpleIdentifier  HideCombinator  ImportDirective
-    addSource('/home/test/lib/ab.dart', '''
+    addSource('$testPackageLibPath/ab.dart', '''
       library libAB;
       part "ab_part.dart";
       class A { }
       class B { }
       class _AB''');
-    addSource('/home/test/lib/ab_part.dart', '''
+    addSource('$testPackageLibPath/ab_part.dart', '''
       part of libAB;
       var T1;
       PB F1() => new PB();
       typedef PB2 F2(int blat);
       class Clz = Object with Object;
       class PB { }''');
-    addSource('/home/test/lib/cd.dart', '''
+    addSource('$testPackageLibPath/cd.dart', '''
       class C { }
       class D { }''');
     addTestSource('''
@@ -129,11 +129,11 @@
   }
 
   Future<void> test_Combinator_show_export_withShow() async {
-    addSource('/home/test/lib/a.dart', r'''
+    addSource('$testPackageLibPath/a.dart', r'''
 class A {}
 class B {}
 ''');
-    addSource('/home/test/lib/b.dart', r'''
+    addSource('$testPackageLibPath/b.dart', r'''
 export 'a.dart' show A;
 ''');
     addTestSource(r'''
@@ -152,10 +152,10 @@
   }
 
   Future<void> test_Combinator_show_recursive() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 class A {}
 ''');
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 export 'a.dart';
 export 'b.dart';
 class B {}
diff --git a/pkg/analysis_server/test/services/completion/dart/completion_contributor_util.dart b/pkg/analysis_server/test/services/completion/dart/completion_contributor_util.dart
index 4926490..a8c7e39 100644
--- a/pkg/analysis_server/test/services/completion/dart/completion_contributor_util.dart
+++ b/pkg/analysis_server/test/services/completion/dart/completion_contributor_util.dart
@@ -5,7 +5,6 @@
 import 'dart:async';
 
 import 'package:analysis_server/src/provisional/completion/dart/completion_dart.dart';
-import 'package:analysis_server/src/services/completion/completion_performance.dart';
 import 'package:analysis_server/src/services/completion/dart/completion_manager.dart'
     show DartCompletionRequest;
 import 'package:analysis_server/src/services/completion/dart/suggestion_builder.dart';
@@ -530,24 +529,21 @@
 
   Future computeSuggestions({int times = 200}) async {
     result = await session.getResolvedUnit(testFile) as ResolvedUnitResult;
-    return await CompletionPerformance().runRequestOperation(
-      (performance) async {
-        // Build the request
-        var request = DartCompletionRequest(
-          resolvedUnit: result,
-          offset: completionOffset,
-          dartdocDirectiveInfo: dartdocInfo,
-        );
 
-        var range = request.target.computeReplacementRange(request.offset);
-        replacementOffset = range.offset;
-        replacementLength = range.length;
-
-        // Request completions
-        suggestions = await computeContributedSuggestions(request);
-        expect(suggestions, isNotNull, reason: 'expected suggestions');
-      },
+    // Build the request
+    var request = DartCompletionRequest.forResolvedUnit(
+      resolvedUnit: result,
+      offset: completionOffset,
+      dartdocDirectiveInfo: dartdocInfo,
     );
+
+    var range = request.target.computeReplacementRange(request.offset);
+    replacementOffset = range.offset;
+    replacementLength = range.length;
+
+    // Request completions
+    suggestions = await computeContributedSuggestions(request);
+    expect(suggestions, isNotNull, reason: 'expected suggestions');
   }
 
   Never failedCompletion(String message,
@@ -613,7 +609,7 @@
   @override
   void setUp() {
     super.setUp();
-    testFile = convertPath('/home/test/lib/test.dart');
+    testFile = convertPath('$testPackageLibPath/test.dart');
   }
 
   CompletionSuggestion suggestionWith(
diff --git a/pkg/analysis_server/test/services/completion/dart/completion_manager_test.dart b/pkg/analysis_server/test/services/completion/dart/completion_manager_test.dart
index 972198c..be920e7 100644
--- a/pkg/analysis_server/test/services/completion/dart/completion_manager_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/completion_manager_test.dart
@@ -52,12 +52,12 @@
     // Build the request
     var resolvedUnit =
         await session.getResolvedUnit(testFile) as ResolvedUnitResult;
-    request = DartCompletionRequest(
+    request = DartCompletionRequest.forResolvedUnit(
       resolvedUnit: resolvedUnit,
       offset: completionOffset,
     );
 
-    var directives = request.target.unit.directives;
+    var directives = resolvedUnit.unit.directives;
 
     var imports = request.libraryElement.imports;
     expect(imports, hasLength(directives.length + 1));
diff --git a/pkg/analysis_server/test/services/completion/dart/imported_reference_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/imported_reference_contributor_test.dart
index 6f277c3..534635b 100644
--- a/pkg/analysis_server/test/services/completion/dart/imported_reference_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/imported_reference_contributor_test.dart
@@ -36,7 +36,7 @@
 class ImportedReferenceContributorTest extends DartCompletionContributorTest
     with ImportedReferenceContributorMixin {
   Future<void> test_Annotation_typeArguments() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 class C {}
 typedef T1 = void Function();
 typedef T2 = List<int>;
@@ -67,7 +67,7 @@
   Future<void> test_ArgDefaults_function_with_required_named() async {
     writeTestPackageConfig(meta: true);
 
-    resolveSource('/home/test/lib/b.dart', '''
+    resolveSource('$testPackageLibPath/b.dart', '''
 lib B;
 import 'package:meta/meta.dart';
 
@@ -85,7 +85,7 @@
 
   Future<void> test_ArgumentList() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
         library A;
         bool hasLength(int expected) { }
         void baz() { }''');
@@ -110,7 +110,7 @@
 
   Future<void> test_ArgumentList_imported_function() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
         library A;
         bool hasLength(int expected) { }
         expect(arg) { }
@@ -137,7 +137,7 @@
   Future<void>
       test_ArgumentList_InstanceCreationExpression_functionalArg() async {
     // ArgumentList  InstanceCreationExpression  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         library A;
         class A { A(f()) { } }
         bool hasLength(int expected) { }
@@ -167,7 +167,7 @@
 
   Future<void> test_ArgumentList_InstanceCreationExpression_typedefArg() async {
     // ArgumentList  InstanceCreationExpression  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         library A;
         typedef Funct();
         class A { A(Funct f) { } }
@@ -198,7 +198,7 @@
 
   Future<void> test_ArgumentList_local_function() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
         library A;
         bool hasLength(int expected) { }
         void baz() { }''');
@@ -224,7 +224,7 @@
 
   Future<void> test_ArgumentList_local_method() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
         library A;
         bool hasLength(int expected) { }
         void baz() { }''');
@@ -250,7 +250,7 @@
 
   Future<void> test_ArgumentList_MethodInvocation_functionalArg() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         library A;
         class A { A(f()) { } }
         bool hasLength(int expected) { }
@@ -280,7 +280,7 @@
 
   Future<void> test_ArgumentList_MethodInvocation_methodArg() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         library A;
         class A { A(f()) { } }
         bool hasLength(int expected) { }
@@ -309,7 +309,7 @@
   Future<void> test_ArgumentList_namedParam() async {
     // SimpleIdentifier  NamedExpression  ArgumentList  MethodInvocation
     // ExpressionStatement
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         library A;
         bool hasLength(int expected) { }''');
     addTestSource('''
@@ -331,7 +331,7 @@
   }
 
   Future<void> test_AsExpression() async {
-    // SimpleIdentifier  TypeName  AsExpression
+    // SimpleIdentifier  NamedType  AsExpression
     addTestSource('''
         class A {var b; X _c; foo() {var a; (a as ^).foo();}''');
 
@@ -351,8 +351,8 @@
     // suggesting types. We ought to do so because there's no reason to cast a
     // value to the type it already has.
 
-    // SimpleIdentifier  TypeName  AsExpression  IfStatement
-    addSource('/home/test/lib/b.dart', '''
+    // SimpleIdentifier  NamedType  AsExpression  IfStatement
+    addSource('$testPackageLibPath/b.dart', '''
           foo() { }
           class A {} class B extends A {} class C extends B {}
           class X {X.c(); X._d(); z() {}}''');
@@ -378,8 +378,8 @@
     // suggesting types. We ought to do so because there's no reason to cast a
     // value to the type it already has.
 
-    // SimpleIdentifier  TypeName  AsExpression  IfStatement
-    addSource('/home/test/lib/b.dart', '''
+    // SimpleIdentifier  NamedType  AsExpression  IfStatement
+    addSource('$testPackageLibPath/b.dart', '''
           foo() { }
           class A {} class B implements A {} class C implements B {}
           class X {X.c(); X._d(); z() {}}''');
@@ -423,7 +423,7 @@
   }
 
   Future<void> test_AssignmentExpression_type() async {
-    // SimpleIdentifier  TypeName  VariableDeclarationList
+    // SimpleIdentifier  NamedType  VariableDeclarationList
     // VariableDeclarationStatement  Block
     addTestSource('''
         class A {} void f() {
@@ -446,7 +446,7 @@
   }
 
   Future<void> test_AssignmentExpression_type_newline() async {
-    // SimpleIdentifier  TypeName  VariableDeclarationList
+    // SimpleIdentifier  NamedType  VariableDeclarationList
     // VariableDeclarationStatement  Block
     addTestSource('''
         class A {} void f() {
@@ -468,7 +468,7 @@
   }
 
   Future<void> test_AssignmentExpression_type_partial() async {
-    // SimpleIdentifier  TypeName  VariableDeclarationList
+    // SimpleIdentifier  NamedType  VariableDeclarationList
     // VariableDeclarationStatement  Block
     addTestSource('''
         class A {} void f() {
@@ -491,7 +491,7 @@
   }
 
   Future<void> test_AssignmentExpression_type_partial_newline() async {
-    // SimpleIdentifier  TypeName  VariableDeclarationList
+    // SimpleIdentifier  NamedType  VariableDeclarationList
     // VariableDeclarationStatement  Block
     addTestSource('''
         class A {} void f() {
@@ -528,7 +528,7 @@
   }
 
   Future<void> test_AwaitExpression_function() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 Future y() async {return 0;}
 ''');
     addTestSource('''
@@ -548,7 +548,7 @@
 
   Future<void> test_AwaitExpression_inherited() async {
     // SimpleIdentifier  AwaitExpression  ExpressionStatement
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 lib libB;
 class A {
   Future y() async { return 0; }
@@ -602,21 +602,21 @@
 
   Future<void> test_Block() async {
     // Block  BlockFunctionBody  MethodDeclaration
-    addSource('/home/test/lib/ab.dart', '''
+    addSource('$testPackageLibPath/ab.dart', '''
         export "dart:math" hide max;
         class A {int x;}
         @deprecated D1() {int x;}
         class _B {boo() { partBoo() {}} }''');
-    addSource('/home/test/lib/cd.dart', '''
+    addSource('$testPackageLibPath/cd.dart', '''
         String T1;
         var _T2;
         class C { }
         class D { }''');
-    addSource('/home/test/lib/eef.dart', '''
+    addSource('$testPackageLibPath/eef.dart', '''
         class EE { }
         class F { }''');
-    addSource('/home/test/lib/g.dart', 'class G { }');
-    addSource('/home/test/lib/h.dart', '''
+    addSource('$testPackageLibPath/g.dart', 'class G { }');
+    addSource('$testPackageLibPath/h.dart', '''
         class H { }
         int T3;
         var _T4;'''); // not imported
@@ -657,7 +657,7 @@
     assertNotSuggested('x');
     assertNotSuggested('partT8');
 
-    assertSuggestClass('A', elemFile: '/home/test/lib/ab.dart');
+    assertSuggestClass('A', elemFile: '$testPackageLibPath/ab.dart');
     if (suggestConstructorsWithoutNew) {
       assertSuggestConstructor('A');
     }
@@ -705,21 +705,21 @@
 
   Future<void> test_Block_final() async {
     // Block  BlockFunctionBody  MethodDeclaration
-    addSource('/home/test/lib/ab.dart', '''
+    addSource('$testPackageLibPath/ab.dart', '''
         export "dart:math" hide max;
         class A {int x;}
         @deprecated D1() {int x;}
         class _B {boo() { partBoo() {}} }''');
-    addSource('/home/test/lib/cd.dart', '''
+    addSource('$testPackageLibPath/cd.dart', '''
         String T1;
         var _T2;
         class C { }
         class D { }''');
-    addSource('/home/test/lib/eef.dart', '''
+    addSource('$testPackageLibPath/eef.dart', '''
         class EE { }
         class F { }''');
-    addSource('/home/test/lib/g.dart', 'class G { }');
-    addSource('/home/test/lib/h.dart', '''
+    addSource('$testPackageLibPath/g.dart', 'class G { }');
+    addSource('$testPackageLibPath/h.dart', '''
         class H { }
         int T3;
         var _T4;'''); // not imported
@@ -818,21 +818,21 @@
 
   Future<void> test_Block_final_final() async {
     // Block  BlockFunctionBody  MethodDeclaration
-    addSource('/home/test/lib/ab.dart', '''
+    addSource('$testPackageLibPath/ab.dart', '''
         export "dart:math" hide max;
         class A {int x;}
         @deprecated D1() {int x;}
         class _B {boo() { partBoo() {}} }''');
-    addSource('/home/test/lib/cd.dart', '''
+    addSource('$testPackageLibPath/cd.dart', '''
         String T1;
         var _T2;
         class C { }
         class D { }''');
-    addSource('/home/test/lib/eef.dart', '''
+    addSource('$testPackageLibPath/eef.dart', '''
         class EE { }
         class F { }''');
-    addSource('/home/test/lib/g.dart', 'class G { }');
-    addSource('/home/test/lib/h.dart', '''
+    addSource('$testPackageLibPath/g.dart', 'class G { }');
+    addSource('$testPackageLibPath/h.dart', '''
         class H { }
         int T3;
         var _T4;'''); // not imported
@@ -919,21 +919,21 @@
 
   Future<void> test_Block_final_var() async {
     // Block  BlockFunctionBody  MethodDeclaration
-    addSource('/home/test/lib/ab.dart', '''
+    addSource('$testPackageLibPath/ab.dart', '''
         export "dart:math" hide max;
         class A {int x;}
         @deprecated D1() {int x;}
         class _B {boo() { partBoo() {}} }''');
-    addSource('/home/test/lib/cd.dart', '''
+    addSource('$testPackageLibPath/cd.dart', '''
         String T1;
         var _T2;
         class C { }
         class D { }''');
-    addSource('/home/test/lib/eef.dart', '''
+    addSource('$testPackageLibPath/eef.dart', '''
         class EE { }
         class F { }''');
-    addSource('/home/test/lib/g.dart', 'class G { }');
-    addSource('/home/test/lib/h.dart', '''
+    addSource('$testPackageLibPath/g.dart', 'class G { }');
+    addSource('$testPackageLibPath/h.dart', '''
         class H { }
         int T3;
         var _T4;'''); // not imported
@@ -1017,21 +1017,21 @@
   }
 
   Future<void> test_Block_identifier_partial() async {
-    resolveSource('/home/test/lib/ab.dart', '''
+    resolveSource('$testPackageLibPath/ab.dart', '''
         export "dart:math" hide max;
         class A {int x;}
         @deprecated D1() {int x;}
         class _B { }''');
-    addSource('/home/test/lib/cd.dart', '''
+    addSource('$testPackageLibPath/cd.dart', '''
         String T1;
         var _T2;
         class C { }
         class D { }''');
-    addSource('/home/test/lib/eef.dart', '''
+    addSource('$testPackageLibPath/eef.dart', '''
         class EE { }
         class DF { }''');
-    addSource('/home/test/lib/g.dart', 'class G { }');
-    addSource('/home/test/lib/h.dart', '''
+    addSource('$testPackageLibPath/g.dart', 'class G { }');
+    addSource('$testPackageLibPath/h.dart', '''
         class H { }
         class D3 { }
         int T3;
@@ -1094,7 +1094,7 @@
 
   Future<void> test_Block_inherited_imported() async {
     // Block  BlockFunctionBody  MethodDeclaration  ClassDeclaration
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         class F { var f1; f2() { } get f3 => 0; set f4(fx) { } var _pf; }
         class E extends F { var e1; e2() { } }
@@ -1148,21 +1148,21 @@
   }
 
   Future<void> test_Block_local_function() async {
-    addSource('/home/test/lib/ab.dart', '''
+    addSource('$testPackageLibPath/ab.dart', '''
         export "dart:math" hide max;
         class A {int x;}
         @deprecated D1() {int x;}
         class _B {boo() { partBoo() {}} }''');
-    addSource('/home/test/lib/cd.dart', '''
+    addSource('$testPackageLibPath/cd.dart', '''
         String T1;
         var _T2;
         class C { }
         class D { }''');
-    addSource('/home/test/lib/eef.dart', '''
+    addSource('$testPackageLibPath/eef.dart', '''
         class EE { }
         class F { }''');
-    addSource('/home/test/lib/g.dart', 'class G { }');
-    addSource('/home/test/lib/h.dart', '''
+    addSource('$testPackageLibPath/g.dart', 'class G { }');
+    addSource('$testPackageLibPath/h.dart', '''
         class H { }
         int T3;
         var _T4;'''); // not imported
@@ -1200,21 +1200,21 @@
 
   Future<void> test_Block_partial_results() async {
     // Block  BlockFunctionBody  MethodDeclaration
-    addSource('/home/test/lib/ab.dart', '''
+    addSource('$testPackageLibPath/ab.dart', '''
         export "dart:math" hide max;
         class A {int x;}
         @deprecated D1() {int x;}
         class _B { }''');
-    addSource('/home/test/lib/cd.dart', '''
+    addSource('$testPackageLibPath/cd.dart', '''
         String T1;
         var _T2;
         class C { }
         class D { }''');
-    addSource('/home/test/lib/eef.dart', '''
+    addSource('$testPackageLibPath/eef.dart', '''
         class EE { }
         class F { }''');
-    addSource('/home/test/lib/g.dart', 'class G { }');
-    addSource('/home/test/lib/h.dart', '''
+    addSource('$testPackageLibPath/g.dart', 'class G { }');
+    addSource('$testPackageLibPath/h.dart', '''
         class H { }
         int T3;
         var _T4;'''); // not imported
@@ -1252,7 +1252,7 @@
 
   Future<void> test_CascadeExpression_selector1() async {
     // PropertyAccess  CascadeExpression  ExpressionStatement  Block
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         class B { }''');
     addTestSource('''
         import 'b.dart';
@@ -1277,7 +1277,7 @@
 
   Future<void> test_CascadeExpression_selector2() async {
     // SimpleIdentifier  PropertyAccess  CascadeExpression  ExpressionStatement
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         class B { }''');
     addTestSource('''
         import 'b.dart';
@@ -1300,7 +1300,7 @@
 
   Future<void> test_CascadeExpression_selector2_withTrailingReturn() async {
     // PropertyAccess  CascadeExpression  ExpressionStatement  Block
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         class B { }''');
     addTestSource('''
         import 'b.dart';
@@ -1342,7 +1342,7 @@
   }
 
   Future<void> test_CatchClause_onType() async {
-    // TypeName  CatchClause  TryStatement
+    // NamedType  CatchClause  TryStatement
     addTestSource('class A {a() {try{var x;} on ^ {}}}');
 
     await computeSuggestions();
@@ -1355,7 +1355,7 @@
   }
 
   Future<void> test_CatchClause_onType_noBrackets() async {
-    // TypeName  CatchClause  TryStatement
+    // NamedType  CatchClause  TryStatement
     addTestSource('class A {a() {try{var x;} on ^}}');
 
     await computeSuggestions();
@@ -1395,7 +1395,7 @@
 
   Future<void> test_ClassDeclaration_body() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         class B { }''');
     addTestSource('''
         import "b.dart" as x;
@@ -1420,7 +1420,7 @@
 
   Future<void> test_ClassDeclaration_body_final() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         class B { }''');
     addTestSource('''
         import "b.dart" as x;
@@ -1441,7 +1441,7 @@
 
   Future<void> test_ClassDeclaration_body_final_field() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         class B { }''');
     addTestSource('''
         import "b.dart" as x;
@@ -1462,7 +1462,7 @@
 
   Future<void> test_ClassDeclaration_body_final_field2() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         class B { }''');
     addTestSource('''
         import "b.dart" as Soo;
@@ -1483,7 +1483,7 @@
 
   Future<void> test_ClassDeclaration_body_final_final() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         class B { }''');
     addTestSource('''
         import "b.dart" as x;
@@ -1504,7 +1504,7 @@
 
   Future<void> test_ClassDeclaration_body_final_var() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         class B { }''');
     addTestSource('''
         import "b.dart" as x;
@@ -1525,7 +1525,7 @@
 
   Future<void> test_Combinator_hide() async {
     // SimpleIdentifier  HideCombinator  ImportDirective
-    addSource('/home/test/lib/ab.dart', '''
+    addSource('$testPackageLibPath/ab.dart', '''
         library libAB;
         part 'partAB.dart';
         class A { }
@@ -1535,7 +1535,7 @@
         var T1;
         PB F1() => new PB();
         class PB { }''');
-    addSource('/home/test/lib/cd.dart', '''
+    addSource('$testPackageLibPath/cd.dart', '''
         class C { }
         class D { }''');
     addTestSource('''
@@ -1549,7 +1549,7 @@
 
   Future<void> test_Combinator_show() async {
     // SimpleIdentifier  HideCombinator  ImportDirective
-    addSource('/home/test/lib/ab.dart', '''
+    addSource('$testPackageLibPath/ab.dart', '''
         library libAB;
         part 'partAB.dart';
         class A { }
@@ -1561,7 +1561,7 @@
         typedef PB2 F2(int blat);
         class Clz = Object with Object;
         class PB { }''');
-    addSource('/home/test/lib/cd.dart', '''
+    addSource('$testPackageLibPath/cd.dart', '''
         class C { }
         class D { }''');
     addTestSource('''
@@ -1575,7 +1575,7 @@
 
   Future<void> test_ConditionalExpression_elseExpression() async {
     // SimpleIdentifier  ConditionalExpression  ReturnStatement
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         class A {int x;}''');
@@ -1595,7 +1595,7 @@
 
   Future<void> test_ConditionalExpression_elseExpression_empty() async {
     // SimpleIdentifier  ConditionalExpression  ReturnStatement
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         class A {int x;}''');
@@ -1624,7 +1624,7 @@
 
   Future<void> test_ConditionalExpression_partial_thenExpression() async {
     // SimpleIdentifier  ConditionalExpression  ReturnStatement
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         class A {int x;}''');
@@ -1644,7 +1644,7 @@
 
   Future<void> test_ConditionalExpression_partial_thenExpression_empty() async {
     // SimpleIdentifier  ConditionalExpression  ReturnStatement
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         class A {int x;}''');
@@ -1673,7 +1673,7 @@
 
   Future<void> test_ConditionalExpression_thenExpression() async {
     // SimpleIdentifier  ConditionalExpression  ReturnStatement
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         class A {int x;}''');
@@ -1692,9 +1692,9 @@
   }
 
   Future<void> test_ConstructorName_importedClass() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  PrefixedIdentifier  NamedType  ConstructorName
     // InstanceCreationExpression
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         int T1;
         F1() { }
@@ -1717,9 +1717,9 @@
   }
 
   Future<void> test_ConstructorName_importedFactory() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  PrefixedIdentifier  NamedType  ConstructorName
     // InstanceCreationExpression
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         int T1;
         F1() { }
@@ -1742,7 +1742,7 @@
   }
 
   Future<void> test_ConstructorName_importedFactory2() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  PrefixedIdentifier  NamedType  ConstructorName
     // InstanceCreationExpression
     addTestSource('''
         void f() {new String.fr^omCharCodes([]);}''');
@@ -1760,7 +1760,7 @@
   }
 
   Future<void> test_ConstructorName_localClass() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  PrefixedIdentifier  NamedType  ConstructorName
     // InstanceCreationExpression
     addTestSource('''
         int T1;
@@ -1781,7 +1781,7 @@
   }
 
   Future<void> test_ConstructorName_localFactory() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  PrefixedIdentifier  NamedType  ConstructorName
     // InstanceCreationExpression
     addTestSource('''
         int T1;
@@ -1820,7 +1820,7 @@
   }
 
   Future<void> test_doc_class() async {
-    addSource('/home/test/lib/a.dart', r'''
+    addSource('$testPackageLibPath/a.dart', r'''
 library A;
 /// My class.
 /// Short description.
@@ -1842,7 +1842,7 @@
   }
 
   Future<void> test_doc_function() async {
-    resolveSource('/home/test/lib/a.dart', r'''
+    resolveSource('$testPackageLibPath/a.dart', r'''
 library A;
 /// My function.
 /// Short description.
@@ -1861,7 +1861,7 @@
   }
 
   Future<void> test_doc_function_c_style() async {
-    resolveSource('/home/test/lib/a.dart', r'''
+    resolveSource('$testPackageLibPath/a.dart', r'''
 library A;
 /**
  * My function.
@@ -1882,7 +1882,7 @@
   }
 
   Future<void> test_enum() async {
-    addSource('/home/test/lib/a.dart', 'library A; enum E { one, two }');
+    addSource('$testPackageLibPath/a.dart', 'library A; enum E { one, two }');
     addTestSource('import "a.dart"; void f() {^}');
     await computeSuggestions();
     assertSuggestEnum('E');
@@ -1891,8 +1891,8 @@
   }
 
   Future<void> test_enum_deprecated() async {
-    addSource(
-        '/home/test/lib/a.dart', 'library A; @deprecated enum E { one, two }');
+    addSource('$testPackageLibPath/a.dart',
+        'library A; @deprecated enum E { one, two }');
     addTestSource('import "a.dart"; void f() {^}');
     await computeSuggestions();
     // TODO(danrube) investigate why suggestion/element is not deprecated
@@ -1903,7 +1903,7 @@
   }
 
   Future<void> test_enum_filter() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 enum E { one, two }
 enum F { three, four }
 ''');
@@ -1929,7 +1929,7 @@
 
   Future<void> test_ExpressionStatement_identifier() async {
     // SimpleIdentifier  ExpressionStatement  Block
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
         _B F1() { }
         class A {int x;}
         class _B { }''');
@@ -1959,7 +1959,7 @@
 
   Future<void> test_ExpressionStatement_name() async {
     // ExpressionStatement  Block  BlockFunctionBody  MethodDeclaration
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         B T1;
         class B{}''');
     addTestSource('''
@@ -1971,7 +1971,7 @@
   }
 
   Future<void> test_ExtendsClause() async {
-    newFile('/home/test/lib/a.dart', content: 'class A {}');
+    newFile('$testPackageLibPath/a.dart', content: 'class A {}');
     addTestSource('''
 import 'a.dart';
 
@@ -1982,7 +1982,7 @@
   }
 
   Future<void> test_ExtensionDeclaration_extendedType() async {
-    newFile('/home/test/lib/a.dart', content: 'class A {}');
+    newFile('$testPackageLibPath/a.dart', content: 'class A {}');
     addTestSource('''
 import 'a.dart';
 
@@ -1994,7 +1994,7 @@
   }
 
   Future<void> test_ExtensionDeclaration_extendedType2() async {
-    newFile('/home/test/lib/a.dart', content: 'class A {}');
+    newFile('$testPackageLibPath/a.dart', content: 'class A {}');
     addTestSource('''
 import 'a.dart';
 
@@ -2006,7 +2006,7 @@
   }
 
   Future<void> test_ExtensionDeclaration_member() async {
-    newFile('/home/test/lib/a.dart', content: 'class A {}');
+    newFile('$testPackageLibPath/a.dart', content: 'class A {}');
     addTestSource('''
 import 'a.dart';
 
@@ -2019,7 +2019,7 @@
   Future<void> test_FieldDeclaration_name_typed() async {
     // SimpleIdentifier  VariableDeclaration  VariableDeclarationList
     // FieldDeclaration
-    addSource('/home/test/lib/a.dart', 'class A { }');
+    addSource('$testPackageLibPath/a.dart', 'class A { }');
     addTestSource('''
         import 'a.dart';
         class C {A ^}''');
@@ -2031,7 +2031,7 @@
   Future<void> test_FieldDeclaration_name_var() async {
     // SimpleIdentifier  VariableDeclaration  VariableDeclarationList
     // FieldDeclaration
-    addSource('/home/test/lib/a.dart', 'class A { }');
+    addSource('$testPackageLibPath/a.dart', 'class A { }');
     addTestSource('''
         import 'a.dart';
         class C {var ^}''');
@@ -2043,7 +2043,7 @@
   Future<void> test_FieldDeclaration_type() async {
     // SimpleIdentifier  VariableDeclaration  VariableDeclarationList
     // FieldDeclaration
-    addSource('/home/test/lib/a.dart', 'class A { }');
+    addSource('$testPackageLibPath/a.dart', 'class A { }');
     addTestSource('''
         import 'a.dart';
         class C {^ foo;) ''');
@@ -2056,7 +2056,7 @@
   Future<void> test_FieldDeclaration_type_after_comment1() async {
     // SimpleIdentifier  VariableDeclaration  VariableDeclarationList
     // FieldDeclaration
-    addSource('/home/test/lib/a.dart', 'class A { }');
+    addSource('$testPackageLibPath/a.dart', 'class A { }');
     addTestSource('''
         import 'a.dart';
         class C {
@@ -2072,7 +2072,7 @@
   Future<void> test_FieldDeclaration_type_after_comment2() async {
     // SimpleIdentifier  VariableDeclaration  VariableDeclarationList
     // FieldDeclaration
-    addSource('/home/test/lib/a.dart', 'class A { }');
+    addSource('$testPackageLibPath/a.dart', 'class A { }');
     addTestSource('''
         import 'a.dart';
         class C {
@@ -2088,7 +2088,7 @@
   Future<void> test_FieldDeclaration_type_after_comment3() async {
     // SimpleIdentifier  VariableDeclaration  VariableDeclarationList
     // FieldDeclaration
-    addSource('/home/test/lib/a.dart', 'class A { }');
+    addSource('$testPackageLibPath/a.dart', 'class A { }');
     addTestSource('''
         import 'a.dart';
         class C {
@@ -2104,7 +2104,7 @@
   Future<void> test_FieldDeclaration_type_without_semicolon() async {
     // SimpleIdentifier  VariableDeclaration  VariableDeclarationList
     // FieldDeclaration
-    addSource('/home/test/lib/a.dart', 'class A { }');
+    addSource('$testPackageLibPath/a.dart', 'class A { }');
     addTestSource('''
         import 'a.dart';
         class C {^ foo} ''');
@@ -2287,7 +2287,7 @@
   }
 
   Future<void> test_function_parameters_mixed_required_and_named() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 int m(x, {int y}) {}
 ''');
     addTestSource('''
@@ -2310,7 +2310,7 @@
   }
 
   Future<void> test_function_parameters_mixed_required_and_positional() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 void m(x, [int y]) {}
 ''');
     addTestSource('''
@@ -2333,7 +2333,7 @@
   }
 
   Future<void> test_function_parameters_named() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 void m({x, int y}) {}
 ''');
     addTestSource('''
@@ -2357,7 +2357,7 @@
 
   Future<void> test_function_parameters_nnbd_required() async {
     createAnalysisOptionsFile(experiments: [EnableString.non_nullable]);
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 void m(int? nullable, int nonNullable) {}
 ''');
     addTestSource('''
@@ -2380,7 +2380,7 @@
 
   Future<void> test_function_parameters_nnbd_required_into_legacy() async {
     createAnalysisOptionsFile(experiments: [EnableString.non_nullable]);
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 void m(int? nullable, int nonNullable) {}
 ''');
     addTestSource('''
@@ -2404,7 +2404,7 @@
 
   Future<void> test_function_parameters_nnbd_required_legacy() async {
     createAnalysisOptionsFile(experiments: [EnableString.non_nullable]);
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 // @dart = 2.8
 void m(int param) {}
 ''');
@@ -2425,7 +2425,7 @@
   }
 
   Future<void> test_function_parameters_none() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 void m() {}
 ''');
     addTestSource('''
@@ -2444,7 +2444,7 @@
   }
 
   Future<void> test_function_parameters_positional() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 void m([x, int y]) {}
 ''');
     addTestSource('''
@@ -2467,7 +2467,7 @@
   }
 
   Future<void> test_function_parameters_required() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 void m(x, int y) {}
 ''');
     addTestSource('''
@@ -2491,7 +2491,7 @@
 
   Future<void> test_FunctionDeclaration_returnType_afterComment() async {
     // ClassDeclaration  CompilationUnit
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -2522,7 +2522,7 @@
 
   Future<void> test_FunctionDeclaration_returnType_afterComment2() async {
     // FunctionDeclaration  ClassDeclaration  CompilationUnit
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -2553,7 +2553,7 @@
 
   Future<void> test_FunctionDeclaration_returnType_afterComment3() async {
     // FunctionDeclaration  ClassDeclaration  CompilationUnit
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -2600,7 +2600,7 @@
   }
 
   Future<void> test_functionTypeAlias_genericTypeAlias() async {
-    addSource('/home/test/lib/a.dart', r'''
+    addSource('$testPackageLibPath/a.dart', r'''
 typedef F = void Function();
 ''');
     addTestSource(r'''
@@ -2616,7 +2616,7 @@
   }
 
   Future<void> test_functionTypeAlias_old() async {
-    addSource('/home/test/lib/a.dart', r'''
+    addSource('$testPackageLibPath/a.dart', r'''
 typedef void F();
 ''');
     addTestSource(r'''
@@ -2697,7 +2697,7 @@
   }
 
   Future<void> test_implementsClause() async {
-    newFile('/home/test/lib/a.dart', content: 'class A {}');
+    newFile('$testPackageLibPath/a.dart', content: 'class A {}');
     addTestSource('''
 import 'a.dart';
 
@@ -2708,7 +2708,7 @@
   }
 
   Future<void> test_implicitCreation() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 class A {
   A.a1();
   A.a2();
@@ -2748,7 +2748,7 @@
 
   Future<void> test_IndexExpression() async {
     // ExpressionStatement  Block
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         class A {int x;}''');
@@ -2777,7 +2777,7 @@
 
   Future<void> test_IndexExpression2() async {
     // SimpleIdentifier IndexExpression ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         class A {int x;}''');
@@ -2796,7 +2796,7 @@
   }
 
   Future<void> test_InstanceCreationExpression() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 class A {foo(){var f; {var x;}}}
 class B {B(this.x, [String boo]) { } int x;}
 class C {C.bar({boo: 'hoo', int z: 0}) { } }''');
@@ -2850,7 +2850,7 @@
   }
 
   Future<void> test_InstanceCreationExpression_abstractClass() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 abstract class A {
   A();
   A.generative();
@@ -2873,7 +2873,7 @@
 
   Future<void>
       test_InstanceCreationExpression_abstractClass_implicitConstructor() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 abstract class A {}
 ''');
     addTestSource('''
@@ -2889,7 +2889,7 @@
   }
 
   Future<void> test_InstanceCreationExpression_filter() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 class A {}
 class B extends A {}
 class C implements A {}
@@ -2911,8 +2911,8 @@
   }
 
   Future<void> test_InstanceCreationExpression_imported() async {
-    // SimpleIdentifier  TypeName  ConstructorName  InstanceCreationExpression
-    addSource('/home/test/lib/a.dart', '''
+    // SimpleIdentifier  NamedType  ConstructorName  InstanceCreationExpression
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         class A {A(this.x) { } int x;}''');
@@ -2954,8 +2954,8 @@
   }
 
   Future<void> test_InstanceCreationExpression_unimported() async {
-    // SimpleIdentifier  TypeName  ConstructorName  InstanceCreationExpression
-    addSource('/home/test/lib/ab.dart', 'class Clip { }');
+    // SimpleIdentifier  NamedType  ConstructorName  InstanceCreationExpression
+    addSource('$testPackageLibPath/ab.dart', 'class Clip { }');
     addTestSource('class A {foo(){new C^}}');
 
     await computeSuggestions();
@@ -2979,7 +2979,7 @@
 
   Future<void> test_InterpolationExpression() async {
     // SimpleIdentifier  InterpolationExpression  StringInterpolation
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -3013,7 +3013,7 @@
 
   Future<void> test_InterpolationExpression_block() async {
     // SimpleIdentifier  InterpolationExpression  StringInterpolation
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -3087,8 +3087,8 @@
   }
 
   Future<void> test_IsExpression() async {
-    // SimpleIdentifier  TypeName  IsExpression  IfStatement
-    addSource('/home/test/lib/b.dart', '''
+    // SimpleIdentifier  NamedType  IsExpression  IfStatement
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         foo() { }
         class X {X.c(); X._d(); z() {}}''');
@@ -3127,7 +3127,7 @@
   }
 
   Future<void> test_IsExpression_type() async {
-    // SimpleIdentifier  TypeName  IsExpression  IfStatement
+    // SimpleIdentifier  NamedType  IsExpression  IfStatement
     addTestSource('''
         class A {int x; int y() => 0;}
         void f(){var a; if (a is ^)}''');
@@ -3142,7 +3142,7 @@
   }
 
   Future<void> test_IsExpression_type_partial() async {
-    // SimpleIdentifier  TypeName  IsExpression  IfStatement
+    // SimpleIdentifier  NamedType  IsExpression  IfStatement
     addTestSource('''
         class A {int x; int y() => 0;}
         void f(){var a; if (a is Obj^)}''');
@@ -3162,8 +3162,8 @@
     // suggesting types. We ought to do so because there's no reason to cast a
     // value to the type it already has.
 
-    // SimpleIdentifier  TypeName  IsExpression  IfStatement
-    addSource('/home/test/lib/b.dart', '''
+    // SimpleIdentifier  NamedType  IsExpression  IfStatement
+    addSource('$testPackageLibPath/b.dart', '''
         foo() { }
         class A {} class B extends A {} class C extends B {}
         class X {X.c(); X._d(); z() {}}''');
@@ -3189,8 +3189,8 @@
     // suggesting types. We ought to do so because there's no reason to cast a
     // value to the type it already has.
 
-    // SimpleIdentifier  TypeName  IsExpression  IfStatement
-    addSource('/home/test/lib/b.dart', '''
+    // SimpleIdentifier  NamedType  IsExpression  IfStatement
+    addSource('$testPackageLibPath/b.dart', '''
         foo() { }
         class A {} class B implements A {} class C implements B {}
         class X {X.c(); X._d(); z() {}}''');
@@ -3211,7 +3211,7 @@
   }
 
   Future<void> test_keyword() async {
-    resolveSource('/home/test/lib/b.dart', '''
+    resolveSource('$testPackageLibPath/b.dart', '''
         lib B;
         int newT1;
         int T1;
@@ -3272,7 +3272,7 @@
 
   Future<void> test_MapLiteralEntry() async {
     // MapLiteralEntry  MapLiteral  VariableDeclaration
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -3310,7 +3310,7 @@
 
   Future<void> test_MapLiteralEntry1() async {
     // MapLiteralEntry  MapLiteral  VariableDeclaration
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -3337,7 +3337,7 @@
 
   Future<void> test_MapLiteralEntry2() async {
     // SimpleIdentifier  MapLiteralEntry  MapLiteral  VariableDeclaration
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -3358,7 +3358,7 @@
   }
 
   Future<void> test_method_parameters_mixed_required_and_named() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 void m(x, {int y}) {}
 ''');
     addTestSource('''
@@ -3381,7 +3381,7 @@
   }
 
   Future<void> test_method_parameters_mixed_required_and_positional() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 void m(x, [int y]) {}
 ''');
     addTestSource('''
@@ -3404,7 +3404,7 @@
   }
 
   Future<void> test_method_parameters_named() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 void m({x, int y}) {}
 ''');
     addTestSource('''
@@ -3427,7 +3427,7 @@
   }
 
   Future<void> test_method_parameters_none() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 void m() {}
 ''');
     addTestSource('''
@@ -3446,7 +3446,7 @@
   }
 
   Future<void> test_method_parameters_positional() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 void m([x, int y]) {}
 ''');
     addTestSource('''
@@ -3469,7 +3469,7 @@
   }
 
   Future<void> test_method_parameters_required() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 void m(x, int y) {}
 ''');
     addTestSource('''
@@ -3505,7 +3505,7 @@
 
   Future<void> test_MethodDeclaration_body_static() async {
     // Block  BlockFunctionBody  MethodDeclaration
-    addSource('/home/test/lib/c.dart', '''
+    addSource('$testPackageLibPath/c.dart', '''
         class C {
           c1() {}
           var c2;
@@ -3591,7 +3591,7 @@
 
   Future<void> test_MethodDeclaration_returnType() async {
     // ClassDeclaration  CompilationUnit
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -3621,7 +3621,7 @@
 
   Future<void> test_MethodDeclaration_returnType_afterComment() async {
     // ClassDeclaration  CompilationUnit
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -3651,7 +3651,7 @@
 
   Future<void> test_MethodDeclaration_returnType_afterComment2() async {
     // MethodDeclaration  ClassDeclaration  CompilationUnit
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -3681,7 +3681,7 @@
 
   Future<void> test_MethodDeclaration_returnType_afterComment3() async {
     // MethodDeclaration  ClassDeclaration  CompilationUnit
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -3745,7 +3745,7 @@
   }
 
   Future<void> test_MethodTypeArgumentList() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 class A {}
 class B {}
 ''');
@@ -3786,7 +3786,7 @@
   }
 
   Future<void> test_mixin_ordering() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 class B {}
 class M1 {
   void m() {}
@@ -3820,7 +3820,7 @@
   }
 
   Future<void> test_no_parameters_field() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 int x;
 ''');
     addTestSource('''
@@ -3835,7 +3835,7 @@
   }
 
   Future<void> test_no_parameters_getter() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 int get x => null;
 ''');
     addTestSource('''
@@ -3850,7 +3850,7 @@
   }
 
   Future<void> test_no_parameters_setter() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 set x(int value) {};
 ''');
     addTestSource('''
@@ -3872,7 +3872,7 @@
   }
 
   Future<void> test_partFile_TypeName() async {
-    // SimpleIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  NamedType  ConstructorName
     addSource('$testPackageLibPath/b.dart', '''
         lib B;
         int T1;
@@ -3909,13 +3909,13 @@
   }
 
   Future<void> test_partFile_TypeName2() async {
-    // SimpleIdentifier  TypeName  ConstructorName
-    addSource('/home/test/lib/b.dart', '''
+    // SimpleIdentifier  NamedType  ConstructorName
+    addSource('$testPackageLibPath/b.dart', '''
         lib libB;
         int T1;
         F1() { }
         class X {X.c(); X._d(); z() {}}''');
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         part of libA;
         class B { }''');
     addTestSource('''
@@ -3945,7 +3945,7 @@
 
   Future<void> test_PrefixedIdentifier_class_const() async {
     // SimpleIdentifier PrefixedIdentifier ExpressionStatement Block
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         class I {
           static const scI = 'boo';
@@ -3992,7 +3992,7 @@
 
   Future<void> test_PrefixedIdentifier_class_imported() async {
     // SimpleIdentifier  PrefixedIdentifier  ExpressionStatement
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         class I {X get f => new A();get _g => new A();}
         class A implements I {
@@ -4071,7 +4071,7 @@
 
   Future<void> test_PrefixedIdentifier_library() async {
     // SimpleIdentifier  PrefixedIdentifier  ExpressionStatement
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         var T1;
         class X { }
@@ -4097,8 +4097,8 @@
   }
 
   Future<void> test_PrefixedIdentifier_library_typesOnly() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName
-    addSource('/home/test/lib/b.dart', '''
+    // SimpleIdentifier  PrefixedIdentifier  NamedType
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         var T1;
         class X { }
@@ -4124,8 +4124,8 @@
   }
 
   Future<void> test_PrefixedIdentifier_library_typesOnly2() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName
-    addSource('/home/test/lib/b.dart', '''
+    // SimpleIdentifier  PrefixedIdentifier  NamedType
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         var T1;
         class X { }
@@ -4152,7 +4152,7 @@
 
   Future<void> test_PrefixedIdentifier_parameter() async {
     // SimpleIdentifier  PrefixedIdentifier  ExpressionStatement
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         class _W {M y; var _z;}
         class X extends _W {}
@@ -4171,7 +4171,7 @@
 
   Future<void> test_PrefixedIdentifier_prefix() async {
     // SimpleIdentifier  PrefixedIdentifier  ExpressionStatement
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         class A {static int bar = 10;}
         _B() {}''');
     addTestSource('''
@@ -4317,7 +4317,7 @@
 
   Future<void> test_PropertyAccess_noTarget() async {
     // SimpleIdentifier  PropertyAccess  ExpressionStatement
-    addSource('/home/test/lib/ab.dart', 'class Foo { }');
+    addSource('$testPackageLibPath/ab.dart', 'class Foo { }');
     addTestSource('class C {foo(){.^}}');
 
     await computeSuggestions();
@@ -4326,7 +4326,7 @@
 
   Future<void> test_PropertyAccess_noTarget2() async {
     // SimpleIdentifier  PropertyAccess  ExpressionStatement
-    addSource('/home/test/lib/ab.dart', 'class Foo { }');
+    addSource('$testPackageLibPath/ab.dart', 'class Foo { }');
     addTestSource('void f() {.^}');
 
     await computeSuggestions();
@@ -4598,7 +4598,7 @@
   Future<void> test_TopLevelVariableDeclaration_type() async {
     // SimpleIdentifier  VariableDeclaration  VariableDeclarationList
     // TopLevelVariableDeclaration
-    addSource('/home/test/lib/a.dart', 'class A { }');
+    addSource('$testPackageLibPath/a.dart', 'class A { }');
     addTestSource('''
         import 'a.dart';
         ^ foo; ''');
@@ -4611,7 +4611,7 @@
   Future<void> test_TopLevelVariableDeclaration_type_after_comment1() async {
     // SimpleIdentifier  VariableDeclaration  VariableDeclarationList
     // TopLevelVariableDeclaration
-    addSource('/home/test/lib/a.dart', 'class A { }');
+    addSource('$testPackageLibPath/a.dart', 'class A { }');
     addTestSource('''
         import 'a.dart';
         // comment
@@ -4625,7 +4625,7 @@
   Future<void> test_TopLevelVariableDeclaration_type_after_comment2() async {
     // SimpleIdentifier  VariableDeclaration  VariableDeclarationList
     // TopLevelVariableDeclaration
-    addSource('/home/test/lib/a.dart', 'class A { }');
+    addSource('$testPackageLibPath/a.dart', 'class A { }');
     addTestSource('''
         import 'a.dart';
         /* comment */
@@ -4639,7 +4639,7 @@
   Future<void> test_TopLevelVariableDeclaration_type_after_comment3() async {
     // SimpleIdentifier  VariableDeclaration  VariableDeclarationList
     // TopLevelVariableDeclaration
-    addSource('/home/test/lib/a.dart', 'class A { }');
+    addSource('$testPackageLibPath/a.dart', 'class A { }');
     addTestSource('''
         import 'a.dart';
         /// some dartdoc
@@ -4653,7 +4653,7 @@
   Future<void> test_TopLevelVariableDeclaration_type_without_semicolon() async {
     // SimpleIdentifier  VariableDeclaration  VariableDeclarationList
     // TopLevelVariableDeclaration
-    addSource('/home/test/lib/a.dart', 'class A { }');
+    addSource('$testPackageLibPath/a.dart', 'class A { }');
     addTestSource('''
         import 'a.dart';
         ^ foo ''');
@@ -4730,7 +4730,7 @@
 
   Future<void> test_TypeArgumentList() async {
     // SimpleIdentifier  BinaryExpression  ExpressionStatement
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
         class C1 {int x;}
         F1() => 0;
         typedef String T1(int blat);''');
@@ -4756,8 +4756,8 @@
   }
 
   Future<void> test_TypeArgumentList2() async {
-    // TypeName  TypeArgumentList  TypeName
-    addSource('/home/test/lib/a.dart', '''
+    // NamedType  TypeArgumentList  NamedType
+    addSource('$testPackageLibPath/a.dart', '''
         class C1 {int x;}
         F1() => 0;
         typedef String T1(int blat);''');
@@ -4795,10 +4795,10 @@
   }
 
   Future<void> test_TypeArgumentList_recursive() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 class A {}
 ''');
-    resolveSource('/home/test/lib/b.dart', '''
+    resolveSource('$testPackageLibPath/b.dart', '''
 export 'a.dart';
 export 'b.dart';
 class B {}
@@ -4817,7 +4817,7 @@
   Future<void> test_VariableDeclaration_name() async {
     // SimpleIdentifier  VariableDeclaration  VariableDeclarationList
     // VariableDeclarationStatement  Block
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         foo() { }
         class _B { }
@@ -4844,7 +4844,7 @@
   Future<void> test_VariableDeclarationStatement_RHS() async {
     // SimpleIdentifier  VariableDeclaration  VariableDeclarationList
     // VariableDeclarationStatement
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         foo() { }
         class _B { }
@@ -4869,7 +4869,7 @@
   Future<void> test_VariableDeclarationStatement_RHS_missing_semicolon() async {
     // VariableDeclaration  VariableDeclarationList
     // VariableDeclarationStatement
-    resolveSource('/home/test/lib/b.dart', '''
+    resolveSource('$testPackageLibPath/b.dart', '''
         lib B;
         foo1() { }
         void bar1() { }
@@ -4898,7 +4898,7 @@
   }
 
   Future<void> test_withClause_mixin() async {
-    newFile('/home/test/lib/a.dart', content: 'mixin M {}');
+    newFile('$testPackageLibPath/a.dart', content: 'mixin M {}');
     addTestSource('''
 import 'a.dart';
 
diff --git a/pkg/analysis_server/test/services/completion/dart/library_member_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/library_member_contributor_test.dart
index 5c1db88..d9dc05e 100644
--- a/pkg/analysis_server/test/services/completion/dart/library_member_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/library_member_contributor_test.dart
@@ -29,7 +29,7 @@
 
   Future<void> test_extension() async {
     // SimpleIdentifier  PrefixedIdentifier  ExpressionStatement
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 extension MyExt on int {}
 ''');
     addTestSource('''
@@ -134,7 +134,7 @@
 
   Future<void> test_PrefixedIdentifier_library() async {
     // SimpleIdentifier  PrefixedIdentifier  ExpressionStatement
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         var T1;
         class X { }
@@ -158,11 +158,11 @@
   }
 
   Future<void> test_PrefixedIdentifier_library_export_withShow() async {
-    addSource('/home/test/lib/a.dart', r'''
+    addSource('$testPackageLibPath/a.dart', r'''
 class A {}
 class B {}
 ''');
-    addSource('/home/test/lib/b.dart', r'''
+    addSource('$testPackageLibPath/b.dart', r'''
 export 'a.dart' show A;
 ''');
     addTestSource(r'''
@@ -177,7 +177,7 @@
   }
 
   Future<void> test_PrefixedIdentifier_library_import_withShow() async {
-    addSource('/home/test/lib/a.dart', r'''
+    addSource('$testPackageLibPath/a.dart', r'''
 class A {}
 class B {}
 ''');
@@ -224,7 +224,7 @@
   }
 
   Future<void> test_PrefixedIdentifier_library_typesOnly() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName
+    // SimpleIdentifier  PrefixedIdentifier  NamedType
     newFile('$testPackageLibPath/b.dart', content: '''
         lib B;
         var T1;
@@ -257,7 +257,7 @@
   }
 
   Future<void> test_PrefixedIdentifier_library_typesOnly2() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName
+    // SimpleIdentifier  PrefixedIdentifier  NamedType
     newFile('$testPackageLibPath/b.dart', content: '''
         lib B;
         var T1;
diff --git a/pkg/analysis_server/test/services/completion/dart/library_prefix_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/library_prefix_contributor_test.dart
index aa2e6a2..34904db 100644
--- a/pkg/analysis_server/test/services/completion/dart/library_prefix_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/library_prefix_contributor_test.dart
@@ -45,21 +45,21 @@
 
   Future<void> test_Block() async {
     // Block  BlockFunctionBody  MethodDeclaration
-    addSource('/home/test/lib/ab.dart', '''
+    addSource('$testPackageLibPath/ab.dart', '''
 export "dart:math" hide max;
 class A {int x;}
 @deprecated D1() {int x;}
 class _B {boo() { partBoo() {}} }''');
-    addSource('/home/test/lib/cd.dart', '''
+    addSource('$testPackageLibPath/cd.dart', '''
 String T1;
 var _T2;
 class C { }
 class D { }''');
-    addSource('/home/test/lib/eef.dart', '''
+    addSource('$testPackageLibPath/eef.dart', '''
 class EE { }
 class F { }''');
-    addSource('/home/test/lib/g.dart', 'class G { }');
-    addSource('/home/test/lib/h.dart', '''
+    addSource('$testPackageLibPath/g.dart', 'class G { }');
+    addSource('$testPackageLibPath/h.dart', '''
 class H { }
 int T3;
 var _T4;'''); // not imported
@@ -186,7 +186,7 @@
 
   Future<void> test_ClassDeclaration_body() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 class B { }''');
     addTestSource('''
 import "b.dart" as x;
@@ -201,7 +201,7 @@
 
   Future<void> test_ClassDeclaration_body_final() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 class B { }''');
     addTestSource('''
 import "b.dart" as x;
@@ -216,7 +216,7 @@
 
   Future<void> test_ClassDeclaration_body_final_field() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 class B { }''');
     addTestSource('''
 import "b.dart" as x;
@@ -231,7 +231,7 @@
 
   Future<void> test_ClassDeclaration_body_final_field2() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 class B { }''');
     addTestSource('''
 import "b.dart" as Soo;
@@ -246,7 +246,7 @@
 
   Future<void> test_ClassDeclaration_body_final_final() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 class B { }''');
     addTestSource('''
 import "b.dart" as x;
@@ -261,7 +261,7 @@
 
   Future<void> test_ClassDeclaration_body_final_var() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 class B { }''');
     addTestSource('''
 import "b.dart" as x;
@@ -275,7 +275,7 @@
   }
 
   Future<void> test_InstanceCreationExpression() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 class A {foo(){var f; {var x;}}}
 class B {B(this.x, [String boo]) { } int x;}
 class C {C.bar({boo: 'hoo', int z: 0}) { } }''');
@@ -294,11 +294,11 @@
   }
 
   Future<void> test_InstanceCreationExpression_inPart() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 class A {foo(){var f; {var x;}}}
 class B {B(this.x, [String boo]) { } int x;}
 class C {C.bar({boo: 'hoo', int z: 0}) { } }''');
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 library testB;
 import "a.dart" as t;
 import "dart:math" as math;
@@ -313,11 +313,11 @@
   }
 
   Future<void> test_InstanceCreationExpression_inPart_detached() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 class A {foo(){var f; {var x;}}}
 class B {B(this.x, [String boo]) { } int x;}
 class C {C.bar({boo: 'hoo', int z: 0}) { } }''');
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 library testB;
 import "a.dart" as t;
 import "dart:math" as math;
diff --git a/pkg/analysis_server/test/services/completion/dart/local_library_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/local_library_contributor_test.dart
index 3a6fa56..52c6b90 100644
--- a/pkg/analysis_server/test/services/completion/dart/local_library_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/local_library_contributor_test.dart
@@ -28,7 +28,7 @@
   }
 
   Future<void> test_partFile_Constructor() async {
-    // SimpleIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  NamedType  ConstructorName
     newFile('$testPackageLibPath/b.dart', content: '''
         lib B;
         int T1;
@@ -63,7 +63,7 @@
   }
 
   Future<void> test_partFile_Constructor2() async {
-    // SimpleIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  NamedType  ConstructorName
     newFile('$testPackageLibPath/b.dart', content: '''
         lib B;
         int T1;
diff --git a/pkg/analysis_server/test/services/completion/dart/local_reference_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/local_reference_contributor_test.dart
index 6e7253d..804bc3a 100644
--- a/pkg/analysis_server/test/services/completion/dart/local_reference_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/local_reference_contributor_test.dart
@@ -81,7 +81,7 @@
 
   Future<void> test_ArgDefaults_inherited_method_with_required_named() async {
     writeTestPackageConfig(meta: true);
-    resolveSource('/home/test/lib/b.dart', '''
+    resolveSource('$testPackageLibPath/b.dart', '''
 import 'package:meta/meta.dart';
 
 lib libB;
@@ -120,7 +120,7 @@
 
   Future<void> test_ArgumentList() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 library A;
 bool hasLength(int expected) { }
 void baz() { }''');
@@ -145,7 +145,7 @@
 
   Future<void> test_ArgumentList_imported_function() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 library A;
 bool hasLength(int expected) { }
 expect(arg) { }
@@ -172,7 +172,7 @@
   Future<void>
       test_ArgumentList_InstanceCreationExpression_functionalArg() async {
     // ArgumentList  InstanceCreationExpression  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 library A;
 class A { A(f()) { } }
 bool hasLength(int expected) { }
@@ -201,7 +201,7 @@
 
   Future<void> test_ArgumentList_InstanceCreationExpression_typedefArg() async {
     // ArgumentList  InstanceCreationExpression  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 library A;
 typedef Funct();
 class A { A(Funct f) { } }
@@ -231,7 +231,7 @@
 
   Future<void> test_ArgumentList_local_function() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 library A;
 bool hasLength(int expected) { }
 void baz() { }''');
@@ -257,7 +257,7 @@
 
   Future<void> test_ArgumentList_local_method() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 library A;
 bool hasLength(int expected) { }
 void baz() { }''');
@@ -283,7 +283,7 @@
 
   Future<void> test_ArgumentList_MethodInvocation_functionalArg() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 library A;
 class A { A(f()) { } }
 bool hasLength(int expected) { }
@@ -314,7 +314,7 @@
 
   Future<void> test_ArgumentList_MethodInvocation_functionalArg2() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 library A;
 class A { A(f()) { } }
 bool hasLength(int expected) { }
@@ -350,7 +350,7 @@
 
   Future<void> test_ArgumentList_MethodInvocation_methodArg() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 library A;
 class A { A(f()) { } }
 bool hasLength(int expected) { }
@@ -375,7 +375,7 @@
   }
 
   Future<void> test_ArgumentList_namedFieldParam_tear_off() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 typedef void VoidCallback();
 
 class Button {
@@ -406,7 +406,7 @@
   Future<void> test_ArgumentList_namedParam() async {
     // SimpleIdentifier  NamedExpression  ArgumentList  MethodInvocation
     // ExpressionStatement
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 library A;
 bool hasLength(int expected) { }''');
     addTestSource('''
@@ -452,7 +452,7 @@
   }
 
   Future<void> test_ArgumentList_namedParam_tear_off() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 typedef void VoidCallback();
 
 class Button {
@@ -480,7 +480,7 @@
   }
 
   Future<void> test_ArgumentList_namedParam_tear_off_1() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 typedef void VoidCallback();
 
 class Button {
@@ -508,7 +508,7 @@
   }
 
   Future<void> test_ArgumentList_namedParam_tear_off_2() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 typedef void VoidCallback();
 
 class Button {
@@ -536,7 +536,7 @@
   }
 
   Future<void> test_AsExpression_type() async {
-    // SimpleIdentifier  TypeName  AsExpression
+    // SimpleIdentifier  NamedType  AsExpression
     addTestSource('''
         class A {var b; X _c; foo() {var a; (a as ^).foo();}''');
     await computeSuggestions();
@@ -556,7 +556,7 @@
     // suggesting types. We ought to do so because there's no reason to cast a
     // value to the type it already has.
 
-    // SimpleIdentifier  TypeName  AsExpression
+    // SimpleIdentifier  NamedType  AsExpression
     addTestSource('''
 class A {} class B extends A {} class C extends A {} class D {}
 f(A a){ (a as ^) }''');
@@ -577,7 +577,7 @@
     // suggesting types. We ought to do so because there's no reason to cast a
     // value to the type it already has.
 
-    // SimpleIdentifier  TypeName  AsExpression
+    // SimpleIdentifier  NamedType  AsExpression
     addTestSource('''
 class A {} class B implements A {} class C implements A {} class D {}
 f(A a){ (a as ^) }''');
@@ -593,7 +593,7 @@
   }
 
   Future<void> test_AsExpression_type_filter_undefined_type() async {
-    // SimpleIdentifier  TypeName  AsExpression
+    // SimpleIdentifier  NamedType  AsExpression
     addTestSource('''
 class A {}
 f(U u){ (u as ^) }''');
@@ -628,7 +628,7 @@
   }
 
   Future<void> test_AssignmentExpression_type() async {
-    // SimpleIdentifier  TypeName  VariableDeclarationList
+    // SimpleIdentifier  NamedType  VariableDeclarationList
     // VariableDeclarationStatement  Block
     addTestSource('''
 class A {} void f() {
@@ -652,7 +652,7 @@
   }
 
   Future<void> test_AssignmentExpression_type_newline() async {
-    // SimpleIdentifier  TypeName  VariableDeclarationList
+    // SimpleIdentifier  NamedType  VariableDeclarationList
     // VariableDeclarationStatement  Block
     addTestSource('''
 class A {} void f() {
@@ -675,7 +675,7 @@
   }
 
   Future<void> test_AssignmentExpression_type_partial() async {
-    // SimpleIdentifier  TypeName  VariableDeclarationList
+    // SimpleIdentifier  NamedType  VariableDeclarationList
     // VariableDeclarationStatement  Block
     addTestSource('''
 class A {} void f() {
@@ -699,7 +699,7 @@
   }
 
   Future<void> test_AssignmentExpression_type_partial_newline() async {
-    // SimpleIdentifier  TypeName  VariableDeclarationList
+    // SimpleIdentifier  NamedType  VariableDeclarationList
     // VariableDeclarationStatement  Block
     addTestSource('''
 class A {} void f() {
@@ -755,7 +755,7 @@
 
   Future<void> test_AwaitExpression_inherited() async {
     // SimpleIdentifier  AwaitExpression  ExpressionStatement
-    resolveSource('/home/test/lib/b.dart', '''
+    resolveSource('$testPackageLibPath/b.dart', '''
 lib libB;
 class A {
   Future y() async {return 0;}
@@ -812,21 +812,21 @@
 
   Future<void> test_Block() async {
     // Block  BlockFunctionBody  MethodDeclaration
-    addSource('/home/test/lib/ab.dart', '''
+    addSource('$testPackageLibPath/ab.dart', '''
 export "dart:math" hide max;
 class A {int x;}
 @deprecated D1() {int x;}
 class _B {boo() { partBoo() {}} }''');
-    addSource('/home/test/lib/cd.dart', '''
+    addSource('$testPackageLibPath/cd.dart', '''
 String T1;
 var _T2;
 class C { }
 class D { }''');
-    addSource('/home/test/lib/eef.dart', '''
+    addSource('$testPackageLibPath/eef.dart', '''
 class EE { }
 class F { }''');
-    addSource('/home/test/lib/g.dart', 'class G { }');
-    addSource('/home/test/lib/h.dart', '''
+    addSource('$testPackageLibPath/g.dart', 'class G { }');
+    addSource('$testPackageLibPath/h.dart', '''
 class H { }
 int T3;
 var _T4;'''); // not imported
@@ -905,21 +905,21 @@
 
   Future<void> test_Block_final() async {
     // Block  BlockFunctionBody  MethodDeclaration
-    addSource('/home/test/lib/ab.dart', '''
+    addSource('$testPackageLibPath/ab.dart', '''
 export "dart:math" hide max;
 class A {int x;}
 @deprecated D1() {int x;}
 class _B {boo() { partBoo() {}} }''');
-    addSource('/home/test/lib/cd.dart', '''
+    addSource('$testPackageLibPath/cd.dart', '''
 String T1;
 var _T2;
 class C { }
 class D { }''');
-    addSource('/home/test/lib/eef.dart', '''
+    addSource('$testPackageLibPath/eef.dart', '''
 class EE { }
 class F { }''');
-    addSource('/home/test/lib/g.dart', 'class G { }');
-    addSource('/home/test/lib/h.dart', '''
+    addSource('$testPackageLibPath/g.dart', 'class G { }');
+    addSource('$testPackageLibPath/h.dart', '''
 class H { }
 int T3;
 var _T4;'''); // not imported
@@ -1018,21 +1018,21 @@
 
   Future<void> test_Block_final_final() async {
     // Block  BlockFunctionBody  MethodDeclaration
-    addSource('/home/test/lib/ab.dart', '''
+    addSource('$testPackageLibPath/ab.dart', '''
 export "dart:math" hide max;
 class A {int x;}
 @deprecated D1() {int x;}
 class _B {boo() { partBoo() {}} }''');
-    addSource('/home/test/lib/cd.dart', '''
+    addSource('$testPackageLibPath/cd.dart', '''
 String T1;
 var _T2;
 class C { }
 class D { }''');
-    addSource('/home/test/lib/eef.dart', '''
+    addSource('$testPackageLibPath/eef.dart', '''
 class EE { }
 class F { }''');
-    addSource('/home/test/lib/g.dart', 'class G { }');
-    addSource('/home/test/lib/h.dart', '''
+    addSource('$testPackageLibPath/g.dart', 'class G { }');
+    addSource('$testPackageLibPath/h.dart', '''
 class H { }
 int T3;
 var _T4;'''); // not imported
@@ -1117,21 +1117,21 @@
 
   Future<void> test_Block_final_var() async {
     // Block  BlockFunctionBody  MethodDeclaration
-    addSource('/home/test/lib/ab.dart', '''
+    addSource('$testPackageLibPath/ab.dart', '''
 export "dart:math" hide max;
 class A {int x;}
 @deprecated D1() {int x;}
 class _B {boo() { partBoo() {}} }''');
-    addSource('/home/test/lib/cd.dart', '''
+    addSource('$testPackageLibPath/cd.dart', '''
 String T1;
 var _T2;
 class C { }
 class D { }''');
-    addSource('/home/test/lib/eef.dart', '''
+    addSource('$testPackageLibPath/eef.dart', '''
 class EE { }
 class F { }''');
-    addSource('/home/test/lib/g.dart', 'class G { }');
-    addSource('/home/test/lib/h.dart', '''
+    addSource('$testPackageLibPath/g.dart', 'class G { }');
+    addSource('$testPackageLibPath/h.dart', '''
 class H { }
 int T3;
 var _T4;'''); // not imported
@@ -1215,21 +1215,21 @@
   }
 
   Future<void> test_Block_identifier_partial() async {
-    addSource('/home/test/lib/ab.dart', '''
+    addSource('$testPackageLibPath/ab.dart', '''
 export "dart:math" hide max;
 class A {int x;}
 @deprecated D1() {int x;}
 class _B { }''');
-    addSource('/home/test/lib/cd.dart', '''
+    addSource('$testPackageLibPath/cd.dart', '''
 String T1;
 var _T2;
 class C { }
 class D { }''');
-    addSource('/home/test/lib/eef.dart', '''
+    addSource('$testPackageLibPath/eef.dart', '''
 class EE { }
 class F { }''');
-    addSource('/home/test/lib/g.dart', 'class G { }');
-    addSource('/home/test/lib/h.dart', '''
+    addSource('$testPackageLibPath/g.dart', 'class G { }');
+    addSource('$testPackageLibPath/h.dart', '''
 class H { }
 class D3 { }
 int T3;
@@ -1294,7 +1294,7 @@
 
   Future<void> test_Block_inherited_imported() async {
     // Block  BlockFunctionBody  MethodDeclaration  ClassDeclaration
-    resolveSource('/home/test/lib/b.dart', '''
+    resolveSource('$testPackageLibPath/b.dart', '''
 lib B;
 class F { var f1; f2() { } get f3 => 0; set f4(fx) { } var _pf; }
 class E extends F { var e1; e2() { } }
@@ -1322,7 +1322,7 @@
 
   Future<void> test_Block_inherited_imported_from_constructor() async {
     // Block  BlockFunctionBody  ConstructorDeclaration  ClassDeclaration
-    resolveSource('/home/test/lib/b.dart', '''
+    resolveSource('$testPackageLibPath/b.dart', '''
       lib B;
       class F { var f1; f2() { } get f3 => 0; set f4(fx) { } var _pf; }
       class E extends F { var e1; e2() { } }
@@ -1349,7 +1349,7 @@
 
   Future<void> test_Block_inherited_imported_from_method() async {
     // Block  BlockFunctionBody  MethodDeclaration  ClassDeclaration
-    resolveSource('/home/test/lib/b.dart', '''
+    resolveSource('$testPackageLibPath/b.dart', '''
       lib B;
       class F { var f1; f2() { } get f3 => 0; set f4(fx) { } var _pf; }
       class E extends F { var e1; e2() { } }
@@ -1448,21 +1448,21 @@
   }
 
   Future<void> test_Block_local_function() async {
-    addSource('/home/test/lib/ab.dart', '''
+    addSource('$testPackageLibPath/ab.dart', '''
 export "dart:math" hide max;
 class A {int x;}
 @deprecated D1() {int x;}
 class _B {boo() { partBoo() {}} }''');
-    addSource('/home/test/lib/cd.dart', '''
+    addSource('$testPackageLibPath/cd.dart', '''
 String T1;
 var _T2;
 class C { }
 class D { }''');
-    addSource('/home/test/lib/eef.dart', '''
+    addSource('$testPackageLibPath/eef.dart', '''
 class EE { }
 class F { }''');
-    addSource('/home/test/lib/g.dart', 'class G { }');
-    addSource('/home/test/lib/h.dart', '''
+    addSource('$testPackageLibPath/g.dart', 'class G { }');
+    addSource('$testPackageLibPath/h.dart', '''
 class H { }
 int T3;
 var _T4;'''); // not imported
@@ -1526,7 +1526,7 @@
 
   Future<void> test_CascadeExpression_selector1() async {
     // PropertyAccess  CascadeExpression  ExpressionStatement  Block
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 class B { }''');
     addTestSource('''
 import "b.dart";
@@ -1551,7 +1551,7 @@
 
   Future<void> test_CascadeExpression_selector2() async {
     // SimpleIdentifier  PropertyAccess  CascadeExpression  ExpressionStatement
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 class B { }''');
     addTestSource('''
 import "b.dart";
@@ -1574,7 +1574,7 @@
 
   Future<void> test_CascadeExpression_selector2_withTrailingReturn() async {
     // PropertyAccess  CascadeExpression  ExpressionStatement  Block
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 class B { }''');
     addTestSource('''
 import "b.dart";
@@ -1616,7 +1616,7 @@
   }
 
   Future<void> test_CatchClause_onType() async {
-    // TypeName  CatchClause  TryStatement
+    // NamedType  CatchClause  TryStatement
     addTestSource('class A {a() {try{var x;} on ^ {}}}');
     await computeSuggestions();
 
@@ -1629,7 +1629,7 @@
   }
 
   Future<void> test_CatchClause_onType_noBrackets() async {
-    // TypeName  CatchClause  TryStatement
+    // NamedType  CatchClause  TryStatement
     addTestSource('class A {a() {try{var x;} on ^}}');
     await computeSuggestions();
 
@@ -1680,7 +1680,7 @@
 
   Future<void> test_ClassDeclaration_body() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 class B { }''');
     addTestSource('''
 import "b.dart" as x;
@@ -1709,7 +1709,7 @@
 
   Future<void> test_ClassDeclaration_body_final() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 class B { }''');
     addTestSource('''
 import "b.dart" as x;
@@ -1730,7 +1730,7 @@
 
   Future<void> test_ClassDeclaration_body_final_field() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 class B { }''');
     addTestSource('''
 import "b.dart" as x;
@@ -1751,7 +1751,7 @@
 
   Future<void> test_ClassDeclaration_body_final_field2() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 class B { }''');
     addTestSource('''
 import "b.dart" as Soo;
@@ -1772,7 +1772,7 @@
 
   Future<void> test_ClassDeclaration_body_final_final() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 class B { }''');
     addTestSource('''
 import "b.dart" as x;
@@ -1793,7 +1793,7 @@
 
   Future<void> test_ClassDeclaration_body_final_var() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 class B { }''');
     addTestSource('''
 import "b.dart" as x;
@@ -1839,7 +1839,7 @@
 
   Future<void> test_Combinator_hide() async {
     // SimpleIdentifier  HideCombinator  ImportDirective
-    addSource('/home/test/lib/ab.dart', '''
+    addSource('$testPackageLibPath/ab.dart', '''
 library libAB;
 part 'partAB.dart';
 class A { }
@@ -1849,7 +1849,7 @@
 var T1;
 PB F1() => new PB();
 class PB { }''');
-    addSource('/home/test/lib/cd.dart', '''
+    addSource('$testPackageLibPath/cd.dart', '''
 class C { }
 class D { }''');
     addTestSource('''
@@ -1863,7 +1863,7 @@
 
   Future<void> test_Combinator_show() async {
     // SimpleIdentifier  HideCombinator  ImportDirective
-    addSource('/home/test/lib/ab.dart', '''
+    addSource('$testPackageLibPath/ab.dart', '''
 library libAB;
 part 'partAB.dart';
 class A { }
@@ -1875,7 +1875,7 @@
 typedef PB2 F2(int blat);
 class Clz = Object with Object;
 class PB { }''');
-    addSource('/home/test/lib/cd.dart', '''
+    addSource('$testPackageLibPath/cd.dart', '''
 class C { }
 class D { }''');
     addTestSource('''
@@ -1889,7 +1889,7 @@
 
   Future<void> test_ConditionalExpression_elseExpression() async {
     // SimpleIdentifier  ConditionalExpression  ReturnStatement
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 int T1;
 F1() { }
 class A {int x;}''');
@@ -1909,7 +1909,7 @@
 
   Future<void> test_ConditionalExpression_elseExpression_empty() async {
     // SimpleIdentifier  ConditionalExpression  ReturnStatement
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 int T1;
 F1() { }
 class A {int x;}''');
@@ -1935,7 +1935,7 @@
 
   Future<void> test_ConditionalExpression_partial_thenExpression() async {
     // SimpleIdentifier  ConditionalExpression  ReturnStatement
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 int T1;
 F1() { }
 class A {int x;}''');
@@ -1955,7 +1955,7 @@
 
   Future<void> test_ConditionalExpression_partial_thenExpression_empty() async {
     // SimpleIdentifier  ConditionalExpression  ReturnStatement
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 int T1;
 F1() { }
 class A {int x;}''');
@@ -1981,7 +1981,7 @@
 
   Future<void> test_ConditionalExpression_thenExpression() async {
     // SimpleIdentifier  ConditionalExpression  ReturnStatement
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 int T1;
 F1() { }
 class A {int x;}''');
@@ -2066,9 +2066,9 @@
   }
 
   Future<void> test_ConstructorName_importedClass() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  PrefixedIdentifier  NamedType  ConstructorName
     // InstanceCreationExpression
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 lib B;
 int T1;
 F1() { }
@@ -2091,9 +2091,9 @@
   }
 
   Future<void> test_ConstructorName_importedFactory() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  PrefixedIdentifier  NamedType  ConstructorName
     // InstanceCreationExpression
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 lib B;
 int T1;
 F1() { }
@@ -2116,7 +2116,7 @@
   }
 
   Future<void> test_ConstructorName_importedFactory2() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  PrefixedIdentifier  NamedType  ConstructorName
     // InstanceCreationExpression
     addTestSource('''
         void f() {new String.fr^omCharCodes([]);}''');
@@ -2134,7 +2134,7 @@
   }
 
   Future<void> test_ConstructorName_localClass() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  PrefixedIdentifier  NamedType  ConstructorName
     // InstanceCreationExpression
     addTestSource('''
 int T1;
@@ -2155,7 +2155,7 @@
   }
 
   Future<void> test_ConstructorName_localFactory() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  PrefixedIdentifier  NamedType  ConstructorName
     // InstanceCreationExpression
     addTestSource('''
 int T1;
@@ -2572,7 +2572,7 @@
 
   Future<void> test_ExpressionStatement_identifier() async {
     // SimpleIdentifier  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 _B F1() { }
 class A {int x;}
 class _B { }''');
@@ -2600,7 +2600,7 @@
 
   Future<void> test_ExpressionStatement_name() async {
     // ExpressionStatement  Block  BlockFunctionBody  MethodDeclaration
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         B T1;
         class B{}''');
     addTestSource('''
@@ -2670,7 +2670,7 @@
 
   Future<void> test_extensionDeclaration_notInBody() async {
     // ExtensionDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 class B { }''');
     addTestSource('''
 import "b.dart" as x;
@@ -2723,7 +2723,7 @@
   Future<void> test_FieldDeclaration_name_typed() async {
     // SimpleIdentifier  VariableDeclaration  VariableDeclarationList
     // FieldDeclaration
-    addSource('/home/test/lib/a.dart', 'class A { }');
+    addSource('$testPackageLibPath/a.dart', 'class A { }');
     addTestSource('''
         import "a.dart";
         class C {A ^}''');
@@ -2735,7 +2735,7 @@
   Future<void> test_FieldDeclaration_name_var() async {
     // SimpleIdentifier  VariableDeclaration  VariableDeclarationList
     // FieldDeclaration
-    addSource('/home/test/lib/a.dart', 'class A { }');
+    addSource('$testPackageLibPath/a.dart', 'class A { }');
     addTestSource('''
         import "a.dart";
         class C {var ^}''');
@@ -3232,7 +3232,7 @@
 
   Future<void> test_FunctionDeclaration_returnType_afterComment() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 int T1;
 F1() { }
 typedef D1();
@@ -3263,7 +3263,7 @@
 
   Future<void> test_FunctionDeclaration_returnType_afterComment2() async {
     // FunctionDeclaration  ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 int T1;
 F1() { }
 typedef D1();
@@ -3294,7 +3294,7 @@
 
   Future<void> test_FunctionDeclaration_returnType_afterComment3() async {
     // FunctionDeclaration  ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 int T1;
 F1() { }
 typedef D1();
@@ -3560,7 +3560,7 @@
 
   Future<void> test_IndexExpression() async {
     // ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 int T1;
 F1() { }
 class A {int x;}''');
@@ -3586,7 +3586,7 @@
 
   Future<void> test_IndexExpression2() async {
     // SimpleIdentifier IndexExpression ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 int T1;
 F1() { }
 class A {int x;}''');
@@ -3611,7 +3611,7 @@
   }
 
   Future<void> test_inherited() async {
-    resolveSource('/home/test/lib/b.dart', '''
+    resolveSource('$testPackageLibPath/b.dart', '''
 lib libB;
 class A2 {
   int x;
@@ -3762,8 +3762,8 @@
   }
 
   Future<void> test_InstanceCreationExpression_imported() async {
-    // SimpleIdentifier  TypeName  ConstructorName  InstanceCreationExpression
-    addSource('/home/test/lib/a.dart', '''
+    // SimpleIdentifier  NamedType  ConstructorName  InstanceCreationExpression
+    addSource('$testPackageLibPath/a.dart', '''
 int T1;
 F1() { }
 class A {A(this.x) { } int x;}''');
@@ -3822,7 +3822,7 @@
   }
 
   Future<void> test_InstanceCreationExpression_unimported() async {
-    // SimpleIdentifier  TypeName  ConstructorName  InstanceCreationExpression
+    // SimpleIdentifier  NamedType  ConstructorName  InstanceCreationExpression
     addSource('/testAB.dart', 'class Foo { }');
     addTestSource('class C {foo(){new F^}}');
     await computeSuggestions();
@@ -3865,7 +3865,7 @@
 
   Future<void> test_InterpolationExpression_block() async {
     // SimpleIdentifier  InterpolationExpression  StringInterpolation
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 int T1;
 F1() { }
 typedef D1();
@@ -3937,8 +3937,8 @@
   }
 
   Future<void> test_IsExpression() async {
-    // SimpleIdentifier  TypeName  IsExpression  IfStatement
-    addSource('/home/test/lib/b.dart', '''
+    // SimpleIdentifier  NamedType  IsExpression  IfStatement
+    addSource('$testPackageLibPath/b.dart', '''
 lib B;
 foo() { }
 class X {X.c(); X._d(); z() {}}''');
@@ -3977,7 +3977,7 @@
   }
 
   Future<void> test_IsExpression_type() async {
-    // SimpleIdentifier  TypeName  IsExpression  IfStatement
+    // SimpleIdentifier  NamedType  IsExpression  IfStatement
     addTestSource('''
 class A {int x; int y() => 0;}
 void f(){var a; if (a is ^)}''');
@@ -3997,7 +3997,7 @@
     // suggesting types. We ought to do so because there's no reason to cast a
     // value to the type it already has.
 
-    // SimpleIdentifier  TypeName  IsExpression  IfStatement
+    // SimpleIdentifier  NamedType  IsExpression  IfStatement
     addTestSource('''
 class A {} class B extends A {} class C extends A {} class D {}
 f(A a){ if (a is ^) {}}''');
@@ -4018,7 +4018,7 @@
     // suggesting types. We ought to do so because there's no reason to cast a
     // value to the type it already has.
 
-    // SimpleIdentifier  TypeName  IsExpression  IfStatement
+    // SimpleIdentifier  NamedType  IsExpression  IfStatement
     addTestSource('''
 class A {} class B implements A {} class C implements A {} class D {}
 f(A a){ if (a is ^) {}}''');
@@ -4034,7 +4034,7 @@
   }
 
   Future<void> test_IsExpression_type_filter_undefined_type() async {
-    // SimpleIdentifier  TypeName  AsExpression
+    // SimpleIdentifier  NamedType  AsExpression
     addTestSource('''
 class A {}
 f(U u){ (u as ^) }''');
@@ -4046,7 +4046,7 @@
   }
 
   Future<void> test_IsExpression_type_partial() async {
-    // SimpleIdentifier  TypeName  IsExpression  IfStatement
+    // SimpleIdentifier  NamedType  IsExpression  IfStatement
     addTestSource('''
 class A {int x; int y() => 0;}
 void f(){var a; if (a is Obj^)}''');
@@ -4061,7 +4061,7 @@
   }
 
   Future<void> test_keyword() async {
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 lib B;
 int newT1;
 int T1;
@@ -4214,7 +4214,7 @@
 
   Future<void> test_MapLiteralEntry() async {
     // MapLiteralEntry  MapLiteral  VariableDeclaration
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 int T1;
 F1() { }
 typedef D1();
@@ -4244,7 +4244,7 @@
 
   Future<void> test_MapLiteralEntry1() async {
     // MapLiteralEntry  MapLiteral  VariableDeclaration
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 int T1;
 F1() { }
 typedef D1();
@@ -4266,7 +4266,7 @@
 
   Future<void> test_MapLiteralEntry2() async {
     // SimpleIdentifier  MapLiteralEntry  MapLiteral  VariableDeclaration
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 int T1;
 F1() { }
 typedef D1();
@@ -4322,7 +4322,7 @@
   }
 
   Future<void> test_method_parameters_mixed_required_and_named() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 class A {
   void m(x, {int y}) {}
 }
@@ -4369,7 +4369,7 @@
   }
 
   Future<void> test_method_parameters_mixed_required_and_positional() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 class A {
   void m(x, [int y]) {}
 }
@@ -4417,7 +4417,7 @@
   }
 
   Future<void> test_method_parameters_named() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 class A {
   void m({x, int y}) {}
 }
@@ -4464,7 +4464,7 @@
   }
 
   Future<void> test_method_parameters_none() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 class A {
   void m() {}
 }
@@ -4501,7 +4501,7 @@
   }
 
   Future<void> test_method_parameters_positional() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 class A {
   void m([x, int y]) {}
 }
@@ -4548,7 +4548,7 @@
   }
 
   Future<void> test_method_parameters_required() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 class A {
   void m(x, int y) {}
 }
@@ -4607,7 +4607,7 @@
 
   Future<void> test_MethodDeclaration_body_static() async {
     // Block  BlockFunctionBody  MethodDeclaration
-    addSource('/home/test/lib/c.dart', '''
+    addSource('$testPackageLibPath/c.dart', '''
 class C {
   c1() {}
   var c2;
@@ -4784,7 +4784,7 @@
 
   Future<void> test_MethodDeclaration_returnType() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 int T1;
 F1() { }
 typedef D1();
@@ -4814,7 +4814,7 @@
 
   Future<void> test_MethodDeclaration_returnType_afterComment() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 int T1;
 F1() { }
 typedef D1();
@@ -4844,7 +4844,7 @@
 
   Future<void> test_MethodDeclaration_returnType_afterComment2() async {
     // MethodDeclaration  ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 int T1;
 F1() { }
 typedef D1();
@@ -4874,7 +4874,7 @@
 
   Future<void> test_MethodDeclaration_returnType_afterComment3() async {
     // MethodDeclaration  ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 int T1;
 F1() { }
 typedef D1();
@@ -5008,7 +5008,7 @@
   }
 
   Future<void> test_mixin_ordering() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 class B {}
 class M1 {
   void m() {}
@@ -5031,7 +5031,7 @@
 
   Future<void> test_MixinDeclaration_body() async {
     // MixinDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 class B { }''');
     addTestSource('''
 import "b.dart" as x;
@@ -5115,7 +5115,7 @@
   }
 
   Future<void> test_no_parameters_field() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 class A {
   int x;
 }
@@ -5132,7 +5132,7 @@
   }
 
   Future<void> test_no_parameters_getter() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 class A {
   int get x => null;
 }
@@ -5149,7 +5149,7 @@
   }
 
   Future<void> test_no_parameters_setter() async {
-    resolveSource('/home/test/lib/a.dart', '''
+    resolveSource('$testPackageLibPath/a.dart', '''
 class A {
   set x(int value) {};
 }
@@ -5166,7 +5166,7 @@
   }
 
   Future<void> test_outside_class() async {
-    resolveSource('/home/test/lib/b.dart', '''
+    resolveSource('$testPackageLibPath/b.dart', '''
 lib libB;
 class A2 {
   int x;
@@ -5253,7 +5253,7 @@
 
   Future<void> test_PrefixedIdentifier_class_const() async {
     // SimpleIdentifier PrefixedIdentifier ExpressionStatement Block
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 lib B;
 class I {
   static const scI = 'boo';
@@ -5300,7 +5300,7 @@
 
   Future<void> test_PrefixedIdentifier_class_imported() async {
     // SimpleIdentifier  PrefixedIdentifier  ExpressionStatement
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 lib B;
 class I {X get f => new A();get _g => new A();}
 class A implements I {
@@ -5379,7 +5379,7 @@
 
   Future<void> test_PrefixedIdentifier_library() async {
     // SimpleIdentifier  PrefixedIdentifier  ExpressionStatement
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 lib B;
 var T1;
 class X { }
@@ -5405,8 +5405,8 @@
   }
 
   Future<void> test_PrefixedIdentifier_library_typesOnly() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName
-    addSource('/home/test/lib/b.dart', '''
+    // SimpleIdentifier  PrefixedIdentifier  NamedType
+    addSource('$testPackageLibPath/b.dart', '''
 lib B;
 var T1;
 class X { }
@@ -5432,8 +5432,8 @@
   }
 
   Future<void> test_PrefixedIdentifier_library_typesOnly2() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName
-    addSource('/home/test/lib/b.dart', '''
+    // SimpleIdentifier  PrefixedIdentifier  NamedType
+    addSource('$testPackageLibPath/b.dart', '''
 lib B;
 var T1;
 class X { }
@@ -5460,7 +5460,7 @@
 
   Future<void> test_PrefixedIdentifier_parameter() async {
     // SimpleIdentifier  PrefixedIdentifier  ExpressionStatement
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 lib B;
 class _W {M y; var _z;}
 class X extends _W {}
@@ -5479,7 +5479,7 @@
 
   Future<void> test_PrefixedIdentifier_prefix() async {
     // SimpleIdentifier  PrefixedIdentifier  ExpressionStatement
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 class A {static int bar = 10;}
 _B() {}''');
     addTestSource('''
@@ -5643,7 +5643,7 @@
 
   Future<void> test_PropertyAccess_noTarget() async {
     // SimpleIdentifier  PropertyAccess  ExpressionStatement
-    addSource('/home/test/lib/ab.dart', 'class Foo { }');
+    addSource('$testPackageLibPath/ab.dart', 'class Foo { }');
     addTestSource('class C {foo(){.^}}');
     await computeSuggestions();
 
@@ -5652,7 +5652,7 @@
 
   Future<void> test_PropertyAccess_noTarget2() async {
     // SimpleIdentifier  PropertyAccess  ExpressionStatement
-    addSource('/home/test/lib/ab.dart', 'class Foo { }');
+    addSource('$testPackageLibPath/ab.dart', 'class Foo { }');
     addTestSource('void f() {.^}');
     await computeSuggestions();
 
@@ -5680,7 +5680,7 @@
   }
 
   Future<void> test_static_field() async {
-    resolveSource('/home/test/lib/b.dart', '''
+    resolveSource('$testPackageLibPath/b.dart', '''
 lib libB;
 class A2 {
   int x;
@@ -5722,7 +5722,7 @@
   }
 
   Future<void> test_static_method() async {
-    resolveSource('/home/test/lib/b.dart', '''
+    resolveSource('$testPackageLibPath/b.dart', '''
 lib libB;
 class A2 {
   int x;
@@ -6107,7 +6107,7 @@
 
   Future<void> test_TypeArgumentList() async {
     // SimpleIdentifier  BinaryExpression  ExpressionStatement
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 class C1 {int x;}
 F1() => 0;
 typedef String T1(int blat);''');
@@ -6133,8 +6133,8 @@
   }
 
   Future<void> test_TypeArgumentList2() async {
-    // TypeName  TypeArgumentList  TypeName
-    addSource('/home/test/lib/a.dart', '''
+    // NamedType  TypeArgumentList  NamedType
+    addSource('$testPackageLibPath/a.dart', '''
 class C1 {int x;}
 F1() => 0;
 typedef String T1(int blat);''');
@@ -6198,7 +6198,7 @@
   Future<void> test_VariableDeclaration_name() async {
     // SimpleIdentifier  VariableDeclaration  VariableDeclarationList
     // VariableDeclarationStatement  Block
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 lib B;
 foo() { }
 class _B { }
@@ -6225,7 +6225,7 @@
   Future<void> test_VariableDeclarationStatement_RHS() async {
     // SimpleIdentifier  VariableDeclaration  VariableDeclarationList
     // VariableDeclarationStatement
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 lib B;
 foo() { }
 class _B { }
@@ -6250,7 +6250,7 @@
   Future<void> test_VariableDeclarationStatement_RHS_missing_semicolon() async {
     // VariableDeclaration  VariableDeclarationList
     // VariableDeclarationStatement
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
 lib B;
 foo1() { }
 void bar1() { }
diff --git a/pkg/analysis_server/test/services/completion/dart/named_constructor_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/named_constructor_contributor_test.dart
index a671eeb..7c9b3d8 100644
--- a/pkg/analysis_server/test/services/completion/dart/named_constructor_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/named_constructor_contributor_test.dart
@@ -290,9 +290,9 @@
   }
 
   Future<void> test_ConstructorName_importedClass() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  PrefixedIdentifier  NamedType  ConstructorName
     // InstanceCreationExpression
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         int T1;
         F1() { }
@@ -318,9 +318,9 @@
   }
 
   Future<void> test_ConstructorName_importedClass_unresolved() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  PrefixedIdentifier  NamedType  ConstructorName
     // InstanceCreationExpression
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         int T1;
         F1() { }
@@ -347,9 +347,9 @@
   }
 
   Future<void> test_ConstructorName_importedFactory() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  PrefixedIdentifier  NamedType  ConstructorName
     // InstanceCreationExpression
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         int T1;
         F1() { }
@@ -375,7 +375,7 @@
   }
 
   Future<void> test_ConstructorName_importedFactory2() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  PrefixedIdentifier  NamedType  ConstructorName
     // InstanceCreationExpression
     addTestSource('''
         main() {new String.fr^omCharCodes([]);}''');
@@ -395,7 +395,7 @@
   }
 
   Future<void> test_ConstructorName_localClass() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  PrefixedIdentifier  NamedType  ConstructorName
     // InstanceCreationExpression
     addTestSource('''
         int T1;
@@ -422,7 +422,7 @@
   }
 
   Future<void> test_ConstructorName_localFactory() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  PrefixedIdentifier  NamedType  ConstructorName
     // InstanceCreationExpression
     addTestSource('''
         int T1;
@@ -450,7 +450,7 @@
 
   Future<void>
       test_importPrefix_className_typeArguments_period_nothing_functionTypeContext_matchingReturnType() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 class A<T> {
   A.named();
   A.new();
diff --git a/pkg/analysis_server/test/services/completion/dart/override_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/override_contributor_test.dart
index e8eff71..0e65414 100644
--- a/pkg/analysis_server/test/services/completion/dart/override_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/override_contributor_test.dart
@@ -153,7 +153,7 @@
   }
 
   Future<void> test_fromPart() async {
-    addSource('/home/test/lib/myLib.dart', '''
+    addSource('$testPackageLibPath/myLib.dart', '''
 library myLib;
 part 'test.dart';
 part 'otherPart.dart';
@@ -162,7 +162,7 @@
   B suggested2(String y) => null;
 }
 ''');
-    addSource('/home/test/lib/otherPart.dart', '''
+    addSource('$testPackageLibPath/otherPart.dart', '''
 part of myLib;
 class B extends A {
   B suggested2(String y) => null;
diff --git a/pkg/analysis_server/test/services/completion/dart/static_member_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/static_member_contributor_test.dart
index e4bc0d3..7c2a610 100644
--- a/pkg/analysis_server/test/services/completion/dart/static_member_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/static_member_contributor_test.dart
@@ -28,7 +28,7 @@
   }
 
   Future<void> test_class_static_notPrivate() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 class A {
   static int _f;
   static String get _g => '';
@@ -138,7 +138,7 @@
   }
 
   Future<void> test_extension_static_notPrivate() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 extension E {
   static int _f;
   static String get _g => '';
@@ -160,7 +160,7 @@
   }
 
   Future<void> test_implicitCreation() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 class A {
   A.foo();
   A.bar();
@@ -181,7 +181,7 @@
 
   Future<void>
       test_implicitCreation_functionContextType_matchingReturnType() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 class A {
   A.foo();
   A.bar();
@@ -202,7 +202,7 @@
 
   Future<void>
       test_implicitCreation_functionContextType_notMatchingReturnType() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 class A {
   A.foo();
   A.bar();
@@ -365,7 +365,7 @@
 
   Future<void> test_PrefixedIdentifier_class_const() async {
     // SimpleIdentifier PrefixedIdentifier ExpressionStatement Block
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         class I {
           static const scI = 'boo';
@@ -409,7 +409,7 @@
   }
 
   Future<void> test_simpleIdentifier_typeAlias_interfaceType_class() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 class A {
   static int _privateField = 0;
   static int get _privateGetter => 0;
@@ -451,7 +451,7 @@
   }
 
   Future<void> test_simpleIdentifier_typeAlias_interfaceType_enum() async {
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
 enum E {
   aaa,
   _bbb,
diff --git a/pkg/analysis_server/test/services/completion/dart/type_member_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/type_member_contributor_test.dart
index c7f9a18..47000b2 100644
--- a/pkg/analysis_server/test/services/completion/dart/type_member_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/type_member_contributor_test.dart
@@ -114,7 +114,7 @@
 
   Future<void> test_ArgumentList() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         library A;
         bool hasLength(int expected) { }
         void baz() { }''');
@@ -138,7 +138,7 @@
 
   Future<void> test_ArgumentList_imported_function() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         library A;
         bool hasLength(int expected) { }
         expect(arg) { }
@@ -164,7 +164,7 @@
   Future<void>
       test_ArgumentList_InstanceCreationExpression_functionalArg() async {
     // ArgumentList  InstanceCreationExpression  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         library A;
         class A { A(f()) { } }
         bool hasLength(int expected) { }
@@ -191,7 +191,7 @@
 
   Future<void> test_ArgumentList_InstanceCreationExpression_typedefArg() async {
     // ArgumentList  InstanceCreationExpression  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         library A;
         typedef Funct();
         class A { A(Funct f) { } }
@@ -219,7 +219,7 @@
 
   Future<void> test_ArgumentList_local_function() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         library A;
         bool hasLength(int expected) { }
         void baz() { }''');
@@ -244,7 +244,7 @@
 
   Future<void> test_ArgumentList_local_method() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         library A;
         bool hasLength(int expected) { }
         void baz() { }''');
@@ -269,7 +269,7 @@
 
   Future<void> test_ArgumentList_MethodInvocation_functionalArg() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         library A;
         class A { A(f()) { } }
         bool hasLength(int expected) { }
@@ -296,7 +296,7 @@
 
   Future<void> test_ArgumentList_MethodInvocation_methodArg() async {
     // ArgumentList  MethodInvocation  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         library A;
         class A { A(f()) { } }
         bool hasLength(int expected) { }
@@ -322,7 +322,7 @@
   Future<void> test_ArgumentList_namedParam() async {
     // SimpleIdentifier  NamedExpression  ArgumentList  MethodInvocation
     // ExpressionStatement
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         library A;
         bool hasLength(int expected) { }''');
     addTestSource('''
@@ -338,7 +338,7 @@
   }
 
   Future<void> test_AsExpression() async {
-    // SimpleIdentifier  TypeName  AsExpression
+    // SimpleIdentifier  NamedType  AsExpression
     addTestSource('''
         class A {var b; X _c; foo() {var a; (a as ^).foo();}''');
     await computeSuggestions();
@@ -373,7 +373,7 @@
   }
 
   Future<void> test_AssignmentExpression_type() async {
-    // SimpleIdentifier  TypeName  VariableDeclarationList
+    // SimpleIdentifier  NamedType  VariableDeclarationList
     // VariableDeclarationStatement  Block
     addTestSource('''
         class A {} void f() {
@@ -395,7 +395,7 @@
   }
 
   Future<void> test_AssignmentExpression_type_newline() async {
-    // SimpleIdentifier  TypeName  VariableDeclarationList
+    // SimpleIdentifier  NamedType  VariableDeclarationList
     // VariableDeclarationStatement  Block
     addTestSource('''
         class A {} void f() {
@@ -416,7 +416,7 @@
   }
 
   Future<void> test_AssignmentExpression_type_partial() async {
-    // SimpleIdentifier  TypeName  VariableDeclarationList
+    // SimpleIdentifier  NamedType  VariableDeclarationList
     // VariableDeclarationStatement  Block
     addTestSource('''
         class A {} void f() {
@@ -438,7 +438,7 @@
   }
 
   Future<void> test_AssignmentExpression_type_partial_newline() async {
-    // SimpleIdentifier  TypeName  VariableDeclarationList
+    // SimpleIdentifier  NamedType  VariableDeclarationList
     // VariableDeclarationStatement  Block
     addTestSource('''
         class A {} void f() {
@@ -977,7 +977,7 @@
 
   Future<void> test_Block_inherited_imported() async {
     // Block  BlockFunctionBody  MethodDeclaration  ClassDeclaration
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         class F { var f1; f2() { } get f3 => 0; set f4(fx) { } var _pf; }
         class E extends F { var e1; e2() { } }
@@ -1093,7 +1093,7 @@
 
   Future<void> test_CascadeExpression_method1() async {
     // PropertyAccess  CascadeExpression  ExpressionStatement  Block
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         class B { }''');
     addTestSource('''
         import "b.dart";
@@ -1117,7 +1117,7 @@
 
   Future<void> test_CascadeExpression_selector1() async {
     // PropertyAccess  CascadeExpression  ExpressionStatement  Block
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         class B { }''');
     addTestSource('''
         import "b.dart";
@@ -1141,7 +1141,7 @@
 
   Future<void> test_CascadeExpression_selector2() async {
     // SimpleIdentifier  PropertyAccess  CascadeExpression  ExpressionStatement
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         class B { }''');
     addTestSource('''
         import "b.dart";
@@ -1163,7 +1163,7 @@
 
   Future<void> test_CascadeExpression_selector2_withTrailingReturn() async {
     // PropertyAccess  CascadeExpression  ExpressionStatement  Block
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         class B { }''');
     addTestSource('''
         import "b.dart";
@@ -1203,7 +1203,7 @@
   }
 
   Future<void> test_CatchClause_onType() async {
-    // TypeName  CatchClause  TryStatement
+    // NamedType  CatchClause  TryStatement
     addTestSource('class A {a() {try{var x;} on ^ {}}}');
     await computeSuggestions();
     expect(replacementOffset, completionOffset);
@@ -1215,7 +1215,7 @@
   }
 
   Future<void> test_CatchClause_onType_noBrackets() async {
-    // TypeName  CatchClause  TryStatement
+    // NamedType  CatchClause  TryStatement
     addTestSource('class A {a() {try{var x;} on ^}}');
     await computeSuggestions();
     expect(replacementOffset, completionOffset);
@@ -1252,7 +1252,7 @@
 
   Future<void> test_ClassDeclaration_body() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         class B { }''');
     addTestSource('''
         import "b.dart" as x;
@@ -1271,7 +1271,7 @@
 
   Future<void> test_ClassDeclaration_body_final() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         class B { }''');
     addTestSource('''
         import "b.dart" as x;
@@ -1290,7 +1290,7 @@
 
   Future<void> test_ClassDeclaration_body_final_field() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         class B { }''');
     addTestSource('''
         import "b.dart" as x;
@@ -1309,7 +1309,7 @@
 
   Future<void> test_ClassDeclaration_body_final_field2() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         class B { }''');
     addTestSource('''
         import "b.dart" as Soo;
@@ -1328,7 +1328,7 @@
 
   Future<void> test_ClassDeclaration_body_final_final() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         class B { }''');
     addTestSource('''
         import "b.dart" as x;
@@ -1347,7 +1347,7 @@
 
   Future<void> test_ClassDeclaration_body_final_var() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         class B { }''');
     addTestSource('''
         import "b.dart" as x;
@@ -1414,7 +1414,7 @@
 
   Future<void> test_ConditionalExpression_elseExpression() async {
     // SimpleIdentifier  ConditionalExpression  ReturnStatement
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         class A {int x;}''');
@@ -1433,7 +1433,7 @@
 
   Future<void> test_ConditionalExpression_elseExpression_empty() async {
     // SimpleIdentifier  ConditionalExpression  ReturnStatement
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         class A {int x;}''');
@@ -1458,7 +1458,7 @@
 
   Future<void> test_ConditionalExpression_partial_thenExpression() async {
     // SimpleIdentifier  ConditionalExpression  ReturnStatement
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         class A {int x;}''');
@@ -1477,7 +1477,7 @@
 
   Future<void> test_ConditionalExpression_partial_thenExpression_empty() async {
     // SimpleIdentifier  ConditionalExpression  ReturnStatement
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         class A {int x;}''');
@@ -1502,7 +1502,7 @@
 
   Future<void> test_ConditionalExpression_thenExpression() async {
     // SimpleIdentifier  ConditionalExpression  ReturnStatement
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         class A {int x;}''');
@@ -1520,9 +1520,9 @@
   }
 
   Future<void> test_ConstructorName_importedClass() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  PrefixedIdentifier  NamedType  ConstructorName
     // InstanceCreationExpression
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         int T1;
         F1() { }
@@ -1544,9 +1544,9 @@
   }
 
   Future<void> test_ConstructorName_importedFactory() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  PrefixedIdentifier  NamedType  ConstructorName
     // InstanceCreationExpression
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         int T1;
         F1() { }
@@ -1568,7 +1568,7 @@
   }
 
   Future<void> test_ConstructorName_importedFactory2() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  PrefixedIdentifier  NamedType  ConstructorName
     // InstanceCreationExpression
     addTestSource('''
         void f() {new String.fr^omCharCodes([]);}''');
@@ -1585,7 +1585,7 @@
   }
 
   Future<void> test_ConstructorName_localClass() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  PrefixedIdentifier  NamedType  ConstructorName
     // InstanceCreationExpression
     addTestSource('''
         int T1;
@@ -1605,7 +1605,7 @@
   }
 
   Future<void> test_ConstructorName_localFactory() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName  ConstructorName
+    // SimpleIdentifier  PrefixedIdentifier  NamedType  ConstructorName
     // InstanceCreationExpression
     addTestSource('''
         int T1;
@@ -1706,7 +1706,7 @@
 
   Future<void> test_ExpressionStatement_identifier() async {
     // SimpleIdentifier  ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         _B F1() { }
         class A {int x;}
         class _B { }''');
@@ -1732,7 +1732,7 @@
 
   Future<void> test_ExpressionStatement_name() async {
     // ExpressionStatement  Block  BlockFunctionBody  MethodDeclaration
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         B T1;
         class B{}''');
     addTestSource('''
@@ -1759,7 +1759,7 @@
   Future<void> test_FieldDeclaration_name_typed() async {
     // SimpleIdentifier  VariableDeclaration  VariableDeclarationList
     // FieldDeclaration
-    addSource('/home/test/lib/a.dart', 'class A { }');
+    addSource('$testPackageLibPath/a.dart', 'class A { }');
     addTestSource('''
         import "a.dart";
         class C {A ^}''');
@@ -1770,7 +1770,7 @@
   Future<void> test_FieldDeclaration_name_var() async {
     // SimpleIdentifier  VariableDeclaration  VariableDeclarationList
     // FieldDeclaration
-    addSource('/home/test/lib/a.dart', 'class A { }');
+    addSource('$testPackageLibPath/a.dart', 'class A { }');
     addTestSource('''
         import "a.dart";
         class C {var ^}''');
@@ -1922,7 +1922,7 @@
 
   Future<void> test_FunctionDeclaration_returnType_afterComment() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -1951,7 +1951,7 @@
 
   Future<void> test_FunctionDeclaration_returnType_afterComment2() async {
     // FunctionDeclaration  ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -1980,7 +1980,7 @@
 
   Future<void> test_FunctionDeclaration_returnType_afterComment3() async {
     // FunctionDeclaration  ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -2174,7 +2174,7 @@
 
   Future<void> test_IndexExpression() async {
     // ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         class A {int x;}''');
@@ -2199,7 +2199,7 @@
 
   Future<void> test_IndexExpression2() async {
     // SimpleIdentifier IndexExpression ExpressionStatement  Block
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         class A {int x;}''');
@@ -2217,8 +2217,8 @@
   }
 
   Future<void> test_InstanceCreationExpression_imported() async {
-    // SimpleIdentifier  TypeName  ConstructorName  InstanceCreationExpression
-    addSource('/home/test/lib/a.dart', '''
+    // SimpleIdentifier  NamedType  ConstructorName  InstanceCreationExpression
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         class A {A(this.x) { } int x;}''');
@@ -2247,7 +2247,7 @@
   }
 
   Future<void> test_InstanceCreationExpression_unimported() async {
-    // SimpleIdentifier  TypeName  ConstructorName  InstanceCreationExpression
+    // SimpleIdentifier  NamedType  ConstructorName  InstanceCreationExpression
     addSource('/testAB.dart', 'class Foo { }');
     addTestSource('class C {foo(){new F^}}');
     await computeSuggestions();
@@ -2304,7 +2304,7 @@
 
   Future<void> test_InterpolationExpression() async {
     // SimpleIdentifier  InterpolationExpression  StringInterpolation
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -2333,7 +2333,7 @@
 
   Future<void> test_InterpolationExpression_block() async {
     // SimpleIdentifier  InterpolationExpression  StringInterpolation
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -2398,8 +2398,8 @@
   }
 
   Future<void> test_IsExpression() async {
-    // SimpleIdentifier  TypeName  IsExpression  IfStatement
-    addSource('/home/test/lib/b.dart', '''
+    // SimpleIdentifier  NamedType  IsExpression  IfStatement
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         foo() { }
         class X {X.c(); X._d(); z() {}}''');
@@ -2436,7 +2436,7 @@
   }
 
   Future<void> test_IsExpression_type() async {
-    // SimpleIdentifier  TypeName  IsExpression  IfStatement
+    // SimpleIdentifier  NamedType  IsExpression  IfStatement
     addTestSource('''
         class A {int x; int y() => 0;}
         void f(){var a; if (a is ^)}''');
@@ -2450,7 +2450,7 @@
   }
 
   Future<void> test_IsExpression_type_partial() async {
-    // SimpleIdentifier  TypeName  IsExpression  IfStatement
+    // SimpleIdentifier  NamedType  IsExpression  IfStatement
     addTestSource('''
         class A {int x; int y() => 0;}
         void f(){var a; if (a is Obj^)}''');
@@ -2472,7 +2472,7 @@
   }
 
   Future<void> test_keyword2() async {
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         int newT1;
         int T1;
@@ -2532,8 +2532,8 @@
   }
 
   Future<void> test_libraryPrefix_with_exports() async {
-    addSource('/home/test/lib/a.dart', 'class A { }');
-    addSource('/home/test/lib/b.dart', 'export "a.dart"; class B { }');
+    addSource('$testPackageLibPath/a.dart', 'class A { }');
+    addSource('$testPackageLibPath/b.dart', 'export "a.dart"; class B { }');
     addTestSource('import "b.dart" as foo; void f() {foo.^} class C { }');
     await computeSuggestions();
     // Suggested by LibraryMemberContributor
@@ -2591,7 +2591,7 @@
 
   Future<void> test_MapLiteralEntry() async {
     // MapLiteralEntry  MapLiteral  VariableDeclaration
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -2618,7 +2618,7 @@
 
   Future<void> test_MapLiteralEntry1() async {
     // MapLiteralEntry  MapLiteral  VariableDeclaration
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -2638,7 +2638,7 @@
 
   Future<void> test_MapLiteralEntry2() async {
     // SimpleIdentifier  MapLiteralEntry  MapLiteral  VariableDeclaration
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -2937,7 +2937,7 @@
 
   Future<void> test_MethodDeclaration_returnType() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -2965,7 +2965,7 @@
 
   Future<void> test_MethodDeclaration_returnType_afterComment() async {
     // ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -2993,7 +2993,7 @@
 
   Future<void> test_MethodDeclaration_returnType_afterComment2() async {
     // MethodDeclaration  ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -3021,7 +3021,7 @@
 
   Future<void> test_MethodDeclaration_returnType_afterComment3() async {
     // MethodDeclaration  ClassDeclaration  CompilationUnit
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         int T1;
         F1() { }
         typedef D1();
@@ -3267,13 +3267,13 @@
   }
 
   Future<void> test_partFile_TypeName() async {
-    // SimpleIdentifier  TypeName  ConstructorName
-    addSource('/home/test/lib/b.dart', '''
+    // SimpleIdentifier  NamedType  ConstructorName
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         int T1;
         F1() { }
         class X {X.c(); X._d(); z() {}}''');
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         library libA;
         import "b.dart";
         part "${resourceProvider.pathContext.basename(testFile)}";
@@ -3299,13 +3299,13 @@
   }
 
   Future<void> test_partFile_TypeName2() async {
-    // SimpleIdentifier  TypeName  ConstructorName
-    addSource('/home/test/lib/b.dart', '''
+    // SimpleIdentifier  NamedType  ConstructorName
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         int T1;
         F1() { }
         class X {X.c(); X._d(); z() {}}''');
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         part of libA;
         class B { }''');
     addTestSource('''
@@ -3332,7 +3332,7 @@
 
   Future<void> test_PrefixedIdentifier_class_const() async {
     // SimpleIdentifier PrefixedIdentifier ExpressionStatement Block
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         class I {
           static const scI = 'boo';
@@ -3378,7 +3378,7 @@
 
   Future<void> test_PrefixedIdentifier_class_imported() async {
     // SimpleIdentifier  PrefixedIdentifier  ExpressionStatement
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         class I {X get f => new A();get _g => new A();}
         class A implements I {
@@ -3454,7 +3454,7 @@
 
   Future<void> test_PrefixedIdentifier_library() async {
     // SimpleIdentifier  PrefixedIdentifier  ExpressionStatement
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         var T1;
         class X { }
@@ -3479,8 +3479,8 @@
   }
 
   Future<void> test_PrefixedIdentifier_library_typesOnly() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName
-    addSource('/home/test/lib/b.dart', '''
+    // SimpleIdentifier  PrefixedIdentifier  NamedType
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         var T1;
         class X { }
@@ -3505,8 +3505,8 @@
   }
 
   Future<void> test_PrefixedIdentifier_library_typesOnly2() async {
-    // SimpleIdentifier  PrefixedIdentifier  TypeName
-    addSource('/home/test/lib/b.dart', '''
+    // SimpleIdentifier  PrefixedIdentifier  NamedType
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         var T1;
         class X { }
@@ -3532,7 +3532,7 @@
 
   Future<void> test_PrefixedIdentifier_parameter() async {
     // SimpleIdentifier  PrefixedIdentifier  ExpressionStatement
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         class _W {M y; var _z;}
         class X extends _W {}
@@ -3550,7 +3550,7 @@
 
   Future<void> test_PrefixedIdentifier_prefix() async {
     // SimpleIdentifier  PrefixedIdentifier  ExpressionStatement
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         class A {static int bar = 10;}
         _B() {}''');
     addTestSource('''
@@ -4149,7 +4149,7 @@
 
   Future<void> test_TypeArgumentList() async {
     // SimpleIdentifier  BinaryExpression  ExpressionStatement
-    addSource('/home/test/lib/a.dart', '''
+    addSource('$testPackageLibPath/a.dart', '''
         class C1 {int x;}
         F1() => 0;
         typedef String T1(int blat);''');
@@ -4173,8 +4173,8 @@
   }
 
   Future<void> test_TypeArgumentList2() async {
-    // TypeName  TypeArgumentList  TypeName
-    addSource('/home/test/lib/a.dart', '''
+    // NamedType  TypeArgumentList  NamedType
+    addSource('$testPackageLibPath/a.dart', '''
         class C1 {int x;}
         F1() => 0;
         typedef String T1(int blat);''');
@@ -4218,7 +4218,7 @@
   Future<void> test_VariableDeclaration_name() async {
     // SimpleIdentifier  VariableDeclaration  VariableDeclarationList
     // VariableDeclarationStatement  Block
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         foo() { }
         class _B { }
@@ -4243,7 +4243,7 @@
   Future<void> test_VariableDeclarationStatement_RHS() async {
     // SimpleIdentifier  VariableDeclaration  VariableDeclarationList
     // VariableDeclarationStatement
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         foo() { }
         class _B { }
@@ -4267,7 +4267,7 @@
   Future<void> test_VariableDeclarationStatement_RHS_missing_semicolon() async {
     // VariableDeclaration  VariableDeclarationList
     // VariableDeclarationStatement
-    addSource('/home/test/lib/b.dart', '''
+    addSource('$testPackageLibPath/b.dart', '''
         lib B;
         foo1() { }
         void bar1() { }
diff --git a/pkg/analysis_server/test/services/completion/postfix/postfix_completion_test.dart b/pkg/analysis_server/test/services/completion/postfix/postfix_completion_test.dart
index 5e73ef0..dfc309c 100644
--- a/pkg/analysis_server/test/services/completion/postfix/postfix_completion_test.dart
+++ b/pkg/analysis_server/test/services/completion/postfix/postfix_completion_test.dart
@@ -738,7 +738,7 @@
   }
 
   Future<void> test_tryonThrowStatement_nnbd_into_legacy() async {
-    newFile('/home/test/lib/a.dart', content: r'''
+    newFile('$testPackageLibPath/a.dart', content: r'''
 String? x;
 ''');
     await _prepareCompletion('.tryon', '''
@@ -762,7 +762,7 @@
   }
 
   Future<void> test_tryonThrowStatement_nnbd_into_legacy_nested() async {
-    newFile('/home/test/lib/a.dart', content: r'''
+    newFile('$testPackageLibPath/a.dart', content: r'''
 List<String?> x;
 ''');
     await _prepareCompletion('.tryon', '''
@@ -786,7 +786,7 @@
   }
 
   Future<void> test_tryonThrowStatement_nnbd_legacy() async {
-    newFile('/home/test/lib/a.dart', content: r'''
+    newFile('$testPackageLibPath/a.dart', content: r'''
 // @dart = 2.8
 String x;
 ''');
@@ -809,7 +809,7 @@
   }
 
   Future<void> test_tryonThrowStatement_nnbd_legacy_nested() async {
-    newFile('/home/test/lib/a.dart', content: r'''
+    newFile('$testPackageLibPath/a.dart', content: r'''
 // @dart = 2.8
 List<String> x;
 ''');
diff --git a/pkg/analysis_server/test/services/correction/organize_directives_test.dart b/pkg/analysis_server/test/services/correction/organize_directives_test.dart
index f28613f..8ecae36 100644
--- a/pkg/analysis_server/test/services/correction/organize_directives_test.dart
+++ b/pkg/analysis_server/test/services/correction/organize_directives_test.dart
@@ -22,6 +22,12 @@
 class OrganizeDirectivesTest extends AbstractSingleUnitTest {
   late List<AnalysisError> testErrors;
 
+  @override
+  void setUp() {
+    super.setUp();
+    writeTestPackageConfig(meta: true);
+  }
+
   Future<void> test_docComment_beforeDirective_hasUnresolvedIdentifier() async {
     await _computeUnitAndErrors(r'''
 /// Library documentation comment A
@@ -682,6 +688,219 @@
 import 'package:b/a.dart';''');
   }
 
+  Future<void> test_sort_libraryAnnotation_movedDirective() async {
+    await _addAnnotationsFile();
+    await _computeUnitAndErrors(r'''
+@libraryAnnotation
+@LibraryAnnotation()
+
+// annotations
+import 'annotations.dart';
+
+// io
+import 'dart:io';
+''');
+    // Validate annotation is not moved with import.
+    _assertOrganize(r'''
+@libraryAnnotation
+@LibraryAnnotation()
+
+// io
+import 'dart:io';
+
+// annotations
+import 'annotations.dart';
+''');
+  }
+
+  Future<void> test_sort_libraryAnnotation_removedDirective() async {
+    await _addAnnotationsFile();
+    await _computeUnitAndErrors(r'''
+@libraryAnnotation
+@LibraryAnnotation()
+
+// io
+import 'dart:io'; // unused
+// annotations
+import 'annotations.dart'; // used
+''');
+    // Validate annotation is not removed with import.
+    _assertOrganize(r'''
+@libraryAnnotation
+@LibraryAnnotation()
+
+// annotations
+import 'annotations.dart'; // used
+''', removeUnused: true);
+  }
+
+  Future<void> test_sort_multipleAnnotation_movedDirective() async {
+    await _addAnnotationsFile();
+    await _computeUnitAndErrors(r'''
+@libraryAnnotation
+@LibraryAnnotation()
+
+@nonLibraryAnnotation
+import 'annotations.dart';
+@nonLibraryAnnotation
+import 'dart:io';
+''');
+    // Validate only the non-library annotation is moved with import.
+    _assertOrganize(r'''
+@libraryAnnotation
+@LibraryAnnotation()
+
+@nonLibraryAnnotation
+import 'dart:io';
+
+@nonLibraryAnnotation
+import 'annotations.dart';
+''');
+  }
+
+  Future<void> test_sort_multipleAnnotation_removedDirective() async {
+    await _addAnnotationsFile();
+    await _computeUnitAndErrors(r'''
+@libraryAnnotation
+@LibraryAnnotation()
+
+@nonLibraryAnnotation
+import 'dart:io';
+@nonLibraryAnnotation
+import 'annotations.dart';
+''');
+    // Validate only the non-library annotation is removed with import.
+    _assertOrganize(r'''
+@libraryAnnotation
+@LibraryAnnotation()
+
+@nonLibraryAnnotation
+import 'annotations.dart';
+''', removeUnused: true);
+  }
+
+  Future<void> test_sort_multipleAnnotationWithComments_movedDirective() async {
+    await _addAnnotationsFile();
+    await _computeUnitAndErrors(r'''
+// lib1
+@libraryAnnotation // lib1
+// lib2
+@LibraryAnnotation() // lib2
+
+// nonLib on annotations import
+@nonLibraryAnnotation // nonLib on annotations import
+// annotations import
+import 'annotations.dart'; // annotations import
+// nonLib on io import
+@nonLibraryAnnotation // nonLib on io import
+// io import
+import 'dart:io'; // io import
+''');
+    // Validate only the non-library annotation is moved with import.
+    _assertOrganize(r'''
+// lib1
+@libraryAnnotation // lib1
+// lib2
+@LibraryAnnotation() // lib2
+
+// nonLib on io import
+@nonLibraryAnnotation // nonLib on io import
+// io import
+import 'dart:io'; // io import
+
+// nonLib on annotations import
+@nonLibraryAnnotation // nonLib on annotations import
+// annotations import
+import 'annotations.dart'; // annotations import
+''');
+  }
+
+  Future<void>
+      test_sort_multipleAnnotationWithComments_removedDirective() async {
+    await _addAnnotationsFile();
+    await _computeUnitAndErrors(r'''
+// lib1
+@libraryAnnotation // lib1
+// lib2
+@LibraryAnnotation() // lib2
+
+// nonLib on io import
+@nonLibraryAnnotation // nonLib on io import
+// io import
+import 'dart:io'; // io import
+// nonLib on annotations import
+@nonLibraryAnnotation // nonLib on annotations import
+// annotations import
+import 'annotations.dart'; // annotations import
+''');
+    // Validate only the non-library annotation is removed with import.
+    _assertOrganize(r'''
+// lib1
+@libraryAnnotation // lib1
+// lib2
+@LibraryAnnotation() // lib2
+
+// nonLib on annotations import
+@nonLibraryAnnotation // nonLib on annotations import
+// annotations import
+import 'annotations.dart'; // annotations import
+''', removeUnused: true);
+  }
+
+  Future<void> test_sort_nonLibraryAnnotation_movedDirective() async {
+    await _addAnnotationsFile();
+    await _computeUnitAndErrors(r'''
+@nonLibraryAnnotation
+import 'annotations.dart';
+
+import 'dart:io';
+''');
+    // Validate annotation is moved with import.
+    _assertOrganize(r'''
+import 'dart:io';
+
+@nonLibraryAnnotation
+import 'annotations.dart';
+''');
+  }
+
+  Future<void> test_sort_nonLibraryAnnotation_removedDirective() async {
+    await _addAnnotationsFile();
+    await _computeUnitAndErrors(r'''
+@nonLibraryAnnotation
+// io
+import 'dart:io'; // unused
+// annotations
+import 'annotations.dart'; // used
+''');
+    // Validate annotation is removed with import.
+    _assertOrganize(r'''
+// annotations
+import 'annotations.dart'; // used
+''', removeUnused: true);
+  }
+
+  Future<void> _addAnnotationsFile() async {
+    final annotationsFile = convertPath('$testPackageLibPath/annotations.dart');
+    const annotationsContent = '''
+import 'package:meta/meta_meta.dart';
+
+const libraryAnnotation = LibraryAnnotation();
+const nonLibraryAnnotation = NonLibraryAnnotation();
+
+@Target({TargetKind.library})
+class LibraryAnnotation {
+  const LibraryAnnotation();
+}
+
+@Target({TargetKind.classType})
+class NonLibraryAnnotation {
+  const NonLibraryAnnotation();
+}
+    ''';
+    addSource(annotationsFile, annotationsContent);
+  }
+
   void _assertOrganize(String expectedCode, {bool removeUnused = false}) {
     var organizer = ImportOrganizer(testCode, testUnit, testErrors,
         removeUnused: removeUnused);
diff --git a/pkg/analysis_server/test/services/refactoring/convert_getter_to_method_test.dart b/pkg/analysis_server/test/services/refactoring/convert_getter_to_method_test.dart
index b8cc8eb..8b090db 100644
--- a/pkg/analysis_server/test/services/refactoring/convert_getter_to_method_test.dart
+++ b/pkg/analysis_server/test/services/refactoring/convert_getter_to_method_test.dart
@@ -89,7 +89,7 @@
   }
 
   Future<void> test_change_multipleFiles() async {
-    await indexUnit('/home/test/lib/other.dart', r'''
+    await indexUnit('$testPackageLibPath/other.dart', r'''
 class A {
   int get test => 1;
 }
diff --git a/pkg/analysis_server/test/services/refactoring/convert_method_to_getter_test.dart b/pkg/analysis_server/test/services/refactoring/convert_method_to_getter_test.dart
index c95f9e0..58aea84 100644
--- a/pkg/analysis_server/test/services/refactoring/convert_method_to_getter_test.dart
+++ b/pkg/analysis_server/test/services/refactoring/convert_method_to_getter_test.dart
@@ -88,7 +88,7 @@
   }
 
   Future<void> test_change_multipleFiles() async {
-    await indexUnit('/home/test/lib/other.dart', r'''
+    await indexUnit('$testPackageLibPath/other.dart', r'''
 class A {
   int test() => 1;
 }
diff --git a/pkg/analysis_server/test/services/refactoring/extract_method_test.dart b/pkg/analysis_server/test/services/refactoring/extract_method_test.dart
index 527b60f..98584b8 100644
--- a/pkg/analysis_server/test/services/refactoring/extract_method_test.dart
+++ b/pkg/analysis_server/test/services/refactoring/extract_method_test.dart
@@ -2871,7 +2871,7 @@
   }
 
   void _addLibraryReturningAsync() {
-    addSource('/home/test/lib/asyncLib.dart', r'''
+    addSource('$testPackageLibPath/asyncLib.dart', r'''
 import 'dart:async';
 
 Completer<int> newCompleter() => null;
diff --git a/pkg/analysis_server/test/services/refactoring/move_file_test.dart b/pkg/analysis_server/test/services/refactoring/move_file_test.dart
index 5094b24..52fe0df 100644
--- a/pkg/analysis_server/test/services/refactoring/move_file_test.dart
+++ b/pkg/analysis_server/test/services/refactoring/move_file_test.dart
@@ -57,7 +57,7 @@
   }
 
   Future<void> test_file_imported_with_package_uri_down() async {
-    var file = newFile('/home/test/lib/old_name.dart', content: '');
+    var file = newFile('$testPackageLibPath/old_name.dart', content: '');
     addTestSource(r'''
 import 'package:test/old_name.dart';
 ''');
@@ -69,7 +69,8 @@
     testAnalysisResult =
         await session.getResolvedUnit(file.path) as ResolvedUnitResult;
 
-    _createRefactoring('/home/test/lib/222/new_name.dart', oldFile: file.path);
+    _createRefactoring('$testPackageLibPath/222/new_name.dart',
+        oldFile: file.path);
     await _assertSuccessfulRefactoring();
 
     assertFileChangeResult(testFile, '''
@@ -150,7 +151,7 @@
   }
 
   Future<void> test_file_imported_with_package_uri_sideways() async {
-    var file = newFile('/home/test/lib/111/old_name.dart', content: '');
+    var file = newFile('$testPackageLibPath/111/old_name.dart', content: '');
     addTestSource(r'''
 import 'package:test/111/old_name.dart';
 ''');
@@ -162,7 +163,8 @@
     testAnalysisResult =
         await session.getResolvedUnit(file.path) as ResolvedUnitResult;
 
-    _createRefactoring('/home/test/lib/222/new_name.dart', oldFile: file.path);
+    _createRefactoring('$testPackageLibPath/222/new_name.dart',
+        oldFile: file.path);
     await _assertSuccessfulRefactoring();
 
     assertFileChangeResult(testFile, '''
@@ -171,7 +173,7 @@
   }
 
   Future<void> test_file_imported_with_package_uri_up() async {
-    var file = newFile('/home/test/lib/222/old_name.dart', content: '');
+    var file = newFile('$testPackageLibPath/222/old_name.dart', content: '');
     addTestSource(r'''
 import 'package:test/222/old_name.dart';
 ''');
@@ -183,7 +185,7 @@
     testAnalysisResult =
         await session.getResolvedUnit(file.path) as ResolvedUnitResult;
 
-    _createRefactoring('/home/test/lib/new_name.dart', oldFile: file.path);
+    _createRefactoring('$testPackageLibPath/new_name.dart', oldFile: file.path);
     await _assertSuccessfulRefactoring();
 
     assertFileChangeResult(testFile, '''
diff --git a/pkg/analysis_server/test/services/refactoring/rename_class_member_test.dart b/pkg/analysis_server/test/services/refactoring/rename_class_member_test.dart
index 872fe9d..af8c5b5 100644
--- a/pkg/analysis_server/test/services/refactoring/rename_class_member_test.dart
+++ b/pkg/analysis_server/test/services/refactoring/rename_class_member_test.dart
@@ -157,7 +157,7 @@
   test() {}
 }
 ''');
-    await indexUnit('/home/test/lib/lib.dart', '''
+    await indexUnit('$testPackageLibPath/lib.dart', '''
 library my.lib;
 import 'test.dart';
 
@@ -181,7 +181,7 @@
   var foo = 1;
 }
 ''');
-    await indexUnit('/home/test/lib/lib.dart', '''
+    await indexUnit('$testPackageLibPath/lib.dart', '''
 import 'test.dart';
 
 void f(A a) {
@@ -387,7 +387,7 @@
   newName() {} // marker
 }
 ''';
-    await indexUnit('/home/test/lib/lib.dart', libCode);
+    await indexUnit('$testPackageLibPath/lib.dart', libCode);
     await indexTestUnit('''
 import 'lib.dart';
 class B extends A {
diff --git a/pkg/analysis_server/test/services/refactoring/rename_library_test.dart b/pkg/analysis_server/test/services/refactoring/rename_library_test.dart
index 2f37e06..0b6b03c 100644
--- a/pkg/analysis_server/test/services/refactoring/rename_library_test.dart
+++ b/pkg/analysis_server/test/services/refactoring/rename_library_test.dart
@@ -35,7 +35,7 @@
   }
 
   Future<void> test_createChange() async {
-    addSource('/home/test/lib/part.dart', '''
+    addSource('$testPackageLibPath/part.dart', '''
 part of my.app;
 ''');
     await indexTestUnit('''
@@ -52,13 +52,13 @@
 library the.new.name;
 part 'part.dart';
 ''');
-    assertFileChangeResult('/home/test/lib/part.dart', '''
+    assertFileChangeResult('$testPackageLibPath/part.dart', '''
 part of the.new.name;
 ''');
   }
 
   Future<void> test_createChange_hasWhitespaces() async {
-    addSource('/home/test/lib/part.dart', '''
+    addSource('$testPackageLibPath/part.dart', '''
 part of my .  app;
 ''');
     await indexTestUnit('''
@@ -75,7 +75,7 @@
 library the.new.name;
 part 'part.dart';
 ''');
-    assertFileChangeResult('/home/test/lib/part.dart', '''
+    assertFileChangeResult('$testPackageLibPath/part.dart', '''
 part of the.new.name;
 ''');
   }
diff --git a/pkg/analysis_server/test/services/refactoring/rename_local_test.dart b/pkg/analysis_server/test/services/refactoring/rename_local_test.dart
index 5c43032..5b42916 100644
--- a/pkg/analysis_server/test/services/refactoring/rename_local_test.dart
+++ b/pkg/analysis_server/test/services/refactoring/rename_local_test.dart
@@ -442,9 +442,38 @@
 ''');
   }
 
+  Future<void> test_createChange_parameter_named_anywhere() async {
+    await indexTestUnit('''
+myFunction(int a, int b, {required int test}) {
+  test = 1;
+  test += 2;
+  print(test);
+}
+void f() {
+  myFunction(0, test: 2, 1);
+}
+''');
+    // configure refactoring
+    createRenameRefactoringAtString('test}) {');
+    expect(refactoring.refactoringName, 'Rename Parameter');
+    expect(refactoring.elementKindName, 'parameter');
+    refactoring.newName = 'newName';
+    // validate change
+    return assertSuccessfulRefactoring('''
+myFunction(int a, int b, {required int newName}) {
+  newName = 1;
+  newName += 2;
+  print(newName);
+}
+void f() {
+  myFunction(0, newName: 2, 1);
+}
+''');
+  }
+
   Future<void> test_createChange_parameter_named_inOtherFile() async {
-    var a = convertPath('/home/test/lib/a.dart');
-    var b = convertPath('/home/test/lib/b.dart');
+    var a = convertPath('$testPackageLibPath/a.dart');
+    var b = convertPath('$testPackageLibPath/b.dart');
 
     newFile(a, content: r'''
 class A {
@@ -537,7 +566,7 @@
   }
 
   Future<void> test_createChange_parameter_named_updateHierarchy() async {
-    await indexUnit('/home/test/lib/test2.dart', '''
+    await indexUnit('$testPackageLibPath/test2.dart', '''
 library test2;
 class A {
   void foo({int? test}) {
@@ -581,7 +610,7 @@
   }
 }
 ''');
-    assertFileChangeResult('/home/test/lib/test2.dart', '''
+    assertFileChangeResult('$testPackageLibPath/test2.dart', '''
 library test2;
 class A {
   void foo({int? newName}) {
diff --git a/pkg/analysis_server/test/services/refactoring/rename_unit_member_test.dart b/pkg/analysis_server/test/services/refactoring/rename_unit_member_test.dart
index a65f922..e0ebb09 100644
--- a/pkg/analysis_server/test/services/refactoring/rename_unit_member_test.dart
+++ b/pkg/analysis_server/test/services/refactoring/rename_unit_member_test.dart
@@ -71,7 +71,7 @@
     await indexTestUnit('''
 class Test {}
 ''');
-    await indexUnit('/home/test/lib/lib.dart', '''
+    await indexUnit('$testPackageLibPath/lib.dart', '''
 library my.lib;
 import 'test.dart';
 
@@ -112,7 +112,7 @@
     await indexTestUnit('''
 class Test {}
 ''');
-    await indexUnit('/home/test/lib/lib.dart', '''
+    await indexUnit('$testPackageLibPath/lib.dart', '''
 library my.lib;
 import 'test.dart';
 class A {
@@ -610,7 +610,7 @@
   }
 
   Future<void> test_createChange_FunctionElement_imported() async {
-    await indexUnit('/home/test/lib/foo.dart', r'''
+    await indexUnit('$testPackageLibPath/foo.dart', r'''
 test() {}
 foo() {}
 ''');
@@ -637,7 +637,7 @@
   foo();
 }
 ''');
-    assertFileChangeResult('/home/test/lib/foo.dart', '''
+    assertFileChangeResult('$testPackageLibPath/foo.dart', '''
 newName() {}
 foo() {}
 ''');
diff --git a/pkg/analysis_server/test/src/cider/rename_test.dart b/pkg/analysis_server/test/src/cider/rename_test.dart
index 028aaea..626135f 100644
--- a/pkg/analysis_server/test/src/cider/rename_test.dart
+++ b/pkg/analysis_server/test/src/cider/rename_test.dart
@@ -4,6 +4,7 @@
 
 import 'package:analysis_server/src/cider/rename.dart';
 import 'package:analyzer/source/line_info.dart';
+import 'package:analyzer/src/dart/micro/resolve_file.dart';
 import 'package:test/test.dart';
 import 'package:test_reflective_loader/test_reflective_loader.dart';
 
@@ -29,7 +30,6 @@
 }
 ''');
 
-    expect(refactor, isNotNull);
     expect(refactor!.refactoringElement.element.name, 'bar');
     expect(refactor.refactoringElement.offset, _correctionContext.offset);
   }
@@ -40,7 +40,6 @@
 }
 ''');
 
-    expect(refactor, isNotNull);
     expect(refactor!.refactoringElement.element.name, 'foo');
     expect(refactor.refactoringElement.offset, _correctionContext.offset);
   }
@@ -68,7 +67,6 @@
 }
 ''');
 
-    expect(refactor, isNotNull);
     expect(refactor!.refactoringElement.element.name, 'a');
     expect(refactor.refactoringElement.offset, _correctionContext.offset);
   }
@@ -80,7 +78,6 @@
 }
 ''');
 
-    expect(refactor, isNotNull);
     expect(refactor!.refactoringElement.element.name, 'foo');
     expect(refactor.refactoringElement.offset, _correctionContext.offset);
   }
@@ -112,9 +109,8 @@
 int ^foo() => 2;
 ''', 'bar');
 
-    expect(result, isNotNull);
-    expect(result?.status.problems.length, 0);
-    expect(result?.oldName, 'foo');
+    expect(result!.status.problems.length, 0);
+    expect(result.oldName, 'foo');
   }
 
   void test_checkName_local() {
@@ -124,9 +120,8 @@
 }
 ''', 'bar');
 
-    expect(result, isNotNull);
-    expect(result?.status.problems.length, 0);
-    expect(result?.oldName, 'a');
+    expect(result!.status.problems.length, 0);
+    expect(result.oldName, 'a');
   }
 
   void test_checkName_local_invalid() {
@@ -136,9 +131,8 @@
 }
 ''', 'Aa');
 
-    expect(result, isNotNull);
-    expect(result?.status.problems.length, 1);
-    expect(result?.oldName, 'a');
+    expect(result!.status.problems.length, 1);
+    expect(result.oldName, 'a');
   }
 
   void test_checkName_parameter() {
@@ -148,9 +142,57 @@
 }
 ''', 'bar');
 
-    expect(result, isNotNull);
-    expect(result?.status.problems.length, 0);
-    expect(result?.oldName, 'a');
+    expect(result!.status.problems.length, 0);
+    expect(result.oldName, 'a');
+  }
+
+  void test_rename_local() {
+    var result = _rename(r'''
+void foo() {
+  var ^a = 0; var b = a + 1;
+}
+''', 'bar');
+
+    expect(result!.matches.length, 1);
+    expect(
+        result.matches[0],
+        CiderSearchMatch(convertPath('/workspace/dart/test/lib/test.dart'),
+            [CharacterLocation(2, 7), CharacterLocation(2, 22)]));
+  }
+
+  void test_rename_method() {
+    var a = newFile('/workspace/dart/test/lib/a.dart', content: r'''
+void foo() {
+  a;
+}
+''');
+    fileResolver.resolve(path: a.path);
+
+    var result = _rename(r'''
+import 'a.dart';
+
+main() {
+^foo();
+}
+''', 'bar');
+
+    expect(result!.matches.length, 2);
+    expect(result.matches, [
+      CiderSearchMatch(convertPath('/workspace/dart/test/lib/a.dart'),
+          [CharacterLocation(1, 6)]),
+      CiderSearchMatch(convertPath('/workspace/dart/test/lib/test.dart'),
+          [CharacterLocation(4, 1)])
+    ]);
+  }
+
+  void test_rename_parameter() {
+    var result = _rename(r'''
+void foo(String ^a) {
+  var b = a + 1;
+}
+''', 'bar');
+    expect(result!.matches.length, 1);
+    expect(result.checkName.oldName, 'a');
   }
 
   CheckNameResponse? _checkName(String content, String newName) {
@@ -158,12 +200,13 @@
 
     return CiderRenameComputer(
       fileResolver,
-    ).checkNewName(
-      convertPath(testPath),
-      _correctionContext.line,
-      _correctionContext.character,
-      newName,
-    );
+    )
+        .canRename(
+          convertPath(testPath),
+          _correctionContext.line,
+          _correctionContext.character,
+        )
+        ?.checkNewName(newName);
   }
 
   CanRenameResponse? _compute(String content) {
@@ -178,6 +221,21 @@
     );
   }
 
+  RenameResponse? _rename(String content, newName) {
+    _updateFile(content);
+
+    return CiderRenameComputer(
+      fileResolver,
+    )
+        .canRename(
+          convertPath(testPath),
+          _correctionContext.line,
+          _correctionContext.character,
+        )
+        ?.checkNewName(newName)
+        ?.computeRenameRanges();
+  }
+
   void _updateFile(String content) {
     var offset = content.indexOf('^');
     expect(offset, isPositive, reason: 'Expected to find ^');
diff --git a/pkg/analysis_server/test/src/computer/closing_labels_computer_test.dart b/pkg/analysis_server/test/src/computer/closing_labels_computer_test.dart
index 83a9954..3c99d77 100644
--- a/pkg/analysis_server/test/src/computer/closing_labels_computer_test.dart
+++ b/pkg/analysis_server/test/src/computer/closing_labels_computer_test.dart
@@ -23,7 +23,7 @@
   @override
   void setUp() {
     super.setUp();
-    sourcePath = convertPath('/home/test/lib/test.dart');
+    sourcePath = convertPath('$testPackageLibPath/test.dart');
   }
 
   Future<void> test_adjacentLinesExcluded() async {
diff --git a/pkg/analysis_server/test/src/computer/color_computer_test.dart b/pkg/analysis_server/test/src/computer/color_computer_test.dart
new file mode 100644
index 0000000..1178812
--- /dev/null
+++ b/pkg/analysis_server/test/src/computer/color_computer_test.da