Version 2.14.0-287.0.dev

Merge commit 'c2f5625fa714c16abd748024db7769402a97adf5' into 'dev'
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 3992b34..0688ab2 100644
--- a/pkg/_fe_analyzer_shared/lib/src/parser/parser_impl.dart
+++ b/pkg/_fe_analyzer_shared/lib/src/parser/parser_impl.dart
@@ -3455,7 +3455,7 @@
   /// method takes the next token to be consumed rather than the last consumed
   /// token and returns the token after the last consumed token rather than the
   /// last consumed token.
-  Token parseClassMember(Token token, String className) {
+  Token parseClassMember(Token token, String? className) {
     return parseClassOrMixinOrExtensionMemberImpl(
             syntheticPreviousToken(token), DeclarationKind.Class, className)
         .next!;
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 ce64454..455dfdf 100644
--- a/pkg/_fe_analyzer_shared/lib/src/parser/stack_listener.dart
+++ b/pkg/_fe_analyzer_shared/lib/src/parser/stack_listener.dart
@@ -504,6 +504,10 @@
   /// Returns [null] if a [ParserRecovery] value is found, or [list] otherwise.
   List<T?>? popList<T>(int count, List<T?> list, NullValue? nullValue);
 
+  /// Pops [count] elements from the stack and puts it into [list].
+  /// Returns [null] if a [ParserRecovery] value is found, or [list] otherwise.
+  List<T>? popNonNullableList<T>(int count, List<T> list);
+
   void push(Object value);
 
   /// Will return [null] instead of [NullValue].
@@ -583,6 +587,27 @@
     return isParserRecovery ? null : list;
   }
 
+  List<T>? popNonNullableList<T>(int count, List<T> list) {
+    assert(arrayLength >= count);
+    final List<Object?> array = this.array;
+    final int length = arrayLength;
+    final int startIndex = length - count;
+    bool isParserRecovery = false;
+    for (int i = 0; i < count; i++) {
+      int arrayIndex = startIndex + i;
+      final Object? value = array[arrayIndex];
+      array[arrayIndex] = null;
+      if (value is ParserRecovery) {
+        isParserRecovery = true;
+      } else {
+        list[i] = value as T;
+      }
+    }
+    arrayLength -= count;
+
+    return isParserRecovery ? null : list;
+  }
+
   List<Object?> get values {
     final int length = arrayLength;
     final List<Object?> list = new List<Object?>.filled(length, null);
@@ -642,6 +667,14 @@
   }
 
   @override
+  List<T>? popNonNullableList<T>(int count, List<T> list) {
+    List<T>? result = realStack.popNonNullableList(count, list);
+    latestStacktraces.length = count;
+    stackTraceStack.popList(count, latestStacktraces, /* nullValue = */ null);
+    return result;
+  }
+
+  @override
   void push(Object value) {
     realStack.push(value);
     stackTraceStack.push(StackTrace.current);
@@ -662,12 +695,25 @@
     return stack.popList(count, new List<T?>.filled(count, null), nullValue);
   }
 
+  List<T>? popNonNullable(Stack stack, int count, T dummyValue) {
+    if (count == 0) return null;
+    return stack.popNonNullableList(
+        count, new List<T>.filled(count, dummyValue));
+  }
+
   List<T?>? popPadded(Stack stack, int count, int padding,
       [NullValue? nullValue]) {
     if (count + padding == 0) return null;
     return stack.popList(
         count, new List<T?>.filled(count + padding, null), nullValue);
   }
+
+  List<T>? popPaddedNonNullable(
+      Stack stack, int count, int padding, T dummyValue) {
+    if (count + padding == 0) return null;
+    return stack.popNonNullableList(
+        count, new List<T>.filled(count + padding, dummyValue));
+  }
 }
 
 /// Helper constant for popping a list of the top of a [Stack].  This helper
@@ -681,6 +727,12 @@
         new List<T?>.filled(count, /* fill = */ null, growable: true),
         nullValue);
   }
+
+  List<T>? popNonNullable(Stack stack, int count, T dummyValue) {
+    if (count == 0) return null;
+    return stack.popNonNullableList(
+        count, new List<T>.filled(count, dummyValue, growable: true));
+  }
 }
 
 class ParserRecovery {
diff --git a/pkg/analysis_server/lib/lsp_protocol/protocol_custom_generated.dart b/pkg/analysis_server/lib/lsp_protocol/protocol_custom_generated.dart
index 03f9e6a..7c0603b 100644
--- a/pkg/analysis_server/lib/lsp_protocol/protocol_custom_generated.dart
+++ b/pkg/analysis_server/lib/lsp_protocol/protocol_custom_generated.dart
@@ -25,32 +25,34 @@
       AnalyzerStatusParams.canParse, AnalyzerStatusParams.fromJson);
 
   AnalyzerStatusParams({required this.isAnalyzing});
-  static AnalyzerStatusParams fromJson(Map<String, dynamic> json) {
-    final isAnalyzing = json['isAnalyzing'];
+  static AnalyzerStatusParams fromJson(Map<String, Object?> json) {
+    final isAnalyzingJson = json['isAnalyzing'];
+    final isAnalyzing = isAnalyzingJson as bool;
     return AnalyzerStatusParams(isAnalyzing: isAnalyzing);
   }
 
   final bool isAnalyzing;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['isAnalyzing'] = isAnalyzing;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('isAnalyzing');
       try {
         if (!obj.containsKey('isAnalyzing')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['isAnalyzing'] == null) {
+        final isAnalyzing = obj['isAnalyzing'];
+        if (isAnalyzing == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['isAnalyzing'] is bool)) {
+        if (!(isAnalyzing is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -89,35 +91,38 @@
       LspJsonHandler(ClosingLabel.canParse, ClosingLabel.fromJson);
 
   ClosingLabel({required this.range, required this.label});
-  static ClosingLabel fromJson(Map<String, dynamic> json) {
-    final range = Range.fromJson(json['range']);
-    final label = json['label'];
+  static ClosingLabel fromJson(Map<String, Object?> json) {
+    final rangeJson = json['range'];
+    final range = Range.fromJson(rangeJson as Map<String, Object?>);
+    final labelJson = json['label'];
+    final label = labelJson as String;
     return ClosingLabel(range: range, label: label);
   }
 
   final String label;
   final Range range;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['range'] = range.toJson();
     __result['label'] = label;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('range');
       try {
         if (!obj.containsKey('range')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['range'] == null) {
+        final range = obj['range'];
+        if (range == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['range'], reporter))) {
+        if (!(Range.canParse(range, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -130,11 +135,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['label'] == null) {
+        final label = obj['label'];
+        if (label == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['label'] is String)) {
+        if (!(label is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -174,7 +180,7 @@
       CompletionItemResolutionInfo.fromJson);
 
   CompletionItemResolutionInfo({required this.file, required this.offset});
-  static CompletionItemResolutionInfo fromJson(Map<String, dynamic> json) {
+  static CompletionItemResolutionInfo fromJson(Map<String, Object?> json) {
     if (DartCompletionItemResolutionInfo.canParse(json, nullLspJsonReporter)) {
       return DartCompletionItemResolutionInfo.fromJson(json);
     }
@@ -182,34 +188,37 @@
         json, nullLspJsonReporter)) {
       return PubPackageCompletionItemResolutionInfo.fromJson(json);
     }
-    final file = json['file'];
-    final offset = json['offset'];
+    final fileJson = json['file'];
+    final file = fileJson as String;
+    final offsetJson = json['offset'];
+    final offset = offsetJson as int;
     return CompletionItemResolutionInfo(file: file, offset: offset);
   }
 
   final String file;
   final int offset;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['file'] = file;
     __result['offset'] = offset;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('file');
       try {
         if (!obj.containsKey('file')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['file'] == null) {
+        final file = obj['file'];
+        if (file == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['file'] is String)) {
+        if (!(file is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -222,11 +231,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['offset'] == null) {
+        final offset = obj['offset'];
+        if (offset == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['offset'] is int)) {
+        if (!(offset is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -275,14 +285,21 @@
       required this.rLength,
       required this.file,
       required this.offset});
-  static DartCompletionItemResolutionInfo fromJson(Map<String, dynamic> json) {
-    final libId = json['libId'];
-    final displayUri = json['displayUri'];
-    final rOffset = json['rOffset'];
-    final iLength = json['iLength'];
-    final rLength = json['rLength'];
-    final file = json['file'];
-    final offset = json['offset'];
+  static DartCompletionItemResolutionInfo fromJson(Map<String, Object?> json) {
+    final libIdJson = json['libId'];
+    final libId = libIdJson as int;
+    final displayUriJson = json['displayUri'];
+    final displayUri = displayUriJson as String;
+    final rOffsetJson = json['rOffset'];
+    final rOffset = rOffsetJson as int;
+    final iLengthJson = json['iLength'];
+    final iLength = iLengthJson as int;
+    final rLengthJson = json['rLength'];
+    final rLength = rLengthJson as int;
+    final fileJson = json['file'];
+    final file = fileJson as String;
+    final offsetJson = json['offset'];
+    final offset = offsetJson as int;
     return DartCompletionItemResolutionInfo(
         libId: libId,
         displayUri: displayUri,
@@ -301,8 +318,8 @@
   final int rLength;
   final int rOffset;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['libId'] = libId;
     __result['displayUri'] = displayUri;
     __result['rOffset'] = rOffset;
@@ -314,18 +331,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('libId');
       try {
         if (!obj.containsKey('libId')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['libId'] == null) {
+        final libId = obj['libId'];
+        if (libId == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['libId'] is int)) {
+        if (!(libId is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -338,11 +356,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['displayUri'] == null) {
+        final displayUri = obj['displayUri'];
+        if (displayUri == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['displayUri'] is String)) {
+        if (!(displayUri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -355,11 +374,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['rOffset'] == null) {
+        final rOffset = obj['rOffset'];
+        if (rOffset == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['rOffset'] is int)) {
+        if (!(rOffset is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -372,11 +392,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['iLength'] == null) {
+        final iLength = obj['iLength'];
+        if (iLength == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['iLength'] is int)) {
+        if (!(iLength is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -389,11 +410,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['rLength'] == null) {
+        final rLength = obj['rLength'];
+        if (rLength == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['rLength'] is int)) {
+        if (!(rLength is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -406,11 +428,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['file'] == null) {
+        final file = obj['file'];
+        if (file == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['file'] is String)) {
+        if (!(file is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -423,11 +446,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['offset'] == null) {
+        final offset = obj['offset'];
+        if (offset == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['offset'] is int)) {
+        if (!(offset is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -479,32 +503,34 @@
       DartDiagnosticServer.canParse, DartDiagnosticServer.fromJson);
 
   DartDiagnosticServer({required this.port});
-  static DartDiagnosticServer fromJson(Map<String, dynamic> json) {
-    final port = json['port'];
+  static DartDiagnosticServer fromJson(Map<String, Object?> json) {
+    final portJson = json['port'];
+    final port = portJson as int;
     return DartDiagnosticServer(port: port);
   }
 
   final int port;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['port'] = port;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('port');
       try {
         if (!obj.containsKey('port')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['port'] == null) {
+        final port = obj['port'];
+        if (port == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['port'] is int)) {
+        if (!(port is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -548,13 +574,21 @@
       this.parameters,
       this.typeParameters,
       this.returnType});
-  static Element fromJson(Map<String, dynamic> json) {
-    final range = json['range'] != null ? Range.fromJson(json['range']) : null;
-    final name = json['name'];
-    final kind = json['kind'];
-    final parameters = json['parameters'];
-    final typeParameters = json['typeParameters'];
-    final returnType = json['returnType'];
+  static Element fromJson(Map<String, Object?> json) {
+    final rangeJson = json['range'];
+    final range = rangeJson != null
+        ? Range.fromJson(rangeJson as Map<String, Object?>)
+        : null;
+    final nameJson = json['name'];
+    final name = nameJson as String;
+    final kindJson = json['kind'];
+    final kind = kindJson as String;
+    final parametersJson = json['parameters'];
+    final parameters = parametersJson as String?;
+    final typeParametersJson = json['typeParameters'];
+    final typeParameters = typeParametersJson as String?;
+    final returnTypeJson = json['returnType'];
+    final returnType = returnTypeJson as String?;
     return Element(
         range: range,
         name: name,
@@ -571,8 +605,8 @@
   final String? returnType;
   final String? typeParameters;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (range != null) {
       __result['range'] = range?.toJson();
     }
@@ -591,10 +625,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('range');
       try {
-        if (obj['range'] != null && !(Range.canParse(obj['range'], reporter))) {
+        final range = obj['range'];
+        if (range != null && !(Range.canParse(range, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -607,11 +642,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['name'] == null) {
+        final name = obj['name'];
+        if (name == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['name'] is String)) {
+        if (!(name is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -624,11 +660,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['kind'] == null) {
+        final kind = obj['kind'];
+        if (kind == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['kind'] is String)) {
+        if (!(kind is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -637,7 +674,8 @@
       }
       reporter.push('parameters');
       try {
-        if (obj['parameters'] != null && !(obj['parameters'] is String)) {
+        final parameters = obj['parameters'];
+        if (parameters != null && !(parameters is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -646,8 +684,8 @@
       }
       reporter.push('typeParameters');
       try {
-        if (obj['typeParameters'] != null &&
-            !(obj['typeParameters'] is String)) {
+        final typeParameters = obj['typeParameters'];
+        if (typeParameters != null && !(typeParameters is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -656,7 +694,8 @@
       }
       reporter.push('returnType');
       try {
-        if (obj['returnType'] != null && !(obj['returnType'] is String)) {
+        final returnType = obj['returnType'];
+        if (returnType != null && !(returnType is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -714,25 +753,32 @@
       required this.range,
       required this.codeRange,
       this.children});
-  static FlutterOutline fromJson(Map<String, dynamic> json) {
-    final kind = json['kind'];
-    final label = json['label'];
-    final className = json['className'];
-    final variableName = json['variableName'];
-    final attributes = json['attributes']
+  static FlutterOutline fromJson(Map<String, Object?> json) {
+    final kindJson = json['kind'];
+    final kind = kindJson as String;
+    final labelJson = json['label'];
+    final label = labelJson as String?;
+    final classNameJson = json['className'];
+    final className = classNameJson as String?;
+    final variableNameJson = json['variableName'];
+    final variableName = variableNameJson as String?;
+    final attributesJson = json['attributes'];
+    final attributes = (attributesJson as List<Object?>?)
         ?.map((item) =>
-            item != null ? FlutterOutlineAttribute.fromJson(item) : null)
-        ?.cast<FlutterOutlineAttribute>()
-        ?.toList();
-    final dartElement = json['dartElement'] != null
-        ? Element.fromJson(json['dartElement'])
+            FlutterOutlineAttribute.fromJson(item as Map<String, Object?>))
+        .toList();
+    final dartElementJson = json['dartElement'];
+    final dartElement = dartElementJson != null
+        ? Element.fromJson(dartElementJson as Map<String, Object?>)
         : null;
-    final range = Range.fromJson(json['range']);
-    final codeRange = Range.fromJson(json['codeRange']);
-    final children = json['children']
-        ?.map((item) => item != null ? FlutterOutline.fromJson(item) : null)
-        ?.cast<FlutterOutline>()
-        ?.toList();
+    final rangeJson = json['range'];
+    final range = Range.fromJson(rangeJson as Map<String, Object?>);
+    final codeRangeJson = json['codeRange'];
+    final codeRange = Range.fromJson(codeRangeJson as Map<String, Object?>);
+    final childrenJson = json['children'];
+    final children = (childrenJson as List<Object?>?)
+        ?.map((item) => FlutterOutline.fromJson(item as Map<String, Object?>))
+        .toList();
     return FlutterOutline(
         kind: kind,
         label: label,
@@ -755,8 +801,8 @@
   final Range range;
   final String? variableName;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['kind'] = kind;
     if (label != null) {
       __result['label'] = label;
@@ -783,18 +829,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('kind');
       try {
         if (!obj.containsKey('kind')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['kind'] == null) {
+        final kind = obj['kind'];
+        if (kind == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['kind'] is String)) {
+        if (!(kind is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -803,7 +850,8 @@
       }
       reporter.push('label');
       try {
-        if (obj['label'] != null && !(obj['label'] is String)) {
+        final label = obj['label'];
+        if (label != null && !(label is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -812,7 +860,8 @@
       }
       reporter.push('className');
       try {
-        if (obj['className'] != null && !(obj['className'] is String)) {
+        final className = obj['className'];
+        if (className != null && !(className is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -821,7 +870,8 @@
       }
       reporter.push('variableName');
       try {
-        if (obj['variableName'] != null && !(obj['variableName'] is String)) {
+        final variableName = obj['variableName'];
+        if (variableName != null && !(variableName is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -830,9 +880,10 @@
       }
       reporter.push('attributes');
       try {
-        if (obj['attributes'] != null &&
-            !((obj['attributes'] is List &&
-                (obj['attributes'].every((item) =>
+        final attributes = obj['attributes'];
+        if (attributes != null &&
+            !((attributes is List &&
+                (attributes.every((item) =>
                     FlutterOutlineAttribute.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<FlutterOutlineAttribute>');
           return false;
@@ -842,8 +893,8 @@
       }
       reporter.push('dartElement');
       try {
-        if (obj['dartElement'] != null &&
-            !(Element.canParse(obj['dartElement'], reporter))) {
+        final dartElement = obj['dartElement'];
+        if (dartElement != null && !(Element.canParse(dartElement, reporter))) {
           reporter.reportError('must be of type Element');
           return false;
         }
@@ -856,11 +907,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['range'] == null) {
+        final range = obj['range'];
+        if (range == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['range'], reporter))) {
+        if (!(Range.canParse(range, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -873,11 +925,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['codeRange'] == null) {
+        final codeRange = obj['codeRange'];
+        if (codeRange == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['codeRange'], reporter))) {
+        if (!(Range.canParse(codeRange, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -886,9 +939,10 @@
       }
       reporter.push('children');
       try {
-        if (obj['children'] != null &&
-            !((obj['children'] is List &&
-                (obj['children'].every(
+        final children = obj['children'];
+        if (children != null &&
+            !((children is List &&
+                (children.every(
                     (item) => FlutterOutline.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<FlutterOutline>');
           return false;
@@ -950,11 +1004,15 @@
 
   FlutterOutlineAttribute(
       {required this.name, required this.label, this.valueRange});
-  static FlutterOutlineAttribute fromJson(Map<String, dynamic> json) {
-    final name = json['name'];
-    final label = json['label'];
-    final valueRange =
-        json['valueRange'] != null ? Range.fromJson(json['valueRange']) : null;
+  static FlutterOutlineAttribute fromJson(Map<String, Object?> json) {
+    final nameJson = json['name'];
+    final name = nameJson as String;
+    final labelJson = json['label'];
+    final label = labelJson as String;
+    final valueRangeJson = json['valueRange'];
+    final valueRange = valueRangeJson != null
+        ? Range.fromJson(valueRangeJson as Map<String, Object?>)
+        : null;
     return FlutterOutlineAttribute(
         name: name, label: label, valueRange: valueRange);
   }
@@ -963,8 +1021,8 @@
   final String name;
   final Range? valueRange;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['name'] = name;
     __result['label'] = label;
     if (valueRange != null) {
@@ -974,18 +1032,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('name');
       try {
         if (!obj.containsKey('name')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['name'] == null) {
+        final name = obj['name'];
+        if (name == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['name'] is String)) {
+        if (!(name is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -998,11 +1057,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['label'] == null) {
+        final label = obj['label'];
+        if (label == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['label'] is String)) {
+        if (!(label is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -1011,8 +1071,8 @@
       }
       reporter.push('valueRange');
       try {
-        if (obj['valueRange'] != null &&
-            !(Range.canParse(obj['valueRange'], reporter))) {
+        final valueRange = obj['valueRange'];
+        if (valueRange != null && !(Range.canParse(valueRange, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -1059,14 +1119,17 @@
       required this.range,
       required this.codeRange,
       this.children});
-  static Outline fromJson(Map<String, dynamic> json) {
-    final element = Element.fromJson(json['element']);
-    final range = Range.fromJson(json['range']);
-    final codeRange = Range.fromJson(json['codeRange']);
-    final children = json['children']
-        ?.map((item) => item != null ? Outline.fromJson(item) : null)
-        ?.cast<Outline>()
-        ?.toList();
+  static Outline fromJson(Map<String, Object?> json) {
+    final elementJson = json['element'];
+    final element = Element.fromJson(elementJson as Map<String, Object?>);
+    final rangeJson = json['range'];
+    final range = Range.fromJson(rangeJson as Map<String, Object?>);
+    final codeRangeJson = json['codeRange'];
+    final codeRange = Range.fromJson(codeRangeJson as Map<String, Object?>);
+    final childrenJson = json['children'];
+    final children = (childrenJson as List<Object?>?)
+        ?.map((item) => Outline.fromJson(item as Map<String, Object?>))
+        .toList();
     return Outline(
         element: element,
         range: range,
@@ -1079,8 +1142,8 @@
   final Element element;
   final Range range;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['element'] = element.toJson();
     __result['range'] = range.toJson();
     __result['codeRange'] = codeRange.toJson();
@@ -1091,18 +1154,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('element');
       try {
         if (!obj.containsKey('element')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['element'] == null) {
+        final element = obj['element'];
+        if (element == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Element.canParse(obj['element'], reporter))) {
+        if (!(Element.canParse(element, reporter))) {
           reporter.reportError('must be of type Element');
           return false;
         }
@@ -1115,11 +1179,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['range'] == null) {
+        final range = obj['range'];
+        if (range == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['range'], reporter))) {
+        if (!(Range.canParse(range, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -1132,11 +1197,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['codeRange'] == null) {
+        final codeRange = obj['codeRange'];
+        if (codeRange == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['codeRange'], reporter))) {
+        if (!(Range.canParse(codeRange, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -1145,9 +1211,10 @@
       }
       reporter.push('children');
       try {
-        if (obj['children'] != null &&
-            !((obj['children'] is List &&
-                (obj['children']
+        final children = obj['children'];
+        if (children != null &&
+            !((children is List &&
+                (children
                     .every((item) => Outline.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<Outline>');
           return false;
@@ -1198,10 +1265,13 @@
   PubPackageCompletionItemResolutionInfo(
       {required this.packageName, required this.file, required this.offset});
   static PubPackageCompletionItemResolutionInfo fromJson(
-      Map<String, dynamic> json) {
-    final packageName = json['packageName'];
-    final file = json['file'];
-    final offset = json['offset'];
+      Map<String, Object?> json) {
+    final packageNameJson = json['packageName'];
+    final packageName = packageNameJson as String;
+    final fileJson = json['file'];
+    final file = fileJson as String;
+    final offsetJson = json['offset'];
+    final offset = offsetJson as int;
     return PubPackageCompletionItemResolutionInfo(
         packageName: packageName, file: file, offset: offset);
   }
@@ -1210,8 +1280,8 @@
   final int offset;
   final String packageName;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['packageName'] = packageName;
     __result['file'] = file;
     __result['offset'] = offset;
@@ -1219,18 +1289,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('packageName');
       try {
         if (!obj.containsKey('packageName')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['packageName'] == null) {
+        final packageName = obj['packageName'];
+        if (packageName == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['packageName'] is String)) {
+        if (!(packageName is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -1243,11 +1314,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['file'] == null) {
+        final file = obj['file'];
+        if (file == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['file'] is String)) {
+        if (!(file is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -1260,11 +1332,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['offset'] == null) {
+        final offset = obj['offset'];
+        if (offset == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['offset'] is int)) {
+        if (!(offset is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -1309,38 +1382,40 @@
       PublishClosingLabelsParams.canParse, PublishClosingLabelsParams.fromJson);
 
   PublishClosingLabelsParams({required this.uri, required this.labels});
-  static PublishClosingLabelsParams fromJson(Map<String, dynamic> json) {
-    final uri = json['uri'];
-    final labels = json['labels']
-        ?.map((item) => ClosingLabel.fromJson(item))
-        ?.cast<ClosingLabel>()
-        ?.toList();
+  static PublishClosingLabelsParams fromJson(Map<String, Object?> json) {
+    final uriJson = json['uri'];
+    final uri = uriJson as String;
+    final labelsJson = json['labels'];
+    final labels = (labelsJson as List<Object?>)
+        .map((item) => ClosingLabel.fromJson(item as Map<String, Object?>))
+        .toList();
     return PublishClosingLabelsParams(uri: uri, labels: labels);
   }
 
   final List<ClosingLabel> labels;
   final String uri;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['uri'] = uri;
     __result['labels'] = labels.map((item) => item.toJson()).toList();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('uri');
       try {
         if (!obj.containsKey('uri')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['uri'] == null) {
+        final uri = obj['uri'];
+        if (uri == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['uri'] is String)) {
+        if (!(uri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -1353,13 +1428,13 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['labels'] == null) {
+        final labels = obj['labels'];
+        if (labels == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['labels'] is List &&
-            (obj['labels']
-                .every((item) => ClosingLabel.canParse(item, reporter)))))) {
+        if (!((labels is List &&
+            (labels.every((item) => ClosingLabel.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<ClosingLabel>');
           return false;
         }
@@ -1403,35 +1478,39 @@
       PublishFlutterOutlineParams.fromJson);
 
   PublishFlutterOutlineParams({required this.uri, required this.outline});
-  static PublishFlutterOutlineParams fromJson(Map<String, dynamic> json) {
-    final uri = json['uri'];
-    final outline = FlutterOutline.fromJson(json['outline']);
+  static PublishFlutterOutlineParams fromJson(Map<String, Object?> json) {
+    final uriJson = json['uri'];
+    final uri = uriJson as String;
+    final outlineJson = json['outline'];
+    final outline =
+        FlutterOutline.fromJson(outlineJson as Map<String, Object?>);
     return PublishFlutterOutlineParams(uri: uri, outline: outline);
   }
 
   final FlutterOutline outline;
   final String uri;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['uri'] = uri;
     __result['outline'] = outline.toJson();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('uri');
       try {
         if (!obj.containsKey('uri')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['uri'] == null) {
+        final uri = obj['uri'];
+        if (uri == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['uri'] is String)) {
+        if (!(uri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -1444,11 +1523,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['outline'] == null) {
+        final outline = obj['outline'];
+        if (outline == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(FlutterOutline.canParse(obj['outline'], reporter))) {
+        if (!(FlutterOutline.canParse(outline, reporter))) {
           reporter.reportError('must be of type FlutterOutline');
           return false;
         }
@@ -1488,35 +1568,38 @@
       PublishOutlineParams.canParse, PublishOutlineParams.fromJson);
 
   PublishOutlineParams({required this.uri, required this.outline});
-  static PublishOutlineParams fromJson(Map<String, dynamic> json) {
-    final uri = json['uri'];
-    final outline = Outline.fromJson(json['outline']);
+  static PublishOutlineParams fromJson(Map<String, Object?> json) {
+    final uriJson = json['uri'];
+    final uri = uriJson as String;
+    final outlineJson = json['outline'];
+    final outline = Outline.fromJson(outlineJson as Map<String, Object?>);
     return PublishOutlineParams(uri: uri, outline: outline);
   }
 
   final Outline outline;
   final String uri;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['uri'] = uri;
     __result['outline'] = outline.toJson();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('uri');
       try {
         if (!obj.containsKey('uri')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['uri'] == null) {
+        final uri = obj['uri'];
+        if (uri == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['uri'] is String)) {
+        if (!(uri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -1529,11 +1612,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['outline'] == null) {
+        final outline = obj['outline'];
+        if (outline == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Outline.canParse(obj['outline'], reporter))) {
+        if (!(Outline.canParse(outline, reporter))) {
           reporter.reportError('must be of type Outline');
           return false;
         }
@@ -1576,11 +1660,14 @@
       {required this.insertTextFormat,
       required this.range,
       required this.newText});
-  static SnippetTextEdit fromJson(Map<String, dynamic> json) {
+  static SnippetTextEdit fromJson(Map<String, Object?> json) {
+    final insertTextFormatJson = json['insertTextFormat'];
     final insertTextFormat =
-        InsertTextFormat.fromJson(json['insertTextFormat']);
-    final range = Range.fromJson(json['range']);
-    final newText = json['newText'];
+        InsertTextFormat.fromJson(insertTextFormatJson as int);
+    final rangeJson = json['range'];
+    final range = Range.fromJson(rangeJson as Map<String, Object?>);
+    final newTextJson = json['newText'];
+    final newText = newTextJson as String;
     return SnippetTextEdit(
         insertTextFormat: insertTextFormat, range: range, newText: newText);
   }
@@ -1594,8 +1681,8 @@
   /// document create a range where start === end.
   final Range range;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['insertTextFormat'] = insertTextFormat.toJson();
     __result['range'] = range.toJson();
     __result['newText'] = newText;
@@ -1603,18 +1690,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('insertTextFormat');
       try {
         if (!obj.containsKey('insertTextFormat')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['insertTextFormat'] == null) {
+        final insertTextFormat = obj['insertTextFormat'];
+        if (insertTextFormat == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(InsertTextFormat.canParse(obj['insertTextFormat'], reporter))) {
+        if (!(InsertTextFormat.canParse(insertTextFormat, reporter))) {
           reporter.reportError('must be of type InsertTextFormat');
           return false;
         }
@@ -1627,11 +1715,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['range'] == null) {
+        final range = obj['range'];
+        if (range == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['range'], reporter))) {
+        if (!(Range.canParse(range, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -1644,11 +1733,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['newText'] == null) {
+        final newText = obj['newText'];
+        if (newText == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['newText'] is String)) {
+        if (!(newText is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
diff --git a/pkg/analysis_server/lib/lsp_protocol/protocol_generated.dart b/pkg/analysis_server/lib/lsp_protocol/protocol_generated.dart
index 99fa136..f40ac85 100644
--- a/pkg/analysis_server/lib/lsp_protocol/protocol_generated.dart
+++ b/pkg/analysis_server/lib/lsp_protocol/protocol_generated.dart
@@ -28,10 +28,13 @@
 
   AnnotatedTextEdit(
       {required this.annotationId, required this.range, required this.newText});
-  static AnnotatedTextEdit fromJson(Map<String, dynamic> json) {
-    final annotationId = json['annotationId'];
-    final range = Range.fromJson(json['range']);
-    final newText = json['newText'];
+  static AnnotatedTextEdit fromJson(Map<String, Object?> json) {
+    final annotationIdJson = json['annotationId'];
+    final annotationId = annotationIdJson as String;
+    final rangeJson = json['range'];
+    final range = Range.fromJson(rangeJson as Map<String, Object?>);
+    final newTextJson = json['newText'];
+    final newText = newTextJson as String;
     return AnnotatedTextEdit(
         annotationId: annotationId, range: range, newText: newText);
   }
@@ -46,8 +49,8 @@
   /// document create a range where start === end.
   final Range range;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['annotationId'] = annotationId;
     __result['range'] = range.toJson();
     __result['newText'] = newText;
@@ -55,18 +58,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('annotationId');
       try {
         if (!obj.containsKey('annotationId')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['annotationId'] == null) {
+        final annotationId = obj['annotationId'];
+        if (annotationId == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['annotationId'] is String)) {
+        if (!(annotationId is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -79,11 +83,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['range'] == null) {
+        final range = obj['range'];
+        if (range == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['range'], reporter))) {
+        if (!(Range.canParse(range, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -96,11 +101,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['newText'] == null) {
+        final newText = obj['newText'];
+        if (newText == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['newText'] is String)) {
+        if (!(newText is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -143,9 +149,11 @@
       ApplyWorkspaceEditParams.canParse, ApplyWorkspaceEditParams.fromJson);
 
   ApplyWorkspaceEditParams({this.label, required this.edit});
-  static ApplyWorkspaceEditParams fromJson(Map<String, dynamic> json) {
-    final label = json['label'];
-    final edit = WorkspaceEdit.fromJson(json['edit']);
+  static ApplyWorkspaceEditParams fromJson(Map<String, Object?> json) {
+    final labelJson = json['label'];
+    final label = labelJson as String?;
+    final editJson = json['edit'];
+    final edit = WorkspaceEdit.fromJson(editJson as Map<String, Object?>);
     return ApplyWorkspaceEditParams(label: label, edit: edit);
   }
 
@@ -156,8 +164,8 @@
   /// user interface for example on an undo stack to undo the workspace edit.
   final String? label;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (label != null) {
       __result['label'] = label;
     }
@@ -166,10 +174,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('label');
       try {
-        if (obj['label'] != null && !(obj['label'] is String)) {
+        final label = obj['label'];
+        if (label != null && !(label is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -182,11 +191,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['edit'] == null) {
+        final edit = obj['edit'];
+        if (edit == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(WorkspaceEdit.canParse(obj['edit'], reporter))) {
+        if (!(WorkspaceEdit.canParse(edit, reporter))) {
           reporter.reportError('must be of type WorkspaceEdit');
           return false;
         }
@@ -227,10 +237,13 @@
 
   ApplyWorkspaceEditResponse(
       {required this.applied, this.failureReason, this.failedChange});
-  static ApplyWorkspaceEditResponse fromJson(Map<String, dynamic> json) {
-    final applied = json['applied'];
-    final failureReason = json['failureReason'];
-    final failedChange = json['failedChange'];
+  static ApplyWorkspaceEditResponse fromJson(Map<String, Object?> json) {
+    final appliedJson = json['applied'];
+    final applied = appliedJson as bool;
+    final failureReasonJson = json['failureReason'];
+    final failureReason = failureReasonJson as String?;
+    final failedChangeJson = json['failedChange'];
+    final failedChange = failedChangeJson as int?;
     return ApplyWorkspaceEditResponse(
         applied: applied,
         failureReason: failureReason,
@@ -251,8 +264,8 @@
   /// error for a request that triggered the edit.
   final String? failureReason;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['applied'] = applied;
     if (failureReason != null) {
       __result['failureReason'] = failureReason;
@@ -264,18 +277,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('applied');
       try {
         if (!obj.containsKey('applied')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['applied'] == null) {
+        final applied = obj['applied'];
+        if (applied == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['applied'] is bool)) {
+        if (!(applied is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -284,7 +298,8 @@
       }
       reporter.push('failureReason');
       try {
-        if (obj['failureReason'] != null && !(obj['failureReason'] is String)) {
+        final failureReason = obj['failureReason'];
+        if (failureReason != null && !(failureReason is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -293,7 +308,8 @@
       }
       reporter.push('failedChange');
       try {
-        if (obj['failedChange'] != null && !(obj['failedChange'] is int)) {
+        final failedChange = obj['failedChange'];
+        if (failedChange != null && !(failedChange is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -338,8 +354,9 @@
       CallHierarchyClientCapabilities.fromJson);
 
   CallHierarchyClientCapabilities({this.dynamicRegistration});
-  static CallHierarchyClientCapabilities fromJson(Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
+  static CallHierarchyClientCapabilities fromJson(Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
     return CallHierarchyClientCapabilities(
         dynamicRegistration: dynamicRegistration);
   }
@@ -350,8 +367,8 @@
   /// capability as well.
   final bool? dynamicRegistration;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -359,11 +376,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -402,12 +419,13 @@
       CallHierarchyIncomingCall.canParse, CallHierarchyIncomingCall.fromJson);
 
   CallHierarchyIncomingCall({required this.from, required this.fromRanges});
-  static CallHierarchyIncomingCall fromJson(Map<String, dynamic> json) {
-    final from = CallHierarchyItem.fromJson(json['from']);
-    final fromRanges = json['fromRanges']
-        ?.map((item) => Range.fromJson(item))
-        ?.cast<Range>()
-        ?.toList();
+  static CallHierarchyIncomingCall fromJson(Map<String, Object?> json) {
+    final fromJson = json['from'];
+    final from = CallHierarchyItem.fromJson(fromJson as Map<String, Object?>);
+    final fromRangesJson = json['fromRanges'];
+    final fromRanges = (fromRangesJson as List<Object?>)
+        .map((item) => Range.fromJson(item as Map<String, Object?>))
+        .toList();
     return CallHierarchyIncomingCall(from: from, fromRanges: fromRanges);
   }
 
@@ -418,26 +436,27 @@
   /// denoted by [`this.from`](#CallHierarchyIncomingCall.from).
   final List<Range> fromRanges;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['from'] = from.toJson();
     __result['fromRanges'] = fromRanges.map((item) => item.toJson()).toList();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('from');
       try {
         if (!obj.containsKey('from')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['from'] == null) {
+        final from = obj['from'];
+        if (from == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(CallHierarchyItem.canParse(obj['from'], reporter))) {
+        if (!(CallHierarchyItem.canParse(from, reporter))) {
           reporter.reportError('must be of type CallHierarchyItem');
           return false;
         }
@@ -450,13 +469,13 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['fromRanges'] == null) {
+        final fromRanges = obj['fromRanges'];
+        if (fromRanges == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['fromRanges'] is List &&
-            (obj['fromRanges']
-                .every((item) => Range.canParse(item, reporter)))))) {
+        if (!((fromRanges is List &&
+            (fromRanges.every((item) => Range.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<Range>');
           return false;
         }
@@ -502,22 +521,25 @@
 
   CallHierarchyIncomingCallsParams(
       {required this.item, this.workDoneToken, this.partialResultToken});
-  static CallHierarchyIncomingCallsParams fromJson(Map<String, dynamic> json) {
-    final item = CallHierarchyItem.fromJson(json['item']);
-    final workDoneToken = json['workDoneToken'] == null
+  static CallHierarchyIncomingCallsParams fromJson(Map<String, Object?> json) {
+    final itemJson = json['item'];
+    final item = CallHierarchyItem.fromJson(itemJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
-    final partialResultToken = json['partialResultToken'] == null
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
+    final partialResultTokenJson = json['partialResultToken'];
+    final partialResultToken = partialResultTokenJson == null
         ? null
-        : (json['partialResultToken'] is int
-            ? Either2<int, String>.t1(json['partialResultToken'])
-            : (json['partialResultToken'] is String
-                ? Either2<int, String>.t2(json['partialResultToken'])
-                : (throw '''${json['partialResultToken']} was not one of (int, String)''')));
+        : (partialResultTokenJson is int
+            ? Either2<int, String>.t1(partialResultTokenJson)
+            : (partialResultTokenJson is String
+                ? Either2<int, String>.t2(partialResultTokenJson)
+                : (throw '''$partialResultTokenJson was not one of (int, String)''')));
     return CallHierarchyIncomingCallsParams(
         item: item,
         workDoneToken: workDoneToken,
@@ -533,8 +555,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['item'] = item.toJson();
     if (workDoneToken != null) {
       __result['workDoneToken'] = workDoneToken;
@@ -546,18 +568,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('item');
       try {
         if (!obj.containsKey('item')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['item'] == null) {
+        final item = obj['item'];
+        if (item == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(CallHierarchyItem.canParse(obj['item'], reporter))) {
+        if (!(CallHierarchyItem.canParse(item, reporter))) {
           reporter.reportError('must be of type CallHierarchyItem');
           return false;
         }
@@ -566,9 +589,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -577,9 +600,9 @@
       }
       reporter.push('partialResultToken');
       try {
-        if (obj['partialResultToken'] != null &&
-            !((obj['partialResultToken'] is int ||
-                obj['partialResultToken'] is String))) {
+        final partialResultToken = obj['partialResultToken'];
+        if (partialResultToken != null &&
+            !((partialResultToken is int || partialResultToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -631,18 +654,26 @@
       required this.range,
       required this.selectionRange,
       this.data});
-  static CallHierarchyItem fromJson(Map<String, dynamic> json) {
-    final name = json['name'];
-    final kind = SymbolKind.fromJson(json['kind']);
-    final tags = json['tags']
-        ?.map((item) => item != null ? SymbolTag.fromJson(item) : null)
-        ?.cast<SymbolTag>()
-        ?.toList();
-    final detail = json['detail'];
-    final uri = json['uri'];
-    final range = Range.fromJson(json['range']);
-    final selectionRange = Range.fromJson(json['selectionRange']);
-    final data = json['data'];
+  static CallHierarchyItem fromJson(Map<String, Object?> json) {
+    final nameJson = json['name'];
+    final name = nameJson as String;
+    final kindJson = json['kind'];
+    final kind = SymbolKind.fromJson(kindJson as int);
+    final tagsJson = json['tags'];
+    final tags = (tagsJson as List<Object?>?)
+        ?.map((item) => SymbolTag.fromJson(item as num))
+        .toList();
+    final detailJson = json['detail'];
+    final detail = detailJson as String?;
+    final uriJson = json['uri'];
+    final uri = uriJson as String;
+    final rangeJson = json['range'];
+    final range = Range.fromJson(rangeJson as Map<String, Object?>);
+    final selectionRangeJson = json['selectionRange'];
+    final selectionRange =
+        Range.fromJson(selectionRangeJson as Map<String, Object?>);
+    final dataJson = json['data'];
+    final data = dataJson;
     return CallHierarchyItem(
         name: name,
         kind: kind,
@@ -656,7 +687,7 @@
 
   /// A data entry field that is preserved between a call hierarchy prepare and
   /// incoming calls or outgoing calls requests.
-  final dynamic data;
+  final Object? data;
 
   /// More detail for this item, e.g. the signature of a function.
   final String? detail;
@@ -682,8 +713,8 @@
   /// The resource identifier of this item.
   final String uri;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['name'] = name;
     __result['kind'] = kind.toJson();
     if (tags != null) {
@@ -702,18 +733,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('name');
       try {
         if (!obj.containsKey('name')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['name'] == null) {
+        final name = obj['name'];
+        if (name == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['name'] is String)) {
+        if (!(name is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -726,11 +758,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['kind'] == null) {
+        final kind = obj['kind'];
+        if (kind == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(SymbolKind.canParse(obj['kind'], reporter))) {
+        if (!(SymbolKind.canParse(kind, reporter))) {
           reporter.reportError('must be of type SymbolKind');
           return false;
         }
@@ -739,10 +772,10 @@
       }
       reporter.push('tags');
       try {
-        if (obj['tags'] != null &&
-            !((obj['tags'] is List &&
-                (obj['tags']
-                    .every((item) => SymbolTag.canParse(item, reporter)))))) {
+        final tags = obj['tags'];
+        if (tags != null &&
+            !((tags is List &&
+                (tags.every((item) => SymbolTag.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<SymbolTag>');
           return false;
         }
@@ -751,7 +784,8 @@
       }
       reporter.push('detail');
       try {
-        if (obj['detail'] != null && !(obj['detail'] is String)) {
+        final detail = obj['detail'];
+        if (detail != null && !(detail is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -764,11 +798,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['uri'] == null) {
+        final uri = obj['uri'];
+        if (uri == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['uri'] is String)) {
+        if (!(uri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -781,11 +816,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['range'] == null) {
+        final range = obj['range'];
+        if (range == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['range'], reporter))) {
+        if (!(Range.canParse(range, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -798,11 +834,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['selectionRange'] == null) {
+        final selectionRange = obj['selectionRange'];
+        if (selectionRange == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['selectionRange'], reporter))) {
+        if (!(Range.canParse(selectionRange, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -855,18 +892,19 @@
       CallHierarchyOptions.canParse, CallHierarchyOptions.fromJson);
 
   CallHierarchyOptions({this.workDoneProgress});
-  static CallHierarchyOptions fromJson(Map<String, dynamic> json) {
+  static CallHierarchyOptions fromJson(Map<String, Object?> json) {
     if (CallHierarchyRegistrationOptions.canParse(json, nullLspJsonReporter)) {
       return CallHierarchyRegistrationOptions.fromJson(json);
     }
-    final workDoneProgress = json['workDoneProgress'];
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return CallHierarchyOptions(workDoneProgress: workDoneProgress);
   }
 
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
     }
@@ -874,11 +912,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -917,12 +955,13 @@
       CallHierarchyOutgoingCall.canParse, CallHierarchyOutgoingCall.fromJson);
 
   CallHierarchyOutgoingCall({required this.to, required this.fromRanges});
-  static CallHierarchyOutgoingCall fromJson(Map<String, dynamic> json) {
-    final to = CallHierarchyItem.fromJson(json['to']);
-    final fromRanges = json['fromRanges']
-        ?.map((item) => Range.fromJson(item))
-        ?.cast<Range>()
-        ?.toList();
+  static CallHierarchyOutgoingCall fromJson(Map<String, Object?> json) {
+    final toJson = json['to'];
+    final to = CallHierarchyItem.fromJson(toJson as Map<String, Object?>);
+    final fromRangesJson = json['fromRanges'];
+    final fromRanges = (fromRangesJson as List<Object?>)
+        .map((item) => Range.fromJson(item as Map<String, Object?>))
+        .toList();
     return CallHierarchyOutgoingCall(to: to, fromRanges: fromRanges);
   }
 
@@ -933,26 +972,27 @@
   /// The item that is called.
   final CallHierarchyItem to;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['to'] = to.toJson();
     __result['fromRanges'] = fromRanges.map((item) => item.toJson()).toList();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('to');
       try {
         if (!obj.containsKey('to')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['to'] == null) {
+        final to = obj['to'];
+        if (to == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(CallHierarchyItem.canParse(obj['to'], reporter))) {
+        if (!(CallHierarchyItem.canParse(to, reporter))) {
           reporter.reportError('must be of type CallHierarchyItem');
           return false;
         }
@@ -965,13 +1005,13 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['fromRanges'] == null) {
+        final fromRanges = obj['fromRanges'];
+        if (fromRanges == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['fromRanges'] is List &&
-            (obj['fromRanges']
-                .every((item) => Range.canParse(item, reporter)))))) {
+        if (!((fromRanges is List &&
+            (fromRanges.every((item) => Range.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<Range>');
           return false;
         }
@@ -1017,22 +1057,25 @@
 
   CallHierarchyOutgoingCallsParams(
       {required this.item, this.workDoneToken, this.partialResultToken});
-  static CallHierarchyOutgoingCallsParams fromJson(Map<String, dynamic> json) {
-    final item = CallHierarchyItem.fromJson(json['item']);
-    final workDoneToken = json['workDoneToken'] == null
+  static CallHierarchyOutgoingCallsParams fromJson(Map<String, Object?> json) {
+    final itemJson = json['item'];
+    final item = CallHierarchyItem.fromJson(itemJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
-    final partialResultToken = json['partialResultToken'] == null
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
+    final partialResultTokenJson = json['partialResultToken'];
+    final partialResultToken = partialResultTokenJson == null
         ? null
-        : (json['partialResultToken'] is int
-            ? Either2<int, String>.t1(json['partialResultToken'])
-            : (json['partialResultToken'] is String
-                ? Either2<int, String>.t2(json['partialResultToken'])
-                : (throw '''${json['partialResultToken']} was not one of (int, String)''')));
+        : (partialResultTokenJson is int
+            ? Either2<int, String>.t1(partialResultTokenJson)
+            : (partialResultTokenJson is String
+                ? Either2<int, String>.t2(partialResultTokenJson)
+                : (throw '''$partialResultTokenJson was not one of (int, String)''')));
     return CallHierarchyOutgoingCallsParams(
         item: item,
         workDoneToken: workDoneToken,
@@ -1048,8 +1091,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['item'] = item.toJson();
     if (workDoneToken != null) {
       __result['workDoneToken'] = workDoneToken;
@@ -1061,18 +1104,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('item');
       try {
         if (!obj.containsKey('item')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['item'] == null) {
+        final item = obj['item'];
+        if (item == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(CallHierarchyItem.canParse(obj['item'], reporter))) {
+        if (!(CallHierarchyItem.canParse(item, reporter))) {
           reporter.reportError('must be of type CallHierarchyItem');
           return false;
         }
@@ -1081,9 +1125,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -1092,9 +1136,9 @@
       }
       reporter.push('partialResultToken');
       try {
-        if (obj['partialResultToken'] != null &&
-            !((obj['partialResultToken'] is int ||
-                obj['partialResultToken'] is String))) {
+        final partialResultToken = obj['partialResultToken'];
+        if (partialResultToken != null &&
+            !((partialResultToken is int || partialResultToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -1140,16 +1184,20 @@
 
   CallHierarchyPrepareParams(
       {required this.textDocument, required this.position, this.workDoneToken});
-  static CallHierarchyPrepareParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final position = Position.fromJson(json['position']);
-    final workDoneToken = json['workDoneToken'] == null
+  static CallHierarchyPrepareParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final positionJson = json['position'];
+    final position = Position.fromJson(positionJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
     return CallHierarchyPrepareParams(
         textDocument: textDocument,
         position: position,
@@ -1165,8 +1213,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     __result['position'] = position.toJson();
     if (workDoneToken != null) {
@@ -1176,18 +1224,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -1200,11 +1249,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['position'] == null) {
+        final position = obj['position'];
+        if (position == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Position.canParse(obj['position'], reporter))) {
+        if (!(Position.canParse(position, reporter))) {
           reporter.reportError('must be of type Position');
           return false;
         }
@@ -1213,9 +1263,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -1266,13 +1316,15 @@
 
   CallHierarchyRegistrationOptions(
       {this.documentSelector, this.workDoneProgress, this.id});
-  static CallHierarchyRegistrationOptions fromJson(Map<String, dynamic> json) {
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final workDoneProgress = json['workDoneProgress'];
-    final id = json['id'];
+  static CallHierarchyRegistrationOptions fromJson(Map<String, Object?> json) {
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
+    final idJson = json['id'];
+    final id = idJson as String?;
     return CallHierarchyRegistrationOptions(
         documentSelector: documentSelector,
         workDoneProgress: workDoneProgress,
@@ -1288,8 +1340,8 @@
   final String? id;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['documentSelector'] = documentSelector;
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
@@ -1301,16 +1353,17 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentSelector');
       try {
         if (!obj.containsKey('documentSelector')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -1320,8 +1373,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -1330,7 +1383,8 @@
       }
       reporter.push('id');
       try {
-        if (obj['id'] != null && !(obj['id'] is String)) {
+        final id = obj['id'];
+        if (id != null && !(id is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -1375,37 +1429,39 @@
       LspJsonHandler(CancelParams.canParse, CancelParams.fromJson);
 
   CancelParams({required this.id});
-  static CancelParams fromJson(Map<String, dynamic> json) {
-    final id = json['id'] is int
-        ? Either2<int, String>.t1(json['id'])
-        : (json['id'] is String
-            ? Either2<int, String>.t2(json['id'])
-            : (throw '''${json['id']} was not one of (int, String)'''));
+  static CancelParams fromJson(Map<String, Object?> json) {
+    final idJson = json['id'];
+    final id = idJson is int
+        ? Either2<int, String>.t1(idJson)
+        : (idJson is String
+            ? Either2<int, String>.t2(idJson)
+            : (throw '''$idJson was not one of (int, String)'''));
     return CancelParams(id: id);
   }
 
   /// The request id to cancel.
   final Either2<int, String> id;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['id'] = id;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('id');
       try {
         if (!obj.containsKey('id')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['id'] == null) {
+        final id = obj['id'];
+        if (id == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['id'] is int || obj['id'] is String))) {
+        if (!((id is int || id is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -1446,10 +1502,13 @@
 
   ChangeAnnotation(
       {required this.label, this.needsConfirmation, this.description});
-  static ChangeAnnotation fromJson(Map<String, dynamic> json) {
-    final label = json['label'];
-    final needsConfirmation = json['needsConfirmation'];
-    final description = json['description'];
+  static ChangeAnnotation fromJson(Map<String, Object?> json) {
+    final labelJson = json['label'];
+    final label = labelJson as String;
+    final needsConfirmationJson = json['needsConfirmation'];
+    final needsConfirmation = needsConfirmationJson as bool?;
+    final descriptionJson = json['description'];
+    final description = descriptionJson as String?;
     return ChangeAnnotation(
         label: label,
         needsConfirmation: needsConfirmation,
@@ -1468,8 +1527,8 @@
   /// the change.
   final bool? needsConfirmation;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['label'] = label;
     if (needsConfirmation != null) {
       __result['needsConfirmation'] = needsConfirmation;
@@ -1481,18 +1540,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('label');
       try {
         if (!obj.containsKey('label')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['label'] == null) {
+        final label = obj['label'];
+        if (label == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['label'] is String)) {
+        if (!(label is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -1501,8 +1561,8 @@
       }
       reporter.push('needsConfirmation');
       try {
-        if (obj['needsConfirmation'] != null &&
-            !(obj['needsConfirmation'] is bool)) {
+        final needsConfirmation = obj['needsConfirmation'];
+        if (needsConfirmation != null && !(needsConfirmation is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -1511,7 +1571,8 @@
       }
       reporter.push('description');
       try {
-        if (obj['description'] != null && !(obj['description'] is String)) {
+        final description = obj['description'];
+        if (description != null && !(description is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -1559,20 +1620,28 @@
       this.window,
       this.general,
       this.experimental});
-  static ClientCapabilities fromJson(Map<String, dynamic> json) {
-    final workspace = json['workspace'] != null
-        ? ClientCapabilitiesWorkspace.fromJson(json['workspace'])
+  static ClientCapabilities fromJson(Map<String, Object?> json) {
+    final workspaceJson = json['workspace'];
+    final workspace = workspaceJson != null
+        ? ClientCapabilitiesWorkspace.fromJson(
+            workspaceJson as Map<String, Object?>)
         : null;
-    final textDocument = json['textDocument'] != null
-        ? TextDocumentClientCapabilities.fromJson(json['textDocument'])
+    final textDocumentJson = json['textDocument'];
+    final textDocument = textDocumentJson != null
+        ? TextDocumentClientCapabilities.fromJson(
+            textDocumentJson as Map<String, Object?>)
         : null;
-    final window = json['window'] != null
-        ? ClientCapabilitiesWindow.fromJson(json['window'])
+    final windowJson = json['window'];
+    final window = windowJson != null
+        ? ClientCapabilitiesWindow.fromJson(windowJson as Map<String, Object?>)
         : null;
-    final general = json['general'] != null
-        ? ClientCapabilitiesGeneral.fromJson(json['general'])
+    final generalJson = json['general'];
+    final general = generalJson != null
+        ? ClientCapabilitiesGeneral.fromJson(
+            generalJson as Map<String, Object?>)
         : null;
-    final experimental = json['experimental'];
+    final experimentalJson = json['experimental'];
+    final experimental = experimentalJson;
     return ClientCapabilities(
         workspace: workspace,
         textDocument: textDocument,
@@ -1582,7 +1651,7 @@
   }
 
   /// Experimental client capabilities.
-  final dynamic experimental;
+  final Object? experimental;
 
   /// General client capabilities.
   ///  @since 3.16.0
@@ -1597,8 +1666,8 @@
   /// Workspace specific client capabilities.
   final ClientCapabilitiesWorkspace? workspace;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workspace != null) {
       __result['workspace'] = workspace?.toJson();
     }
@@ -1618,12 +1687,12 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workspace');
       try {
-        if (obj['workspace'] != null &&
-            !(ClientCapabilitiesWorkspace.canParse(
-                obj['workspace'], reporter))) {
+        final workspace = obj['workspace'];
+        if (workspace != null &&
+            !(ClientCapabilitiesWorkspace.canParse(workspace, reporter))) {
           reporter.reportError('must be of type ClientCapabilitiesWorkspace');
           return false;
         }
@@ -1632,9 +1701,10 @@
       }
       reporter.push('textDocument');
       try {
-        if (obj['textDocument'] != null &&
+        final textDocument = obj['textDocument'];
+        if (textDocument != null &&
             !(TextDocumentClientCapabilities.canParse(
-                obj['textDocument'], reporter))) {
+                textDocument, reporter))) {
           reporter
               .reportError('must be of type TextDocumentClientCapabilities');
           return false;
@@ -1644,8 +1714,9 @@
       }
       reporter.push('window');
       try {
-        if (obj['window'] != null &&
-            !(ClientCapabilitiesWindow.canParse(obj['window'], reporter))) {
+        final window = obj['window'];
+        if (window != null &&
+            !(ClientCapabilitiesWindow.canParse(window, reporter))) {
           reporter.reportError('must be of type ClientCapabilitiesWindow');
           return false;
         }
@@ -1654,8 +1725,9 @@
       }
       reporter.push('general');
       try {
-        if (obj['general'] != null &&
-            !(ClientCapabilitiesGeneral.canParse(obj['general'], reporter))) {
+        final general = obj['general'];
+        if (general != null &&
+            !(ClientCapabilitiesGeneral.canParse(general, reporter))) {
           reporter.reportError('must be of type ClientCapabilitiesGeneral');
           return false;
         }
@@ -1711,14 +1783,21 @@
       this.willRename,
       this.didDelete,
       this.willDelete});
-  static ClientCapabilitiesFileOperations fromJson(Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
-    final didCreate = json['didCreate'];
-    final willCreate = json['willCreate'];
-    final didRename = json['didRename'];
-    final willRename = json['willRename'];
-    final didDelete = json['didDelete'];
-    final willDelete = json['willDelete'];
+  static ClientCapabilitiesFileOperations fromJson(Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
+    final didCreateJson = json['didCreate'];
+    final didCreate = didCreateJson as bool?;
+    final willCreateJson = json['willCreate'];
+    final willCreate = willCreateJson as bool?;
+    final didRenameJson = json['didRename'];
+    final didRename = didRenameJson as bool?;
+    final willRenameJson = json['willRename'];
+    final willRename = willRenameJson as bool?;
+    final didDeleteJson = json['didDelete'];
+    final didDelete = didDeleteJson as bool?;
+    final willDeleteJson = json['willDelete'];
+    final willDelete = willDeleteJson as bool?;
     return ClientCapabilitiesFileOperations(
         dynamicRegistration: dynamicRegistration,
         didCreate: didCreate,
@@ -1751,8 +1830,8 @@
   /// The client has support for sending willRenameFiles requests.
   final bool? willRename;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -1778,11 +1857,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -1791,7 +1870,8 @@
       }
       reporter.push('didCreate');
       try {
-        if (obj['didCreate'] != null && !(obj['didCreate'] is bool)) {
+        final didCreate = obj['didCreate'];
+        if (didCreate != null && !(didCreate is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -1800,7 +1880,8 @@
       }
       reporter.push('willCreate');
       try {
-        if (obj['willCreate'] != null && !(obj['willCreate'] is bool)) {
+        final willCreate = obj['willCreate'];
+        if (willCreate != null && !(willCreate is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -1809,7 +1890,8 @@
       }
       reporter.push('didRename');
       try {
-        if (obj['didRename'] != null && !(obj['didRename'] is bool)) {
+        final didRename = obj['didRename'];
+        if (didRename != null && !(didRename is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -1818,7 +1900,8 @@
       }
       reporter.push('willRename');
       try {
-        if (obj['willRename'] != null && !(obj['willRename'] is bool)) {
+        final willRename = obj['willRename'];
+        if (willRename != null && !(willRename is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -1827,7 +1910,8 @@
       }
       reporter.push('didDelete');
       try {
-        if (obj['didDelete'] != null && !(obj['didDelete'] is bool)) {
+        final didDelete = obj['didDelete'];
+        if (didDelete != null && !(didDelete is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -1836,7 +1920,8 @@
       }
       reporter.push('willDelete');
       try {
-        if (obj['willDelete'] != null && !(obj['willDelete'] is bool)) {
+        final willDelete = obj['willDelete'];
+        if (willDelete != null && !(willDelete is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -1888,13 +1973,16 @@
       ClientCapabilitiesGeneral.canParse, ClientCapabilitiesGeneral.fromJson);
 
   ClientCapabilitiesGeneral({this.regularExpressions, this.markdown});
-  static ClientCapabilitiesGeneral fromJson(Map<String, dynamic> json) {
-    final regularExpressions = json['regularExpressions'] != null
+  static ClientCapabilitiesGeneral fromJson(Map<String, Object?> json) {
+    final regularExpressionsJson = json['regularExpressions'];
+    final regularExpressions = regularExpressionsJson != null
         ? RegularExpressionsClientCapabilities.fromJson(
-            json['regularExpressions'])
+            regularExpressionsJson as Map<String, Object?>)
         : null;
-    final markdown = json['markdown'] != null
-        ? MarkdownClientCapabilities.fromJson(json['markdown'])
+    final markdownJson = json['markdown'];
+    final markdown = markdownJson != null
+        ? MarkdownClientCapabilities.fromJson(
+            markdownJson as Map<String, Object?>)
         : null;
     return ClientCapabilitiesGeneral(
         regularExpressions: regularExpressions, markdown: markdown);
@@ -1908,8 +1996,8 @@
   ///  @since 3.16.0
   final RegularExpressionsClientCapabilities? regularExpressions;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (regularExpressions != null) {
       __result['regularExpressions'] = regularExpressions?.toJson();
     }
@@ -1920,12 +2008,13 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('regularExpressions');
       try {
-        if (obj['regularExpressions'] != null &&
+        final regularExpressions = obj['regularExpressions'];
+        if (regularExpressions != null &&
             !(RegularExpressionsClientCapabilities.canParse(
-                obj['regularExpressions'], reporter))) {
+                regularExpressions, reporter))) {
           reporter.reportError(
               'must be of type RegularExpressionsClientCapabilities');
           return false;
@@ -1935,8 +2024,9 @@
       }
       reporter.push('markdown');
       try {
-        if (obj['markdown'] != null &&
-            !(MarkdownClientCapabilities.canParse(obj['markdown'], reporter))) {
+        final markdown = obj['markdown'];
+        if (markdown != null &&
+            !(MarkdownClientCapabilities.canParse(markdown, reporter))) {
           reporter.reportError('must be of type MarkdownClientCapabilities');
           return false;
         }
@@ -1979,13 +2069,18 @@
 
   ClientCapabilitiesWindow(
       {this.workDoneProgress, this.showMessage, this.showDocument});
-  static ClientCapabilitiesWindow fromJson(Map<String, dynamic> json) {
-    final workDoneProgress = json['workDoneProgress'];
-    final showMessage = json['showMessage'] != null
-        ? ShowMessageRequestClientCapabilities.fromJson(json['showMessage'])
+  static ClientCapabilitiesWindow fromJson(Map<String, Object?> json) {
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
+    final showMessageJson = json['showMessage'];
+    final showMessage = showMessageJson != null
+        ? ShowMessageRequestClientCapabilities.fromJson(
+            showMessageJson as Map<String, Object?>)
         : null;
-    final showDocument = json['showDocument'] != null
-        ? ShowDocumentClientCapabilities.fromJson(json['showDocument'])
+    final showDocumentJson = json['showDocument'];
+    final showDocument = showDocumentJson != null
+        ? ShowDocumentClientCapabilities.fromJson(
+            showDocumentJson as Map<String, Object?>)
         : null;
     return ClientCapabilitiesWindow(
         workDoneProgress: workDoneProgress,
@@ -2007,8 +2102,8 @@
   ///  @since 3.15.0
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
     }
@@ -2022,11 +2117,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -2035,9 +2130,10 @@
       }
       reporter.push('showMessage');
       try {
-        if (obj['showMessage'] != null &&
+        final showMessage = obj['showMessage'];
+        if (showMessage != null &&
             !(ShowMessageRequestClientCapabilities.canParse(
-                obj['showMessage'], reporter))) {
+                showMessage, reporter))) {
           reporter.reportError(
               'must be of type ShowMessageRequestClientCapabilities');
           return false;
@@ -2047,9 +2143,10 @@
       }
       reporter.push('showDocument');
       try {
-        if (obj['showDocument'] != null &&
+        final showDocument = obj['showDocument'];
+        if (showDocument != null &&
             !(ShowDocumentClientCapabilities.canParse(
-                obj['showDocument'], reporter))) {
+                showDocument, reporter))) {
           reporter
               .reportError('must be of type ShowDocumentClientCapabilities');
           return false;
@@ -2106,36 +2203,52 @@
       this.semanticTokens,
       this.codeLens,
       this.fileOperations});
-  static ClientCapabilitiesWorkspace fromJson(Map<String, dynamic> json) {
-    final applyEdit = json['applyEdit'];
-    final workspaceEdit = json['workspaceEdit'] != null
-        ? WorkspaceEditClientCapabilities.fromJson(json['workspaceEdit'])
+  static ClientCapabilitiesWorkspace fromJson(Map<String, Object?> json) {
+    final applyEditJson = json['applyEdit'];
+    final applyEdit = applyEditJson as bool?;
+    final workspaceEditJson = json['workspaceEdit'];
+    final workspaceEdit = workspaceEditJson != null
+        ? WorkspaceEditClientCapabilities.fromJson(
+            workspaceEditJson as Map<String, Object?>)
         : null;
-    final didChangeConfiguration = json['didChangeConfiguration'] != null
+    final didChangeConfigurationJson = json['didChangeConfiguration'];
+    final didChangeConfiguration = didChangeConfigurationJson != null
         ? DidChangeConfigurationClientCapabilities.fromJson(
-            json['didChangeConfiguration'])
+            didChangeConfigurationJson as Map<String, Object?>)
         : null;
-    final didChangeWatchedFiles = json['didChangeWatchedFiles'] != null
+    final didChangeWatchedFilesJson = json['didChangeWatchedFiles'];
+    final didChangeWatchedFiles = didChangeWatchedFilesJson != null
         ? DidChangeWatchedFilesClientCapabilities.fromJson(
-            json['didChangeWatchedFiles'])
+            didChangeWatchedFilesJson as Map<String, Object?>)
         : null;
-    final symbol = json['symbol'] != null
-        ? WorkspaceSymbolClientCapabilities.fromJson(json['symbol'])
+    final symbolJson = json['symbol'];
+    final symbol = symbolJson != null
+        ? WorkspaceSymbolClientCapabilities.fromJson(
+            symbolJson as Map<String, Object?>)
         : null;
-    final executeCommand = json['executeCommand'] != null
-        ? ExecuteCommandClientCapabilities.fromJson(json['executeCommand'])
+    final executeCommandJson = json['executeCommand'];
+    final executeCommand = executeCommandJson != null
+        ? ExecuteCommandClientCapabilities.fromJson(
+            executeCommandJson as Map<String, Object?>)
         : null;
-    final workspaceFolders = json['workspaceFolders'];
-    final configuration = json['configuration'];
-    final semanticTokens = json['semanticTokens'] != null
+    final workspaceFoldersJson = json['workspaceFolders'];
+    final workspaceFolders = workspaceFoldersJson as bool?;
+    final configurationJson = json['configuration'];
+    final configuration = configurationJson as bool?;
+    final semanticTokensJson = json['semanticTokens'];
+    final semanticTokens = semanticTokensJson != null
         ? SemanticTokensWorkspaceClientCapabilities.fromJson(
-            json['semanticTokens'])
+            semanticTokensJson as Map<String, Object?>)
         : null;
-    final codeLens = json['codeLens'] != null
-        ? CodeLensWorkspaceClientCapabilities.fromJson(json['codeLens'])
+    final codeLensJson = json['codeLens'];
+    final codeLens = codeLensJson != null
+        ? CodeLensWorkspaceClientCapabilities.fromJson(
+            codeLensJson as Map<String, Object?>)
         : null;
-    final fileOperations = json['fileOperations'] != null
-        ? ClientCapabilitiesFileOperations.fromJson(json['fileOperations'])
+    final fileOperationsJson = json['fileOperations'];
+    final fileOperations = fileOperationsJson != null
+        ? ClientCapabilitiesFileOperations.fromJson(
+            fileOperationsJson as Map<String, Object?>)
         : null;
     return ClientCapabilitiesWorkspace(
         applyEdit: applyEdit,
@@ -2193,8 +2306,8 @@
   ///  @since 3.6.0
   final bool? workspaceFolders;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (applyEdit != null) {
       __result['applyEdit'] = applyEdit;
     }
@@ -2232,10 +2345,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('applyEdit');
       try {
-        if (obj['applyEdit'] != null && !(obj['applyEdit'] is bool)) {
+        final applyEdit = obj['applyEdit'];
+        if (applyEdit != null && !(applyEdit is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -2244,9 +2358,10 @@
       }
       reporter.push('workspaceEdit');
       try {
-        if (obj['workspaceEdit'] != null &&
+        final workspaceEdit = obj['workspaceEdit'];
+        if (workspaceEdit != null &&
             !(WorkspaceEditClientCapabilities.canParse(
-                obj['workspaceEdit'], reporter))) {
+                workspaceEdit, reporter))) {
           reporter
               .reportError('must be of type WorkspaceEditClientCapabilities');
           return false;
@@ -2256,9 +2371,10 @@
       }
       reporter.push('didChangeConfiguration');
       try {
-        if (obj['didChangeConfiguration'] != null &&
+        final didChangeConfiguration = obj['didChangeConfiguration'];
+        if (didChangeConfiguration != null &&
             !(DidChangeConfigurationClientCapabilities.canParse(
-                obj['didChangeConfiguration'], reporter))) {
+                didChangeConfiguration, reporter))) {
           reporter.reportError(
               'must be of type DidChangeConfigurationClientCapabilities');
           return false;
@@ -2268,9 +2384,10 @@
       }
       reporter.push('didChangeWatchedFiles');
       try {
-        if (obj['didChangeWatchedFiles'] != null &&
+        final didChangeWatchedFiles = obj['didChangeWatchedFiles'];
+        if (didChangeWatchedFiles != null &&
             !(DidChangeWatchedFilesClientCapabilities.canParse(
-                obj['didChangeWatchedFiles'], reporter))) {
+                didChangeWatchedFiles, reporter))) {
           reporter.reportError(
               'must be of type DidChangeWatchedFilesClientCapabilities');
           return false;
@@ -2280,9 +2397,9 @@
       }
       reporter.push('symbol');
       try {
-        if (obj['symbol'] != null &&
-            !(WorkspaceSymbolClientCapabilities.canParse(
-                obj['symbol'], reporter))) {
+        final symbol = obj['symbol'];
+        if (symbol != null &&
+            !(WorkspaceSymbolClientCapabilities.canParse(symbol, reporter))) {
           reporter
               .reportError('must be of type WorkspaceSymbolClientCapabilities');
           return false;
@@ -2292,9 +2409,10 @@
       }
       reporter.push('executeCommand');
       try {
-        if (obj['executeCommand'] != null &&
+        final executeCommand = obj['executeCommand'];
+        if (executeCommand != null &&
             !(ExecuteCommandClientCapabilities.canParse(
-                obj['executeCommand'], reporter))) {
+                executeCommand, reporter))) {
           reporter
               .reportError('must be of type ExecuteCommandClientCapabilities');
           return false;
@@ -2304,8 +2422,8 @@
       }
       reporter.push('workspaceFolders');
       try {
-        if (obj['workspaceFolders'] != null &&
-            !(obj['workspaceFolders'] is bool)) {
+        final workspaceFolders = obj['workspaceFolders'];
+        if (workspaceFolders != null && !(workspaceFolders is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -2314,7 +2432,8 @@
       }
       reporter.push('configuration');
       try {
-        if (obj['configuration'] != null && !(obj['configuration'] is bool)) {
+        final configuration = obj['configuration'];
+        if (configuration != null && !(configuration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -2323,9 +2442,10 @@
       }
       reporter.push('semanticTokens');
       try {
-        if (obj['semanticTokens'] != null &&
+        final semanticTokens = obj['semanticTokens'];
+        if (semanticTokens != null &&
             !(SemanticTokensWorkspaceClientCapabilities.canParse(
-                obj['semanticTokens'], reporter))) {
+                semanticTokens, reporter))) {
           reporter.reportError(
               'must be of type SemanticTokensWorkspaceClientCapabilities');
           return false;
@@ -2335,9 +2455,10 @@
       }
       reporter.push('codeLens');
       try {
-        if (obj['codeLens'] != null &&
+        final codeLens = obj['codeLens'];
+        if (codeLens != null &&
             !(CodeLensWorkspaceClientCapabilities.canParse(
-                obj['codeLens'], reporter))) {
+                codeLens, reporter))) {
           reporter.reportError(
               'must be of type CodeLensWorkspaceClientCapabilities');
           return false;
@@ -2347,9 +2468,10 @@
       }
       reporter.push('fileOperations');
       try {
-        if (obj['fileOperations'] != null &&
+        final fileOperations = obj['fileOperations'];
+        if (fileOperations != null &&
             !(ClientCapabilitiesFileOperations.canParse(
-                obj['fileOperations'], reporter))) {
+                fileOperations, reporter))) {
           reporter
               .reportError('must be of type ClientCapabilitiesFileOperations');
           return false;
@@ -2423,23 +2545,32 @@
       this.edit,
       this.command,
       this.data});
-  static CodeAction fromJson(Map<String, dynamic> json) {
-    final title = json['title'];
+  static CodeAction fromJson(Map<String, Object?> json) {
+    final titleJson = json['title'];
+    final title = titleJson as String;
+    final kindJson = json['kind'];
     final kind =
-        json['kind'] != null ? CodeActionKind.fromJson(json['kind']) : null;
-    final diagnostics = json['diagnostics']
-        ?.map((item) => item != null ? Diagnostic.fromJson(item) : null)
-        ?.cast<Diagnostic>()
-        ?.toList();
-    final isPreferred = json['isPreferred'];
-    final disabled = json['disabled'] != null
-        ? CodeActionDisabled.fromJson(json['disabled'])
+        kindJson != null ? CodeActionKind.fromJson(kindJson as String) : null;
+    final diagnosticsJson = json['diagnostics'];
+    final diagnostics = (diagnosticsJson as List<Object?>?)
+        ?.map((item) => Diagnostic.fromJson(item as Map<String, Object?>))
+        .toList();
+    final isPreferredJson = json['isPreferred'];
+    final isPreferred = isPreferredJson as bool?;
+    final disabledJson = json['disabled'];
+    final disabled = disabledJson != null
+        ? CodeActionDisabled.fromJson(disabledJson as Map<String, Object?>)
         : null;
-    final edit =
-        json['edit'] != null ? WorkspaceEdit.fromJson(json['edit']) : null;
-    final command =
-        json['command'] != null ? Command.fromJson(json['command']) : null;
-    final data = json['data'];
+    final editJson = json['edit'];
+    final edit = editJson != null
+        ? WorkspaceEdit.fromJson(editJson as Map<String, Object?>)
+        : null;
+    final commandJson = json['command'];
+    final command = commandJson != null
+        ? Command.fromJson(commandJson as Map<String, Object?>)
+        : null;
+    final dataJson = json['data'];
+    final data = dataJson;
     return CodeAction(
         title: title,
         kind: kind,
@@ -2458,7 +2589,7 @@
   /// A data entry field that is preserved on a code action between a
   /// `textDocument/codeAction` and a `codeAction/resolve` request.
   ///  @since 3.16.0
-  final dynamic data;
+  final Object? data;
 
   /// The diagnostics that this code action resolves.
   final List<Diagnostic>? diagnostics;
@@ -2501,8 +2632,8 @@
   /// A short, human-readable, title for this code action.
   final String title;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['title'] = title;
     if (kind != null) {
       __result['kind'] = kind?.toJson();
@@ -2530,18 +2661,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('title');
       try {
         if (!obj.containsKey('title')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['title'] == null) {
+        final title = obj['title'];
+        if (title == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['title'] is String)) {
+        if (!(title is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -2550,8 +2682,8 @@
       }
       reporter.push('kind');
       try {
-        if (obj['kind'] != null &&
-            !(CodeActionKind.canParse(obj['kind'], reporter))) {
+        final kind = obj['kind'];
+        if (kind != null && !(CodeActionKind.canParse(kind, reporter))) {
           reporter.reportError('must be of type CodeActionKind');
           return false;
         }
@@ -2560,9 +2692,10 @@
       }
       reporter.push('diagnostics');
       try {
-        if (obj['diagnostics'] != null &&
-            !((obj['diagnostics'] is List &&
-                (obj['diagnostics']
+        final diagnostics = obj['diagnostics'];
+        if (diagnostics != null &&
+            !((diagnostics is List &&
+                (diagnostics
                     .every((item) => Diagnostic.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<Diagnostic>');
           return false;
@@ -2572,7 +2705,8 @@
       }
       reporter.push('isPreferred');
       try {
-        if (obj['isPreferred'] != null && !(obj['isPreferred'] is bool)) {
+        final isPreferred = obj['isPreferred'];
+        if (isPreferred != null && !(isPreferred is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -2581,8 +2715,9 @@
       }
       reporter.push('disabled');
       try {
-        if (obj['disabled'] != null &&
-            !(CodeActionDisabled.canParse(obj['disabled'], reporter))) {
+        final disabled = obj['disabled'];
+        if (disabled != null &&
+            !(CodeActionDisabled.canParse(disabled, reporter))) {
           reporter.reportError('must be of type CodeActionDisabled');
           return false;
         }
@@ -2591,8 +2726,8 @@
       }
       reporter.push('edit');
       try {
-        if (obj['edit'] != null &&
-            !(WorkspaceEdit.canParse(obj['edit'], reporter))) {
+        final edit = obj['edit'];
+        if (edit != null && !(WorkspaceEdit.canParse(edit, reporter))) {
           reporter.reportError('must be of type WorkspaceEdit');
           return false;
         }
@@ -2601,8 +2736,8 @@
       }
       reporter.push('command');
       try {
-        if (obj['command'] != null &&
-            !(Command.canParse(obj['command'], reporter))) {
+        final command = obj['command'];
+        if (command != null && !(Command.canParse(command, reporter))) {
           reporter.reportError('must be of type Command');
           return false;
         }
@@ -2664,20 +2799,27 @@
       this.dataSupport,
       this.resolveSupport,
       this.honorsChangeAnnotations});
-  static CodeActionClientCapabilities fromJson(Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
-    final codeActionLiteralSupport = json['codeActionLiteralSupport'] != null
+  static CodeActionClientCapabilities fromJson(Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
+    final codeActionLiteralSupportJson = json['codeActionLiteralSupport'];
+    final codeActionLiteralSupport = codeActionLiteralSupportJson != null
         ? CodeActionClientCapabilitiesCodeActionLiteralSupport.fromJson(
-            json['codeActionLiteralSupport'])
+            codeActionLiteralSupportJson as Map<String, Object?>)
         : null;
-    final isPreferredSupport = json['isPreferredSupport'];
-    final disabledSupport = json['disabledSupport'];
-    final dataSupport = json['dataSupport'];
-    final resolveSupport = json['resolveSupport'] != null
+    final isPreferredSupportJson = json['isPreferredSupport'];
+    final isPreferredSupport = isPreferredSupportJson as bool?;
+    final disabledSupportJson = json['disabledSupport'];
+    final disabledSupport = disabledSupportJson as bool?;
+    final dataSupportJson = json['dataSupport'];
+    final dataSupport = dataSupportJson as bool?;
+    final resolveSupportJson = json['resolveSupport'];
+    final resolveSupport = resolveSupportJson != null
         ? CodeActionClientCapabilitiesResolveSupport.fromJson(
-            json['resolveSupport'])
+            resolveSupportJson as Map<String, Object?>)
         : null;
-    final honorsChangeAnnotations = json['honorsChangeAnnotations'];
+    final honorsChangeAnnotationsJson = json['honorsChangeAnnotations'];
+    final honorsChangeAnnotations = honorsChangeAnnotationsJson as bool?;
     return CodeActionClientCapabilities(
         dynamicRegistration: dynamicRegistration,
         codeActionLiteralSupport: codeActionLiteralSupport,
@@ -2722,8 +2864,8 @@
   ///  @since 3.16.0
   final CodeActionClientCapabilitiesResolveSupport? resolveSupport;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -2749,11 +2891,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -2762,9 +2904,10 @@
       }
       reporter.push('codeActionLiteralSupport');
       try {
-        if (obj['codeActionLiteralSupport'] != null &&
+        final codeActionLiteralSupport = obj['codeActionLiteralSupport'];
+        if (codeActionLiteralSupport != null &&
             !(CodeActionClientCapabilitiesCodeActionLiteralSupport.canParse(
-                obj['codeActionLiteralSupport'], reporter))) {
+                codeActionLiteralSupport, reporter))) {
           reporter.reportError(
               'must be of type CodeActionClientCapabilitiesCodeActionLiteralSupport');
           return false;
@@ -2774,8 +2917,8 @@
       }
       reporter.push('isPreferredSupport');
       try {
-        if (obj['isPreferredSupport'] != null &&
-            !(obj['isPreferredSupport'] is bool)) {
+        final isPreferredSupport = obj['isPreferredSupport'];
+        if (isPreferredSupport != null && !(isPreferredSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -2784,8 +2927,8 @@
       }
       reporter.push('disabledSupport');
       try {
-        if (obj['disabledSupport'] != null &&
-            !(obj['disabledSupport'] is bool)) {
+        final disabledSupport = obj['disabledSupport'];
+        if (disabledSupport != null && !(disabledSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -2794,7 +2937,8 @@
       }
       reporter.push('dataSupport');
       try {
-        if (obj['dataSupport'] != null && !(obj['dataSupport'] is bool)) {
+        final dataSupport = obj['dataSupport'];
+        if (dataSupport != null && !(dataSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -2803,9 +2947,10 @@
       }
       reporter.push('resolveSupport');
       try {
-        if (obj['resolveSupport'] != null &&
+        final resolveSupport = obj['resolveSupport'];
+        if (resolveSupport != null &&
             !(CodeActionClientCapabilitiesResolveSupport.canParse(
-                obj['resolveSupport'], reporter))) {
+                resolveSupport, reporter))) {
           reporter.reportError(
               'must be of type CodeActionClientCapabilitiesResolveSupport');
           return false;
@@ -2815,8 +2960,9 @@
       }
       reporter.push('honorsChangeAnnotations');
       try {
-        if (obj['honorsChangeAnnotations'] != null &&
-            !(obj['honorsChangeAnnotations'] is bool)) {
+        final honorsChangeAnnotations = obj['honorsChangeAnnotations'];
+        if (honorsChangeAnnotations != null &&
+            !(honorsChangeAnnotations is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -2870,11 +3016,11 @@
 
   CodeActionClientCapabilitiesCodeActionKind({required this.valueSet});
   static CodeActionClientCapabilitiesCodeActionKind fromJson(
-      Map<String, dynamic> json) {
-    final valueSet = json['valueSet']
-        ?.map((item) => CodeActionKind.fromJson(item))
-        ?.cast<CodeActionKind>()
-        ?.toList();
+      Map<String, Object?> json) {
+    final valueSetJson = json['valueSet'];
+    final valueSet = (valueSetJson as List<Object?>)
+        .map((item) => CodeActionKind.fromJson(item as String))
+        .toList();
     return CodeActionClientCapabilitiesCodeActionKind(valueSet: valueSet);
   }
 
@@ -2883,26 +3029,27 @@
   /// gracefully and falls back to a default value when unknown.
   final List<CodeActionKind> valueSet;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['valueSet'] = valueSet.map((item) => item.toJson()).toList();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('valueSet');
       try {
         if (!obj.containsKey('valueSet')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['valueSet'] == null) {
+        final valueSet = obj['valueSet'];
+        if (valueSet == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['valueSet'] is List &&
-            (obj['valueSet']
+        if (!((valueSet is List &&
+            (valueSet
                 .every((item) => CodeActionKind.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<CodeActionKind>');
           return false;
@@ -2949,9 +3096,10 @@
   CodeActionClientCapabilitiesCodeActionLiteralSupport(
       {required this.codeActionKind});
   static CodeActionClientCapabilitiesCodeActionLiteralSupport fromJson(
-      Map<String, dynamic> json) {
+      Map<String, Object?> json) {
+    final codeActionKindJson = json['codeActionKind'];
     final codeActionKind = CodeActionClientCapabilitiesCodeActionKind.fromJson(
-        json['codeActionKind']);
+        codeActionKindJson as Map<String, Object?>);
     return CodeActionClientCapabilitiesCodeActionLiteralSupport(
         codeActionKind: codeActionKind);
   }
@@ -2959,26 +3107,27 @@
   /// The code action kind is supported with the following value set.
   final CodeActionClientCapabilitiesCodeActionKind codeActionKind;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['codeActionKind'] = codeActionKind.toJson();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('codeActionKind');
       try {
         if (!obj.containsKey('codeActionKind')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['codeActionKind'] == null) {
+        final codeActionKind = obj['codeActionKind'];
+        if (codeActionKind == null) {
           reporter.reportError('must not be null');
           return false;
         }
         if (!(CodeActionClientCapabilitiesCodeActionKind.canParse(
-            obj['codeActionKind'], reporter))) {
+            codeActionKind, reporter))) {
           reporter.reportError(
               'must be of type CodeActionClientCapabilitiesCodeActionKind');
           return false;
@@ -3022,35 +3171,38 @@
 
   CodeActionClientCapabilitiesResolveSupport({required this.properties});
   static CodeActionClientCapabilitiesResolveSupport fromJson(
-      Map<String, dynamic> json) {
-    final properties =
-        json['properties']?.map((item) => item)?.cast<String>()?.toList();
+      Map<String, Object?> json) {
+    final propertiesJson = json['properties'];
+    final properties = (propertiesJson as List<Object?>)
+        .map((item) => item as String)
+        .toList();
     return CodeActionClientCapabilitiesResolveSupport(properties: properties);
   }
 
   /// The properties that a client can resolve lazily.
   final List<String> properties;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['properties'] = properties;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('properties');
       try {
         if (!obj.containsKey('properties')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['properties'] == null) {
+        final properties = obj['properties'];
+        if (properties == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['properties'] is List &&
-            (obj['properties'].every((item) => item is String))))) {
+        if (!((properties is List &&
+            (properties.every((item) => item is String))))) {
           reporter.reportError('must be of type List<String>');
           return false;
         }
@@ -3094,15 +3246,15 @@
       LspJsonHandler(CodeActionContext.canParse, CodeActionContext.fromJson);
 
   CodeActionContext({required this.diagnostics, this.only});
-  static CodeActionContext fromJson(Map<String, dynamic> json) {
-    final diagnostics = json['diagnostics']
-        ?.map((item) => Diagnostic.fromJson(item))
-        ?.cast<Diagnostic>()
-        ?.toList();
-    final only = json['only']
-        ?.map((item) => item != null ? CodeActionKind.fromJson(item) : null)
-        ?.cast<CodeActionKind>()
-        ?.toList();
+  static CodeActionContext fromJson(Map<String, Object?> json) {
+    final diagnosticsJson = json['diagnostics'];
+    final diagnostics = (diagnosticsJson as List<Object?>)
+        .map((item) => Diagnostic.fromJson(item as Map<String, Object?>))
+        .toList();
+    final onlyJson = json['only'];
+    final only = (onlyJson as List<Object?>?)
+        ?.map((item) => CodeActionKind.fromJson(item as String))
+        .toList();
     return CodeActionContext(diagnostics: diagnostics, only: only);
   }
 
@@ -3120,8 +3272,8 @@
   /// shown. So servers can omit computing them.
   final List<CodeActionKind>? only;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['diagnostics'] = diagnostics.map((item) => item.toJson()).toList();
     if (only != null) {
       __result['only'] = only?.map((item) => item.toJson()).toList();
@@ -3130,19 +3282,20 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('diagnostics');
       try {
         if (!obj.containsKey('diagnostics')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['diagnostics'] == null) {
+        final diagnostics = obj['diagnostics'];
+        if (diagnostics == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['diagnostics'] is List &&
-            (obj['diagnostics']
+        if (!((diagnostics is List &&
+            (diagnostics
                 .every((item) => Diagnostic.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<Diagnostic>');
           return false;
@@ -3152,9 +3305,10 @@
       }
       reporter.push('only');
       try {
-        if (obj['only'] != null &&
-            !((obj['only'] is List &&
-                (obj['only'].every(
+        final only = obj['only'];
+        if (only != null &&
+            !((only is List &&
+                (only.every(
                     (item) => CodeActionKind.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<CodeActionKind>');
           return false;
@@ -3198,8 +3352,9 @@
       LspJsonHandler(CodeActionDisabled.canParse, CodeActionDisabled.fromJson);
 
   CodeActionDisabled({required this.reason});
-  static CodeActionDisabled fromJson(Map<String, dynamic> json) {
-    final reason = json['reason'];
+  static CodeActionDisabled fromJson(Map<String, Object?> json) {
+    final reasonJson = json['reason'];
+    final reason = reasonJson as String;
     return CodeActionDisabled(reason: reason);
   }
 
@@ -3208,25 +3363,26 @@
   /// This is displayed in the code actions UI.
   final String reason;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['reason'] = reason;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('reason');
       try {
         if (!obj.containsKey('reason')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['reason'] == null) {
+        final reason = obj['reason'];
+        if (reason == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['reason'] is String)) {
+        if (!(reason is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -3338,16 +3494,18 @@
 
   CodeActionOptions(
       {this.codeActionKinds, this.resolveProvider, this.workDoneProgress});
-  static CodeActionOptions fromJson(Map<String, dynamic> json) {
+  static CodeActionOptions fromJson(Map<String, Object?> json) {
     if (CodeActionRegistrationOptions.canParse(json, nullLspJsonReporter)) {
       return CodeActionRegistrationOptions.fromJson(json);
     }
-    final codeActionKinds = json['codeActionKinds']
-        ?.map((item) => item != null ? CodeActionKind.fromJson(item) : null)
-        ?.cast<CodeActionKind>()
-        ?.toList();
-    final resolveProvider = json['resolveProvider'];
-    final workDoneProgress = json['workDoneProgress'];
+    final codeActionKindsJson = json['codeActionKinds'];
+    final codeActionKinds = (codeActionKindsJson as List<Object?>?)
+        ?.map((item) => CodeActionKind.fromJson(item as String))
+        .toList();
+    final resolveProviderJson = json['resolveProvider'];
+    final resolveProvider = resolveProviderJson as bool?;
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return CodeActionOptions(
         codeActionKinds: codeActionKinds,
         resolveProvider: resolveProvider,
@@ -3366,8 +3524,8 @@
   final bool? resolveProvider;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (codeActionKinds != null) {
       __result['codeActionKinds'] =
           codeActionKinds?.map((item) => item.toJson()).toList();
@@ -3382,12 +3540,13 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('codeActionKinds');
       try {
-        if (obj['codeActionKinds'] != null &&
-            !((obj['codeActionKinds'] is List &&
-                (obj['codeActionKinds'].every(
+        final codeActionKinds = obj['codeActionKinds'];
+        if (codeActionKinds != null &&
+            !((codeActionKinds is List &&
+                (codeActionKinds.every(
                     (item) => CodeActionKind.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<CodeActionKind>');
           return false;
@@ -3397,8 +3556,8 @@
       }
       reporter.push('resolveProvider');
       try {
-        if (obj['resolveProvider'] != null &&
-            !(obj['resolveProvider'] is bool)) {
+        final resolveProvider = obj['resolveProvider'];
+        if (resolveProvider != null && !(resolveProvider is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -3407,8 +3566,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -3459,24 +3618,31 @@
       required this.context,
       this.workDoneToken,
       this.partialResultToken});
-  static CodeActionParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final range = Range.fromJson(json['range']);
-    final context = CodeActionContext.fromJson(json['context']);
-    final workDoneToken = json['workDoneToken'] == null
+  static CodeActionParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final rangeJson = json['range'];
+    final range = Range.fromJson(rangeJson as Map<String, Object?>);
+    final contextJson = json['context'];
+    final context =
+        CodeActionContext.fromJson(contextJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
-    final partialResultToken = json['partialResultToken'] == null
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
+    final partialResultTokenJson = json['partialResultToken'];
+    final partialResultToken = partialResultTokenJson == null
         ? null
-        : (json['partialResultToken'] is int
-            ? Either2<int, String>.t1(json['partialResultToken'])
-            : (json['partialResultToken'] is String
-                ? Either2<int, String>.t2(json['partialResultToken'])
-                : (throw '''${json['partialResultToken']} was not one of (int, String)''')));
+        : (partialResultTokenJson is int
+            ? Either2<int, String>.t1(partialResultTokenJson)
+            : (partialResultTokenJson is String
+                ? Either2<int, String>.t2(partialResultTokenJson)
+                : (throw '''$partialResultTokenJson was not one of (int, String)''')));
     return CodeActionParams(
         textDocument: textDocument,
         range: range,
@@ -3501,8 +3667,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     __result['range'] = range.toJson();
     __result['context'] = context.toJson();
@@ -3516,18 +3682,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -3540,11 +3707,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['range'] == null) {
+        final range = obj['range'];
+        if (range == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['range'], reporter))) {
+        if (!(Range.canParse(range, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -3557,11 +3725,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['context'] == null) {
+        final context = obj['context'];
+        if (context == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(CodeActionContext.canParse(obj['context'], reporter))) {
+        if (!(CodeActionContext.canParse(context, reporter))) {
           reporter.reportError('must be of type CodeActionContext');
           return false;
         }
@@ -3570,9 +3739,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -3581,9 +3750,9 @@
       }
       reporter.push('partialResultToken');
       try {
-        if (obj['partialResultToken'] != null &&
-            !((obj['partialResultToken'] is int ||
-                obj['partialResultToken'] is String))) {
+        final partialResultToken = obj['partialResultToken'];
+        if (partialResultToken != null &&
+            !((partialResultToken is int || partialResultToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -3636,17 +3805,19 @@
       this.codeActionKinds,
       this.resolveProvider,
       this.workDoneProgress});
-  static CodeActionRegistrationOptions fromJson(Map<String, dynamic> json) {
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final codeActionKinds = json['codeActionKinds']
-        ?.map((item) => item != null ? CodeActionKind.fromJson(item) : null)
-        ?.cast<CodeActionKind>()
-        ?.toList();
-    final resolveProvider = json['resolveProvider'];
-    final workDoneProgress = json['workDoneProgress'];
+  static CodeActionRegistrationOptions fromJson(Map<String, Object?> json) {
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final codeActionKindsJson = json['codeActionKinds'];
+    final codeActionKinds = (codeActionKindsJson as List<Object?>?)
+        ?.map((item) => CodeActionKind.fromJson(item as String))
+        .toList();
+    final resolveProviderJson = json['resolveProvider'];
+    final resolveProvider = resolveProviderJson as bool?;
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return CodeActionRegistrationOptions(
         documentSelector: documentSelector,
         codeActionKinds: codeActionKinds,
@@ -3670,8 +3841,8 @@
   final bool? resolveProvider;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['documentSelector'] = documentSelector;
     if (codeActionKinds != null) {
       __result['codeActionKinds'] =
@@ -3687,16 +3858,17 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentSelector');
       try {
         if (!obj.containsKey('documentSelector')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -3706,9 +3878,10 @@
       }
       reporter.push('codeActionKinds');
       try {
-        if (obj['codeActionKinds'] != null &&
-            !((obj['codeActionKinds'] is List &&
-                (obj['codeActionKinds'].every(
+        final codeActionKinds = obj['codeActionKinds'];
+        if (codeActionKinds != null &&
+            !((codeActionKinds is List &&
+                (codeActionKinds.every(
                     (item) => CodeActionKind.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<CodeActionKind>');
           return false;
@@ -3718,8 +3891,8 @@
       }
       reporter.push('resolveProvider');
       try {
-        if (obj['resolveProvider'] != null &&
-            !(obj['resolveProvider'] is bool)) {
+        final resolveProvider = obj['resolveProvider'];
+        if (resolveProvider != null && !(resolveProvider is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -3728,8 +3901,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -3779,33 +3952,35 @@
       LspJsonHandler(CodeDescription.canParse, CodeDescription.fromJson);
 
   CodeDescription({required this.href});
-  static CodeDescription fromJson(Map<String, dynamic> json) {
-    final href = json['href'];
+  static CodeDescription fromJson(Map<String, Object?> json) {
+    final hrefJson = json['href'];
+    final href = hrefJson as String;
     return CodeDescription(href: href);
   }
 
   /// An URI to open with more information about the diagnostic error.
   final String href;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['href'] = href;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('href');
       try {
         if (!obj.containsKey('href')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['href'] == null) {
+        final href = obj['href'];
+        if (href == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['href'] is String)) {
+        if (!(href is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -3849,11 +4024,15 @@
       LspJsonHandler(CodeLens.canParse, CodeLens.fromJson);
 
   CodeLens({required this.range, this.command, this.data});
-  static CodeLens fromJson(Map<String, dynamic> json) {
-    final range = Range.fromJson(json['range']);
-    final command =
-        json['command'] != null ? Command.fromJson(json['command']) : null;
-    final data = json['data'];
+  static CodeLens fromJson(Map<String, Object?> json) {
+    final rangeJson = json['range'];
+    final range = Range.fromJson(rangeJson as Map<String, Object?>);
+    final commandJson = json['command'];
+    final command = commandJson != null
+        ? Command.fromJson(commandJson as Map<String, Object?>)
+        : null;
+    final dataJson = json['data'];
+    final data = dataJson;
     return CodeLens(range: range, command: command, data: data);
   }
 
@@ -3862,14 +4041,14 @@
 
   /// A data entry field that is preserved on a code lens item between a code
   /// lens and a code lens resolve request.
-  final dynamic data;
+  final Object? data;
 
   /// The range in which this code lens is valid. Should only span a single
   /// line.
   final Range range;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['range'] = range.toJson();
     if (command != null) {
       __result['command'] = command?.toJson();
@@ -3881,18 +4060,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('range');
       try {
         if (!obj.containsKey('range')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['range'] == null) {
+        final range = obj['range'];
+        if (range == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['range'], reporter))) {
+        if (!(Range.canParse(range, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -3901,8 +4081,8 @@
       }
       reporter.push('command');
       try {
-        if (obj['command'] != null &&
-            !(Command.canParse(obj['command'], reporter))) {
+        final command = obj['command'];
+        if (command != null && !(Command.canParse(command, reporter))) {
           reporter.reportError('must be of type Command');
           return false;
         }
@@ -3945,16 +4125,17 @@
       CodeLensClientCapabilities.canParse, CodeLensClientCapabilities.fromJson);
 
   CodeLensClientCapabilities({this.dynamicRegistration});
-  static CodeLensClientCapabilities fromJson(Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
+  static CodeLensClientCapabilities fromJson(Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
     return CodeLensClientCapabilities(dynamicRegistration: dynamicRegistration);
   }
 
   /// Whether code lens supports dynamic registration.
   final bool? dynamicRegistration;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -3962,11 +4143,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -4005,12 +4186,14 @@
       LspJsonHandler(CodeLensOptions.canParse, CodeLensOptions.fromJson);
 
   CodeLensOptions({this.resolveProvider, this.workDoneProgress});
-  static CodeLensOptions fromJson(Map<String, dynamic> json) {
+  static CodeLensOptions fromJson(Map<String, Object?> json) {
     if (CodeLensRegistrationOptions.canParse(json, nullLspJsonReporter)) {
       return CodeLensRegistrationOptions.fromJson(json);
     }
-    final resolveProvider = json['resolveProvider'];
-    final workDoneProgress = json['workDoneProgress'];
+    final resolveProviderJson = json['resolveProvider'];
+    final resolveProvider = resolveProviderJson as bool?;
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return CodeLensOptions(
         resolveProvider: resolveProvider, workDoneProgress: workDoneProgress);
   }
@@ -4019,8 +4202,8 @@
   final bool? resolveProvider;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (resolveProvider != null) {
       __result['resolveProvider'] = resolveProvider;
     }
@@ -4031,11 +4214,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('resolveProvider');
       try {
-        if (obj['resolveProvider'] != null &&
-            !(obj['resolveProvider'] is bool)) {
+        final resolveProvider = obj['resolveProvider'];
+        if (resolveProvider != null && !(resolveProvider is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -4044,8 +4227,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -4090,22 +4273,26 @@
       {required this.textDocument,
       this.workDoneToken,
       this.partialResultToken});
-  static CodeLensParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final workDoneToken = json['workDoneToken'] == null
+  static CodeLensParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
-    final partialResultToken = json['partialResultToken'] == null
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
+    final partialResultTokenJson = json['partialResultToken'];
+    final partialResultToken = partialResultTokenJson == null
         ? null
-        : (json['partialResultToken'] is int
-            ? Either2<int, String>.t1(json['partialResultToken'])
-            : (json['partialResultToken'] is String
-                ? Either2<int, String>.t2(json['partialResultToken'])
-                : (throw '''${json['partialResultToken']} was not one of (int, String)''')));
+        : (partialResultTokenJson is int
+            ? Either2<int, String>.t1(partialResultTokenJson)
+            : (partialResultTokenJson is String
+                ? Either2<int, String>.t2(partialResultTokenJson)
+                : (throw '''$partialResultTokenJson was not one of (int, String)''')));
     return CodeLensParams(
         textDocument: textDocument,
         workDoneToken: workDoneToken,
@@ -4122,8 +4309,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     if (workDoneToken != null) {
       __result['workDoneToken'] = workDoneToken;
@@ -4135,18 +4322,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -4155,9 +4343,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -4166,9 +4354,9 @@
       }
       reporter.push('partialResultToken');
       try {
-        if (obj['partialResultToken'] != null &&
-            !((obj['partialResultToken'] is int ||
-                obj['partialResultToken'] is String))) {
+        final partialResultToken = obj['partialResultToken'];
+        if (partialResultToken != null &&
+            !((partialResultToken is int || partialResultToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -4214,13 +4402,15 @@
 
   CodeLensRegistrationOptions(
       {this.documentSelector, this.resolveProvider, this.workDoneProgress});
-  static CodeLensRegistrationOptions fromJson(Map<String, dynamic> json) {
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final resolveProvider = json['resolveProvider'];
-    final workDoneProgress = json['workDoneProgress'];
+  static CodeLensRegistrationOptions fromJson(Map<String, Object?> json) {
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final resolveProviderJson = json['resolveProvider'];
+    final resolveProvider = resolveProviderJson as bool?;
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return CodeLensRegistrationOptions(
         documentSelector: documentSelector,
         resolveProvider: resolveProvider,
@@ -4235,8 +4425,8 @@
   final bool? resolveProvider;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['documentSelector'] = documentSelector;
     if (resolveProvider != null) {
       __result['resolveProvider'] = resolveProvider;
@@ -4248,16 +4438,17 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentSelector');
       try {
         if (!obj.containsKey('documentSelector')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -4267,8 +4458,8 @@
       }
       reporter.push('resolveProvider');
       try {
-        if (obj['resolveProvider'] != null &&
-            !(obj['resolveProvider'] is bool)) {
+        final resolveProvider = obj['resolveProvider'];
+        if (resolveProvider != null && !(resolveProvider is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -4277,8 +4468,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -4325,8 +4516,9 @@
 
   CodeLensWorkspaceClientCapabilities({this.refreshSupport});
   static CodeLensWorkspaceClientCapabilities fromJson(
-      Map<String, dynamic> json) {
-    final refreshSupport = json['refreshSupport'];
+      Map<String, Object?> json) {
+    final refreshSupportJson = json['refreshSupport'];
+    final refreshSupport = refreshSupportJson as bool?;
     return CodeLensWorkspaceClientCapabilities(refreshSupport: refreshSupport);
   }
 
@@ -4339,8 +4531,8 @@
   /// change that requires such a calculation.
   final bool? refreshSupport;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (refreshSupport != null) {
       __result['refreshSupport'] = refreshSupport;
     }
@@ -4348,10 +4540,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('refreshSupport');
       try {
-        if (obj['refreshSupport'] != null && !(obj['refreshSupport'] is bool)) {
+        final refreshSupport = obj['refreshSupport'];
+        if (refreshSupport != null && !(refreshSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -4395,11 +4588,15 @@
       required this.green,
       required this.blue,
       required this.alpha});
-  static Color fromJson(Map<String, dynamic> json) {
-    final red = json['red'];
-    final green = json['green'];
-    final blue = json['blue'];
-    final alpha = json['alpha'];
+  static Color fromJson(Map<String, Object?> json) {
+    final redJson = json['red'];
+    final red = redJson as num;
+    final greenJson = json['green'];
+    final green = greenJson as num;
+    final blueJson = json['blue'];
+    final blue = blueJson as num;
+    final alphaJson = json['alpha'];
+    final alpha = alphaJson as num;
     return Color(red: red, green: green, blue: blue, alpha: alpha);
   }
 
@@ -4415,8 +4612,8 @@
   /// The red component of this color in the range [0-1].
   final num red;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['red'] = red;
     __result['green'] = green;
     __result['blue'] = blue;
@@ -4425,18 +4622,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('red');
       try {
         if (!obj.containsKey('red')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['red'] == null) {
+        final red = obj['red'];
+        if (red == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['red'] is num)) {
+        if (!(red is num)) {
           reporter.reportError('must be of type num');
           return false;
         }
@@ -4449,11 +4647,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['green'] == null) {
+        final green = obj['green'];
+        if (green == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['green'] is num)) {
+        if (!(green is num)) {
           reporter.reportError('must be of type num');
           return false;
         }
@@ -4466,11 +4665,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['blue'] == null) {
+        final blue = obj['blue'];
+        if (blue == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['blue'] is num)) {
+        if (!(blue is num)) {
           reporter.reportError('must be of type num');
           return false;
         }
@@ -4483,11 +4683,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['alpha'] == null) {
+        final alpha = obj['alpha'];
+        if (alpha == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['alpha'] is num)) {
+        if (!(alpha is num)) {
           reporter.reportError('must be of type num');
           return false;
         }
@@ -4532,9 +4733,11 @@
       LspJsonHandler(ColorInformation.canParse, ColorInformation.fromJson);
 
   ColorInformation({required this.range, required this.color});
-  static ColorInformation fromJson(Map<String, dynamic> json) {
-    final range = Range.fromJson(json['range']);
-    final color = Color.fromJson(json['color']);
+  static ColorInformation fromJson(Map<String, Object?> json) {
+    final rangeJson = json['range'];
+    final range = Range.fromJson(rangeJson as Map<String, Object?>);
+    final colorJson = json['color'];
+    final color = Color.fromJson(colorJson as Map<String, Object?>);
     return ColorInformation(range: range, color: color);
   }
 
@@ -4544,26 +4747,27 @@
   /// The range in the document where this color appears.
   final Range range;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['range'] = range.toJson();
     __result['color'] = color.toJson();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('range');
       try {
         if (!obj.containsKey('range')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['range'] == null) {
+        final range = obj['range'];
+        if (range == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['range'], reporter))) {
+        if (!(Range.canParse(range, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -4576,11 +4780,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['color'] == null) {
+        final color = obj['color'];
+        if (color == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Color.canParse(obj['color'], reporter))) {
+        if (!(Color.canParse(color, reporter))) {
           reporter.reportError('must be of type Color');
           return false;
         }
@@ -4620,14 +4825,17 @@
 
   ColorPresentation(
       {required this.label, this.textEdit, this.additionalTextEdits});
-  static ColorPresentation fromJson(Map<String, dynamic> json) {
-    final label = json['label'];
-    final textEdit =
-        json['textEdit'] != null ? TextEdit.fromJson(json['textEdit']) : null;
-    final additionalTextEdits = json['additionalTextEdits']
-        ?.map((item) => item != null ? TextEdit.fromJson(item) : null)
-        ?.cast<TextEdit>()
-        ?.toList();
+  static ColorPresentation fromJson(Map<String, Object?> json) {
+    final labelJson = json['label'];
+    final label = labelJson as String;
+    final textEditJson = json['textEdit'];
+    final textEdit = textEditJson != null
+        ? TextEdit.fromJson(textEditJson as Map<String, Object?>)
+        : null;
+    final additionalTextEditsJson = json['additionalTextEdits'];
+    final additionalTextEdits = (additionalTextEditsJson as List<Object?>?)
+        ?.map((item) => TextEdit.fromJson(item as Map<String, Object?>))
+        .toList();
     return ColorPresentation(
         label: label,
         textEdit: textEdit,
@@ -4649,8 +4857,8 @@
   /// [label](#ColorPresentation.label) is used.
   final TextEdit? textEdit;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['label'] = label;
     if (textEdit != null) {
       __result['textEdit'] = textEdit?.toJson();
@@ -4663,18 +4871,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('label');
       try {
         if (!obj.containsKey('label')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['label'] == null) {
+        final label = obj['label'];
+        if (label == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['label'] is String)) {
+        if (!(label is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -4683,8 +4892,8 @@
       }
       reporter.push('textEdit');
       try {
-        if (obj['textEdit'] != null &&
-            !(TextEdit.canParse(obj['textEdit'], reporter))) {
+        final textEdit = obj['textEdit'];
+        if (textEdit != null && !(TextEdit.canParse(textEdit, reporter))) {
           reporter.reportError('must be of type TextEdit');
           return false;
         }
@@ -4693,9 +4902,10 @@
       }
       reporter.push('additionalTextEdits');
       try {
-        if (obj['additionalTextEdits'] != null &&
-            !((obj['additionalTextEdits'] is List &&
-                (obj['additionalTextEdits']
+        final additionalTextEdits = obj['additionalTextEdits'];
+        if (additionalTextEdits != null &&
+            !((additionalTextEdits is List &&
+                (additionalTextEdits
                     .every((item) => TextEdit.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<TextEdit>');
           return false;
@@ -4746,24 +4956,30 @@
       required this.range,
       this.workDoneToken,
       this.partialResultToken});
-  static ColorPresentationParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final color = Color.fromJson(json['color']);
-    final range = Range.fromJson(json['range']);
-    final workDoneToken = json['workDoneToken'] == null
+  static ColorPresentationParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final colorJson = json['color'];
+    final color = Color.fromJson(colorJson as Map<String, Object?>);
+    final rangeJson = json['range'];
+    final range = Range.fromJson(rangeJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
-    final partialResultToken = json['partialResultToken'] == null
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
+    final partialResultTokenJson = json['partialResultToken'];
+    final partialResultToken = partialResultTokenJson == null
         ? null
-        : (json['partialResultToken'] is int
-            ? Either2<int, String>.t1(json['partialResultToken'])
-            : (json['partialResultToken'] is String
-                ? Either2<int, String>.t2(json['partialResultToken'])
-                : (throw '''${json['partialResultToken']} was not one of (int, String)''')));
+        : (partialResultTokenJson is int
+            ? Either2<int, String>.t1(partialResultTokenJson)
+            : (partialResultTokenJson is String
+                ? Either2<int, String>.t2(partialResultTokenJson)
+                : (throw '''$partialResultTokenJson was not one of (int, String)''')));
     return ColorPresentationParams(
         textDocument: textDocument,
         color: color,
@@ -4788,8 +5004,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     __result['color'] = color.toJson();
     __result['range'] = range.toJson();
@@ -4803,18 +5019,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -4827,11 +5044,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['color'] == null) {
+        final color = obj['color'];
+        if (color == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Color.canParse(obj['color'], reporter))) {
+        if (!(Color.canParse(color, reporter))) {
           reporter.reportError('must be of type Color');
           return false;
         }
@@ -4844,11 +5062,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['range'] == null) {
+        final range = obj['range'];
+        if (range == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['range'], reporter))) {
+        if (!(Range.canParse(range, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -4857,9 +5076,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -4868,9 +5087,9 @@
       }
       reporter.push('partialResultToken');
       try {
-        if (obj['partialResultToken'] != null &&
-            !((obj['partialResultToken'] is int ||
-                obj['partialResultToken'] is String))) {
+        final partialResultToken = obj['partialResultToken'];
+        if (partialResultToken != null &&
+            !((partialResultToken is int || partialResultToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -4917,16 +5136,19 @@
   static const jsonHandler = LspJsonHandler(Command.canParse, Command.fromJson);
 
   Command({required this.title, required this.command, this.arguments});
-  static Command fromJson(Map<String, dynamic> json) {
-    final title = json['title'];
-    final command = json['command'];
+  static Command fromJson(Map<String, Object?> json) {
+    final titleJson = json['title'];
+    final title = titleJson as String;
+    final commandJson = json['command'];
+    final command = commandJson as String;
+    final argumentsJson = json['arguments'];
     final arguments =
-        json['arguments']?.map((item) => item)?.cast<dynamic>()?.toList();
+        (argumentsJson as List<Object?>?)?.map((item) => item).toList();
     return Command(title: title, command: command, arguments: arguments);
   }
 
   /// Arguments that the command handler should be invoked with.
-  final List<dynamic>? arguments;
+  final List<Object?>? arguments;
 
   /// The identifier of the actual command handler.
   final String command;
@@ -4934,8 +5156,8 @@
   /// Title of the command, like `save`.
   final String title;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['title'] = title;
     __result['command'] = command;
     if (arguments != null) {
@@ -4945,18 +5167,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('title');
       try {
         if (!obj.containsKey('title')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['title'] == null) {
+        final title = obj['title'];
+        if (title == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['title'] is String)) {
+        if (!(title is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -4969,11 +5192,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['command'] == null) {
+        final command = obj['command'];
+        if (command == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['command'] is String)) {
+        if (!(command is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -4982,10 +5206,10 @@
       }
       reporter.push('arguments');
       try {
-        if (obj['arguments'] != null &&
-            !((obj['arguments'] is List &&
-                (obj['arguments'].every((item) => true))))) {
-          reporter.reportError('must be of type List<dynamic>');
+        final arguments = obj['arguments'];
+        if (arguments != null &&
+            !((arguments is List && (arguments.every((item) => true))))) {
+          reporter.reportError('must be of type List<Object?>');
           return false;
         }
       } finally {
@@ -5004,7 +5228,7 @@
       return title == other.title &&
           command == other.command &&
           listEqual(
-              arguments, other.arguments, (dynamic a, dynamic b) => a == b) &&
+              arguments, other.arguments, (Object? a, Object? b) => a == b) &&
           true;
     }
     return false;
@@ -5033,17 +5257,21 @@
       this.completionItem,
       this.completionItemKind,
       this.contextSupport});
-  static CompletionClientCapabilities fromJson(Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
-    final completionItem = json['completionItem'] != null
+  static CompletionClientCapabilities fromJson(Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
+    final completionItemJson = json['completionItem'];
+    final completionItem = completionItemJson != null
         ? CompletionClientCapabilitiesCompletionItem.fromJson(
-            json['completionItem'])
+            completionItemJson as Map<String, Object?>)
         : null;
-    final completionItemKind = json['completionItemKind'] != null
+    final completionItemKindJson = json['completionItemKind'];
+    final completionItemKind = completionItemKindJson != null
         ? CompletionClientCapabilitiesCompletionItemKind.fromJson(
-            json['completionItemKind'])
+            completionItemKindJson as Map<String, Object?>)
         : null;
-    final contextSupport = json['contextSupport'];
+    final contextSupportJson = json['contextSupport'];
+    final contextSupport = contextSupportJson as bool?;
     return CompletionClientCapabilities(
         dynamicRegistration: dynamicRegistration,
         completionItem: completionItem,
@@ -5062,8 +5290,8 @@
   /// Whether completion supports dynamic registration.
   final bool? dynamicRegistration;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -5080,11 +5308,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -5093,9 +5321,10 @@
       }
       reporter.push('completionItem');
       try {
-        if (obj['completionItem'] != null &&
+        final completionItem = obj['completionItem'];
+        if (completionItem != null &&
             !(CompletionClientCapabilitiesCompletionItem.canParse(
-                obj['completionItem'], reporter))) {
+                completionItem, reporter))) {
           reporter.reportError(
               'must be of type CompletionClientCapabilitiesCompletionItem');
           return false;
@@ -5105,9 +5334,10 @@
       }
       reporter.push('completionItemKind');
       try {
-        if (obj['completionItemKind'] != null &&
+        final completionItemKind = obj['completionItemKind'];
+        if (completionItemKind != null &&
             !(CompletionClientCapabilitiesCompletionItemKind.canParse(
-                obj['completionItemKind'], reporter))) {
+                completionItemKind, reporter))) {
           reporter.reportError(
               'must be of type CompletionClientCapabilitiesCompletionItemKind');
           return false;
@@ -5117,7 +5347,8 @@
       }
       reporter.push('contextSupport');
       try {
-        if (obj['contextSupport'] != null && !(obj['contextSupport'] is bool)) {
+        final contextSupport = obj['contextSupport'];
+        if (contextSupport != null && !(contextSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -5174,26 +5405,35 @@
       this.resolveSupport,
       this.insertTextModeSupport});
   static CompletionClientCapabilitiesCompletionItem fromJson(
-      Map<String, dynamic> json) {
-    final snippetSupport = json['snippetSupport'];
-    final commitCharactersSupport = json['commitCharactersSupport'];
-    final documentationFormat = json['documentationFormat']
-        ?.map((item) => item != null ? MarkupKind.fromJson(item) : null)
-        ?.cast<MarkupKind>()
-        ?.toList();
-    final deprecatedSupport = json['deprecatedSupport'];
-    final preselectSupport = json['preselectSupport'];
-    final tagSupport = json['tagSupport'] != null
-        ? CompletionClientCapabilitiesTagSupport.fromJson(json['tagSupport'])
+      Map<String, Object?> json) {
+    final snippetSupportJson = json['snippetSupport'];
+    final snippetSupport = snippetSupportJson as bool?;
+    final commitCharactersSupportJson = json['commitCharactersSupport'];
+    final commitCharactersSupport = commitCharactersSupportJson as bool?;
+    final documentationFormatJson = json['documentationFormat'];
+    final documentationFormat = (documentationFormatJson as List<Object?>?)
+        ?.map((item) => MarkupKind.fromJson(item as String))
+        .toList();
+    final deprecatedSupportJson = json['deprecatedSupport'];
+    final deprecatedSupport = deprecatedSupportJson as bool?;
+    final preselectSupportJson = json['preselectSupport'];
+    final preselectSupport = preselectSupportJson as bool?;
+    final tagSupportJson = json['tagSupport'];
+    final tagSupport = tagSupportJson != null
+        ? CompletionClientCapabilitiesTagSupport.fromJson(
+            tagSupportJson as Map<String, Object?>)
         : null;
-    final insertReplaceSupport = json['insertReplaceSupport'];
-    final resolveSupport = json['resolveSupport'] != null
+    final insertReplaceSupportJson = json['insertReplaceSupport'];
+    final insertReplaceSupport = insertReplaceSupportJson as bool?;
+    final resolveSupportJson = json['resolveSupport'];
+    final resolveSupport = resolveSupportJson != null
         ? CompletionClientCapabilitiesResolveSupport.fromJson(
-            json['resolveSupport'])
+            resolveSupportJson as Map<String, Object?>)
         : null;
-    final insertTextModeSupport = json['insertTextModeSupport'] != null
+    final insertTextModeSupportJson = json['insertTextModeSupport'];
+    final insertTextModeSupport = insertTextModeSupportJson != null
         ? CompletionClientCapabilitiesInsertTextModeSupport.fromJson(
-            json['insertTextModeSupport'])
+            insertTextModeSupportJson as Map<String, Object?>)
         : null;
     return CompletionClientCapabilitiesCompletionItem(
         snippetSupport: snippetSupport,
@@ -5253,8 +5493,8 @@
   ///  @since 3.15.0
   final CompletionClientCapabilitiesTagSupport? tagSupport;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (snippetSupport != null) {
       __result['snippetSupport'] = snippetSupport;
     }
@@ -5287,10 +5527,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('snippetSupport');
       try {
-        if (obj['snippetSupport'] != null && !(obj['snippetSupport'] is bool)) {
+        final snippetSupport = obj['snippetSupport'];
+        if (snippetSupport != null && !(snippetSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -5299,8 +5540,9 @@
       }
       reporter.push('commitCharactersSupport');
       try {
-        if (obj['commitCharactersSupport'] != null &&
-            !(obj['commitCharactersSupport'] is bool)) {
+        final commitCharactersSupport = obj['commitCharactersSupport'];
+        if (commitCharactersSupport != null &&
+            !(commitCharactersSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -5309,9 +5551,10 @@
       }
       reporter.push('documentationFormat');
       try {
-        if (obj['documentationFormat'] != null &&
-            !((obj['documentationFormat'] is List &&
-                (obj['documentationFormat']
+        final documentationFormat = obj['documentationFormat'];
+        if (documentationFormat != null &&
+            !((documentationFormat is List &&
+                (documentationFormat
                     .every((item) => MarkupKind.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<MarkupKind>');
           return false;
@@ -5321,8 +5564,8 @@
       }
       reporter.push('deprecatedSupport');
       try {
-        if (obj['deprecatedSupport'] != null &&
-            !(obj['deprecatedSupport'] is bool)) {
+        final deprecatedSupport = obj['deprecatedSupport'];
+        if (deprecatedSupport != null && !(deprecatedSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -5331,8 +5574,8 @@
       }
       reporter.push('preselectSupport');
       try {
-        if (obj['preselectSupport'] != null &&
-            !(obj['preselectSupport'] is bool)) {
+        final preselectSupport = obj['preselectSupport'];
+        if (preselectSupport != null && !(preselectSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -5341,9 +5584,10 @@
       }
       reporter.push('tagSupport');
       try {
-        if (obj['tagSupport'] != null &&
+        final tagSupport = obj['tagSupport'];
+        if (tagSupport != null &&
             !(CompletionClientCapabilitiesTagSupport.canParse(
-                obj['tagSupport'], reporter))) {
+                tagSupport, reporter))) {
           reporter.reportError(
               'must be of type CompletionClientCapabilitiesTagSupport');
           return false;
@@ -5353,8 +5597,8 @@
       }
       reporter.push('insertReplaceSupport');
       try {
-        if (obj['insertReplaceSupport'] != null &&
-            !(obj['insertReplaceSupport'] is bool)) {
+        final insertReplaceSupport = obj['insertReplaceSupport'];
+        if (insertReplaceSupport != null && !(insertReplaceSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -5363,9 +5607,10 @@
       }
       reporter.push('resolveSupport');
       try {
-        if (obj['resolveSupport'] != null &&
+        final resolveSupport = obj['resolveSupport'];
+        if (resolveSupport != null &&
             !(CompletionClientCapabilitiesResolveSupport.canParse(
-                obj['resolveSupport'], reporter))) {
+                resolveSupport, reporter))) {
           reporter.reportError(
               'must be of type CompletionClientCapabilitiesResolveSupport');
           return false;
@@ -5375,9 +5620,10 @@
       }
       reporter.push('insertTextModeSupport');
       try {
-        if (obj['insertTextModeSupport'] != null &&
+        final insertTextModeSupport = obj['insertTextModeSupport'];
+        if (insertTextModeSupport != null &&
             !(CompletionClientCapabilitiesInsertTextModeSupport.canParse(
-                obj['insertTextModeSupport'], reporter))) {
+                insertTextModeSupport, reporter))) {
           reporter.reportError(
               'must be of type CompletionClientCapabilitiesInsertTextModeSupport');
           return false;
@@ -5438,11 +5684,11 @@
 
   CompletionClientCapabilitiesCompletionItemKind({this.valueSet});
   static CompletionClientCapabilitiesCompletionItemKind fromJson(
-      Map<String, dynamic> json) {
-    final valueSet = json['valueSet']
-        ?.map((item) => item != null ? CompletionItemKind.fromJson(item) : null)
-        ?.cast<CompletionItemKind>()
-        ?.toList();
+      Map<String, Object?> json) {
+    final valueSetJson = json['valueSet'];
+    final valueSet = (valueSetJson as List<Object?>?)
+        ?.map((item) => CompletionItemKind.fromJson(item as int))
+        .toList();
     return CompletionClientCapabilitiesCompletionItemKind(valueSet: valueSet);
   }
 
@@ -5455,8 +5701,8 @@
   /// of the protocol.
   final List<CompletionItemKind>? valueSet;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (valueSet != null) {
       __result['valueSet'] = valueSet?.map((item) => item.toJson()).toList();
     }
@@ -5464,12 +5710,13 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('valueSet');
       try {
-        if (obj['valueSet'] != null &&
-            !((obj['valueSet'] is List &&
-                (obj['valueSet'].every(
+        final valueSet = obj['valueSet'];
+        if (valueSet != null &&
+            !((valueSet is List &&
+                (valueSet.every(
                     (item) => CompletionItemKind.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<CompletionItemKind>');
           return false;
@@ -5514,37 +5761,38 @@
 
   CompletionClientCapabilitiesInsertTextModeSupport({required this.valueSet});
   static CompletionClientCapabilitiesInsertTextModeSupport fromJson(
-      Map<String, dynamic> json) {
-    final valueSet = json['valueSet']
-        ?.map((item) => InsertTextMode.fromJson(item))
-        ?.cast<InsertTextMode>()
-        ?.toList();
+      Map<String, Object?> json) {
+    final valueSetJson = json['valueSet'];
+    final valueSet = (valueSetJson as List<Object?>)
+        .map((item) => InsertTextMode.fromJson(item as num))
+        .toList();
     return CompletionClientCapabilitiesInsertTextModeSupport(
         valueSet: valueSet);
   }
 
   final List<InsertTextMode> valueSet;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['valueSet'] = valueSet.map((item) => item.toJson()).toList();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('valueSet');
       try {
         if (!obj.containsKey('valueSet')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['valueSet'] == null) {
+        final valueSet = obj['valueSet'];
+        if (valueSet == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['valueSet'] is List &&
-            (obj['valueSet']
+        if (!((valueSet is List &&
+            (valueSet
                 .every((item) => InsertTextMode.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<InsertTextMode>');
           return false;
@@ -5590,35 +5838,38 @@
 
   CompletionClientCapabilitiesResolveSupport({required this.properties});
   static CompletionClientCapabilitiesResolveSupport fromJson(
-      Map<String, dynamic> json) {
-    final properties =
-        json['properties']?.map((item) => item)?.cast<String>()?.toList();
+      Map<String, Object?> json) {
+    final propertiesJson = json['properties'];
+    final properties = (propertiesJson as List<Object?>)
+        .map((item) => item as String)
+        .toList();
     return CompletionClientCapabilitiesResolveSupport(properties: properties);
   }
 
   /// The properties that a client can resolve lazily.
   final List<String> properties;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['properties'] = properties;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('properties');
       try {
         if (!obj.containsKey('properties')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['properties'] == null) {
+        final properties = obj['properties'];
+        if (properties == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['properties'] is List &&
-            (obj['properties'].every((item) => item is String))))) {
+        if (!((properties is List &&
+            (properties.every((item) => item is String))))) {
           reporter.reportError('must be of type List<String>');
           return false;
         }
@@ -5662,37 +5913,38 @@
 
   CompletionClientCapabilitiesTagSupport({required this.valueSet});
   static CompletionClientCapabilitiesTagSupport fromJson(
-      Map<String, dynamic> json) {
-    final valueSet = json['valueSet']
-        ?.map((item) => CompletionItemTag.fromJson(item))
-        ?.cast<CompletionItemTag>()
-        ?.toList();
+      Map<String, Object?> json) {
+    final valueSetJson = json['valueSet'];
+    final valueSet = (valueSetJson as List<Object?>)
+        .map((item) => CompletionItemTag.fromJson(item as int))
+        .toList();
     return CompletionClientCapabilitiesTagSupport(valueSet: valueSet);
   }
 
   /// The tags supported by the client.
   final List<CompletionItemTag> valueSet;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['valueSet'] = valueSet.map((item) => item.toJson()).toList();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('valueSet');
       try {
         if (!obj.containsKey('valueSet')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['valueSet'] == null) {
+        final valueSet = obj['valueSet'];
+        if (valueSet == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['valueSet'] is List &&
-            (obj['valueSet'].every(
+        if (!((valueSet is List &&
+            (valueSet.every(
                 (item) => CompletionItemTag.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<CompletionItemTag>');
           return false;
@@ -5737,9 +5989,11 @@
       LspJsonHandler(CompletionContext.canParse, CompletionContext.fromJson);
 
   CompletionContext({required this.triggerKind, this.triggerCharacter});
-  static CompletionContext fromJson(Map<String, dynamic> json) {
-    final triggerKind = CompletionTriggerKind.fromJson(json['triggerKind']);
-    final triggerCharacter = json['triggerCharacter'];
+  static CompletionContext fromJson(Map<String, Object?> json) {
+    final triggerKindJson = json['triggerKind'];
+    final triggerKind = CompletionTriggerKind.fromJson(triggerKindJson as num);
+    final triggerCharacterJson = json['triggerCharacter'];
+    final triggerCharacter = triggerCharacterJson as String?;
     return CompletionContext(
         triggerKind: triggerKind, triggerCharacter: triggerCharacter);
   }
@@ -5751,8 +6005,8 @@
   /// How the completion was triggered.
   final CompletionTriggerKind triggerKind;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['triggerKind'] = triggerKind.toJson();
     if (triggerCharacter != null) {
       __result['triggerCharacter'] = triggerCharacter;
@@ -5761,18 +6015,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('triggerKind');
       try {
         if (!obj.containsKey('triggerKind')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['triggerKind'] == null) {
+        final triggerKind = obj['triggerKind'];
+        if (triggerKind == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(CompletionTriggerKind.canParse(obj['triggerKind'], reporter))) {
+        if (!(CompletionTriggerKind.canParse(triggerKind, reporter))) {
           reporter.reportError('must be of type CompletionTriggerKind');
           return false;
         }
@@ -5781,8 +6036,8 @@
       }
       reporter.push('triggerCharacter');
       try {
-        if (obj['triggerCharacter'] != null &&
-            !(obj['triggerCharacter'] is String)) {
+        final triggerCharacter = obj['triggerCharacter'];
+        if (triggerCharacter != null && !(triggerCharacter is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -5840,54 +6095,72 @@
       this.commitCharacters,
       this.command,
       this.data});
-  static CompletionItem fromJson(Map<String, dynamic> json) {
-    final label = json['label'];
+  static CompletionItem fromJson(Map<String, Object?> json) {
+    final labelJson = json['label'];
+    final label = labelJson as String;
+    final kindJson = json['kind'];
     final kind =
-        json['kind'] != null ? CompletionItemKind.fromJson(json['kind']) : null;
-    final tags = json['tags']
-        ?.map((item) => item != null ? CompletionItemTag.fromJson(item) : null)
-        ?.cast<CompletionItemTag>()
-        ?.toList();
-    final detail = json['detail'];
-    final documentation = json['documentation'] == null
+        kindJson != null ? CompletionItemKind.fromJson(kindJson as int) : null;
+    final tagsJson = json['tags'];
+    final tags = (tagsJson as List<Object?>?)
+        ?.map((item) => CompletionItemTag.fromJson(item as int))
+        .toList();
+    final detailJson = json['detail'];
+    final detail = detailJson as String?;
+    final documentationJson = json['documentation'];
+    final documentation = documentationJson == null
         ? null
-        : (json['documentation'] is String
-            ? Either2<String, MarkupContent>.t1(json['documentation'])
-            : (MarkupContent.canParse(
-                    json['documentation'], nullLspJsonReporter)
-                ? Either2<String, MarkupContent>.t2(
-                    MarkupContent.fromJson(json['documentation']))
-                : (throw '''${json['documentation']} was not one of (String, MarkupContent)''')));
-    final deprecated = json['deprecated'];
-    final preselect = json['preselect'];
-    final sortText = json['sortText'];
-    final filterText = json['filterText'];
-    final insertText = json['insertText'];
-    final insertTextFormat = json['insertTextFormat'] != null
-        ? InsertTextFormat.fromJson(json['insertTextFormat'])
+        : (documentationJson is String
+            ? Either2<String, MarkupContent>.t1(documentationJson)
+            : (MarkupContent.canParse(documentationJson, nullLspJsonReporter)
+                ? Either2<String, MarkupContent>.t2(MarkupContent.fromJson(
+                    documentationJson as Map<String, Object?>))
+                : (throw '''$documentationJson was not one of (String, MarkupContent)''')));
+    final deprecatedJson = json['deprecated'];
+    final deprecated = deprecatedJson as bool?;
+    final preselectJson = json['preselect'];
+    final preselect = preselectJson as bool?;
+    final sortTextJson = json['sortText'];
+    final sortText = sortTextJson as String?;
+    final filterTextJson = json['filterText'];
+    final filterText = filterTextJson as String?;
+    final insertTextJson = json['insertText'];
+    final insertText = insertTextJson as String?;
+    final insertTextFormatJson = json['insertTextFormat'];
+    final insertTextFormat = insertTextFormatJson != null
+        ? InsertTextFormat.fromJson(insertTextFormatJson as int)
         : null;
-    final insertTextMode = json['insertTextMode'] != null
-        ? InsertTextMode.fromJson(json['insertTextMode'])
+    final insertTextModeJson = json['insertTextMode'];
+    final insertTextMode = insertTextModeJson != null
+        ? InsertTextMode.fromJson(insertTextModeJson as num)
         : null;
-    final textEdit = json['textEdit'] == null
+    final textEditJson = json['textEdit'];
+    final textEdit = textEditJson == null
         ? null
-        : (TextEdit.canParse(json['textEdit'], nullLspJsonReporter)
+        : (TextEdit.canParse(textEditJson, nullLspJsonReporter)
             ? Either2<TextEdit, InsertReplaceEdit>.t1(
-                TextEdit.fromJson(json['textEdit']))
-            : (InsertReplaceEdit.canParse(json['textEdit'], nullLspJsonReporter)
+                TextEdit.fromJson(textEditJson as Map<String, Object?>))
+            : (InsertReplaceEdit.canParse(textEditJson, nullLspJsonReporter)
                 ? Either2<TextEdit, InsertReplaceEdit>.t2(
-                    InsertReplaceEdit.fromJson(json['textEdit']))
-                : (throw '''${json['textEdit']} was not one of (TextEdit, InsertReplaceEdit)''')));
-    final additionalTextEdits = json['additionalTextEdits']
-        ?.map((item) => item != null ? TextEdit.fromJson(item) : null)
-        ?.cast<TextEdit>()
-        ?.toList();
-    final commitCharacters =
-        json['commitCharacters']?.map((item) => item)?.cast<String>()?.toList();
-    final command =
-        json['command'] != null ? Command.fromJson(json['command']) : null;
-    final data = json['data'] != null
-        ? CompletionItemResolutionInfo.fromJson(json['data'])
+                    InsertReplaceEdit.fromJson(
+                        textEditJson as Map<String, Object?>))
+                : (throw '''$textEditJson was not one of (TextEdit, InsertReplaceEdit)''')));
+    final additionalTextEditsJson = json['additionalTextEdits'];
+    final additionalTextEdits = (additionalTextEditsJson as List<Object?>?)
+        ?.map((item) => TextEdit.fromJson(item as Map<String, Object?>))
+        .toList();
+    final commitCharactersJson = json['commitCharacters'];
+    final commitCharacters = (commitCharactersJson as List<Object?>?)
+        ?.map((item) => item as String)
+        .toList();
+    final commandJson = json['command'];
+    final command = commandJson != null
+        ? Command.fromJson(commandJson as Map<String, Object?>)
+        : null;
+    final dataJson = json['data'];
+    final data = dataJson != null
+        ? CompletionItemResolutionInfo.fromJson(
+            dataJson as Map<String, Object?>)
         : null;
     return CompletionItem(
         label: label,
@@ -6016,8 +6289,8 @@
   ///  @since 3.16.0 additional type `InsertReplaceEdit`
   final Either2<TextEdit, InsertReplaceEdit>? textEdit;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['label'] = label;
     if (kind != null) {
       __result['kind'] = kind?.toJson();
@@ -6072,18 +6345,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('label');
       try {
         if (!obj.containsKey('label')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['label'] == null) {
+        final label = obj['label'];
+        if (label == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['label'] is String)) {
+        if (!(label is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -6092,8 +6366,8 @@
       }
       reporter.push('kind');
       try {
-        if (obj['kind'] != null &&
-            !(CompletionItemKind.canParse(obj['kind'], reporter))) {
+        final kind = obj['kind'];
+        if (kind != null && !(CompletionItemKind.canParse(kind, reporter))) {
           reporter.reportError('must be of type CompletionItemKind');
           return false;
         }
@@ -6102,9 +6376,10 @@
       }
       reporter.push('tags');
       try {
-        if (obj['tags'] != null &&
-            !((obj['tags'] is List &&
-                (obj['tags'].every(
+        final tags = obj['tags'];
+        if (tags != null &&
+            !((tags is List &&
+                (tags.every(
                     (item) => CompletionItemTag.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<CompletionItemTag>');
           return false;
@@ -6114,7 +6389,8 @@
       }
       reporter.push('detail');
       try {
-        if (obj['detail'] != null && !(obj['detail'] is String)) {
+        final detail = obj['detail'];
+        if (detail != null && !(detail is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -6123,9 +6399,10 @@
       }
       reporter.push('documentation');
       try {
-        if (obj['documentation'] != null &&
-            !((obj['documentation'] is String ||
-                MarkupContent.canParse(obj['documentation'], reporter)))) {
+        final documentation = obj['documentation'];
+        if (documentation != null &&
+            !((documentation is String ||
+                MarkupContent.canParse(documentation, reporter)))) {
           reporter
               .reportError('must be of type Either2<String, MarkupContent>');
           return false;
@@ -6135,7 +6412,8 @@
       }
       reporter.push('deprecated');
       try {
-        if (obj['deprecated'] != null && !(obj['deprecated'] is bool)) {
+        final deprecated = obj['deprecated'];
+        if (deprecated != null && !(deprecated is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -6144,7 +6422,8 @@
       }
       reporter.push('preselect');
       try {
-        if (obj['preselect'] != null && !(obj['preselect'] is bool)) {
+        final preselect = obj['preselect'];
+        if (preselect != null && !(preselect is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -6153,7 +6432,8 @@
       }
       reporter.push('sortText');
       try {
-        if (obj['sortText'] != null && !(obj['sortText'] is String)) {
+        final sortText = obj['sortText'];
+        if (sortText != null && !(sortText is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -6162,7 +6442,8 @@
       }
       reporter.push('filterText');
       try {
-        if (obj['filterText'] != null && !(obj['filterText'] is String)) {
+        final filterText = obj['filterText'];
+        if (filterText != null && !(filterText is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -6171,7 +6452,8 @@
       }
       reporter.push('insertText');
       try {
-        if (obj['insertText'] != null && !(obj['insertText'] is String)) {
+        final insertText = obj['insertText'];
+        if (insertText != null && !(insertText is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -6180,8 +6462,9 @@
       }
       reporter.push('insertTextFormat');
       try {
-        if (obj['insertTextFormat'] != null &&
-            !(InsertTextFormat.canParse(obj['insertTextFormat'], reporter))) {
+        final insertTextFormat = obj['insertTextFormat'];
+        if (insertTextFormat != null &&
+            !(InsertTextFormat.canParse(insertTextFormat, reporter))) {
           reporter.reportError('must be of type InsertTextFormat');
           return false;
         }
@@ -6190,8 +6473,9 @@
       }
       reporter.push('insertTextMode');
       try {
-        if (obj['insertTextMode'] != null &&
-            !(InsertTextMode.canParse(obj['insertTextMode'], reporter))) {
+        final insertTextMode = obj['insertTextMode'];
+        if (insertTextMode != null &&
+            !(InsertTextMode.canParse(insertTextMode, reporter))) {
           reporter.reportError('must be of type InsertTextMode');
           return false;
         }
@@ -6200,9 +6484,10 @@
       }
       reporter.push('textEdit');
       try {
-        if (obj['textEdit'] != null &&
-            !((TextEdit.canParse(obj['textEdit'], reporter) ||
-                InsertReplaceEdit.canParse(obj['textEdit'], reporter)))) {
+        final textEdit = obj['textEdit'];
+        if (textEdit != null &&
+            !((TextEdit.canParse(textEdit, reporter) ||
+                InsertReplaceEdit.canParse(textEdit, reporter)))) {
           reporter.reportError(
               'must be of type Either2<TextEdit, InsertReplaceEdit>');
           return false;
@@ -6212,9 +6497,10 @@
       }
       reporter.push('additionalTextEdits');
       try {
-        if (obj['additionalTextEdits'] != null &&
-            !((obj['additionalTextEdits'] is List &&
-                (obj['additionalTextEdits']
+        final additionalTextEdits = obj['additionalTextEdits'];
+        if (additionalTextEdits != null &&
+            !((additionalTextEdits is List &&
+                (additionalTextEdits
                     .every((item) => TextEdit.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<TextEdit>');
           return false;
@@ -6224,9 +6510,10 @@
       }
       reporter.push('commitCharacters');
       try {
-        if (obj['commitCharacters'] != null &&
-            !((obj['commitCharacters'] is List &&
-                (obj['commitCharacters'].every((item) => item is String))))) {
+        final commitCharacters = obj['commitCharacters'];
+        if (commitCharacters != null &&
+            !((commitCharacters is List &&
+                (commitCharacters.every((item) => item is String))))) {
           reporter.reportError('must be of type List<String>');
           return false;
         }
@@ -6235,8 +6522,8 @@
       }
       reporter.push('command');
       try {
-        if (obj['command'] != null &&
-            !(Command.canParse(obj['command'], reporter))) {
+        final command = obj['command'];
+        if (command != null && !(Command.canParse(command, reporter))) {
           reporter.reportError('must be of type Command');
           return false;
         }
@@ -6245,8 +6532,9 @@
       }
       reporter.push('data');
       try {
-        if (obj['data'] != null &&
-            !(CompletionItemResolutionInfo.canParse(obj['data'], reporter))) {
+        final data = obj['data'];
+        if (data != null &&
+            !(CompletionItemResolutionInfo.canParse(data, reporter))) {
           reporter.reportError('must be of type CompletionItemResolutionInfo');
           return false;
         }
@@ -6397,12 +6685,13 @@
       LspJsonHandler(CompletionList.canParse, CompletionList.fromJson);
 
   CompletionList({required this.isIncomplete, required this.items});
-  static CompletionList fromJson(Map<String, dynamic> json) {
-    final isIncomplete = json['isIncomplete'];
-    final items = json['items']
-        ?.map((item) => CompletionItem.fromJson(item))
-        ?.cast<CompletionItem>()
-        ?.toList();
+  static CompletionList fromJson(Map<String, Object?> json) {
+    final isIncompleteJson = json['isIncomplete'];
+    final isIncomplete = isIncompleteJson as bool;
+    final itemsJson = json['items'];
+    final items = (itemsJson as List<Object?>)
+        .map((item) => CompletionItem.fromJson(item as Map<String, Object?>))
+        .toList();
     return CompletionList(isIncomplete: isIncomplete, items: items);
   }
 
@@ -6413,26 +6702,27 @@
   /// The completion items.
   final List<CompletionItem> items;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['isIncomplete'] = isIncomplete;
     __result['items'] = items.map((item) => item.toJson()).toList();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('isIncomplete');
       try {
         if (!obj.containsKey('isIncomplete')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['isIncomplete'] == null) {
+        final isIncomplete = obj['isIncomplete'];
+        if (isIncomplete == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['isIncomplete'] is bool)) {
+        if (!(isIncomplete is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -6445,12 +6735,13 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['items'] == null) {
+        final items = obj['items'];
+        if (items == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['items'] is List &&
-            (obj['items']
+        if (!((items is List &&
+            (items
                 .every((item) => CompletionItem.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<CompletionItem>');
           return false;
@@ -6498,20 +6789,22 @@
       this.allCommitCharacters,
       this.resolveProvider,
       this.workDoneProgress});
-  static CompletionOptions fromJson(Map<String, dynamic> json) {
+  static CompletionOptions fromJson(Map<String, Object?> json) {
     if (CompletionRegistrationOptions.canParse(json, nullLspJsonReporter)) {
       return CompletionRegistrationOptions.fromJson(json);
     }
-    final triggerCharacters = json['triggerCharacters']
-        ?.map((item) => item)
-        ?.cast<String>()
-        ?.toList();
-    final allCommitCharacters = json['allCommitCharacters']
-        ?.map((item) => item)
-        ?.cast<String>()
-        ?.toList();
-    final resolveProvider = json['resolveProvider'];
-    final workDoneProgress = json['workDoneProgress'];
+    final triggerCharactersJson = json['triggerCharacters'];
+    final triggerCharacters = (triggerCharactersJson as List<Object?>?)
+        ?.map((item) => item as String)
+        .toList();
+    final allCommitCharactersJson = json['allCommitCharacters'];
+    final allCommitCharacters = (allCommitCharactersJson as List<Object?>?)
+        ?.map((item) => item as String)
+        .toList();
+    final resolveProviderJson = json['resolveProvider'];
+    final resolveProvider = resolveProviderJson as bool?;
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return CompletionOptions(
         triggerCharacters: triggerCharacters,
         allCommitCharacters: allCommitCharacters,
@@ -6546,8 +6839,8 @@
   final List<String>? triggerCharacters;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (triggerCharacters != null) {
       __result['triggerCharacters'] = triggerCharacters;
     }
@@ -6564,12 +6857,13 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('triggerCharacters');
       try {
-        if (obj['triggerCharacters'] != null &&
-            !((obj['triggerCharacters'] is List &&
-                (obj['triggerCharacters'].every((item) => item is String))))) {
+        final triggerCharacters = obj['triggerCharacters'];
+        if (triggerCharacters != null &&
+            !((triggerCharacters is List &&
+                (triggerCharacters.every((item) => item is String))))) {
           reporter.reportError('must be of type List<String>');
           return false;
         }
@@ -6578,10 +6872,10 @@
       }
       reporter.push('allCommitCharacters');
       try {
-        if (obj['allCommitCharacters'] != null &&
-            !((obj['allCommitCharacters'] is List &&
-                (obj['allCommitCharacters']
-                    .every((item) => item is String))))) {
+        final allCommitCharacters = obj['allCommitCharacters'];
+        if (allCommitCharacters != null &&
+            !((allCommitCharacters is List &&
+                (allCommitCharacters.every((item) => item is String))))) {
           reporter.reportError('must be of type List<String>');
           return false;
         }
@@ -6590,8 +6884,8 @@
       }
       reporter.push('resolveProvider');
       try {
-        if (obj['resolveProvider'] != null &&
-            !(obj['resolveProvider'] is bool)) {
+        final resolveProvider = obj['resolveProvider'];
+        if (resolveProvider != null && !(resolveProvider is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -6600,8 +6894,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -6658,26 +6952,32 @@
       required this.position,
       this.workDoneToken,
       this.partialResultToken});
-  static CompletionParams fromJson(Map<String, dynamic> json) {
-    final context = json['context'] != null
-        ? CompletionContext.fromJson(json['context'])
+  static CompletionParams fromJson(Map<String, Object?> json) {
+    final contextJson = json['context'];
+    final context = contextJson != null
+        ? CompletionContext.fromJson(contextJson as Map<String, Object?>)
         : null;
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final position = Position.fromJson(json['position']);
-    final workDoneToken = json['workDoneToken'] == null
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final positionJson = json['position'];
+    final position = Position.fromJson(positionJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
-    final partialResultToken = json['partialResultToken'] == null
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
+    final partialResultTokenJson = json['partialResultToken'];
+    final partialResultToken = partialResultTokenJson == null
         ? null
-        : (json['partialResultToken'] is int
-            ? Either2<int, String>.t1(json['partialResultToken'])
-            : (json['partialResultToken'] is String
-                ? Either2<int, String>.t2(json['partialResultToken'])
-                : (throw '''${json['partialResultToken']} was not one of (int, String)''')));
+        : (partialResultTokenJson is int
+            ? Either2<int, String>.t1(partialResultTokenJson)
+            : (partialResultTokenJson is String
+                ? Either2<int, String>.t2(partialResultTokenJson)
+                : (throw '''$partialResultTokenJson was not one of (int, String)''')));
     return CompletionParams(
         context: context,
         textDocument: textDocument,
@@ -6703,8 +7003,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (context != null) {
       __result['context'] = context?.toJson();
     }
@@ -6720,11 +7020,12 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('context');
       try {
-        if (obj['context'] != null &&
-            !(CompletionContext.canParse(obj['context'], reporter))) {
+        final context = obj['context'];
+        if (context != null &&
+            !(CompletionContext.canParse(context, reporter))) {
           reporter.reportError('must be of type CompletionContext');
           return false;
         }
@@ -6737,11 +7038,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -6754,11 +7056,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['position'] == null) {
+        final position = obj['position'];
+        if (position == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Position.canParse(obj['position'], reporter))) {
+        if (!(Position.canParse(position, reporter))) {
           reporter.reportError('must be of type Position');
           return false;
         }
@@ -6767,9 +7070,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -6778,9 +7081,9 @@
       }
       reporter.push('partialResultToken');
       try {
-        if (obj['partialResultToken'] != null &&
-            !((obj['partialResultToken'] is int ||
-                obj['partialResultToken'] is String))) {
+        final partialResultToken = obj['partialResultToken'];
+        if (partialResultToken != null &&
+            !((partialResultToken is int || partialResultToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -6834,21 +7137,23 @@
       this.allCommitCharacters,
       this.resolveProvider,
       this.workDoneProgress});
-  static CompletionRegistrationOptions fromJson(Map<String, dynamic> json) {
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final triggerCharacters = json['triggerCharacters']
-        ?.map((item) => item)
-        ?.cast<String>()
-        ?.toList();
-    final allCommitCharacters = json['allCommitCharacters']
-        ?.map((item) => item)
-        ?.cast<String>()
-        ?.toList();
-    final resolveProvider = json['resolveProvider'];
-    final workDoneProgress = json['workDoneProgress'];
+  static CompletionRegistrationOptions fromJson(Map<String, Object?> json) {
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final triggerCharactersJson = json['triggerCharacters'];
+    final triggerCharacters = (triggerCharactersJson as List<Object?>?)
+        ?.map((item) => item as String)
+        .toList();
+    final allCommitCharactersJson = json['allCommitCharacters'];
+    final allCommitCharacters = (allCommitCharactersJson as List<Object?>?)
+        ?.map((item) => item as String)
+        .toList();
+    final resolveProviderJson = json['resolveProvider'];
+    final resolveProvider = resolveProviderJson as bool?;
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return CompletionRegistrationOptions(
         documentSelector: documentSelector,
         triggerCharacters: triggerCharacters,
@@ -6888,8 +7193,8 @@
   final List<String>? triggerCharacters;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['documentSelector'] = documentSelector;
     if (triggerCharacters != null) {
       __result['triggerCharacters'] = triggerCharacters;
@@ -6907,16 +7212,17 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentSelector');
       try {
         if (!obj.containsKey('documentSelector')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -6926,9 +7232,10 @@
       }
       reporter.push('triggerCharacters');
       try {
-        if (obj['triggerCharacters'] != null &&
-            !((obj['triggerCharacters'] is List &&
-                (obj['triggerCharacters'].every((item) => item is String))))) {
+        final triggerCharacters = obj['triggerCharacters'];
+        if (triggerCharacters != null &&
+            !((triggerCharacters is List &&
+                (triggerCharacters.every((item) => item is String))))) {
           reporter.reportError('must be of type List<String>');
           return false;
         }
@@ -6937,10 +7244,10 @@
       }
       reporter.push('allCommitCharacters');
       try {
-        if (obj['allCommitCharacters'] != null &&
-            !((obj['allCommitCharacters'] is List &&
-                (obj['allCommitCharacters']
-                    .every((item) => item is String))))) {
+        final allCommitCharacters = obj['allCommitCharacters'];
+        if (allCommitCharacters != null &&
+            !((allCommitCharacters is List &&
+                (allCommitCharacters.every((item) => item is String))))) {
           reporter.reportError('must be of type List<String>');
           return false;
         }
@@ -6949,8 +7256,8 @@
       }
       reporter.push('resolveProvider');
       try {
-        if (obj['resolveProvider'] != null &&
-            !(obj['resolveProvider'] is bool)) {
+        final resolveProvider = obj['resolveProvider'];
+        if (resolveProvider != null && !(resolveProvider is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -6959,8 +7266,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -7051,9 +7358,11 @@
       LspJsonHandler(ConfigurationItem.canParse, ConfigurationItem.fromJson);
 
   ConfigurationItem({this.scopeUri, this.section});
-  static ConfigurationItem fromJson(Map<String, dynamic> json) {
-    final scopeUri = json['scopeUri'];
-    final section = json['section'];
+  static ConfigurationItem fromJson(Map<String, Object?> json) {
+    final scopeUriJson = json['scopeUri'];
+    final scopeUri = scopeUriJson as String?;
+    final sectionJson = json['section'];
+    final section = sectionJson as String?;
     return ConfigurationItem(scopeUri: scopeUri, section: section);
   }
 
@@ -7063,8 +7372,8 @@
   /// The configuration section asked for.
   final String? section;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (scopeUri != null) {
       __result['scopeUri'] = scopeUri;
     }
@@ -7075,10 +7384,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('scopeUri');
       try {
-        if (obj['scopeUri'] != null && !(obj['scopeUri'] is String)) {
+        final scopeUri = obj['scopeUri'];
+        if (scopeUri != null && !(scopeUri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -7087,7 +7397,8 @@
       }
       reporter.push('section');
       try {
-        if (obj['section'] != null && !(obj['section'] is String)) {
+        final section = obj['section'];
+        if (section != null && !(section is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -7126,36 +7437,37 @@
       ConfigurationParams.canParse, ConfigurationParams.fromJson);
 
   ConfigurationParams({required this.items});
-  static ConfigurationParams fromJson(Map<String, dynamic> json) {
-    final items = json['items']
-        ?.map((item) => ConfigurationItem.fromJson(item))
-        ?.cast<ConfigurationItem>()
-        ?.toList();
+  static ConfigurationParams fromJson(Map<String, Object?> json) {
+    final itemsJson = json['items'];
+    final items = (itemsJson as List<Object?>)
+        .map((item) => ConfigurationItem.fromJson(item as Map<String, Object?>))
+        .toList();
     return ConfigurationParams(items: items);
   }
 
   final List<ConfigurationItem> items;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['items'] = items.map((item) => item.toJson()).toList();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('items');
       try {
         if (!obj.containsKey('items')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['items'] == null) {
+        final items = obj['items'];
+        if (items == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['items'] is List &&
-            (obj['items'].every(
+        if (!((items is List &&
+            (items.every(
                 (item) => ConfigurationItem.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<ConfigurationItem>');
           return false;
@@ -7206,13 +7518,17 @@
       throw 'kind may only be the literal \'create\'';
     }
   }
-  static CreateFile fromJson(Map<String, dynamic> json) {
-    final kind = json['kind'];
-    final uri = json['uri'];
-    final options = json['options'] != null
-        ? CreateFileOptions.fromJson(json['options'])
+  static CreateFile fromJson(Map<String, Object?> json) {
+    final kindJson = json['kind'];
+    final kind = kindJson as String;
+    final uriJson = json['uri'];
+    final uri = uriJson as String;
+    final optionsJson = json['options'];
+    final options = optionsJson != null
+        ? CreateFileOptions.fromJson(optionsJson as Map<String, Object?>)
         : null;
-    final annotationId = json['annotationId'];
+    final annotationIdJson = json['annotationId'];
+    final annotationId = annotationIdJson as String?;
     return CreateFile(
         kind: kind, uri: uri, options: options, annotationId: annotationId);
   }
@@ -7230,8 +7546,8 @@
   /// The resource to create.
   final String uri;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['kind'] = kind;
     __result['uri'] = uri;
     if (options != null) {
@@ -7244,18 +7560,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('kind');
       try {
         if (!obj.containsKey('kind')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['kind'] == null) {
+        final kind = obj['kind'];
+        if (kind == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['kind'] == 'create')) {
+        if (!(kind == 'create')) {
           reporter.reportError('must be the literal \'create\'');
           return false;
         }
@@ -7268,11 +7585,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['uri'] == null) {
+        final uri = obj['uri'];
+        if (uri == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['uri'] is String)) {
+        if (!(uri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -7281,8 +7599,9 @@
       }
       reporter.push('options');
       try {
-        if (obj['options'] != null &&
-            !(CreateFileOptions.canParse(obj['options'], reporter))) {
+        final options = obj['options'];
+        if (options != null &&
+            !(CreateFileOptions.canParse(options, reporter))) {
           reporter.reportError('must be of type CreateFileOptions');
           return false;
         }
@@ -7291,7 +7610,8 @@
       }
       reporter.push('annotationId');
       try {
-        if (obj['annotationId'] != null && !(obj['annotationId'] is String)) {
+        final annotationId = obj['annotationId'];
+        if (annotationId != null && !(annotationId is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -7337,9 +7657,11 @@
       LspJsonHandler(CreateFileOptions.canParse, CreateFileOptions.fromJson);
 
   CreateFileOptions({this.overwrite, this.ignoreIfExists});
-  static CreateFileOptions fromJson(Map<String, dynamic> json) {
-    final overwrite = json['overwrite'];
-    final ignoreIfExists = json['ignoreIfExists'];
+  static CreateFileOptions fromJson(Map<String, Object?> json) {
+    final overwriteJson = json['overwrite'];
+    final overwrite = overwriteJson as bool?;
+    final ignoreIfExistsJson = json['ignoreIfExists'];
+    final ignoreIfExists = ignoreIfExistsJson as bool?;
     return CreateFileOptions(
         overwrite: overwrite, ignoreIfExists: ignoreIfExists);
   }
@@ -7350,8 +7672,8 @@
   /// Overwrite existing file. Overwrite wins over `ignoreIfExists`
   final bool? overwrite;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (overwrite != null) {
       __result['overwrite'] = overwrite;
     }
@@ -7362,10 +7684,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('overwrite');
       try {
-        if (obj['overwrite'] != null && !(obj['overwrite'] is bool)) {
+        final overwrite = obj['overwrite'];
+        if (overwrite != null && !(overwrite is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -7374,7 +7697,8 @@
       }
       reporter.push('ignoreIfExists');
       try {
-        if (obj['ignoreIfExists'] != null && !(obj['ignoreIfExists'] is bool)) {
+        final ignoreIfExists = obj['ignoreIfExists'];
+        if (ignoreIfExists != null && !(ignoreIfExists is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -7418,38 +7742,38 @@
       LspJsonHandler(CreateFilesParams.canParse, CreateFilesParams.fromJson);
 
   CreateFilesParams({required this.files});
-  static CreateFilesParams fromJson(Map<String, dynamic> json) {
-    final files = json['files']
-        ?.map((item) => FileCreate.fromJson(item))
-        ?.cast<FileCreate>()
-        ?.toList();
+  static CreateFilesParams fromJson(Map<String, Object?> json) {
+    final filesJson = json['files'];
+    final files = (filesJson as List<Object?>)
+        .map((item) => FileCreate.fromJson(item as Map<String, Object?>))
+        .toList();
     return CreateFilesParams(files: files);
   }
 
   /// An array of all files/folders created in this operation.
   final List<FileCreate> files;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['files'] = files.map((item) => item.toJson()).toList();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('files');
       try {
         if (!obj.containsKey('files')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['files'] == null) {
+        final files = obj['files'];
+        if (files == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['files'] is List &&
-            (obj['files']
-                .every((item) => FileCreate.canParse(item, reporter)))))) {
+        if (!((files is List &&
+            (files.every((item) => FileCreate.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<FileCreate>');
           return false;
         }
@@ -7490,9 +7814,11 @@
       DeclarationClientCapabilities.fromJson);
 
   DeclarationClientCapabilities({this.dynamicRegistration, this.linkSupport});
-  static DeclarationClientCapabilities fromJson(Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
-    final linkSupport = json['linkSupport'];
+  static DeclarationClientCapabilities fromJson(Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
+    final linkSupportJson = json['linkSupport'];
+    final linkSupport = linkSupportJson as bool?;
     return DeclarationClientCapabilities(
         dynamicRegistration: dynamicRegistration, linkSupport: linkSupport);
   }
@@ -7505,8 +7831,8 @@
   /// The client supports additional metadata in the form of declaration links.
   final bool? linkSupport;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -7517,11 +7843,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -7530,7 +7856,8 @@
       }
       reporter.push('linkSupport');
       try {
-        if (obj['linkSupport'] != null && !(obj['linkSupport'] is bool)) {
+        final linkSupport = obj['linkSupport'];
+        if (linkSupport != null && !(linkSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -7572,18 +7899,19 @@
       LspJsonHandler(DeclarationOptions.canParse, DeclarationOptions.fromJson);
 
   DeclarationOptions({this.workDoneProgress});
-  static DeclarationOptions fromJson(Map<String, dynamic> json) {
+  static DeclarationOptions fromJson(Map<String, Object?> json) {
     if (DeclarationRegistrationOptions.canParse(json, nullLspJsonReporter)) {
       return DeclarationRegistrationOptions.fromJson(json);
     }
-    final workDoneProgress = json['workDoneProgress'];
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return DeclarationOptions(workDoneProgress: workDoneProgress);
   }
 
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
     }
@@ -7591,11 +7919,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -7643,23 +7971,28 @@
       required this.position,
       this.workDoneToken,
       this.partialResultToken});
-  static DeclarationParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final position = Position.fromJson(json['position']);
-    final workDoneToken = json['workDoneToken'] == null
+  static DeclarationParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final positionJson = json['position'];
+    final position = Position.fromJson(positionJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
-    final partialResultToken = json['partialResultToken'] == null
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
+    final partialResultTokenJson = json['partialResultToken'];
+    final partialResultToken = partialResultTokenJson == null
         ? null
-        : (json['partialResultToken'] is int
-            ? Either2<int, String>.t1(json['partialResultToken'])
-            : (json['partialResultToken'] is String
-                ? Either2<int, String>.t2(json['partialResultToken'])
-                : (throw '''${json['partialResultToken']} was not one of (int, String)''')));
+        : (partialResultTokenJson is int
+            ? Either2<int, String>.t1(partialResultTokenJson)
+            : (partialResultTokenJson is String
+                ? Either2<int, String>.t2(partialResultTokenJson)
+                : (throw '''$partialResultTokenJson was not one of (int, String)''')));
     return DeclarationParams(
         textDocument: textDocument,
         position: position,
@@ -7680,8 +8013,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     __result['position'] = position.toJson();
     if (workDoneToken != null) {
@@ -7694,18 +8027,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -7718,11 +8052,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['position'] == null) {
+        final position = obj['position'];
+        if (position == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Position.canParse(obj['position'], reporter))) {
+        if (!(Position.canParse(position, reporter))) {
           reporter.reportError('must be of type Position');
           return false;
         }
@@ -7731,9 +8066,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -7742,9 +8077,9 @@
       }
       reporter.push('partialResultToken');
       try {
-        if (obj['partialResultToken'] != null &&
-            !((obj['partialResultToken'] is int ||
-                obj['partialResultToken'] is String))) {
+        final partialResultToken = obj['partialResultToken'];
+        if (partialResultToken != null &&
+            !((partialResultToken is int || partialResultToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -7796,13 +8131,15 @@
 
   DeclarationRegistrationOptions(
       {this.workDoneProgress, this.documentSelector, this.id});
-  static DeclarationRegistrationOptions fromJson(Map<String, dynamic> json) {
-    final workDoneProgress = json['workDoneProgress'];
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final id = json['id'];
+  static DeclarationRegistrationOptions fromJson(Map<String, Object?> json) {
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final idJson = json['id'];
+    final id = idJson as String?;
     return DeclarationRegistrationOptions(
         workDoneProgress: workDoneProgress,
         documentSelector: documentSelector,
@@ -7818,8 +8155,8 @@
   final String? id;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
     }
@@ -7831,11 +8168,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -7848,9 +8185,10 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -7860,7 +8198,8 @@
       }
       reporter.push('id');
       try {
-        if (obj['id'] != null && !(obj['id'] is String)) {
+        final id = obj['id'];
+        if (id != null && !(id is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -7906,9 +8245,11 @@
       DefinitionClientCapabilities.fromJson);
 
   DefinitionClientCapabilities({this.dynamicRegistration, this.linkSupport});
-  static DefinitionClientCapabilities fromJson(Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
-    final linkSupport = json['linkSupport'];
+  static DefinitionClientCapabilities fromJson(Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
+    final linkSupportJson = json['linkSupport'];
+    final linkSupport = linkSupportJson as bool?;
     return DefinitionClientCapabilities(
         dynamicRegistration: dynamicRegistration, linkSupport: linkSupport);
   }
@@ -7920,8 +8261,8 @@
   ///  @since 3.14.0
   final bool? linkSupport;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -7932,11 +8273,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -7945,7 +8286,8 @@
       }
       reporter.push('linkSupport');
       try {
-        if (obj['linkSupport'] != null && !(obj['linkSupport'] is bool)) {
+        final linkSupport = obj['linkSupport'];
+        if (linkSupport != null && !(linkSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -7987,18 +8329,19 @@
       LspJsonHandler(DefinitionOptions.canParse, DefinitionOptions.fromJson);
 
   DefinitionOptions({this.workDoneProgress});
-  static DefinitionOptions fromJson(Map<String, dynamic> json) {
+  static DefinitionOptions fromJson(Map<String, Object?> json) {
     if (DefinitionRegistrationOptions.canParse(json, nullLspJsonReporter)) {
       return DefinitionRegistrationOptions.fromJson(json);
     }
-    final workDoneProgress = json['workDoneProgress'];
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return DefinitionOptions(workDoneProgress: workDoneProgress);
   }
 
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
     }
@@ -8006,11 +8349,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -8057,23 +8400,28 @@
       required this.position,
       this.workDoneToken,
       this.partialResultToken});
-  static DefinitionParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final position = Position.fromJson(json['position']);
-    final workDoneToken = json['workDoneToken'] == null
+  static DefinitionParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final positionJson = json['position'];
+    final position = Position.fromJson(positionJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
-    final partialResultToken = json['partialResultToken'] == null
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
+    final partialResultTokenJson = json['partialResultToken'];
+    final partialResultToken = partialResultTokenJson == null
         ? null
-        : (json['partialResultToken'] is int
-            ? Either2<int, String>.t1(json['partialResultToken'])
-            : (json['partialResultToken'] is String
-                ? Either2<int, String>.t2(json['partialResultToken'])
-                : (throw '''${json['partialResultToken']} was not one of (int, String)''')));
+        : (partialResultTokenJson is int
+            ? Either2<int, String>.t1(partialResultTokenJson)
+            : (partialResultTokenJson is String
+                ? Either2<int, String>.t2(partialResultTokenJson)
+                : (throw '''$partialResultTokenJson was not one of (int, String)''')));
     return DefinitionParams(
         textDocument: textDocument,
         position: position,
@@ -8094,8 +8442,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     __result['position'] = position.toJson();
     if (workDoneToken != null) {
@@ -8108,18 +8456,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -8132,11 +8481,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['position'] == null) {
+        final position = obj['position'];
+        if (position == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Position.canParse(obj['position'], reporter))) {
+        if (!(Position.canParse(position, reporter))) {
           reporter.reportError('must be of type Position');
           return false;
         }
@@ -8145,9 +8495,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -8156,9 +8506,9 @@
       }
       reporter.push('partialResultToken');
       try {
-        if (obj['partialResultToken'] != null &&
-            !((obj['partialResultToken'] is int ||
-                obj['partialResultToken'] is String))) {
+        final partialResultToken = obj['partialResultToken'];
+        if (partialResultToken != null &&
+            !((partialResultToken is int || partialResultToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -8205,12 +8555,13 @@
       DefinitionRegistrationOptions.fromJson);
 
   DefinitionRegistrationOptions({this.documentSelector, this.workDoneProgress});
-  static DefinitionRegistrationOptions fromJson(Map<String, dynamic> json) {
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final workDoneProgress = json['workDoneProgress'];
+  static DefinitionRegistrationOptions fromJson(Map<String, Object?> json) {
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return DefinitionRegistrationOptions(
         documentSelector: documentSelector, workDoneProgress: workDoneProgress);
   }
@@ -8220,8 +8571,8 @@
   final List<DocumentFilter>? documentSelector;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['documentSelector'] = documentSelector;
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
@@ -8230,16 +8581,17 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentSelector');
       try {
         if (!obj.containsKey('documentSelector')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -8249,8 +8601,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -8302,13 +8654,17 @@
       throw 'kind may only be the literal \'delete\'';
     }
   }
-  static DeleteFile fromJson(Map<String, dynamic> json) {
-    final kind = json['kind'];
-    final uri = json['uri'];
-    final options = json['options'] != null
-        ? DeleteFileOptions.fromJson(json['options'])
+  static DeleteFile fromJson(Map<String, Object?> json) {
+    final kindJson = json['kind'];
+    final kind = kindJson as String;
+    final uriJson = json['uri'];
+    final uri = uriJson as String;
+    final optionsJson = json['options'];
+    final options = optionsJson != null
+        ? DeleteFileOptions.fromJson(optionsJson as Map<String, Object?>)
         : null;
-    final annotationId = json['annotationId'];
+    final annotationIdJson = json['annotationId'];
+    final annotationId = annotationIdJson as String?;
     return DeleteFile(
         kind: kind, uri: uri, options: options, annotationId: annotationId);
   }
@@ -8326,8 +8682,8 @@
   /// The file to delete.
   final String uri;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['kind'] = kind;
     __result['uri'] = uri;
     if (options != null) {
@@ -8340,18 +8696,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('kind');
       try {
         if (!obj.containsKey('kind')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['kind'] == null) {
+        final kind = obj['kind'];
+        if (kind == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['kind'] == 'delete')) {
+        if (!(kind == 'delete')) {
           reporter.reportError('must be the literal \'delete\'');
           return false;
         }
@@ -8364,11 +8721,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['uri'] == null) {
+        final uri = obj['uri'];
+        if (uri == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['uri'] is String)) {
+        if (!(uri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -8377,8 +8735,9 @@
       }
       reporter.push('options');
       try {
-        if (obj['options'] != null &&
-            !(DeleteFileOptions.canParse(obj['options'], reporter))) {
+        final options = obj['options'];
+        if (options != null &&
+            !(DeleteFileOptions.canParse(options, reporter))) {
           reporter.reportError('must be of type DeleteFileOptions');
           return false;
         }
@@ -8387,7 +8746,8 @@
       }
       reporter.push('annotationId');
       try {
-        if (obj['annotationId'] != null && !(obj['annotationId'] is String)) {
+        final annotationId = obj['annotationId'];
+        if (annotationId != null && !(annotationId is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -8433,9 +8793,11 @@
       LspJsonHandler(DeleteFileOptions.canParse, DeleteFileOptions.fromJson);
 
   DeleteFileOptions({this.recursive, this.ignoreIfNotExists});
-  static DeleteFileOptions fromJson(Map<String, dynamic> json) {
-    final recursive = json['recursive'];
-    final ignoreIfNotExists = json['ignoreIfNotExists'];
+  static DeleteFileOptions fromJson(Map<String, Object?> json) {
+    final recursiveJson = json['recursive'];
+    final recursive = recursiveJson as bool?;
+    final ignoreIfNotExistsJson = json['ignoreIfNotExists'];
+    final ignoreIfNotExists = ignoreIfNotExistsJson as bool?;
     return DeleteFileOptions(
         recursive: recursive, ignoreIfNotExists: ignoreIfNotExists);
   }
@@ -8446,8 +8808,8 @@
   /// Delete the content recursively if a folder is denoted.
   final bool? recursive;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (recursive != null) {
       __result['recursive'] = recursive;
     }
@@ -8458,10 +8820,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('recursive');
       try {
-        if (obj['recursive'] != null && !(obj['recursive'] is bool)) {
+        final recursive = obj['recursive'];
+        if (recursive != null && !(recursive is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -8470,8 +8833,8 @@
       }
       reporter.push('ignoreIfNotExists');
       try {
-        if (obj['ignoreIfNotExists'] != null &&
-            !(obj['ignoreIfNotExists'] is bool)) {
+        final ignoreIfNotExists = obj['ignoreIfNotExists'];
+        if (ignoreIfNotExists != null && !(ignoreIfNotExists is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -8515,38 +8878,38 @@
       LspJsonHandler(DeleteFilesParams.canParse, DeleteFilesParams.fromJson);
 
   DeleteFilesParams({required this.files});
-  static DeleteFilesParams fromJson(Map<String, dynamic> json) {
-    final files = json['files']
-        ?.map((item) => FileDelete.fromJson(item))
-        ?.cast<FileDelete>()
-        ?.toList();
+  static DeleteFilesParams fromJson(Map<String, Object?> json) {
+    final filesJson = json['files'];
+    final files = (filesJson as List<Object?>)
+        .map((item) => FileDelete.fromJson(item as Map<String, Object?>))
+        .toList();
     return DeleteFilesParams(files: files);
   }
 
   /// An array of all files/folders deleted in this operation.
   final List<FileDelete> files;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['files'] = files.map((item) => item.toJson()).toList();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('files');
       try {
         if (!obj.containsKey('files')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['files'] == null) {
+        final files = obj['files'];
+        if (files == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['files'] is List &&
-            (obj['files']
-                .every((item) => FileDelete.canParse(item, reporter)))))) {
+        if (!((files is List &&
+            (files.every((item) => FileDelete.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<FileDelete>');
           return false;
         }
@@ -8595,27 +8958,34 @@
       this.tags,
       this.relatedInformation,
       this.data});
-  static Diagnostic fromJson(Map<String, dynamic> json) {
-    final range = Range.fromJson(json['range']);
-    final severity = json['severity'] != null
-        ? DiagnosticSeverity.fromJson(json['severity'])
+  static Diagnostic fromJson(Map<String, Object?> json) {
+    final rangeJson = json['range'];
+    final range = Range.fromJson(rangeJson as Map<String, Object?>);
+    final severityJson = json['severity'];
+    final severity = severityJson != null
+        ? DiagnosticSeverity.fromJson(severityJson as num)
         : null;
-    final code = json['code'];
-    final codeDescription = json['codeDescription'] != null
-        ? CodeDescription.fromJson(json['codeDescription'])
+    final codeJson = json['code'];
+    final code = codeJson as String?;
+    final codeDescriptionJson = json['codeDescription'];
+    final codeDescription = codeDescriptionJson != null
+        ? CodeDescription.fromJson(codeDescriptionJson as Map<String, Object?>)
         : null;
-    final source = json['source'];
-    final message = json['message'];
-    final tags = json['tags']
-        ?.map((item) => item != null ? DiagnosticTag.fromJson(item) : null)
-        ?.cast<DiagnosticTag>()
-        ?.toList();
-    final relatedInformation = json['relatedInformation']
+    final sourceJson = json['source'];
+    final source = sourceJson as String?;
+    final messageJson = json['message'];
+    final message = messageJson as String;
+    final tagsJson = json['tags'];
+    final tags = (tagsJson as List<Object?>?)
+        ?.map((item) => DiagnosticTag.fromJson(item as num))
+        .toList();
+    final relatedInformationJson = json['relatedInformation'];
+    final relatedInformation = (relatedInformationJson as List<Object?>?)
         ?.map((item) =>
-            item != null ? DiagnosticRelatedInformation.fromJson(item) : null)
-        ?.cast<DiagnosticRelatedInformation>()
-        ?.toList();
-    final data = json['data'];
+            DiagnosticRelatedInformation.fromJson(item as Map<String, Object?>))
+        .toList();
+    final dataJson = json['data'];
+    final data = dataJson;
     return Diagnostic(
         range: range,
         severity: severity,
@@ -8639,7 +9009,7 @@
   /// `textDocument/publishDiagnostics` notification and
   /// `textDocument/codeAction` request.
   ///  @since 3.16.0
-  final dynamic data;
+  final Object? data;
 
   /// The diagnostic's message.
   final String message;
@@ -8663,8 +9033,8 @@
   ///  @since 3.15.0
   final List<DiagnosticTag>? tags;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['range'] = range.toJson();
     if (severity != null) {
       __result['severity'] = severity?.toJson();
@@ -8693,18 +9063,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('range');
       try {
         if (!obj.containsKey('range')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['range'] == null) {
+        final range = obj['range'];
+        if (range == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['range'], reporter))) {
+        if (!(Range.canParse(range, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -8713,8 +9084,9 @@
       }
       reporter.push('severity');
       try {
-        if (obj['severity'] != null &&
-            !(DiagnosticSeverity.canParse(obj['severity'], reporter))) {
+        final severity = obj['severity'];
+        if (severity != null &&
+            !(DiagnosticSeverity.canParse(severity, reporter))) {
           reporter.reportError('must be of type DiagnosticSeverity');
           return false;
         }
@@ -8723,7 +9095,8 @@
       }
       reporter.push('code');
       try {
-        if (obj['code'] != null && !(obj['code'] is String)) {
+        final code = obj['code'];
+        if (code != null && !(code is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -8732,8 +9105,9 @@
       }
       reporter.push('codeDescription');
       try {
-        if (obj['codeDescription'] != null &&
-            !(CodeDescription.canParse(obj['codeDescription'], reporter))) {
+        final codeDescription = obj['codeDescription'];
+        if (codeDescription != null &&
+            !(CodeDescription.canParse(codeDescription, reporter))) {
           reporter.reportError('must be of type CodeDescription');
           return false;
         }
@@ -8742,7 +9116,8 @@
       }
       reporter.push('source');
       try {
-        if (obj['source'] != null && !(obj['source'] is String)) {
+        final source = obj['source'];
+        if (source != null && !(source is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -8755,11 +9130,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['message'] == null) {
+        final message = obj['message'];
+        if (message == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['message'] is String)) {
+        if (!(message is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -8768,9 +9144,10 @@
       }
       reporter.push('tags');
       try {
-        if (obj['tags'] != null &&
-            !((obj['tags'] is List &&
-                (obj['tags'].every(
+        final tags = obj['tags'];
+        if (tags != null &&
+            !((tags is List &&
+                (tags.every(
                     (item) => DiagnosticTag.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DiagnosticTag>');
           return false;
@@ -8780,9 +9157,10 @@
       }
       reporter.push('relatedInformation');
       try {
-        if (obj['relatedInformation'] != null &&
-            !((obj['relatedInformation'] is List &&
-                (obj['relatedInformation'].every((item) =>
+        final relatedInformation = obj['relatedInformation'];
+        if (relatedInformation != null &&
+            !((relatedInformation is List &&
+                (relatedInformation.every((item) =>
                     DiagnosticRelatedInformation.canParse(item, reporter)))))) {
           reporter.reportError(
               'must be of type List<DiagnosticRelatedInformation>');
@@ -8849,9 +9227,11 @@
       DiagnosticRelatedInformation.fromJson);
 
   DiagnosticRelatedInformation({required this.location, required this.message});
-  static DiagnosticRelatedInformation fromJson(Map<String, dynamic> json) {
-    final location = Location.fromJson(json['location']);
-    final message = json['message'];
+  static DiagnosticRelatedInformation fromJson(Map<String, Object?> json) {
+    final locationJson = json['location'];
+    final location = Location.fromJson(locationJson as Map<String, Object?>);
+    final messageJson = json['message'];
+    final message = messageJson as String;
     return DiagnosticRelatedInformation(location: location, message: message);
   }
 
@@ -8861,26 +9241,27 @@
   /// The message of this related diagnostic information.
   final String message;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['location'] = location.toJson();
     __result['message'] = message;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('location');
       try {
         if (!obj.containsKey('location')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['location'] == null) {
+        final location = obj['location'];
+        if (location == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Location.canParse(obj['location'], reporter))) {
+        if (!(Location.canParse(location, reporter))) {
           reporter.reportError('must be of type Location');
           return false;
         }
@@ -8893,11 +9274,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['message'] == null) {
+        final message = obj['message'];
+        if (message == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['message'] is String)) {
+        if (!(message is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -9006,8 +9388,9 @@
 
   DidChangeConfigurationClientCapabilities({this.dynamicRegistration});
   static DidChangeConfigurationClientCapabilities fromJson(
-      Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
+      Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
     return DidChangeConfigurationClientCapabilities(
         dynamicRegistration: dynamicRegistration);
   }
@@ -9015,8 +9398,8 @@
   /// Did change configuration notification supports dynamic registration.
   final bool? dynamicRegistration;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -9024,11 +9407,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -9069,22 +9452,23 @@
       DidChangeConfigurationParams.fromJson);
 
   DidChangeConfigurationParams({this.settings});
-  static DidChangeConfigurationParams fromJson(Map<String, dynamic> json) {
-    final settings = json['settings'];
+  static DidChangeConfigurationParams fromJson(Map<String, Object?> json) {
+    final settingsJson = json['settings'];
+    final settings = settingsJson;
     return DidChangeConfigurationParams(settings: settings);
   }
 
   /// The actual changed settings
-  final dynamic settings;
+  final Object? settings;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['settings'] = settings;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       return true;
     } else {
       reporter.reportError('must be of type DidChangeConfigurationParams');
@@ -9119,22 +9503,23 @@
 
   DidChangeTextDocumentParams(
       {required this.textDocument, required this.contentChanges});
-  static DidChangeTextDocumentParams fromJson(Map<String, dynamic> json) {
-    final textDocument =
-        VersionedTextDocumentIdentifier.fromJson(json['textDocument']);
-    final contentChanges = json['contentChanges']
-        ?.map((item) => TextDocumentContentChangeEvent1.canParse(
+  static DidChangeTextDocumentParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = VersionedTextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final contentChangesJson = json['contentChanges'];
+    final contentChanges = (contentChangesJson as List<Object?>)
+        .map((item) => TextDocumentContentChangeEvent1.canParse(
                 item, nullLspJsonReporter)
-            ? Either2<TextDocumentContentChangeEvent1,
-                    TextDocumentContentChangeEvent2>.t1(
-                TextDocumentContentChangeEvent1.fromJson(item))
+            ? Either2<TextDocumentContentChangeEvent1, TextDocumentContentChangeEvent2>.t1(
+                TextDocumentContentChangeEvent1.fromJson(
+                    item as Map<String, Object?>))
             : (TextDocumentContentChangeEvent2.canParse(item, nullLspJsonReporter)
                 ? Either2<TextDocumentContentChangeEvent1,
                         TextDocumentContentChangeEvent2>.t2(
-                    TextDocumentContentChangeEvent2.fromJson(item))
+                    TextDocumentContentChangeEvent2.fromJson(item as Map<String, Object?>))
                 : (throw '''$item was not one of (TextDocumentContentChangeEvent1, TextDocumentContentChangeEvent2)''')))
-        ?.cast<Either2<TextDocumentContentChangeEvent1, TextDocumentContentChangeEvent2>>()
-        ?.toList();
+        .toList();
     return DidChangeTextDocumentParams(
         textDocument: textDocument, contentChanges: contentChanges);
   }
@@ -9160,27 +9545,28 @@
   /// after all provided content changes have been applied.
   final VersionedTextDocumentIdentifier textDocument;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     __result['contentChanges'] = contentChanges;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
         if (!(VersionedTextDocumentIdentifier.canParse(
-            obj['textDocument'], reporter))) {
+            textDocument, reporter))) {
           reporter
               .reportError('must be of type VersionedTextDocumentIdentifier');
           return false;
@@ -9194,12 +9580,13 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['contentChanges'] == null) {
+        final contentChanges = obj['contentChanges'];
+        if (contentChanges == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['contentChanges'] is List &&
-            (obj['contentChanges'].every((item) =>
+        if (!((contentChanges is List &&
+            (contentChanges.every((item) =>
                 (TextDocumentContentChangeEvent1.canParse(item, reporter) ||
                     TextDocumentContentChangeEvent2.canParse(
                         item, reporter))))))) {
@@ -9256,8 +9643,9 @@
 
   DidChangeWatchedFilesClientCapabilities({this.dynamicRegistration});
   static DidChangeWatchedFilesClientCapabilities fromJson(
-      Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
+      Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
     return DidChangeWatchedFilesClientCapabilities(
         dynamicRegistration: dynamicRegistration);
   }
@@ -9267,8 +9655,8 @@
   /// for file changes from the server side.
   final bool? dynamicRegistration;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -9276,11 +9664,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -9321,38 +9709,38 @@
       DidChangeWatchedFilesParams.fromJson);
 
   DidChangeWatchedFilesParams({required this.changes});
-  static DidChangeWatchedFilesParams fromJson(Map<String, dynamic> json) {
-    final changes = json['changes']
-        ?.map((item) => FileEvent.fromJson(item))
-        ?.cast<FileEvent>()
-        ?.toList();
+  static DidChangeWatchedFilesParams fromJson(Map<String, Object?> json) {
+    final changesJson = json['changes'];
+    final changes = (changesJson as List<Object?>)
+        .map((item) => FileEvent.fromJson(item as Map<String, Object?>))
+        .toList();
     return DidChangeWatchedFilesParams(changes: changes);
   }
 
   /// The actual file events.
   final List<FileEvent> changes;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['changes'] = changes.map((item) => item.toJson()).toList();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('changes');
       try {
         if (!obj.containsKey('changes')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['changes'] == null) {
+        final changes = obj['changes'];
+        if (changes == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['changes'] is List &&
-            (obj['changes']
-                .every((item) => FileEvent.canParse(item, reporter)))))) {
+        if (!((changes is List &&
+            (changes.every((item) => FileEvent.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<FileEvent>');
           return false;
         }
@@ -9396,37 +9784,38 @@
 
   DidChangeWatchedFilesRegistrationOptions({required this.watchers});
   static DidChangeWatchedFilesRegistrationOptions fromJson(
-      Map<String, dynamic> json) {
-    final watchers = json['watchers']
-        ?.map((item) => FileSystemWatcher.fromJson(item))
-        ?.cast<FileSystemWatcher>()
-        ?.toList();
+      Map<String, Object?> json) {
+    final watchersJson = json['watchers'];
+    final watchers = (watchersJson as List<Object?>)
+        .map((item) => FileSystemWatcher.fromJson(item as Map<String, Object?>))
+        .toList();
     return DidChangeWatchedFilesRegistrationOptions(watchers: watchers);
   }
 
   /// The watchers to register.
   final List<FileSystemWatcher> watchers;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['watchers'] = watchers.map((item) => item.toJson()).toList();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('watchers');
       try {
         if (!obj.containsKey('watchers')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['watchers'] == null) {
+        final watchers = obj['watchers'];
+        if (watchers == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['watchers'] is List &&
-            (obj['watchers'].every(
+        if (!((watchers is List &&
+            (watchers.every(
                 (item) => FileSystemWatcher.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<FileSystemWatcher>');
           return false;
@@ -9470,33 +9859,36 @@
       DidChangeWorkspaceFoldersParams.fromJson);
 
   DidChangeWorkspaceFoldersParams({required this.event});
-  static DidChangeWorkspaceFoldersParams fromJson(Map<String, dynamic> json) {
-    final event = WorkspaceFoldersChangeEvent.fromJson(json['event']);
+  static DidChangeWorkspaceFoldersParams fromJson(Map<String, Object?> json) {
+    final eventJson = json['event'];
+    final event =
+        WorkspaceFoldersChangeEvent.fromJson(eventJson as Map<String, Object?>);
     return DidChangeWorkspaceFoldersParams(event: event);
   }
 
   /// The actual workspace folder change event.
   final WorkspaceFoldersChangeEvent event;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['event'] = event.toJson();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('event');
       try {
         if (!obj.containsKey('event')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['event'] == null) {
+        final event = obj['event'];
+        if (event == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(WorkspaceFoldersChangeEvent.canParse(obj['event'], reporter))) {
+        if (!(WorkspaceFoldersChangeEvent.canParse(event, reporter))) {
           reporter.reportError('must be of type WorkspaceFoldersChangeEvent');
           return false;
         }
@@ -9535,33 +9927,36 @@
       DidCloseTextDocumentParams.canParse, DidCloseTextDocumentParams.fromJson);
 
   DidCloseTextDocumentParams({required this.textDocument});
-  static DidCloseTextDocumentParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
+  static DidCloseTextDocumentParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
     return DidCloseTextDocumentParams(textDocument: textDocument);
   }
 
   /// The document that was closed.
   final TextDocumentIdentifier textDocument;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -9600,33 +9995,36 @@
       DidOpenTextDocumentParams.canParse, DidOpenTextDocumentParams.fromJson);
 
   DidOpenTextDocumentParams({required this.textDocument});
-  static DidOpenTextDocumentParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentItem.fromJson(json['textDocument']);
+  static DidOpenTextDocumentParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument =
+        TextDocumentItem.fromJson(textDocumentJson as Map<String, Object?>);
     return DidOpenTextDocumentParams(textDocument: textDocument);
   }
 
   /// The document that was opened.
   final TextDocumentItem textDocument;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentItem.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentItem.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentItem');
           return false;
         }
@@ -9665,9 +10063,12 @@
       DidSaveTextDocumentParams.canParse, DidSaveTextDocumentParams.fromJson);
 
   DidSaveTextDocumentParams({required this.textDocument, this.text});
-  static DidSaveTextDocumentParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final text = json['text'];
+  static DidSaveTextDocumentParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final textJson = json['text'];
+    final text = textJson as String?;
     return DidSaveTextDocumentParams(textDocument: textDocument, text: text);
   }
 
@@ -9678,8 +10079,8 @@
   /// The document that was saved.
   final TextDocumentIdentifier textDocument;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     if (text != null) {
       __result['text'] = text;
@@ -9688,18 +10089,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -9708,7 +10110,8 @@
       }
       reporter.push('text');
       try {
-        if (obj['text'] != null && !(obj['text'] is String)) {
+        final text = obj['text'];
+        if (text != null && !(text is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -9749,8 +10152,9 @@
       DocumentColorClientCapabilities.fromJson);
 
   DocumentColorClientCapabilities({this.dynamicRegistration});
-  static DocumentColorClientCapabilities fromJson(Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
+  static DocumentColorClientCapabilities fromJson(Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
     return DocumentColorClientCapabilities(
         dynamicRegistration: dynamicRegistration);
   }
@@ -9758,8 +10162,8 @@
   /// Whether document color supports dynamic registration.
   final bool? dynamicRegistration;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -9767,11 +10171,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -9810,18 +10214,19 @@
       DocumentColorOptions.canParse, DocumentColorOptions.fromJson);
 
   DocumentColorOptions({this.workDoneProgress});
-  static DocumentColorOptions fromJson(Map<String, dynamic> json) {
+  static DocumentColorOptions fromJson(Map<String, Object?> json) {
     if (DocumentColorRegistrationOptions.canParse(json, nullLspJsonReporter)) {
       return DocumentColorRegistrationOptions.fromJson(json);
     }
-    final workDoneProgress = json['workDoneProgress'];
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return DocumentColorOptions(workDoneProgress: workDoneProgress);
   }
 
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
     }
@@ -9829,11 +10234,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -9876,22 +10281,26 @@
       {required this.textDocument,
       this.workDoneToken,
       this.partialResultToken});
-  static DocumentColorParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final workDoneToken = json['workDoneToken'] == null
+  static DocumentColorParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
-    final partialResultToken = json['partialResultToken'] == null
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
+    final partialResultTokenJson = json['partialResultToken'];
+    final partialResultToken = partialResultTokenJson == null
         ? null
-        : (json['partialResultToken'] is int
-            ? Either2<int, String>.t1(json['partialResultToken'])
-            : (json['partialResultToken'] is String
-                ? Either2<int, String>.t2(json['partialResultToken'])
-                : (throw '''${json['partialResultToken']} was not one of (int, String)''')));
+        : (partialResultTokenJson is int
+            ? Either2<int, String>.t1(partialResultTokenJson)
+            : (partialResultTokenJson is String
+                ? Either2<int, String>.t2(partialResultTokenJson)
+                : (throw '''$partialResultTokenJson was not one of (int, String)''')));
     return DocumentColorParams(
         textDocument: textDocument,
         workDoneToken: workDoneToken,
@@ -9908,8 +10317,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     if (workDoneToken != null) {
       __result['workDoneToken'] = workDoneToken;
@@ -9921,18 +10330,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -9941,9 +10351,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -9952,9 +10362,9 @@
       }
       reporter.push('partialResultToken');
       try {
-        if (obj['partialResultToken'] != null &&
-            !((obj['partialResultToken'] is int ||
-                obj['partialResultToken'] is String))) {
+        final partialResultToken = obj['partialResultToken'];
+        if (partialResultToken != null &&
+            !((partialResultToken is int || partialResultToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -10005,13 +10415,15 @@
 
   DocumentColorRegistrationOptions(
       {this.documentSelector, this.id, this.workDoneProgress});
-  static DocumentColorRegistrationOptions fromJson(Map<String, dynamic> json) {
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final id = json['id'];
-    final workDoneProgress = json['workDoneProgress'];
+  static DocumentColorRegistrationOptions fromJson(Map<String, Object?> json) {
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final idJson = json['id'];
+    final id = idJson as String?;
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return DocumentColorRegistrationOptions(
         documentSelector: documentSelector,
         id: id,
@@ -10027,8 +10439,8 @@
   final String? id;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['documentSelector'] = documentSelector;
     if (id != null) {
       __result['id'] = id;
@@ -10040,16 +10452,17 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentSelector');
       try {
         if (!obj.containsKey('documentSelector')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -10059,7 +10472,8 @@
       }
       reporter.push('id');
       try {
-        if (obj['id'] != null && !(obj['id'] is String)) {
+        final id = obj['id'];
+        if (id != null && !(id is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -10068,8 +10482,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -10114,10 +10528,13 @@
       LspJsonHandler(DocumentFilter.canParse, DocumentFilter.fromJson);
 
   DocumentFilter({this.language, this.scheme, this.pattern});
-  static DocumentFilter fromJson(Map<String, dynamic> json) {
-    final language = json['language'];
-    final scheme = json['scheme'];
-    final pattern = json['pattern'];
+  static DocumentFilter fromJson(Map<String, Object?> json) {
+    final languageJson = json['language'];
+    final language = languageJson as String?;
+    final schemeJson = json['scheme'];
+    final scheme = schemeJson as String?;
+    final patternJson = json['pattern'];
+    final pattern = patternJson as String?;
     return DocumentFilter(language: language, scheme: scheme, pattern: pattern);
   }
 
@@ -10142,8 +10559,8 @@
   /// A Uri [scheme](#Uri.scheme), like `file` or `untitled`.
   final String? scheme;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (language != null) {
       __result['language'] = language;
     }
@@ -10157,10 +10574,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('language');
       try {
-        if (obj['language'] != null && !(obj['language'] is String)) {
+        final language = obj['language'];
+        if (language != null && !(language is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -10169,7 +10587,8 @@
       }
       reporter.push('scheme');
       try {
-        if (obj['scheme'] != null && !(obj['scheme'] is String)) {
+        final scheme = obj['scheme'];
+        if (scheme != null && !(scheme is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -10178,7 +10597,8 @@
       }
       reporter.push('pattern');
       try {
-        if (obj['pattern'] != null && !(obj['pattern'] is String)) {
+        final pattern = obj['pattern'];
+        if (pattern != null && !(pattern is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -10223,8 +10643,9 @@
 
   DocumentFormattingClientCapabilities({this.dynamicRegistration});
   static DocumentFormattingClientCapabilities fromJson(
-      Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
+      Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
     return DocumentFormattingClientCapabilities(
         dynamicRegistration: dynamicRegistration);
   }
@@ -10232,8 +10653,8 @@
   /// Whether formatting supports dynamic registration.
   final bool? dynamicRegistration;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -10241,11 +10662,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -10285,19 +10706,20 @@
       DocumentFormattingOptions.canParse, DocumentFormattingOptions.fromJson);
 
   DocumentFormattingOptions({this.workDoneProgress});
-  static DocumentFormattingOptions fromJson(Map<String, dynamic> json) {
+  static DocumentFormattingOptions fromJson(Map<String, Object?> json) {
     if (DocumentFormattingRegistrationOptions.canParse(
         json, nullLspJsonReporter)) {
       return DocumentFormattingRegistrationOptions.fromJson(json);
     }
-    final workDoneProgress = json['workDoneProgress'];
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return DocumentFormattingOptions(workDoneProgress: workDoneProgress);
   }
 
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
     }
@@ -10305,11 +10727,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -10349,16 +10771,21 @@
 
   DocumentFormattingParams(
       {required this.textDocument, required this.options, this.workDoneToken});
-  static DocumentFormattingParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final options = FormattingOptions.fromJson(json['options']);
-    final workDoneToken = json['workDoneToken'] == null
+  static DocumentFormattingParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final optionsJson = json['options'];
+    final options =
+        FormattingOptions.fromJson(optionsJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
     return DocumentFormattingParams(
         textDocument: textDocument,
         options: options,
@@ -10374,8 +10801,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     __result['options'] = options.toJson();
     if (workDoneToken != null) {
@@ -10385,18 +10812,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -10409,11 +10837,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['options'] == null) {
+        final options = obj['options'];
+        if (options == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(FormattingOptions.canParse(obj['options'], reporter))) {
+        if (!(FormattingOptions.canParse(options, reporter))) {
           reporter.reportError('must be of type FormattingOptions');
           return false;
         }
@@ -10422,9 +10851,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -10475,12 +10904,13 @@
   DocumentFormattingRegistrationOptions(
       {this.documentSelector, this.workDoneProgress});
   static DocumentFormattingRegistrationOptions fromJson(
-      Map<String, dynamic> json) {
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final workDoneProgress = json['workDoneProgress'];
+      Map<String, Object?> json) {
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return DocumentFormattingRegistrationOptions(
         documentSelector: documentSelector, workDoneProgress: workDoneProgress);
   }
@@ -10490,8 +10920,8 @@
   final List<DocumentFilter>? documentSelector;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['documentSelector'] = documentSelector;
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
@@ -10500,16 +10930,17 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentSelector');
       try {
         if (!obj.containsKey('documentSelector')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -10519,8 +10950,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -10567,10 +10998,12 @@
       LspJsonHandler(DocumentHighlight.canParse, DocumentHighlight.fromJson);
 
   DocumentHighlight({required this.range, this.kind});
-  static DocumentHighlight fromJson(Map<String, dynamic> json) {
-    final range = Range.fromJson(json['range']);
-    final kind = json['kind'] != null
-        ? DocumentHighlightKind.fromJson(json['kind'])
+  static DocumentHighlight fromJson(Map<String, Object?> json) {
+    final rangeJson = json['range'];
+    final range = Range.fromJson(rangeJson as Map<String, Object?>);
+    final kindJson = json['kind'];
+    final kind = kindJson != null
+        ? DocumentHighlightKind.fromJson(kindJson as int)
         : null;
     return DocumentHighlight(range: range, kind: kind);
   }
@@ -10581,8 +11014,8 @@
   /// The range this highlight applies to.
   final Range range;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['range'] = range.toJson();
     if (kind != null) {
       __result['kind'] = kind?.toJson();
@@ -10591,18 +11024,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('range');
       try {
         if (!obj.containsKey('range')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['range'] == null) {
+        final range = obj['range'];
+        if (range == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['range'], reporter))) {
+        if (!(Range.canParse(range, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -10611,8 +11045,8 @@
       }
       reporter.push('kind');
       try {
-        if (obj['kind'] != null &&
-            !(DocumentHighlightKind.canParse(obj['kind'], reporter))) {
+        final kind = obj['kind'];
+        if (kind != null && !(DocumentHighlightKind.canParse(kind, reporter))) {
           reporter.reportError('must be of type DocumentHighlightKind');
           return false;
         }
@@ -10653,8 +11087,9 @@
 
   DocumentHighlightClientCapabilities({this.dynamicRegistration});
   static DocumentHighlightClientCapabilities fromJson(
-      Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
+      Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
     return DocumentHighlightClientCapabilities(
         dynamicRegistration: dynamicRegistration);
   }
@@ -10662,8 +11097,8 @@
   /// Whether document highlight supports dynamic registration.
   final bool? dynamicRegistration;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -10671,11 +11106,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -10747,19 +11182,20 @@
       DocumentHighlightOptions.canParse, DocumentHighlightOptions.fromJson);
 
   DocumentHighlightOptions({this.workDoneProgress});
-  static DocumentHighlightOptions fromJson(Map<String, dynamic> json) {
+  static DocumentHighlightOptions fromJson(Map<String, Object?> json) {
     if (DocumentHighlightRegistrationOptions.canParse(
         json, nullLspJsonReporter)) {
       return DocumentHighlightRegistrationOptions.fromJson(json);
     }
-    final workDoneProgress = json['workDoneProgress'];
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return DocumentHighlightOptions(workDoneProgress: workDoneProgress);
   }
 
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
     }
@@ -10767,11 +11203,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -10819,23 +11255,28 @@
       required this.position,
       this.workDoneToken,
       this.partialResultToken});
-  static DocumentHighlightParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final position = Position.fromJson(json['position']);
-    final workDoneToken = json['workDoneToken'] == null
+  static DocumentHighlightParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final positionJson = json['position'];
+    final position = Position.fromJson(positionJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
-    final partialResultToken = json['partialResultToken'] == null
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
+    final partialResultTokenJson = json['partialResultToken'];
+    final partialResultToken = partialResultTokenJson == null
         ? null
-        : (json['partialResultToken'] is int
-            ? Either2<int, String>.t1(json['partialResultToken'])
-            : (json['partialResultToken'] is String
-                ? Either2<int, String>.t2(json['partialResultToken'])
-                : (throw '''${json['partialResultToken']} was not one of (int, String)''')));
+        : (partialResultTokenJson is int
+            ? Either2<int, String>.t1(partialResultTokenJson)
+            : (partialResultTokenJson is String
+                ? Either2<int, String>.t2(partialResultTokenJson)
+                : (throw '''$partialResultTokenJson was not one of (int, String)''')));
     return DocumentHighlightParams(
         textDocument: textDocument,
         position: position,
@@ -10856,8 +11297,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     __result['position'] = position.toJson();
     if (workDoneToken != null) {
@@ -10870,18 +11311,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -10894,11 +11336,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['position'] == null) {
+        final position = obj['position'];
+        if (position == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Position.canParse(obj['position'], reporter))) {
+        if (!(Position.canParse(position, reporter))) {
           reporter.reportError('must be of type Position');
           return false;
         }
@@ -10907,9 +11350,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -10918,9 +11361,9 @@
       }
       reporter.push('partialResultToken');
       try {
-        if (obj['partialResultToken'] != null &&
-            !((obj['partialResultToken'] is int ||
-                obj['partialResultToken'] is String))) {
+        final partialResultToken = obj['partialResultToken'];
+        if (partialResultToken != null &&
+            !((partialResultToken is int || partialResultToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -10973,12 +11416,13 @@
   DocumentHighlightRegistrationOptions(
       {this.documentSelector, this.workDoneProgress});
   static DocumentHighlightRegistrationOptions fromJson(
-      Map<String, dynamic> json) {
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final workDoneProgress = json['workDoneProgress'];
+      Map<String, Object?> json) {
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return DocumentHighlightRegistrationOptions(
         documentSelector: documentSelector, workDoneProgress: workDoneProgress);
   }
@@ -10988,8 +11432,8 @@
   final List<DocumentFilter>? documentSelector;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['documentSelector'] = documentSelector;
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
@@ -10998,16 +11442,17 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentSelector');
       try {
         if (!obj.containsKey('documentSelector')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -11017,8 +11462,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -11064,18 +11509,22 @@
       LspJsonHandler(DocumentLink.canParse, DocumentLink.fromJson);
 
   DocumentLink({required this.range, this.target, this.tooltip, this.data});
-  static DocumentLink fromJson(Map<String, dynamic> json) {
-    final range = Range.fromJson(json['range']);
-    final target = json['target'];
-    final tooltip = json['tooltip'];
-    final data = json['data'];
+  static DocumentLink fromJson(Map<String, Object?> json) {
+    final rangeJson = json['range'];
+    final range = Range.fromJson(rangeJson as Map<String, Object?>);
+    final targetJson = json['target'];
+    final target = targetJson as String?;
+    final tooltipJson = json['tooltip'];
+    final tooltip = tooltipJson as String?;
+    final dataJson = json['data'];
+    final data = dataJson;
     return DocumentLink(
         range: range, target: target, tooltip: tooltip, data: data);
   }
 
   /// A data entry field that is preserved on a document link between a
   /// DocumentLinkRequest and a DocumentLinkResolveRequest.
-  final dynamic data;
+  final Object? data;
 
   /// The range this link applies to.
   final Range range;
@@ -11092,8 +11541,8 @@
   ///  @since 3.15.0
   final String? tooltip;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['range'] = range.toJson();
     if (target != null) {
       __result['target'] = target;
@@ -11108,18 +11557,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('range');
       try {
         if (!obj.containsKey('range')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['range'] == null) {
+        final range = obj['range'];
+        if (range == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['range'], reporter))) {
+        if (!(Range.canParse(range, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -11128,7 +11578,8 @@
       }
       reporter.push('target');
       try {
-        if (obj['target'] != null && !(obj['target'] is String)) {
+        final target = obj['target'];
+        if (target != null && !(target is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -11137,7 +11588,8 @@
       }
       reporter.push('tooltip');
       try {
-        if (obj['tooltip'] != null && !(obj['tooltip'] is String)) {
+        final tooltip = obj['tooltip'];
+        if (tooltip != null && !(tooltip is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -11184,9 +11636,11 @@
 
   DocumentLinkClientCapabilities(
       {this.dynamicRegistration, this.tooltipSupport});
-  static DocumentLinkClientCapabilities fromJson(Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
-    final tooltipSupport = json['tooltipSupport'];
+  static DocumentLinkClientCapabilities fromJson(Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
+    final tooltipSupportJson = json['tooltipSupport'];
+    final tooltipSupport = tooltipSupportJson as bool?;
     return DocumentLinkClientCapabilities(
         dynamicRegistration: dynamicRegistration,
         tooltipSupport: tooltipSupport);
@@ -11199,8 +11653,8 @@
   ///  @since 3.15.0
   final bool? tooltipSupport;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -11211,11 +11665,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -11224,7 +11678,8 @@
       }
       reporter.push('tooltipSupport');
       try {
-        if (obj['tooltipSupport'] != null && !(obj['tooltipSupport'] is bool)) {
+        final tooltipSupport = obj['tooltipSupport'];
+        if (tooltipSupport != null && !(tooltipSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -11266,12 +11721,14 @@
       DocumentLinkOptions.canParse, DocumentLinkOptions.fromJson);
 
   DocumentLinkOptions({this.resolveProvider, this.workDoneProgress});
-  static DocumentLinkOptions fromJson(Map<String, dynamic> json) {
+  static DocumentLinkOptions fromJson(Map<String, Object?> json) {
     if (DocumentLinkRegistrationOptions.canParse(json, nullLspJsonReporter)) {
       return DocumentLinkRegistrationOptions.fromJson(json);
     }
-    final resolveProvider = json['resolveProvider'];
-    final workDoneProgress = json['workDoneProgress'];
+    final resolveProviderJson = json['resolveProvider'];
+    final resolveProvider = resolveProviderJson as bool?;
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return DocumentLinkOptions(
         resolveProvider: resolveProvider, workDoneProgress: workDoneProgress);
   }
@@ -11280,8 +11737,8 @@
   final bool? resolveProvider;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (resolveProvider != null) {
       __result['resolveProvider'] = resolveProvider;
     }
@@ -11292,11 +11749,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('resolveProvider');
       try {
-        if (obj['resolveProvider'] != null &&
-            !(obj['resolveProvider'] is bool)) {
+        final resolveProvider = obj['resolveProvider'];
+        if (resolveProvider != null && !(resolveProvider is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -11305,8 +11762,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -11352,22 +11809,26 @@
       {required this.textDocument,
       this.workDoneToken,
       this.partialResultToken});
-  static DocumentLinkParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final workDoneToken = json['workDoneToken'] == null
+  static DocumentLinkParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
-    final partialResultToken = json['partialResultToken'] == null
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
+    final partialResultTokenJson = json['partialResultToken'];
+    final partialResultToken = partialResultTokenJson == null
         ? null
-        : (json['partialResultToken'] is int
-            ? Either2<int, String>.t1(json['partialResultToken'])
-            : (json['partialResultToken'] is String
-                ? Either2<int, String>.t2(json['partialResultToken'])
-                : (throw '''${json['partialResultToken']} was not one of (int, String)''')));
+        : (partialResultTokenJson is int
+            ? Either2<int, String>.t1(partialResultTokenJson)
+            : (partialResultTokenJson is String
+                ? Either2<int, String>.t2(partialResultTokenJson)
+                : (throw '''$partialResultTokenJson was not one of (int, String)''')));
     return DocumentLinkParams(
         textDocument: textDocument,
         workDoneToken: workDoneToken,
@@ -11384,8 +11845,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     if (workDoneToken != null) {
       __result['workDoneToken'] = workDoneToken;
@@ -11397,18 +11858,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -11417,9 +11879,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -11428,9 +11890,9 @@
       }
       reporter.push('partialResultToken');
       try {
-        if (obj['partialResultToken'] != null &&
-            !((obj['partialResultToken'] is int ||
-                obj['partialResultToken'] is String))) {
+        final partialResultToken = obj['partialResultToken'];
+        if (partialResultToken != null &&
+            !((partialResultToken is int || partialResultToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -11480,13 +11942,15 @@
 
   DocumentLinkRegistrationOptions(
       {this.documentSelector, this.resolveProvider, this.workDoneProgress});
-  static DocumentLinkRegistrationOptions fromJson(Map<String, dynamic> json) {
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final resolveProvider = json['resolveProvider'];
-    final workDoneProgress = json['workDoneProgress'];
+  static DocumentLinkRegistrationOptions fromJson(Map<String, Object?> json) {
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final resolveProviderJson = json['resolveProvider'];
+    final resolveProvider = resolveProviderJson as bool?;
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return DocumentLinkRegistrationOptions(
         documentSelector: documentSelector,
         resolveProvider: resolveProvider,
@@ -11501,8 +11965,8 @@
   final bool? resolveProvider;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['documentSelector'] = documentSelector;
     if (resolveProvider != null) {
       __result['resolveProvider'] = resolveProvider;
@@ -11514,16 +11978,17 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentSelector');
       try {
         if (!obj.containsKey('documentSelector')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -11533,8 +11998,8 @@
       }
       reporter.push('resolveProvider');
       try {
-        if (obj['resolveProvider'] != null &&
-            !(obj['resolveProvider'] is bool)) {
+        final resolveProvider = obj['resolveProvider'];
+        if (resolveProvider != null && !(resolveProvider is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -11543,8 +12008,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -11591,8 +12056,9 @@
 
   DocumentOnTypeFormattingClientCapabilities({this.dynamicRegistration});
   static DocumentOnTypeFormattingClientCapabilities fromJson(
-      Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
+      Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
     return DocumentOnTypeFormattingClientCapabilities(
         dynamicRegistration: dynamicRegistration);
   }
@@ -11600,8 +12066,8 @@
   /// Whether on type formatting supports dynamic registration.
   final bool? dynamicRegistration;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -11609,11 +12075,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -11655,16 +12121,17 @@
 
   DocumentOnTypeFormattingOptions(
       {required this.firstTriggerCharacter, this.moreTriggerCharacter});
-  static DocumentOnTypeFormattingOptions fromJson(Map<String, dynamic> json) {
+  static DocumentOnTypeFormattingOptions fromJson(Map<String, Object?> json) {
     if (DocumentOnTypeFormattingRegistrationOptions.canParse(
         json, nullLspJsonReporter)) {
       return DocumentOnTypeFormattingRegistrationOptions.fromJson(json);
     }
-    final firstTriggerCharacter = json['firstTriggerCharacter'];
-    final moreTriggerCharacter = json['moreTriggerCharacter']
-        ?.map((item) => item)
-        ?.cast<String>()
-        ?.toList();
+    final firstTriggerCharacterJson = json['firstTriggerCharacter'];
+    final firstTriggerCharacter = firstTriggerCharacterJson as String;
+    final moreTriggerCharacterJson = json['moreTriggerCharacter'];
+    final moreTriggerCharacter = (moreTriggerCharacterJson as List<Object?>?)
+        ?.map((item) => item as String)
+        .toList();
     return DocumentOnTypeFormattingOptions(
         firstTriggerCharacter: firstTriggerCharacter,
         moreTriggerCharacter: moreTriggerCharacter);
@@ -11676,8 +12143,8 @@
   /// More trigger characters.
   final List<String>? moreTriggerCharacter;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['firstTriggerCharacter'] = firstTriggerCharacter;
     if (moreTriggerCharacter != null) {
       __result['moreTriggerCharacter'] = moreTriggerCharacter;
@@ -11686,18 +12153,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('firstTriggerCharacter');
       try {
         if (!obj.containsKey('firstTriggerCharacter')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['firstTriggerCharacter'] == null) {
+        final firstTriggerCharacter = obj['firstTriggerCharacter'];
+        if (firstTriggerCharacter == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['firstTriggerCharacter'] is String)) {
+        if (!(firstTriggerCharacter is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -11706,10 +12174,10 @@
       }
       reporter.push('moreTriggerCharacter');
       try {
-        if (obj['moreTriggerCharacter'] != null &&
-            !((obj['moreTriggerCharacter'] is List &&
-                (obj['moreTriggerCharacter']
-                    .every((item) => item is String))))) {
+        final moreTriggerCharacter = obj['moreTriggerCharacter'];
+        if (moreTriggerCharacter != null &&
+            !((moreTriggerCharacter is List &&
+                (moreTriggerCharacter.every((item) => item is String))))) {
           reporter.reportError('must be of type List<String>');
           return false;
         }
@@ -11758,11 +12226,17 @@
       required this.options,
       required this.textDocument,
       required this.position});
-  static DocumentOnTypeFormattingParams fromJson(Map<String, dynamic> json) {
-    final ch = json['ch'];
-    final options = FormattingOptions.fromJson(json['options']);
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final position = Position.fromJson(json['position']);
+  static DocumentOnTypeFormattingParams fromJson(Map<String, Object?> json) {
+    final chJson = json['ch'];
+    final ch = chJson as String;
+    final optionsJson = json['options'];
+    final options =
+        FormattingOptions.fromJson(optionsJson as Map<String, Object?>);
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final positionJson = json['position'];
+    final position = Position.fromJson(positionJson as Map<String, Object?>);
     return DocumentOnTypeFormattingParams(
         ch: ch,
         options: options,
@@ -11782,8 +12256,8 @@
   /// The text document.
   final TextDocumentIdentifier textDocument;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['ch'] = ch;
     __result['options'] = options.toJson();
     __result['textDocument'] = textDocument.toJson();
@@ -11792,18 +12266,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('ch');
       try {
         if (!obj.containsKey('ch')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['ch'] == null) {
+        final ch = obj['ch'];
+        if (ch == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['ch'] is String)) {
+        if (!(ch is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -11816,11 +12291,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['options'] == null) {
+        final options = obj['options'];
+        if (options == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(FormattingOptions.canParse(obj['options'], reporter))) {
+        if (!(FormattingOptions.canParse(options, reporter))) {
           reporter.reportError('must be of type FormattingOptions');
           return false;
         }
@@ -11833,11 +12309,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -11850,11 +12327,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['position'] == null) {
+        final position = obj['position'];
+        if (position == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Position.canParse(obj['position'], reporter))) {
+        if (!(Position.canParse(position, reporter))) {
           reporter.reportError('must be of type Position');
           return false;
         }
@@ -11909,16 +12387,17 @@
       required this.firstTriggerCharacter,
       this.moreTriggerCharacter});
   static DocumentOnTypeFormattingRegistrationOptions fromJson(
-      Map<String, dynamic> json) {
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final firstTriggerCharacter = json['firstTriggerCharacter'];
-    final moreTriggerCharacter = json['moreTriggerCharacter']
-        ?.map((item) => item)
-        ?.cast<String>()
-        ?.toList();
+      Map<String, Object?> json) {
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final firstTriggerCharacterJson = json['firstTriggerCharacter'];
+    final firstTriggerCharacter = firstTriggerCharacterJson as String;
+    final moreTriggerCharacterJson = json['moreTriggerCharacter'];
+    final moreTriggerCharacter = (moreTriggerCharacterJson as List<Object?>?)
+        ?.map((item) => item as String)
+        .toList();
     return DocumentOnTypeFormattingRegistrationOptions(
         documentSelector: documentSelector,
         firstTriggerCharacter: firstTriggerCharacter,
@@ -11935,8 +12414,8 @@
   /// More trigger characters.
   final List<String>? moreTriggerCharacter;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['documentSelector'] = documentSelector;
     __result['firstTriggerCharacter'] = firstTriggerCharacter;
     if (moreTriggerCharacter != null) {
@@ -11946,16 +12425,17 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentSelector');
       try {
         if (!obj.containsKey('documentSelector')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -11969,11 +12449,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['firstTriggerCharacter'] == null) {
+        final firstTriggerCharacter = obj['firstTriggerCharacter'];
+        if (firstTriggerCharacter == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['firstTriggerCharacter'] is String)) {
+        if (!(firstTriggerCharacter is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -11982,10 +12463,10 @@
       }
       reporter.push('moreTriggerCharacter');
       try {
-        if (obj['moreTriggerCharacter'] != null &&
-            !((obj['moreTriggerCharacter'] is List &&
-                (obj['moreTriggerCharacter']
-                    .every((item) => item is String))))) {
+        final moreTriggerCharacter = obj['moreTriggerCharacter'];
+        if (moreTriggerCharacter != null &&
+            !((moreTriggerCharacter is List &&
+                (moreTriggerCharacter.every((item) => item is String))))) {
           reporter.reportError('must be of type List<String>');
           return false;
         }
@@ -12034,8 +12515,9 @@
 
   DocumentRangeFormattingClientCapabilities({this.dynamicRegistration});
   static DocumentRangeFormattingClientCapabilities fromJson(
-      Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
+      Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
     return DocumentRangeFormattingClientCapabilities(
         dynamicRegistration: dynamicRegistration);
   }
@@ -12043,8 +12525,8 @@
   /// Whether formatting supports dynamic registration.
   final bool? dynamicRegistration;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -12052,11 +12534,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -12098,19 +12580,20 @@
       DocumentRangeFormattingOptions.fromJson);
 
   DocumentRangeFormattingOptions({this.workDoneProgress});
-  static DocumentRangeFormattingOptions fromJson(Map<String, dynamic> json) {
+  static DocumentRangeFormattingOptions fromJson(Map<String, Object?> json) {
     if (DocumentRangeFormattingRegistrationOptions.canParse(
         json, nullLspJsonReporter)) {
       return DocumentRangeFormattingRegistrationOptions.fromJson(json);
     }
-    final workDoneProgress = json['workDoneProgress'];
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return DocumentRangeFormattingOptions(workDoneProgress: workDoneProgress);
   }
 
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
     }
@@ -12118,11 +12601,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -12167,17 +12650,23 @@
       required this.range,
       required this.options,
       this.workDoneToken});
-  static DocumentRangeFormattingParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final range = Range.fromJson(json['range']);
-    final options = FormattingOptions.fromJson(json['options']);
-    final workDoneToken = json['workDoneToken'] == null
+  static DocumentRangeFormattingParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final rangeJson = json['range'];
+    final range = Range.fromJson(rangeJson as Map<String, Object?>);
+    final optionsJson = json['options'];
+    final options =
+        FormattingOptions.fromJson(optionsJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
     return DocumentRangeFormattingParams(
         textDocument: textDocument,
         range: range,
@@ -12197,8 +12686,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     __result['range'] = range.toJson();
     __result['options'] = options.toJson();
@@ -12209,18 +12698,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -12233,11 +12723,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['range'] == null) {
+        final range = obj['range'];
+        if (range == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['range'], reporter))) {
+        if (!(Range.canParse(range, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -12250,11 +12741,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['options'] == null) {
+        final options = obj['options'];
+        if (options == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(FormattingOptions.canParse(obj['options'], reporter))) {
+        if (!(FormattingOptions.canParse(options, reporter))) {
           reporter.reportError('must be of type FormattingOptions');
           return false;
         }
@@ -12263,9 +12755,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -12318,12 +12810,13 @@
   DocumentRangeFormattingRegistrationOptions(
       {this.documentSelector, this.workDoneProgress});
   static DocumentRangeFormattingRegistrationOptions fromJson(
-      Map<String, dynamic> json) {
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final workDoneProgress = json['workDoneProgress'];
+      Map<String, Object?> json) {
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return DocumentRangeFormattingRegistrationOptions(
         documentSelector: documentSelector, workDoneProgress: workDoneProgress);
   }
@@ -12333,8 +12826,8 @@
   final List<DocumentFilter>? documentSelector;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['documentSelector'] = documentSelector;
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
@@ -12343,16 +12836,17 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentSelector');
       try {
         if (!obj.containsKey('documentSelector')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -12362,8 +12856,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -12419,21 +12913,28 @@
       required this.range,
       required this.selectionRange,
       this.children});
-  static DocumentSymbol fromJson(Map<String, dynamic> json) {
-    final name = json['name'];
-    final detail = json['detail'];
-    final kind = SymbolKind.fromJson(json['kind']);
-    final tags = json['tags']
-        ?.map((item) => item != null ? SymbolTag.fromJson(item) : null)
-        ?.cast<SymbolTag>()
-        ?.toList();
-    final deprecated = json['deprecated'];
-    final range = Range.fromJson(json['range']);
-    final selectionRange = Range.fromJson(json['selectionRange']);
-    final children = json['children']
-        ?.map((item) => item != null ? DocumentSymbol.fromJson(item) : null)
-        ?.cast<DocumentSymbol>()
-        ?.toList();
+  static DocumentSymbol fromJson(Map<String, Object?> json) {
+    final nameJson = json['name'];
+    final name = nameJson as String;
+    final detailJson = json['detail'];
+    final detail = detailJson as String?;
+    final kindJson = json['kind'];
+    final kind = SymbolKind.fromJson(kindJson as int);
+    final tagsJson = json['tags'];
+    final tags = (tagsJson as List<Object?>?)
+        ?.map((item) => SymbolTag.fromJson(item as num))
+        .toList();
+    final deprecatedJson = json['deprecated'];
+    final deprecated = deprecatedJson as bool?;
+    final rangeJson = json['range'];
+    final range = Range.fromJson(rangeJson as Map<String, Object?>);
+    final selectionRangeJson = json['selectionRange'];
+    final selectionRange =
+        Range.fromJson(selectionRangeJson as Map<String, Object?>);
+    final childrenJson = json['children'];
+    final children = (childrenJson as List<Object?>?)
+        ?.map((item) => DocumentSymbol.fromJson(item as Map<String, Object?>))
+        .toList();
     return DocumentSymbol(
         name: name,
         detail: detail,
@@ -12477,8 +12978,8 @@
   ///  @since 3.16.0
   final List<SymbolTag>? tags;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['name'] = name;
     if (detail != null) {
       __result['detail'] = detail;
@@ -12499,18 +13000,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('name');
       try {
         if (!obj.containsKey('name')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['name'] == null) {
+        final name = obj['name'];
+        if (name == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['name'] is String)) {
+        if (!(name is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -12519,7 +13021,8 @@
       }
       reporter.push('detail');
       try {
-        if (obj['detail'] != null && !(obj['detail'] is String)) {
+        final detail = obj['detail'];
+        if (detail != null && !(detail is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -12532,11 +13035,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['kind'] == null) {
+        final kind = obj['kind'];
+        if (kind == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(SymbolKind.canParse(obj['kind'], reporter))) {
+        if (!(SymbolKind.canParse(kind, reporter))) {
           reporter.reportError('must be of type SymbolKind');
           return false;
         }
@@ -12545,10 +13049,10 @@
       }
       reporter.push('tags');
       try {
-        if (obj['tags'] != null &&
-            !((obj['tags'] is List &&
-                (obj['tags']
-                    .every((item) => SymbolTag.canParse(item, reporter)))))) {
+        final tags = obj['tags'];
+        if (tags != null &&
+            !((tags is List &&
+                (tags.every((item) => SymbolTag.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<SymbolTag>');
           return false;
         }
@@ -12557,7 +13061,8 @@
       }
       reporter.push('deprecated');
       try {
-        if (obj['deprecated'] != null && !(obj['deprecated'] is bool)) {
+        final deprecated = obj['deprecated'];
+        if (deprecated != null && !(deprecated is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -12570,11 +13075,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['range'] == null) {
+        final range = obj['range'];
+        if (range == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['range'], reporter))) {
+        if (!(Range.canParse(range, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -12587,11 +13093,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['selectionRange'] == null) {
+        final selectionRange = obj['selectionRange'];
+        if (selectionRange == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['selectionRange'], reporter))) {
+        if (!(Range.canParse(selectionRange, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -12600,9 +13107,10 @@
       }
       reporter.push('children');
       try {
-        if (obj['children'] != null &&
-            !((obj['children'] is List &&
-                (obj['children'].every(
+        final children = obj['children'];
+        if (children != null &&
+            !((children is List &&
+                (children.every(
                     (item) => DocumentSymbol.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentSymbol>');
           return false;
@@ -12663,19 +13171,25 @@
       this.hierarchicalDocumentSymbolSupport,
       this.tagSupport,
       this.labelSupport});
-  static DocumentSymbolClientCapabilities fromJson(Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
-    final symbolKind = json['symbolKind'] != null
+  static DocumentSymbolClientCapabilities fromJson(Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
+    final symbolKindJson = json['symbolKind'];
+    final symbolKind = symbolKindJson != null
         ? DocumentSymbolClientCapabilitiesSymbolKind.fromJson(
-            json['symbolKind'])
+            symbolKindJson as Map<String, Object?>)
         : null;
-    final hierarchicalDocumentSymbolSupport =
+    final hierarchicalDocumentSymbolSupportJson =
         json['hierarchicalDocumentSymbolSupport'];
-    final tagSupport = json['tagSupport'] != null
+    final hierarchicalDocumentSymbolSupport =
+        hierarchicalDocumentSymbolSupportJson as bool?;
+    final tagSupportJson = json['tagSupport'];
+    final tagSupport = tagSupportJson != null
         ? DocumentSymbolClientCapabilitiesTagSupport.fromJson(
-            json['tagSupport'])
+            tagSupportJson as Map<String, Object?>)
         : null;
-    final labelSupport = json['labelSupport'];
+    final labelSupportJson = json['labelSupport'];
+    final labelSupport = labelSupportJson as bool?;
     return DocumentSymbolClientCapabilities(
         dynamicRegistration: dynamicRegistration,
         symbolKind: symbolKind,
@@ -12705,8 +13219,8 @@
   ///  @since 3.16.0
   final DocumentSymbolClientCapabilitiesTagSupport? tagSupport;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -12727,11 +13241,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -12740,9 +13254,10 @@
       }
       reporter.push('symbolKind');
       try {
-        if (obj['symbolKind'] != null &&
+        final symbolKind = obj['symbolKind'];
+        if (symbolKind != null &&
             !(DocumentSymbolClientCapabilitiesSymbolKind.canParse(
-                obj['symbolKind'], reporter))) {
+                symbolKind, reporter))) {
           reporter.reportError(
               'must be of type DocumentSymbolClientCapabilitiesSymbolKind');
           return false;
@@ -12752,8 +13267,10 @@
       }
       reporter.push('hierarchicalDocumentSymbolSupport');
       try {
-        if (obj['hierarchicalDocumentSymbolSupport'] != null &&
-            !(obj['hierarchicalDocumentSymbolSupport'] is bool)) {
+        final hierarchicalDocumentSymbolSupport =
+            obj['hierarchicalDocumentSymbolSupport'];
+        if (hierarchicalDocumentSymbolSupport != null &&
+            !(hierarchicalDocumentSymbolSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -12762,9 +13279,10 @@
       }
       reporter.push('tagSupport');
       try {
-        if (obj['tagSupport'] != null &&
+        final tagSupport = obj['tagSupport'];
+        if (tagSupport != null &&
             !(DocumentSymbolClientCapabilitiesTagSupport.canParse(
-                obj['tagSupport'], reporter))) {
+                tagSupport, reporter))) {
           reporter.reportError(
               'must be of type DocumentSymbolClientCapabilitiesTagSupport');
           return false;
@@ -12774,7 +13292,8 @@
       }
       reporter.push('labelSupport');
       try {
-        if (obj['labelSupport'] != null && !(obj['labelSupport'] is bool)) {
+        final labelSupport = obj['labelSupport'];
+        if (labelSupport != null && !(labelSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -12826,11 +13345,11 @@
 
   DocumentSymbolClientCapabilitiesSymbolKind({this.valueSet});
   static DocumentSymbolClientCapabilitiesSymbolKind fromJson(
-      Map<String, dynamic> json) {
-    final valueSet = json['valueSet']
-        ?.map((item) => item != null ? SymbolKind.fromJson(item) : null)
-        ?.cast<SymbolKind>()
-        ?.toList();
+      Map<String, Object?> json) {
+    final valueSetJson = json['valueSet'];
+    final valueSet = (valueSetJson as List<Object?>?)
+        ?.map((item) => SymbolKind.fromJson(item as int))
+        .toList();
     return DocumentSymbolClientCapabilitiesSymbolKind(valueSet: valueSet);
   }
 
@@ -12842,8 +13361,8 @@
   /// from `File` to `Array` as defined in the initial version of the protocol.
   final List<SymbolKind>? valueSet;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (valueSet != null) {
       __result['valueSet'] = valueSet?.map((item) => item.toJson()).toList();
     }
@@ -12851,12 +13370,13 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('valueSet');
       try {
-        if (obj['valueSet'] != null &&
-            !((obj['valueSet'] is List &&
-                (obj['valueSet']
+        final valueSet = obj['valueSet'];
+        if (valueSet != null &&
+            !((valueSet is List &&
+                (valueSet
                     .every((item) => SymbolKind.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<SymbolKind>');
           return false;
@@ -12901,38 +13421,38 @@
 
   DocumentSymbolClientCapabilitiesTagSupport({required this.valueSet});
   static DocumentSymbolClientCapabilitiesTagSupport fromJson(
-      Map<String, dynamic> json) {
-    final valueSet = json['valueSet']
-        ?.map((item) => SymbolTag.fromJson(item))
-        ?.cast<SymbolTag>()
-        ?.toList();
+      Map<String, Object?> json) {
+    final valueSetJson = json['valueSet'];
+    final valueSet = (valueSetJson as List<Object?>)
+        .map((item) => SymbolTag.fromJson(item as num))
+        .toList();
     return DocumentSymbolClientCapabilitiesTagSupport(valueSet: valueSet);
   }
 
   /// The tags supported by the client.
   final List<SymbolTag> valueSet;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['valueSet'] = valueSet.map((item) => item.toJson()).toList();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('valueSet');
       try {
         if (!obj.containsKey('valueSet')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['valueSet'] == null) {
+        final valueSet = obj['valueSet'];
+        if (valueSet == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['valueSet'] is List &&
-            (obj['valueSet']
-                .every((item) => SymbolTag.canParse(item, reporter)))))) {
+        if (!((valueSet is List &&
+            (valueSet.every((item) => SymbolTag.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<SymbolTag>');
           return false;
         }
@@ -12974,12 +13494,14 @@
       DocumentSymbolOptions.canParse, DocumentSymbolOptions.fromJson);
 
   DocumentSymbolOptions({this.label, this.workDoneProgress});
-  static DocumentSymbolOptions fromJson(Map<String, dynamic> json) {
+  static DocumentSymbolOptions fromJson(Map<String, Object?> json) {
     if (DocumentSymbolRegistrationOptions.canParse(json, nullLspJsonReporter)) {
       return DocumentSymbolRegistrationOptions.fromJson(json);
     }
-    final label = json['label'];
-    final workDoneProgress = json['workDoneProgress'];
+    final labelJson = json['label'];
+    final label = labelJson as String?;
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return DocumentSymbolOptions(
         label: label, workDoneProgress: workDoneProgress);
   }
@@ -12990,8 +13512,8 @@
   final String? label;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (label != null) {
       __result['label'] = label;
     }
@@ -13002,10 +13524,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('label');
       try {
-        if (obj['label'] != null && !(obj['label'] is String)) {
+        final label = obj['label'];
+        if (label != null && !(label is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -13014,8 +13537,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -13061,22 +13584,26 @@
       {required this.textDocument,
       this.workDoneToken,
       this.partialResultToken});
-  static DocumentSymbolParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final workDoneToken = json['workDoneToken'] == null
+  static DocumentSymbolParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
-    final partialResultToken = json['partialResultToken'] == null
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
+    final partialResultTokenJson = json['partialResultToken'];
+    final partialResultToken = partialResultTokenJson == null
         ? null
-        : (json['partialResultToken'] is int
-            ? Either2<int, String>.t1(json['partialResultToken'])
-            : (json['partialResultToken'] is String
-                ? Either2<int, String>.t2(json['partialResultToken'])
-                : (throw '''${json['partialResultToken']} was not one of (int, String)''')));
+        : (partialResultTokenJson is int
+            ? Either2<int, String>.t1(partialResultTokenJson)
+            : (partialResultTokenJson is String
+                ? Either2<int, String>.t2(partialResultTokenJson)
+                : (throw '''$partialResultTokenJson was not one of (int, String)''')));
     return DocumentSymbolParams(
         textDocument: textDocument,
         workDoneToken: workDoneToken,
@@ -13093,8 +13620,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     if (workDoneToken != null) {
       __result['workDoneToken'] = workDoneToken;
@@ -13106,18 +13633,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -13126,9 +13654,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -13137,9 +13665,9 @@
       }
       reporter.push('partialResultToken');
       try {
-        if (obj['partialResultToken'] != null &&
-            !((obj['partialResultToken'] is int ||
-                obj['partialResultToken'] is String))) {
+        final partialResultToken = obj['partialResultToken'];
+        if (partialResultToken != null &&
+            !((partialResultToken is int || partialResultToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -13189,13 +13717,15 @@
 
   DocumentSymbolRegistrationOptions(
       {this.documentSelector, this.label, this.workDoneProgress});
-  static DocumentSymbolRegistrationOptions fromJson(Map<String, dynamic> json) {
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final label = json['label'];
-    final workDoneProgress = json['workDoneProgress'];
+  static DocumentSymbolRegistrationOptions fromJson(Map<String, Object?> json) {
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final labelJson = json['label'];
+    final label = labelJson as String?;
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return DocumentSymbolRegistrationOptions(
         documentSelector: documentSelector,
         label: label,
@@ -13212,8 +13742,8 @@
   final String? label;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['documentSelector'] = documentSelector;
     if (label != null) {
       __result['label'] = label;
@@ -13225,16 +13755,17 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentSelector');
       try {
         if (!obj.containsKey('documentSelector')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -13244,7 +13775,8 @@
       }
       reporter.push('label');
       try {
-        if (obj['label'] != null && !(obj['label'] is String)) {
+        final label = obj['label'];
+        if (label != null && !(label is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -13253,8 +13785,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -13353,8 +13885,9 @@
       ExecuteCommandClientCapabilities.fromJson);
 
   ExecuteCommandClientCapabilities({this.dynamicRegistration});
-  static ExecuteCommandClientCapabilities fromJson(Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
+  static ExecuteCommandClientCapabilities fromJson(Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
     return ExecuteCommandClientCapabilities(
         dynamicRegistration: dynamicRegistration);
   }
@@ -13362,8 +13895,8 @@
   /// Execute command supports dynamic registration.
   final bool? dynamicRegistration;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -13371,11 +13904,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -13414,13 +13947,15 @@
       ExecuteCommandOptions.canParse, ExecuteCommandOptions.fromJson);
 
   ExecuteCommandOptions({required this.commands, this.workDoneProgress});
-  static ExecuteCommandOptions fromJson(Map<String, dynamic> json) {
+  static ExecuteCommandOptions fromJson(Map<String, Object?> json) {
     if (ExecuteCommandRegistrationOptions.canParse(json, nullLspJsonReporter)) {
       return ExecuteCommandRegistrationOptions.fromJson(json);
     }
+    final commandsJson = json['commands'];
     final commands =
-        json['commands']?.map((item) => item)?.cast<String>()?.toList();
-    final workDoneProgress = json['workDoneProgress'];
+        (commandsJson as List<Object?>).map((item) => item as String).toList();
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return ExecuteCommandOptions(
         commands: commands, workDoneProgress: workDoneProgress);
   }
@@ -13429,8 +13964,8 @@
   final List<String> commands;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['commands'] = commands;
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
@@ -13439,19 +13974,20 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('commands');
       try {
         if (!obj.containsKey('commands')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['commands'] == null) {
+        final commands = obj['commands'];
+        if (commands == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['commands'] is List &&
-            (obj['commands'].every((item) => item is String))))) {
+        if (!((commands is List &&
+            (commands.every((item) => item is String))))) {
           reporter.reportError('must be of type List<String>');
           return false;
         }
@@ -13460,8 +13996,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -13505,23 +14041,26 @@
 
   ExecuteCommandParams(
       {required this.command, this.arguments, this.workDoneToken});
-  static ExecuteCommandParams fromJson(Map<String, dynamic> json) {
-    final command = json['command'];
+  static ExecuteCommandParams fromJson(Map<String, Object?> json) {
+    final commandJson = json['command'];
+    final command = commandJson as String;
+    final argumentsJson = json['arguments'];
     final arguments =
-        json['arguments']?.map((item) => item)?.cast<dynamic>()?.toList();
-    final workDoneToken = json['workDoneToken'] == null
+        (argumentsJson as List<Object?>?)?.map((item) => item).toList();
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
     return ExecuteCommandParams(
         command: command, arguments: arguments, workDoneToken: workDoneToken);
   }
 
   /// Arguments that the command should be invoked with.
-  final List<dynamic>? arguments;
+  final List<Object?>? arguments;
 
   /// The identifier of the actual command handler.
   final String command;
@@ -13529,8 +14068,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['command'] = command;
     if (arguments != null) {
       __result['arguments'] = arguments;
@@ -13542,18 +14081,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('command');
       try {
         if (!obj.containsKey('command')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['command'] == null) {
+        final command = obj['command'];
+        if (command == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['command'] is String)) {
+        if (!(command is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -13562,10 +14102,10 @@
       }
       reporter.push('arguments');
       try {
-        if (obj['arguments'] != null &&
-            !((obj['arguments'] is List &&
-                (obj['arguments'].every((item) => true))))) {
-          reporter.reportError('must be of type List<dynamic>');
+        final arguments = obj['arguments'];
+        if (arguments != null &&
+            !((arguments is List && (arguments.every((item) => true))))) {
+          reporter.reportError('must be of type List<Object?>');
           return false;
         }
       } finally {
@@ -13573,9 +14113,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -13595,7 +14135,7 @@
         other.runtimeType == ExecuteCommandParams) {
       return command == other.command &&
           listEqual(
-              arguments, other.arguments, (dynamic a, dynamic b) => a == b) &&
+              arguments, other.arguments, (Object? a, Object? b) => a == b) &&
           workDoneToken == other.workDoneToken &&
           true;
     }
@@ -13624,10 +14164,12 @@
 
   ExecuteCommandRegistrationOptions(
       {required this.commands, this.workDoneProgress});
-  static ExecuteCommandRegistrationOptions fromJson(Map<String, dynamic> json) {
+  static ExecuteCommandRegistrationOptions fromJson(Map<String, Object?> json) {
+    final commandsJson = json['commands'];
     final commands =
-        json['commands']?.map((item) => item)?.cast<String>()?.toList();
-    final workDoneProgress = json['workDoneProgress'];
+        (commandsJson as List<Object?>).map((item) => item as String).toList();
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return ExecuteCommandRegistrationOptions(
         commands: commands, workDoneProgress: workDoneProgress);
   }
@@ -13636,8 +14178,8 @@
   final List<String> commands;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['commands'] = commands;
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
@@ -13646,19 +14188,20 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('commands');
       try {
         if (!obj.containsKey('commands')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['commands'] == null) {
+        final commands = obj['commands'];
+        if (commands == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['commands'] is List &&
-            (obj['commands'].every((item) => item is String))))) {
+        if (!((commands is List &&
+            (commands.every((item) => item is String))))) {
           reporter.reportError('must be of type List<String>');
           return false;
         }
@@ -13667,8 +14210,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -13791,33 +14334,35 @@
       LspJsonHandler(FileCreate.canParse, FileCreate.fromJson);
 
   FileCreate({required this.uri});
-  static FileCreate fromJson(Map<String, dynamic> json) {
-    final uri = json['uri'];
+  static FileCreate fromJson(Map<String, Object?> json) {
+    final uriJson = json['uri'];
+    final uri = uriJson as String;
     return FileCreate(uri: uri);
   }
 
   /// A file:// URI for the location of the file/folder being created.
   final String uri;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['uri'] = uri;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('uri');
       try {
         if (!obj.containsKey('uri')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['uri'] == null) {
+        final uri = obj['uri'];
+        if (uri == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['uri'] is String)) {
+        if (!(uri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -13857,33 +14402,35 @@
       LspJsonHandler(FileDelete.canParse, FileDelete.fromJson);
 
   FileDelete({required this.uri});
-  static FileDelete fromJson(Map<String, dynamic> json) {
-    final uri = json['uri'];
+  static FileDelete fromJson(Map<String, Object?> json) {
+    final uriJson = json['uri'];
+    final uri = uriJson as String;
     return FileDelete(uri: uri);
   }
 
   /// A file:// URI for the location of the file/folder being deleted.
   final String uri;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['uri'] = uri;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('uri');
       try {
         if (!obj.containsKey('uri')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['uri'] == null) {
+        final uri = obj['uri'];
+        if (uri == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['uri'] is String)) {
+        if (!(uri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -13922,9 +14469,11 @@
       LspJsonHandler(FileEvent.canParse, FileEvent.fromJson);
 
   FileEvent({required this.uri, required this.type});
-  static FileEvent fromJson(Map<String, dynamic> json) {
-    final uri = json['uri'];
-    final type = json['type'];
+  static FileEvent fromJson(Map<String, Object?> json) {
+    final uriJson = json['uri'];
+    final uri = uriJson as String;
+    final typeJson = json['type'];
+    final type = typeJson as int;
     return FileEvent(uri: uri, type: type);
   }
 
@@ -13934,26 +14483,27 @@
   /// The file's URI.
   final String uri;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['uri'] = uri;
     __result['type'] = type;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('uri');
       try {
         if (!obj.containsKey('uri')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['uri'] == null) {
+        final uri = obj['uri'];
+        if (uri == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['uri'] is String)) {
+        if (!(uri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -13966,11 +14516,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['type'] == null) {
+        final type = obj['type'];
+        if (type == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['type'] is int)) {
+        if (!(type is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -14012,9 +14563,12 @@
       FileOperationFilter.canParse, FileOperationFilter.fromJson);
 
   FileOperationFilter({this.scheme, required this.pattern});
-  static FileOperationFilter fromJson(Map<String, dynamic> json) {
-    final scheme = json['scheme'];
-    final pattern = FileOperationPattern.fromJson(json['pattern']);
+  static FileOperationFilter fromJson(Map<String, Object?> json) {
+    final schemeJson = json['scheme'];
+    final scheme = schemeJson as String?;
+    final patternJson = json['pattern'];
+    final pattern =
+        FileOperationPattern.fromJson(patternJson as Map<String, Object?>);
     return FileOperationFilter(scheme: scheme, pattern: pattern);
   }
 
@@ -14024,8 +14578,8 @@
   /// A Uri like `file` or `untitled`.
   final String? scheme;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (scheme != null) {
       __result['scheme'] = scheme;
     }
@@ -14034,10 +14588,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('scheme');
       try {
-        if (obj['scheme'] != null && !(obj['scheme'] is String)) {
+        final scheme = obj['scheme'];
+        if (scheme != null && !(scheme is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -14050,11 +14605,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['pattern'] == null) {
+        final pattern = obj['pattern'];
+        if (pattern == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(FileOperationPattern.canParse(obj['pattern'], reporter))) {
+        if (!(FileOperationPattern.canParse(pattern, reporter))) {
           reporter.reportError('must be of type FileOperationPattern');
           return false;
         }
@@ -14097,13 +14653,17 @@
       FileOperationPattern.canParse, FileOperationPattern.fromJson);
 
   FileOperationPattern({required this.glob, this.matches, this.options});
-  static FileOperationPattern fromJson(Map<String, dynamic> json) {
-    final glob = json['glob'];
-    final matches = json['matches'] != null
-        ? FileOperationPatternKind.fromJson(json['matches'])
+  static FileOperationPattern fromJson(Map<String, Object?> json) {
+    final globJson = json['glob'];
+    final glob = globJson as String;
+    final matchesJson = json['matches'];
+    final matches = matchesJson != null
+        ? FileOperationPatternKind.fromJson(matchesJson as String)
         : null;
-    final options = json['options'] != null
-        ? FileOperationPatternOptions.fromJson(json['options'])
+    final optionsJson = json['options'];
+    final options = optionsJson != null
+        ? FileOperationPatternOptions.fromJson(
+            optionsJson as Map<String, Object?>)
         : null;
     return FileOperationPattern(glob: glob, matches: matches, options: options);
   }
@@ -14129,8 +14689,8 @@
   /// Additional options used during matching.
   final FileOperationPatternOptions? options;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['glob'] = glob;
     if (matches != null) {
       __result['matches'] = matches?.toJson();
@@ -14142,18 +14702,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('glob');
       try {
         if (!obj.containsKey('glob')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['glob'] == null) {
+        final glob = obj['glob'];
+        if (glob == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['glob'] is String)) {
+        if (!(glob is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -14162,8 +14723,9 @@
       }
       reporter.push('matches');
       try {
-        if (obj['matches'] != null &&
-            !(FileOperationPatternKind.canParse(obj['matches'], reporter))) {
+        final matches = obj['matches'];
+        if (matches != null &&
+            !(FileOperationPatternKind.canParse(matches, reporter))) {
           reporter.reportError('must be of type FileOperationPatternKind');
           return false;
         }
@@ -14172,8 +14734,9 @@
       }
       reporter.push('options');
       try {
-        if (obj['options'] != null &&
-            !(FileOperationPatternOptions.canParse(obj['options'], reporter))) {
+        final options = obj['options'];
+        if (options != null &&
+            !(FileOperationPatternOptions.canParse(options, reporter))) {
           reporter.reportError('must be of type FileOperationPatternOptions');
           return false;
         }
@@ -14250,16 +14813,17 @@
       FileOperationPatternOptions.fromJson);
 
   FileOperationPatternOptions({this.ignoreCase});
-  static FileOperationPatternOptions fromJson(Map<String, dynamic> json) {
-    final ignoreCase = json['ignoreCase'];
+  static FileOperationPatternOptions fromJson(Map<String, Object?> json) {
+    final ignoreCaseJson = json['ignoreCase'];
+    final ignoreCase = ignoreCaseJson as bool?;
     return FileOperationPatternOptions(ignoreCase: ignoreCase);
   }
 
   /// The pattern should be matched ignoring casing.
   final bool? ignoreCase;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (ignoreCase != null) {
       __result['ignoreCase'] = ignoreCase;
     }
@@ -14267,10 +14831,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('ignoreCase');
       try {
-        if (obj['ignoreCase'] != null && !(obj['ignoreCase'] is bool)) {
+        final ignoreCase = obj['ignoreCase'];
+        if (ignoreCase != null && !(ignoreCase is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -14312,37 +14877,39 @@
       FileOperationRegistrationOptions.fromJson);
 
   FileOperationRegistrationOptions({required this.filters});
-  static FileOperationRegistrationOptions fromJson(Map<String, dynamic> json) {
-    final filters = json['filters']
-        ?.map((item) => FileOperationFilter.fromJson(item))
-        ?.cast<FileOperationFilter>()
-        ?.toList();
+  static FileOperationRegistrationOptions fromJson(Map<String, Object?> json) {
+    final filtersJson = json['filters'];
+    final filters = (filtersJson as List<Object?>)
+        .map((item) =>
+            FileOperationFilter.fromJson(item as Map<String, Object?>))
+        .toList();
     return FileOperationRegistrationOptions(filters: filters);
   }
 
   /// The actual filters.
   final List<FileOperationFilter> filters;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['filters'] = filters.map((item) => item.toJson()).toList();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('filters');
       try {
         if (!obj.containsKey('filters')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['filters'] == null) {
+        final filters = obj['filters'];
+        if (filters == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['filters'] is List &&
-            (obj['filters'].every(
+        if (!((filters is List &&
+            (filters.every(
                 (item) => FileOperationFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<FileOperationFilter>');
           return false;
@@ -14386,9 +14953,11 @@
       LspJsonHandler(FileRename.canParse, FileRename.fromJson);
 
   FileRename({required this.oldUri, required this.newUri});
-  static FileRename fromJson(Map<String, dynamic> json) {
-    final oldUri = json['oldUri'];
-    final newUri = json['newUri'];
+  static FileRename fromJson(Map<String, Object?> json) {
+    final oldUriJson = json['oldUri'];
+    final oldUri = oldUriJson as String;
+    final newUriJson = json['newUri'];
+    final newUri = newUriJson as String;
     return FileRename(oldUri: oldUri, newUri: newUri);
   }
 
@@ -14398,26 +14967,27 @@
   /// A file:// URI for the original location of the file/folder being renamed.
   final String oldUri;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['oldUri'] = oldUri;
     __result['newUri'] = newUri;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('oldUri');
       try {
         if (!obj.containsKey('oldUri')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['oldUri'] == null) {
+        final oldUri = obj['oldUri'];
+        if (oldUri == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['oldUri'] is String)) {
+        if (!(oldUri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -14430,11 +15000,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['newUri'] == null) {
+        final newUri = obj['newUri'];
+        if (newUri == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['newUri'] is String)) {
+        if (!(newUri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -14473,9 +15044,11 @@
       LspJsonHandler(FileSystemWatcher.canParse, FileSystemWatcher.fromJson);
 
   FileSystemWatcher({required this.globPattern, this.kind});
-  static FileSystemWatcher fromJson(Map<String, dynamic> json) {
-    final globPattern = json['globPattern'];
-    final kind = json['kind'] != null ? WatchKind.fromJson(json['kind']) : null;
+  static FileSystemWatcher fromJson(Map<String, Object?> json) {
+    final globPatternJson = json['globPattern'];
+    final globPattern = globPatternJson as String;
+    final kindJson = json['kind'];
+    final kind = kindJson != null ? WatchKind.fromJson(kindJson as int) : null;
     return FileSystemWatcher(globPattern: globPattern, kind: kind);
   }
 
@@ -14498,8 +15071,8 @@
   /// | WatchKind.Change | WatchKind.Delete which is 7.
   final WatchKind? kind;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['globPattern'] = globPattern;
     if (kind != null) {
       __result['kind'] = kind?.toJson();
@@ -14508,18 +15081,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('globPattern');
       try {
         if (!obj.containsKey('globPattern')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['globPattern'] == null) {
+        final globPattern = obj['globPattern'];
+        if (globPattern == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['globPattern'] is String)) {
+        if (!(globPattern is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -14528,8 +15102,8 @@
       }
       reporter.push('kind');
       try {
-        if (obj['kind'] != null &&
-            !(WatchKind.canParse(obj['kind'], reporter))) {
+        final kind = obj['kind'];
+        if (kind != null && !(WatchKind.canParse(kind, reporter))) {
           reporter.reportError('must be of type WatchKind');
           return false;
         }
@@ -14576,13 +15150,18 @@
       required this.endLine,
       this.endCharacter,
       this.kind});
-  static FoldingRange fromJson(Map<String, dynamic> json) {
-    final startLine = json['startLine'];
-    final startCharacter = json['startCharacter'];
-    final endLine = json['endLine'];
-    final endCharacter = json['endCharacter'];
+  static FoldingRange fromJson(Map<String, Object?> json) {
+    final startLineJson = json['startLine'];
+    final startLine = startLineJson as int;
+    final startCharacterJson = json['startCharacter'];
+    final startCharacter = startCharacterJson as int?;
+    final endLineJson = json['endLine'];
+    final endLine = endLineJson as int;
+    final endCharacterJson = json['endCharacter'];
+    final endCharacter = endCharacterJson as int?;
+    final kindJson = json['kind'];
     final kind =
-        json['kind'] != null ? FoldingRangeKind.fromJson(json['kind']) : null;
+        kindJson != null ? FoldingRangeKind.fromJson(kindJson as String) : null;
     return FoldingRange(
         startLine: startLine,
         startCharacter: startCharacter,
@@ -14615,8 +15194,8 @@
   /// larger and smaller than the number of lines in the document.
   final int startLine;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['startLine'] = startLine;
     if (startCharacter != null) {
       __result['startCharacter'] = startCharacter;
@@ -14632,18 +15211,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('startLine');
       try {
         if (!obj.containsKey('startLine')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['startLine'] == null) {
+        final startLine = obj['startLine'];
+        if (startLine == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['startLine'] is int)) {
+        if (!(startLine is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -14652,7 +15232,8 @@
       }
       reporter.push('startCharacter');
       try {
-        if (obj['startCharacter'] != null && !(obj['startCharacter'] is int)) {
+        final startCharacter = obj['startCharacter'];
+        if (startCharacter != null && !(startCharacter is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -14665,11 +15246,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['endLine'] == null) {
+        final endLine = obj['endLine'];
+        if (endLine == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['endLine'] is int)) {
+        if (!(endLine is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -14678,7 +15260,8 @@
       }
       reporter.push('endCharacter');
       try {
-        if (obj['endCharacter'] != null && !(obj['endCharacter'] is int)) {
+        final endCharacter = obj['endCharacter'];
+        if (endCharacter != null && !(endCharacter is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -14687,8 +15270,8 @@
       }
       reporter.push('kind');
       try {
-        if (obj['kind'] != null &&
-            !(FoldingRangeKind.canParse(obj['kind'], reporter))) {
+        final kind = obj['kind'];
+        if (kind != null && !(FoldingRangeKind.canParse(kind, reporter))) {
           reporter.reportError('must be of type FoldingRangeKind');
           return false;
         }
@@ -14737,10 +15320,13 @@
 
   FoldingRangeClientCapabilities(
       {this.dynamicRegistration, this.rangeLimit, this.lineFoldingOnly});
-  static FoldingRangeClientCapabilities fromJson(Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
-    final rangeLimit = json['rangeLimit'];
-    final lineFoldingOnly = json['lineFoldingOnly'];
+  static FoldingRangeClientCapabilities fromJson(Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
+    final rangeLimitJson = json['rangeLimit'];
+    final rangeLimit = rangeLimitJson as int?;
+    final lineFoldingOnlyJson = json['lineFoldingOnly'];
+    final lineFoldingOnly = lineFoldingOnlyJson as bool?;
     return FoldingRangeClientCapabilities(
         dynamicRegistration: dynamicRegistration,
         rangeLimit: rangeLimit,
@@ -14763,8 +15349,8 @@
   /// limit.
   final int? rangeLimit;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -14778,11 +15364,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -14791,7 +15377,8 @@
       }
       reporter.push('rangeLimit');
       try {
-        if (obj['rangeLimit'] != null && !(obj['rangeLimit'] is int)) {
+        final rangeLimit = obj['rangeLimit'];
+        if (rangeLimit != null && !(rangeLimit is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -14800,8 +15387,8 @@
       }
       reporter.push('lineFoldingOnly');
       try {
-        if (obj['lineFoldingOnly'] != null &&
-            !(obj['lineFoldingOnly'] is bool)) {
+        final lineFoldingOnly = obj['lineFoldingOnly'];
+        if (lineFoldingOnly != null && !(lineFoldingOnly is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -14876,18 +15463,19 @@
       FoldingRangeOptions.canParse, FoldingRangeOptions.fromJson);
 
   FoldingRangeOptions({this.workDoneProgress});
-  static FoldingRangeOptions fromJson(Map<String, dynamic> json) {
+  static FoldingRangeOptions fromJson(Map<String, Object?> json) {
     if (FoldingRangeRegistrationOptions.canParse(json, nullLspJsonReporter)) {
       return FoldingRangeRegistrationOptions.fromJson(json);
     }
-    final workDoneProgress = json['workDoneProgress'];
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return FoldingRangeOptions(workDoneProgress: workDoneProgress);
   }
 
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
     }
@@ -14895,11 +15483,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -14942,22 +15530,26 @@
       {required this.textDocument,
       this.workDoneToken,
       this.partialResultToken});
-  static FoldingRangeParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final workDoneToken = json['workDoneToken'] == null
+  static FoldingRangeParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
-    final partialResultToken = json['partialResultToken'] == null
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
+    final partialResultTokenJson = json['partialResultToken'];
+    final partialResultToken = partialResultTokenJson == null
         ? null
-        : (json['partialResultToken'] is int
-            ? Either2<int, String>.t1(json['partialResultToken'])
-            : (json['partialResultToken'] is String
-                ? Either2<int, String>.t2(json['partialResultToken'])
-                : (throw '''${json['partialResultToken']} was not one of (int, String)''')));
+        : (partialResultTokenJson is int
+            ? Either2<int, String>.t1(partialResultTokenJson)
+            : (partialResultTokenJson is String
+                ? Either2<int, String>.t2(partialResultTokenJson)
+                : (throw '''$partialResultTokenJson was not one of (int, String)''')));
     return FoldingRangeParams(
         textDocument: textDocument,
         workDoneToken: workDoneToken,
@@ -14974,8 +15566,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     if (workDoneToken != null) {
       __result['workDoneToken'] = workDoneToken;
@@ -14987,18 +15579,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -15007,9 +15600,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -15018,9 +15611,9 @@
       }
       reporter.push('partialResultToken');
       try {
-        if (obj['partialResultToken'] != null &&
-            !((obj['partialResultToken'] is int ||
-                obj['partialResultToken'] is String))) {
+        final partialResultToken = obj['partialResultToken'];
+        if (partialResultToken != null &&
+            !((partialResultToken is int || partialResultToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -15071,13 +15664,15 @@
 
   FoldingRangeRegistrationOptions(
       {this.documentSelector, this.workDoneProgress, this.id});
-  static FoldingRangeRegistrationOptions fromJson(Map<String, dynamic> json) {
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final workDoneProgress = json['workDoneProgress'];
-    final id = json['id'];
+  static FoldingRangeRegistrationOptions fromJson(Map<String, Object?> json) {
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
+    final idJson = json['id'];
+    final id = idJson as String?;
     return FoldingRangeRegistrationOptions(
         documentSelector: documentSelector,
         workDoneProgress: workDoneProgress,
@@ -15093,8 +15688,8 @@
   final String? id;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['documentSelector'] = documentSelector;
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
@@ -15106,16 +15701,17 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentSelector');
       try {
         if (!obj.containsKey('documentSelector')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -15125,8 +15721,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -15135,7 +15731,8 @@
       }
       reporter.push('id');
       try {
-        if (obj['id'] != null && !(obj['id'] is String)) {
+        final id = obj['id'];
+        if (id != null && !(id is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -15186,12 +15783,17 @@
       this.trimTrailingWhitespace,
       this.insertFinalNewline,
       this.trimFinalNewlines});
-  static FormattingOptions fromJson(Map<String, dynamic> json) {
-    final tabSize = json['tabSize'];
-    final insertSpaces = json['insertSpaces'];
-    final trimTrailingWhitespace = json['trimTrailingWhitespace'];
-    final insertFinalNewline = json['insertFinalNewline'];
-    final trimFinalNewlines = json['trimFinalNewlines'];
+  static FormattingOptions fromJson(Map<String, Object?> json) {
+    final tabSizeJson = json['tabSize'];
+    final tabSize = tabSizeJson as int;
+    final insertSpacesJson = json['insertSpaces'];
+    final insertSpaces = insertSpacesJson as bool;
+    final trimTrailingWhitespaceJson = json['trimTrailingWhitespace'];
+    final trimTrailingWhitespace = trimTrailingWhitespaceJson as bool?;
+    final insertFinalNewlineJson = json['insertFinalNewline'];
+    final insertFinalNewline = insertFinalNewlineJson as bool?;
+    final trimFinalNewlinesJson = json['trimFinalNewlines'];
+    final trimFinalNewlines = trimFinalNewlinesJson as bool?;
     return FormattingOptions(
         tabSize: tabSize,
         insertSpaces: insertSpaces,
@@ -15218,8 +15820,8 @@
   ///  @since 3.15.0
   final bool? trimTrailingWhitespace;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['tabSize'] = tabSize;
     __result['insertSpaces'] = insertSpaces;
     if (trimTrailingWhitespace != null) {
@@ -15235,18 +15837,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('tabSize');
       try {
         if (!obj.containsKey('tabSize')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['tabSize'] == null) {
+        final tabSize = obj['tabSize'];
+        if (tabSize == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['tabSize'] is int)) {
+        if (!(tabSize is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -15259,11 +15862,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['insertSpaces'] == null) {
+        final insertSpaces = obj['insertSpaces'];
+        if (insertSpaces == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['insertSpaces'] is bool)) {
+        if (!(insertSpaces is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -15272,8 +15876,9 @@
       }
       reporter.push('trimTrailingWhitespace');
       try {
-        if (obj['trimTrailingWhitespace'] != null &&
-            !(obj['trimTrailingWhitespace'] is bool)) {
+        final trimTrailingWhitespace = obj['trimTrailingWhitespace'];
+        if (trimTrailingWhitespace != null &&
+            !(trimTrailingWhitespace is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -15282,8 +15887,8 @@
       }
       reporter.push('insertFinalNewline');
       try {
-        if (obj['insertFinalNewline'] != null &&
-            !(obj['insertFinalNewline'] is bool)) {
+        final insertFinalNewline = obj['insertFinalNewline'];
+        if (insertFinalNewline != null && !(insertFinalNewline is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -15292,8 +15897,8 @@
       }
       reporter.push('trimFinalNewlines');
       try {
-        if (obj['trimFinalNewlines'] != null &&
-            !(obj['trimFinalNewlines'] is bool)) {
+        final trimFinalNewlines = obj['trimFinalNewlines'];
+        if (trimFinalNewlines != null && !(trimFinalNewlines is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -15340,14 +15945,18 @@
   static const jsonHandler = LspJsonHandler(Hover.canParse, Hover.fromJson);
 
   Hover({required this.contents, this.range});
-  static Hover fromJson(Map<String, dynamic> json) {
-    final contents = json['contents'] is String
-        ? Either2<String, MarkupContent>.t1(json['contents'])
-        : (MarkupContent.canParse(json['contents'], nullLspJsonReporter)
+  static Hover fromJson(Map<String, Object?> json) {
+    final contentsJson = json['contents'];
+    final contents = contentsJson is String
+        ? Either2<String, MarkupContent>.t1(contentsJson)
+        : (MarkupContent.canParse(contentsJson, nullLspJsonReporter)
             ? Either2<String, MarkupContent>.t2(
-                MarkupContent.fromJson(json['contents']))
-            : (throw '''${json['contents']} was not one of (String, MarkupContent)'''));
-    final range = json['range'] != null ? Range.fromJson(json['range']) : null;
+                MarkupContent.fromJson(contentsJson as Map<String, Object?>))
+            : (throw '''$contentsJson was not one of (String, MarkupContent)'''));
+    final rangeJson = json['range'];
+    final range = rangeJson != null
+        ? Range.fromJson(rangeJson as Map<String, Object?>)
+        : null;
     return Hover(contents: contents, range: range);
   }
 
@@ -15358,8 +15967,8 @@
   /// visualize a hover, e.g. by changing the background color.
   final Range? range;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['contents'] = contents;
     if (range != null) {
       __result['range'] = range?.toJson();
@@ -15368,19 +15977,20 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('contents');
       try {
         if (!obj.containsKey('contents')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['contents'] == null) {
+        final contents = obj['contents'];
+        if (contents == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['contents'] is String ||
-            MarkupContent.canParse(obj['contents'], reporter)))) {
+        if (!((contents is String ||
+            MarkupContent.canParse(contents, reporter)))) {
           reporter
               .reportError('must be of type Either2<String, MarkupContent>');
           return false;
@@ -15390,7 +16000,8 @@
       }
       reporter.push('range');
       try {
-        if (obj['range'] != null && !(Range.canParse(obj['range'], reporter))) {
+        final range = obj['range'];
+        if (range != null && !(Range.canParse(range, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -15429,12 +16040,13 @@
       HoverClientCapabilities.canParse, HoverClientCapabilities.fromJson);
 
   HoverClientCapabilities({this.dynamicRegistration, this.contentFormat});
-  static HoverClientCapabilities fromJson(Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
-    final contentFormat = json['contentFormat']
-        ?.map((item) => item != null ? MarkupKind.fromJson(item) : null)
-        ?.cast<MarkupKind>()
-        ?.toList();
+  static HoverClientCapabilities fromJson(Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
+    final contentFormatJson = json['contentFormat'];
+    final contentFormat = (contentFormatJson as List<Object?>?)
+        ?.map((item) => MarkupKind.fromJson(item as String))
+        .toList();
     return HoverClientCapabilities(
         dynamicRegistration: dynamicRegistration, contentFormat: contentFormat);
   }
@@ -15447,8 +16059,8 @@
   /// Whether hover supports dynamic registration.
   final bool? dynamicRegistration;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -15460,11 +16072,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -15473,9 +16085,10 @@
       }
       reporter.push('contentFormat');
       try {
-        if (obj['contentFormat'] != null &&
-            !((obj['contentFormat'] is List &&
-                (obj['contentFormat']
+        final contentFormat = obj['contentFormat'];
+        if (contentFormat != null &&
+            !((contentFormat is List &&
+                (contentFormat
                     .every((item) => MarkupKind.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<MarkupKind>');
           return false;
@@ -15519,18 +16132,19 @@
       LspJsonHandler(HoverOptions.canParse, HoverOptions.fromJson);
 
   HoverOptions({this.workDoneProgress});
-  static HoverOptions fromJson(Map<String, dynamic> json) {
+  static HoverOptions fromJson(Map<String, Object?> json) {
     if (HoverRegistrationOptions.canParse(json, nullLspJsonReporter)) {
       return HoverRegistrationOptions.fromJson(json);
     }
-    final workDoneProgress = json['workDoneProgress'];
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return HoverOptions(workDoneProgress: workDoneProgress);
   }
 
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
     }
@@ -15538,11 +16152,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -15582,16 +16196,20 @@
 
   HoverParams(
       {required this.textDocument, required this.position, this.workDoneToken});
-  static HoverParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final position = Position.fromJson(json['position']);
-    final workDoneToken = json['workDoneToken'] == null
+  static HoverParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final positionJson = json['position'];
+    final position = Position.fromJson(positionJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
     return HoverParams(
         textDocument: textDocument,
         position: position,
@@ -15607,8 +16225,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     __result['position'] = position.toJson();
     if (workDoneToken != null) {
@@ -15618,18 +16236,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -15642,11 +16261,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['position'] == null) {
+        final position = obj['position'];
+        if (position == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Position.canParse(obj['position'], reporter))) {
+        if (!(Position.canParse(position, reporter))) {
           reporter.reportError('must be of type Position');
           return false;
         }
@@ -15655,9 +16275,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -15701,12 +16321,13 @@
       HoverRegistrationOptions.canParse, HoverRegistrationOptions.fromJson);
 
   HoverRegistrationOptions({this.documentSelector, this.workDoneProgress});
-  static HoverRegistrationOptions fromJson(Map<String, dynamic> json) {
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final workDoneProgress = json['workDoneProgress'];
+  static HoverRegistrationOptions fromJson(Map<String, Object?> json) {
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return HoverRegistrationOptions(
         documentSelector: documentSelector, workDoneProgress: workDoneProgress);
   }
@@ -15716,8 +16337,8 @@
   final List<DocumentFilter>? documentSelector;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['documentSelector'] = documentSelector;
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
@@ -15726,16 +16347,17 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentSelector');
       try {
         if (!obj.containsKey('documentSelector')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -15745,8 +16367,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -15791,9 +16413,11 @@
 
   ImplementationClientCapabilities(
       {this.dynamicRegistration, this.linkSupport});
-  static ImplementationClientCapabilities fromJson(Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
-    final linkSupport = json['linkSupport'];
+  static ImplementationClientCapabilities fromJson(Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
+    final linkSupportJson = json['linkSupport'];
+    final linkSupport = linkSupportJson as bool?;
     return ImplementationClientCapabilities(
         dynamicRegistration: dynamicRegistration, linkSupport: linkSupport);
   }
@@ -15807,8 +16431,8 @@
   ///  @since 3.14.0
   final bool? linkSupport;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -15819,11 +16443,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -15832,7 +16456,8 @@
       }
       reporter.push('linkSupport');
       try {
-        if (obj['linkSupport'] != null && !(obj['linkSupport'] is bool)) {
+        final linkSupport = obj['linkSupport'];
+        if (linkSupport != null && !(linkSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -15874,18 +16499,19 @@
       ImplementationOptions.canParse, ImplementationOptions.fromJson);
 
   ImplementationOptions({this.workDoneProgress});
-  static ImplementationOptions fromJson(Map<String, dynamic> json) {
+  static ImplementationOptions fromJson(Map<String, Object?> json) {
     if (ImplementationRegistrationOptions.canParse(json, nullLspJsonReporter)) {
       return ImplementationRegistrationOptions.fromJson(json);
     }
-    final workDoneProgress = json['workDoneProgress'];
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return ImplementationOptions(workDoneProgress: workDoneProgress);
   }
 
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
     }
@@ -15893,11 +16519,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -15945,23 +16571,28 @@
       required this.position,
       this.workDoneToken,
       this.partialResultToken});
-  static ImplementationParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final position = Position.fromJson(json['position']);
-    final workDoneToken = json['workDoneToken'] == null
+  static ImplementationParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final positionJson = json['position'];
+    final position = Position.fromJson(positionJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
-    final partialResultToken = json['partialResultToken'] == null
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
+    final partialResultTokenJson = json['partialResultToken'];
+    final partialResultToken = partialResultTokenJson == null
         ? null
-        : (json['partialResultToken'] is int
-            ? Either2<int, String>.t1(json['partialResultToken'])
-            : (json['partialResultToken'] is String
-                ? Either2<int, String>.t2(json['partialResultToken'])
-                : (throw '''${json['partialResultToken']} was not one of (int, String)''')));
+        : (partialResultTokenJson is int
+            ? Either2<int, String>.t1(partialResultTokenJson)
+            : (partialResultTokenJson is String
+                ? Either2<int, String>.t2(partialResultTokenJson)
+                : (throw '''$partialResultTokenJson was not one of (int, String)''')));
     return ImplementationParams(
         textDocument: textDocument,
         position: position,
@@ -15982,8 +16613,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     __result['position'] = position.toJson();
     if (workDoneToken != null) {
@@ -15996,18 +16627,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -16020,11 +16652,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['position'] == null) {
+        final position = obj['position'];
+        if (position == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Position.canParse(obj['position'], reporter))) {
+        if (!(Position.canParse(position, reporter))) {
           reporter.reportError('must be of type Position');
           return false;
         }
@@ -16033,9 +16666,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -16044,9 +16677,9 @@
       }
       reporter.push('partialResultToken');
       try {
-        if (obj['partialResultToken'] != null &&
-            !((obj['partialResultToken'] is int ||
-                obj['partialResultToken'] is String))) {
+        final partialResultToken = obj['partialResultToken'];
+        if (partialResultToken != null &&
+            !((partialResultToken is int || partialResultToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -16099,13 +16732,15 @@
 
   ImplementationRegistrationOptions(
       {this.documentSelector, this.workDoneProgress, this.id});
-  static ImplementationRegistrationOptions fromJson(Map<String, dynamic> json) {
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final workDoneProgress = json['workDoneProgress'];
-    final id = json['id'];
+  static ImplementationRegistrationOptions fromJson(Map<String, Object?> json) {
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
+    final idJson = json['id'];
+    final id = idJson as String?;
     return ImplementationRegistrationOptions(
         documentSelector: documentSelector,
         workDoneProgress: workDoneProgress,
@@ -16121,8 +16756,8 @@
   final String? id;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['documentSelector'] = documentSelector;
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
@@ -16134,16 +16769,17 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentSelector');
       try {
         if (!obj.containsKey('documentSelector')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -16153,8 +16789,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -16163,7 +16799,8 @@
       }
       reporter.push('id');
       try {
-        if (obj['id'] != null && !(obj['id'] is String)) {
+        final id = obj['id'];
+        if (id != null && !(id is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -16218,31 +16855,41 @@
       this.trace,
       this.workspaceFolders,
       this.workDoneToken});
-  static InitializeParams fromJson(Map<String, dynamic> json) {
-    final processId = json['processId'];
-    final clientInfo = json['clientInfo'] != null
-        ? InitializeParamsClientInfo.fromJson(json['clientInfo'])
+  static InitializeParams fromJson(Map<String, Object?> json) {
+    final processIdJson = json['processId'];
+    final processId = processIdJson as int?;
+    final clientInfoJson = json['clientInfo'];
+    final clientInfo = clientInfoJson != null
+        ? InitializeParamsClientInfo.fromJson(
+            clientInfoJson as Map<String, Object?>)
         : null;
-    final locale = json['locale'];
-    final rootPath = json['rootPath'];
-    final rootUri = json['rootUri'];
-    final initializationOptions = json['initializationOptions'];
-    final capabilities = ClientCapabilities.fromJson(json['capabilities']);
-    final trace = const {null, 'off', 'message', 'verbose'}
-            .contains(json['trace'])
-        ? json['trace']
-        : throw '''${json['trace']} was not one of (null, 'off', 'message', 'verbose')''';
-    final workspaceFolders = json['workspaceFolders']
-        ?.map((item) => item != null ? WorkspaceFolder.fromJson(item) : null)
-        ?.cast<WorkspaceFolder>()
-        ?.toList();
-    final workDoneToken = json['workDoneToken'] == null
+    final localeJson = json['locale'];
+    final locale = localeJson as String?;
+    final rootPathJson = json['rootPath'];
+    final rootPath = rootPathJson as String?;
+    final rootUriJson = json['rootUri'];
+    final rootUri = rootUriJson as String?;
+    final initializationOptionsJson = json['initializationOptions'];
+    final initializationOptions = initializationOptionsJson;
+    final capabilitiesJson = json['capabilities'];
+    final capabilities =
+        ClientCapabilities.fromJson(capabilitiesJson as Map<String, Object?>);
+    final traceJson = json['trace'];
+    final trace = const {null, 'off', 'message', 'verbose'}.contains(traceJson)
+        ? traceJson as String?
+        : throw '''$traceJson was not one of (null, 'off', 'message', 'verbose')''';
+    final workspaceFoldersJson = json['workspaceFolders'];
+    final workspaceFolders = (workspaceFoldersJson as List<Object?>?)
+        ?.map((item) => WorkspaceFolder.fromJson(item as Map<String, Object?>))
+        .toList();
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
     return InitializeParams(
         processId: processId,
         clientInfo: clientInfo,
@@ -16264,7 +16911,7 @@
   final InitializeParamsClientInfo? clientInfo;
 
   /// User provided initialization options.
-  final dynamic initializationOptions;
+  final Object? initializationOptions;
 
   /// The locale the client is currently showing the user interface in. This
   /// must not necessarily be the locale of the operating system.
@@ -16302,8 +16949,8 @@
   ///  @since 3.6.0
   final List<WorkspaceFolder>? workspaceFolders;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['processId'] = processId;
     if (clientInfo != null) {
       __result['clientInfo'] = clientInfo?.toJson();
@@ -16333,14 +16980,15 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('processId');
       try {
         if (!obj.containsKey('processId')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['processId'] != null && !(obj['processId'] is int)) {
+        final processId = obj['processId'];
+        if (processId != null && !(processId is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -16349,9 +16997,9 @@
       }
       reporter.push('clientInfo');
       try {
-        if (obj['clientInfo'] != null &&
-            !(InitializeParamsClientInfo.canParse(
-                obj['clientInfo'], reporter))) {
+        final clientInfo = obj['clientInfo'];
+        if (clientInfo != null &&
+            !(InitializeParamsClientInfo.canParse(clientInfo, reporter))) {
           reporter.reportError('must be of type InitializeParamsClientInfo');
           return false;
         }
@@ -16360,7 +17008,8 @@
       }
       reporter.push('locale');
       try {
-        if (obj['locale'] != null && !(obj['locale'] is String)) {
+        final locale = obj['locale'];
+        if (locale != null && !(locale is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -16369,7 +17018,8 @@
       }
       reporter.push('rootPath');
       try {
-        if (obj['rootPath'] != null && !(obj['rootPath'] is String)) {
+        final rootPath = obj['rootPath'];
+        if (rootPath != null && !(rootPath is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -16382,7 +17032,8 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['rootUri'] != null && !(obj['rootUri'] is String)) {
+        final rootUri = obj['rootUri'];
+        if (rootUri != null && !(rootUri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -16395,11 +17046,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['capabilities'] == null) {
+        final capabilities = obj['capabilities'];
+        if (capabilities == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(ClientCapabilities.canParse(obj['capabilities'], reporter))) {
+        if (!(ClientCapabilities.canParse(capabilities, reporter))) {
           reporter.reportError('must be of type ClientCapabilities');
           return false;
         }
@@ -16408,10 +17060,9 @@
       }
       reporter.push('trace');
       try {
-        if (obj['trace'] != null &&
-            !((obj['trace'] == 'off' ||
-                obj['trace'] == 'message' ||
-                obj['trace'] == 'verbose'))) {
+        final trace = obj['trace'];
+        if (trace != null &&
+            !((trace == 'off' || trace == 'message' || trace == 'verbose'))) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -16420,9 +17071,10 @@
       }
       reporter.push('workspaceFolders');
       try {
-        if (obj['workspaceFolders'] != null &&
-            !((obj['workspaceFolders'] is List &&
-                (obj['workspaceFolders'].every(
+        final workspaceFolders = obj['workspaceFolders'];
+        if (workspaceFolders != null &&
+            !((workspaceFolders is List &&
+                (workspaceFolders.every(
                     (item) => WorkspaceFolder.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<WorkspaceFolder>');
           return false;
@@ -16432,9 +17084,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -16492,9 +17144,11 @@
       InitializeParamsClientInfo.canParse, InitializeParamsClientInfo.fromJson);
 
   InitializeParamsClientInfo({required this.name, this.version});
-  static InitializeParamsClientInfo fromJson(Map<String, dynamic> json) {
-    final name = json['name'];
-    final version = json['version'];
+  static InitializeParamsClientInfo fromJson(Map<String, Object?> json) {
+    final nameJson = json['name'];
+    final name = nameJson as String;
+    final versionJson = json['version'];
+    final version = versionJson as String?;
     return InitializeParamsClientInfo(name: name, version: version);
   }
 
@@ -16504,8 +17158,8 @@
   /// The client's version as defined by the client.
   final String? version;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['name'] = name;
     if (version != null) {
       __result['version'] = version;
@@ -16514,18 +17168,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('name');
       try {
         if (!obj.containsKey('name')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['name'] == null) {
+        final name = obj['name'];
+        if (name == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['name'] is String)) {
+        if (!(name is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -16534,7 +17189,8 @@
       }
       reporter.push('version');
       try {
-        if (obj['version'] != null && !(obj['version'] is String)) {
+        final version = obj['version'];
+        if (version != null && !(version is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -16574,10 +17230,14 @@
       LspJsonHandler(InitializeResult.canParse, InitializeResult.fromJson);
 
   InitializeResult({required this.capabilities, this.serverInfo});
-  static InitializeResult fromJson(Map<String, dynamic> json) {
-    final capabilities = ServerCapabilities.fromJson(json['capabilities']);
-    final serverInfo = json['serverInfo'] != null
-        ? InitializeResultServerInfo.fromJson(json['serverInfo'])
+  static InitializeResult fromJson(Map<String, Object?> json) {
+    final capabilitiesJson = json['capabilities'];
+    final capabilities =
+        ServerCapabilities.fromJson(capabilitiesJson as Map<String, Object?>);
+    final serverInfoJson = json['serverInfo'];
+    final serverInfo = serverInfoJson != null
+        ? InitializeResultServerInfo.fromJson(
+            serverInfoJson as Map<String, Object?>)
         : null;
     return InitializeResult(capabilities: capabilities, serverInfo: serverInfo);
   }
@@ -16589,8 +17249,8 @@
   ///  @since 3.15.0
   final InitializeResultServerInfo? serverInfo;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['capabilities'] = capabilities.toJson();
     if (serverInfo != null) {
       __result['serverInfo'] = serverInfo?.toJson();
@@ -16599,18 +17259,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('capabilities');
       try {
         if (!obj.containsKey('capabilities')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['capabilities'] == null) {
+        final capabilities = obj['capabilities'];
+        if (capabilities == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(ServerCapabilities.canParse(obj['capabilities'], reporter))) {
+        if (!(ServerCapabilities.canParse(capabilities, reporter))) {
           reporter.reportError('must be of type ServerCapabilities');
           return false;
         }
@@ -16619,9 +17280,9 @@
       }
       reporter.push('serverInfo');
       try {
-        if (obj['serverInfo'] != null &&
-            !(InitializeResultServerInfo.canParse(
-                obj['serverInfo'], reporter))) {
+        final serverInfo = obj['serverInfo'];
+        if (serverInfo != null &&
+            !(InitializeResultServerInfo.canParse(serverInfo, reporter))) {
           reporter.reportError('must be of type InitializeResultServerInfo');
           return false;
         }
@@ -16662,9 +17323,11 @@
       InitializeResultServerInfo.canParse, InitializeResultServerInfo.fromJson);
 
   InitializeResultServerInfo({required this.name, this.version});
-  static InitializeResultServerInfo fromJson(Map<String, dynamic> json) {
-    final name = json['name'];
-    final version = json['version'];
+  static InitializeResultServerInfo fromJson(Map<String, Object?> json) {
+    final nameJson = json['name'];
+    final name = nameJson as String;
+    final versionJson = json['version'];
+    final version = versionJson as String?;
     return InitializeResultServerInfo(name: name, version: version);
   }
 
@@ -16674,8 +17337,8 @@
   /// The server's version as defined by the server.
   final String? version;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['name'] = name;
     if (version != null) {
       __result['version'] = version;
@@ -16684,18 +17347,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('name');
       try {
         if (!obj.containsKey('name')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['name'] == null) {
+        final name = obj['name'];
+        if (name == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['name'] is String)) {
+        if (!(name is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -16704,7 +17368,8 @@
       }
       reporter.push('version');
       try {
-        if (obj['version'] != null && !(obj['version'] is String)) {
+        final version = obj['version'];
+        if (version != null && !(version is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -16743,17 +17408,17 @@
   static const jsonHandler =
       LspJsonHandler(InitializedParams.canParse, InitializedParams.fromJson);
 
-  static InitializedParams fromJson(Map<String, dynamic> json) {
+  static InitializedParams fromJson(Map<String, Object?> json) {
     return InitializedParams();
   }
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       return true;
     } else {
       reporter.reportError('must be of type InitializedParams');
@@ -16787,10 +17452,13 @@
 
   InsertReplaceEdit(
       {required this.newText, required this.insert, required this.replace});
-  static InsertReplaceEdit fromJson(Map<String, dynamic> json) {
-    final newText = json['newText'];
-    final insert = Range.fromJson(json['insert']);
-    final replace = Range.fromJson(json['replace']);
+  static InsertReplaceEdit fromJson(Map<String, Object?> json) {
+    final newTextJson = json['newText'];
+    final newText = newTextJson as String;
+    final insertJson = json['insert'];
+    final insert = Range.fromJson(insertJson as Map<String, Object?>);
+    final replaceJson = json['replace'];
+    final replace = Range.fromJson(replaceJson as Map<String, Object?>);
     return InsertReplaceEdit(
         newText: newText, insert: insert, replace: replace);
   }
@@ -16804,8 +17472,8 @@
   /// The range if the replace is requested.
   final Range replace;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['newText'] = newText;
     __result['insert'] = insert.toJson();
     __result['replace'] = replace.toJson();
@@ -16813,18 +17481,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('newText');
       try {
         if (!obj.containsKey('newText')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['newText'] == null) {
+        final newText = obj['newText'];
+        if (newText == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['newText'] is String)) {
+        if (!(newText is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -16837,11 +17506,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['insert'] == null) {
+        final insert = obj['insert'];
+        if (insert == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['insert'], reporter))) {
+        if (!(Range.canParse(insert, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -16854,11 +17524,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['replace'] == null) {
+        final replace = obj['replace'];
+        if (replace == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['replace'], reporter))) {
+        if (!(Range.canParse(replace, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -16979,8 +17650,9 @@
 
   LinkedEditingRangeClientCapabilities({this.dynamicRegistration});
   static LinkedEditingRangeClientCapabilities fromJson(
-      Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
+      Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
     return LinkedEditingRangeClientCapabilities(
         dynamicRegistration: dynamicRegistration);
   }
@@ -16991,8 +17663,8 @@
   /// capability as well.
   final bool? dynamicRegistration;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -17000,11 +17672,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -17044,19 +17716,20 @@
       LinkedEditingRangeOptions.canParse, LinkedEditingRangeOptions.fromJson);
 
   LinkedEditingRangeOptions({this.workDoneProgress});
-  static LinkedEditingRangeOptions fromJson(Map<String, dynamic> json) {
+  static LinkedEditingRangeOptions fromJson(Map<String, Object?> json) {
     if (LinkedEditingRangeRegistrationOptions.canParse(
         json, nullLspJsonReporter)) {
       return LinkedEditingRangeRegistrationOptions.fromJson(json);
     }
-    final workDoneProgress = json['workDoneProgress'];
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return LinkedEditingRangeOptions(workDoneProgress: workDoneProgress);
   }
 
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
     }
@@ -17064,11 +17737,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -17109,16 +17782,20 @@
 
   LinkedEditingRangeParams(
       {required this.textDocument, required this.position, this.workDoneToken});
-  static LinkedEditingRangeParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final position = Position.fromJson(json['position']);
-    final workDoneToken = json['workDoneToken'] == null
+  static LinkedEditingRangeParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final positionJson = json['position'];
+    final position = Position.fromJson(positionJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
     return LinkedEditingRangeParams(
         textDocument: textDocument,
         position: position,
@@ -17134,8 +17811,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     __result['position'] = position.toJson();
     if (workDoneToken != null) {
@@ -17145,18 +17822,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -17169,11 +17847,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['position'] == null) {
+        final position = obj['position'];
+        if (position == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Position.canParse(obj['position'], reporter))) {
+        if (!(Position.canParse(position, reporter))) {
           reporter.reportError('must be of type Position');
           return false;
         }
@@ -17182,9 +17861,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -17236,13 +17915,15 @@
   LinkedEditingRangeRegistrationOptions(
       {this.documentSelector, this.workDoneProgress, this.id});
   static LinkedEditingRangeRegistrationOptions fromJson(
-      Map<String, dynamic> json) {
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final workDoneProgress = json['workDoneProgress'];
-    final id = json['id'];
+      Map<String, Object?> json) {
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
+    final idJson = json['id'];
+    final id = idJson as String?;
     return LinkedEditingRangeRegistrationOptions(
         documentSelector: documentSelector,
         workDoneProgress: workDoneProgress,
@@ -17258,8 +17939,8 @@
   final String? id;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['documentSelector'] = documentSelector;
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
@@ -17271,16 +17952,17 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentSelector');
       try {
         if (!obj.containsKey('documentSelector')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -17290,8 +17972,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -17300,7 +17982,8 @@
       }
       reporter.push('id');
       try {
-        if (obj['id'] != null && !(obj['id'] is String)) {
+        final id = obj['id'];
+        if (id != null && !(id is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -17346,12 +18029,13 @@
       LinkedEditingRanges.canParse, LinkedEditingRanges.fromJson);
 
   LinkedEditingRanges({required this.ranges, this.wordPattern});
-  static LinkedEditingRanges fromJson(Map<String, dynamic> json) {
-    final ranges = json['ranges']
-        ?.map((item) => Range.fromJson(item))
-        ?.cast<Range>()
-        ?.toList();
-    final wordPattern = json['wordPattern'];
+  static LinkedEditingRanges fromJson(Map<String, Object?> json) {
+    final rangesJson = json['ranges'];
+    final ranges = (rangesJson as List<Object?>)
+        .map((item) => Range.fromJson(item as Map<String, Object?>))
+        .toList();
+    final wordPatternJson = json['wordPattern'];
+    final wordPattern = wordPatternJson as String?;
     return LinkedEditingRanges(ranges: ranges, wordPattern: wordPattern);
   }
 
@@ -17365,8 +18049,8 @@
   /// configuration's word pattern will be used.
   final String? wordPattern;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['ranges'] = ranges.map((item) => item.toJson()).toList();
     if (wordPattern != null) {
       __result['wordPattern'] = wordPattern;
@@ -17375,19 +18059,20 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('ranges');
       try {
         if (!obj.containsKey('ranges')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['ranges'] == null) {
+        final ranges = obj['ranges'];
+        if (ranges == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['ranges'] is List &&
-            (obj['ranges'].every((item) => Range.canParse(item, reporter)))))) {
+        if (!((ranges is List &&
+            (ranges.every((item) => Range.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<Range>');
           return false;
         }
@@ -17396,7 +18081,8 @@
       }
       reporter.push('wordPattern');
       try {
-        if (obj['wordPattern'] != null && !(obj['wordPattern'] is String)) {
+        final wordPattern = obj['wordPattern'];
+        if (wordPattern != null && !(wordPattern is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -17438,35 +18124,38 @@
       LspJsonHandler(Location.canParse, Location.fromJson);
 
   Location({required this.uri, required this.range});
-  static Location fromJson(Map<String, dynamic> json) {
-    final uri = json['uri'];
-    final range = Range.fromJson(json['range']);
+  static Location fromJson(Map<String, Object?> json) {
+    final uriJson = json['uri'];
+    final uri = uriJson as String;
+    final rangeJson = json['range'];
+    final range = Range.fromJson(rangeJson as Map<String, Object?>);
     return Location(uri: uri, range: range);
   }
 
   final Range range;
   final String uri;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['uri'] = uri;
     __result['range'] = range.toJson();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('uri');
       try {
         if (!obj.containsKey('uri')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['uri'] == null) {
+        final uri = obj['uri'];
+        if (uri == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['uri'] is String)) {
+        if (!(uri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -17479,11 +18168,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['range'] == null) {
+        final range = obj['range'];
+        if (range == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['range'], reporter))) {
+        if (!(Range.canParse(range, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -17526,13 +18216,18 @@
       required this.targetUri,
       required this.targetRange,
       required this.targetSelectionRange});
-  static LocationLink fromJson(Map<String, dynamic> json) {
-    final originSelectionRange = json['originSelectionRange'] != null
-        ? Range.fromJson(json['originSelectionRange'])
+  static LocationLink fromJson(Map<String, Object?> json) {
+    final originSelectionRangeJson = json['originSelectionRange'];
+    final originSelectionRange = originSelectionRangeJson != null
+        ? Range.fromJson(originSelectionRangeJson as Map<String, Object?>)
         : null;
-    final targetUri = json['targetUri'];
-    final targetRange = Range.fromJson(json['targetRange']);
-    final targetSelectionRange = Range.fromJson(json['targetSelectionRange']);
+    final targetUriJson = json['targetUri'];
+    final targetUri = targetUriJson as String;
+    final targetRangeJson = json['targetRange'];
+    final targetRange = Range.fromJson(targetRangeJson as Map<String, Object?>);
+    final targetSelectionRangeJson = json['targetSelectionRange'];
+    final targetSelectionRange =
+        Range.fromJson(targetSelectionRangeJson as Map<String, Object?>);
     return LocationLink(
         originSelectionRange: originSelectionRange,
         targetUri: targetUri,
@@ -17560,8 +18255,8 @@
   /// The target resource identifier of this link.
   final String targetUri;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (originSelectionRange != null) {
       __result['originSelectionRange'] = originSelectionRange?.toJson();
     }
@@ -17572,11 +18267,12 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('originSelectionRange');
       try {
-        if (obj['originSelectionRange'] != null &&
-            !(Range.canParse(obj['originSelectionRange'], reporter))) {
+        final originSelectionRange = obj['originSelectionRange'];
+        if (originSelectionRange != null &&
+            !(Range.canParse(originSelectionRange, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -17589,11 +18285,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['targetUri'] == null) {
+        final targetUri = obj['targetUri'];
+        if (targetUri == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['targetUri'] is String)) {
+        if (!(targetUri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -17606,11 +18303,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['targetRange'] == null) {
+        final targetRange = obj['targetRange'];
+        if (targetRange == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['targetRange'], reporter))) {
+        if (!(Range.canParse(targetRange, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -17623,11 +18321,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['targetSelectionRange'] == null) {
+        final targetSelectionRange = obj['targetSelectionRange'];
+        if (targetSelectionRange == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['targetSelectionRange'], reporter))) {
+        if (!(Range.canParse(targetSelectionRange, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -17672,9 +18371,11 @@
       LspJsonHandler(LogMessageParams.canParse, LogMessageParams.fromJson);
 
   LogMessageParams({required this.type, required this.message});
-  static LogMessageParams fromJson(Map<String, dynamic> json) {
-    final type = MessageType.fromJson(json['type']);
-    final message = json['message'];
+  static LogMessageParams fromJson(Map<String, Object?> json) {
+    final typeJson = json['type'];
+    final type = MessageType.fromJson(typeJson as int);
+    final messageJson = json['message'];
+    final message = messageJson as String;
     return LogMessageParams(type: type, message: message);
   }
 
@@ -17684,26 +18385,27 @@
   /// The message type.
   final MessageType type;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['type'] = type.toJson();
     __result['message'] = message;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('type');
       try {
         if (!obj.containsKey('type')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['type'] == null) {
+        final type = obj['type'];
+        if (type == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(MessageType.canParse(obj['type'], reporter))) {
+        if (!(MessageType.canParse(type, reporter))) {
           reporter.reportError('must be of type MessageType');
           return false;
         }
@@ -17716,11 +18418,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['message'] == null) {
+        final message = obj['message'];
+        if (message == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['message'] is String)) {
+        if (!(message is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -17759,9 +18462,11 @@
       LspJsonHandler(LogTraceParams.canParse, LogTraceParams.fromJson);
 
   LogTraceParams({required this.message, this.verbose});
-  static LogTraceParams fromJson(Map<String, dynamic> json) {
-    final message = json['message'];
-    final verbose = json['verbose'];
+  static LogTraceParams fromJson(Map<String, Object?> json) {
+    final messageJson = json['message'];
+    final message = messageJson as String;
+    final verboseJson = json['verbose'];
+    final verbose = verboseJson as String?;
     return LogTraceParams(message: message, verbose: verbose);
   }
 
@@ -17772,8 +18477,8 @@
   /// is set to `'verbose'`
   final String? verbose;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['message'] = message;
     if (verbose != null) {
       __result['verbose'] = verbose;
@@ -17782,18 +18487,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('message');
       try {
         if (!obj.containsKey('message')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['message'] == null) {
+        final message = obj['message'];
+        if (message == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['message'] is String)) {
+        if (!(message is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -17802,7 +18508,8 @@
       }
       reporter.push('verbose');
       try {
-        if (obj['verbose'] != null && !(obj['verbose'] is String)) {
+        final verbose = obj['verbose'];
+        if (verbose != null && !(verbose is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -17843,9 +18550,11 @@
       MarkdownClientCapabilities.canParse, MarkdownClientCapabilities.fromJson);
 
   MarkdownClientCapabilities({required this.parser, this.version});
-  static MarkdownClientCapabilities fromJson(Map<String, dynamic> json) {
-    final parser = json['parser'];
-    final version = json['version'];
+  static MarkdownClientCapabilities fromJson(Map<String, Object?> json) {
+    final parserJson = json['parser'];
+    final parser = parserJson as String;
+    final versionJson = json['version'];
+    final version = versionJson as String?;
     return MarkdownClientCapabilities(parser: parser, version: version);
   }
 
@@ -17855,8 +18564,8 @@
   /// The version of the parser.
   final String? version;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['parser'] = parser;
     if (version != null) {
       __result['version'] = version;
@@ -17865,18 +18574,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('parser');
       try {
         if (!obj.containsKey('parser')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['parser'] == null) {
+        final parser = obj['parser'];
+        if (parser == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['parser'] is String)) {
+        if (!(parser is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -17885,7 +18595,8 @@
       }
       reporter.push('version');
       try {
-        if (obj['version'] != null && !(obj['version'] is String)) {
+        final version = obj['version'];
+        if (version != null && !(version is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -17946,9 +18657,11 @@
       LspJsonHandler(MarkupContent.canParse, MarkupContent.fromJson);
 
   MarkupContent({required this.kind, required this.value});
-  static MarkupContent fromJson(Map<String, dynamic> json) {
-    final kind = MarkupKind.fromJson(json['kind']);
-    final value = json['value'];
+  static MarkupContent fromJson(Map<String, Object?> json) {
+    final kindJson = json['kind'];
+    final kind = MarkupKind.fromJson(kindJson as String);
+    final valueJson = json['value'];
+    final value = valueJson as String;
     return MarkupContent(kind: kind, value: value);
   }
 
@@ -17958,26 +18671,27 @@
   /// The content itself
   final String value;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['kind'] = kind.toJson();
     __result['value'] = value;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('kind');
       try {
         if (!obj.containsKey('kind')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['kind'] == null) {
+        final kind = obj['kind'];
+        if (kind == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(MarkupKind.canParse(obj['kind'], reporter))) {
+        if (!(MarkupKind.canParse(kind, reporter))) {
           reporter.reportError('must be of type MarkupKind');
           return false;
         }
@@ -17990,11 +18704,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['value'] == null) {
+        final value = obj['value'];
+        if (value == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['value'] is String)) {
+        if (!(value is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -18069,7 +18784,7 @@
   static const jsonHandler = LspJsonHandler(Message.canParse, Message.fromJson);
 
   Message({required this.jsonrpc});
-  static Message fromJson(Map<String, dynamic> json) {
+  static Message fromJson(Map<String, Object?> json) {
     if (RequestMessage.canParse(json, nullLspJsonReporter)) {
       return RequestMessage.fromJson(json);
     }
@@ -18079,31 +18794,33 @@
     if (NotificationMessage.canParse(json, nullLspJsonReporter)) {
       return NotificationMessage.fromJson(json);
     }
-    final jsonrpc = json['jsonrpc'];
+    final jsonrpcJson = json['jsonrpc'];
+    final jsonrpc = jsonrpcJson as String;
     return Message(jsonrpc: jsonrpc);
   }
 
   final String jsonrpc;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['jsonrpc'] = jsonrpc;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('jsonrpc');
       try {
         if (!obj.containsKey('jsonrpc')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['jsonrpc'] == null) {
+        final jsonrpc = obj['jsonrpc'];
+        if (jsonrpc == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['jsonrpc'] is String)) {
+        if (!(jsonrpc is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -18141,33 +18858,35 @@
       LspJsonHandler(MessageActionItem.canParse, MessageActionItem.fromJson);
 
   MessageActionItem({required this.title});
-  static MessageActionItem fromJson(Map<String, dynamic> json) {
-    final title = json['title'];
+  static MessageActionItem fromJson(Map<String, Object?> json) {
+    final titleJson = json['title'];
+    final title = titleJson as String;
     return MessageActionItem(title: title);
   }
 
   /// A short title like 'Retry', 'Open Log' etc.
   final String title;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['title'] = title;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('title');
       try {
         if (!obj.containsKey('title')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['title'] == null) {
+        final title = obj['title'];
+        if (title == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['title'] is String)) {
+        if (!(title is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -18515,12 +19234,16 @@
       required this.identifier,
       required this.unique,
       this.kind});
-  static Moniker fromJson(Map<String, dynamic> json) {
-    final scheme = json['scheme'];
-    final identifier = json['identifier'];
-    final unique = UniquenessLevel.fromJson(json['unique']);
+  static Moniker fromJson(Map<String, Object?> json) {
+    final schemeJson = json['scheme'];
+    final scheme = schemeJson as String;
+    final identifierJson = json['identifier'];
+    final identifier = identifierJson as String;
+    final uniqueJson = json['unique'];
+    final unique = UniquenessLevel.fromJson(uniqueJson as String);
+    final kindJson = json['kind'];
     final kind =
-        json['kind'] != null ? MonikerKind.fromJson(json['kind']) : null;
+        kindJson != null ? MonikerKind.fromJson(kindJson as String) : null;
     return Moniker(
         scheme: scheme, identifier: identifier, unique: unique, kind: kind);
   }
@@ -18538,8 +19261,8 @@
   /// The scope in which the moniker is unique
   final UniquenessLevel unique;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['scheme'] = scheme;
     __result['identifier'] = identifier;
     __result['unique'] = unique.toJson();
@@ -18550,18 +19273,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('scheme');
       try {
         if (!obj.containsKey('scheme')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['scheme'] == null) {
+        final scheme = obj['scheme'];
+        if (scheme == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['scheme'] is String)) {
+        if (!(scheme is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -18574,11 +19298,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['identifier'] == null) {
+        final identifier = obj['identifier'];
+        if (identifier == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['identifier'] is String)) {
+        if (!(identifier is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -18591,11 +19316,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['unique'] == null) {
+        final unique = obj['unique'];
+        if (unique == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(UniquenessLevel.canParse(obj['unique'], reporter))) {
+        if (!(UniquenessLevel.canParse(unique, reporter))) {
           reporter.reportError('must be of type UniquenessLevel');
           return false;
         }
@@ -18604,8 +19330,8 @@
       }
       reporter.push('kind');
       try {
-        if (obj['kind'] != null &&
-            !(MonikerKind.canParse(obj['kind'], reporter))) {
+        final kind = obj['kind'];
+        if (kind != null && !(MonikerKind.canParse(kind, reporter))) {
           reporter.reportError('must be of type MonikerKind');
           return false;
         }
@@ -18650,8 +19376,9 @@
       MonikerClientCapabilities.canParse, MonikerClientCapabilities.fromJson);
 
   MonikerClientCapabilities({this.dynamicRegistration});
-  static MonikerClientCapabilities fromJson(Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
+  static MonikerClientCapabilities fromJson(Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
     return MonikerClientCapabilities(dynamicRegistration: dynamicRegistration);
   }
 
@@ -18661,8 +19388,8 @@
   /// capability as well.
   final bool? dynamicRegistration;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -18670,11 +19397,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -18745,18 +19472,19 @@
       LspJsonHandler(MonikerOptions.canParse, MonikerOptions.fromJson);
 
   MonikerOptions({this.workDoneProgress});
-  static MonikerOptions fromJson(Map<String, dynamic> json) {
+  static MonikerOptions fromJson(Map<String, Object?> json) {
     if (MonikerRegistrationOptions.canParse(json, nullLspJsonReporter)) {
       return MonikerRegistrationOptions.fromJson(json);
     }
-    final workDoneProgress = json['workDoneProgress'];
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return MonikerOptions(workDoneProgress: workDoneProgress);
   }
 
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
     }
@@ -18764,11 +19492,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -18815,23 +19543,28 @@
       required this.position,
       this.workDoneToken,
       this.partialResultToken});
-  static MonikerParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final position = Position.fromJson(json['position']);
-    final workDoneToken = json['workDoneToken'] == null
+  static MonikerParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final positionJson = json['position'];
+    final position = Position.fromJson(positionJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
-    final partialResultToken = json['partialResultToken'] == null
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
+    final partialResultTokenJson = json['partialResultToken'];
+    final partialResultToken = partialResultTokenJson == null
         ? null
-        : (json['partialResultToken'] is int
-            ? Either2<int, String>.t1(json['partialResultToken'])
-            : (json['partialResultToken'] is String
-                ? Either2<int, String>.t2(json['partialResultToken'])
-                : (throw '''${json['partialResultToken']} was not one of (int, String)''')));
+        : (partialResultTokenJson is int
+            ? Either2<int, String>.t1(partialResultTokenJson)
+            : (partialResultTokenJson is String
+                ? Either2<int, String>.t2(partialResultTokenJson)
+                : (throw '''$partialResultTokenJson was not one of (int, String)''')));
     return MonikerParams(
         textDocument: textDocument,
         position: position,
@@ -18852,8 +19585,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     __result['position'] = position.toJson();
     if (workDoneToken != null) {
@@ -18866,18 +19599,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -18890,11 +19624,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['position'] == null) {
+        final position = obj['position'];
+        if (position == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Position.canParse(obj['position'], reporter))) {
+        if (!(Position.canParse(position, reporter))) {
           reporter.reportError('must be of type Position');
           return false;
         }
@@ -18903,9 +19638,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -18914,9 +19649,9 @@
       }
       reporter.push('partialResultToken');
       try {
-        if (obj['partialResultToken'] != null &&
-            !((obj['partialResultToken'] is int ||
-                obj['partialResultToken'] is String))) {
+        final partialResultToken = obj['partialResultToken'];
+        if (partialResultToken != null &&
+            !((partialResultToken is int || partialResultToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -18962,12 +19697,13 @@
       MonikerRegistrationOptions.canParse, MonikerRegistrationOptions.fromJson);
 
   MonikerRegistrationOptions({this.documentSelector, this.workDoneProgress});
-  static MonikerRegistrationOptions fromJson(Map<String, dynamic> json) {
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final workDoneProgress = json['workDoneProgress'];
+  static MonikerRegistrationOptions fromJson(Map<String, Object?> json) {
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return MonikerRegistrationOptions(
         documentSelector: documentSelector, workDoneProgress: workDoneProgress);
   }
@@ -18977,8 +19713,8 @@
   final List<DocumentFilter>? documentSelector;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['documentSelector'] = documentSelector;
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
@@ -18987,16 +19723,17 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentSelector');
       try {
         if (!obj.containsKey('documentSelector')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -19006,8 +19743,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -19051,10 +19788,13 @@
 
   NotificationMessage(
       {required this.method, this.params, required this.jsonrpc});
-  static NotificationMessage fromJson(Map<String, dynamic> json) {
-    final method = Method.fromJson(json['method']);
-    final params = json['params'];
-    final jsonrpc = json['jsonrpc'];
+  static NotificationMessage fromJson(Map<String, Object?> json) {
+    final methodJson = json['method'];
+    final method = Method.fromJson(methodJson as String);
+    final paramsJson = json['params'];
+    final params = paramsJson;
+    final jsonrpcJson = json['jsonrpc'];
+    final jsonrpc = jsonrpcJson as String;
     return NotificationMessage(
         method: method, params: params, jsonrpc: jsonrpc);
   }
@@ -19065,10 +19805,10 @@
   final Method method;
 
   /// The notification's params.
-  final dynamic params;
+  final Object? params;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['method'] = method.toJson();
     if (params != null) {
       __result['params'] = params;
@@ -19078,18 +19818,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('method');
       try {
         if (!obj.containsKey('method')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['method'] == null) {
+        final method = obj['method'];
+        if (method == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Method.canParse(obj['method'], reporter))) {
+        if (!(Method.canParse(method, reporter))) {
           reporter.reportError('must be of type Method');
           return false;
         }
@@ -19102,11 +19843,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['jsonrpc'] == null) {
+        final jsonrpc = obj['jsonrpc'];
+        if (jsonrpc == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['jsonrpc'] is String)) {
+        if (!(jsonrpc is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -19153,9 +19895,11 @@
 
   OptionalVersionedTextDocumentIdentifier({this.version, required this.uri});
   static OptionalVersionedTextDocumentIdentifier fromJson(
-      Map<String, dynamic> json) {
-    final version = json['version'];
-    final uri = json['uri'];
+      Map<String, Object?> json) {
+    final versionJson = json['version'];
+    final version = versionJson as int?;
+    final uriJson = json['uri'];
+    final uri = uriJson as String;
     return OptionalVersionedTextDocumentIdentifier(version: version, uri: uri);
   }
 
@@ -19173,22 +19917,23 @@
   /// including undo/redo. The number doesn't need to be consecutive.
   final int? version;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['version'] = version;
     __result['uri'] = uri;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('version');
       try {
         if (!obj.containsKey('version')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['version'] != null && !(obj['version'] is int)) {
+        final version = obj['version'];
+        if (version != null && !(version is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -19201,11 +19946,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['uri'] == null) {
+        final uri = obj['uri'];
+        if (uri == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['uri'] is String)) {
+        if (!(uri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -19248,17 +19994,18 @@
       ParameterInformation.canParse, ParameterInformation.fromJson);
 
   ParameterInformation({required this.label, this.documentation});
-  static ParameterInformation fromJson(Map<String, dynamic> json) {
-    final label = json['label'];
-    final documentation = json['documentation'] == null
+  static ParameterInformation fromJson(Map<String, Object?> json) {
+    final labelJson = json['label'];
+    final label = labelJson as String;
+    final documentationJson = json['documentation'];
+    final documentation = documentationJson == null
         ? null
-        : (json['documentation'] is String
-            ? Either2<String, MarkupContent>.t1(json['documentation'])
-            : (MarkupContent.canParse(
-                    json['documentation'], nullLspJsonReporter)
-                ? Either2<String, MarkupContent>.t2(
-                    MarkupContent.fromJson(json['documentation']))
-                : (throw '''${json['documentation']} was not one of (String, MarkupContent)''')));
+        : (documentationJson is String
+            ? Either2<String, MarkupContent>.t1(documentationJson)
+            : (MarkupContent.canParse(documentationJson, nullLspJsonReporter)
+                ? Either2<String, MarkupContent>.t2(MarkupContent.fromJson(
+                    documentationJson as Map<String, Object?>))
+                : (throw '''$documentationJson was not one of (String, MarkupContent)''')));
     return ParameterInformation(label: label, documentation: documentation);
   }
 
@@ -19278,8 +20025,8 @@
   /// part in the `SignatureInformation.label`.
   final String label;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['label'] = label;
     if (documentation != null) {
       __result['documentation'] = documentation;
@@ -19288,18 +20035,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('label');
       try {
         if (!obj.containsKey('label')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['label'] == null) {
+        final label = obj['label'];
+        if (label == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['label'] is String)) {
+        if (!(label is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -19308,9 +20056,10 @@
       }
       reporter.push('documentation');
       try {
-        if (obj['documentation'] != null &&
-            !((obj['documentation'] is String ||
-                MarkupContent.canParse(obj['documentation'], reporter)))) {
+        final documentation = obj['documentation'];
+        if (documentation != null &&
+            !((documentation is String ||
+                MarkupContent.canParse(documentation, reporter)))) {
           reporter
               .reportError('must be of type Either2<String, MarkupContent>');
           return false;
@@ -19353,7 +20102,7 @@
       PartialResultParams.canParse, PartialResultParams.fromJson);
 
   PartialResultParams({this.partialResultToken});
-  static PartialResultParams fromJson(Map<String, dynamic> json) {
+  static PartialResultParams fromJson(Map<String, Object?> json) {
     if (WorkspaceSymbolParams.canParse(json, nullLspJsonReporter)) {
       return WorkspaceSymbolParams.fromJson(json);
     }
@@ -19420,13 +20169,14 @@
     if (MonikerParams.canParse(json, nullLspJsonReporter)) {
       return MonikerParams.fromJson(json);
     }
-    final partialResultToken = json['partialResultToken'] == null
+    final partialResultTokenJson = json['partialResultToken'];
+    final partialResultToken = partialResultTokenJson == null
         ? null
-        : (json['partialResultToken'] is int
-            ? Either2<int, String>.t1(json['partialResultToken'])
-            : (json['partialResultToken'] is String
-                ? Either2<int, String>.t2(json['partialResultToken'])
-                : (throw '''${json['partialResultToken']} was not one of (int, String)''')));
+        : (partialResultTokenJson is int
+            ? Either2<int, String>.t1(partialResultTokenJson)
+            : (partialResultTokenJson is String
+                ? Either2<int, String>.t2(partialResultTokenJson)
+                : (throw '''$partialResultTokenJson was not one of (int, String)''')));
     return PartialResultParams(partialResultToken: partialResultToken);
   }
 
@@ -19434,8 +20184,8 @@
   /// streaming) to the client.
   final Either2<int, String>? partialResultToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (partialResultToken != null) {
       __result['partialResultToken'] = partialResultToken;
     }
@@ -19443,12 +20193,12 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('partialResultToken');
       try {
-        if (obj['partialResultToken'] != null &&
-            !((obj['partialResultToken'] is int ||
-                obj['partialResultToken'] is String))) {
+        final partialResultToken = obj['partialResultToken'];
+        if (partialResultToken != null &&
+            !((partialResultToken is int || partialResultToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -19487,9 +20237,11 @@
       LspJsonHandler(Position.canParse, Position.fromJson);
 
   Position({required this.line, required this.character});
-  static Position fromJson(Map<String, dynamic> json) {
-    final line = json['line'];
-    final character = json['character'];
+  static Position fromJson(Map<String, Object?> json) {
+    final lineJson = json['line'];
+    final line = lineJson as int;
+    final characterJson = json['character'];
+    final character = characterJson as int;
     return Position(line: line, character: character);
   }
 
@@ -19504,26 +20256,27 @@
   /// Line position in a document (zero-based).
   final int line;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['line'] = line;
     __result['character'] = character;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('line');
       try {
         if (!obj.containsKey('line')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['line'] == null) {
+        final line = obj['line'];
+        if (line == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['line'] is int)) {
+        if (!(line is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -19536,11 +20289,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['character'] == null) {
+        final character = obj['character'];
+        if (character == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['character'] is int)) {
+        if (!(character is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -19579,9 +20333,12 @@
       PrepareRenameParams.canParse, PrepareRenameParams.fromJson);
 
   PrepareRenameParams({required this.textDocument, required this.position});
-  static PrepareRenameParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final position = Position.fromJson(json['position']);
+  static PrepareRenameParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final positionJson = json['position'];
+    final position = Position.fromJson(positionJson as Map<String, Object?>);
     return PrepareRenameParams(textDocument: textDocument, position: position);
   }
 
@@ -19591,26 +20348,27 @@
   /// The text document.
   final TextDocumentIdentifier textDocument;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     __result['position'] = position.toJson();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -19623,11 +20381,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['position'] == null) {
+        final position = obj['position'];
+        if (position == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Position.canParse(obj['position'], reporter))) {
+        if (!(Position.canParse(position, reporter))) {
           reporter.reportError('must be of type Position');
           return false;
         }
@@ -19695,13 +20454,15 @@
       LspJsonHandler(ProgressParams.canParse, ProgressParams.fromJson);
 
   ProgressParams({required this.token, this.value});
-  static ProgressParams<T> fromJson<T>(Map<String, dynamic> json) {
-    final token = json['token'] is int
-        ? Either2<int, String>.t1(json['token'])
-        : (json['token'] is String
-            ? Either2<int, String>.t2(json['token'])
-            : (throw '''${json['token']} was not one of (int, String)'''));
-    final value = json['value'];
+  static ProgressParams<T> fromJson<T>(Map<String, Object?> json) {
+    final tokenJson = json['token'];
+    final token = tokenJson is int
+        ? Either2<int, String>.t1(tokenJson)
+        : (tokenJson is String
+            ? Either2<int, String>.t2(tokenJson)
+            : (throw '''$tokenJson was not one of (int, String)'''));
+    final valueJson = json['value'];
+    final value = valueJson;
     return ProgressParams<T>(token: token, value: value);
   }
 
@@ -19709,28 +20470,29 @@
   final Either2<int, String> token;
 
   /// The progress data.
-  final dynamic value;
+  final Object? value;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['token'] = token;
     __result['value'] = value;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('token');
       try {
         if (!obj.containsKey('token')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['token'] == null) {
+        final token = obj['token'];
+        if (token == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['token'] is int || obj['token'] is String))) {
+        if (!((token is int || token is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -19776,15 +20538,20 @@
       this.codeDescriptionSupport,
       this.dataSupport});
   static PublishDiagnosticsClientCapabilities fromJson(
-      Map<String, dynamic> json) {
-    final relatedInformation = json['relatedInformation'];
-    final tagSupport = json['tagSupport'] != null
+      Map<String, Object?> json) {
+    final relatedInformationJson = json['relatedInformation'];
+    final relatedInformation = relatedInformationJson as bool?;
+    final tagSupportJson = json['tagSupport'];
+    final tagSupport = tagSupportJson != null
         ? PublishDiagnosticsClientCapabilitiesTagSupport.fromJson(
-            json['tagSupport'])
+            tagSupportJson as Map<String, Object?>)
         : null;
-    final versionSupport = json['versionSupport'];
-    final codeDescriptionSupport = json['codeDescriptionSupport'];
-    final dataSupport = json['dataSupport'];
+    final versionSupportJson = json['versionSupport'];
+    final versionSupport = versionSupportJson as bool?;
+    final codeDescriptionSupportJson = json['codeDescriptionSupport'];
+    final codeDescriptionSupport = codeDescriptionSupportJson as bool?;
+    final dataSupportJson = json['dataSupport'];
+    final dataSupport = dataSupportJson as bool?;
     return PublishDiagnosticsClientCapabilities(
         relatedInformation: relatedInformation,
         tagSupport: tagSupport,
@@ -19816,8 +20583,8 @@
   ///  @since 3.15.0
   final bool? versionSupport;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (relatedInformation != null) {
       __result['relatedInformation'] = relatedInformation;
     }
@@ -19837,11 +20604,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('relatedInformation');
       try {
-        if (obj['relatedInformation'] != null &&
-            !(obj['relatedInformation'] is bool)) {
+        final relatedInformation = obj['relatedInformation'];
+        if (relatedInformation != null && !(relatedInformation is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -19850,9 +20617,10 @@
       }
       reporter.push('tagSupport');
       try {
-        if (obj['tagSupport'] != null &&
+        final tagSupport = obj['tagSupport'];
+        if (tagSupport != null &&
             !(PublishDiagnosticsClientCapabilitiesTagSupport.canParse(
-                obj['tagSupport'], reporter))) {
+                tagSupport, reporter))) {
           reporter.reportError(
               'must be of type PublishDiagnosticsClientCapabilitiesTagSupport');
           return false;
@@ -19862,7 +20630,8 @@
       }
       reporter.push('versionSupport');
       try {
-        if (obj['versionSupport'] != null && !(obj['versionSupport'] is bool)) {
+        final versionSupport = obj['versionSupport'];
+        if (versionSupport != null && !(versionSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -19871,8 +20640,9 @@
       }
       reporter.push('codeDescriptionSupport');
       try {
-        if (obj['codeDescriptionSupport'] != null &&
-            !(obj['codeDescriptionSupport'] is bool)) {
+        final codeDescriptionSupport = obj['codeDescriptionSupport'];
+        if (codeDescriptionSupport != null &&
+            !(codeDescriptionSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -19881,7 +20651,8 @@
       }
       reporter.push('dataSupport');
       try {
-        if (obj['dataSupport'] != null && !(obj['dataSupport'] is bool)) {
+        final dataSupport = obj['dataSupport'];
+        if (dataSupport != null && !(dataSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -19932,37 +20703,38 @@
 
   PublishDiagnosticsClientCapabilitiesTagSupport({required this.valueSet});
   static PublishDiagnosticsClientCapabilitiesTagSupport fromJson(
-      Map<String, dynamic> json) {
-    final valueSet = json['valueSet']
-        ?.map((item) => DiagnosticTag.fromJson(item))
-        ?.cast<DiagnosticTag>()
-        ?.toList();
+      Map<String, Object?> json) {
+    final valueSetJson = json['valueSet'];
+    final valueSet = (valueSetJson as List<Object?>)
+        .map((item) => DiagnosticTag.fromJson(item as num))
+        .toList();
     return PublishDiagnosticsClientCapabilitiesTagSupport(valueSet: valueSet);
   }
 
   /// The tags supported by the client.
   final List<DiagnosticTag> valueSet;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['valueSet'] = valueSet.map((item) => item.toJson()).toList();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('valueSet');
       try {
         if (!obj.containsKey('valueSet')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['valueSet'] == null) {
+        final valueSet = obj['valueSet'];
+        if (valueSet == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['valueSet'] is List &&
-            (obj['valueSet']
+        if (!((valueSet is List &&
+            (valueSet
                 .every((item) => DiagnosticTag.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DiagnosticTag>');
           return false;
@@ -20006,13 +20778,15 @@
 
   PublishDiagnosticsParams(
       {required this.uri, this.version, required this.diagnostics});
-  static PublishDiagnosticsParams fromJson(Map<String, dynamic> json) {
-    final uri = json['uri'];
-    final version = json['version'];
-    final diagnostics = json['diagnostics']
-        ?.map((item) => Diagnostic.fromJson(item))
-        ?.cast<Diagnostic>()
-        ?.toList();
+  static PublishDiagnosticsParams fromJson(Map<String, Object?> json) {
+    final uriJson = json['uri'];
+    final uri = uriJson as String;
+    final versionJson = json['version'];
+    final version = versionJson as int?;
+    final diagnosticsJson = json['diagnostics'];
+    final diagnostics = (diagnosticsJson as List<Object?>)
+        .map((item) => Diagnostic.fromJson(item as Map<String, Object?>))
+        .toList();
     return PublishDiagnosticsParams(
         uri: uri, version: version, diagnostics: diagnostics);
   }
@@ -20028,8 +20802,8 @@
   ///  @since 3.15.0
   final int? version;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['uri'] = uri;
     if (version != null) {
       __result['version'] = version;
@@ -20039,18 +20813,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('uri');
       try {
         if (!obj.containsKey('uri')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['uri'] == null) {
+        final uri = obj['uri'];
+        if (uri == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['uri'] is String)) {
+        if (!(uri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -20059,7 +20834,8 @@
       }
       reporter.push('version');
       try {
-        if (obj['version'] != null && !(obj['version'] is int)) {
+        final version = obj['version'];
+        if (version != null && !(version is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -20072,12 +20848,13 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['diagnostics'] == null) {
+        final diagnostics = obj['diagnostics'];
+        if (diagnostics == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['diagnostics'] is List &&
-            (obj['diagnostics']
+        if (!((diagnostics is List &&
+            (diagnostics
                 .every((item) => Diagnostic.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<Diagnostic>');
           return false;
@@ -20122,9 +20899,11 @@
   static const jsonHandler = LspJsonHandler(Range.canParse, Range.fromJson);
 
   Range({required this.start, required this.end});
-  static Range fromJson(Map<String, dynamic> json) {
-    final start = Position.fromJson(json['start']);
-    final end = Position.fromJson(json['end']);
+  static Range fromJson(Map<String, Object?> json) {
+    final startJson = json['start'];
+    final start = Position.fromJson(startJson as Map<String, Object?>);
+    final endJson = json['end'];
+    final end = Position.fromJson(endJson as Map<String, Object?>);
     return Range(start: start, end: end);
   }
 
@@ -20134,26 +20913,27 @@
   /// The range's start position.
   final Position start;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['start'] = start.toJson();
     __result['end'] = end.toJson();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('start');
       try {
         if (!obj.containsKey('start')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['start'] == null) {
+        final start = obj['start'];
+        if (start == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Position.canParse(obj['start'], reporter))) {
+        if (!(Position.canParse(start, reporter))) {
           reporter.reportError('must be of type Position');
           return false;
         }
@@ -20166,11 +20946,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['end'] == null) {
+        final end = obj['end'];
+        if (end == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Position.canParse(obj['end'], reporter))) {
+        if (!(Position.canParse(end, reporter))) {
           reporter.reportError('must be of type Position');
           return false;
         }
@@ -20209,35 +20990,38 @@
       RangeAndPlaceholder.canParse, RangeAndPlaceholder.fromJson);
 
   RangeAndPlaceholder({required this.range, required this.placeholder});
-  static RangeAndPlaceholder fromJson(Map<String, dynamic> json) {
-    final range = Range.fromJson(json['range']);
-    final placeholder = json['placeholder'];
+  static RangeAndPlaceholder fromJson(Map<String, Object?> json) {
+    final rangeJson = json['range'];
+    final range = Range.fromJson(rangeJson as Map<String, Object?>);
+    final placeholderJson = json['placeholder'];
+    final placeholder = placeholderJson as String;
     return RangeAndPlaceholder(range: range, placeholder: placeholder);
   }
 
   final String placeholder;
   final Range range;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['range'] = range.toJson();
     __result['placeholder'] = placeholder;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('range');
       try {
         if (!obj.containsKey('range')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['range'] == null) {
+        final range = obj['range'];
+        if (range == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['range'], reporter))) {
+        if (!(Range.canParse(range, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -20250,11 +21034,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['placeholder'] == null) {
+        final placeholder = obj['placeholder'];
+        if (placeholder == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['placeholder'] is String)) {
+        if (!(placeholder is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -20295,8 +21080,9 @@
       ReferenceClientCapabilities.fromJson);
 
   ReferenceClientCapabilities({this.dynamicRegistration});
-  static ReferenceClientCapabilities fromJson(Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
+  static ReferenceClientCapabilities fromJson(Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
     return ReferenceClientCapabilities(
         dynamicRegistration: dynamicRegistration);
   }
@@ -20304,8 +21090,8 @@
   /// Whether references supports dynamic registration.
   final bool? dynamicRegistration;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -20313,11 +21099,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -20356,33 +21142,35 @@
       LspJsonHandler(ReferenceContext.canParse, ReferenceContext.fromJson);
 
   ReferenceContext({required this.includeDeclaration});
-  static ReferenceContext fromJson(Map<String, dynamic> json) {
-    final includeDeclaration = json['includeDeclaration'];
+  static ReferenceContext fromJson(Map<String, Object?> json) {
+    final includeDeclarationJson = json['includeDeclaration'];
+    final includeDeclaration = includeDeclarationJson as bool;
     return ReferenceContext(includeDeclaration: includeDeclaration);
   }
 
   /// Include the declaration of the current symbol.
   final bool includeDeclaration;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['includeDeclaration'] = includeDeclaration;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('includeDeclaration');
       try {
         if (!obj.containsKey('includeDeclaration')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['includeDeclaration'] == null) {
+        final includeDeclaration = obj['includeDeclaration'];
+        if (includeDeclaration == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['includeDeclaration'] is bool)) {
+        if (!(includeDeclaration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -20420,18 +21208,19 @@
       LspJsonHandler(ReferenceOptions.canParse, ReferenceOptions.fromJson);
 
   ReferenceOptions({this.workDoneProgress});
-  static ReferenceOptions fromJson(Map<String, dynamic> json) {
+  static ReferenceOptions fromJson(Map<String, Object?> json) {
     if (ReferenceRegistrationOptions.canParse(json, nullLspJsonReporter)) {
       return ReferenceRegistrationOptions.fromJson(json);
     }
-    final workDoneProgress = json['workDoneProgress'];
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return ReferenceOptions(workDoneProgress: workDoneProgress);
   }
 
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
     }
@@ -20439,11 +21228,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -20491,24 +21280,31 @@
       required this.position,
       this.workDoneToken,
       this.partialResultToken});
-  static ReferenceParams fromJson(Map<String, dynamic> json) {
-    final context = ReferenceContext.fromJson(json['context']);
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final position = Position.fromJson(json['position']);
-    final workDoneToken = json['workDoneToken'] == null
+  static ReferenceParams fromJson(Map<String, Object?> json) {
+    final contextJson = json['context'];
+    final context =
+        ReferenceContext.fromJson(contextJson as Map<String, Object?>);
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final positionJson = json['position'];
+    final position = Position.fromJson(positionJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
-    final partialResultToken = json['partialResultToken'] == null
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
+    final partialResultTokenJson = json['partialResultToken'];
+    final partialResultToken = partialResultTokenJson == null
         ? null
-        : (json['partialResultToken'] is int
-            ? Either2<int, String>.t1(json['partialResultToken'])
-            : (json['partialResultToken'] is String
-                ? Either2<int, String>.t2(json['partialResultToken'])
-                : (throw '''${json['partialResultToken']} was not one of (int, String)''')));
+        : (partialResultTokenJson is int
+            ? Either2<int, String>.t1(partialResultTokenJson)
+            : (partialResultTokenJson is String
+                ? Either2<int, String>.t2(partialResultTokenJson)
+                : (throw '''$partialResultTokenJson was not one of (int, String)''')));
     return ReferenceParams(
         context: context,
         textDocument: textDocument,
@@ -20532,8 +21328,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['context'] = context.toJson();
     __result['textDocument'] = textDocument.toJson();
     __result['position'] = position.toJson();
@@ -20547,18 +21343,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('context');
       try {
         if (!obj.containsKey('context')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['context'] == null) {
+        final context = obj['context'];
+        if (context == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(ReferenceContext.canParse(obj['context'], reporter))) {
+        if (!(ReferenceContext.canParse(context, reporter))) {
           reporter.reportError('must be of type ReferenceContext');
           return false;
         }
@@ -20571,11 +21368,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -20588,11 +21386,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['position'] == null) {
+        final position = obj['position'];
+        if (position == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Position.canParse(obj['position'], reporter))) {
+        if (!(Position.canParse(position, reporter))) {
           reporter.reportError('must be of type Position');
           return false;
         }
@@ -20601,9 +21400,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -20612,9 +21411,9 @@
       }
       reporter.push('partialResultToken');
       try {
-        if (obj['partialResultToken'] != null &&
-            !((obj['partialResultToken'] is int ||
-                obj['partialResultToken'] is String))) {
+        final partialResultToken = obj['partialResultToken'];
+        if (partialResultToken != null &&
+            !((partialResultToken is int || partialResultToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -20663,12 +21462,13 @@
       ReferenceRegistrationOptions.fromJson);
 
   ReferenceRegistrationOptions({this.documentSelector, this.workDoneProgress});
-  static ReferenceRegistrationOptions fromJson(Map<String, dynamic> json) {
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final workDoneProgress = json['workDoneProgress'];
+  static ReferenceRegistrationOptions fromJson(Map<String, Object?> json) {
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return ReferenceRegistrationOptions(
         documentSelector: documentSelector, workDoneProgress: workDoneProgress);
   }
@@ -20678,8 +21478,8 @@
   final List<DocumentFilter>? documentSelector;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['documentSelector'] = documentSelector;
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
@@ -20688,16 +21488,17 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentSelector');
       try {
         if (!obj.containsKey('documentSelector')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -20707,8 +21508,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -20752,10 +21553,13 @@
       LspJsonHandler(Registration.canParse, Registration.fromJson);
 
   Registration({required this.id, required this.method, this.registerOptions});
-  static Registration fromJson(Map<String, dynamic> json) {
-    final id = json['id'];
-    final method = json['method'];
-    final registerOptions = json['registerOptions'];
+  static Registration fromJson(Map<String, Object?> json) {
+    final idJson = json['id'];
+    final id = idJson as String;
+    final methodJson = json['method'];
+    final method = methodJson as String;
+    final registerOptionsJson = json['registerOptions'];
+    final registerOptions = registerOptionsJson;
     return Registration(
         id: id, method: method, registerOptions: registerOptions);
   }
@@ -20768,10 +21572,10 @@
   final String method;
 
   /// Options necessary for the registration.
-  final dynamic registerOptions;
+  final Object? registerOptions;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['id'] = id;
     __result['method'] = method;
     if (registerOptions != null) {
@@ -20781,18 +21585,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('id');
       try {
         if (!obj.containsKey('id')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['id'] == null) {
+        final id = obj['id'];
+        if (id == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['id'] is String)) {
+        if (!(id is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -20805,11 +21610,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['method'] == null) {
+        final method = obj['method'];
+        if (method == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['method'] is String)) {
+        if (!(method is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -20852,37 +21658,38 @@
       LspJsonHandler(RegistrationParams.canParse, RegistrationParams.fromJson);
 
   RegistrationParams({required this.registrations});
-  static RegistrationParams fromJson(Map<String, dynamic> json) {
-    final registrations = json['registrations']
-        ?.map((item) => Registration.fromJson(item))
-        ?.cast<Registration>()
-        ?.toList();
+  static RegistrationParams fromJson(Map<String, Object?> json) {
+    final registrationsJson = json['registrations'];
+    final registrations = (registrationsJson as List<Object?>)
+        .map((item) => Registration.fromJson(item as Map<String, Object?>))
+        .toList();
     return RegistrationParams(registrations: registrations);
   }
 
   final List<Registration> registrations;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['registrations'] =
         registrations.map((item) => item.toJson()).toList();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('registrations');
       try {
         if (!obj.containsKey('registrations')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['registrations'] == null) {
+        final registrations = obj['registrations'];
+        if (registrations == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['registrations'] is List &&
-            (obj['registrations']
+        if (!((registrations is List &&
+            (registrations
                 .every((item) => Registration.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<Registration>');
           return false;
@@ -20927,9 +21734,11 @@
 
   RegularExpressionsClientCapabilities({required this.engine, this.version});
   static RegularExpressionsClientCapabilities fromJson(
-      Map<String, dynamic> json) {
-    final engine = json['engine'];
-    final version = json['version'];
+      Map<String, Object?> json) {
+    final engineJson = json['engine'];
+    final engine = engineJson as String;
+    final versionJson = json['version'];
+    final version = versionJson as String?;
     return RegularExpressionsClientCapabilities(
         engine: engine, version: version);
   }
@@ -20940,8 +21749,8 @@
   /// The engine's version.
   final String? version;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['engine'] = engine;
     if (version != null) {
       __result['version'] = version;
@@ -20950,18 +21759,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('engine');
       try {
         if (!obj.containsKey('engine')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['engine'] == null) {
+        final engine = obj['engine'];
+        if (engine == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['engine'] is String)) {
+        if (!(engine is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -20970,7 +21780,8 @@
       }
       reporter.push('version');
       try {
-        if (obj['version'] != null && !(obj['version'] is String)) {
+        final version = obj['version'];
+        if (version != null && !(version is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -21015,15 +21826,20 @@
       this.prepareSupport,
       this.prepareSupportDefaultBehavior,
       this.honorsChangeAnnotations});
-  static RenameClientCapabilities fromJson(Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
-    final prepareSupport = json['prepareSupport'];
+  static RenameClientCapabilities fromJson(Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
+    final prepareSupportJson = json['prepareSupport'];
+    final prepareSupport = prepareSupportJson as bool?;
+    final prepareSupportDefaultBehaviorJson =
+        json['prepareSupportDefaultBehavior'];
     final prepareSupportDefaultBehavior =
-        json['prepareSupportDefaultBehavior'] != null
+        prepareSupportDefaultBehaviorJson != null
             ? PrepareSupportDefaultBehavior.fromJson(
-                json['prepareSupportDefaultBehavior'])
+                prepareSupportDefaultBehaviorJson as num)
             : null;
-    final honorsChangeAnnotations = json['honorsChangeAnnotations'];
+    final honorsChangeAnnotationsJson = json['honorsChangeAnnotations'];
+    final honorsChangeAnnotations = honorsChangeAnnotationsJson as bool?;
     return RenameClientCapabilities(
         dynamicRegistration: dynamicRegistration,
         prepareSupport: prepareSupport,
@@ -21053,8 +21869,8 @@
   ///  @since version 3.16.0
   final PrepareSupportDefaultBehavior? prepareSupportDefaultBehavior;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -21072,11 +21888,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -21085,7 +21901,8 @@
       }
       reporter.push('prepareSupport');
       try {
-        if (obj['prepareSupport'] != null && !(obj['prepareSupport'] is bool)) {
+        final prepareSupport = obj['prepareSupport'];
+        if (prepareSupport != null && !(prepareSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -21094,9 +21911,11 @@
       }
       reporter.push('prepareSupportDefaultBehavior');
       try {
-        if (obj['prepareSupportDefaultBehavior'] != null &&
+        final prepareSupportDefaultBehavior =
+            obj['prepareSupportDefaultBehavior'];
+        if (prepareSupportDefaultBehavior != null &&
             !(PrepareSupportDefaultBehavior.canParse(
-                obj['prepareSupportDefaultBehavior'], reporter))) {
+                prepareSupportDefaultBehavior, reporter))) {
           reporter.reportError('must be of type PrepareSupportDefaultBehavior');
           return false;
         }
@@ -21105,8 +21924,9 @@
       }
       reporter.push('honorsChangeAnnotations');
       try {
-        if (obj['honorsChangeAnnotations'] != null &&
-            !(obj['honorsChangeAnnotations'] is bool)) {
+        final honorsChangeAnnotations = obj['honorsChangeAnnotations'];
+        if (honorsChangeAnnotations != null &&
+            !(honorsChangeAnnotations is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -21163,14 +21983,19 @@
       throw 'kind may only be the literal \'rename\'';
     }
   }
-  static RenameFile fromJson(Map<String, dynamic> json) {
-    final kind = json['kind'];
-    final oldUri = json['oldUri'];
-    final newUri = json['newUri'];
-    final options = json['options'] != null
-        ? RenameFileOptions.fromJson(json['options'])
+  static RenameFile fromJson(Map<String, Object?> json) {
+    final kindJson = json['kind'];
+    final kind = kindJson as String;
+    final oldUriJson = json['oldUri'];
+    final oldUri = oldUriJson as String;
+    final newUriJson = json['newUri'];
+    final newUri = newUriJson as String;
+    final optionsJson = json['options'];
+    final options = optionsJson != null
+        ? RenameFileOptions.fromJson(optionsJson as Map<String, Object?>)
         : null;
-    final annotationId = json['annotationId'];
+    final annotationIdJson = json['annotationId'];
+    final annotationId = annotationIdJson as String?;
     return RenameFile(
         kind: kind,
         oldUri: oldUri,
@@ -21195,8 +22020,8 @@
   /// Rename options.
   final RenameFileOptions? options;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['kind'] = kind;
     __result['oldUri'] = oldUri;
     __result['newUri'] = newUri;
@@ -21210,18 +22035,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('kind');
       try {
         if (!obj.containsKey('kind')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['kind'] == null) {
+        final kind = obj['kind'];
+        if (kind == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['kind'] == 'rename')) {
+        if (!(kind == 'rename')) {
           reporter.reportError('must be the literal \'rename\'');
           return false;
         }
@@ -21234,11 +22060,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['oldUri'] == null) {
+        final oldUri = obj['oldUri'];
+        if (oldUri == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['oldUri'] is String)) {
+        if (!(oldUri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -21251,11 +22078,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['newUri'] == null) {
+        final newUri = obj['newUri'];
+        if (newUri == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['newUri'] is String)) {
+        if (!(newUri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -21264,8 +22092,9 @@
       }
       reporter.push('options');
       try {
-        if (obj['options'] != null &&
-            !(RenameFileOptions.canParse(obj['options'], reporter))) {
+        final options = obj['options'];
+        if (options != null &&
+            !(RenameFileOptions.canParse(options, reporter))) {
           reporter.reportError('must be of type RenameFileOptions');
           return false;
         }
@@ -21274,7 +22103,8 @@
       }
       reporter.push('annotationId');
       try {
-        if (obj['annotationId'] != null && !(obj['annotationId'] is String)) {
+        final annotationId = obj['annotationId'];
+        if (annotationId != null && !(annotationId is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -21322,9 +22152,11 @@
       LspJsonHandler(RenameFileOptions.canParse, RenameFileOptions.fromJson);
 
   RenameFileOptions({this.overwrite, this.ignoreIfExists});
-  static RenameFileOptions fromJson(Map<String, dynamic> json) {
-    final overwrite = json['overwrite'];
-    final ignoreIfExists = json['ignoreIfExists'];
+  static RenameFileOptions fromJson(Map<String, Object?> json) {
+    final overwriteJson = json['overwrite'];
+    final overwrite = overwriteJson as bool?;
+    final ignoreIfExistsJson = json['ignoreIfExists'];
+    final ignoreIfExists = ignoreIfExistsJson as bool?;
     return RenameFileOptions(
         overwrite: overwrite, ignoreIfExists: ignoreIfExists);
   }
@@ -21335,8 +22167,8 @@
   /// Overwrite target if existing. Overwrite wins over `ignoreIfExists`
   final bool? overwrite;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (overwrite != null) {
       __result['overwrite'] = overwrite;
     }
@@ -21347,10 +22179,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('overwrite');
       try {
-        if (obj['overwrite'] != null && !(obj['overwrite'] is bool)) {
+        final overwrite = obj['overwrite'];
+        if (overwrite != null && !(overwrite is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -21359,7 +22192,8 @@
       }
       reporter.push('ignoreIfExists');
       try {
-        if (obj['ignoreIfExists'] != null && !(obj['ignoreIfExists'] is bool)) {
+        final ignoreIfExists = obj['ignoreIfExists'];
+        if (ignoreIfExists != null && !(ignoreIfExists is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -21403,11 +22237,11 @@
       LspJsonHandler(RenameFilesParams.canParse, RenameFilesParams.fromJson);
 
   RenameFilesParams({required this.files});
-  static RenameFilesParams fromJson(Map<String, dynamic> json) {
-    final files = json['files']
-        ?.map((item) => FileRename.fromJson(item))
-        ?.cast<FileRename>()
-        ?.toList();
+  static RenameFilesParams fromJson(Map<String, Object?> json) {
+    final filesJson = json['files'];
+    final files = (filesJson as List<Object?>)
+        .map((item) => FileRename.fromJson(item as Map<String, Object?>))
+        .toList();
     return RenameFilesParams(files: files);
   }
 
@@ -21415,27 +22249,27 @@
   /// renamed, only the folder will be included, and not its children.
   final List<FileRename> files;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['files'] = files.map((item) => item.toJson()).toList();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('files');
       try {
         if (!obj.containsKey('files')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['files'] == null) {
+        final files = obj['files'];
+        if (files == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['files'] is List &&
-            (obj['files']
-                .every((item) => FileRename.canParse(item, reporter)))))) {
+        if (!((files is List &&
+            (files.every((item) => FileRename.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<FileRename>');
           return false;
         }
@@ -21475,12 +22309,14 @@
       LspJsonHandler(RenameOptions.canParse, RenameOptions.fromJson);
 
   RenameOptions({this.prepareProvider, this.workDoneProgress});
-  static RenameOptions fromJson(Map<String, dynamic> json) {
+  static RenameOptions fromJson(Map<String, Object?> json) {
     if (RenameRegistrationOptions.canParse(json, nullLspJsonReporter)) {
       return RenameRegistrationOptions.fromJson(json);
     }
-    final prepareProvider = json['prepareProvider'];
-    final workDoneProgress = json['workDoneProgress'];
+    final prepareProviderJson = json['prepareProvider'];
+    final prepareProvider = prepareProviderJson as bool?;
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return RenameOptions(
         prepareProvider: prepareProvider, workDoneProgress: workDoneProgress);
   }
@@ -21489,8 +22325,8 @@
   final bool? prepareProvider;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (prepareProvider != null) {
       __result['prepareProvider'] = prepareProvider;
     }
@@ -21501,11 +22337,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('prepareProvider');
       try {
-        if (obj['prepareProvider'] != null &&
-            !(obj['prepareProvider'] is bool)) {
+        final prepareProvider = obj['prepareProvider'];
+        if (prepareProvider != null && !(prepareProvider is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -21514,8 +22350,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -21561,17 +22397,22 @@
       required this.textDocument,
       required this.position,
       this.workDoneToken});
-  static RenameParams fromJson(Map<String, dynamic> json) {
-    final newName = json['newName'];
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final position = Position.fromJson(json['position']);
-    final workDoneToken = json['workDoneToken'] == null
+  static RenameParams fromJson(Map<String, Object?> json) {
+    final newNameJson = json['newName'];
+    final newName = newNameJson as String;
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final positionJson = json['position'];
+    final position = Position.fromJson(positionJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
     return RenameParams(
         newName: newName,
         textDocument: textDocument,
@@ -21592,8 +22433,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['newName'] = newName;
     __result['textDocument'] = textDocument.toJson();
     __result['position'] = position.toJson();
@@ -21604,18 +22445,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('newName');
       try {
         if (!obj.containsKey('newName')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['newName'] == null) {
+        final newName = obj['newName'];
+        if (newName == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['newName'] is String)) {
+        if (!(newName is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -21628,11 +22470,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -21645,11 +22488,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['position'] == null) {
+        final position = obj['position'];
+        if (position == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Position.canParse(obj['position'], reporter))) {
+        if (!(Position.canParse(position, reporter))) {
           reporter.reportError('must be of type Position');
           return false;
         }
@@ -21658,9 +22502,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -21707,13 +22551,15 @@
 
   RenameRegistrationOptions(
       {this.documentSelector, this.prepareProvider, this.workDoneProgress});
-  static RenameRegistrationOptions fromJson(Map<String, dynamic> json) {
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final prepareProvider = json['prepareProvider'];
-    final workDoneProgress = json['workDoneProgress'];
+  static RenameRegistrationOptions fromJson(Map<String, Object?> json) {
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final prepareProviderJson = json['prepareProvider'];
+    final prepareProvider = prepareProviderJson as bool?;
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return RenameRegistrationOptions(
         documentSelector: documentSelector,
         prepareProvider: prepareProvider,
@@ -21728,8 +22574,8 @@
   final bool? prepareProvider;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['documentSelector'] = documentSelector;
     if (prepareProvider != null) {
       __result['prepareProvider'] = prepareProvider;
@@ -21741,16 +22587,17 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentSelector');
       try {
         if (!obj.containsKey('documentSelector')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -21760,8 +22607,8 @@
       }
       reporter.push('prepareProvider');
       try {
-        if (obj['prepareProvider'] != null &&
-            !(obj['prepareProvider'] is bool)) {
+        final prepareProvider = obj['prepareProvider'];
+        if (prepareProvider != null && !(prepareProvider is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -21770,8 +22617,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -21820,15 +22667,19 @@
       required this.method,
       this.params,
       required this.jsonrpc});
-  static RequestMessage fromJson(Map<String, dynamic> json) {
-    final id = json['id'] is int
-        ? Either2<int, String>.t1(json['id'])
-        : (json['id'] is String
-            ? Either2<int, String>.t2(json['id'])
-            : (throw '''${json['id']} was not one of (int, String)'''));
-    final method = Method.fromJson(json['method']);
-    final params = json['params'];
-    final jsonrpc = json['jsonrpc'];
+  static RequestMessage fromJson(Map<String, Object?> json) {
+    final idJson = json['id'];
+    final id = idJson is int
+        ? Either2<int, String>.t1(idJson)
+        : (idJson is String
+            ? Either2<int, String>.t2(idJson)
+            : (throw '''$idJson was not one of (int, String)'''));
+    final methodJson = json['method'];
+    final method = Method.fromJson(methodJson as String);
+    final paramsJson = json['params'];
+    final params = paramsJson;
+    final jsonrpcJson = json['jsonrpc'];
+    final jsonrpc = jsonrpcJson as String;
     return RequestMessage(
         id: id, method: method, params: params, jsonrpc: jsonrpc);
   }
@@ -21841,10 +22692,10 @@
   final Method method;
 
   /// The method's params.
-  final dynamic params;
+  final Object? params;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['id'] = id;
     __result['method'] = method.toJson();
     if (params != null) {
@@ -21855,18 +22706,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('id');
       try {
         if (!obj.containsKey('id')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['id'] == null) {
+        final id = obj['id'];
+        if (id == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['id'] is int || obj['id'] is String))) {
+        if (!((id is int || id is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -21879,11 +22731,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['method'] == null) {
+        final method = obj['method'];
+        if (method == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Method.canParse(obj['method'], reporter))) {
+        if (!(Method.canParse(method, reporter))) {
           reporter.reportError('must be of type Method');
           return false;
         }
@@ -21896,11 +22749,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['jsonrpc'] == null) {
+        final jsonrpc = obj['jsonrpc'];
+        if (jsonrpc == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['jsonrpc'] is String)) {
+        if (!(jsonrpc is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -21982,10 +22836,13 @@
       LspJsonHandler(ResponseError.canParse, ResponseError.fromJson);
 
   ResponseError({required this.code, required this.message, this.data});
-  static ResponseError fromJson(Map<String, dynamic> json) {
-    final code = ErrorCodes.fromJson(json['code']);
-    final message = json['message'];
-    final data = json['data'];
+  static ResponseError fromJson(Map<String, Object?> json) {
+    final codeJson = json['code'];
+    final code = ErrorCodes.fromJson(codeJson as int);
+    final messageJson = json['message'];
+    final message = messageJson as String;
+    final dataJson = json['data'];
+    final data = dataJson as String?;
     return ResponseError(code: code, message: message, data: data);
   }
 
@@ -21999,8 +22856,8 @@
   /// A string providing a short description of the error.
   final String message;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['code'] = code.toJson();
     __result['message'] = message;
     if (data != null) {
@@ -22010,18 +22867,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('code');
       try {
         if (!obj.containsKey('code')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['code'] == null) {
+        final code = obj['code'];
+        if (code == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(ErrorCodes.canParse(obj['code'], reporter))) {
+        if (!(ErrorCodes.canParse(code, reporter))) {
           reporter.reportError('must be of type ErrorCodes');
           return false;
         }
@@ -22034,11 +22892,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['message'] == null) {
+        final message = obj['message'];
+        if (message == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['message'] is String)) {
+        if (!(message is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -22047,7 +22906,8 @@
       }
       reporter.push('data');
       try {
-        if (obj['data'] != null && !(obj['data'] is String)) {
+        final data = obj['data'];
+        if (data != null && !(data is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -22090,18 +22950,23 @@
       LspJsonHandler(ResponseMessage.canParse, ResponseMessage.fromJson);
 
   ResponseMessage({this.id, this.result, this.error, required this.jsonrpc});
-  static ResponseMessage fromJson(Map<String, dynamic> json) {
-    final id = json['id'] == null
+  static ResponseMessage fromJson(Map<String, Object?> json) {
+    final idJson = json['id'];
+    final id = idJson == null
         ? null
-        : (json['id'] is int
-            ? Either2<int, String>.t1(json['id'])
-            : (json['id'] is String
-                ? Either2<int, String>.t2(json['id'])
-                : (throw '''${json['id']} was not one of (int, String)''')));
-    final result = json['result'];
-    final error =
-        json['error'] != null ? ResponseError.fromJson(json['error']) : null;
-    final jsonrpc = json['jsonrpc'];
+        : (idJson is int
+            ? Either2<int, String>.t1(idJson)
+            : (idJson is String
+                ? Either2<int, String>.t2(idJson)
+                : (throw '''$idJson was not one of (int, String)''')));
+    final resultJson = json['result'];
+    final result = resultJson;
+    final errorJson = json['error'];
+    final error = errorJson != null
+        ? ResponseError.fromJson(errorJson as Map<String, Object?>)
+        : null;
+    final jsonrpcJson = json['jsonrpc'];
+    final jsonrpc = jsonrpcJson as String;
     return ResponseMessage(
         id: id, result: result, error: error, jsonrpc: jsonrpc);
   }
@@ -22115,10 +22980,10 @@
 
   /// The result of a request. This member is REQUIRED on success. This member
   /// MUST NOT exist if there was an error invoking the method.
-  final dynamic result;
+  final Object? result;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['id'] = id;
     __result['jsonrpc'] = jsonrpc;
     if (error != null && result != null) {
@@ -22132,14 +22997,15 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('id');
       try {
         if (!obj.containsKey('id')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['id'] != null && !((obj['id'] is int || obj['id'] is String))) {
+        final id = obj['id'];
+        if (id != null && !((id is int || id is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -22148,8 +23014,8 @@
       }
       reporter.push('error');
       try {
-        if (obj['error'] != null &&
-            !(ResponseError.canParse(obj['error'], reporter))) {
+        final error = obj['error'];
+        if (error != null && !(ResponseError.canParse(error, reporter))) {
           reporter.reportError('must be of type ResponseError');
           return false;
         }
@@ -22162,11 +23028,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['jsonrpc'] == null) {
+        final jsonrpc = obj['jsonrpc'];
+        if (jsonrpc == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['jsonrpc'] is String)) {
+        if (!(jsonrpc is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -22211,16 +23078,17 @@
       LspJsonHandler(SaveOptions.canParse, SaveOptions.fromJson);
 
   SaveOptions({this.includeText});
-  static SaveOptions fromJson(Map<String, dynamic> json) {
-    final includeText = json['includeText'];
+  static SaveOptions fromJson(Map<String, Object?> json) {
+    final includeTextJson = json['includeText'];
+    final includeText = includeTextJson as bool?;
     return SaveOptions(includeText: includeText);
   }
 
   /// The client is supposed to include the content on save.
   final bool? includeText;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (includeText != null) {
       __result['includeText'] = includeText;
     }
@@ -22228,10 +23096,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('includeText');
       try {
-        if (obj['includeText'] != null && !(obj['includeText'] is bool)) {
+        final includeText = obj['includeText'];
+        if (includeText != null && !(includeText is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -22269,10 +23138,13 @@
       LspJsonHandler(SelectionRange.canParse, SelectionRange.fromJson);
 
   SelectionRange({required this.range, this.parent});
-  static SelectionRange fromJson(Map<String, dynamic> json) {
-    final range = Range.fromJson(json['range']);
-    final parent =
-        json['parent'] != null ? SelectionRange.fromJson(json['parent']) : null;
+  static SelectionRange fromJson(Map<String, Object?> json) {
+    final rangeJson = json['range'];
+    final range = Range.fromJson(rangeJson as Map<String, Object?>);
+    final parentJson = json['parent'];
+    final parent = parentJson != null
+        ? SelectionRange.fromJson(parentJson as Map<String, Object?>)
+        : null;
     return SelectionRange(range: range, parent: parent);
   }
 
@@ -22283,8 +23155,8 @@
   /// The range ([Range]) of this selection range.
   final Range range;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['range'] = range.toJson();
     if (parent != null) {
       __result['parent'] = parent?.toJson();
@@ -22293,18 +23165,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('range');
       try {
         if (!obj.containsKey('range')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['range'] == null) {
+        final range = obj['range'];
+        if (range == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['range'], reporter))) {
+        if (!(Range.canParse(range, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -22313,8 +23186,8 @@
       }
       reporter.push('parent');
       try {
-        if (obj['parent'] != null &&
-            !(SelectionRange.canParse(obj['parent'], reporter))) {
+        final parent = obj['parent'];
+        if (parent != null && !(SelectionRange.canParse(parent, reporter))) {
           reporter.reportError('must be of type SelectionRange');
           return false;
         }
@@ -22354,8 +23227,9 @@
       SelectionRangeClientCapabilities.fromJson);
 
   SelectionRangeClientCapabilities({this.dynamicRegistration});
-  static SelectionRangeClientCapabilities fromJson(Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
+  static SelectionRangeClientCapabilities fromJson(Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
     return SelectionRangeClientCapabilities(
         dynamicRegistration: dynamicRegistration);
   }
@@ -22366,8 +23240,8 @@
   /// server capability as well.
   final bool? dynamicRegistration;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -22375,11 +23249,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -22418,18 +23292,19 @@
       SelectionRangeOptions.canParse, SelectionRangeOptions.fromJson);
 
   SelectionRangeOptions({this.workDoneProgress});
-  static SelectionRangeOptions fromJson(Map<String, dynamic> json) {
+  static SelectionRangeOptions fromJson(Map<String, Object?> json) {
     if (SelectionRangeRegistrationOptions.canParse(json, nullLspJsonReporter)) {
       return SelectionRangeRegistrationOptions.fromJson(json);
     }
-    final workDoneProgress = json['workDoneProgress'];
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return SelectionRangeOptions(workDoneProgress: workDoneProgress);
   }
 
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
     }
@@ -22437,11 +23312,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -22485,26 +23360,30 @@
       required this.positions,
       this.workDoneToken,
       this.partialResultToken});
-  static SelectionRangeParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final positions = json['positions']
-        ?.map((item) => Position.fromJson(item))
-        ?.cast<Position>()
-        ?.toList();
-    final workDoneToken = json['workDoneToken'] == null
+  static SelectionRangeParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final positionsJson = json['positions'];
+    final positions = (positionsJson as List<Object?>)
+        .map((item) => Position.fromJson(item as Map<String, Object?>))
+        .toList();
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
-    final partialResultToken = json['partialResultToken'] == null
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
+    final partialResultTokenJson = json['partialResultToken'];
+    final partialResultToken = partialResultTokenJson == null
         ? null
-        : (json['partialResultToken'] is int
-            ? Either2<int, String>.t1(json['partialResultToken'])
-            : (json['partialResultToken'] is String
-                ? Either2<int, String>.t2(json['partialResultToken'])
-                : (throw '''${json['partialResultToken']} was not one of (int, String)''')));
+        : (partialResultTokenJson is int
+            ? Either2<int, String>.t1(partialResultTokenJson)
+            : (partialResultTokenJson is String
+                ? Either2<int, String>.t2(partialResultTokenJson)
+                : (throw '''$partialResultTokenJson was not one of (int, String)''')));
     return SelectionRangeParams(
         textDocument: textDocument,
         positions: positions,
@@ -22525,8 +23404,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     __result['positions'] = positions.map((item) => item.toJson()).toList();
     if (workDoneToken != null) {
@@ -22539,18 +23418,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -22563,13 +23443,13 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['positions'] == null) {
+        final positions = obj['positions'];
+        if (positions == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['positions'] is List &&
-            (obj['positions']
-                .every((item) => Position.canParse(item, reporter)))))) {
+        if (!((positions is List &&
+            (positions.every((item) => Position.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<Position>');
           return false;
         }
@@ -22578,9 +23458,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -22589,9 +23469,9 @@
       }
       reporter.push('partialResultToken');
       try {
-        if (obj['partialResultToken'] != null &&
-            !((obj['partialResultToken'] is int ||
-                obj['partialResultToken'] is String))) {
+        final partialResultToken = obj['partialResultToken'];
+        if (partialResultToken != null &&
+            !((partialResultToken is int || partialResultToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -22645,13 +23525,15 @@
 
   SelectionRangeRegistrationOptions(
       {this.workDoneProgress, this.documentSelector, this.id});
-  static SelectionRangeRegistrationOptions fromJson(Map<String, dynamic> json) {
-    final workDoneProgress = json['workDoneProgress'];
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final id = json['id'];
+  static SelectionRangeRegistrationOptions fromJson(Map<String, Object?> json) {
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final idJson = json['id'];
+    final id = idJson as String?;
     return SelectionRangeRegistrationOptions(
         workDoneProgress: workDoneProgress,
         documentSelector: documentSelector,
@@ -22667,8 +23549,8 @@
   final String? id;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
     }
@@ -22680,11 +23562,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -22697,9 +23579,10 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -22709,7 +23592,8 @@
       }
       reporter.push('id');
       try {
-        if (obj['id'] != null && !(obj['id'] is String)) {
+        final id = obj['id'];
+        if (id != null && !(id is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -22834,9 +23718,12 @@
       LspJsonHandler(SemanticTokens.canParse, SemanticTokens.fromJson);
 
   SemanticTokens({this.resultId, required this.data});
-  static SemanticTokens fromJson(Map<String, dynamic> json) {
-    final resultId = json['resultId'];
-    final data = json['data']?.map((item) => item)?.cast<int>()?.toList();
+  static SemanticTokens fromJson(Map<String, Object?> json) {
+    final resultIdJson = json['resultId'];
+    final resultId = resultIdJson as String?;
+    final dataJson = json['data'];
+    final data =
+        (dataJson as List<Object?>).map((item) => item as int).toList();
     return SemanticTokens(resultId: resultId, data: data);
   }
 
@@ -22849,8 +23736,8 @@
   /// a delta.
   final String? resultId;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (resultId != null) {
       __result['resultId'] = resultId;
     }
@@ -22859,10 +23746,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('resultId');
       try {
-        if (obj['resultId'] != null && !(obj['resultId'] is String)) {
+        final resultId = obj['resultId'];
+        if (resultId != null && !(resultId is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -22875,12 +23763,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['data'] == null) {
+        final data = obj['data'];
+        if (data == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['data'] is List &&
-            (obj['data'].every((item) => item is int))))) {
+        if (!((data is List && (data.every((item) => item is int))))) {
           reporter.reportError('must be of type List<int>');
           return false;
         }
@@ -22929,20 +23817,28 @@
       required this.formats,
       this.overlappingTokenSupport,
       this.multilineTokenSupport});
-  static SemanticTokensClientCapabilities fromJson(Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
-    final requests =
-        SemanticTokensClientCapabilitiesRequests.fromJson(json['requests']);
-    final tokenTypes =
-        json['tokenTypes']?.map((item) => item)?.cast<String>()?.toList();
-    final tokenModifiers =
-        json['tokenModifiers']?.map((item) => item)?.cast<String>()?.toList();
-    final formats = json['formats']
-        ?.map((item) => TokenFormat.fromJson(item))
-        ?.cast<TokenFormat>()
-        ?.toList();
-    final overlappingTokenSupport = json['overlappingTokenSupport'];
-    final multilineTokenSupport = json['multilineTokenSupport'];
+  static SemanticTokensClientCapabilities fromJson(Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
+    final requestsJson = json['requests'];
+    final requests = SemanticTokensClientCapabilitiesRequests.fromJson(
+        requestsJson as Map<String, Object?>);
+    final tokenTypesJson = json['tokenTypes'];
+    final tokenTypes = (tokenTypesJson as List<Object?>)
+        .map((item) => item as String)
+        .toList();
+    final tokenModifiersJson = json['tokenModifiers'];
+    final tokenModifiers = (tokenModifiersJson as List<Object?>)
+        .map((item) => item as String)
+        .toList();
+    final formatsJson = json['formats'];
+    final formats = (formatsJson as List<Object?>)
+        .map((item) => TokenFormat.fromJson(item as String))
+        .toList();
+    final overlappingTokenSupportJson = json['overlappingTokenSupport'];
+    final overlappingTokenSupport = overlappingTokenSupportJson as bool?;
+    final multilineTokenSupportJson = json['multilineTokenSupport'];
+    final multilineTokenSupport = multilineTokenSupportJson as bool?;
     return SemanticTokensClientCapabilities(
         dynamicRegistration: dynamicRegistration,
         requests: requests,
@@ -22984,8 +23880,8 @@
   /// The token types that the client supports.
   final List<String> tokenTypes;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -23003,11 +23899,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -23020,12 +23916,13 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['requests'] == null) {
+        final requests = obj['requests'];
+        if (requests == null) {
           reporter.reportError('must not be null');
           return false;
         }
         if (!(SemanticTokensClientCapabilitiesRequests.canParse(
-            obj['requests'], reporter))) {
+            requests, reporter))) {
           reporter.reportError(
               'must be of type SemanticTokensClientCapabilitiesRequests');
           return false;
@@ -23039,12 +23936,13 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['tokenTypes'] == null) {
+        final tokenTypes = obj['tokenTypes'];
+        if (tokenTypes == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['tokenTypes'] is List &&
-            (obj['tokenTypes'].every((item) => item is String))))) {
+        if (!((tokenTypes is List &&
+            (tokenTypes.every((item) => item is String))))) {
           reporter.reportError('must be of type List<String>');
           return false;
         }
@@ -23057,12 +23955,13 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['tokenModifiers'] == null) {
+        final tokenModifiers = obj['tokenModifiers'];
+        if (tokenModifiers == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['tokenModifiers'] is List &&
-            (obj['tokenModifiers'].every((item) => item is String))))) {
+        if (!((tokenModifiers is List &&
+            (tokenModifiers.every((item) => item is String))))) {
           reporter.reportError('must be of type List<String>');
           return false;
         }
@@ -23075,13 +23974,13 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['formats'] == null) {
+        final formats = obj['formats'];
+        if (formats == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['formats'] is List &&
-            (obj['formats']
-                .every((item) => TokenFormat.canParse(item, reporter)))))) {
+        if (!((formats is List &&
+            (formats.every((item) => TokenFormat.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<TokenFormat>');
           return false;
         }
@@ -23090,8 +23989,9 @@
       }
       reporter.push('overlappingTokenSupport');
       try {
-        if (obj['overlappingTokenSupport'] != null &&
-            !(obj['overlappingTokenSupport'] is bool)) {
+        final overlappingTokenSupport = obj['overlappingTokenSupport'];
+        if (overlappingTokenSupport != null &&
+            !(overlappingTokenSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -23100,8 +24000,8 @@
       }
       reporter.push('multilineTokenSupport');
       try {
-        if (obj['multilineTokenSupport'] != null &&
-            !(obj['multilineTokenSupport'] is bool)) {
+        final multilineTokenSupport = obj['multilineTokenSupport'];
+        if (multilineTokenSupport != null && !(multilineTokenSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -23158,8 +24058,9 @@
 
   SemanticTokensClientCapabilitiesFull({this.delta});
   static SemanticTokensClientCapabilitiesFull fromJson(
-      Map<String, dynamic> json) {
-    final delta = json['delta'];
+      Map<String, Object?> json) {
+    final deltaJson = json['delta'];
+    final delta = deltaJson as bool?;
     return SemanticTokensClientCapabilitiesFull(delta: delta);
   }
 
@@ -23167,8 +24068,8 @@
   /// if the server provides a corresponding handler.
   final bool? delta;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (delta != null) {
       __result['delta'] = delta;
     }
@@ -23176,10 +24077,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('delta');
       try {
-        if (obj['delta'] != null && !(obj['delta'] is bool)) {
+        final delta = obj['delta'];
+        if (delta != null && !(delta is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -23220,17 +24122,17 @@
       SemanticTokensClientCapabilitiesRange.fromJson);
 
   static SemanticTokensClientCapabilitiesRange fromJson(
-      Map<String, dynamic> json) {
+      Map<String, Object?> json) {
     return SemanticTokensClientCapabilitiesRange();
   }
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       return true;
     } else {
       reporter
@@ -23265,28 +24167,29 @@
 
   SemanticTokensClientCapabilitiesRequests({this.range, this.full});
   static SemanticTokensClientCapabilitiesRequests fromJson(
-      Map<String, dynamic> json) {
-    final range = json['range'] == null
+      Map<String, Object?> json) {
+    final rangeJson = json['range'];
+    final range = rangeJson == null
         ? null
-        : (json['range'] is bool
-            ? Either2<bool, SemanticTokensClientCapabilitiesRange>.t1(
-                json['range'])
+        : (rangeJson is bool
+            ? Either2<bool, SemanticTokensClientCapabilitiesRange>.t1(rangeJson)
             : (SemanticTokensClientCapabilitiesRange.canParse(
-                    json['range'], nullLspJsonReporter)
+                    rangeJson, nullLspJsonReporter)
                 ? Either2<bool, SemanticTokensClientCapabilitiesRange>.t2(
                     SemanticTokensClientCapabilitiesRange.fromJson(
-                        json['range']))
-                : (throw '''${json['range']} was not one of (bool, SemanticTokensClientCapabilitiesRange)''')));
-    final full = json['full'] == null
+                        rangeJson as Map<String, Object?>))
+                : (throw '''$rangeJson was not one of (bool, SemanticTokensClientCapabilitiesRange)''')));
+    final fullJson = json['full'];
+    final full = fullJson == null
         ? null
-        : (json['full'] is bool
-            ? Either2<bool, SemanticTokensClientCapabilitiesFull>.t1(
-                json['full'])
+        : (fullJson is bool
+            ? Either2<bool, SemanticTokensClientCapabilitiesFull>.t1(fullJson)
             : (SemanticTokensClientCapabilitiesFull.canParse(
-                    json['full'], nullLspJsonReporter)
+                    fullJson, nullLspJsonReporter)
                 ? Either2<bool, SemanticTokensClientCapabilitiesFull>.t2(
-                    SemanticTokensClientCapabilitiesFull.fromJson(json['full']))
-                : (throw '''${json['full']} was not one of (bool, SemanticTokensClientCapabilitiesFull)''')));
+                    SemanticTokensClientCapabilitiesFull.fromJson(
+                        fullJson as Map<String, Object?>))
+                : (throw '''$fullJson was not one of (bool, SemanticTokensClientCapabilitiesFull)''')));
     return SemanticTokensClientCapabilitiesRequests(range: range, full: full);
   }
 
@@ -23298,8 +24201,8 @@
   /// the server provides a corresponding handler.
   final Either2<bool, SemanticTokensClientCapabilitiesRange>? range;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (range != null) {
       __result['range'] = range;
     }
@@ -23310,13 +24213,14 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('range');
       try {
-        if (obj['range'] != null &&
-            !((obj['range'] is bool ||
+        final range = obj['range'];
+        if (range != null &&
+            !((range is bool ||
                 SemanticTokensClientCapabilitiesRange.canParse(
-                    obj['range'], reporter)))) {
+                    range, reporter)))) {
           reporter.reportError(
               'must be of type Either2<bool, SemanticTokensClientCapabilitiesRange>');
           return false;
@@ -23326,10 +24230,11 @@
       }
       reporter.push('full');
       try {
-        if (obj['full'] != null &&
-            !((obj['full'] is bool ||
+        final full = obj['full'];
+        if (full != null &&
+            !((full is bool ||
                 SemanticTokensClientCapabilitiesFull.canParse(
-                    obj['full'], reporter)))) {
+                    full, reporter)))) {
           reporter.reportError(
               'must be of type Either2<bool, SemanticTokensClientCapabilitiesFull>');
           return false;
@@ -23371,12 +24276,14 @@
       SemanticTokensDelta.canParse, SemanticTokensDelta.fromJson);
 
   SemanticTokensDelta({this.resultId, required this.edits});
-  static SemanticTokensDelta fromJson(Map<String, dynamic> json) {
-    final resultId = json['resultId'];
-    final edits = json['edits']
-        ?.map((item) => SemanticTokensEdit.fromJson(item))
-        ?.cast<SemanticTokensEdit>()
-        ?.toList();
+  static SemanticTokensDelta fromJson(Map<String, Object?> json) {
+    final resultIdJson = json['resultId'];
+    final resultId = resultIdJson as String?;
+    final editsJson = json['edits'];
+    final edits = (editsJson as List<Object?>)
+        .map(
+            (item) => SemanticTokensEdit.fromJson(item as Map<String, Object?>))
+        .toList();
     return SemanticTokensDelta(resultId: resultId, edits: edits);
   }
 
@@ -23384,8 +24291,8 @@
   final List<SemanticTokensEdit> edits;
   final String? resultId;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (resultId != null) {
       __result['resultId'] = resultId;
     }
@@ -23394,10 +24301,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('resultId');
       try {
-        if (obj['resultId'] != null && !(obj['resultId'] is String)) {
+        final resultId = obj['resultId'];
+        if (resultId != null && !(resultId is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -23410,12 +24318,13 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['edits'] == null) {
+        final edits = obj['edits'];
+        if (edits == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['edits'] is List &&
-            (obj['edits'].every(
+        if (!((edits is List &&
+            (edits.every(
                 (item) => SemanticTokensEdit.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<SemanticTokensEdit>');
           return false;
@@ -23464,23 +24373,28 @@
       required this.previousResultId,
       this.workDoneToken,
       this.partialResultToken});
-  static SemanticTokensDeltaParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final previousResultId = json['previousResultId'];
-    final workDoneToken = json['workDoneToken'] == null
+  static SemanticTokensDeltaParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final previousResultIdJson = json['previousResultId'];
+    final previousResultId = previousResultIdJson as String;
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
-    final partialResultToken = json['partialResultToken'] == null
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
+    final partialResultTokenJson = json['partialResultToken'];
+    final partialResultToken = partialResultTokenJson == null
         ? null
-        : (json['partialResultToken'] is int
-            ? Either2<int, String>.t1(json['partialResultToken'])
-            : (json['partialResultToken'] is String
-                ? Either2<int, String>.t2(json['partialResultToken'])
-                : (throw '''${json['partialResultToken']} was not one of (int, String)''')));
+        : (partialResultTokenJson is int
+            ? Either2<int, String>.t1(partialResultTokenJson)
+            : (partialResultTokenJson is String
+                ? Either2<int, String>.t2(partialResultTokenJson)
+                : (throw '''$partialResultTokenJson was not one of (int, String)''')));
     return SemanticTokensDeltaParams(
         textDocument: textDocument,
         previousResultId: previousResultId,
@@ -23502,8 +24416,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     __result['previousResultId'] = previousResultId;
     if (workDoneToken != null) {
@@ -23516,18 +24430,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -23540,11 +24455,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['previousResultId'] == null) {
+        final previousResultId = obj['previousResultId'];
+        if (previousResultId == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['previousResultId'] is String)) {
+        if (!(previousResultId is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -23553,9 +24469,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -23564,9 +24480,9 @@
       }
       reporter.push('partialResultToken');
       try {
-        if (obj['partialResultToken'] != null &&
-            !((obj['partialResultToken'] is int ||
-                obj['partialResultToken'] is String))) {
+        final partialResultToken = obj['partialResultToken'];
+        if (partialResultToken != null &&
+            !((partialResultToken is int || partialResultToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -23613,36 +24529,38 @@
       SemanticTokensDeltaPartialResult.fromJson);
 
   SemanticTokensDeltaPartialResult({required this.edits});
-  static SemanticTokensDeltaPartialResult fromJson(Map<String, dynamic> json) {
-    final edits = json['edits']
-        ?.map((item) => SemanticTokensEdit.fromJson(item))
-        ?.cast<SemanticTokensEdit>()
-        ?.toList();
+  static SemanticTokensDeltaPartialResult fromJson(Map<String, Object?> json) {
+    final editsJson = json['edits'];
+    final edits = (editsJson as List<Object?>)
+        .map(
+            (item) => SemanticTokensEdit.fromJson(item as Map<String, Object?>))
+        .toList();
     return SemanticTokensDeltaPartialResult(edits: edits);
   }
 
   final List<SemanticTokensEdit> edits;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['edits'] = edits.map((item) => item.toJson()).toList();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('edits');
       try {
         if (!obj.containsKey('edits')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['edits'] == null) {
+        final edits = obj['edits'];
+        if (edits == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['edits'] is List &&
-            (obj['edits'].every(
+        if (!((edits is List &&
+            (edits.every(
                 (item) => SemanticTokensEdit.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<SemanticTokensEdit>');
           return false;
@@ -23685,10 +24603,14 @@
 
   SemanticTokensEdit(
       {required this.start, required this.deleteCount, this.data});
-  static SemanticTokensEdit fromJson(Map<String, dynamic> json) {
-    final start = json['start'];
-    final deleteCount = json['deleteCount'];
-    final data = json['data']?.map((item) => item)?.cast<int>()?.toList();
+  static SemanticTokensEdit fromJson(Map<String, Object?> json) {
+    final startJson = json['start'];
+    final start = startJson as int;
+    final deleteCountJson = json['deleteCount'];
+    final deleteCount = deleteCountJson as int;
+    final dataJson = json['data'];
+    final data =
+        (dataJson as List<Object?>?)?.map((item) => item as int).toList();
     return SemanticTokensEdit(
         start: start, deleteCount: deleteCount, data: data);
   }
@@ -23702,8 +24624,8 @@
   /// The start offset of the edit.
   final int start;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['start'] = start;
     __result['deleteCount'] = deleteCount;
     if (data != null) {
@@ -23713,18 +24635,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('start');
       try {
         if (!obj.containsKey('start')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['start'] == null) {
+        final start = obj['start'];
+        if (start == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['start'] is int)) {
+        if (!(start is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -23737,11 +24660,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['deleteCount'] == null) {
+        final deleteCount = obj['deleteCount'];
+        if (deleteCount == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['deleteCount'] is int)) {
+        if (!(deleteCount is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -23750,9 +24674,9 @@
       }
       reporter.push('data');
       try {
-        if (obj['data'] != null &&
-            !((obj['data'] is List &&
-                (obj['data'].every((item) => item is int))))) {
+        final data = obj['data'];
+        if (data != null &&
+            !((data is List && (data.every((item) => item is int))))) {
           reporter.reportError('must be of type List<int>');
           return false;
         }
@@ -23797,11 +24721,15 @@
 
   SemanticTokensLegend(
       {required this.tokenTypes, required this.tokenModifiers});
-  static SemanticTokensLegend fromJson(Map<String, dynamic> json) {
-    final tokenTypes =
-        json['tokenTypes']?.map((item) => item)?.cast<String>()?.toList();
-    final tokenModifiers =
-        json['tokenModifiers']?.map((item) => item)?.cast<String>()?.toList();
+  static SemanticTokensLegend fromJson(Map<String, Object?> json) {
+    final tokenTypesJson = json['tokenTypes'];
+    final tokenTypes = (tokenTypesJson as List<Object?>)
+        .map((item) => item as String)
+        .toList();
+    final tokenModifiersJson = json['tokenModifiers'];
+    final tokenModifiers = (tokenModifiersJson as List<Object?>)
+        .map((item) => item as String)
+        .toList();
     return SemanticTokensLegend(
         tokenTypes: tokenTypes, tokenModifiers: tokenModifiers);
   }
@@ -23812,27 +24740,28 @@
   /// The token types a server uses.
   final List<String> tokenTypes;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['tokenTypes'] = tokenTypes;
     __result['tokenModifiers'] = tokenModifiers;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('tokenTypes');
       try {
         if (!obj.containsKey('tokenTypes')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['tokenTypes'] == null) {
+        final tokenTypes = obj['tokenTypes'];
+        if (tokenTypes == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['tokenTypes'] is List &&
-            (obj['tokenTypes'].every((item) => item is String))))) {
+        if (!((tokenTypes is List &&
+            (tokenTypes.every((item) => item is String))))) {
           reporter.reportError('must be of type List<String>');
           return false;
         }
@@ -23845,12 +24774,13 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['tokenModifiers'] == null) {
+        final tokenModifiers = obj['tokenModifiers'];
+        if (tokenModifiers == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['tokenModifiers'] is List &&
-            (obj['tokenModifiers'].every((item) => item is String))))) {
+        if (!((tokenModifiers is List &&
+            (tokenModifiers.every((item) => item is String))))) {
           reporter.reportError('must be of type List<String>');
           return false;
         }
@@ -23895,30 +24825,36 @@
 
   SemanticTokensOptions(
       {required this.legend, this.range, this.full, this.workDoneProgress});
-  static SemanticTokensOptions fromJson(Map<String, dynamic> json) {
+  static SemanticTokensOptions fromJson(Map<String, Object?> json) {
     if (SemanticTokensRegistrationOptions.canParse(json, nullLspJsonReporter)) {
       return SemanticTokensRegistrationOptions.fromJson(json);
     }
-    final legend = SemanticTokensLegend.fromJson(json['legend']);
-    final range = json['range'] == null
+    final legendJson = json['legend'];
+    final legend =
+        SemanticTokensLegend.fromJson(legendJson as Map<String, Object?>);
+    final rangeJson = json['range'];
+    final range = rangeJson == null
         ? null
-        : (json['range'] is bool
-            ? Either2<bool, SemanticTokensOptionsRange>.t1(json['range'])
+        : (rangeJson is bool
+            ? Either2<bool, SemanticTokensOptionsRange>.t1(rangeJson)
             : (SemanticTokensOptionsRange.canParse(
-                    json['range'], nullLspJsonReporter)
+                    rangeJson, nullLspJsonReporter)
                 ? Either2<bool, SemanticTokensOptionsRange>.t2(
-                    SemanticTokensOptionsRange.fromJson(json['range']))
-                : (throw '''${json['range']} was not one of (bool, SemanticTokensOptionsRange)''')));
-    final full = json['full'] == null
+                    SemanticTokensOptionsRange.fromJson(
+                        rangeJson as Map<String, Object?>))
+                : (throw '''$rangeJson was not one of (bool, SemanticTokensOptionsRange)''')));
+    final fullJson = json['full'];
+    final full = fullJson == null
         ? null
-        : (json['full'] is bool
-            ? Either2<bool, SemanticTokensOptionsFull>.t1(json['full'])
-            : (SemanticTokensOptionsFull.canParse(
-                    json['full'], nullLspJsonReporter)
+        : (fullJson is bool
+            ? Either2<bool, SemanticTokensOptionsFull>.t1(fullJson)
+            : (SemanticTokensOptionsFull.canParse(fullJson, nullLspJsonReporter)
                 ? Either2<bool, SemanticTokensOptionsFull>.t2(
-                    SemanticTokensOptionsFull.fromJson(json['full']))
-                : (throw '''${json['full']} was not one of (bool, SemanticTokensOptionsFull)''')));
-    final workDoneProgress = json['workDoneProgress'];
+                    SemanticTokensOptionsFull.fromJson(
+                        fullJson as Map<String, Object?>))
+                : (throw '''$fullJson was not one of (bool, SemanticTokensOptionsFull)''')));
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return SemanticTokensOptions(
         legend: legend,
         range: range,
@@ -23937,8 +24873,8 @@
   final Either2<bool, SemanticTokensOptionsRange>? range;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['legend'] = legend.toJson();
     if (range != null) {
       __result['range'] = range;
@@ -23953,18 +24889,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('legend');
       try {
         if (!obj.containsKey('legend')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['legend'] == null) {
+        final legend = obj['legend'];
+        if (legend == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(SemanticTokensLegend.canParse(obj['legend'], reporter))) {
+        if (!(SemanticTokensLegend.canParse(legend, reporter))) {
           reporter.reportError('must be of type SemanticTokensLegend');
           return false;
         }
@@ -23973,9 +24910,10 @@
       }
       reporter.push('range');
       try {
-        if (obj['range'] != null &&
-            !((obj['range'] is bool ||
-                SemanticTokensOptionsRange.canParse(obj['range'], reporter)))) {
+        final range = obj['range'];
+        if (range != null &&
+            !((range is bool ||
+                SemanticTokensOptionsRange.canParse(range, reporter)))) {
           reporter.reportError(
               'must be of type Either2<bool, SemanticTokensOptionsRange>');
           return false;
@@ -23985,9 +24923,10 @@
       }
       reporter.push('full');
       try {
-        if (obj['full'] != null &&
-            !((obj['full'] is bool ||
-                SemanticTokensOptionsFull.canParse(obj['full'], reporter)))) {
+        final full = obj['full'];
+        if (full != null &&
+            !((full is bool ||
+                SemanticTokensOptionsFull.canParse(full, reporter)))) {
           reporter.reportError(
               'must be of type Either2<bool, SemanticTokensOptionsFull>');
           return false;
@@ -23997,8 +24936,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -24044,16 +24983,17 @@
       SemanticTokensOptionsFull.canParse, SemanticTokensOptionsFull.fromJson);
 
   SemanticTokensOptionsFull({this.delta});
-  static SemanticTokensOptionsFull fromJson(Map<String, dynamic> json) {
-    final delta = json['delta'];
+  static SemanticTokensOptionsFull fromJson(Map<String, Object?> json) {
+    final deltaJson = json['delta'];
+    final delta = deltaJson as bool?;
     return SemanticTokensOptionsFull(delta: delta);
   }
 
   /// The server supports deltas for full documents.
   final bool? delta;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (delta != null) {
       __result['delta'] = delta;
     }
@@ -24061,10 +25001,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('delta');
       try {
-        if (obj['delta'] != null && !(obj['delta'] is bool)) {
+        final delta = obj['delta'];
+        if (delta != null && !(delta is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -24102,17 +25043,17 @@
   static const jsonHandler = LspJsonHandler(
       SemanticTokensOptionsRange.canParse, SemanticTokensOptionsRange.fromJson);
 
-  static SemanticTokensOptionsRange fromJson(Map<String, dynamic> json) {
+  static SemanticTokensOptionsRange fromJson(Map<String, Object?> json) {
     return SemanticTokensOptionsRange();
   }
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       return true;
     } else {
       reporter.reportError('must be of type SemanticTokensOptionsRange');
@@ -24148,22 +25089,26 @@
       {required this.textDocument,
       this.workDoneToken,
       this.partialResultToken});
-  static SemanticTokensParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final workDoneToken = json['workDoneToken'] == null
+  static SemanticTokensParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
-    final partialResultToken = json['partialResultToken'] == null
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
+    final partialResultTokenJson = json['partialResultToken'];
+    final partialResultToken = partialResultTokenJson == null
         ? null
-        : (json['partialResultToken'] is int
-            ? Either2<int, String>.t1(json['partialResultToken'])
-            : (json['partialResultToken'] is String
-                ? Either2<int, String>.t2(json['partialResultToken'])
-                : (throw '''${json['partialResultToken']} was not one of (int, String)''')));
+        : (partialResultTokenJson is int
+            ? Either2<int, String>.t1(partialResultTokenJson)
+            : (partialResultTokenJson is String
+                ? Either2<int, String>.t2(partialResultTokenJson)
+                : (throw '''$partialResultTokenJson was not one of (int, String)''')));
     return SemanticTokensParams(
         textDocument: textDocument,
         workDoneToken: workDoneToken,
@@ -24180,8 +25125,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     if (workDoneToken != null) {
       __result['workDoneToken'] = workDoneToken;
@@ -24193,18 +25138,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -24213,9 +25159,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -24224,9 +25170,9 @@
       }
       reporter.push('partialResultToken');
       try {
-        if (obj['partialResultToken'] != null &&
-            !((obj['partialResultToken'] is int ||
-                obj['partialResultToken'] is String))) {
+        final partialResultToken = obj['partialResultToken'];
+        if (partialResultToken != null &&
+            !((partialResultToken is int || partialResultToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -24271,33 +25217,35 @@
       SemanticTokensPartialResult.fromJson);
 
   SemanticTokensPartialResult({required this.data});
-  static SemanticTokensPartialResult fromJson(Map<String, dynamic> json) {
-    final data = json['data']?.map((item) => item)?.cast<int>()?.toList();
+  static SemanticTokensPartialResult fromJson(Map<String, Object?> json) {
+    final dataJson = json['data'];
+    final data =
+        (dataJson as List<Object?>).map((item) => item as int).toList();
     return SemanticTokensPartialResult(data: data);
   }
 
   final List<int> data;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['data'] = data;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('data');
       try {
         if (!obj.containsKey('data')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['data'] == null) {
+        final data = obj['data'];
+        if (data == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['data'] is List &&
-            (obj['data'].every((item) => item is int))))) {
+        if (!((data is List && (data.every((item) => item is int))))) {
           reporter.reportError('must be of type List<int>');
           return false;
         }
@@ -24341,23 +25289,28 @@
       required this.range,
       this.workDoneToken,
       this.partialResultToken});
-  static SemanticTokensRangeParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final range = Range.fromJson(json['range']);
-    final workDoneToken = json['workDoneToken'] == null
+  static SemanticTokensRangeParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final rangeJson = json['range'];
+    final range = Range.fromJson(rangeJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
-    final partialResultToken = json['partialResultToken'] == null
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
+    final partialResultTokenJson = json['partialResultToken'];
+    final partialResultToken = partialResultTokenJson == null
         ? null
-        : (json['partialResultToken'] is int
-            ? Either2<int, String>.t1(json['partialResultToken'])
-            : (json['partialResultToken'] is String
-                ? Either2<int, String>.t2(json['partialResultToken'])
-                : (throw '''${json['partialResultToken']} was not one of (int, String)''')));
+        : (partialResultTokenJson is int
+            ? Either2<int, String>.t1(partialResultTokenJson)
+            : (partialResultTokenJson is String
+                ? Either2<int, String>.t2(partialResultTokenJson)
+                : (throw '''$partialResultTokenJson was not one of (int, String)''')));
     return SemanticTokensRangeParams(
         textDocument: textDocument,
         range: range,
@@ -24378,8 +25331,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     __result['range'] = range.toJson();
     if (workDoneToken != null) {
@@ -24392,18 +25345,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -24416,11 +25370,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['range'] == null) {
+        final range = obj['range'];
+        if (range == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['range'], reporter))) {
+        if (!(Range.canParse(range, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -24429,9 +25384,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -24440,9 +25395,9 @@
       }
       reporter.push('partialResultToken');
       try {
-        if (obj['partialResultToken'] != null &&
-            !((obj['partialResultToken'] is int ||
-                obj['partialResultToken'] is String))) {
+        final partialResultToken = obj['partialResultToken'];
+        if (partialResultToken != null &&
+            !((partialResultToken is int || partialResultToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -24500,32 +25455,39 @@
       this.full,
       this.workDoneProgress,
       this.id});
-  static SemanticTokensRegistrationOptions fromJson(Map<String, dynamic> json) {
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final legend = SemanticTokensLegend.fromJson(json['legend']);
-    final range = json['range'] == null
+  static SemanticTokensRegistrationOptions fromJson(Map<String, Object?> json) {
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final legendJson = json['legend'];
+    final legend =
+        SemanticTokensLegend.fromJson(legendJson as Map<String, Object?>);
+    final rangeJson = json['range'];
+    final range = rangeJson == null
         ? null
-        : (json['range'] is bool
-            ? Either2<bool, SemanticTokensOptionsRange>.t1(json['range'])
+        : (rangeJson is bool
+            ? Either2<bool, SemanticTokensOptionsRange>.t1(rangeJson)
             : (SemanticTokensOptionsRange.canParse(
-                    json['range'], nullLspJsonReporter)
+                    rangeJson, nullLspJsonReporter)
                 ? Either2<bool, SemanticTokensOptionsRange>.t2(
-                    SemanticTokensOptionsRange.fromJson(json['range']))
-                : (throw '''${json['range']} was not one of (bool, SemanticTokensOptionsRange)''')));
-    final full = json['full'] == null
+                    SemanticTokensOptionsRange.fromJson(
+                        rangeJson as Map<String, Object?>))
+                : (throw '''$rangeJson was not one of (bool, SemanticTokensOptionsRange)''')));
+    final fullJson = json['full'];
+    final full = fullJson == null
         ? null
-        : (json['full'] is bool
-            ? Either2<bool, SemanticTokensOptionsFull>.t1(json['full'])
-            : (SemanticTokensOptionsFull.canParse(
-                    json['full'], nullLspJsonReporter)
+        : (fullJson is bool
+            ? Either2<bool, SemanticTokensOptionsFull>.t1(fullJson)
+            : (SemanticTokensOptionsFull.canParse(fullJson, nullLspJsonReporter)
                 ? Either2<bool, SemanticTokensOptionsFull>.t2(
-                    SemanticTokensOptionsFull.fromJson(json['full']))
-                : (throw '''${json['full']} was not one of (bool, SemanticTokensOptionsFull)''')));
-    final workDoneProgress = json['workDoneProgress'];
-    final id = json['id'];
+                    SemanticTokensOptionsFull.fromJson(
+                        fullJson as Map<String, Object?>))
+                : (throw '''$fullJson was not one of (bool, SemanticTokensOptionsFull)''')));
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
+    final idJson = json['id'];
+    final id = idJson as String?;
     return SemanticTokensRegistrationOptions(
         documentSelector: documentSelector,
         legend: legend,
@@ -24554,8 +25516,8 @@
   final Either2<bool, SemanticTokensOptionsRange>? range;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['documentSelector'] = documentSelector;
     __result['legend'] = legend.toJson();
     if (range != null) {
@@ -24574,16 +25536,17 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentSelector');
       try {
         if (!obj.containsKey('documentSelector')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -24597,11 +25560,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['legend'] == null) {
+        final legend = obj['legend'];
+        if (legend == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(SemanticTokensLegend.canParse(obj['legend'], reporter))) {
+        if (!(SemanticTokensLegend.canParse(legend, reporter))) {
           reporter.reportError('must be of type SemanticTokensLegend');
           return false;
         }
@@ -24610,9 +25574,10 @@
       }
       reporter.push('range');
       try {
-        if (obj['range'] != null &&
-            !((obj['range'] is bool ||
-                SemanticTokensOptionsRange.canParse(obj['range'], reporter)))) {
+        final range = obj['range'];
+        if (range != null &&
+            !((range is bool ||
+                SemanticTokensOptionsRange.canParse(range, reporter)))) {
           reporter.reportError(
               'must be of type Either2<bool, SemanticTokensOptionsRange>');
           return false;
@@ -24622,9 +25587,10 @@
       }
       reporter.push('full');
       try {
-        if (obj['full'] != null &&
-            !((obj['full'] is bool ||
-                SemanticTokensOptionsFull.canParse(obj['full'], reporter)))) {
+        final full = obj['full'];
+        if (full != null &&
+            !((full is bool ||
+                SemanticTokensOptionsFull.canParse(full, reporter)))) {
           reporter.reportError(
               'must be of type Either2<bool, SemanticTokensOptionsFull>');
           return false;
@@ -24634,8 +25600,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -24644,7 +25610,8 @@
       }
       reporter.push('id');
       try {
-        if (obj['id'] != null && !(obj['id'] is String)) {
+        final id = obj['id'];
+        if (id != null && !(id is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -24697,8 +25664,9 @@
 
   SemanticTokensWorkspaceClientCapabilities({this.refreshSupport});
   static SemanticTokensWorkspaceClientCapabilities fromJson(
-      Map<String, dynamic> json) {
-    final refreshSupport = json['refreshSupport'];
+      Map<String, Object?> json) {
+    final refreshSupportJson = json['refreshSupport'];
+    final refreshSupport = refreshSupportJson as bool?;
     return SemanticTokensWorkspaceClientCapabilities(
         refreshSupport: refreshSupport);
   }
@@ -24712,8 +25680,8 @@
   /// change that requires such a calculation.
   final bool? refreshSupport;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (refreshSupport != null) {
       __result['refreshSupport'] = refreshSupport;
     }
@@ -24721,10 +25689,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('refreshSupport');
       try {
-        if (obj['refreshSupport'] != null && !(obj['refreshSupport'] is bool)) {
+        final refreshSupport = obj['refreshSupport'];
+        if (refreshSupport != null && !(refreshSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -24793,299 +25762,337 @@
       this.workspaceSymbolProvider,
       this.workspace,
       this.experimental});
-  static ServerCapabilities fromJson(Map<String, dynamic> json) {
-    final textDocumentSync = json['textDocumentSync'] == null
+  static ServerCapabilities fromJson(Map<String, Object?> json) {
+    final textDocumentSyncJson = json['textDocumentSync'];
+    final textDocumentSync = textDocumentSyncJson == null
         ? null
         : (TextDocumentSyncOptions.canParse(
-                json['textDocumentSync'], nullLspJsonReporter)
+                textDocumentSyncJson, nullLspJsonReporter)
             ? Either2<TextDocumentSyncOptions, TextDocumentSyncKind>.t1(
-                TextDocumentSyncOptions.fromJson(json['textDocumentSync']))
+                TextDocumentSyncOptions.fromJson(
+                    textDocumentSyncJson as Map<String, Object?>))
             : (TextDocumentSyncKind.canParse(
-                    json['textDocumentSync'], nullLspJsonReporter)
+                    textDocumentSyncJson, nullLspJsonReporter)
                 ? Either2<TextDocumentSyncOptions, TextDocumentSyncKind>.t2(
-                    TextDocumentSyncKind.fromJson(json['textDocumentSync']))
-                : (throw '''${json['textDocumentSync']} was not one of (TextDocumentSyncOptions, TextDocumentSyncKind)''')));
-    final completionProvider = json['completionProvider'] != null
-        ? CompletionOptions.fromJson(json['completionProvider'])
+                    TextDocumentSyncKind.fromJson(textDocumentSyncJson as int))
+                : (throw '''$textDocumentSyncJson was not one of (TextDocumentSyncOptions, TextDocumentSyncKind)''')));
+    final completionProviderJson = json['completionProvider'];
+    final completionProvider = completionProviderJson != null
+        ? CompletionOptions.fromJson(
+            completionProviderJson as Map<String, Object?>)
         : null;
-    final hoverProvider = json['hoverProvider'] == null
+    final hoverProviderJson = json['hoverProvider'];
+    final hoverProvider = hoverProviderJson == null
         ? null
-        : (json['hoverProvider'] is bool
-            ? Either2<bool, HoverOptions>.t1(json['hoverProvider'])
-            : (HoverOptions.canParse(json['hoverProvider'], nullLspJsonReporter)
-                ? Either2<bool, HoverOptions>.t2(
-                    HoverOptions.fromJson(json['hoverProvider']))
-                : (throw '''${json['hoverProvider']} was not one of (bool, HoverOptions)''')));
-    final signatureHelpProvider = json['signatureHelpProvider'] != null
-        ? SignatureHelpOptions.fromJson(json['signatureHelpProvider'])
+        : (hoverProviderJson is bool
+            ? Either2<bool, HoverOptions>.t1(hoverProviderJson)
+            : (HoverOptions.canParse(hoverProviderJson, nullLspJsonReporter)
+                ? Either2<bool, HoverOptions>.t2(HoverOptions.fromJson(
+                    hoverProviderJson as Map<String, Object?>))
+                : (throw '''$hoverProviderJson was not one of (bool, HoverOptions)''')));
+    final signatureHelpProviderJson = json['signatureHelpProvider'];
+    final signatureHelpProvider = signatureHelpProviderJson != null
+        ? SignatureHelpOptions.fromJson(
+            signatureHelpProviderJson as Map<String, Object?>)
         : null;
-    final declarationProvider = json['declarationProvider'] == null
+    final declarationProviderJson = json['declarationProvider'];
+    final declarationProvider = declarationProviderJson == null
         ? null
-        : (json['declarationProvider'] is bool
-            ? Either3<bool, DeclarationOptions,
-                DeclarationRegistrationOptions>.t1(json['declarationProvider'])
+        : (declarationProviderJson is bool
+            ? Either3<bool, DeclarationOptions, DeclarationRegistrationOptions>.t1(
+                declarationProviderJson)
             : (DeclarationOptions.canParse(
-                    json['declarationProvider'], nullLspJsonReporter)
+                    declarationProviderJson, nullLspJsonReporter)
                 ? Either3<bool, DeclarationOptions, DeclarationRegistrationOptions>.t2(
-                    DeclarationOptions.fromJson(json['declarationProvider']))
+                    DeclarationOptions.fromJson(
+                        declarationProviderJson as Map<String, Object?>))
                 : (DeclarationRegistrationOptions.canParse(
-                        json['declarationProvider'], nullLspJsonReporter)
+                        declarationProviderJson, nullLspJsonReporter)
                     ? Either3<bool, DeclarationOptions, DeclarationRegistrationOptions>.t3(
                         DeclarationRegistrationOptions.fromJson(
-                            json['declarationProvider']))
-                    : (throw '''${json['declarationProvider']} was not one of (bool, DeclarationOptions, DeclarationRegistrationOptions)'''))));
-    final definitionProvider = json['definitionProvider'] == null
+                            declarationProviderJson as Map<String, Object?>))
+                    : (throw '''$declarationProviderJson was not one of (bool, DeclarationOptions, DeclarationRegistrationOptions)'''))));
+    final definitionProviderJson = json['definitionProvider'];
+    final definitionProvider = definitionProviderJson == null
         ? null
-        : (json['definitionProvider'] is bool
-            ? Either2<bool, DefinitionOptions>.t1(json['definitionProvider'])
+        : (definitionProviderJson is bool
+            ? Either2<bool, DefinitionOptions>.t1(definitionProviderJson)
             : (DefinitionOptions.canParse(
-                    json['definitionProvider'], nullLspJsonReporter)
+                    definitionProviderJson, nullLspJsonReporter)
                 ? Either2<bool, DefinitionOptions>.t2(
-                    DefinitionOptions.fromJson(json['definitionProvider']))
-                : (throw '''${json['definitionProvider']} was not one of (bool, DefinitionOptions)''')));
-    final typeDefinitionProvider = json['typeDefinitionProvider'] == null
+                    DefinitionOptions.fromJson(
+                        definitionProviderJson as Map<String, Object?>))
+                : (throw '''$definitionProviderJson was not one of (bool, DefinitionOptions)''')));
+    final typeDefinitionProviderJson = json['typeDefinitionProvider'];
+    final typeDefinitionProvider = typeDefinitionProviderJson == null
         ? null
-        : (json['typeDefinitionProvider'] is bool
+        : (typeDefinitionProviderJson is bool
             ? Either3<bool, TypeDefinitionOptions, TypeDefinitionRegistrationOptions>.t1(
-                json['typeDefinitionProvider'])
+                typeDefinitionProviderJson)
             : (TypeDefinitionOptions.canParse(
-                    json['typeDefinitionProvider'], nullLspJsonReporter)
+                    typeDefinitionProviderJson, nullLspJsonReporter)
                 ? Either3<bool, TypeDefinitionOptions, TypeDefinitionRegistrationOptions>.t2(
                     TypeDefinitionOptions.fromJson(
-                        json['typeDefinitionProvider']))
+                        typeDefinitionProviderJson as Map<String, Object?>))
                 : (TypeDefinitionRegistrationOptions.canParse(
-                        json['typeDefinitionProvider'], nullLspJsonReporter)
+                        typeDefinitionProviderJson, nullLspJsonReporter)
                     ? Either3<bool, TypeDefinitionOptions, TypeDefinitionRegistrationOptions>.t3(
                         TypeDefinitionRegistrationOptions.fromJson(
-                            json['typeDefinitionProvider']))
-                    : (throw '''${json['typeDefinitionProvider']} was not one of (bool, TypeDefinitionOptions, TypeDefinitionRegistrationOptions)'''))));
-    final implementationProvider = json['implementationProvider'] == null
+                            typeDefinitionProviderJson as Map<String, Object?>))
+                    : (throw '''$typeDefinitionProviderJson was not one of (bool, TypeDefinitionOptions, TypeDefinitionRegistrationOptions)'''))));
+    final implementationProviderJson = json['implementationProvider'];
+    final implementationProvider = implementationProviderJson == null
         ? null
-        : (json['implementationProvider'] is bool
+        : (implementationProviderJson is bool
             ? Either3<bool, ImplementationOptions, ImplementationRegistrationOptions>.t1(
-                json['implementationProvider'])
+                implementationProviderJson)
             : (ImplementationOptions.canParse(
-                    json['implementationProvider'], nullLspJsonReporter)
+                    implementationProviderJson, nullLspJsonReporter)
                 ? Either3<bool, ImplementationOptions, ImplementationRegistrationOptions>.t2(
                     ImplementationOptions.fromJson(
-                        json['implementationProvider']))
+                        implementationProviderJson as Map<String, Object?>))
                 : (ImplementationRegistrationOptions.canParse(
-                        json['implementationProvider'], nullLspJsonReporter)
+                        implementationProviderJson, nullLspJsonReporter)
                     ? Either3<bool, ImplementationOptions, ImplementationRegistrationOptions>.t3(
                         ImplementationRegistrationOptions.fromJson(
-                            json['implementationProvider']))
-                    : (throw '''${json['implementationProvider']} was not one of (bool, ImplementationOptions, ImplementationRegistrationOptions)'''))));
-    final referencesProvider = json['referencesProvider'] == null
+                            implementationProviderJson as Map<String, Object?>))
+                    : (throw '''$implementationProviderJson was not one of (bool, ImplementationOptions, ImplementationRegistrationOptions)'''))));
+    final referencesProviderJson = json['referencesProvider'];
+    final referencesProvider = referencesProviderJson == null
         ? null
-        : (json['referencesProvider'] is bool
-            ? Either2<bool, ReferenceOptions>.t1(json['referencesProvider'])
+        : (referencesProviderJson is bool
+            ? Either2<bool, ReferenceOptions>.t1(referencesProviderJson)
             : (ReferenceOptions.canParse(
-                    json['referencesProvider'], nullLspJsonReporter)
-                ? Either2<bool, ReferenceOptions>.t2(
-                    ReferenceOptions.fromJson(json['referencesProvider']))
-                : (throw '''${json['referencesProvider']} was not one of (bool, ReferenceOptions)''')));
-    final documentHighlightProvider = json['documentHighlightProvider'] == null
+                    referencesProviderJson, nullLspJsonReporter)
+                ? Either2<bool, ReferenceOptions>.t2(ReferenceOptions.fromJson(
+                    referencesProviderJson as Map<String, Object?>))
+                : (throw '''$referencesProviderJson was not one of (bool, ReferenceOptions)''')));
+    final documentHighlightProviderJson = json['documentHighlightProvider'];
+    final documentHighlightProvider = documentHighlightProviderJson == null
         ? null
-        : (json['documentHighlightProvider'] is bool
+        : (documentHighlightProviderJson is bool
             ? Either2<bool, DocumentHighlightOptions>.t1(
-                json['documentHighlightProvider'])
+                documentHighlightProviderJson)
             : (DocumentHighlightOptions.canParse(
-                    json['documentHighlightProvider'], nullLspJsonReporter)
+                    documentHighlightProviderJson, nullLspJsonReporter)
                 ? Either2<bool, DocumentHighlightOptions>.t2(
                     DocumentHighlightOptions.fromJson(
-                        json['documentHighlightProvider']))
-                : (throw '''${json['documentHighlightProvider']} was not one of (bool, DocumentHighlightOptions)''')));
-    final documentSymbolProvider = json['documentSymbolProvider'] == null
+                        documentHighlightProviderJson as Map<String, Object?>))
+                : (throw '''$documentHighlightProviderJson was not one of (bool, DocumentHighlightOptions)''')));
+    final documentSymbolProviderJson = json['documentSymbolProvider'];
+    final documentSymbolProvider = documentSymbolProviderJson == null
         ? null
-        : (json['documentSymbolProvider'] is bool
+        : (documentSymbolProviderJson is bool
             ? Either2<bool, DocumentSymbolOptions>.t1(
-                json['documentSymbolProvider'])
+                documentSymbolProviderJson)
             : (DocumentSymbolOptions.canParse(
-                    json['documentSymbolProvider'], nullLspJsonReporter)
+                    documentSymbolProviderJson, nullLspJsonReporter)
                 ? Either2<bool, DocumentSymbolOptions>.t2(
                     DocumentSymbolOptions.fromJson(
-                        json['documentSymbolProvider']))
-                : (throw '''${json['documentSymbolProvider']} was not one of (bool, DocumentSymbolOptions)''')));
-    final codeActionProvider = json['codeActionProvider'] == null
+                        documentSymbolProviderJson as Map<String, Object?>))
+                : (throw '''$documentSymbolProviderJson was not one of (bool, DocumentSymbolOptions)''')));
+    final codeActionProviderJson = json['codeActionProvider'];
+    final codeActionProvider = codeActionProviderJson == null
         ? null
-        : (json['codeActionProvider'] is bool
-            ? Either2<bool, CodeActionOptions>.t1(json['codeActionProvider'])
+        : (codeActionProviderJson is bool
+            ? Either2<bool, CodeActionOptions>.t1(codeActionProviderJson)
             : (CodeActionOptions.canParse(
-                    json['codeActionProvider'], nullLspJsonReporter)
+                    codeActionProviderJson, nullLspJsonReporter)
                 ? Either2<bool, CodeActionOptions>.t2(
-                    CodeActionOptions.fromJson(json['codeActionProvider']))
-                : (throw '''${json['codeActionProvider']} was not one of (bool, CodeActionOptions)''')));
-    final codeLensProvider = json['codeLensProvider'] != null
-        ? CodeLensOptions.fromJson(json['codeLensProvider'])
+                    CodeActionOptions.fromJson(
+                        codeActionProviderJson as Map<String, Object?>))
+                : (throw '''$codeActionProviderJson was not one of (bool, CodeActionOptions)''')));
+    final codeLensProviderJson = json['codeLensProvider'];
+    final codeLensProvider = codeLensProviderJson != null
+        ? CodeLensOptions.fromJson(codeLensProviderJson as Map<String, Object?>)
         : null;
-    final documentLinkProvider = json['documentLinkProvider'] != null
-        ? DocumentLinkOptions.fromJson(json['documentLinkProvider'])
+    final documentLinkProviderJson = json['documentLinkProvider'];
+    final documentLinkProvider = documentLinkProviderJson != null
+        ? DocumentLinkOptions.fromJson(
+            documentLinkProviderJson as Map<String, Object?>)
         : null;
-    final colorProvider = json['colorProvider'] == null
+    final colorProviderJson = json['colorProvider'];
+    final colorProvider = colorProviderJson == null
         ? null
-        : (json['colorProvider'] is bool
-            ? Either3<bool, DocumentColorOptions, DocumentColorRegistrationOptions>.t1(
-                json['colorProvider'])
-            : (DocumentColorOptions.canParse(json['colorProvider'], nullLspJsonReporter)
+        : (colorProviderJson is bool
+            ? Either3<bool, DocumentColorOptions,
+                DocumentColorRegistrationOptions>.t1(colorProviderJson)
+            : (DocumentColorOptions.canParse(colorProviderJson, nullLspJsonReporter)
                 ? Either3<bool, DocumentColorOptions, DocumentColorRegistrationOptions>.t2(
-                    DocumentColorOptions.fromJson(json['colorProvider']))
+                    DocumentColorOptions.fromJson(
+                        colorProviderJson as Map<String, Object?>))
                 : (DocumentColorRegistrationOptions.canParse(
-                        json['colorProvider'], nullLspJsonReporter)
-                    ? Either3<bool, DocumentColorOptions,
-                            DocumentColorRegistrationOptions>.t3(
+                        colorProviderJson, nullLspJsonReporter)
+                    ? Either3<bool, DocumentColorOptions, DocumentColorRegistrationOptions>.t3(
                         DocumentColorRegistrationOptions.fromJson(
-                            json['colorProvider']))
-                    : (throw '''${json['colorProvider']} was not one of (bool, DocumentColorOptions, DocumentColorRegistrationOptions)'''))));
-    final documentFormattingProvider = json['documentFormattingProvider'] ==
-            null
+                            colorProviderJson as Map<String, Object?>))
+                    : (throw '''$colorProviderJson was not one of (bool, DocumentColorOptions, DocumentColorRegistrationOptions)'''))));
+    final documentFormattingProviderJson = json['documentFormattingProvider'];
+    final documentFormattingProvider = documentFormattingProviderJson == null
         ? null
-        : (json['documentFormattingProvider'] is bool
+        : (documentFormattingProviderJson is bool
             ? Either2<bool, DocumentFormattingOptions>.t1(
-                json['documentFormattingProvider'])
+                documentFormattingProviderJson)
             : (DocumentFormattingOptions.canParse(
-                    json['documentFormattingProvider'], nullLspJsonReporter)
+                    documentFormattingProviderJson, nullLspJsonReporter)
                 ? Either2<bool, DocumentFormattingOptions>.t2(
                     DocumentFormattingOptions.fromJson(
-                        json['documentFormattingProvider']))
-                : (throw '''${json['documentFormattingProvider']} was not one of (bool, DocumentFormattingOptions)''')));
-    final documentRangeFormattingProvider = json[
-                'documentRangeFormattingProvider'] ==
+                        documentFormattingProviderJson as Map<String, Object?>))
+                : (throw '''$documentFormattingProviderJson was not one of (bool, DocumentFormattingOptions)''')));
+    final documentRangeFormattingProviderJson =
+        json['documentRangeFormattingProvider'];
+    final documentRangeFormattingProvider = documentRangeFormattingProviderJson ==
             null
         ? null
-        : (json['documentRangeFormattingProvider'] is bool
+        : (documentRangeFormattingProviderJson is bool
             ? Either2<bool, DocumentRangeFormattingOptions>.t1(
-                json['documentRangeFormattingProvider'])
+                documentRangeFormattingProviderJson)
             : (DocumentRangeFormattingOptions.canParse(
-                    json['documentRangeFormattingProvider'],
-                    nullLspJsonReporter)
+                    documentRangeFormattingProviderJson, nullLspJsonReporter)
                 ? Either2<bool, DocumentRangeFormattingOptions>.t2(
                     DocumentRangeFormattingOptions.fromJson(
-                        json['documentRangeFormattingProvider']))
-                : (throw '''${json['documentRangeFormattingProvider']} was not one of (bool, DocumentRangeFormattingOptions)''')));
+                        documentRangeFormattingProviderJson
+                            as Map<String, Object?>))
+                : (throw '''$documentRangeFormattingProviderJson was not one of (bool, DocumentRangeFormattingOptions)''')));
+    final documentOnTypeFormattingProviderJson =
+        json['documentOnTypeFormattingProvider'];
     final documentOnTypeFormattingProvider =
-        json['documentOnTypeFormattingProvider'] != null
+        documentOnTypeFormattingProviderJson != null
             ? DocumentOnTypeFormattingOptions.fromJson(
-                json['documentOnTypeFormattingProvider'])
+                documentOnTypeFormattingProviderJson as Map<String, Object?>)
             : null;
-    final renameProvider = json['renameProvider'] == null
+    final renameProviderJson = json['renameProvider'];
+    final renameProvider = renameProviderJson == null
         ? null
-        : (json['renameProvider'] is bool
-            ? Either2<bool, RenameOptions>.t1(json['renameProvider'])
-            : (RenameOptions.canParse(
-                    json['renameProvider'], nullLspJsonReporter)
-                ? Either2<bool, RenameOptions>.t2(
-                    RenameOptions.fromJson(json['renameProvider']))
-                : (throw '''${json['renameProvider']} was not one of (bool, RenameOptions)''')));
-    final foldingRangeProvider = json['foldingRangeProvider'] == null
+        : (renameProviderJson is bool
+            ? Either2<bool, RenameOptions>.t1(renameProviderJson)
+            : (RenameOptions.canParse(renameProviderJson, nullLspJsonReporter)
+                ? Either2<bool, RenameOptions>.t2(RenameOptions.fromJson(
+                    renameProviderJson as Map<String, Object?>))
+                : (throw '''$renameProviderJson was not one of (bool, RenameOptions)''')));
+    final foldingRangeProviderJson = json['foldingRangeProvider'];
+    final foldingRangeProvider = foldingRangeProviderJson == null
         ? null
-        : (json['foldingRangeProvider'] is bool
+        : (foldingRangeProviderJson is bool
             ? Either3<bool, FoldingRangeOptions, FoldingRangeRegistrationOptions>.t1(
-                json['foldingRangeProvider'])
+                foldingRangeProviderJson)
             : (FoldingRangeOptions.canParse(
-                    json['foldingRangeProvider'], nullLspJsonReporter)
+                    foldingRangeProviderJson, nullLspJsonReporter)
                 ? Either3<bool, FoldingRangeOptions, FoldingRangeRegistrationOptions>.t2(
-                    FoldingRangeOptions.fromJson(json['foldingRangeProvider']))
+                    FoldingRangeOptions.fromJson(
+                        foldingRangeProviderJson as Map<String, Object?>))
                 : (FoldingRangeRegistrationOptions.canParse(
-                        json['foldingRangeProvider'], nullLspJsonReporter)
+                        foldingRangeProviderJson, nullLspJsonReporter)
                     ? Either3<bool, FoldingRangeOptions, FoldingRangeRegistrationOptions>.t3(
                         FoldingRangeRegistrationOptions.fromJson(
-                            json['foldingRangeProvider']))
-                    : (throw '''${json['foldingRangeProvider']} was not one of (bool, FoldingRangeOptions, FoldingRangeRegistrationOptions)'''))));
-    final executeCommandProvider = json['executeCommandProvider'] != null
-        ? ExecuteCommandOptions.fromJson(json['executeCommandProvider'])
+                            foldingRangeProviderJson as Map<String, Object?>))
+                    : (throw '''$foldingRangeProviderJson was not one of (bool, FoldingRangeOptions, FoldingRangeRegistrationOptions)'''))));
+    final executeCommandProviderJson = json['executeCommandProvider'];
+    final executeCommandProvider = executeCommandProviderJson != null
+        ? ExecuteCommandOptions.fromJson(
+            executeCommandProviderJson as Map<String, Object?>)
         : null;
-    final selectionRangeProvider = json['selectionRangeProvider'] == null
+    final selectionRangeProviderJson = json['selectionRangeProvider'];
+    final selectionRangeProvider = selectionRangeProviderJson == null
         ? null
-        : (json['selectionRangeProvider'] is bool
+        : (selectionRangeProviderJson is bool
             ? Either3<bool, SelectionRangeOptions, SelectionRangeRegistrationOptions>.t1(
-                json['selectionRangeProvider'])
+                selectionRangeProviderJson)
             : (SelectionRangeOptions.canParse(
-                    json['selectionRangeProvider'], nullLspJsonReporter)
+                    selectionRangeProviderJson, nullLspJsonReporter)
                 ? Either3<bool, SelectionRangeOptions, SelectionRangeRegistrationOptions>.t2(
                     SelectionRangeOptions.fromJson(
-                        json['selectionRangeProvider']))
+                        selectionRangeProviderJson as Map<String, Object?>))
                 : (SelectionRangeRegistrationOptions.canParse(
-                        json['selectionRangeProvider'], nullLspJsonReporter)
+                        selectionRangeProviderJson, nullLspJsonReporter)
                     ? Either3<bool, SelectionRangeOptions, SelectionRangeRegistrationOptions>.t3(
                         SelectionRangeRegistrationOptions.fromJson(
-                            json['selectionRangeProvider']))
-                    : (throw '''${json['selectionRangeProvider']} was not one of (bool, SelectionRangeOptions, SelectionRangeRegistrationOptions)'''))));
-    final linkedEditingRangeProvider = json['linkedEditingRangeProvider'] == null
+                            selectionRangeProviderJson as Map<String, Object?>))
+                    : (throw '''$selectionRangeProviderJson was not one of (bool, SelectionRangeOptions, SelectionRangeRegistrationOptions)'''))));
+    final linkedEditingRangeProviderJson = json['linkedEditingRangeProvider'];
+    final linkedEditingRangeProvider = linkedEditingRangeProviderJson == null
         ? null
-        : (json['linkedEditingRangeProvider'] is bool
+        : (linkedEditingRangeProviderJson is bool
             ? Either3<bool, LinkedEditingRangeOptions, LinkedEditingRangeRegistrationOptions>.t1(
-                json['linkedEditingRangeProvider'])
+                linkedEditingRangeProviderJson)
             : (LinkedEditingRangeOptions.canParse(
-                    json['linkedEditingRangeProvider'], nullLspJsonReporter)
+                    linkedEditingRangeProviderJson, nullLspJsonReporter)
                 ? Either3<bool, LinkedEditingRangeOptions, LinkedEditingRangeRegistrationOptions>.t2(
                     LinkedEditingRangeOptions.fromJson(
-                        json['linkedEditingRangeProvider']))
+                        linkedEditingRangeProviderJson as Map<String, Object?>))
                 : (LinkedEditingRangeRegistrationOptions.canParse(
-                        json['linkedEditingRangeProvider'], nullLspJsonReporter)
+                        linkedEditingRangeProviderJson, nullLspJsonReporter)
                     ? Either3<bool, LinkedEditingRangeOptions, LinkedEditingRangeRegistrationOptions>.t3(
                         LinkedEditingRangeRegistrationOptions.fromJson(
-                            json['linkedEditingRangeProvider']))
-                    : (throw '''${json['linkedEditingRangeProvider']} was not one of (bool, LinkedEditingRangeOptions, LinkedEditingRangeRegistrationOptions)'''))));
-    final callHierarchyProvider = json['callHierarchyProvider'] == null
+                            linkedEditingRangeProviderJson as Map<String, Object?>))
+                    : (throw '''$linkedEditingRangeProviderJson was not one of (bool, LinkedEditingRangeOptions, LinkedEditingRangeRegistrationOptions)'''))));
+    final callHierarchyProviderJson = json['callHierarchyProvider'];
+    final callHierarchyProvider = callHierarchyProviderJson == null
         ? null
-        : (json['callHierarchyProvider'] is bool
+        : (callHierarchyProviderJson is bool
             ? Either3<bool, CallHierarchyOptions, CallHierarchyRegistrationOptions>.t1(
-                json['callHierarchyProvider'])
+                callHierarchyProviderJson)
             : (CallHierarchyOptions.canParse(
-                    json['callHierarchyProvider'], nullLspJsonReporter)
+                    callHierarchyProviderJson, nullLspJsonReporter)
                 ? Either3<bool, CallHierarchyOptions, CallHierarchyRegistrationOptions>.t2(
                     CallHierarchyOptions.fromJson(
-                        json['callHierarchyProvider']))
+                        callHierarchyProviderJson as Map<String, Object?>))
                 : (CallHierarchyRegistrationOptions.canParse(
-                        json['callHierarchyProvider'], nullLspJsonReporter)
+                        callHierarchyProviderJson, nullLspJsonReporter)
                     ? Either3<bool, CallHierarchyOptions, CallHierarchyRegistrationOptions>.t3(
                         CallHierarchyRegistrationOptions.fromJson(
-                            json['callHierarchyProvider']))
-                    : (throw '''${json['callHierarchyProvider']} was not one of (bool, CallHierarchyOptions, CallHierarchyRegistrationOptions)'''))));
-    final semanticTokensProvider = json['semanticTokensProvider'] == null
+                            callHierarchyProviderJson as Map<String, Object?>))
+                    : (throw '''$callHierarchyProviderJson was not one of (bool, CallHierarchyOptions, CallHierarchyRegistrationOptions)'''))));
+    final semanticTokensProviderJson = json['semanticTokensProvider'];
+    final semanticTokensProvider = semanticTokensProviderJson == null
         ? null
         : (SemanticTokensOptions.canParse(
-                json['semanticTokensProvider'], nullLspJsonReporter)
+                semanticTokensProviderJson, nullLspJsonReporter)
             ? Either2<SemanticTokensOptions, SemanticTokensRegistrationOptions>.t1(
-                SemanticTokensOptions.fromJson(json['semanticTokensProvider']))
+                SemanticTokensOptions.fromJson(
+                    semanticTokensProviderJson as Map<String, Object?>))
             : (SemanticTokensRegistrationOptions.canParse(
-                    json['semanticTokensProvider'], nullLspJsonReporter)
-                ? Either2<SemanticTokensOptions,
-                        SemanticTokensRegistrationOptions>.t2(
+                    semanticTokensProviderJson, nullLspJsonReporter)
+                ? Either2<SemanticTokensOptions, SemanticTokensRegistrationOptions>.t2(
                     SemanticTokensRegistrationOptions.fromJson(
-                        json['semanticTokensProvider']))
-                : (throw '''${json['semanticTokensProvider']} was not one of (SemanticTokensOptions, SemanticTokensRegistrationOptions)''')));
-    final monikerProvider = json['monikerProvider'] == null
+                        semanticTokensProviderJson as Map<String, Object?>))
+                : (throw '''$semanticTokensProviderJson was not one of (SemanticTokensOptions, SemanticTokensRegistrationOptions)''')));
+    final monikerProviderJson = json['monikerProvider'];
+    final monikerProvider = monikerProviderJson == null
         ? null
-        : (json['monikerProvider'] is bool
+        : (monikerProviderJson is bool
             ? Either3<bool, MonikerOptions, MonikerRegistrationOptions>.t1(
-                json['monikerProvider'])
-            : (MonikerOptions.canParse(
-                    json['monikerProvider'], nullLspJsonReporter)
+                monikerProviderJson)
+            : (MonikerOptions.canParse(monikerProviderJson, nullLspJsonReporter)
                 ? Either3<bool, MonikerOptions, MonikerRegistrationOptions>.t2(
-                    MonikerOptions.fromJson(json['monikerProvider']))
+                    MonikerOptions.fromJson(
+                        monikerProviderJson as Map<String, Object?>))
                 : (MonikerRegistrationOptions.canParse(
-                        json['monikerProvider'], nullLspJsonReporter)
+                        monikerProviderJson, nullLspJsonReporter)
                     ? Either3<bool, MonikerOptions,
                             MonikerRegistrationOptions>.t3(
                         MonikerRegistrationOptions.fromJson(
-                            json['monikerProvider']))
-                    : (throw '''${json['monikerProvider']} was not one of (bool, MonikerOptions, MonikerRegistrationOptions)'''))));
-    final workspaceSymbolProvider = json['workspaceSymbolProvider'] == null
+                            monikerProviderJson as Map<String, Object?>))
+                    : (throw '''$monikerProviderJson was not one of (bool, MonikerOptions, MonikerRegistrationOptions)'''))));
+    final workspaceSymbolProviderJson = json['workspaceSymbolProvider'];
+    final workspaceSymbolProvider = workspaceSymbolProviderJson == null
         ? null
-        : (json['workspaceSymbolProvider'] is bool
+        : (workspaceSymbolProviderJson is bool
             ? Either2<bool, WorkspaceSymbolOptions>.t1(
-                json['workspaceSymbolProvider'])
+                workspaceSymbolProviderJson)
             : (WorkspaceSymbolOptions.canParse(
-                    json['workspaceSymbolProvider'], nullLspJsonReporter)
+                    workspaceSymbolProviderJson, nullLspJsonReporter)
                 ? Either2<bool, WorkspaceSymbolOptions>.t2(
                     WorkspaceSymbolOptions.fromJson(
-                        json['workspaceSymbolProvider']))
-                : (throw '''${json['workspaceSymbolProvider']} was not one of (bool, WorkspaceSymbolOptions)''')));
-    final workspace = json['workspace'] != null
-        ? ServerCapabilitiesWorkspace.fromJson(json['workspace'])
+                        workspaceSymbolProviderJson as Map<String, Object?>))
+                : (throw '''$workspaceSymbolProviderJson was not one of (bool, WorkspaceSymbolOptions)''')));
+    final workspaceJson = json['workspace'];
+    final workspace = workspaceJson != null
+        ? ServerCapabilitiesWorkspace.fromJson(
+            workspaceJson as Map<String, Object?>)
         : null;
-    final experimental = json['experimental'];
+    final experimentalJson = json['experimental'];
+    final experimental = experimentalJson;
     return ServerCapabilities(
         textDocumentSync: textDocumentSync,
         completionProvider: completionProvider,
@@ -25170,7 +26177,7 @@
   final ExecuteCommandOptions? executeCommandProvider;
 
   /// Experimental server capabilities.
-  final dynamic experimental;
+  final Object? experimental;
 
   /// The server provides folding provider support.
   ///  @since 3.10.0
@@ -25234,8 +26241,8 @@
   /// The server provides workspace symbol support.
   final Either2<bool, WorkspaceSymbolOptions>? workspaceSymbolProvider;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (textDocumentSync != null) {
       __result['textDocumentSync'] = textDocumentSync;
     }
@@ -25329,14 +26336,13 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocumentSync');
       try {
-        if (obj['textDocumentSync'] != null &&
-            !((TextDocumentSyncOptions.canParse(
-                    obj['textDocumentSync'], reporter) ||
-                TextDocumentSyncKind.canParse(
-                    obj['textDocumentSync'], reporter)))) {
+        final textDocumentSync = obj['textDocumentSync'];
+        if (textDocumentSync != null &&
+            !((TextDocumentSyncOptions.canParse(textDocumentSync, reporter) ||
+                TextDocumentSyncKind.canParse(textDocumentSync, reporter)))) {
           reporter.reportError(
               'must be of type Either2<TextDocumentSyncOptions, TextDocumentSyncKind>');
           return false;
@@ -25346,9 +26352,9 @@
       }
       reporter.push('completionProvider');
       try {
-        if (obj['completionProvider'] != null &&
-            !(CompletionOptions.canParse(
-                obj['completionProvider'], reporter))) {
+        final completionProvider = obj['completionProvider'];
+        if (completionProvider != null &&
+            !(CompletionOptions.canParse(completionProvider, reporter))) {
           reporter.reportError('must be of type CompletionOptions');
           return false;
         }
@@ -25357,9 +26363,10 @@
       }
       reporter.push('hoverProvider');
       try {
-        if (obj['hoverProvider'] != null &&
-            !((obj['hoverProvider'] is bool ||
-                HoverOptions.canParse(obj['hoverProvider'], reporter)))) {
+        final hoverProvider = obj['hoverProvider'];
+        if (hoverProvider != null &&
+            !((hoverProvider is bool ||
+                HoverOptions.canParse(hoverProvider, reporter)))) {
           reporter.reportError('must be of type Either2<bool, HoverOptions>');
           return false;
         }
@@ -25368,9 +26375,9 @@
       }
       reporter.push('signatureHelpProvider');
       try {
-        if (obj['signatureHelpProvider'] != null &&
-            !(SignatureHelpOptions.canParse(
-                obj['signatureHelpProvider'], reporter))) {
+        final signatureHelpProvider = obj['signatureHelpProvider'];
+        if (signatureHelpProvider != null &&
+            !(SignatureHelpOptions.canParse(signatureHelpProvider, reporter))) {
           reporter.reportError('must be of type SignatureHelpOptions');
           return false;
         }
@@ -25379,12 +26386,12 @@
       }
       reporter.push('declarationProvider');
       try {
-        if (obj['declarationProvider'] != null &&
-            !((obj['declarationProvider'] is bool ||
-                DeclarationOptions.canParse(
-                    obj['declarationProvider'], reporter) ||
+        final declarationProvider = obj['declarationProvider'];
+        if (declarationProvider != null &&
+            !((declarationProvider is bool ||
+                DeclarationOptions.canParse(declarationProvider, reporter) ||
                 DeclarationRegistrationOptions.canParse(
-                    obj['declarationProvider'], reporter)))) {
+                    declarationProvider, reporter)))) {
           reporter.reportError(
               'must be of type Either3<bool, DeclarationOptions, DeclarationRegistrationOptions>');
           return false;
@@ -25394,10 +26401,10 @@
       }
       reporter.push('definitionProvider');
       try {
-        if (obj['definitionProvider'] != null &&
-            !((obj['definitionProvider'] is bool ||
-                DefinitionOptions.canParse(
-                    obj['definitionProvider'], reporter)))) {
+        final definitionProvider = obj['definitionProvider'];
+        if (definitionProvider != null &&
+            !((definitionProvider is bool ||
+                DefinitionOptions.canParse(definitionProvider, reporter)))) {
           reporter
               .reportError('must be of type Either2<bool, DefinitionOptions>');
           return false;
@@ -25407,12 +26414,13 @@
       }
       reporter.push('typeDefinitionProvider');
       try {
-        if (obj['typeDefinitionProvider'] != null &&
-            !((obj['typeDefinitionProvider'] is bool ||
+        final typeDefinitionProvider = obj['typeDefinitionProvider'];
+        if (typeDefinitionProvider != null &&
+            !((typeDefinitionProvider is bool ||
                 TypeDefinitionOptions.canParse(
-                    obj['typeDefinitionProvider'], reporter) ||
+                    typeDefinitionProvider, reporter) ||
                 TypeDefinitionRegistrationOptions.canParse(
-                    obj['typeDefinitionProvider'], reporter)))) {
+                    typeDefinitionProvider, reporter)))) {
           reporter.reportError(
               'must be of type Either3<bool, TypeDefinitionOptions, TypeDefinitionRegistrationOptions>');
           return false;
@@ -25422,12 +26430,13 @@
       }
       reporter.push('implementationProvider');
       try {
-        if (obj['implementationProvider'] != null &&
-            !((obj['implementationProvider'] is bool ||
+        final implementationProvider = obj['implementationProvider'];
+        if (implementationProvider != null &&
+            !((implementationProvider is bool ||
                 ImplementationOptions.canParse(
-                    obj['implementationProvider'], reporter) ||
+                    implementationProvider, reporter) ||
                 ImplementationRegistrationOptions.canParse(
-                    obj['implementationProvider'], reporter)))) {
+                    implementationProvider, reporter)))) {
           reporter.reportError(
               'must be of type Either3<bool, ImplementationOptions, ImplementationRegistrationOptions>');
           return false;
@@ -25437,10 +26446,10 @@
       }
       reporter.push('referencesProvider');
       try {
-        if (obj['referencesProvider'] != null &&
-            !((obj['referencesProvider'] is bool ||
-                ReferenceOptions.canParse(
-                    obj['referencesProvider'], reporter)))) {
+        final referencesProvider = obj['referencesProvider'];
+        if (referencesProvider != null &&
+            !((referencesProvider is bool ||
+                ReferenceOptions.canParse(referencesProvider, reporter)))) {
           reporter
               .reportError('must be of type Either2<bool, ReferenceOptions>');
           return false;
@@ -25450,10 +26459,11 @@
       }
       reporter.push('documentHighlightProvider');
       try {
-        if (obj['documentHighlightProvider'] != null &&
-            !((obj['documentHighlightProvider'] is bool ||
+        final documentHighlightProvider = obj['documentHighlightProvider'];
+        if (documentHighlightProvider != null &&
+            !((documentHighlightProvider is bool ||
                 DocumentHighlightOptions.canParse(
-                    obj['documentHighlightProvider'], reporter)))) {
+                    documentHighlightProvider, reporter)))) {
           reporter.reportError(
               'must be of type Either2<bool, DocumentHighlightOptions>');
           return false;
@@ -25463,10 +26473,11 @@
       }
       reporter.push('documentSymbolProvider');
       try {
-        if (obj['documentSymbolProvider'] != null &&
-            !((obj['documentSymbolProvider'] is bool ||
+        final documentSymbolProvider = obj['documentSymbolProvider'];
+        if (documentSymbolProvider != null &&
+            !((documentSymbolProvider is bool ||
                 DocumentSymbolOptions.canParse(
-                    obj['documentSymbolProvider'], reporter)))) {
+                    documentSymbolProvider, reporter)))) {
           reporter.reportError(
               'must be of type Either2<bool, DocumentSymbolOptions>');
           return false;
@@ -25476,10 +26487,10 @@
       }
       reporter.push('codeActionProvider');
       try {
-        if (obj['codeActionProvider'] != null &&
-            !((obj['codeActionProvider'] is bool ||
-                CodeActionOptions.canParse(
-                    obj['codeActionProvider'], reporter)))) {
+        final codeActionProvider = obj['codeActionProvider'];
+        if (codeActionProvider != null &&
+            !((codeActionProvider is bool ||
+                CodeActionOptions.canParse(codeActionProvider, reporter)))) {
           reporter
               .reportError('must be of type Either2<bool, CodeActionOptions>');
           return false;
@@ -25489,8 +26500,9 @@
       }
       reporter.push('codeLensProvider');
       try {
-        if (obj['codeLensProvider'] != null &&
-            !(CodeLensOptions.canParse(obj['codeLensProvider'], reporter))) {
+        final codeLensProvider = obj['codeLensProvider'];
+        if (codeLensProvider != null &&
+            !(CodeLensOptions.canParse(codeLensProvider, reporter))) {
           reporter.reportError('must be of type CodeLensOptions');
           return false;
         }
@@ -25499,9 +26511,9 @@
       }
       reporter.push('documentLinkProvider');
       try {
-        if (obj['documentLinkProvider'] != null &&
-            !(DocumentLinkOptions.canParse(
-                obj['documentLinkProvider'], reporter))) {
+        final documentLinkProvider = obj['documentLinkProvider'];
+        if (documentLinkProvider != null &&
+            !(DocumentLinkOptions.canParse(documentLinkProvider, reporter))) {
           reporter.reportError('must be of type DocumentLinkOptions');
           return false;
         }
@@ -25510,11 +26522,12 @@
       }
       reporter.push('colorProvider');
       try {
-        if (obj['colorProvider'] != null &&
-            !((obj['colorProvider'] is bool ||
-                DocumentColorOptions.canParse(obj['colorProvider'], reporter) ||
+        final colorProvider = obj['colorProvider'];
+        if (colorProvider != null &&
+            !((colorProvider is bool ||
+                DocumentColorOptions.canParse(colorProvider, reporter) ||
                 DocumentColorRegistrationOptions.canParse(
-                    obj['colorProvider'], reporter)))) {
+                    colorProvider, reporter)))) {
           reporter.reportError(
               'must be of type Either3<bool, DocumentColorOptions, DocumentColorRegistrationOptions>');
           return false;
@@ -25524,10 +26537,11 @@
       }
       reporter.push('documentFormattingProvider');
       try {
-        if (obj['documentFormattingProvider'] != null &&
-            !((obj['documentFormattingProvider'] is bool ||
+        final documentFormattingProvider = obj['documentFormattingProvider'];
+        if (documentFormattingProvider != null &&
+            !((documentFormattingProvider is bool ||
                 DocumentFormattingOptions.canParse(
-                    obj['documentFormattingProvider'], reporter)))) {
+                    documentFormattingProvider, reporter)))) {
           reporter.reportError(
               'must be of type Either2<bool, DocumentFormattingOptions>');
           return false;
@@ -25537,10 +26551,12 @@
       }
       reporter.push('documentRangeFormattingProvider');
       try {
-        if (obj['documentRangeFormattingProvider'] != null &&
-            !((obj['documentRangeFormattingProvider'] is bool ||
+        final documentRangeFormattingProvider =
+            obj['documentRangeFormattingProvider'];
+        if (documentRangeFormattingProvider != null &&
+            !((documentRangeFormattingProvider is bool ||
                 DocumentRangeFormattingOptions.canParse(
-                    obj['documentRangeFormattingProvider'], reporter)))) {
+                    documentRangeFormattingProvider, reporter)))) {
           reporter.reportError(
               'must be of type Either2<bool, DocumentRangeFormattingOptions>');
           return false;
@@ -25550,9 +26566,11 @@
       }
       reporter.push('documentOnTypeFormattingProvider');
       try {
-        if (obj['documentOnTypeFormattingProvider'] != null &&
+        final documentOnTypeFormattingProvider =
+            obj['documentOnTypeFormattingProvider'];
+        if (documentOnTypeFormattingProvider != null &&
             !(DocumentOnTypeFormattingOptions.canParse(
-                obj['documentOnTypeFormattingProvider'], reporter))) {
+                documentOnTypeFormattingProvider, reporter))) {
           reporter
               .reportError('must be of type DocumentOnTypeFormattingOptions');
           return false;
@@ -25562,9 +26580,10 @@
       }
       reporter.push('renameProvider');
       try {
-        if (obj['renameProvider'] != null &&
-            !((obj['renameProvider'] is bool ||
-                RenameOptions.canParse(obj['renameProvider'], reporter)))) {
+        final renameProvider = obj['renameProvider'];
+        if (renameProvider != null &&
+            !((renameProvider is bool ||
+                RenameOptions.canParse(renameProvider, reporter)))) {
           reporter.reportError('must be of type Either2<bool, RenameOptions>');
           return false;
         }
@@ -25573,12 +26592,12 @@
       }
       reporter.push('foldingRangeProvider');
       try {
-        if (obj['foldingRangeProvider'] != null &&
-            !((obj['foldingRangeProvider'] is bool ||
-                FoldingRangeOptions.canParse(
-                    obj['foldingRangeProvider'], reporter) ||
+        final foldingRangeProvider = obj['foldingRangeProvider'];
+        if (foldingRangeProvider != null &&
+            !((foldingRangeProvider is bool ||
+                FoldingRangeOptions.canParse(foldingRangeProvider, reporter) ||
                 FoldingRangeRegistrationOptions.canParse(
-                    obj['foldingRangeProvider'], reporter)))) {
+                    foldingRangeProvider, reporter)))) {
           reporter.reportError(
               'must be of type Either3<bool, FoldingRangeOptions, FoldingRangeRegistrationOptions>');
           return false;
@@ -25588,9 +26607,10 @@
       }
       reporter.push('executeCommandProvider');
       try {
-        if (obj['executeCommandProvider'] != null &&
+        final executeCommandProvider = obj['executeCommandProvider'];
+        if (executeCommandProvider != null &&
             !(ExecuteCommandOptions.canParse(
-                obj['executeCommandProvider'], reporter))) {
+                executeCommandProvider, reporter))) {
           reporter.reportError('must be of type ExecuteCommandOptions');
           return false;
         }
@@ -25599,12 +26619,13 @@
       }
       reporter.push('selectionRangeProvider');
       try {
-        if (obj['selectionRangeProvider'] != null &&
-            !((obj['selectionRangeProvider'] is bool ||
+        final selectionRangeProvider = obj['selectionRangeProvider'];
+        if (selectionRangeProvider != null &&
+            !((selectionRangeProvider is bool ||
                 SelectionRangeOptions.canParse(
-                    obj['selectionRangeProvider'], reporter) ||
+                    selectionRangeProvider, reporter) ||
                 SelectionRangeRegistrationOptions.canParse(
-                    obj['selectionRangeProvider'], reporter)))) {
+                    selectionRangeProvider, reporter)))) {
           reporter.reportError(
               'must be of type Either3<bool, SelectionRangeOptions, SelectionRangeRegistrationOptions>');
           return false;
@@ -25614,12 +26635,13 @@
       }
       reporter.push('linkedEditingRangeProvider');
       try {
-        if (obj['linkedEditingRangeProvider'] != null &&
-            !((obj['linkedEditingRangeProvider'] is bool ||
+        final linkedEditingRangeProvider = obj['linkedEditingRangeProvider'];
+        if (linkedEditingRangeProvider != null &&
+            !((linkedEditingRangeProvider is bool ||
                 LinkedEditingRangeOptions.canParse(
-                    obj['linkedEditingRangeProvider'], reporter) ||
+                    linkedEditingRangeProvider, reporter) ||
                 LinkedEditingRangeRegistrationOptions.canParse(
-                    obj['linkedEditingRangeProvider'], reporter)))) {
+                    linkedEditingRangeProvider, reporter)))) {
           reporter.reportError(
               'must be of type Either3<bool, LinkedEditingRangeOptions, LinkedEditingRangeRegistrationOptions>');
           return false;
@@ -25629,12 +26651,13 @@
       }
       reporter.push('callHierarchyProvider');
       try {
-        if (obj['callHierarchyProvider'] != null &&
-            !((obj['callHierarchyProvider'] is bool ||
+        final callHierarchyProvider = obj['callHierarchyProvider'];
+        if (callHierarchyProvider != null &&
+            !((callHierarchyProvider is bool ||
                 CallHierarchyOptions.canParse(
-                    obj['callHierarchyProvider'], reporter) ||
+                    callHierarchyProvider, reporter) ||
                 CallHierarchyRegistrationOptions.canParse(
-                    obj['callHierarchyProvider'], reporter)))) {
+                    callHierarchyProvider, reporter)))) {
           reporter.reportError(
               'must be of type Either3<bool, CallHierarchyOptions, CallHierarchyRegistrationOptions>');
           return false;
@@ -25644,11 +26667,12 @@
       }
       reporter.push('semanticTokensProvider');
       try {
-        if (obj['semanticTokensProvider'] != null &&
+        final semanticTokensProvider = obj['semanticTokensProvider'];
+        if (semanticTokensProvider != null &&
             !((SemanticTokensOptions.canParse(
-                    obj['semanticTokensProvider'], reporter) ||
+                    semanticTokensProvider, reporter) ||
                 SemanticTokensRegistrationOptions.canParse(
-                    obj['semanticTokensProvider'], reporter)))) {
+                    semanticTokensProvider, reporter)))) {
           reporter.reportError(
               'must be of type Either2<SemanticTokensOptions, SemanticTokensRegistrationOptions>');
           return false;
@@ -25658,11 +26682,12 @@
       }
       reporter.push('monikerProvider');
       try {
-        if (obj['monikerProvider'] != null &&
-            !((obj['monikerProvider'] is bool ||
-                MonikerOptions.canParse(obj['monikerProvider'], reporter) ||
+        final monikerProvider = obj['monikerProvider'];
+        if (monikerProvider != null &&
+            !((monikerProvider is bool ||
+                MonikerOptions.canParse(monikerProvider, reporter) ||
                 MonikerRegistrationOptions.canParse(
-                    obj['monikerProvider'], reporter)))) {
+                    monikerProvider, reporter)))) {
           reporter.reportError(
               'must be of type Either3<bool, MonikerOptions, MonikerRegistrationOptions>');
           return false;
@@ -25672,10 +26697,11 @@
       }
       reporter.push('workspaceSymbolProvider');
       try {
-        if (obj['workspaceSymbolProvider'] != null &&
-            !((obj['workspaceSymbolProvider'] is bool ||
+        final workspaceSymbolProvider = obj['workspaceSymbolProvider'];
+        if (workspaceSymbolProvider != null &&
+            !((workspaceSymbolProvider is bool ||
                 WorkspaceSymbolOptions.canParse(
-                    obj['workspaceSymbolProvider'], reporter)))) {
+                    workspaceSymbolProvider, reporter)))) {
           reporter.reportError(
               'must be of type Either2<bool, WorkspaceSymbolOptions>');
           return false;
@@ -25685,9 +26711,9 @@
       }
       reporter.push('workspace');
       try {
-        if (obj['workspace'] != null &&
-            !(ServerCapabilitiesWorkspace.canParse(
-                obj['workspace'], reporter))) {
+        final workspace = obj['workspace'];
+        if (workspace != null &&
+            !(ServerCapabilitiesWorkspace.canParse(workspace, reporter))) {
           reporter.reportError('must be of type ServerCapabilitiesWorkspace');
           return false;
         }
@@ -25794,24 +26820,36 @@
       this.willRename,
       this.didDelete,
       this.willDelete});
-  static ServerCapabilitiesFileOperations fromJson(Map<String, dynamic> json) {
-    final didCreate = json['didCreate'] != null
-        ? FileOperationRegistrationOptions.fromJson(json['didCreate'])
+  static ServerCapabilitiesFileOperations fromJson(Map<String, Object?> json) {
+    final didCreateJson = json['didCreate'];
+    final didCreate = didCreateJson != null
+        ? FileOperationRegistrationOptions.fromJson(
+            didCreateJson as Map<String, Object?>)
         : null;
-    final willCreate = json['willCreate'] != null
-        ? FileOperationRegistrationOptions.fromJson(json['willCreate'])
+    final willCreateJson = json['willCreate'];
+    final willCreate = willCreateJson != null
+        ? FileOperationRegistrationOptions.fromJson(
+            willCreateJson as Map<String, Object?>)
         : null;
-    final didRename = json['didRename'] != null
-        ? FileOperationRegistrationOptions.fromJson(json['didRename'])
+    final didRenameJson = json['didRename'];
+    final didRename = didRenameJson != null
+        ? FileOperationRegistrationOptions.fromJson(
+            didRenameJson as Map<String, Object?>)
         : null;
-    final willRename = json['willRename'] != null
-        ? FileOperationRegistrationOptions.fromJson(json['willRename'])
+    final willRenameJson = json['willRename'];
+    final willRename = willRenameJson != null
+        ? FileOperationRegistrationOptions.fromJson(
+            willRenameJson as Map<String, Object?>)
         : null;
-    final didDelete = json['didDelete'] != null
-        ? FileOperationRegistrationOptions.fromJson(json['didDelete'])
+    final didDeleteJson = json['didDelete'];
+    final didDelete = didDeleteJson != null
+        ? FileOperationRegistrationOptions.fromJson(
+            didDeleteJson as Map<String, Object?>)
         : null;
-    final willDelete = json['willDelete'] != null
-        ? FileOperationRegistrationOptions.fromJson(json['willDelete'])
+    final willDeleteJson = json['willDelete'];
+    final willDelete = willDeleteJson != null
+        ? FileOperationRegistrationOptions.fromJson(
+            willDeleteJson as Map<String, Object?>)
         : null;
     return ServerCapabilitiesFileOperations(
         didCreate: didCreate,
@@ -25840,8 +26878,8 @@
   /// The server is interested in receiving willRenameFiles requests.
   final FileOperationRegistrationOptions? willRename;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (didCreate != null) {
       __result['didCreate'] = didCreate?.toJson();
     }
@@ -25864,12 +26902,12 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('didCreate');
       try {
-        if (obj['didCreate'] != null &&
-            !(FileOperationRegistrationOptions.canParse(
-                obj['didCreate'], reporter))) {
+        final didCreate = obj['didCreate'];
+        if (didCreate != null &&
+            !(FileOperationRegistrationOptions.canParse(didCreate, reporter))) {
           reporter
               .reportError('must be of type FileOperationRegistrationOptions');
           return false;
@@ -25879,9 +26917,10 @@
       }
       reporter.push('willCreate');
       try {
-        if (obj['willCreate'] != null &&
+        final willCreate = obj['willCreate'];
+        if (willCreate != null &&
             !(FileOperationRegistrationOptions.canParse(
-                obj['willCreate'], reporter))) {
+                willCreate, reporter))) {
           reporter
               .reportError('must be of type FileOperationRegistrationOptions');
           return false;
@@ -25891,9 +26930,9 @@
       }
       reporter.push('didRename');
       try {
-        if (obj['didRename'] != null &&
-            !(FileOperationRegistrationOptions.canParse(
-                obj['didRename'], reporter))) {
+        final didRename = obj['didRename'];
+        if (didRename != null &&
+            !(FileOperationRegistrationOptions.canParse(didRename, reporter))) {
           reporter
               .reportError('must be of type FileOperationRegistrationOptions');
           return false;
@@ -25903,9 +26942,10 @@
       }
       reporter.push('willRename');
       try {
-        if (obj['willRename'] != null &&
+        final willRename = obj['willRename'];
+        if (willRename != null &&
             !(FileOperationRegistrationOptions.canParse(
-                obj['willRename'], reporter))) {
+                willRename, reporter))) {
           reporter
               .reportError('must be of type FileOperationRegistrationOptions');
           return false;
@@ -25915,9 +26955,9 @@
       }
       reporter.push('didDelete');
       try {
-        if (obj['didDelete'] != null &&
-            !(FileOperationRegistrationOptions.canParse(
-                obj['didDelete'], reporter))) {
+        final didDelete = obj['didDelete'];
+        if (didDelete != null &&
+            !(FileOperationRegistrationOptions.canParse(didDelete, reporter))) {
           reporter
               .reportError('must be of type FileOperationRegistrationOptions');
           return false;
@@ -25927,9 +26967,10 @@
       }
       reporter.push('willDelete');
       try {
-        if (obj['willDelete'] != null &&
+        final willDelete = obj['willDelete'];
+        if (willDelete != null &&
             !(FileOperationRegistrationOptions.canParse(
-                obj['willDelete'], reporter))) {
+                willDelete, reporter))) {
           reporter
               .reportError('must be of type FileOperationRegistrationOptions');
           return false;
@@ -25981,12 +27022,16 @@
       ServerCapabilitiesWorkspace.fromJson);
 
   ServerCapabilitiesWorkspace({this.workspaceFolders, this.fileOperations});
-  static ServerCapabilitiesWorkspace fromJson(Map<String, dynamic> json) {
-    final workspaceFolders = json['workspaceFolders'] != null
-        ? WorkspaceFoldersServerCapabilities.fromJson(json['workspaceFolders'])
+  static ServerCapabilitiesWorkspace fromJson(Map<String, Object?> json) {
+    final workspaceFoldersJson = json['workspaceFolders'];
+    final workspaceFolders = workspaceFoldersJson != null
+        ? WorkspaceFoldersServerCapabilities.fromJson(
+            workspaceFoldersJson as Map<String, Object?>)
         : null;
-    final fileOperations = json['fileOperations'] != null
-        ? ServerCapabilitiesFileOperations.fromJson(json['fileOperations'])
+    final fileOperationsJson = json['fileOperations'];
+    final fileOperations = fileOperationsJson != null
+        ? ServerCapabilitiesFileOperations.fromJson(
+            fileOperationsJson as Map<String, Object?>)
         : null;
     return ServerCapabilitiesWorkspace(
         workspaceFolders: workspaceFolders, fileOperations: fileOperations);
@@ -26000,8 +27045,8 @@
   ///  @since 3.6.0
   final WorkspaceFoldersServerCapabilities? workspaceFolders;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workspaceFolders != null) {
       __result['workspaceFolders'] = workspaceFolders?.toJson();
     }
@@ -26012,12 +27057,13 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workspaceFolders');
       try {
-        if (obj['workspaceFolders'] != null &&
+        final workspaceFolders = obj['workspaceFolders'];
+        if (workspaceFolders != null &&
             !(WorkspaceFoldersServerCapabilities.canParse(
-                obj['workspaceFolders'], reporter))) {
+                workspaceFolders, reporter))) {
           reporter.reportError(
               'must be of type WorkspaceFoldersServerCapabilities');
           return false;
@@ -26027,9 +27073,10 @@
       }
       reporter.push('fileOperations');
       try {
-        if (obj['fileOperations'] != null &&
+        final fileOperations = obj['fileOperations'];
+        if (fileOperations != null &&
             !(ServerCapabilitiesFileOperations.canParse(
-                obj['fileOperations'], reporter))) {
+                fileOperations, reporter))) {
           reporter
               .reportError('must be of type ServerCapabilitiesFileOperations');
           return false;
@@ -26072,37 +27119,37 @@
       LspJsonHandler(SetTraceParams.canParse, SetTraceParams.fromJson);
 
   SetTraceParams({required this.value});
-  static SetTraceParams fromJson(Map<String, dynamic> json) {
-    final value = const {'off', 'message', 'verbose'}.contains(json['value'])
-        ? json['value']
-        : throw '''${json['value']} was not one of ('off', 'message', 'verbose')''';
+  static SetTraceParams fromJson(Map<String, Object?> json) {
+    final valueJson = json['value'];
+    final value = const {'off', 'message', 'verbose'}.contains(valueJson)
+        ? valueJson as String
+        : throw '''$valueJson was not one of ('off', 'message', 'verbose')''';
     return SetTraceParams(value: value);
   }
 
   /// The new value that should be assigned to the trace setting.
   final String value;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['value'] = value;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('value');
       try {
         if (!obj.containsKey('value')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['value'] == null) {
+        final value = obj['value'];
+        if (value == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['value'] == 'off' ||
-            obj['value'] == 'message' ||
-            obj['value'] == 'verbose'))) {
+        if (!((value == 'off' || value == 'message' || value == 'verbose'))) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -26143,33 +27190,35 @@
       ShowDocumentClientCapabilities.fromJson);
 
   ShowDocumentClientCapabilities({required this.support});
-  static ShowDocumentClientCapabilities fromJson(Map<String, dynamic> json) {
-    final support = json['support'];
+  static ShowDocumentClientCapabilities fromJson(Map<String, Object?> json) {
+    final supportJson = json['support'];
+    final support = supportJson as bool;
     return ShowDocumentClientCapabilities(support: support);
   }
 
   /// The client has support for the show document request.
   final bool support;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['support'] = support;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('support');
       try {
         if (!obj.containsKey('support')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['support'] == null) {
+        final support = obj['support'];
+        if (support == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['support'] is bool)) {
+        if (!(support is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -26211,12 +27260,17 @@
 
   ShowDocumentParams(
       {required this.uri, this.external, this.takeFocus, this.selection});
-  static ShowDocumentParams fromJson(Map<String, dynamic> json) {
-    final uri = json['uri'];
-    final external = json['external'];
-    final takeFocus = json['takeFocus'];
-    final selection =
-        json['selection'] != null ? Range.fromJson(json['selection']) : null;
+  static ShowDocumentParams fromJson(Map<String, Object?> json) {
+    final uriJson = json['uri'];
+    final uri = uriJson as String;
+    final externalJson = json['external'];
+    final external = externalJson as bool?;
+    final takeFocusJson = json['takeFocus'];
+    final takeFocus = takeFocusJson as bool?;
+    final selectionJson = json['selection'];
+    final selection = selectionJson != null
+        ? Range.fromJson(selectionJson as Map<String, Object?>)
+        : null;
     return ShowDocumentParams(
         uri: uri,
         external: external,
@@ -26242,8 +27296,8 @@
   /// The document uri to show.
   final String uri;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['uri'] = uri;
     if (external != null) {
       __result['external'] = external;
@@ -26258,18 +27312,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('uri');
       try {
         if (!obj.containsKey('uri')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['uri'] == null) {
+        final uri = obj['uri'];
+        if (uri == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['uri'] is String)) {
+        if (!(uri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -26278,7 +27333,8 @@
       }
       reporter.push('external');
       try {
-        if (obj['external'] != null && !(obj['external'] is bool)) {
+        final external = obj['external'];
+        if (external != null && !(external is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -26287,7 +27343,8 @@
       }
       reporter.push('takeFocus');
       try {
-        if (obj['takeFocus'] != null && !(obj['takeFocus'] is bool)) {
+        final takeFocus = obj['takeFocus'];
+        if (takeFocus != null && !(takeFocus is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -26296,8 +27353,8 @@
       }
       reporter.push('selection');
       try {
-        if (obj['selection'] != null &&
-            !(Range.canParse(obj['selection'], reporter))) {
+        final selection = obj['selection'];
+        if (selection != null && !(Range.canParse(selection, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -26345,33 +27402,35 @@
       LspJsonHandler(ShowDocumentResult.canParse, ShowDocumentResult.fromJson);
 
   ShowDocumentResult({required this.success});
-  static ShowDocumentResult fromJson(Map<String, dynamic> json) {
-    final success = json['success'];
+  static ShowDocumentResult fromJson(Map<String, Object?> json) {
+    final successJson = json['success'];
+    final success = successJson as bool;
     return ShowDocumentResult(success: success);
   }
 
   /// A boolean indicating if the show was successful.
   final bool success;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['success'] = success;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('success');
       try {
         if (!obj.containsKey('success')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['success'] == null) {
+        final success = obj['success'];
+        if (success == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['success'] is bool)) {
+        if (!(success is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -26410,9 +27469,11 @@
       LspJsonHandler(ShowMessageParams.canParse, ShowMessageParams.fromJson);
 
   ShowMessageParams({required this.type, required this.message});
-  static ShowMessageParams fromJson(Map<String, dynamic> json) {
-    final type = MessageType.fromJson(json['type']);
-    final message = json['message'];
+  static ShowMessageParams fromJson(Map<String, Object?> json) {
+    final typeJson = json['type'];
+    final type = MessageType.fromJson(typeJson as int);
+    final messageJson = json['message'];
+    final message = messageJson as String;
     return ShowMessageParams(type: type, message: message);
   }
 
@@ -26422,26 +27483,27 @@
   /// The message type.
   final MessageType type;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['type'] = type.toJson();
     __result['message'] = message;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('type');
       try {
         if (!obj.containsKey('type')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['type'] == null) {
+        final type = obj['type'];
+        if (type == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(MessageType.canParse(obj['type'], reporter))) {
+        if (!(MessageType.canParse(type, reporter))) {
           reporter.reportError('must be of type MessageType');
           return false;
         }
@@ -26454,11 +27516,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['message'] == null) {
+        final message = obj['message'];
+        if (message == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['message'] is String)) {
+        if (!(message is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -26500,10 +27563,11 @@
 
   ShowMessageRequestClientCapabilities({this.messageActionItem});
   static ShowMessageRequestClientCapabilities fromJson(
-      Map<String, dynamic> json) {
-    final messageActionItem = json['messageActionItem'] != null
+      Map<String, Object?> json) {
+    final messageActionItemJson = json['messageActionItem'];
+    final messageActionItem = messageActionItemJson != null
         ? ShowMessageRequestClientCapabilitiesMessageActionItem.fromJson(
-            json['messageActionItem'])
+            messageActionItemJson as Map<String, Object?>)
         : null;
     return ShowMessageRequestClientCapabilities(
         messageActionItem: messageActionItem);
@@ -26513,8 +27577,8 @@
   final ShowMessageRequestClientCapabilitiesMessageActionItem?
       messageActionItem;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (messageActionItem != null) {
       __result['messageActionItem'] = messageActionItem?.toJson();
     }
@@ -26522,12 +27586,13 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('messageActionItem');
       try {
-        if (obj['messageActionItem'] != null &&
+        final messageActionItem = obj['messageActionItem'];
+        if (messageActionItem != null &&
             !(ShowMessageRequestClientCapabilitiesMessageActionItem.canParse(
-                obj['messageActionItem'], reporter))) {
+                messageActionItem, reporter))) {
           reporter.reportError(
               'must be of type ShowMessageRequestClientCapabilitiesMessageActionItem');
           return false;
@@ -26572,8 +27637,10 @@
   ShowMessageRequestClientCapabilitiesMessageActionItem(
       {this.additionalPropertiesSupport});
   static ShowMessageRequestClientCapabilitiesMessageActionItem fromJson(
-      Map<String, dynamic> json) {
-    final additionalPropertiesSupport = json['additionalPropertiesSupport'];
+      Map<String, Object?> json) {
+    final additionalPropertiesSupportJson = json['additionalPropertiesSupport'];
+    final additionalPropertiesSupport =
+        additionalPropertiesSupportJson as bool?;
     return ShowMessageRequestClientCapabilitiesMessageActionItem(
         additionalPropertiesSupport: additionalPropertiesSupport);
   }
@@ -26582,8 +27649,8 @@
   /// sent back to the server in the request's response.
   final bool? additionalPropertiesSupport;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (additionalPropertiesSupport != null) {
       __result['additionalPropertiesSupport'] = additionalPropertiesSupport;
     }
@@ -26591,11 +27658,12 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('additionalPropertiesSupport');
       try {
-        if (obj['additionalPropertiesSupport'] != null &&
-            !(obj['additionalPropertiesSupport'] is bool)) {
+        final additionalPropertiesSupport = obj['additionalPropertiesSupport'];
+        if (additionalPropertiesSupport != null &&
+            !(additionalPropertiesSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -26638,13 +27706,16 @@
 
   ShowMessageRequestParams(
       {required this.type, required this.message, this.actions});
-  static ShowMessageRequestParams fromJson(Map<String, dynamic> json) {
-    final type = MessageType.fromJson(json['type']);
-    final message = json['message'];
-    final actions = json['actions']
-        ?.map((item) => item != null ? MessageActionItem.fromJson(item) : null)
-        ?.cast<MessageActionItem>()
-        ?.toList();
+  static ShowMessageRequestParams fromJson(Map<String, Object?> json) {
+    final typeJson = json['type'];
+    final type = MessageType.fromJson(typeJson as int);
+    final messageJson = json['message'];
+    final message = messageJson as String;
+    final actionsJson = json['actions'];
+    final actions = (actionsJson as List<Object?>?)
+        ?.map(
+            (item) => MessageActionItem.fromJson(item as Map<String, Object?>))
+        .toList();
     return ShowMessageRequestParams(
         type: type, message: message, actions: actions);
   }
@@ -26658,8 +27729,8 @@
   /// The message type.
   final MessageType type;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['type'] = type.toJson();
     __result['message'] = message;
     if (actions != null) {
@@ -26669,18 +27740,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('type');
       try {
         if (!obj.containsKey('type')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['type'] == null) {
+        final type = obj['type'];
+        if (type == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(MessageType.canParse(obj['type'], reporter))) {
+        if (!(MessageType.canParse(type, reporter))) {
           reporter.reportError('must be of type MessageType');
           return false;
         }
@@ -26693,11 +27765,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['message'] == null) {
+        final message = obj['message'];
+        if (message == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['message'] is String)) {
+        if (!(message is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -26706,9 +27779,10 @@
       }
       reporter.push('actions');
       try {
-        if (obj['actions'] != null &&
-            !((obj['actions'] is List &&
-                (obj['actions'].every(
+        final actions = obj['actions'];
+        if (actions != null &&
+            !((actions is List &&
+                (actions.every(
                     (item) => MessageActionItem.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<MessageActionItem>');
           return false;
@@ -26757,13 +27831,16 @@
 
   SignatureHelp(
       {required this.signatures, this.activeSignature, this.activeParameter});
-  static SignatureHelp fromJson(Map<String, dynamic> json) {
-    final signatures = json['signatures']
-        ?.map((item) => SignatureInformation.fromJson(item))
-        ?.cast<SignatureInformation>()
-        ?.toList();
-    final activeSignature = json['activeSignature'];
-    final activeParameter = json['activeParameter'];
+  static SignatureHelp fromJson(Map<String, Object?> json) {
+    final signaturesJson = json['signatures'];
+    final signatures = (signaturesJson as List<Object?>)
+        .map((item) =>
+            SignatureInformation.fromJson(item as Map<String, Object?>))
+        .toList();
+    final activeSignatureJson = json['activeSignature'];
+    final activeSignature = activeSignatureJson as int?;
+    final activeParameterJson = json['activeParameter'];
+    final activeParameter = activeParameterJson as int?;
     return SignatureHelp(
         signatures: signatures,
         activeSignature: activeSignature,
@@ -26793,8 +27870,8 @@
   /// request should return `null`.
   final List<SignatureInformation> signatures;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['signatures'] = signatures.map((item) => item.toJson()).toList();
     if (activeSignature != null) {
       __result['activeSignature'] = activeSignature;
@@ -26806,19 +27883,20 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('signatures');
       try {
         if (!obj.containsKey('signatures')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['signatures'] == null) {
+        final signatures = obj['signatures'];
+        if (signatures == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['signatures'] is List &&
-            (obj['signatures'].every(
+        if (!((signatures is List &&
+            (signatures.every(
                 (item) => SignatureInformation.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<SignatureInformation>');
           return false;
@@ -26828,8 +27906,8 @@
       }
       reporter.push('activeSignature');
       try {
-        if (obj['activeSignature'] != null &&
-            !(obj['activeSignature'] is int)) {
+        final activeSignature = obj['activeSignature'];
+        if (activeSignature != null && !(activeSignature is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -26838,8 +27916,8 @@
       }
       reporter.push('activeParameter');
       try {
-        if (obj['activeParameter'] != null &&
-            !(obj['activeParameter'] is int)) {
+        final activeParameter = obj['activeParameter'];
+        if (activeParameter != null && !(activeParameter is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -26887,13 +27965,16 @@
       {this.dynamicRegistration,
       this.signatureInformation,
       this.contextSupport});
-  static SignatureHelpClientCapabilities fromJson(Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
-    final signatureInformation = json['signatureInformation'] != null
+  static SignatureHelpClientCapabilities fromJson(Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
+    final signatureInformationJson = json['signatureInformation'];
+    final signatureInformation = signatureInformationJson != null
         ? SignatureHelpClientCapabilitiesSignatureInformation.fromJson(
-            json['signatureInformation'])
+            signatureInformationJson as Map<String, Object?>)
         : null;
-    final contextSupport = json['contextSupport'];
+    final contextSupportJson = json['contextSupport'];
+    final contextSupport = contextSupportJson as bool?;
     return SignatureHelpClientCapabilities(
         dynamicRegistration: dynamicRegistration,
         signatureInformation: signatureInformation,
@@ -26915,8 +27996,8 @@
   final SignatureHelpClientCapabilitiesSignatureInformation?
       signatureInformation;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -26930,11 +28011,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -26943,9 +28024,10 @@
       }
       reporter.push('signatureInformation');
       try {
-        if (obj['signatureInformation'] != null &&
+        final signatureInformation = obj['signatureInformation'];
+        if (signatureInformation != null &&
             !(SignatureHelpClientCapabilitiesSignatureInformation.canParse(
-                obj['signatureInformation'], reporter))) {
+                signatureInformation, reporter))) {
           reporter.reportError(
               'must be of type SignatureHelpClientCapabilitiesSignatureInformation');
           return false;
@@ -26955,7 +28037,8 @@
       }
       reporter.push('contextSupport');
       try {
-        if (obj['contextSupport'] != null && !(obj['contextSupport'] is bool)) {
+        final contextSupport = obj['contextSupport'];
+        if (contextSupport != null && !(contextSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -27003,8 +28086,9 @@
   SignatureHelpClientCapabilitiesParameterInformation(
       {this.labelOffsetSupport});
   static SignatureHelpClientCapabilitiesParameterInformation fromJson(
-      Map<String, dynamic> json) {
-    final labelOffsetSupport = json['labelOffsetSupport'];
+      Map<String, Object?> json) {
+    final labelOffsetSupportJson = json['labelOffsetSupport'];
+    final labelOffsetSupport = labelOffsetSupportJson as bool?;
     return SignatureHelpClientCapabilitiesParameterInformation(
         labelOffsetSupport: labelOffsetSupport);
   }
@@ -27014,8 +28098,8 @@
   ///  @since 3.14.0
   final bool? labelOffsetSupport;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (labelOffsetSupport != null) {
       __result['labelOffsetSupport'] = labelOffsetSupport;
     }
@@ -27023,11 +28107,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('labelOffsetSupport');
       try {
-        if (obj['labelOffsetSupport'] != null &&
-            !(obj['labelOffsetSupport'] is bool)) {
+        final labelOffsetSupport = obj['labelOffsetSupport'];
+        if (labelOffsetSupport != null && !(labelOffsetSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -27074,16 +28158,18 @@
       this.parameterInformation,
       this.activeParameterSupport});
   static SignatureHelpClientCapabilitiesSignatureInformation fromJson(
-      Map<String, dynamic> json) {
-    final documentationFormat = json['documentationFormat']
-        ?.map((item) => item != null ? MarkupKind.fromJson(item) : null)
-        ?.cast<MarkupKind>()
-        ?.toList();
-    final parameterInformation = json['parameterInformation'] != null
+      Map<String, Object?> json) {
+    final documentationFormatJson = json['documentationFormat'];
+    final documentationFormat = (documentationFormatJson as List<Object?>?)
+        ?.map((item) => MarkupKind.fromJson(item as String))
+        .toList();
+    final parameterInformationJson = json['parameterInformation'];
+    final parameterInformation = parameterInformationJson != null
         ? SignatureHelpClientCapabilitiesParameterInformation.fromJson(
-            json['parameterInformation'])
+            parameterInformationJson as Map<String, Object?>)
         : null;
-    final activeParameterSupport = json['activeParameterSupport'];
+    final activeParameterSupportJson = json['activeParameterSupport'];
+    final activeParameterSupport = activeParameterSupportJson as bool?;
     return SignatureHelpClientCapabilitiesSignatureInformation(
         documentationFormat: documentationFormat,
         parameterInformation: parameterInformation,
@@ -27103,8 +28189,8 @@
   final SignatureHelpClientCapabilitiesParameterInformation?
       parameterInformation;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (documentationFormat != null) {
       __result['documentationFormat'] =
           documentationFormat?.map((item) => item.toJson()).toList();
@@ -27119,12 +28205,13 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentationFormat');
       try {
-        if (obj['documentationFormat'] != null &&
-            !((obj['documentationFormat'] is List &&
-                (obj['documentationFormat']
+        final documentationFormat = obj['documentationFormat'];
+        if (documentationFormat != null &&
+            !((documentationFormat is List &&
+                (documentationFormat
                     .every((item) => MarkupKind.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<MarkupKind>');
           return false;
@@ -27134,9 +28221,10 @@
       }
       reporter.push('parameterInformation');
       try {
-        if (obj['parameterInformation'] != null &&
+        final parameterInformation = obj['parameterInformation'];
+        if (parameterInformation != null &&
             !(SignatureHelpClientCapabilitiesParameterInformation.canParse(
-                obj['parameterInformation'], reporter))) {
+                parameterInformation, reporter))) {
           reporter.reportError(
               'must be of type SignatureHelpClientCapabilitiesParameterInformation');
           return false;
@@ -27146,8 +28234,9 @@
       }
       reporter.push('activeParameterSupport');
       try {
-        if (obj['activeParameterSupport'] != null &&
-            !(obj['activeParameterSupport'] is bool)) {
+        final activeParameterSupport = obj['activeParameterSupport'];
+        if (activeParameterSupport != null &&
+            !(activeParameterSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -27201,12 +28290,18 @@
       this.triggerCharacter,
       required this.isRetrigger,
       this.activeSignatureHelp});
-  static SignatureHelpContext fromJson(Map<String, dynamic> json) {
-    final triggerKind = SignatureHelpTriggerKind.fromJson(json['triggerKind']);
-    final triggerCharacter = json['triggerCharacter'];
-    final isRetrigger = json['isRetrigger'];
-    final activeSignatureHelp = json['activeSignatureHelp'] != null
-        ? SignatureHelp.fromJson(json['activeSignatureHelp'])
+  static SignatureHelpContext fromJson(Map<String, Object?> json) {
+    final triggerKindJson = json['triggerKind'];
+    final triggerKind =
+        SignatureHelpTriggerKind.fromJson(triggerKindJson as num);
+    final triggerCharacterJson = json['triggerCharacter'];
+    final triggerCharacter = triggerCharacterJson as String?;
+    final isRetriggerJson = json['isRetrigger'];
+    final isRetrigger = isRetriggerJson as bool;
+    final activeSignatureHelpJson = json['activeSignatureHelp'];
+    final activeSignatureHelp = activeSignatureHelpJson != null
+        ? SignatureHelp.fromJson(
+            activeSignatureHelpJson as Map<String, Object?>)
         : null;
     return SignatureHelpContext(
         triggerKind: triggerKind,
@@ -27237,8 +28332,8 @@
   /// Action that caused signature help to be triggered.
   final SignatureHelpTriggerKind triggerKind;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['triggerKind'] = triggerKind.toJson();
     if (triggerCharacter != null) {
       __result['triggerCharacter'] = triggerCharacter;
@@ -27251,19 +28346,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('triggerKind');
       try {
         if (!obj.containsKey('triggerKind')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['triggerKind'] == null) {
+        final triggerKind = obj['triggerKind'];
+        if (triggerKind == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(SignatureHelpTriggerKind.canParse(
-            obj['triggerKind'], reporter))) {
+        if (!(SignatureHelpTriggerKind.canParse(triggerKind, reporter))) {
           reporter.reportError('must be of type SignatureHelpTriggerKind');
           return false;
         }
@@ -27272,8 +28367,8 @@
       }
       reporter.push('triggerCharacter');
       try {
-        if (obj['triggerCharacter'] != null &&
-            !(obj['triggerCharacter'] is String)) {
+        final triggerCharacter = obj['triggerCharacter'];
+        if (triggerCharacter != null && !(triggerCharacter is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -27286,11 +28381,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['isRetrigger'] == null) {
+        final isRetrigger = obj['isRetrigger'];
+        if (isRetrigger == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['isRetrigger'] is bool)) {
+        if (!(isRetrigger is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -27299,8 +28395,9 @@
       }
       reporter.push('activeSignatureHelp');
       try {
-        if (obj['activeSignatureHelp'] != null &&
-            !(SignatureHelp.canParse(obj['activeSignatureHelp'], reporter))) {
+        final activeSignatureHelp = obj['activeSignatureHelp'];
+        if (activeSignatureHelp != null &&
+            !(SignatureHelp.canParse(activeSignatureHelp, reporter))) {
           reporter.reportError('must be of type SignatureHelp');
           return false;
         }
@@ -27349,19 +28446,20 @@
       {this.triggerCharacters,
       this.retriggerCharacters,
       this.workDoneProgress});
-  static SignatureHelpOptions fromJson(Map<String, dynamic> json) {
+  static SignatureHelpOptions fromJson(Map<String, Object?> json) {
     if (SignatureHelpRegistrationOptions.canParse(json, nullLspJsonReporter)) {
       return SignatureHelpRegistrationOptions.fromJson(json);
     }
-    final triggerCharacters = json['triggerCharacters']
-        ?.map((item) => item)
-        ?.cast<String>()
-        ?.toList();
-    final retriggerCharacters = json['retriggerCharacters']
-        ?.map((item) => item)
-        ?.cast<String>()
-        ?.toList();
-    final workDoneProgress = json['workDoneProgress'];
+    final triggerCharactersJson = json['triggerCharacters'];
+    final triggerCharacters = (triggerCharactersJson as List<Object?>?)
+        ?.map((item) => item as String)
+        .toList();
+    final retriggerCharactersJson = json['retriggerCharacters'];
+    final retriggerCharacters = (retriggerCharactersJson as List<Object?>?)
+        ?.map((item) => item as String)
+        .toList();
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return SignatureHelpOptions(
         triggerCharacters: triggerCharacters,
         retriggerCharacters: retriggerCharacters,
@@ -27379,8 +28477,8 @@
   final List<String>? triggerCharacters;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (triggerCharacters != null) {
       __result['triggerCharacters'] = triggerCharacters;
     }
@@ -27394,12 +28492,13 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('triggerCharacters');
       try {
-        if (obj['triggerCharacters'] != null &&
-            !((obj['triggerCharacters'] is List &&
-                (obj['triggerCharacters'].every((item) => item is String))))) {
+        final triggerCharacters = obj['triggerCharacters'];
+        if (triggerCharacters != null &&
+            !((triggerCharacters is List &&
+                (triggerCharacters.every((item) => item is String))))) {
           reporter.reportError('must be of type List<String>');
           return false;
         }
@@ -27408,10 +28507,10 @@
       }
       reporter.push('retriggerCharacters');
       try {
-        if (obj['retriggerCharacters'] != null &&
-            !((obj['retriggerCharacters'] is List &&
-                (obj['retriggerCharacters']
-                    .every((item) => item is String))))) {
+        final retriggerCharacters = obj['retriggerCharacters'];
+        if (retriggerCharacters != null &&
+            !((retriggerCharacters is List &&
+                (retriggerCharacters.every((item) => item is String))))) {
           reporter.reportError('must be of type List<String>');
           return false;
         }
@@ -27420,8 +28519,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -27472,19 +28571,24 @@
       required this.textDocument,
       required this.position,
       this.workDoneToken});
-  static SignatureHelpParams fromJson(Map<String, dynamic> json) {
-    final context = json['context'] != null
-        ? SignatureHelpContext.fromJson(json['context'])
+  static SignatureHelpParams fromJson(Map<String, Object?> json) {
+    final contextJson = json['context'];
+    final context = contextJson != null
+        ? SignatureHelpContext.fromJson(contextJson as Map<String, Object?>)
         : null;
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final position = Position.fromJson(json['position']);
-    final workDoneToken = json['workDoneToken'] == null
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final positionJson = json['position'];
+    final position = Position.fromJson(positionJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
     return SignatureHelpParams(
         context: context,
         textDocument: textDocument,
@@ -27507,8 +28611,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (context != null) {
       __result['context'] = context?.toJson();
     }
@@ -27521,11 +28625,12 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('context');
       try {
-        if (obj['context'] != null &&
-            !(SignatureHelpContext.canParse(obj['context'], reporter))) {
+        final context = obj['context'];
+        if (context != null &&
+            !(SignatureHelpContext.canParse(context, reporter))) {
           reporter.reportError('must be of type SignatureHelpContext');
           return false;
         }
@@ -27538,11 +28643,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -27555,11 +28661,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['position'] == null) {
+        final position = obj['position'];
+        if (position == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Position.canParse(obj['position'], reporter))) {
+        if (!(Position.canParse(position, reporter))) {
           reporter.reportError('must be of type Position');
           return false;
         }
@@ -27568,9 +28675,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -27625,20 +28732,21 @@
       this.triggerCharacters,
       this.retriggerCharacters,
       this.workDoneProgress});
-  static SignatureHelpRegistrationOptions fromJson(Map<String, dynamic> json) {
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final triggerCharacters = json['triggerCharacters']
-        ?.map((item) => item)
-        ?.cast<String>()
-        ?.toList();
-    final retriggerCharacters = json['retriggerCharacters']
-        ?.map((item) => item)
-        ?.cast<String>()
-        ?.toList();
-    final workDoneProgress = json['workDoneProgress'];
+  static SignatureHelpRegistrationOptions fromJson(Map<String, Object?> json) {
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final triggerCharactersJson = json['triggerCharacters'];
+    final triggerCharacters = (triggerCharactersJson as List<Object?>?)
+        ?.map((item) => item as String)
+        .toList();
+    final retriggerCharactersJson = json['retriggerCharacters'];
+    final retriggerCharacters = (retriggerCharactersJson as List<Object?>?)
+        ?.map((item) => item as String)
+        .toList();
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return SignatureHelpRegistrationOptions(
         documentSelector: documentSelector,
         triggerCharacters: triggerCharacters,
@@ -27661,8 +28769,8 @@
   final List<String>? triggerCharacters;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['documentSelector'] = documentSelector;
     if (triggerCharacters != null) {
       __result['triggerCharacters'] = triggerCharacters;
@@ -27677,16 +28785,17 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentSelector');
       try {
         if (!obj.containsKey('documentSelector')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -27696,9 +28805,10 @@
       }
       reporter.push('triggerCharacters');
       try {
-        if (obj['triggerCharacters'] != null &&
-            !((obj['triggerCharacters'] is List &&
-                (obj['triggerCharacters'].every((item) => item is String))))) {
+        final triggerCharacters = obj['triggerCharacters'];
+        if (triggerCharacters != null &&
+            !((triggerCharacters is List &&
+                (triggerCharacters.every((item) => item is String))))) {
           reporter.reportError('must be of type List<String>');
           return false;
         }
@@ -27707,10 +28817,10 @@
       }
       reporter.push('retriggerCharacters');
       try {
-        if (obj['retriggerCharacters'] != null &&
-            !((obj['retriggerCharacters'] is List &&
-                (obj['retriggerCharacters']
-                    .every((item) => item is String))))) {
+        final retriggerCharacters = obj['retriggerCharacters'];
+        if (retriggerCharacters != null &&
+            !((retriggerCharacters is List &&
+                (retriggerCharacters.every((item) => item is String))))) {
           reporter.reportError('must be of type List<String>');
           return false;
         }
@@ -27719,8 +28829,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -27809,23 +28919,25 @@
       this.documentation,
       this.parameters,
       this.activeParameter});
-  static SignatureInformation fromJson(Map<String, dynamic> json) {
-    final label = json['label'];
-    final documentation = json['documentation'] == null
+  static SignatureInformation fromJson(Map<String, Object?> json) {
+    final labelJson = json['label'];
+    final label = labelJson as String;
+    final documentationJson = json['documentation'];
+    final documentation = documentationJson == null
         ? null
-        : (json['documentation'] is String
-            ? Either2<String, MarkupContent>.t1(json['documentation'])
-            : (MarkupContent.canParse(
-                    json['documentation'], nullLspJsonReporter)
-                ? Either2<String, MarkupContent>.t2(
-                    MarkupContent.fromJson(json['documentation']))
-                : (throw '''${json['documentation']} was not one of (String, MarkupContent)''')));
-    final parameters = json['parameters']
-        ?.map(
-            (item) => item != null ? ParameterInformation.fromJson(item) : null)
-        ?.cast<ParameterInformation>()
-        ?.toList();
-    final activeParameter = json['activeParameter'];
+        : (documentationJson is String
+            ? Either2<String, MarkupContent>.t1(documentationJson)
+            : (MarkupContent.canParse(documentationJson, nullLspJsonReporter)
+                ? Either2<String, MarkupContent>.t2(MarkupContent.fromJson(
+                    documentationJson as Map<String, Object?>))
+                : (throw '''$documentationJson was not one of (String, MarkupContent)''')));
+    final parametersJson = json['parameters'];
+    final parameters = (parametersJson as List<Object?>?)
+        ?.map((item) =>
+            ParameterInformation.fromJson(item as Map<String, Object?>))
+        .toList();
+    final activeParameterJson = json['activeParameter'];
+    final activeParameter = activeParameterJson as int?;
     return SignatureInformation(
         label: label,
         documentation: documentation,
@@ -27849,8 +28961,8 @@
   /// The parameters of this signature.
   final List<ParameterInformation>? parameters;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['label'] = label;
     if (documentation != null) {
       __result['documentation'] = documentation;
@@ -27866,18 +28978,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('label');
       try {
         if (!obj.containsKey('label')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['label'] == null) {
+        final label = obj['label'];
+        if (label == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['label'] is String)) {
+        if (!(label is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -27886,9 +28999,10 @@
       }
       reporter.push('documentation');
       try {
-        if (obj['documentation'] != null &&
-            !((obj['documentation'] is String ||
-                MarkupContent.canParse(obj['documentation'], reporter)))) {
+        final documentation = obj['documentation'];
+        if (documentation != null &&
+            !((documentation is String ||
+                MarkupContent.canParse(documentation, reporter)))) {
           reporter
               .reportError('must be of type Either2<String, MarkupContent>');
           return false;
@@ -27898,9 +29012,10 @@
       }
       reporter.push('parameters');
       try {
-        if (obj['parameters'] != null &&
-            !((obj['parameters'] is List &&
-                (obj['parameters'].every((item) =>
+        final parameters = obj['parameters'];
+        if (parameters != null &&
+            !((parameters is List &&
+                (parameters.every((item) =>
                     ParameterInformation.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<ParameterInformation>');
           return false;
@@ -27910,8 +29025,8 @@
       }
       reporter.push('activeParameter');
       try {
-        if (obj['activeParameter'] != null &&
-            !(obj['activeParameter'] is int)) {
+        final activeParameter = obj['activeParameter'];
+        if (activeParameter != null && !(activeParameter is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -27959,7 +29074,7 @@
       StaticRegistrationOptions.canParse, StaticRegistrationOptions.fromJson);
 
   StaticRegistrationOptions({this.id});
-  static StaticRegistrationOptions fromJson(Map<String, dynamic> json) {
+  static StaticRegistrationOptions fromJson(Map<String, Object?> json) {
     if (DeclarationRegistrationOptions.canParse(json, nullLspJsonReporter)) {
       return DeclarationRegistrationOptions.fromJson(json);
     }
@@ -27988,7 +29103,8 @@
         json, nullLspJsonReporter)) {
       return LinkedEditingRangeRegistrationOptions.fromJson(json);
     }
-    final id = json['id'];
+    final idJson = json['id'];
+    final id = idJson as String?;
     return StaticRegistrationOptions(id: id);
   }
 
@@ -27996,8 +29112,8 @@
   /// request again. See also Registration#id.
   final String? id;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (id != null) {
       __result['id'] = id;
     }
@@ -28005,10 +29121,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('id');
       try {
-        if (obj['id'] != null && !(obj['id'] is String)) {
+        final id = obj['id'];
+        if (id != null && !(id is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -28055,16 +29172,21 @@
       this.deprecated,
       required this.location,
       this.containerName});
-  static SymbolInformation fromJson(Map<String, dynamic> json) {
-    final name = json['name'];
-    final kind = SymbolKind.fromJson(json['kind']);
-    final tags = json['tags']
-        ?.map((item) => item != null ? SymbolTag.fromJson(item) : null)
-        ?.cast<SymbolTag>()
-        ?.toList();
-    final deprecated = json['deprecated'];
-    final location = Location.fromJson(json['location']);
-    final containerName = json['containerName'];
+  static SymbolInformation fromJson(Map<String, Object?> json) {
+    final nameJson = json['name'];
+    final name = nameJson as String;
+    final kindJson = json['kind'];
+    final kind = SymbolKind.fromJson(kindJson as int);
+    final tagsJson = json['tags'];
+    final tags = (tagsJson as List<Object?>?)
+        ?.map((item) => SymbolTag.fromJson(item as num))
+        .toList();
+    final deprecatedJson = json['deprecated'];
+    final deprecated = deprecatedJson as bool?;
+    final locationJson = json['location'];
+    final location = Location.fromJson(locationJson as Map<String, Object?>);
+    final containerNameJson = json['containerName'];
+    final containerName = containerNameJson as String?;
     return SymbolInformation(
         name: name,
         kind: kind,
@@ -28105,8 +29227,8 @@
   ///  @since 3.16.0
   final List<SymbolTag>? tags;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['name'] = name;
     __result['kind'] = kind.toJson();
     if (tags != null) {
@@ -28123,18 +29245,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('name');
       try {
         if (!obj.containsKey('name')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['name'] == null) {
+        final name = obj['name'];
+        if (name == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['name'] is String)) {
+        if (!(name is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -28147,11 +29270,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['kind'] == null) {
+        final kind = obj['kind'];
+        if (kind == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(SymbolKind.canParse(obj['kind'], reporter))) {
+        if (!(SymbolKind.canParse(kind, reporter))) {
           reporter.reportError('must be of type SymbolKind');
           return false;
         }
@@ -28160,10 +29284,10 @@
       }
       reporter.push('tags');
       try {
-        if (obj['tags'] != null &&
-            !((obj['tags'] is List &&
-                (obj['tags']
-                    .every((item) => SymbolTag.canParse(item, reporter)))))) {
+        final tags = obj['tags'];
+        if (tags != null &&
+            !((tags is List &&
+                (tags.every((item) => SymbolTag.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<SymbolTag>');
           return false;
         }
@@ -28172,7 +29296,8 @@
       }
       reporter.push('deprecated');
       try {
-        if (obj['deprecated'] != null && !(obj['deprecated'] is bool)) {
+        final deprecated = obj['deprecated'];
+        if (deprecated != null && !(deprecated is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -28185,11 +29310,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['location'] == null) {
+        final location = obj['location'];
+        if (location == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Location.canParse(obj['location'], reporter))) {
+        if (!(Location.canParse(location, reporter))) {
           reporter.reportError('must be of type Location');
           return false;
         }
@@ -28198,7 +29324,8 @@
       }
       reporter.push('containerName');
       try {
-        if (obj['containerName'] != null && !(obj['containerName'] is String)) {
+        final containerName = obj['containerName'];
+        if (containerName != null && !(containerName is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -28328,12 +29455,13 @@
   TextDocumentChangeRegistrationOptions(
       {required this.syncKind, this.documentSelector});
   static TextDocumentChangeRegistrationOptions fromJson(
-      Map<String, dynamic> json) {
-    final syncKind = TextDocumentSyncKind.fromJson(json['syncKind']);
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
+      Map<String, Object?> json) {
+    final syncKindJson = json['syncKind'];
+    final syncKind = TextDocumentSyncKind.fromJson(syncKindJson as int);
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
     return TextDocumentChangeRegistrationOptions(
         syncKind: syncKind, documentSelector: documentSelector);
   }
@@ -28346,26 +29474,27 @@
   /// TextDocumentSyncKind.Incremental.
   final TextDocumentSyncKind syncKind;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['syncKind'] = syncKind.toJson();
     __result['documentSelector'] = documentSelector;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('syncKind');
       try {
         if (!obj.containsKey('syncKind')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['syncKind'] == null) {
+        final syncKind = obj['syncKind'];
+        if (syncKind == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentSyncKind.canParse(obj['syncKind'], reporter))) {
+        if (!(TextDocumentSyncKind.canParse(syncKind, reporter))) {
           reporter.reportError('must be of type TextDocumentSyncKind');
           return false;
         }
@@ -28378,9 +29507,10 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -28453,89 +29583,134 @@
       this.callHierarchy,
       this.semanticTokens,
       this.moniker});
-  static TextDocumentClientCapabilities fromJson(Map<String, dynamic> json) {
-    final synchronization = json['synchronization'] != null
-        ? TextDocumentSyncClientCapabilities.fromJson(json['synchronization'])
+  static TextDocumentClientCapabilities fromJson(Map<String, Object?> json) {
+    final synchronizationJson = json['synchronization'];
+    final synchronization = synchronizationJson != null
+        ? TextDocumentSyncClientCapabilities.fromJson(
+            synchronizationJson as Map<String, Object?>)
         : null;
-    final completion = json['completion'] != null
-        ? CompletionClientCapabilities.fromJson(json['completion'])
+    final completionJson = json['completion'];
+    final completion = completionJson != null
+        ? CompletionClientCapabilities.fromJson(
+            completionJson as Map<String, Object?>)
         : null;
-    final hover = json['hover'] != null
-        ? HoverClientCapabilities.fromJson(json['hover'])
+    final hoverJson = json['hover'];
+    final hover = hoverJson != null
+        ? HoverClientCapabilities.fromJson(hoverJson as Map<String, Object?>)
         : null;
-    final signatureHelp = json['signatureHelp'] != null
-        ? SignatureHelpClientCapabilities.fromJson(json['signatureHelp'])
+    final signatureHelpJson = json['signatureHelp'];
+    final signatureHelp = signatureHelpJson != null
+        ? SignatureHelpClientCapabilities.fromJson(
+            signatureHelpJson as Map<String, Object?>)
         : null;
-    final declaration = json['declaration'] != null
-        ? DeclarationClientCapabilities.fromJson(json['declaration'])
+    final declarationJson = json['declaration'];
+    final declaration = declarationJson != null
+        ? DeclarationClientCapabilities.fromJson(
+            declarationJson as Map<String, Object?>)
         : null;
-    final definition = json['definition'] != null
-        ? DefinitionClientCapabilities.fromJson(json['definition'])
+    final definitionJson = json['definition'];
+    final definition = definitionJson != null
+        ? DefinitionClientCapabilities.fromJson(
+            definitionJson as Map<String, Object?>)
         : null;
-    final typeDefinition = json['typeDefinition'] != null
-        ? TypeDefinitionClientCapabilities.fromJson(json['typeDefinition'])
+    final typeDefinitionJson = json['typeDefinition'];
+    final typeDefinition = typeDefinitionJson != null
+        ? TypeDefinitionClientCapabilities.fromJson(
+            typeDefinitionJson as Map<String, Object?>)
         : null;
-    final implementation = json['implementation'] != null
-        ? ImplementationClientCapabilities.fromJson(json['implementation'])
+    final implementationJson = json['implementation'];
+    final implementation = implementationJson != null
+        ? ImplementationClientCapabilities.fromJson(
+            implementationJson as Map<String, Object?>)
         : null;
-    final references = json['references'] != null
-        ? ReferenceClientCapabilities.fromJson(json['references'])
+    final referencesJson = json['references'];
+    final references = referencesJson != null
+        ? ReferenceClientCapabilities.fromJson(
+            referencesJson as Map<String, Object?>)
         : null;
-    final documentHighlight = json['documentHighlight'] != null
+    final documentHighlightJson = json['documentHighlight'];
+    final documentHighlight = documentHighlightJson != null
         ? DocumentHighlightClientCapabilities.fromJson(
-            json['documentHighlight'])
+            documentHighlightJson as Map<String, Object?>)
         : null;
-    final documentSymbol = json['documentSymbol'] != null
-        ? DocumentSymbolClientCapabilities.fromJson(json['documentSymbol'])
+    final documentSymbolJson = json['documentSymbol'];
+    final documentSymbol = documentSymbolJson != null
+        ? DocumentSymbolClientCapabilities.fromJson(
+            documentSymbolJson as Map<String, Object?>)
         : null;
-    final codeAction = json['codeAction'] != null
-        ? CodeActionClientCapabilities.fromJson(json['codeAction'])
+    final codeActionJson = json['codeAction'];
+    final codeAction = codeActionJson != null
+        ? CodeActionClientCapabilities.fromJson(
+            codeActionJson as Map<String, Object?>)
         : null;
-    final codeLens = json['codeLens'] != null
-        ? CodeLensClientCapabilities.fromJson(json['codeLens'])
+    final codeLensJson = json['codeLens'];
+    final codeLens = codeLensJson != null
+        ? CodeLensClientCapabilities.fromJson(
+            codeLensJson as Map<String, Object?>)
         : null;
-    final documentLink = json['documentLink'] != null
-        ? DocumentLinkClientCapabilities.fromJson(json['documentLink'])
+    final documentLinkJson = json['documentLink'];
+    final documentLink = documentLinkJson != null
+        ? DocumentLinkClientCapabilities.fromJson(
+            documentLinkJson as Map<String, Object?>)
         : null;
-    final colorProvider = json['colorProvider'] != null
-        ? DocumentColorClientCapabilities.fromJson(json['colorProvider'])
+    final colorProviderJson = json['colorProvider'];
+    final colorProvider = colorProviderJson != null
+        ? DocumentColorClientCapabilities.fromJson(
+            colorProviderJson as Map<String, Object?>)
         : null;
-    final formatting = json['formatting'] != null
-        ? DocumentFormattingClientCapabilities.fromJson(json['formatting'])
+    final formattingJson = json['formatting'];
+    final formatting = formattingJson != null
+        ? DocumentFormattingClientCapabilities.fromJson(
+            formattingJson as Map<String, Object?>)
         : null;
-    final rangeFormatting = json['rangeFormatting'] != null
+    final rangeFormattingJson = json['rangeFormatting'];
+    final rangeFormatting = rangeFormattingJson != null
         ? DocumentRangeFormattingClientCapabilities.fromJson(
-            json['rangeFormatting'])
+            rangeFormattingJson as Map<String, Object?>)
         : null;
-    final onTypeFormatting = json['onTypeFormatting'] != null
+    final onTypeFormattingJson = json['onTypeFormatting'];
+    final onTypeFormatting = onTypeFormattingJson != null
         ? DocumentOnTypeFormattingClientCapabilities.fromJson(
-            json['onTypeFormatting'])
+            onTypeFormattingJson as Map<String, Object?>)
         : null;
-    final rename = json['rename'] != null
-        ? RenameClientCapabilities.fromJson(json['rename'])
+    final renameJson = json['rename'];
+    final rename = renameJson != null
+        ? RenameClientCapabilities.fromJson(renameJson as Map<String, Object?>)
         : null;
-    final publishDiagnostics = json['publishDiagnostics'] != null
+    final publishDiagnosticsJson = json['publishDiagnostics'];
+    final publishDiagnostics = publishDiagnosticsJson != null
         ? PublishDiagnosticsClientCapabilities.fromJson(
-            json['publishDiagnostics'])
+            publishDiagnosticsJson as Map<String, Object?>)
         : null;
-    final foldingRange = json['foldingRange'] != null
-        ? FoldingRangeClientCapabilities.fromJson(json['foldingRange'])
+    final foldingRangeJson = json['foldingRange'];
+    final foldingRange = foldingRangeJson != null
+        ? FoldingRangeClientCapabilities.fromJson(
+            foldingRangeJson as Map<String, Object?>)
         : null;
-    final selectionRange = json['selectionRange'] != null
-        ? SelectionRangeClientCapabilities.fromJson(json['selectionRange'])
+    final selectionRangeJson = json['selectionRange'];
+    final selectionRange = selectionRangeJson != null
+        ? SelectionRangeClientCapabilities.fromJson(
+            selectionRangeJson as Map<String, Object?>)
         : null;
-    final linkedEditingRange = json['linkedEditingRange'] != null
+    final linkedEditingRangeJson = json['linkedEditingRange'];
+    final linkedEditingRange = linkedEditingRangeJson != null
         ? LinkedEditingRangeClientCapabilities.fromJson(
-            json['linkedEditingRange'])
+            linkedEditingRangeJson as Map<String, Object?>)
         : null;
-    final callHierarchy = json['callHierarchy'] != null
-        ? CallHierarchyClientCapabilities.fromJson(json['callHierarchy'])
+    final callHierarchyJson = json['callHierarchy'];
+    final callHierarchy = callHierarchyJson != null
+        ? CallHierarchyClientCapabilities.fromJson(
+            callHierarchyJson as Map<String, Object?>)
         : null;
-    final semanticTokens = json['semanticTokens'] != null
-        ? SemanticTokensClientCapabilities.fromJson(json['semanticTokens'])
+    final semanticTokensJson = json['semanticTokens'];
+    final semanticTokens = semanticTokensJson != null
+        ? SemanticTokensClientCapabilities.fromJson(
+            semanticTokensJson as Map<String, Object?>)
         : null;
-    final moniker = json['moniker'] != null
-        ? MonikerClientCapabilities.fromJson(json['moniker'])
+    final monikerJson = json['moniker'];
+    final moniker = monikerJson != null
+        ? MonikerClientCapabilities.fromJson(
+            monikerJson as Map<String, Object?>)
         : null;
     return TextDocumentClientCapabilities(
         synchronization: synchronization,
@@ -28655,8 +29830,8 @@
   ///  @since 3.6.0
   final TypeDefinitionClientCapabilities? typeDefinition;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (synchronization != null) {
       __result['synchronization'] = synchronization?.toJson();
     }
@@ -28739,12 +29914,13 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('synchronization');
       try {
-        if (obj['synchronization'] != null &&
+        final synchronization = obj['synchronization'];
+        if (synchronization != null &&
             !(TextDocumentSyncClientCapabilities.canParse(
-                obj['synchronization'], reporter))) {
+                synchronization, reporter))) {
           reporter.reportError(
               'must be of type TextDocumentSyncClientCapabilities');
           return false;
@@ -28754,9 +29930,9 @@
       }
       reporter.push('completion');
       try {
-        if (obj['completion'] != null &&
-            !(CompletionClientCapabilities.canParse(
-                obj['completion'], reporter))) {
+        final completion = obj['completion'];
+        if (completion != null &&
+            !(CompletionClientCapabilities.canParse(completion, reporter))) {
           reporter.reportError('must be of type CompletionClientCapabilities');
           return false;
         }
@@ -28765,8 +29941,9 @@
       }
       reporter.push('hover');
       try {
-        if (obj['hover'] != null &&
-            !(HoverClientCapabilities.canParse(obj['hover'], reporter))) {
+        final hover = obj['hover'];
+        if (hover != null &&
+            !(HoverClientCapabilities.canParse(hover, reporter))) {
           reporter.reportError('must be of type HoverClientCapabilities');
           return false;
         }
@@ -28775,9 +29952,10 @@
       }
       reporter.push('signatureHelp');
       try {
-        if (obj['signatureHelp'] != null &&
+        final signatureHelp = obj['signatureHelp'];
+        if (signatureHelp != null &&
             !(SignatureHelpClientCapabilities.canParse(
-                obj['signatureHelp'], reporter))) {
+                signatureHelp, reporter))) {
           reporter
               .reportError('must be of type SignatureHelpClientCapabilities');
           return false;
@@ -28787,9 +29965,9 @@
       }
       reporter.push('declaration');
       try {
-        if (obj['declaration'] != null &&
-            !(DeclarationClientCapabilities.canParse(
-                obj['declaration'], reporter))) {
+        final declaration = obj['declaration'];
+        if (declaration != null &&
+            !(DeclarationClientCapabilities.canParse(declaration, reporter))) {
           reporter.reportError('must be of type DeclarationClientCapabilities');
           return false;
         }
@@ -28798,9 +29976,9 @@
       }
       reporter.push('definition');
       try {
-        if (obj['definition'] != null &&
-            !(DefinitionClientCapabilities.canParse(
-                obj['definition'], reporter))) {
+        final definition = obj['definition'];
+        if (definition != null &&
+            !(DefinitionClientCapabilities.canParse(definition, reporter))) {
           reporter.reportError('must be of type DefinitionClientCapabilities');
           return false;
         }
@@ -28809,9 +29987,10 @@
       }
       reporter.push('typeDefinition');
       try {
-        if (obj['typeDefinition'] != null &&
+        final typeDefinition = obj['typeDefinition'];
+        if (typeDefinition != null &&
             !(TypeDefinitionClientCapabilities.canParse(
-                obj['typeDefinition'], reporter))) {
+                typeDefinition, reporter))) {
           reporter
               .reportError('must be of type TypeDefinitionClientCapabilities');
           return false;
@@ -28821,9 +30000,10 @@
       }
       reporter.push('implementation');
       try {
-        if (obj['implementation'] != null &&
+        final implementation = obj['implementation'];
+        if (implementation != null &&
             !(ImplementationClientCapabilities.canParse(
-                obj['implementation'], reporter))) {
+                implementation, reporter))) {
           reporter
               .reportError('must be of type ImplementationClientCapabilities');
           return false;
@@ -28833,9 +30013,9 @@
       }
       reporter.push('references');
       try {
-        if (obj['references'] != null &&
-            !(ReferenceClientCapabilities.canParse(
-                obj['references'], reporter))) {
+        final references = obj['references'];
+        if (references != null &&
+            !(ReferenceClientCapabilities.canParse(references, reporter))) {
           reporter.reportError('must be of type ReferenceClientCapabilities');
           return false;
         }
@@ -28844,9 +30024,10 @@
       }
       reporter.push('documentHighlight');
       try {
-        if (obj['documentHighlight'] != null &&
+        final documentHighlight = obj['documentHighlight'];
+        if (documentHighlight != null &&
             !(DocumentHighlightClientCapabilities.canParse(
-                obj['documentHighlight'], reporter))) {
+                documentHighlight, reporter))) {
           reporter.reportError(
               'must be of type DocumentHighlightClientCapabilities');
           return false;
@@ -28856,9 +30037,10 @@
       }
       reporter.push('documentSymbol');
       try {
-        if (obj['documentSymbol'] != null &&
+        final documentSymbol = obj['documentSymbol'];
+        if (documentSymbol != null &&
             !(DocumentSymbolClientCapabilities.canParse(
-                obj['documentSymbol'], reporter))) {
+                documentSymbol, reporter))) {
           reporter
               .reportError('must be of type DocumentSymbolClientCapabilities');
           return false;
@@ -28868,9 +30050,9 @@
       }
       reporter.push('codeAction');
       try {
-        if (obj['codeAction'] != null &&
-            !(CodeActionClientCapabilities.canParse(
-                obj['codeAction'], reporter))) {
+        final codeAction = obj['codeAction'];
+        if (codeAction != null &&
+            !(CodeActionClientCapabilities.canParse(codeAction, reporter))) {
           reporter.reportError('must be of type CodeActionClientCapabilities');
           return false;
         }
@@ -28879,8 +30061,9 @@
       }
       reporter.push('codeLens');
       try {
-        if (obj['codeLens'] != null &&
-            !(CodeLensClientCapabilities.canParse(obj['codeLens'], reporter))) {
+        final codeLens = obj['codeLens'];
+        if (codeLens != null &&
+            !(CodeLensClientCapabilities.canParse(codeLens, reporter))) {
           reporter.reportError('must be of type CodeLensClientCapabilities');
           return false;
         }
@@ -28889,9 +30072,10 @@
       }
       reporter.push('documentLink');
       try {
-        if (obj['documentLink'] != null &&
+        final documentLink = obj['documentLink'];
+        if (documentLink != null &&
             !(DocumentLinkClientCapabilities.canParse(
-                obj['documentLink'], reporter))) {
+                documentLink, reporter))) {
           reporter
               .reportError('must be of type DocumentLinkClientCapabilities');
           return false;
@@ -28901,9 +30085,10 @@
       }
       reporter.push('colorProvider');
       try {
-        if (obj['colorProvider'] != null &&
+        final colorProvider = obj['colorProvider'];
+        if (colorProvider != null &&
             !(DocumentColorClientCapabilities.canParse(
-                obj['colorProvider'], reporter))) {
+                colorProvider, reporter))) {
           reporter
               .reportError('must be of type DocumentColorClientCapabilities');
           return false;
@@ -28913,9 +30098,10 @@
       }
       reporter.push('formatting');
       try {
-        if (obj['formatting'] != null &&
+        final formatting = obj['formatting'];
+        if (formatting != null &&
             !(DocumentFormattingClientCapabilities.canParse(
-                obj['formatting'], reporter))) {
+                formatting, reporter))) {
           reporter.reportError(
               'must be of type DocumentFormattingClientCapabilities');
           return false;
@@ -28925,9 +30111,10 @@
       }
       reporter.push('rangeFormatting');
       try {
-        if (obj['rangeFormatting'] != null &&
+        final rangeFormatting = obj['rangeFormatting'];
+        if (rangeFormatting != null &&
             !(DocumentRangeFormattingClientCapabilities.canParse(
-                obj['rangeFormatting'], reporter))) {
+                rangeFormatting, reporter))) {
           reporter.reportError(
               'must be of type DocumentRangeFormattingClientCapabilities');
           return false;
@@ -28937,9 +30124,10 @@
       }
       reporter.push('onTypeFormatting');
       try {
-        if (obj['onTypeFormatting'] != null &&
+        final onTypeFormatting = obj['onTypeFormatting'];
+        if (onTypeFormatting != null &&
             !(DocumentOnTypeFormattingClientCapabilities.canParse(
-                obj['onTypeFormatting'], reporter))) {
+                onTypeFormatting, reporter))) {
           reporter.reportError(
               'must be of type DocumentOnTypeFormattingClientCapabilities');
           return false;
@@ -28949,8 +30137,9 @@
       }
       reporter.push('rename');
       try {
-        if (obj['rename'] != null &&
-            !(RenameClientCapabilities.canParse(obj['rename'], reporter))) {
+        final rename = obj['rename'];
+        if (rename != null &&
+            !(RenameClientCapabilities.canParse(rename, reporter))) {
           reporter.reportError('must be of type RenameClientCapabilities');
           return false;
         }
@@ -28959,9 +30148,10 @@
       }
       reporter.push('publishDiagnostics');
       try {
-        if (obj['publishDiagnostics'] != null &&
+        final publishDiagnostics = obj['publishDiagnostics'];
+        if (publishDiagnostics != null &&
             !(PublishDiagnosticsClientCapabilities.canParse(
-                obj['publishDiagnostics'], reporter))) {
+                publishDiagnostics, reporter))) {
           reporter.reportError(
               'must be of type PublishDiagnosticsClientCapabilities');
           return false;
@@ -28971,9 +30161,10 @@
       }
       reporter.push('foldingRange');
       try {
-        if (obj['foldingRange'] != null &&
+        final foldingRange = obj['foldingRange'];
+        if (foldingRange != null &&
             !(FoldingRangeClientCapabilities.canParse(
-                obj['foldingRange'], reporter))) {
+                foldingRange, reporter))) {
           reporter
               .reportError('must be of type FoldingRangeClientCapabilities');
           return false;
@@ -28983,9 +30174,10 @@
       }
       reporter.push('selectionRange');
       try {
-        if (obj['selectionRange'] != null &&
+        final selectionRange = obj['selectionRange'];
+        if (selectionRange != null &&
             !(SelectionRangeClientCapabilities.canParse(
-                obj['selectionRange'], reporter))) {
+                selectionRange, reporter))) {
           reporter
               .reportError('must be of type SelectionRangeClientCapabilities');
           return false;
@@ -28995,9 +30187,10 @@
       }
       reporter.push('linkedEditingRange');
       try {
-        if (obj['linkedEditingRange'] != null &&
+        final linkedEditingRange = obj['linkedEditingRange'];
+        if (linkedEditingRange != null &&
             !(LinkedEditingRangeClientCapabilities.canParse(
-                obj['linkedEditingRange'], reporter))) {
+                linkedEditingRange, reporter))) {
           reporter.reportError(
               'must be of type LinkedEditingRangeClientCapabilities');
           return false;
@@ -29007,9 +30200,10 @@
       }
       reporter.push('callHierarchy');
       try {
-        if (obj['callHierarchy'] != null &&
+        final callHierarchy = obj['callHierarchy'];
+        if (callHierarchy != null &&
             !(CallHierarchyClientCapabilities.canParse(
-                obj['callHierarchy'], reporter))) {
+                callHierarchy, reporter))) {
           reporter
               .reportError('must be of type CallHierarchyClientCapabilities');
           return false;
@@ -29019,9 +30213,10 @@
       }
       reporter.push('semanticTokens');
       try {
-        if (obj['semanticTokens'] != null &&
+        final semanticTokens = obj['semanticTokens'];
+        if (semanticTokens != null &&
             !(SemanticTokensClientCapabilities.canParse(
-                obj['semanticTokens'], reporter))) {
+                semanticTokens, reporter))) {
           reporter
               .reportError('must be of type SemanticTokensClientCapabilities');
           return false;
@@ -29031,8 +30226,9 @@
       }
       reporter.push('moniker');
       try {
-        if (obj['moniker'] != null &&
-            !(MonikerClientCapabilities.canParse(obj['moniker'], reporter))) {
+        final moniker = obj['moniker'];
+        if (moniker != null &&
+            !(MonikerClientCapabilities.canParse(moniker, reporter))) {
           reporter.reportError('must be of type MonikerClientCapabilities');
           return false;
         }
@@ -29124,10 +30320,13 @@
 
   TextDocumentContentChangeEvent1(
       {required this.range, this.rangeLength, required this.text});
-  static TextDocumentContentChangeEvent1 fromJson(Map<String, dynamic> json) {
-    final range = Range.fromJson(json['range']);
-    final rangeLength = json['rangeLength'];
-    final text = json['text'];
+  static TextDocumentContentChangeEvent1 fromJson(Map<String, Object?> json) {
+    final rangeJson = json['range'];
+    final range = Range.fromJson(rangeJson as Map<String, Object?>);
+    final rangeLengthJson = json['rangeLength'];
+    final rangeLength = rangeLengthJson as int?;
+    final textJson = json['text'];
+    final text = textJson as String;
     return TextDocumentContentChangeEvent1(
         range: range, rangeLength: rangeLength, text: text);
   }
@@ -29142,8 +30341,8 @@
   /// The new text for the provided range.
   final String text;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['range'] = range.toJson();
     if (rangeLength != null) {
       __result['rangeLength'] = rangeLength;
@@ -29153,18 +30352,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('range');
       try {
         if (!obj.containsKey('range')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['range'] == null) {
+        final range = obj['range'];
+        if (range == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['range'], reporter))) {
+        if (!(Range.canParse(range, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -29173,7 +30373,8 @@
       }
       reporter.push('rangeLength');
       try {
-        if (obj['rangeLength'] != null && !(obj['rangeLength'] is int)) {
+        final rangeLength = obj['rangeLength'];
+        if (rangeLength != null && !(rangeLength is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -29186,11 +30387,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['text'] == null) {
+        final text = obj['text'];
+        if (text == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['text'] is String)) {
+        if (!(text is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -29235,33 +30437,35 @@
       TextDocumentContentChangeEvent2.fromJson);
 
   TextDocumentContentChangeEvent2({required this.text});
-  static TextDocumentContentChangeEvent2 fromJson(Map<String, dynamic> json) {
-    final text = json['text'];
+  static TextDocumentContentChangeEvent2 fromJson(Map<String, Object?> json) {
+    final textJson = json['text'];
+    final text = textJson as String;
     return TextDocumentContentChangeEvent2(text: text);
   }
 
   /// The new text of the whole document.
   final String text;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['text'] = text;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('text');
       try {
         if (!obj.containsKey('text')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['text'] == null) {
+        final text = obj['text'];
+        if (text == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['text'] is String)) {
+        if (!(text is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -29300,22 +30504,23 @@
       LspJsonHandler(TextDocumentEdit.canParse, TextDocumentEdit.fromJson);
 
   TextDocumentEdit({required this.textDocument, required this.edits});
-  static TextDocumentEdit fromJson(Map<String, dynamic> json) {
-    final textDocument =
-        OptionalVersionedTextDocumentIdentifier.fromJson(json['textDocument']);
-    final edits = json['edits']
-        ?.map((item) => SnippetTextEdit.canParse(item, nullLspJsonReporter)
+  static TextDocumentEdit fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = OptionalVersionedTextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final editsJson = json['edits'];
+    final edits = (editsJson as List<Object?>)
+        .map((item) => SnippetTextEdit.canParse(item, nullLspJsonReporter)
             ? Either3<SnippetTextEdit, AnnotatedTextEdit, TextEdit>.t1(
-                SnippetTextEdit.fromJson(item))
+                SnippetTextEdit.fromJson(item as Map<String, Object?>))
             : (AnnotatedTextEdit.canParse(item, nullLspJsonReporter)
                 ? Either3<SnippetTextEdit, AnnotatedTextEdit, TextEdit>.t2(
-                    AnnotatedTextEdit.fromJson(item))
+                    AnnotatedTextEdit.fromJson(item as Map<String, Object?>))
                 : (TextEdit.canParse(item, nullLspJsonReporter)
                     ? Either3<SnippetTextEdit, AnnotatedTextEdit, TextEdit>.t3(
-                        TextEdit.fromJson(item))
+                        TextEdit.fromJson(item as Map<String, Object?>))
                     : (throw '''$item was not one of (SnippetTextEdit, AnnotatedTextEdit, TextEdit)'''))))
-        ?.cast<Either3<SnippetTextEdit, AnnotatedTextEdit, TextEdit>>()
-        ?.toList();
+        .toList();
     return TextDocumentEdit(textDocument: textDocument, edits: edits);
   }
 
@@ -29327,27 +30532,28 @@
   /// The text document to change.
   final OptionalVersionedTextDocumentIdentifier textDocument;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     __result['edits'] = edits;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
         if (!(OptionalVersionedTextDocumentIdentifier.canParse(
-            obj['textDocument'], reporter))) {
+            textDocument, reporter))) {
           reporter.reportError(
               'must be of type OptionalVersionedTextDocumentIdentifier');
           return false;
@@ -29361,15 +30567,15 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['edits'] == null) {
+        final edits = obj['edits'];
+        if (edits == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['edits'] is List &&
-            (obj['edits'].every((item) =>
-                (SnippetTextEdit.canParse(item, reporter) ||
-                    AnnotatedTextEdit.canParse(item, reporter) ||
-                    TextEdit.canParse(item, reporter))))))) {
+        if (!((edits is List &&
+            (edits.every((item) => (SnippetTextEdit.canParse(item, reporter) ||
+                AnnotatedTextEdit.canParse(item, reporter) ||
+                TextEdit.canParse(item, reporter))))))) {
           reporter.reportError(
               'must be of type List<Either3<SnippetTextEdit, AnnotatedTextEdit, TextEdit>>');
           return false;
@@ -29417,7 +30623,7 @@
       TextDocumentIdentifier.canParse, TextDocumentIdentifier.fromJson);
 
   TextDocumentIdentifier({required this.uri});
-  static TextDocumentIdentifier fromJson(Map<String, dynamic> json) {
+  static TextDocumentIdentifier fromJson(Map<String, Object?> json) {
     if (VersionedTextDocumentIdentifier.canParse(json, nullLspJsonReporter)) {
       return VersionedTextDocumentIdentifier.fromJson(json);
     }
@@ -29425,32 +30631,34 @@
         json, nullLspJsonReporter)) {
       return OptionalVersionedTextDocumentIdentifier.fromJson(json);
     }
-    final uri = json['uri'];
+    final uriJson = json['uri'];
+    final uri = uriJson as String;
     return TextDocumentIdentifier(uri: uri);
   }
 
   /// The text document's URI.
   final String uri;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['uri'] = uri;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('uri');
       try {
         if (!obj.containsKey('uri')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['uri'] == null) {
+        final uri = obj['uri'];
+        if (uri == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['uri'] is String)) {
+        if (!(uri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -29493,11 +30701,15 @@
       required this.languageId,
       required this.version,
       required this.text});
-  static TextDocumentItem fromJson(Map<String, dynamic> json) {
-    final uri = json['uri'];
-    final languageId = json['languageId'];
-    final version = json['version'];
-    final text = json['text'];
+  static TextDocumentItem fromJson(Map<String, Object?> json) {
+    final uriJson = json['uri'];
+    final uri = uriJson as String;
+    final languageIdJson = json['languageId'];
+    final languageId = languageIdJson as String;
+    final versionJson = json['version'];
+    final version = versionJson as int;
+    final textJson = json['text'];
+    final text = textJson as String;
     return TextDocumentItem(
         uri: uri, languageId: languageId, version: version, text: text);
   }
@@ -29515,8 +30727,8 @@
   /// including undo/redo).
   final int version;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['uri'] = uri;
     __result['languageId'] = languageId;
     __result['version'] = version;
@@ -29525,18 +30737,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('uri');
       try {
         if (!obj.containsKey('uri')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['uri'] == null) {
+        final uri = obj['uri'];
+        if (uri == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['uri'] is String)) {
+        if (!(uri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -29549,11 +30762,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['languageId'] == null) {
+        final languageId = obj['languageId'];
+        if (languageId == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['languageId'] is String)) {
+        if (!(languageId is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -29566,11 +30780,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['version'] == null) {
+        final version = obj['version'];
+        if (version == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['version'] is int)) {
+        if (!(version is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -29583,11 +30798,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['text'] == null) {
+        final text = obj['text'];
+        if (text == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['text'] is String)) {
+        if (!(text is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -29633,7 +30849,7 @@
 
   TextDocumentPositionParams(
       {required this.textDocument, required this.position});
-  static TextDocumentPositionParams fromJson(Map<String, dynamic> json) {
+  static TextDocumentPositionParams fromJson(Map<String, Object?> json) {
     if (CompletionParams.canParse(json, nullLspJsonReporter)) {
       return CompletionParams.fromJson(json);
     }
@@ -29679,8 +30895,11 @@
     if (MonikerParams.canParse(json, nullLspJsonReporter)) {
       return MonikerParams.fromJson(json);
     }
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final position = Position.fromJson(json['position']);
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final positionJson = json['position'];
+    final position = Position.fromJson(positionJson as Map<String, Object?>);
     return TextDocumentPositionParams(
         textDocument: textDocument, position: position);
   }
@@ -29691,26 +30910,27 @@
   /// The text document.
   final TextDocumentIdentifier textDocument;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     __result['position'] = position.toJson();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -29723,11 +30943,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['position'] == null) {
+        final position = obj['position'];
+        if (position == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Position.canParse(obj['position'], reporter))) {
+        if (!(Position.canParse(position, reporter))) {
           reporter.reportError('must be of type Position');
           return false;
         }
@@ -29771,7 +30992,7 @@
       TextDocumentRegistrationOptions.fromJson);
 
   TextDocumentRegistrationOptions({this.documentSelector});
-  static TextDocumentRegistrationOptions fromJson(Map<String, dynamic> json) {
+  static TextDocumentRegistrationOptions fromJson(Map<String, Object?> json) {
     if (TextDocumentChangeRegistrationOptions.canParse(
         json, nullLspJsonReporter)) {
       return TextDocumentChangeRegistrationOptions.fromJson(json);
@@ -29857,10 +31078,10 @@
     if (MonikerRegistrationOptions.canParse(json, nullLspJsonReporter)) {
       return MonikerRegistrationOptions.fromJson(json);
     }
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
     return TextDocumentRegistrationOptions(documentSelector: documentSelector);
   }
 
@@ -29868,23 +31089,24 @@
   /// null the document selector provided on the client side will be used.
   final List<DocumentFilter>? documentSelector;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['documentSelector'] = documentSelector;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentSelector');
       try {
         if (!obj.containsKey('documentSelector')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -29963,12 +31185,13 @@
   TextDocumentSaveRegistrationOptions(
       {this.includeText, this.documentSelector});
   static TextDocumentSaveRegistrationOptions fromJson(
-      Map<String, dynamic> json) {
-    final includeText = json['includeText'];
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
+      Map<String, Object?> json) {
+    final includeTextJson = json['includeText'];
+    final includeText = includeTextJson as bool?;
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
     return TextDocumentSaveRegistrationOptions(
         includeText: includeText, documentSelector: documentSelector);
   }
@@ -29980,8 +31203,8 @@
   /// The client is supposed to include the content on save.
   final bool? includeText;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (includeText != null) {
       __result['includeText'] = includeText;
     }
@@ -29990,10 +31213,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('includeText');
       try {
-        if (obj['includeText'] != null && !(obj['includeText'] is bool)) {
+        final includeText = obj['includeText'];
+        if (includeText != null && !(includeText is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -30006,9 +31230,10 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -30059,11 +31284,15 @@
       this.willSaveWaitUntil,
       this.didSave});
   static TextDocumentSyncClientCapabilities fromJson(
-      Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
-    final willSave = json['willSave'];
-    final willSaveWaitUntil = json['willSaveWaitUntil'];
-    final didSave = json['didSave'];
+      Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
+    final willSaveJson = json['willSave'];
+    final willSave = willSaveJson as bool?;
+    final willSaveWaitUntilJson = json['willSaveWaitUntil'];
+    final willSaveWaitUntil = willSaveWaitUntilJson as bool?;
+    final didSaveJson = json['didSave'];
+    final didSave = didSaveJson as bool?;
     return TextDocumentSyncClientCapabilities(
         dynamicRegistration: dynamicRegistration,
         willSave: willSave,
@@ -30085,8 +31314,8 @@
   /// saved.
   final bool? willSaveWaitUntil;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -30103,11 +31332,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -30116,7 +31345,8 @@
       }
       reporter.push('willSave');
       try {
-        if (obj['willSave'] != null && !(obj['willSave'] is bool)) {
+        final willSave = obj['willSave'];
+        if (willSave != null && !(willSave is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -30125,8 +31355,8 @@
       }
       reporter.push('willSaveWaitUntil');
       try {
-        if (obj['willSaveWaitUntil'] != null &&
-            !(obj['willSaveWaitUntil'] is bool)) {
+        final willSaveWaitUntil = obj['willSaveWaitUntil'];
+        if (willSaveWaitUntil != null && !(willSaveWaitUntil is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -30135,7 +31365,8 @@
       }
       reporter.push('didSave');
       try {
-        if (obj['didSave'] != null && !(obj['didSave'] is bool)) {
+        final didSave = obj['didSave'];
+        if (didSave != null && !(didSave is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -30220,21 +31451,26 @@
       this.willSave,
       this.willSaveWaitUntil,
       this.save});
-  static TextDocumentSyncOptions fromJson(Map<String, dynamic> json) {
-    final openClose = json['openClose'];
-    final change = json['change'] != null
-        ? TextDocumentSyncKind.fromJson(json['change'])
+  static TextDocumentSyncOptions fromJson(Map<String, Object?> json) {
+    final openCloseJson = json['openClose'];
+    final openClose = openCloseJson as bool?;
+    final changeJson = json['change'];
+    final change = changeJson != null
+        ? TextDocumentSyncKind.fromJson(changeJson as int)
         : null;
-    final willSave = json['willSave'];
-    final willSaveWaitUntil = json['willSaveWaitUntil'];
-    final save = json['save'] == null
+    final willSaveJson = json['willSave'];
+    final willSave = willSaveJson as bool?;
+    final willSaveWaitUntilJson = json['willSaveWaitUntil'];
+    final willSaveWaitUntil = willSaveWaitUntilJson as bool?;
+    final saveJson = json['save'];
+    final save = saveJson == null
         ? null
-        : (json['save'] is bool
-            ? Either2<bool, SaveOptions>.t1(json['save'])
-            : (SaveOptions.canParse(json['save'], nullLspJsonReporter)
+        : (saveJson is bool
+            ? Either2<bool, SaveOptions>.t1(saveJson)
+            : (SaveOptions.canParse(saveJson, nullLspJsonReporter)
                 ? Either2<bool, SaveOptions>.t2(
-                    SaveOptions.fromJson(json['save']))
-                : (throw '''${json['save']} was not one of (bool, SaveOptions)''')));
+                    SaveOptions.fromJson(saveJson as Map<String, Object?>))
+                : (throw '''$saveJson was not one of (bool, SaveOptions)''')));
     return TextDocumentSyncOptions(
         openClose: openClose,
         change: change,
@@ -30265,8 +31501,8 @@
   /// omitted the request should not be sent.
   final bool? willSaveWaitUntil;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (openClose != null) {
       __result['openClose'] = openClose;
     }
@@ -30286,10 +31522,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('openClose');
       try {
-        if (obj['openClose'] != null && !(obj['openClose'] is bool)) {
+        final openClose = obj['openClose'];
+        if (openClose != null && !(openClose is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -30298,8 +31535,9 @@
       }
       reporter.push('change');
       try {
-        if (obj['change'] != null &&
-            !(TextDocumentSyncKind.canParse(obj['change'], reporter))) {
+        final change = obj['change'];
+        if (change != null &&
+            !(TextDocumentSyncKind.canParse(change, reporter))) {
           reporter.reportError('must be of type TextDocumentSyncKind');
           return false;
         }
@@ -30308,7 +31546,8 @@
       }
       reporter.push('willSave');
       try {
-        if (obj['willSave'] != null && !(obj['willSave'] is bool)) {
+        final willSave = obj['willSave'];
+        if (willSave != null && !(willSave is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -30317,8 +31556,8 @@
       }
       reporter.push('willSaveWaitUntil');
       try {
-        if (obj['willSaveWaitUntil'] != null &&
-            !(obj['willSaveWaitUntil'] is bool)) {
+        final willSaveWaitUntil = obj['willSaveWaitUntil'];
+        if (willSaveWaitUntil != null && !(willSaveWaitUntil is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -30327,9 +31566,9 @@
       }
       reporter.push('save');
       try {
-        if (obj['save'] != null &&
-            !((obj['save'] is bool ||
-                SaveOptions.canParse(obj['save'], reporter)))) {
+        final save = obj['save'];
+        if (save != null &&
+            !((save is bool || SaveOptions.canParse(save, reporter)))) {
           reporter.reportError('must be of type Either2<bool, SaveOptions>');
           return false;
         }
@@ -30377,15 +31616,17 @@
       LspJsonHandler(TextEdit.canParse, TextEdit.fromJson);
 
   TextEdit({required this.range, required this.newText});
-  static TextEdit fromJson(Map<String, dynamic> json) {
+  static TextEdit fromJson(Map<String, Object?> json) {
     if (AnnotatedTextEdit.canParse(json, nullLspJsonReporter)) {
       return AnnotatedTextEdit.fromJson(json);
     }
     if (SnippetTextEdit.canParse(json, nullLspJsonReporter)) {
       return SnippetTextEdit.fromJson(json);
     }
-    final range = Range.fromJson(json['range']);
-    final newText = json['newText'];
+    final rangeJson = json['range'];
+    final range = Range.fromJson(rangeJson as Map<String, Object?>);
+    final newTextJson = json['newText'];
+    final newText = newTextJson as String;
     return TextEdit(range: range, newText: newText);
   }
 
@@ -30396,26 +31637,27 @@
   /// document create a range where start === end.
   final Range range;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['range'] = range.toJson();
     __result['newText'] = newText;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('range');
       try {
         if (!obj.containsKey('range')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['range'] == null) {
+        final range = obj['range'];
+        if (range == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Range.canParse(obj['range'], reporter))) {
+        if (!(Range.canParse(range, reporter))) {
           reporter.reportError('must be of type Range');
           return false;
         }
@@ -30428,11 +31670,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['newText'] == null) {
+        final newText = obj['newText'];
+        if (newText == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['newText'] is String)) {
+        if (!(newText is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -30496,9 +31739,11 @@
 
   TypeDefinitionClientCapabilities(
       {this.dynamicRegistration, this.linkSupport});
-  static TypeDefinitionClientCapabilities fromJson(Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
-    final linkSupport = json['linkSupport'];
+  static TypeDefinitionClientCapabilities fromJson(Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
+    final linkSupportJson = json['linkSupport'];
+    final linkSupport = linkSupportJson as bool?;
     return TypeDefinitionClientCapabilities(
         dynamicRegistration: dynamicRegistration, linkSupport: linkSupport);
   }
@@ -30512,8 +31757,8 @@
   ///  @since 3.14.0
   final bool? linkSupport;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -30524,11 +31769,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -30537,7 +31782,8 @@
       }
       reporter.push('linkSupport');
       try {
-        if (obj['linkSupport'] != null && !(obj['linkSupport'] is bool)) {
+        final linkSupport = obj['linkSupport'];
+        if (linkSupport != null && !(linkSupport is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -30579,18 +31825,19 @@
       TypeDefinitionOptions.canParse, TypeDefinitionOptions.fromJson);
 
   TypeDefinitionOptions({this.workDoneProgress});
-  static TypeDefinitionOptions fromJson(Map<String, dynamic> json) {
+  static TypeDefinitionOptions fromJson(Map<String, Object?> json) {
     if (TypeDefinitionRegistrationOptions.canParse(json, nullLspJsonReporter)) {
       return TypeDefinitionRegistrationOptions.fromJson(json);
     }
-    final workDoneProgress = json['workDoneProgress'];
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return TypeDefinitionOptions(workDoneProgress: workDoneProgress);
   }
 
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
     }
@@ -30598,11 +31845,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -30650,23 +31897,28 @@
       required this.position,
       this.workDoneToken,
       this.partialResultToken});
-  static TypeDefinitionParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final position = Position.fromJson(json['position']);
-    final workDoneToken = json['workDoneToken'] == null
+  static TypeDefinitionParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final positionJson = json['position'];
+    final position = Position.fromJson(positionJson as Map<String, Object?>);
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
-    final partialResultToken = json['partialResultToken'] == null
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
+    final partialResultTokenJson = json['partialResultToken'];
+    final partialResultToken = partialResultTokenJson == null
         ? null
-        : (json['partialResultToken'] is int
-            ? Either2<int, String>.t1(json['partialResultToken'])
-            : (json['partialResultToken'] is String
-                ? Either2<int, String>.t2(json['partialResultToken'])
-                : (throw '''${json['partialResultToken']} was not one of (int, String)''')));
+        : (partialResultTokenJson is int
+            ? Either2<int, String>.t1(partialResultTokenJson)
+            : (partialResultTokenJson is String
+                ? Either2<int, String>.t2(partialResultTokenJson)
+                : (throw '''$partialResultTokenJson was not one of (int, String)''')));
     return TypeDefinitionParams(
         textDocument: textDocument,
         position: position,
@@ -30687,8 +31939,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     __result['position'] = position.toJson();
     if (workDoneToken != null) {
@@ -30701,18 +31953,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -30725,11 +31978,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['position'] == null) {
+        final position = obj['position'];
+        if (position == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(Position.canParse(obj['position'], reporter))) {
+        if (!(Position.canParse(position, reporter))) {
           reporter.reportError('must be of type Position');
           return false;
         }
@@ -30738,9 +31992,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -30749,9 +32003,9 @@
       }
       reporter.push('partialResultToken');
       try {
-        if (obj['partialResultToken'] != null &&
-            !((obj['partialResultToken'] is int ||
-                obj['partialResultToken'] is String))) {
+        final partialResultToken = obj['partialResultToken'];
+        if (partialResultToken != null &&
+            !((partialResultToken is int || partialResultToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -30804,13 +32058,15 @@
 
   TypeDefinitionRegistrationOptions(
       {this.documentSelector, this.workDoneProgress, this.id});
-  static TypeDefinitionRegistrationOptions fromJson(Map<String, dynamic> json) {
-    final documentSelector = json['documentSelector']
-        ?.map((item) => item != null ? DocumentFilter.fromJson(item) : null)
-        ?.cast<DocumentFilter>()
-        ?.toList();
-    final workDoneProgress = json['workDoneProgress'];
-    final id = json['id'];
+  static TypeDefinitionRegistrationOptions fromJson(Map<String, Object?> json) {
+    final documentSelectorJson = json['documentSelector'];
+    final documentSelector = (documentSelectorJson as List<Object?>?)
+        ?.map((item) => DocumentFilter.fromJson(item as Map<String, Object?>))
+        .toList();
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
+    final idJson = json['id'];
+    final id = idJson as String?;
     return TypeDefinitionRegistrationOptions(
         documentSelector: documentSelector,
         workDoneProgress: workDoneProgress,
@@ -30826,8 +32082,8 @@
   final String? id;
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['documentSelector'] = documentSelector;
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
@@ -30839,16 +32095,17 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentSelector');
       try {
         if (!obj.containsKey('documentSelector')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['documentSelector'] != null &&
-            !((obj['documentSelector'] is List &&
-                (obj['documentSelector'].every(
+        final documentSelector = obj['documentSelector'];
+        if (documentSelector != null &&
+            !((documentSelector is List &&
+                (documentSelector.every(
                     (item) => DocumentFilter.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<DocumentFilter>');
           return false;
@@ -30858,8 +32115,8 @@
       }
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -30868,7 +32125,8 @@
       }
       reporter.push('id');
       try {
-        if (obj['id'] != null && !(obj['id'] is String)) {
+        final id = obj['id'];
+        if (id != null && !(id is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -30951,9 +32209,11 @@
       LspJsonHandler(Unregistration.canParse, Unregistration.fromJson);
 
   Unregistration({required this.id, required this.method});
-  static Unregistration fromJson(Map<String, dynamic> json) {
-    final id = json['id'];
-    final method = json['method'];
+  static Unregistration fromJson(Map<String, Object?> json) {
+    final idJson = json['id'];
+    final id = idJson as String;
+    final methodJson = json['method'];
+    final method = methodJson as String;
     return Unregistration(id: id, method: method);
   }
 
@@ -30964,26 +32224,27 @@
   /// The method / capability to unregister for.
   final String method;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['id'] = id;
     __result['method'] = method;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('id');
       try {
         if (!obj.containsKey('id')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['id'] == null) {
+        final id = obj['id'];
+        if (id == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['id'] is String)) {
+        if (!(id is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -30996,11 +32257,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['method'] == null) {
+        final method = obj['method'];
+        if (method == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['method'] is String)) {
+        if (!(method is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -31039,11 +32301,11 @@
       UnregistrationParams.canParse, UnregistrationParams.fromJson);
 
   UnregistrationParams({required this.unregisterations});
-  static UnregistrationParams fromJson(Map<String, dynamic> json) {
-    final unregisterations = json['unregisterations']
-        ?.map((item) => Unregistration.fromJson(item))
-        ?.cast<Unregistration>()
-        ?.toList();
+  static UnregistrationParams fromJson(Map<String, Object?> json) {
+    final unregisterationsJson = json['unregisterations'];
+    final unregisterations = (unregisterationsJson as List<Object?>)
+        .map((item) => Unregistration.fromJson(item as Map<String, Object?>))
+        .toList();
     return UnregistrationParams(unregisterations: unregisterations);
   }
 
@@ -31052,27 +32314,28 @@
   /// of the specification.
   final List<Unregistration> unregisterations;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['unregisterations'] =
         unregisterations.map((item) => item.toJson()).toList();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('unregisterations');
       try {
         if (!obj.containsKey('unregisterations')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['unregisterations'] == null) {
+        final unregisterations = obj['unregisterations'];
+        if (unregisterations == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['unregisterations'] is List &&
-            (obj['unregisterations']
+        if (!((unregisterations is List &&
+            (unregisterations
                 .every((item) => Unregistration.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<Unregistration>');
           return false;
@@ -31116,9 +32379,11 @@
       VersionedTextDocumentIdentifier.fromJson);
 
   VersionedTextDocumentIdentifier({required this.version, required this.uri});
-  static VersionedTextDocumentIdentifier fromJson(Map<String, dynamic> json) {
-    final version = json['version'];
-    final uri = json['uri'];
+  static VersionedTextDocumentIdentifier fromJson(Map<String, Object?> json) {
+    final versionJson = json['version'];
+    final version = versionJson as int;
+    final uriJson = json['uri'];
+    final uri = uriJson as String;
     return VersionedTextDocumentIdentifier(version: version, uri: uri);
   }
 
@@ -31131,26 +32396,27 @@
   /// including undo/redo. The number doesn't need to be consecutive.
   final int version;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['version'] = version;
     __result['uri'] = uri;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('version');
       try {
         if (!obj.containsKey('version')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['version'] == null) {
+        final version = obj['version'];
+        if (version == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['version'] is int)) {
+        if (!(version is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -31163,11 +32429,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['uri'] == null) {
+        final uri = obj['uri'];
+        if (uri == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['uri'] is String)) {
+        if (!(uri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -31239,9 +32506,12 @@
 
   WillSaveTextDocumentParams(
       {required this.textDocument, required this.reason});
-  static WillSaveTextDocumentParams fromJson(Map<String, dynamic> json) {
-    final textDocument = TextDocumentIdentifier.fromJson(json['textDocument']);
-    final reason = TextDocumentSaveReason.fromJson(json['reason']);
+  static WillSaveTextDocumentParams fromJson(Map<String, Object?> json) {
+    final textDocumentJson = json['textDocument'];
+    final textDocument = TextDocumentIdentifier.fromJson(
+        textDocumentJson as Map<String, Object?>);
+    final reasonJson = json['reason'];
+    final reason = TextDocumentSaveReason.fromJson(reasonJson as int);
     return WillSaveTextDocumentParams(
         textDocument: textDocument, reason: reason);
   }
@@ -31252,26 +32522,27 @@
   /// The document that will be saved.
   final TextDocumentIdentifier textDocument;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['textDocument'] = textDocument.toJson();
     __result['reason'] = reason.toJson();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('textDocument');
       try {
         if (!obj.containsKey('textDocument')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['textDocument'] == null) {
+        final textDocument = obj['textDocument'];
+        if (textDocument == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentIdentifier.canParse(obj['textDocument'], reporter))) {
+        if (!(TextDocumentIdentifier.canParse(textDocument, reporter))) {
           reporter.reportError('must be of type TextDocumentIdentifier');
           return false;
         }
@@ -31284,11 +32555,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['reason'] == null) {
+        final reason = obj['reason'];
+        if (reason == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(TextDocumentSaveReason.canParse(obj['reason'], reporter))) {
+        if (!(TextDocumentSaveReason.canParse(reason, reporter))) {
           reporter.reportError('must be of type TextDocumentSaveReason');
           return false;
         }
@@ -31339,12 +32611,17 @@
       throw 'kind may only be the literal \'begin\'';
     }
   }
-  static WorkDoneProgressBegin fromJson(Map<String, dynamic> json) {
-    final kind = json['kind'];
-    final title = json['title'];
-    final cancellable = json['cancellable'];
-    final message = json['message'];
-    final percentage = json['percentage'];
+  static WorkDoneProgressBegin fromJson(Map<String, Object?> json) {
+    final kindJson = json['kind'];
+    final kind = kindJson as String;
+    final titleJson = json['title'];
+    final title = titleJson as String;
+    final cancellableJson = json['cancellable'];
+    final cancellable = cancellableJson as bool?;
+    final messageJson = json['message'];
+    final message = messageJson as String?;
+    final percentageJson = json['percentage'];
+    final percentage = percentageJson as int?;
     return WorkDoneProgressBegin(
         kind: kind,
         title: title,
@@ -31380,8 +32657,8 @@
   /// Examples: "Indexing" or "Linking dependencies".
   final String title;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['kind'] = kind;
     __result['title'] = title;
     if (cancellable != null) {
@@ -31397,18 +32674,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('kind');
       try {
         if (!obj.containsKey('kind')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['kind'] == null) {
+        final kind = obj['kind'];
+        if (kind == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['kind'] == 'begin')) {
+        if (!(kind == 'begin')) {
           reporter.reportError('must be the literal \'begin\'');
           return false;
         }
@@ -31421,11 +32699,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['title'] == null) {
+        final title = obj['title'];
+        if (title == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['title'] is String)) {
+        if (!(title is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -31434,7 +32713,8 @@
       }
       reporter.push('cancellable');
       try {
-        if (obj['cancellable'] != null && !(obj['cancellable'] is bool)) {
+        final cancellable = obj['cancellable'];
+        if (cancellable != null && !(cancellable is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -31443,7 +32723,8 @@
       }
       reporter.push('message');
       try {
-        if (obj['message'] != null && !(obj['message'] is String)) {
+        final message = obj['message'];
+        if (message != null && !(message is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -31452,7 +32733,8 @@
       }
       reporter.push('percentage');
       try {
-        if (obj['percentage'] != null && !(obj['percentage'] is int)) {
+        final percentage = obj['percentage'];
+        if (percentage != null && !(percentage is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -31501,37 +32783,39 @@
       WorkDoneProgressCancelParams.fromJson);
 
   WorkDoneProgressCancelParams({required this.token});
-  static WorkDoneProgressCancelParams fromJson(Map<String, dynamic> json) {
-    final token = json['token'] is int
-        ? Either2<int, String>.t1(json['token'])
-        : (json['token'] is String
-            ? Either2<int, String>.t2(json['token'])
-            : (throw '''${json['token']} was not one of (int, String)'''));
+  static WorkDoneProgressCancelParams fromJson(Map<String, Object?> json) {
+    final tokenJson = json['token'];
+    final token = tokenJson is int
+        ? Either2<int, String>.t1(tokenJson)
+        : (tokenJson is String
+            ? Either2<int, String>.t2(tokenJson)
+            : (throw '''$tokenJson was not one of (int, String)'''));
     return WorkDoneProgressCancelParams(token: token);
   }
 
   /// The token to be used to report progress.
   final Either2<int, String> token;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['token'] = token;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('token');
       try {
         if (!obj.containsKey('token')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['token'] == null) {
+        final token = obj['token'];
+        if (token == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['token'] is int || obj['token'] is String))) {
+        if (!((token is int || token is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -31571,37 +32855,39 @@
       WorkDoneProgressCreateParams.fromJson);
 
   WorkDoneProgressCreateParams({required this.token});
-  static WorkDoneProgressCreateParams fromJson(Map<String, dynamic> json) {
-    final token = json['token'] is int
-        ? Either2<int, String>.t1(json['token'])
-        : (json['token'] is String
-            ? Either2<int, String>.t2(json['token'])
-            : (throw '''${json['token']} was not one of (int, String)'''));
+  static WorkDoneProgressCreateParams fromJson(Map<String, Object?> json) {
+    final tokenJson = json['token'];
+    final token = tokenJson is int
+        ? Either2<int, String>.t1(tokenJson)
+        : (tokenJson is String
+            ? Either2<int, String>.t2(tokenJson)
+            : (throw '''$tokenJson was not one of (int, String)'''));
     return WorkDoneProgressCreateParams(token: token);
   }
 
   /// The token to be used to report progress.
   final Either2<int, String> token;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['token'] = token;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('token');
       try {
         if (!obj.containsKey('token')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['token'] == null) {
+        final token = obj['token'];
+        if (token == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['token'] is int || obj['token'] is String))) {
+        if (!((token is int || token is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -31644,9 +32930,11 @@
       throw 'kind may only be the literal \'end\'';
     }
   }
-  static WorkDoneProgressEnd fromJson(Map<String, dynamic> json) {
-    final kind = json['kind'];
-    final message = json['message'];
+  static WorkDoneProgressEnd fromJson(Map<String, Object?> json) {
+    final kindJson = json['kind'];
+    final kind = kindJson as String;
+    final messageJson = json['message'];
+    final message = messageJson as String?;
     return WorkDoneProgressEnd(kind: kind, message: message);
   }
 
@@ -31656,8 +32944,8 @@
   /// of the operation.
   final String? message;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['kind'] = kind;
     if (message != null) {
       __result['message'] = message;
@@ -31666,18 +32954,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('kind');
       try {
         if (!obj.containsKey('kind')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['kind'] == null) {
+        final kind = obj['kind'];
+        if (kind == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['kind'] == 'end')) {
+        if (!(kind == 'end')) {
           reporter.reportError('must be the literal \'end\'');
           return false;
         }
@@ -31686,7 +32975,8 @@
       }
       reporter.push('message');
       try {
-        if (obj['message'] != null && !(obj['message'] is String)) {
+        final message = obj['message'];
+        if (message != null && !(message is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -31726,7 +33016,7 @@
       WorkDoneProgressOptions.canParse, WorkDoneProgressOptions.fromJson);
 
   WorkDoneProgressOptions({this.workDoneProgress});
-  static WorkDoneProgressOptions fromJson(Map<String, dynamic> json) {
+  static WorkDoneProgressOptions fromJson(Map<String, Object?> json) {
     if (WorkspaceSymbolOptions.canParse(json, nullLspJsonReporter)) {
       return WorkspaceSymbolOptions.fromJson(json);
     }
@@ -31802,14 +33092,15 @@
     if (MonikerOptions.canParse(json, nullLspJsonReporter)) {
       return MonikerOptions.fromJson(json);
     }
-    final workDoneProgress = json['workDoneProgress'];
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return WorkDoneProgressOptions(workDoneProgress: workDoneProgress);
   }
 
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
     }
@@ -31817,11 +33108,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -31860,7 +33151,7 @@
       WorkDoneProgressParams.canParse, WorkDoneProgressParams.fromJson);
 
   WorkDoneProgressParams({this.workDoneToken});
-  static WorkDoneProgressParams fromJson(Map<String, dynamic> json) {
+  static WorkDoneProgressParams fromJson(Map<String, Object?> json) {
     if (InitializeParams.canParse(json, nullLspJsonReporter)) {
       return InitializeParams.fromJson(json);
     }
@@ -31954,21 +33245,22 @@
     if (MonikerParams.canParse(json, nullLspJsonReporter)) {
       return MonikerParams.fromJson(json);
     }
-    final workDoneToken = json['workDoneToken'] == null
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
     return WorkDoneProgressParams(workDoneToken: workDoneToken);
   }
 
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workDoneToken != null) {
       __result['workDoneToken'] = workDoneToken;
     }
@@ -31976,12 +33268,12 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -32025,11 +33317,15 @@
       throw 'kind may only be the literal \'report\'';
     }
   }
-  static WorkDoneProgressReport fromJson(Map<String, dynamic> json) {
-    final kind = json['kind'];
-    final cancellable = json['cancellable'];
-    final message = json['message'];
-    final percentage = json['percentage'];
+  static WorkDoneProgressReport fromJson(Map<String, Object?> json) {
+    final kindJson = json['kind'];
+    final kind = kindJson as String;
+    final cancellableJson = json['cancellable'];
+    final cancellable = cancellableJson as bool?;
+    final messageJson = json['message'];
+    final message = messageJson as String?;
+    final percentageJson = json['percentage'];
+    final percentage = percentageJson as int?;
     return WorkDoneProgressReport(
         kind: kind,
         cancellable: cancellable,
@@ -32061,8 +33357,8 @@
   /// that are not following this rule. The value range is [0, 100]
   final int? percentage;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['kind'] = kind;
     if (cancellable != null) {
       __result['cancellable'] = cancellable;
@@ -32077,18 +33373,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('kind');
       try {
         if (!obj.containsKey('kind')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['kind'] == null) {
+        final kind = obj['kind'];
+        if (kind == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['kind'] == 'report')) {
+        if (!(kind == 'report')) {
           reporter.reportError('must be the literal \'report\'');
           return false;
         }
@@ -32097,7 +33394,8 @@
       }
       reporter.push('cancellable');
       try {
-        if (obj['cancellable'] != null && !(obj['cancellable'] is bool)) {
+        final cancellable = obj['cancellable'];
+        if (cancellable != null && !(cancellable is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -32106,7 +33404,8 @@
       }
       reporter.push('message');
       try {
-        if (obj['message'] != null && !(obj['message'] is String)) {
+        final message = obj['message'];
+        if (message != null && !(message is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -32115,7 +33414,8 @@
       }
       reporter.push('percentage');
       try {
-        if (obj['percentage'] != null && !(obj['percentage'] is int)) {
+        final percentage = obj['percentage'];
+        if (percentage != null && !(percentage is int)) {
           reporter.reportError('must be of type int');
           return false;
         }
@@ -32161,38 +33461,38 @@
       LspJsonHandler(WorkspaceEdit.canParse, WorkspaceEdit.fromJson);
 
   WorkspaceEdit({this.changes, this.documentChanges, this.changeAnnotations});
-  static WorkspaceEdit fromJson(Map<String, dynamic> json) {
-    final changes = json['changes']
-        ?.map((key, value) => MapEntry(
-            key,
-            value
-                ?.map((item) => item != null ? TextEdit.fromJson(item) : null)
-                ?.cast<TextEdit>()
-                ?.toList()))
-        ?.cast<String, List<TextEdit>>();
-    final documentChanges = json['documentChanges'] == null
+  static WorkspaceEdit fromJson(Map<String, Object?> json) {
+    final changesJson = json['changes'];
+    final changes = (changesJson as Map<Object, Object?>?)?.map((key, value) =>
+        MapEntry(
+            key as String,
+            (value as List<Object?>)
+                .map((item) => TextEdit.fromJson(item as Map<String, Object?>))
+                .toList()));
+    final documentChangesJson = json['documentChanges'];
+    final documentChanges = documentChangesJson == null
         ? null
-        : ((json['documentChanges'] is List && (json['documentChanges'].every((item) => TextDocumentEdit.canParse(item, nullLspJsonReporter))))
-            ? Either2<List<TextDocumentEdit>, List<Either4<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>>>.t1(json['documentChanges']
-                ?.map((item) => TextDocumentEdit.fromJson(item))
-                ?.cast<TextDocumentEdit>()
-                ?.toList())
-            : ((json['documentChanges'] is List &&
-                    (json['documentChanges'].every((item) => (TextDocumentEdit.canParse(item, nullLspJsonReporter) ||
-                        CreateFile.canParse(item, nullLspJsonReporter) ||
-                        RenameFile.canParse(item, nullLspJsonReporter) ||
-                        DeleteFile.canParse(item, nullLspJsonReporter)))))
-                ? Either2<List<TextDocumentEdit>, List<Either4<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>>>.t2(json['documentChanges']
-                    ?.map((item) => TextDocumentEdit.canParse(item, nullLspJsonReporter)
-                        ? Either4<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>.t1(TextDocumentEdit.fromJson(item))
-                        : (CreateFile.canParse(item, nullLspJsonReporter) ? Either4<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>.t2(CreateFile.fromJson(item)) : (RenameFile.canParse(item, nullLspJsonReporter) ? Either4<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>.t3(RenameFile.fromJson(item)) : (DeleteFile.canParse(item, nullLspJsonReporter) ? Either4<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>.t4(DeleteFile.fromJson(item)) : (throw '''$item was not one of (TextDocumentEdit, CreateFile, RenameFile, DeleteFile)''')))))
-                    ?.cast<Either4<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>>()
-                    ?.toList())
-                : (throw '''${json['documentChanges']} was not one of (List<TextDocumentEdit>, List<Either4<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>>)''')));
-    final changeAnnotations = json['changeAnnotations']
-        ?.map((key, value) => MapEntry(
-            key, value != null ? ChangeAnnotation.fromJson(value) : null))
-        ?.cast<String, ChangeAnnotation>();
+        : ((documentChangesJson is List &&
+                (documentChangesJson.every((item) =>
+                    TextDocumentEdit.canParse(item, nullLspJsonReporter))))
+            ? Either2<List<TextDocumentEdit>, List<Either4<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>>>.t1(
+                (documentChangesJson)
+                    .map((item) =>
+                        TextDocumentEdit.fromJson(item as Map<String, Object?>))
+                    .toList())
+            : ((documentChangesJson is List &&
+                    (documentChangesJson.every((item) =>
+                        (TextDocumentEdit.canParse(item, nullLspJsonReporter) ||
+                            CreateFile.canParse(item, nullLspJsonReporter) ||
+                            RenameFile.canParse(item, nullLspJsonReporter) ||
+                            DeleteFile.canParse(item, nullLspJsonReporter)))))
+                ? Either2<List<TextDocumentEdit>, List<Either4<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>>>.t2(
+                    (documentChangesJson).map((item) => TextDocumentEdit.canParse(item, nullLspJsonReporter) ? Either4<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>.t1(TextDocumentEdit.fromJson(item as Map<String, Object?>)) : (CreateFile.canParse(item, nullLspJsonReporter) ? Either4<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>.t2(CreateFile.fromJson(item as Map<String, Object?>)) : (RenameFile.canParse(item, nullLspJsonReporter) ? Either4<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>.t3(RenameFile.fromJson(item as Map<String, Object?>)) : (DeleteFile.canParse(item, nullLspJsonReporter) ? Either4<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>.t4(DeleteFile.fromJson(item as Map<String, Object?>)) : (throw '''$item was not one of (TextDocumentEdit, CreateFile, RenameFile, DeleteFile)'''))))).toList())
+                : (throw '''$documentChangesJson was not one of (List<TextDocumentEdit>, List<Either4<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>>)''')));
+    final changeAnnotationsJson = json['changeAnnotations'];
+    final changeAnnotations = (changeAnnotationsJson as Map<Object, Object?>?)
+        ?.map((key, value) => MapEntry(key as String,
+            ChangeAnnotation.fromJson(value as Map<String, Object?>)));
     return WorkspaceEdit(
         changes: changes,
         documentChanges: documentChanges,
@@ -32227,8 +33527,8 @@
           List<Either4<TextDocumentEdit, CreateFile, RenameFile, DeleteFile>>>?
       documentChanges;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (changes != null) {
       __result['changes'] = changes;
     }
@@ -32242,14 +33542,15 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('changes');
       try {
-        if (obj['changes'] != null &&
-            !((obj['changes'] is Map &&
-                (obj['changes'].keys.every((item) =>
+        final changes = obj['changes'];
+        if (changes != null &&
+            !((changes is Map &&
+                (changes.keys.every((item) =>
                     item is String &&
-                    obj['changes'].values.every((item) => (item is List &&
+                    changes.values.every((item) => (item is List &&
                         (item.every((item) =>
                             TextEdit.canParse(item, reporter)))))))))) {
           reporter.reportError('must be of type Map<String, List<TextEdit>>');
@@ -32260,12 +33561,13 @@
       }
       reporter.push('documentChanges');
       try {
-        if (obj['documentChanges'] != null &&
-            !(((obj['documentChanges'] is List &&
-                    (obj['documentChanges'].every((item) =>
+        final documentChanges = obj['documentChanges'];
+        if (documentChanges != null &&
+            !(((documentChanges is List &&
+                    (documentChanges.every((item) =>
                         TextDocumentEdit.canParse(item, reporter)))) ||
-                (obj['documentChanges'] is List &&
-                    (obj['documentChanges'].every((item) =>
+                (documentChanges is List &&
+                    (documentChanges.every((item) =>
                         (TextDocumentEdit.canParse(item, reporter) ||
                             CreateFile.canParse(item, reporter) ||
                             RenameFile.canParse(item, reporter) ||
@@ -32279,11 +33581,12 @@
       }
       reporter.push('changeAnnotations');
       try {
-        if (obj['changeAnnotations'] != null &&
-            !((obj['changeAnnotations'] is Map &&
-                (obj['changeAnnotations'].keys.every((item) =>
+        final changeAnnotations = obj['changeAnnotations'];
+        if (changeAnnotations != null &&
+            !((changeAnnotations is Map &&
+                (changeAnnotations.keys.every((item) =>
                     item is String &&
-                    obj['changeAnnotations'].values.every((item) =>
+                    changeAnnotations.values.every((item) =>
                         ChangeAnnotation.canParse(item, reporter))))))) {
           reporter.reportError('must be of type Map<String, ChangeAnnotation>');
           return false;
@@ -32338,20 +33641,23 @@
       this.failureHandling,
       this.normalizesLineEndings,
       this.changeAnnotationSupport});
-  static WorkspaceEditClientCapabilities fromJson(Map<String, dynamic> json) {
-    final documentChanges = json['documentChanges'];
-    final resourceOperations = json['resourceOperations']
-        ?.map((item) =>
-            item != null ? ResourceOperationKind.fromJson(item) : null)
-        ?.cast<ResourceOperationKind>()
-        ?.toList();
-    final failureHandling = json['failureHandling'] != null
-        ? FailureHandlingKind.fromJson(json['failureHandling'])
+  static WorkspaceEditClientCapabilities fromJson(Map<String, Object?> json) {
+    final documentChangesJson = json['documentChanges'];
+    final documentChanges = documentChangesJson as bool?;
+    final resourceOperationsJson = json['resourceOperations'];
+    final resourceOperations = (resourceOperationsJson as List<Object?>?)
+        ?.map((item) => ResourceOperationKind.fromJson(item as String))
+        .toList();
+    final failureHandlingJson = json['failureHandling'];
+    final failureHandling = failureHandlingJson != null
+        ? FailureHandlingKind.fromJson(failureHandlingJson as String)
         : null;
-    final normalizesLineEndings = json['normalizesLineEndings'];
-    final changeAnnotationSupport = json['changeAnnotationSupport'] != null
+    final normalizesLineEndingsJson = json['normalizesLineEndings'];
+    final normalizesLineEndings = normalizesLineEndingsJson as bool?;
+    final changeAnnotationSupportJson = json['changeAnnotationSupport'];
+    final changeAnnotationSupport = changeAnnotationSupportJson != null
         ? WorkspaceEditClientCapabilitiesChangeAnnotationSupport.fromJson(
-            json['changeAnnotationSupport'])
+            changeAnnotationSupportJson as Map<String, Object?>)
         : null;
     return WorkspaceEditClientCapabilities(
         documentChanges: documentChanges,
@@ -32386,8 +33692,8 @@
   ///  @since 3.13.0
   final List<ResourceOperationKind>? resourceOperations;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (documentChanges != null) {
       __result['documentChanges'] = documentChanges;
     }
@@ -32408,11 +33714,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('documentChanges');
       try {
-        if (obj['documentChanges'] != null &&
-            !(obj['documentChanges'] is bool)) {
+        final documentChanges = obj['documentChanges'];
+        if (documentChanges != null && !(documentChanges is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -32421,9 +33727,10 @@
       }
       reporter.push('resourceOperations');
       try {
-        if (obj['resourceOperations'] != null &&
-            !((obj['resourceOperations'] is List &&
-                (obj['resourceOperations'].every((item) =>
+        final resourceOperations = obj['resourceOperations'];
+        if (resourceOperations != null &&
+            !((resourceOperations is List &&
+                (resourceOperations.every((item) =>
                     ResourceOperationKind.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<ResourceOperationKind>');
           return false;
@@ -32433,8 +33740,9 @@
       }
       reporter.push('failureHandling');
       try {
-        if (obj['failureHandling'] != null &&
-            !(FailureHandlingKind.canParse(obj['failureHandling'], reporter))) {
+        final failureHandling = obj['failureHandling'];
+        if (failureHandling != null &&
+            !(FailureHandlingKind.canParse(failureHandling, reporter))) {
           reporter.reportError('must be of type FailureHandlingKind');
           return false;
         }
@@ -32443,8 +33751,8 @@
       }
       reporter.push('normalizesLineEndings');
       try {
-        if (obj['normalizesLineEndings'] != null &&
-            !(obj['normalizesLineEndings'] is bool)) {
+        final normalizesLineEndings = obj['normalizesLineEndings'];
+        if (normalizesLineEndings != null && !(normalizesLineEndings is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -32453,9 +33761,10 @@
       }
       reporter.push('changeAnnotationSupport');
       try {
-        if (obj['changeAnnotationSupport'] != null &&
+        final changeAnnotationSupport = obj['changeAnnotationSupport'];
+        if (changeAnnotationSupport != null &&
             !(WorkspaceEditClientCapabilitiesChangeAnnotationSupport.canParse(
-                obj['changeAnnotationSupport'], reporter))) {
+                changeAnnotationSupport, reporter))) {
           reporter.reportError(
               'must be of type WorkspaceEditClientCapabilitiesChangeAnnotationSupport');
           return false;
@@ -32508,8 +33817,9 @@
 
   WorkspaceEditClientCapabilitiesChangeAnnotationSupport({this.groupsOnLabel});
   static WorkspaceEditClientCapabilitiesChangeAnnotationSupport fromJson(
-      Map<String, dynamic> json) {
-    final groupsOnLabel = json['groupsOnLabel'];
+      Map<String, Object?> json) {
+    final groupsOnLabelJson = json['groupsOnLabel'];
+    final groupsOnLabel = groupsOnLabelJson as bool?;
     return WorkspaceEditClientCapabilitiesChangeAnnotationSupport(
         groupsOnLabel: groupsOnLabel);
   }
@@ -32519,8 +33829,8 @@
   /// node.
   final bool? groupsOnLabel;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (groupsOnLabel != null) {
       __result['groupsOnLabel'] = groupsOnLabel;
     }
@@ -32528,10 +33838,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('groupsOnLabel');
       try {
-        if (obj['groupsOnLabel'] != null && !(obj['groupsOnLabel'] is bool)) {
+        final groupsOnLabel = obj['groupsOnLabel'];
+        if (groupsOnLabel != null && !(groupsOnLabel is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -32572,9 +33883,11 @@
       LspJsonHandler(WorkspaceFolder.canParse, WorkspaceFolder.fromJson);
 
   WorkspaceFolder({required this.uri, required this.name});
-  static WorkspaceFolder fromJson(Map<String, dynamic> json) {
-    final uri = json['uri'];
-    final name = json['name'];
+  static WorkspaceFolder fromJson(Map<String, Object?> json) {
+    final uriJson = json['uri'];
+    final uri = uriJson as String;
+    final nameJson = json['name'];
+    final name = nameJson as String;
     return WorkspaceFolder(uri: uri, name: name);
   }
 
@@ -32585,26 +33898,27 @@
   /// The associated URI for this workspace folder.
   final String uri;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['uri'] = uri;
     __result['name'] = name;
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('uri');
       try {
         if (!obj.containsKey('uri')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['uri'] == null) {
+        final uri = obj['uri'];
+        if (uri == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['uri'] is String)) {
+        if (!(uri is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -32617,11 +33931,12 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['name'] == null) {
+        final name = obj['name'];
+        if (name == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['name'] is String)) {
+        if (!(name is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -32662,15 +33977,15 @@
       WorkspaceFoldersChangeEvent.fromJson);
 
   WorkspaceFoldersChangeEvent({required this.added, required this.removed});
-  static WorkspaceFoldersChangeEvent fromJson(Map<String, dynamic> json) {
-    final added = json['added']
-        ?.map((item) => WorkspaceFolder.fromJson(item))
-        ?.cast<WorkspaceFolder>()
-        ?.toList();
-    final removed = json['removed']
-        ?.map((item) => WorkspaceFolder.fromJson(item))
-        ?.cast<WorkspaceFolder>()
-        ?.toList();
+  static WorkspaceFoldersChangeEvent fromJson(Map<String, Object?> json) {
+    final addedJson = json['added'];
+    final added = (addedJson as List<Object?>)
+        .map((item) => WorkspaceFolder.fromJson(item as Map<String, Object?>))
+        .toList();
+    final removedJson = json['removed'];
+    final removed = (removedJson as List<Object?>)
+        .map((item) => WorkspaceFolder.fromJson(item as Map<String, Object?>))
+        .toList();
     return WorkspaceFoldersChangeEvent(added: added, removed: removed);
   }
 
@@ -32680,27 +33995,28 @@
   /// The array of the removed workspace folders
   final List<WorkspaceFolder> removed;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['added'] = added.map((item) => item.toJson()).toList();
     __result['removed'] = removed.map((item) => item.toJson()).toList();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('added');
       try {
         if (!obj.containsKey('added')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['added'] == null) {
+        final added = obj['added'];
+        if (added == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['added'] is List &&
-            (obj['added']
+        if (!((added is List &&
+            (added
                 .every((item) => WorkspaceFolder.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<WorkspaceFolder>');
           return false;
@@ -32714,12 +34030,13 @@
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['removed'] == null) {
+        final removed = obj['removed'];
+        if (removed == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['removed'] is List &&
-            (obj['removed']
+        if (!((removed is List &&
+            (removed
                 .every((item) => WorkspaceFolder.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<WorkspaceFolder>');
           return false;
@@ -32767,15 +34084,17 @@
   WorkspaceFoldersServerCapabilities(
       {this.supported, this.changeNotifications});
   static WorkspaceFoldersServerCapabilities fromJson(
-      Map<String, dynamic> json) {
-    final supported = json['supported'];
-    final changeNotifications = json['changeNotifications'] == null
+      Map<String, Object?> json) {
+    final supportedJson = json['supported'];
+    final supported = supportedJson as bool?;
+    final changeNotificationsJson = json['changeNotifications'];
+    final changeNotifications = changeNotificationsJson == null
         ? null
-        : (json['changeNotifications'] is String
-            ? Either2<String, bool>.t1(json['changeNotifications'])
-            : (json['changeNotifications'] is bool
-                ? Either2<String, bool>.t2(json['changeNotifications'])
-                : (throw '''${json['changeNotifications']} was not one of (String, bool)''')));
+        : (changeNotificationsJson is String
+            ? Either2<String, bool>.t1(changeNotificationsJson)
+            : (changeNotificationsJson is bool
+                ? Either2<String, bool>.t2(changeNotificationsJson)
+                : (throw '''$changeNotificationsJson was not one of (String, bool)''')));
     return WorkspaceFoldersServerCapabilities(
         supported: supported, changeNotifications: changeNotifications);
   }
@@ -32791,8 +34110,8 @@
   /// The server has support for workspace folders
   final bool? supported;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (supported != null) {
       __result['supported'] = supported;
     }
@@ -32803,10 +34122,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('supported');
       try {
-        if (obj['supported'] != null && !(obj['supported'] is bool)) {
+        final supported = obj['supported'];
+        if (supported != null && !(supported is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -32815,9 +34135,9 @@
       }
       reporter.push('changeNotifications');
       try {
-        if (obj['changeNotifications'] != null &&
-            !((obj['changeNotifications'] is String ||
-                obj['changeNotifications'] is bool))) {
+        final changeNotifications = obj['changeNotifications'];
+        if (changeNotifications != null &&
+            !((changeNotifications is String || changeNotifications is bool))) {
           reporter.reportError('must be of type Either2<String, bool>');
           return false;
         }
@@ -32862,15 +34182,18 @@
 
   WorkspaceSymbolClientCapabilities(
       {this.dynamicRegistration, this.symbolKind, this.tagSupport});
-  static WorkspaceSymbolClientCapabilities fromJson(Map<String, dynamic> json) {
-    final dynamicRegistration = json['dynamicRegistration'];
-    final symbolKind = json['symbolKind'] != null
+  static WorkspaceSymbolClientCapabilities fromJson(Map<String, Object?> json) {
+    final dynamicRegistrationJson = json['dynamicRegistration'];
+    final dynamicRegistration = dynamicRegistrationJson as bool?;
+    final symbolKindJson = json['symbolKind'];
+    final symbolKind = symbolKindJson != null
         ? WorkspaceSymbolClientCapabilitiesSymbolKind.fromJson(
-            json['symbolKind'])
+            symbolKindJson as Map<String, Object?>)
         : null;
-    final tagSupport = json['tagSupport'] != null
+    final tagSupportJson = json['tagSupport'];
+    final tagSupport = tagSupportJson != null
         ? WorkspaceSymbolClientCapabilitiesTagSupport.fromJson(
-            json['tagSupport'])
+            tagSupportJson as Map<String, Object?>)
         : null;
     return WorkspaceSymbolClientCapabilities(
         dynamicRegistration: dynamicRegistration,
@@ -32890,8 +34213,8 @@
   ///  @since 3.16.0
   final WorkspaceSymbolClientCapabilitiesTagSupport? tagSupport;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (dynamicRegistration != null) {
       __result['dynamicRegistration'] = dynamicRegistration;
     }
@@ -32905,11 +34228,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('dynamicRegistration');
       try {
-        if (obj['dynamicRegistration'] != null &&
-            !(obj['dynamicRegistration'] is bool)) {
+        final dynamicRegistration = obj['dynamicRegistration'];
+        if (dynamicRegistration != null && !(dynamicRegistration is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -32918,9 +34241,10 @@
       }
       reporter.push('symbolKind');
       try {
-        if (obj['symbolKind'] != null &&
+        final symbolKind = obj['symbolKind'];
+        if (symbolKind != null &&
             !(WorkspaceSymbolClientCapabilitiesSymbolKind.canParse(
-                obj['symbolKind'], reporter))) {
+                symbolKind, reporter))) {
           reporter.reportError(
               'must be of type WorkspaceSymbolClientCapabilitiesSymbolKind');
           return false;
@@ -32930,9 +34254,10 @@
       }
       reporter.push('tagSupport');
       try {
-        if (obj['tagSupport'] != null &&
+        final tagSupport = obj['tagSupport'];
+        if (tagSupport != null &&
             !(WorkspaceSymbolClientCapabilitiesTagSupport.canParse(
-                obj['tagSupport'], reporter))) {
+                tagSupport, reporter))) {
           reporter.reportError(
               'must be of type WorkspaceSymbolClientCapabilitiesTagSupport');
           return false;
@@ -32979,11 +34304,11 @@
 
   WorkspaceSymbolClientCapabilitiesSymbolKind({this.valueSet});
   static WorkspaceSymbolClientCapabilitiesSymbolKind fromJson(
-      Map<String, dynamic> json) {
-    final valueSet = json['valueSet']
-        ?.map((item) => item != null ? SymbolKind.fromJson(item) : null)
-        ?.cast<SymbolKind>()
-        ?.toList();
+      Map<String, Object?> json) {
+    final valueSetJson = json['valueSet'];
+    final valueSet = (valueSetJson as List<Object?>?)
+        ?.map((item) => SymbolKind.fromJson(item as int))
+        .toList();
     return WorkspaceSymbolClientCapabilitiesSymbolKind(valueSet: valueSet);
   }
 
@@ -32995,8 +34320,8 @@
   /// from `File` to `Array` as defined in the initial version of the protocol.
   final List<SymbolKind>? valueSet;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (valueSet != null) {
       __result['valueSet'] = valueSet?.map((item) => item.toJson()).toList();
     }
@@ -33004,12 +34329,13 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('valueSet');
       try {
-        if (obj['valueSet'] != null &&
-            !((obj['valueSet'] is List &&
-                (obj['valueSet']
+        final valueSet = obj['valueSet'];
+        if (valueSet != null &&
+            !((valueSet is List &&
+                (valueSet
                     .every((item) => SymbolKind.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<SymbolKind>');
           return false;
@@ -33054,38 +34380,38 @@
 
   WorkspaceSymbolClientCapabilitiesTagSupport({required this.valueSet});
   static WorkspaceSymbolClientCapabilitiesTagSupport fromJson(
-      Map<String, dynamic> json) {
-    final valueSet = json['valueSet']
-        ?.map((item) => SymbolTag.fromJson(item))
-        ?.cast<SymbolTag>()
-        ?.toList();
+      Map<String, Object?> json) {
+    final valueSetJson = json['valueSet'];
+    final valueSet = (valueSetJson as List<Object?>)
+        .map((item) => SymbolTag.fromJson(item as num))
+        .toList();
     return WorkspaceSymbolClientCapabilitiesTagSupport(valueSet: valueSet);
   }
 
   /// The tags supported by the client.
   final List<SymbolTag> valueSet;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['valueSet'] = valueSet.map((item) => item.toJson()).toList();
     return __result;
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('valueSet');
       try {
         if (!obj.containsKey('valueSet')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['valueSet'] == null) {
+        final valueSet = obj['valueSet'];
+        if (valueSet == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!((obj['valueSet'] is List &&
-            (obj['valueSet']
-                .every((item) => SymbolTag.canParse(item, reporter)))))) {
+        if (!((valueSet is List &&
+            (valueSet.every((item) => SymbolTag.canParse(item, reporter)))))) {
           reporter.reportError('must be of type List<SymbolTag>');
           return false;
         }
@@ -33127,19 +34453,20 @@
       WorkspaceSymbolOptions.canParse, WorkspaceSymbolOptions.fromJson);
 
   WorkspaceSymbolOptions({this.workDoneProgress});
-  static WorkspaceSymbolOptions fromJson(Map<String, dynamic> json) {
+  static WorkspaceSymbolOptions fromJson(Map<String, Object?> json) {
     if (WorkspaceSymbolRegistrationOptions.canParse(
         json, nullLspJsonReporter)) {
       return WorkspaceSymbolRegistrationOptions.fromJson(json);
     }
-    final workDoneProgress = json['workDoneProgress'];
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return WorkspaceSymbolOptions(workDoneProgress: workDoneProgress);
   }
 
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
     }
@@ -33147,11 +34474,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
@@ -33193,22 +34520,25 @@
 
   WorkspaceSymbolParams(
       {required this.query, this.workDoneToken, this.partialResultToken});
-  static WorkspaceSymbolParams fromJson(Map<String, dynamic> json) {
-    final query = json['query'];
-    final workDoneToken = json['workDoneToken'] == null
+  static WorkspaceSymbolParams fromJson(Map<String, Object?> json) {
+    final queryJson = json['query'];
+    final query = queryJson as String;
+    final workDoneTokenJson = json['workDoneToken'];
+    final workDoneToken = workDoneTokenJson == null
         ? null
-        : (json['workDoneToken'] is int
-            ? Either2<int, String>.t1(json['workDoneToken'])
-            : (json['workDoneToken'] is String
-                ? Either2<int, String>.t2(json['workDoneToken'])
-                : (throw '''${json['workDoneToken']} was not one of (int, String)''')));
-    final partialResultToken = json['partialResultToken'] == null
+        : (workDoneTokenJson is int
+            ? Either2<int, String>.t1(workDoneTokenJson)
+            : (workDoneTokenJson is String
+                ? Either2<int, String>.t2(workDoneTokenJson)
+                : (throw '''$workDoneTokenJson was not one of (int, String)''')));
+    final partialResultTokenJson = json['partialResultToken'];
+    final partialResultToken = partialResultTokenJson == null
         ? null
-        : (json['partialResultToken'] is int
-            ? Either2<int, String>.t1(json['partialResultToken'])
-            : (json['partialResultToken'] is String
-                ? Either2<int, String>.t2(json['partialResultToken'])
-                : (throw '''${json['partialResultToken']} was not one of (int, String)''')));
+        : (partialResultTokenJson is int
+            ? Either2<int, String>.t1(partialResultTokenJson)
+            : (partialResultTokenJson is String
+                ? Either2<int, String>.t2(partialResultTokenJson)
+                : (throw '''$partialResultTokenJson was not one of (int, String)''')));
     return WorkspaceSymbolParams(
         query: query,
         workDoneToken: workDoneToken,
@@ -33226,8 +34556,8 @@
   /// An optional token that a server can use to report work done progress.
   final Either2<int, String>? workDoneToken;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     __result['query'] = query;
     if (workDoneToken != null) {
       __result['workDoneToken'] = workDoneToken;
@@ -33239,18 +34569,19 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('query');
       try {
         if (!obj.containsKey('query')) {
           reporter.reportError('must not be undefined');
           return false;
         }
-        if (obj['query'] == null) {
+        final query = obj['query'];
+        if (query == null) {
           reporter.reportError('must not be null');
           return false;
         }
-        if (!(obj['query'] is String)) {
+        if (!(query is String)) {
           reporter.reportError('must be of type String');
           return false;
         }
@@ -33259,9 +34590,9 @@
       }
       reporter.push('workDoneToken');
       try {
-        if (obj['workDoneToken'] != null &&
-            !((obj['workDoneToken'] is int ||
-                obj['workDoneToken'] is String))) {
+        final workDoneToken = obj['workDoneToken'];
+        if (workDoneToken != null &&
+            !((workDoneToken is int || workDoneToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -33270,9 +34601,9 @@
       }
       reporter.push('partialResultToken');
       try {
-        if (obj['partialResultToken'] != null &&
-            !((obj['partialResultToken'] is int ||
-                obj['partialResultToken'] is String))) {
+        final partialResultToken = obj['partialResultToken'];
+        if (partialResultToken != null &&
+            !((partialResultToken is int || partialResultToken is String))) {
           reporter.reportError('must be of type Either2<int, String>');
           return false;
         }
@@ -33319,16 +34650,17 @@
 
   WorkspaceSymbolRegistrationOptions({this.workDoneProgress});
   static WorkspaceSymbolRegistrationOptions fromJson(
-      Map<String, dynamic> json) {
-    final workDoneProgress = json['workDoneProgress'];
+      Map<String, Object?> json) {
+    final workDoneProgressJson = json['workDoneProgress'];
+    final workDoneProgress = workDoneProgressJson as bool?;
     return WorkspaceSymbolRegistrationOptions(
         workDoneProgress: workDoneProgress);
   }
 
   final bool? workDoneProgress;
 
-  Map<String, dynamic> toJson() {
-    var __result = <String, dynamic>{};
+  Map<String, Object?> toJson() {
+    var __result = <String, Object?>{};
     if (workDoneProgress != null) {
       __result['workDoneProgress'] = workDoneProgress;
     }
@@ -33336,11 +34668,11 @@
   }
 
   static bool canParse(Object? obj, LspJsonReporter reporter) {
-    if (obj is Map<String, dynamic>) {
+    if (obj is Map<String, Object?>) {
       reporter.push('workDoneProgress');
       try {
-        if (obj['workDoneProgress'] != null &&
-            !(obj['workDoneProgress'] is bool)) {
+        final workDoneProgress = obj['workDoneProgress'];
+        if (workDoneProgress != null && !(workDoneProgress is bool)) {
           reporter.reportError('must be of type bool');
           return false;
         }
diff --git a/pkg/analysis_server/lib/src/edit/edit_domain.dart b/pkg/analysis_server/lib/src/edit/edit_domain.dart
index e7456df..43b4268 100644
--- a/pkg/analysis_server/lib/src/edit/edit_domain.dart
+++ b/pkg/analysis_server/lib/src/edit/edit_domain.dart
@@ -699,17 +699,23 @@
     if (driver == null) {
       return errorFixesList;
     }
-    var sourceFactory = driver.sourceFactory;
-    var pubspec = _getOptions(sourceFactory, content);
-    if (pubspec == null) {
+    YamlDocument document;
+    try {
+      document = loadYamlDocument(content);
+    } catch (exception) {
       return errorFixesList;
     }
+    var yamlContent = document.contents;
+    if (yamlContent is! YamlMap) {
+      yamlContent = YamlMap();
+    }
     var validator =
         PubspecValidator(server.resourceProvider, pubspecFile.createSource());
     var session = driver.currentSession;
-    var errors = validator.validate(pubspec.nodes);
+    var errors = validator.validate(yamlContent.nodes);
     for (var error in errors) {
-      var generator = PubspecFixGenerator(error, content, pubspec);
+      var generator = PubspecFixGenerator(
+          server.resourceProvider, error, content, document);
       var fixes = await generator.computeFixes();
       if (fixes.isNotEmpty) {
         fixes.sort(Fix.SORT_BY_RELEVANCE);
diff --git a/pkg/analysis_server/lib/src/lsp/client_capabilities.dart b/pkg/analysis_server/lib/src/lsp/client_capabilities.dart
index c6898f3..9a0b40a 100644
--- a/pkg/analysis_server/lib/src/lsp/client_capabilities.dart
+++ b/pkg/analysis_server/lib/src/lsp/client_capabilities.dart
@@ -132,8 +132,9 @@
             raw.workspace?.symbol?.symbolKind?.valueSet,
             defaults: defaultSupportedSymbolKinds),
         experimentalSnippetTextEdit =
-            raw.experimental is Map<String, dynamic> &&
-                raw.experimental['snippetTextEdit'] == true;
+            raw.experimental is Map<String, Object?> &&
+                (raw.experimental as Map<String, Object?>)['snippetTextEdit'] ==
+                    true;
 
   static Set<MarkupKind>? _completionDocumentationFormats(
       ClientCapabilities raw) {
diff --git a/pkg/analysis_server/lib/src/lsp/handlers/commands/simple_edit_handler.dart b/pkg/analysis_server/lib/src/lsp/handlers/commands/simple_edit_handler.dart
index df12d35..879ac92 100644
--- a/pkg/analysis_server/lib/src/lsp/handlers/commands/simple_edit_handler.dart
+++ b/pkg/analysis_server/lib/src/lsp/handlers/commands/simple_edit_handler.dart
@@ -78,8 +78,8 @@
     // sent - and may have failed to apply - was related to this command
     // execution).
     // We need to fromJson to convert the JSON map to the real types.
-    final editResponseResult =
-        ApplyWorkspaceEditResponse.fromJson(editResponse.result);
+    final editResponseResult = ApplyWorkspaceEditResponse.fromJson(
+        editResponse.result as Map<String, Object?>);
     if (editResponseResult.applied) {
       return success(null);
     } else {
diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_execute_command.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_execute_command.dart
index 05aaa4e..02c8a93 100644
--- a/pkg/analysis_server/lib/src/lsp/handlers/handler_execute_command.dart
+++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_execute_command.dart
@@ -51,9 +51,6 @@
         : server.clientCapabilities?.workDoneProgress ?? false
             ? ProgressReporter.serverCreated(server)
             : ProgressReporter.noop;
-    // TODO(dantup): Remove this cast and update codegen to use `Object?` in
-    //   place of the `dynamics`.
-    return handler.handle(
-        params.arguments?.cast<Object?>(), progress, cancellationToken);
+    return handler.handle(params.arguments, progress, cancellationToken);
   }
 }
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 af14c73..ab57310 100644
--- a/pkg/analysis_server/lib/src/lsp/lsp_analysis_server.dart
+++ b/pkg/analysis_server/lib/src/lsp/lsp_analysis_server.dart
@@ -614,7 +614,7 @@
       ShowMessageRequestParams(type: type, message: message, actions: actions),
     );
 
-    return MessageActionItem.fromJson(response.result);
+    return MessageActionItem.fromJson(response.result as Map<String, Object?>);
   }
 
   @override
diff --git a/pkg/analysis_server/lib/src/services/correction/fix/pubspec/fix_generator.dart b/pkg/analysis_server/lib/src/services/correction/fix/pubspec/fix_generator.dart
index 2a96fb7..1a034ce 100644
--- a/pkg/analysis_server/lib/src/services/correction/fix/pubspec/fix_generator.dart
+++ b/pkg/analysis_server/lib/src/services/correction/fix/pubspec/fix_generator.dart
@@ -4,62 +4,120 @@
 
 import 'dart:math' as math;
 
+import 'package:_fe_analyzer_shared/src/scanner/characters.dart';
 import 'package:analysis_server/plugin/edit/fix/fix_core.dart';
-import 'package:analysis_server/src/utilities/strings.dart';
+import 'package:analysis_server/src/services/correction/fix/pubspec/fix_kind.dart';
+import 'package:analysis_server/src/utilities/yaml_node_locator.dart';
+import 'package:analyzer/dart/analysis/session.dart';
 import 'package:analyzer/error/error.dart';
+import 'package:analyzer/file_system/file_system.dart';
 import 'package:analyzer/src/generated/java_core.dart';
 import 'package:analyzer/src/generated/source.dart';
 import 'package:analyzer/src/pubspec/pubspec_warning_code.dart';
+import 'package:analyzer/src/util/yaml.dart';
 import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
+import 'package:analyzer_plugin/utilities/change_builder/change_workspace.dart';
 import 'package:analyzer_plugin/utilities/fixes/fixes.dart';
 import 'package:yaml/yaml.dart';
 
 /// The generator used to generate fixes in pubspec.yaml files.
 class PubspecFixGenerator {
+  /// The resource provider used to access the file system.
+  final ResourceProvider resourceProvider;
+
+  /// The error for which fixes are being generated.
   final AnalysisError error;
 
+  /// The offset of the [error] for which fixes are being generated.
   final int errorOffset;
 
+  /// The length of the [error] for which fixes are being generated.
   final int errorLength;
 
+  /// The textual content of the file for which fixes are being generated.
   final String content;
 
-  final YamlMap options;
+  /// The parsed content of the file for which fixes are being generated.
+  final YamlDocument document;
 
   final LineInfo lineInfo;
 
+  /// The fixes that were generated.
   final List<Fix> fixes = <Fix>[];
 
-  // List<YamlNode> coveringNodePath;
+  /// The end-of-line marker used in the `pubspec.yaml` file.
+  String? _endOfLine;
 
-  PubspecFixGenerator(this.error, this.content, this.options)
+  PubspecFixGenerator(
+      this.resourceProvider, this.error, this.content, this.document)
       : errorOffset = error.offset,
         errorLength = error.length,
         lineInfo = LineInfo.fromContent(content);
 
+  /// Returns the end-of-line marker to use for the `pubspec.yaml` file.
+  String get endOfLine {
+    // TODO(brianwilkerson) Share this with CorrectionUtils, probably by
+    //  creating a subclass of CorrectionUtils containing utilities that are
+    //  only dependent on knowing the content of the file. Also consider moving
+    //  this kind of utility into the ChangeBuilder API directly.
+    var endOfLine = _endOfLine;
+    if (endOfLine != null) {
+      return endOfLine;
+    }
+
+    if (content.contains('\r\n')) {
+      return _endOfLine = '\r\n';
+    } else {
+      return _endOfLine = '\n';
+    }
+  }
+
   /// Return the absolute, normalized path to the file in which the error was
   /// reported.
   String get file => error.source.fullName;
 
   /// Return the list of fixes that apply to the error being fixed.
   Future<List<Fix>> computeFixes() async {
-    // var locator =
-    //     YamlNodeLocator(start: errorOffset, end: errorOffset + errorLength - 1);
-    // coveringNodePath = locator.searchWithin(options);
-    // if (coveringNodePath.isEmpty) {
-    //   return fixes;
-    // }
+    var locator =
+        YamlNodeLocator(start: errorOffset, end: errorOffset + errorLength - 1);
+    var coveringNodePath = locator.searchWithin(document.contents);
+    if (coveringNodePath.isEmpty) {
+      // One of the errors doesn't have a covering path but can still be fixed.
+      // The `if` was left so that the variable wouldn't be unused.
+      // return fixes;
+    }
 
     var errorCode = error.errorCode;
     if (errorCode == PubspecWarningCode.ASSET_DOES_NOT_EXIST) {
+      // Consider replacing the path with a valid path.
     } else if (errorCode == PubspecWarningCode.ASSET_DIRECTORY_DOES_NOT_EXIST) {
+      // Consider replacing the path with a valid path.
+      // Consider creating the directory.
     } else if (errorCode == PubspecWarningCode.ASSET_FIELD_NOT_LIST) {
+      // Not sure how to fix a structural issue.
     } else if (errorCode == PubspecWarningCode.ASSET_NOT_STRING) {
+      // Not sure how to fix a structural issue.
     } else if (errorCode == PubspecWarningCode.DEPENDENCIES_FIELD_NOT_MAP) {
+      // Not sure how to fix a structural issue.
+    } else if (errorCode == PubspecWarningCode.DEPRECATED_FIELD) {
+      // Consider removing the field.
     } else if (errorCode == PubspecWarningCode.FLUTTER_FIELD_NOT_MAP) {
+      // Not sure how to fix a structural issue.
+    } else if (errorCode == PubspecWarningCode.INVALID_DEPENDENCY) {
+      // Consider adding `publish_to: none`.
     } else if (errorCode == PubspecWarningCode.MISSING_NAME) {
+      await _addNameEntry();
     } else if (errorCode == PubspecWarningCode.NAME_NOT_STRING) {
-    } else if (errorCode == PubspecWarningCode.UNNECESSARY_DEV_DEPENDENCY) {}
+      // Not sure how to fix a structural issue.
+    } else if (errorCode == PubspecWarningCode.PATH_DOES_NOT_EXIST) {
+      // Consider replacing the path with a valid path.
+    } else if (errorCode == PubspecWarningCode.PATH_NOT_POSIX) {
+      // Consider converting to a POSIX-style path.
+    } else if (errorCode == PubspecWarningCode.PATH_PUBSPEC_DOES_NOT_EXIST) {
+      // Consider replacing the path with a valid path.
+    } else if (errorCode == PubspecWarningCode.UNNECESSARY_DEV_DEPENDENCY) {
+      // Consider removing the dependency.
+    }
     return fixes;
   }
 
@@ -72,16 +130,59 @@
     if (change.edits.isEmpty) {
       return;
     }
+    change.id = kind.id;
     change.message = formatList(kind.message, args);
     fixes.add(Fix(kind, change));
   }
 
-  // ignore: unused_element
-  int _firstNonWhitespaceBefore(int offset) {
-    while (offset > 0 && isWhitespace(content.codeUnitAt(offset - 1))) {
-      offset--;
+  Future<void> _addNameEntry() async {
+    var context = resourceProvider.pathContext;
+    var packageName = _identifierFrom(context.basename(context.dirname(file)));
+    var builder =
+        ChangeBuilder(workspace: _NonDartChangeWorkspace(), eol: endOfLine);
+    var firstOffset = _initialOffset(document.contents);
+    if (firstOffset < 0) {
+      // The document contains a list, and we don't support converting it to a
+      // map.
+      return;
     }
-    return offset;
+    await builder.addGenericFileEdit(file, (builder) {
+      // TODO(brianwilkerson) Generalize this to add a key to any map by
+      //  inserting the indentation of the line containing `firstOffset` after
+      //  the end-of-line marker.
+      builder.addSimpleInsertion(firstOffset, 'name: $packageName$endOfLine');
+    });
+    _addFixFromBuilder(builder, PubspecFixKind.addName);
+  }
+
+  String _identifierFrom(String directoryName) {
+    var buffer = StringBuffer();
+    for (var i = 0; i < directoryName.length; i++) {
+      var currentChar = directoryName[i];
+      if (_isIdentifierChar(currentChar.codeUnitAt(0))) {
+        buffer.write(currentChar.toLowerCase());
+      }
+    }
+    if (buffer.isEmpty) {
+      return 'insertNameHere';
+    }
+    return buffer.toString();
+  }
+
+  int _initialOffset(YamlNode node) {
+    if (node is YamlMap) {
+      return _offsetOfFirstKey(node);
+    } else if (node is YamlScalar) {
+      return node.span.start.offset;
+    }
+    return -1;
+  }
+
+  bool _isIdentifierChar(int next) {
+    return ($a <= next && next <= $z) ||
+        ($A <= next && next <= $Z) ||
+        ($0 <= next && next <= $9) ||
+        identical(next, $_);
   }
 
   // ignore: unused_element
@@ -93,4 +194,31 @@
         math.min(endLocation.lineNumber, lineInfo.lineCount - 1));
     return SourceRange(startOffset, endOffset - startOffset);
   }
+
+  // ignore: unused_element
+  int _offsetOfFirstKey(YamlMap map) {
+    var firstOffset = -1;
+    for (var key in map.nodeMap.keys) {
+      var keyOffset = key.span.start.offset;
+      if (firstOffset < 0 || keyOffset < firstOffset) {
+        firstOffset = keyOffset;
+      }
+    }
+    if (firstOffset < 0) {
+      firstOffset = 0;
+    }
+    return firstOffset;
+  }
+}
+
+class _NonDartChangeWorkspace implements ChangeWorkspace {
+  @override
+  bool containsFile(String path) {
+    return true;
+  }
+
+  @override
+  AnalysisSession getSession(String path) {
+    throw UnimplementedError('Attempt to work a Dart file.');
+  }
 }
diff --git a/pkg/analysis_server/lib/src/services/correction/fix/pubspec/fix_kind.dart b/pkg/analysis_server/lib/src/services/correction/fix/pubspec/fix_kind.dart
new file mode 100644
index 0000000..1727ba4
--- /dev/null
+++ b/pkg/analysis_server/lib/src/services/correction/fix/pubspec/fix_kind.dart
@@ -0,0 +1,21 @@
+// 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:analyzer_plugin/utilities/fixes/fixes.dart';
+
+/// An enumeration of quick fix kinds found in a pubspec file.
+class PubspecFixKind {
+  static const addName = FixKind(
+    'pubspec.fix.add.name',
+    PubspecFixKindPriority.DEFAULT,
+    "Add 'name' key",
+  );
+
+  /// Prevent the creation of instances of this class.
+  PubspecFixKind._();
+}
+
+class PubspecFixKindPriority {
+  static const int DEFAULT = 50;
+}
diff --git a/pkg/analysis_server/test/integration/lsp_server/integration_tests.dart b/pkg/analysis_server/test/integration/lsp_server/integration_tests.dart
index 66949c4..6b05d1a 100644
--- a/pkg/analysis_server/test/integration/lsp_server/integration_tests.dart
+++ b/pkg/analysis_server/test/integration/lsp_server/integration_tests.dart
@@ -38,7 +38,7 @@
           ? null as T
           : throw 'Expected Null response but got ${resp.result}';
     } else {
-      return fromJson(resp.result);
+      return fromJson(resp.result as R);
     }
   }
 
diff --git a/pkg/analysis_server/test/lsp/code_actions_refactor_test.dart b/pkg/analysis_server/test/lsp/code_actions_refactor_test.dart
index 6891326..5ebc918 100644
--- a/pkg/analysis_server/test/lsp/code_actions_refactor_test.dart
+++ b/pkg/analysis_server/test/lsp/code_actions_refactor_test.dart
@@ -37,7 +37,8 @@
     requestsFromServer
         .where((r) => r.method == Method.window_workDoneProgress_create)
         .listen((request) async {
-      final params = WorkDoneProgressCreateParams.fromJson(request.params);
+      final params = WorkDoneProgressCreateParams.fromJson(
+          request.params as Map<String, Object?>);
       if (params.token != analyzingProgressToken) {
         controller.add('CREATE');
       }
@@ -45,7 +46,8 @@
     notificationsFromServer
         .where((n) => n.method == Method.progress)
         .listen((notification) {
-      final params = ProgressParams.fromJson(notification.params);
+      final params =
+          ProgressParams.fromJson(notification.params as Map<String, Object?>);
       if (params.token != analyzingProgressToken) {
         if (WorkDoneProgressBegin.canParse(params.value, nullLspJsonReporter)) {
           controller.add('BEGIN');
@@ -118,7 +120,8 @@
     late WorkspaceEdit edit;
     requestsFromServer.listen((request) async {
       if (request.method == Method.workspace_applyEdit) {
-        final params = ApplyWorkspaceEditParams.fromJson(request.params);
+        final params = ApplyWorkspaceEditParams.fromJson(
+            request.params as Map<String, Object?>);
         edit = params.edit;
         respondTo(request, ApplyWorkspaceEditResponse(applied: true));
       }
diff --git a/pkg/analysis_server/test/lsp/completion_dart_test.dart b/pkg/analysis_server/test/lsp/completion_dart_test.dart
index 69de58e..0328fa0 100644
--- a/pkg/analysis_server/test/lsp/completion_dart_test.dart
+++ b/pkg/analysis_server/test/lsp/completion_dart_test.dart
@@ -154,7 +154,8 @@
 
     // By default, there should be no commit characters.
     var reg = registration(Method.textDocument_completion);
-    var options = CompletionRegistrationOptions.fromJson(reg.registerOptions);
+    var options = CompletionRegistrationOptions.fromJson(
+        reg.registerOptions as Map<String, Object?>);
     expect(options.allCommitCharacters, isNull);
 
     // When we change config, we should get a re-registration (unregister then
@@ -162,7 +163,8 @@
     await monitorDynamicReregistration(
         registrations, () => updateConfig({'previewCommitCharacters': true}));
     reg = registration(Method.textDocument_completion);
-    options = CompletionRegistrationOptions.fromJson(reg.registerOptions);
+    options = CompletionRegistrationOptions.fromJson(
+        reg.registerOptions as Map<String, Object?>);
     expect(options.allCommitCharacters, equals(dartCompletionCommitCharacters));
   }
 
diff --git a/pkg/analysis_server/test/lsp/initialization_test.dart b/pkg/analysis_server/test/lsp/initialization_test.dart
index e7eb40b..7d1bc71 100644
--- a/pkg/analysis_server/test/lsp/initialization_test.dart
+++ b/pkg/analysis_server/test/lsp/initialization_test.dart
@@ -26,7 +26,8 @@
     Method method,
   ) {
     return TextDocumentRegistrationOptions.fromJson(
-        registrationFor(registrations, method)?.registerOptions);
+        registrationFor(registrations, method)?.registerOptions
+            as Map<String, Object?>);
   }
 
   Future<void> test_bazelWorkspace() async {
@@ -64,14 +65,15 @@
       ),
     );
 
-    final initResult = InitializeResult.fromJson(initResponse.result);
+    final initResult =
+        InitializeResult.fromJson(initResponse.result as Map<String, Object?>);
     expect(initResult.capabilities, isNotNull);
 
     // Check Dart-only registration.
     final dartRegistration =
         registrationForDart(registrations, Method.textDocument_completion);
     final dartOptions = CompletionRegistrationOptions.fromJson(
-        dartRegistration.registerOptions);
+        dartRegistration.registerOptions as Map<String, Object?>);
     expect(dartOptions.documentSelector, hasLength(1));
     expect(dartOptions.documentSelector![0].language, dartLanguageId);
     expect(dartOptions.triggerCharacters, isNotEmpty);
@@ -81,7 +83,7 @@
         r.method == Method.textDocument_completion.toJson() &&
         r != dartRegistration);
     final nonDartOptions = CompletionRegistrationOptions.fromJson(
-        nonDartRegistration.registerOptions);
+        nonDartRegistration.registerOptions as Map<String, Object?>);
     final otherLanguages = nonDartOptions.documentSelector!
         .map((selector) => selector.language)
         .toList();
@@ -109,7 +111,8 @@
     // Because we support dynamic registration for synchronization, we won't send
     // static registrations for them.
     // https://github.com/dart-lang/sdk/issues/38490
-    final initResult = InitializeResult.fromJson(initResponse.result);
+    final initResult =
+        InitializeResult.fromJson(initResponse.result as Map<String, Object?>);
     expect(initResult.serverInfo!.name, 'Dart SDK LSP Analysis Server');
     expect(initResult.serverInfo!.version, isNotNull);
     expect(initResult.capabilities, isNotNull);
@@ -123,7 +126,7 @@
         registrationOptionsFor(registrations, Method.textDocument_didChange);
     final rename = FileOperationRegistrationOptions.fromJson(
         registrationFor(registrations, Method.workspace_willRenameFiles)
-            ?.registerOptions);
+            ?.registerOptions as Map<String, Object?>);
     expect(registrationOptionsFor(registrations, Method.textDocument_didOpen),
         isNotNull);
     expect(registrationOptionsFor(registrations, Method.textDocument_didClose),
@@ -164,7 +167,8 @@
     final initResponse = await initialize();
     await pumpEventQueue();
 
-    final initResult = InitializeResult.fromJson(initResponse.result);
+    final initResult =
+        InitializeResult.fromJson(initResponse.result as Map<String, Object?>);
     expect(initResult.capabilities, isNotNull);
     // When dynamic registration is not supported, we will always statically
     // request text document open/close and incremental updates.
@@ -229,7 +233,8 @@
       ),
     );
 
-    final initResult = InitializeResult.fromJson(initResponse.result);
+    final initResult =
+        InitializeResult.fromJson(initResponse.result as Map<String, Object?>);
     expect(initResult.capabilities, isNotNull);
 
     // Ensure no static registrations. This list should include all server equivilents
@@ -289,9 +294,9 @@
         ..interestingFiles = ['*.foo'];
       pluginManager.pluginsChangedController.add(null);
     });
-    final unregistrations =
-        UnregistrationParams.fromJson(unregisterRequest.params)
-            .unregisterations;
+    final unregistrations = UnregistrationParams.fromJson(
+            unregisterRequest.params as Map<String, Object?>)
+        .unregisterations;
 
     // folding method should have been unregistered as the server now supports
     // *.foo files for it as well.
@@ -321,7 +326,9 @@
         .firstWhere((r) => r.method == Method.client_unregisterCapability)
         .then((request) {
       respondTo(request, null);
-      return UnregistrationParams.fromJson(request.params).unregisterations;
+      return UnregistrationParams.fromJson(
+              request.params as Map<String, Object?>)
+          .unregisterations;
     });
 
     final request = await expectRequest(Method.client_registerCapability, () {
@@ -332,7 +339,8 @@
     });
 
     final registrations =
-        RegistrationParams.fromJson(request.params).registrations;
+        RegistrationParams.fromJson(request.params as Map<String, Object?>)
+            .registrations;
 
     final documentFilterSql =
         DocumentFilter(scheme: 'file', pattern: '**/*.sql');
@@ -343,7 +351,8 @@
       contains(isA<Registration>()
           .having((r) => r.method, 'method', 'textDocument/foldingRange')
           .having(
-            (r) => TextDocumentRegistrationOptions.fromJson(r.registerOptions)
+            (r) => TextDocumentRegistrationOptions.fromJson(
+                    r.registerOptions as Map<String, Object?>)
                 .documentSelector,
             'registerOptions.documentSelector',
             containsAll([documentFilterSql, documentFilterDart]),
@@ -483,7 +492,8 @@
     expect(response.result, isNotNull);
     expect(InitializeResult.canParse(response.result, nullLspJsonReporter),
         isTrue);
-    final result = InitializeResult.fromJson(response.result);
+    final result =
+        InitializeResult.fromJson(response.result as Map<String, Object?>);
     expect(result.capabilities, isNotNull);
     // Check some basic capabilities that are unlikely to change.
     expect(result.capabilities.textDocumentSync, isNotNull);
diff --git a/pkg/analysis_server/test/lsp/rename_test.dart b/pkg/analysis_server/test/lsp/rename_test.dart
index 0559614..27be436 100644
--- a/pkg/analysis_server/test/lsp/rename_test.dart
+++ b/pkg/analysis_server/test/lsp/rename_test.dart
@@ -176,7 +176,8 @@
       throw error;
     }
 
-    final result = WorkspaceEdit.fromJson(response.result);
+    final result =
+        WorkspaceEdit.fromJson(response.result as Map<String, Object?>);
 
     // Ensure applying the changes will give us the expected content.
     final contents = {
@@ -205,7 +206,7 @@
     // Expect a successful empty response if cancelled.
     expect(response.error, isNull);
     expect(
-      WorkspaceEdit.fromJson(response.result),
+      WorkspaceEdit.fromJson(response.result as Map<String, Object?>),
       equals(emptyWorkspaceEdit),
     );
   }
diff --git a/pkg/analysis_server/test/lsp/server_abstract.dart b/pkg/analysis_server/test/lsp/server_abstract.dart
index 6707f2b..ad2d20b 100644
--- a/pkg/analysis_server/test/lsp/server_abstract.dart
+++ b/pkg/analysis_server/test/lsp/server_abstract.dart
@@ -102,7 +102,7 @@
       throw error;
     } else {
       // resp.result should only be null when error != null if T allows null.
-      return resp.result == null ? null as T : fromJson(resp.result);
+      return resp.result == null ? null as T : fromJson(resp.result as R);
     }
   }
 
@@ -122,7 +122,8 @@
   ) {
     return registrations.singleWhere((r) =>
         r.method == method.toJson() &&
-        (TextDocumentRegistrationOptions.fromJson(r.registerOptions)
+        (TextDocumentRegistrationOptions.fromJson(
+                    r.registerOptions as Map<String, Object?>)
                 .documentSelector
                 ?.any((selector) => selector.language == dartLanguageId) ??
             false));
@@ -875,7 +876,8 @@
     final notificationFromServer = await firstError.timeout(timeout);
 
     expect(notificationFromServer, isNotNull);
-    return ShowMessageParams.fromJson(notificationFromServer.params);
+    return ShowMessageParams.fromJson(
+        notificationFromServer.params as Map<String, Object?>);
   }
 
   Future<T> expectNotification<T>(
@@ -1253,7 +1255,8 @@
     });
 
     // Handle the request from the server and send the response back.
-    final clientsResponse = await handler(fromJson(incomingRequest.params));
+    final clientsResponse =
+        await handler(fromJson(incomingRequest.params as Map<String, Object?>));
     respondTo(incomingRequest, clientsResponse);
 
     // Return a future that completes when the response to the original request
@@ -1649,7 +1652,8 @@
                 'but client supports workDoneProgress');
           }
 
-          final params = AnalyzerStatusParams.fromJson(message.params);
+          final params = AnalyzerStatusParams.fromJson(
+              message.params as Map<String, Object?>);
           return params.isAnalyzing == analyzing;
         } else if (message.method == Method.progress) {
           if (_clientCapabilities!.window?.workDoneProgress != true) {
@@ -1658,7 +1662,8 @@
                 'but client supports workDoneProgress');
           }
 
-          final params = ProgressParams.fromJson(message.params);
+          final params =
+              ProgressParams.fromJson(message.params as Map<String, Object?>);
 
           // Skip unrelated progress notifications.
           if (params.token != analyzingProgressToken) {
@@ -1688,8 +1693,8 @@
     await serverToClient.firstWhere((message) {
       if (message is NotificationMessage &&
           message.method == CustomMethods.publishClosingLabels) {
-        closingLabelsParams =
-            PublishClosingLabelsParams.fromJson(message.params);
+        closingLabelsParams = PublishClosingLabelsParams.fromJson(
+            message.params as Map<String, Object?>);
 
         return closingLabelsParams.uri == uri.toString();
       }
@@ -1704,7 +1709,8 @@
         (message) {
       if (message is NotificationMessage &&
           message.method == Method.textDocument_publishDiagnostics) {
-        diagnosticParams = PublishDiagnosticsParams.fromJson(message.params);
+        diagnosticParams = PublishDiagnosticsParams.fromJson(
+            message.params as Map<String, Object?>);
         return diagnosticParams!.uri == uri.toString();
       }
       return false;
@@ -1717,7 +1723,8 @@
     await serverToClient.firstWhere((message) {
       if (message is NotificationMessage &&
           message.method == CustomMethods.publishFlutterOutline) {
-        outlineParams = PublishFlutterOutlineParams.fromJson(message.params);
+        outlineParams = PublishFlutterOutlineParams.fromJson(
+            message.params as Map<String, Object?>);
 
         return outlineParams.uri == uri.toString();
       }
@@ -1731,7 +1738,8 @@
     await serverToClient.firstWhere((message) {
       if (message is NotificationMessage &&
           message.method == CustomMethods.publishOutline) {
-        outlineParams = PublishOutlineParams.fromJson(message.params);
+        outlineParams = PublishOutlineParams.fromJson(
+            message.params as Map<String, Object?>);
 
         return outlineParams.uri == uri.toString();
       }
@@ -1760,7 +1768,8 @@
       (input) => input.cast<Map<String, dynamic>>().map(fromJson).toList();
 
   Future<void> _handleProgress(NotificationMessage request) async {
-    final params = ProgressParams.fromJson(request.params);
+    final params =
+        ProgressParams.fromJson(request.params as Map<String, Object?>);
     if (params.token != clientProvidedTestWorkDoneToken &&
         !validProgressTokens.contains(params.token)) {
       throw Exception('Server sent a progress notification for a token '
@@ -1777,7 +1786,8 @@
       throw Exception('Server sent ${Method.window_workDoneProgress_create} '
           'but client capabilities do not allow');
     }
-    final params = WorkDoneProgressCreateParams.fromJson(request.params);
+    final params = WorkDoneProgressCreateParams.fromJson(
+        request.params as Map<String, Object?>);
     if (validProgressTokens.contains(params.token)) {
       throw Exception('Server tried to create already-active progress token');
     }
diff --git a/pkg/analysis_server/test/mocks_lsp.dart b/pkg/analysis_server/test/mocks_lsp.dart
index d8eafef..35b3c1f 100644
--- a/pkg/analysis_server/test/mocks_lsp.dart
+++ b/pkg/analysis_server/test/mocks_lsp.dart
@@ -40,12 +40,14 @@
     // `window/showMessage`.
     _serverToClient.stream.listen((message) {
       if (message is lsp.NotificationMessage &&
-          message.method == Method.window_showMessage &&
-          message.params is lsp.ShowMessageParams) {
-        if (message.params?.type == MessageType.Error) {
-          shownErrors.add(message.params);
-        } else if (message.params?.type == MessageType.Warning) {
-          shownWarnings.add(message.params);
+          message.method == Method.window_showMessage) {
+        final params = message.params;
+        if (params is lsp.ShowMessageParams) {
+          if (params.type == MessageType.Error) {
+            shownErrors.add(params);
+          } else if (params.type == MessageType.Warning) {
+            shownWarnings.add(params);
+          }
         }
       }
     });
@@ -170,7 +172,9 @@
         (throwOnError &&
             message is lsp.NotificationMessage &&
             message.method == Method.window_showMessage &&
-            lsp.ShowMessageParams.fromJson(message.params).type ==
+            lsp.ShowMessageParams.fromJson(
+                        message.params as Map<String, Object?>)
+                    .type ==
                 MessageType.Error));
 
     if (response is lsp.ResponseMessage) {
diff --git a/pkg/analysis_server/test/src/services/correction/fix/pubspec/missing_name_test.dart b/pkg/analysis_server/test/src/services/correction/fix/pubspec/missing_name_test.dart
new file mode 100644
index 0000000..b5aea94
--- /dev/null
+++ b/pkg/analysis_server/test/src/services/correction/fix/pubspec/missing_name_test.dart
@@ -0,0 +1,68 @@
+// 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/fix/pubspec/fix_kind.dart';
+import 'package:analyzer_plugin/utilities/fixes/fixes.dart';
+import 'package:test_reflective_loader/test_reflective_loader.dart';
+
+import 'test_support.dart';
+
+void main() {
+  defineReflectiveSuite(() {
+    defineReflectiveTests(MissingNameTest);
+  });
+}
+
+@reflectiveTest
+class MissingNameTest extends PubspecFixTest {
+  @override
+  FixKind get kind => PubspecFixKind.addName;
+
+  @failingTest
+  Future<void> test_empty_withComment() async {
+    /// The test fails because the comment is included in the span of the
+    /// `YamlScalar` that is produced as the contents of the document.
+    validatePubspec('''
+# comment
+''');
+    await assertHasFix('''
+# comment
+name: test
+''');
+  }
+
+  Future<void> test_empty_withoutComment() async {
+    validatePubspec('''
+''');
+    await assertHasFix('''
+name: test
+''');
+  }
+
+  Future<void> test_nonEmpty_withComment() async {
+    validatePubspec('''
+# comment
+environment:
+  sdk: '>=2.12.0 <3.0.0'
+''');
+    await assertHasFix('''
+# comment
+name: test
+environment:
+  sdk: '>=2.12.0 <3.0.0'
+''');
+  }
+
+  Future<void> test_nonEmpty_withoutComment() async {
+    validatePubspec('''
+environment:
+  sdk: '>=2.12.0 <3.0.0'
+''');
+    await assertHasFix('''
+name: test
+environment:
+  sdk: '>=2.12.0 <3.0.0'
+''');
+  }
+}
diff --git a/pkg/analysis_server/test/src/services/correction/fix/pubspec/test_all.dart b/pkg/analysis_server/test/src/services/correction/fix/pubspec/test_all.dart
new file mode 100644
index 0000000..f639f7c
--- /dev/null
+++ b/pkg/analysis_server/test/src/services/correction/fix/pubspec/test_all.dart
@@ -0,0 +1,13 @@
+// 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:test_reflective_loader/test_reflective_loader.dart';
+
+import 'missing_name_test.dart' as missing_name_test;
+
+void main() {
+  defineReflectiveSuite(() {
+    missing_name_test.main();
+  });
+}
diff --git a/pkg/analysis_server/test/src/services/correction/fix/pubspec/test_support.dart b/pkg/analysis_server/test/src/services/correction/fix/pubspec/test_support.dart
new file mode 100644
index 0000000..5846f51
--- /dev/null
+++ b/pkg/analysis_server/test/src/services/correction/fix/pubspec/test_support.dart
@@ -0,0 +1,65 @@
+// 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/plugin/edit/fix/fix_core.dart';
+import 'package:analysis_server/src/protocol_server.dart' show SourceEdit;
+import 'package:analysis_server/src/services/correction/fix/pubspec/fix_generator.dart';
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/src/pubspec/pubspec_validator.dart';
+import 'package:analyzer/src/test_utilities/resource_provider_mixin.dart';
+import 'package:analyzer_plugin/utilities/fixes/fixes.dart';
+import 'package:test/test.dart';
+import 'package:yaml/src/yaml_node.dart';
+import 'package:yaml/yaml.dart';
+
+abstract class PubspecFixTest with ResourceProviderMixin {
+  /// The content of the pubspec file that is being tested.
+  late String content;
+
+  /// The result of parsing the [content].
+  late YamlDocument document;
+
+  /// The error to be fixed.
+  late AnalysisError error;
+
+  /// Return the kind of fixes being tested by this test class.
+  FixKind get kind;
+
+  Future<void> assertHasFix(String expected) async {
+    var fixes = await _getFixes();
+    expect(fixes, hasLength(1));
+    var fix = fixes[0];
+    expect(fix.kind, kind);
+    var edits = fix.change.edits;
+    expect(fixes, hasLength(1));
+    var actual = SourceEdit.applySequence(content, edits[0].edits);
+    expect(actual, expected);
+  }
+
+  Future<void> assertHasNoFix(String initialContent) async {
+    var fixes = await _getFixes();
+    expect(fixes, hasLength(0));
+  }
+
+  void validatePubspec(String content) {
+    this.content = content;
+    var pubspecFile = newFile('/home/test/pubspec.yaml', content: content);
+    document = loadYamlDocument(content);
+    var yamlContent = document.contents;
+    if (yamlContent is! YamlMap) {
+      yamlContent = YamlMap();
+    }
+    var validator =
+        PubspecValidator(resourceProvider, pubspecFile.createSource());
+    var errors = validator.validate(yamlContent.nodes);
+    expect(errors.length, 1);
+    error = errors[0];
+  }
+
+  Future<List<Fix>> _getFixes() async {
+    var generator =
+        PubspecFixGenerator(resourceProvider, error, content, document);
+    return await generator.computeFixes();
+  }
+}
diff --git a/pkg/analysis_server/test/src/services/correction/fix/test_all.dart b/pkg/analysis_server/test/src/services/correction/fix/test_all.dart
index c5ba22b..b3e369d 100644
--- a/pkg/analysis_server/test/src/services/correction/fix/test_all.dart
+++ b/pkg/analysis_server/test/src/services/correction/fix/test_all.dart
@@ -106,6 +106,7 @@
 import 'make_variable_nullable_test.dart' as make_variable_nullable;
 import 'move_type_arguments_to_class_test.dart' as move_type_arguments_to_class;
 import 'organize_imports_test.dart' as organize_imports;
+import 'pubspec/test_all.dart' as pubspec;
 import 'qualify_reference_test.dart' as qualify_reference;
 import 'remove_annotation_test.dart' as remove_annotation;
 import 'remove_argument_test.dart' as remove_argument;
@@ -281,6 +282,7 @@
     make_variable_nullable.main();
     move_type_arguments_to_class.main();
     organize_imports.main();
+    pubspec.main();
     qualify_reference.main();
     remove_annotation.main();
     remove_argument.main();
diff --git a/pkg/analysis_server/test/tool/lsp_spec/dart_test.dart b/pkg/analysis_server/test/tool/lsp_spec/dart_test.dart
index 7ead849..4e7b051 100644
--- a/pkg/analysis_server/test/tool/lsp_spec/dart_test.dart
+++ b/pkg/analysis_server/test/tool/lsp_spec/dart_test.dart
@@ -11,8 +11,8 @@
     test('handles basic types', () {
       expect(_simple('string').dartType, equals('String'));
       expect(_simple('boolean').dartType, equals('bool'));
-      expect(_simple('any').dartType, equals('dynamic'));
-      expect(_simple('object').dartType, equals('dynamic'));
+      expect(_simple('any').dartType, equals('Object?'));
+      expect(_simple('object').dartType, equals('Object?'));
       expect(_simple('int').dartType, equals('int'));
       expect(_simple('num').dartType, equals('num'));
     });
diff --git a/pkg/analysis_server/tool/lsp_spec/codegen_dart.dart b/pkg/analysis_server/tool/lsp_spec/codegen_dart.dart
index 66518f3..5698c0b 100644
--- a/pkg/analysis_server/tool/lsp_spec/codegen_dart.dart
+++ b/pkg/analysis_server/tool/lsp_spec/codegen_dart.dart
@@ -177,6 +177,20 @@
   });
 }
 
+/// Returns a String representing the underlying Dart type for the provided
+/// spec [type].
+///
+/// This is `Map<String, Object?>` for complex types but can be a simple type
+/// for enums.
+String _specJsonType(TypeBase type) {
+  if (type is Type && _namespaces.containsKey(type.name)) {
+    final valueType = _namespaces[type.name]!.members.cast<Const>().first.type;
+    return resolveTypeAlias(valueType, resolveEnumClasses: true)
+        .dartTypeWithTypeArgs;
+  }
+  return 'Map<String, Object?>';
+}
+
 Iterable<String> _wrapLines(List<String> lines, int maxLength) sync* {
   lines = lines.map((l) => l.trimRight()).toList();
   for (var line in lines) {
@@ -204,7 +218,7 @@
     ..writeIndentedln(
         'static bool canParse(Object? obj, LspJsonReporter reporter) {')
     ..indent()
-    ..writeIndentedln('if (obj is Map<String, dynamic>) {')
+    ..writeIndentedln('if (obj is Map<String, Object?>) {')
     ..indent();
   // In order to consider this valid for parsing, all fields that must not be
   // undefined must be present and also type check for the correct type.
@@ -227,9 +241,12 @@
         ..outdent()
         ..writeIndentedln('}');
     }
+    // Add a local variable to allow type promotion (and avoid multiple lookups).
+    final localName = _makeValidIdentifier(field.name);
+    buffer.writeIndentedln("final $localName = obj['${field.name}'];");
     if (!field.allowsNull && !field.allowsUndefined) {
       buffer
-        ..writeIndentedln("if (obj['${field.name}'] == null) {")
+        ..writeIndentedln('if ($localName == null) {')
         ..indent()
         ..writeIndentedln("reporter.reportError('must not be null');")
         ..writeIndentedln('return false;')
@@ -238,11 +255,11 @@
     }
     buffer.writeIndented('if (');
     if (field.allowsNull || field.allowsUndefined) {
-      buffer.write("obj['${field.name}'] != null && ");
+      buffer.write('$localName != null && ');
     }
     buffer.write('!(');
     _writeTypeCheckCondition(
-        buffer, interface, "obj['${field.name}']", field.type, 'reporter');
+        buffer, interface, localName, field.type, 'reporter');
     buffer
       ..write(')) {')
       ..indent()
@@ -469,47 +486,56 @@
 }
 
 void _writeFromJsonCode(
-    IndentableStringBuffer buffer, TypeBase type, String valueCode,
-    {required bool allowsNull, bool requiresBracesInInterpolation = false}) {
+  IndentableStringBuffer buffer,
+  TypeBase type,
+  String valueCode, {
+  required bool allowsNull,
+  bool requiresCast = true,
+}) {
   type = resolveTypeAlias(type);
+  final nullOperator = allowsNull ? '?' : '';
+  final cast = requiresCast && type.dartTypeWithTypeArgs != 'Object?'
+      ? ' as ${type.dartTypeWithTypeArgs}$nullOperator'
+      : '';
 
   if (_isSimpleType(type)) {
-    buffer.write('$valueCode');
+    buffer.write('$valueCode$cast');
   } else if (_isSpecType(type)) {
     // Our own types have fromJson() constructors we can call.
     if (allowsNull) {
       buffer.write('$valueCode != null ? ');
     }
-    buffer.write('${type.dartType}.fromJson${type.typeArgsString}($valueCode)');
+    buffer
+      ..write('${type.dartType}.fromJson${type.typeArgsString}')
+      ..write('($valueCode as ${_specJsonType(type)})');
     if (allowsNull) {
       buffer.write(': null');
     }
   } else if (type is ArrayType) {
     // Lists need to be map()'d so we can recursively call writeFromJsonCode
     // as they may need fromJson on each element.
-    buffer.write('$valueCode?.map((item) => ');
-    _writeFromJsonCode(buffer, type.elementType, 'item',
-        allowsNull: allowsNull);
-    buffer
-        .write(')?.cast<${type.elementType.dartTypeWithTypeArgs}>()?.toList()');
+    final listCast = requiresCast ? ' as List<Object?>$nullOperator' : '';
+    buffer.write('($valueCode$listCast)$nullOperator.map((item) => ');
+    _writeFromJsonCode(buffer, type.elementType, 'item', allowsNull: false);
+    buffer.write(').toList()');
   } else if (type is MapType) {
     // Maps need to be map()'d so we can recursively call writeFromJsonCode as
     // they may need fromJson on each key or value.
-    buffer.write('$valueCode?.map((key, value) => MapEntry(');
-    _writeFromJsonCode(buffer, type.indexType, 'key', allowsNull: allowsNull);
+    final mapCast = requiresCast ? ' as Map<Object, Object?>$nullOperator' : '';
+    buffer
+      ..write('($valueCode$mapCast)$nullOperator.map(')
+      ..write('(key, value) => MapEntry(');
+    _writeFromJsonCode(buffer, type.indexType, 'key', allowsNull: false);
     buffer.write(', ');
-    _writeFromJsonCode(buffer, type.valueType, 'value', allowsNull: allowsNull);
-    buffer.write(
-        '))?.cast<${type.indexType.dartTypeWithTypeArgs}, ${type.valueType.dartTypeWithTypeArgs}>()');
+    _writeFromJsonCode(buffer, type.valueType, 'value', allowsNull: false);
+    buffer.write('))');
   } else if (type is LiteralUnionType) {
     _writeFromJsonCodeForLiteralUnion(buffer, type, valueCode,
         allowsNull: allowsNull);
   } else if (type is UnionType) {
-    _writeFromJsonCodeForUnion(buffer, type, valueCode,
-        allowsNull: allowsNull,
-        requiresBracesInInterpolation: requiresBracesInInterpolation);
+    _writeFromJsonCodeForUnion(buffer, type, valueCode, allowsNull: allowsNull);
   } else {
-    buffer.write('$valueCode');
+    buffer.write('$valueCode$cast');
   }
 }
 
@@ -520,14 +546,16 @@
     if (allowsNull) null,
     ...union.literalTypes.map((t) => t.literal)
   ];
+  final valueType = union.literalTypes.first.dartTypeWithTypeArgs;
+  final cast = ' as $valueType${allowsNull ? '?' : ''}';
   buffer.write(
-      "const {${allowedValues.join(', ')}}.contains($valueCode) ? $valueCode : "
-      "throw '''\${$valueCode} was not one of (${allowedValues.join(', ')})'''");
+      "const {${allowedValues.join(', ')}}.contains($valueCode) ? $valueCode$cast : "
+      "throw '''\$$valueCode was not one of (${allowedValues.join(', ')})'''");
 }
 
 void _writeFromJsonCodeForUnion(
     IndentableStringBuffer buffer, UnionType union, String valueCode,
-    {required bool allowsNull, required bool requiresBracesInInterpolation}) {
+    {required bool allowsNull}) {
   // Write a check against each type, eg.:
   // x is y ? new Either.tx(x) : (...)
   var hasIncompleteCondition = false;
@@ -543,7 +571,7 @@
     final type = union.types[i];
     final isAny = isAnyType(type);
 
-    // Dynamic matches all type checks, so only emit it if required.
+    // "any" matches all type checks, so only emit it if required.
     if (!isAny) {
       _writeTypeCheckCondition(
           buffer, null, valueCode, type, 'nullLspJsonReporter');
@@ -552,10 +580,13 @@
 
     // The code to construct a value with this "side" of the union.
     buffer.write('${union.dartTypeWithTypeArgs}.t${i + 1}(');
-    _writeFromJsonCode(buffer, type, valueCode,
-        allowsNull: false, // null is already handled above this loop
-        requiresBracesInInterpolation:
-            requiresBracesInInterpolation); // Call recursively!
+    // Call recursively as unions may be nested.
+    _writeFromJsonCode(
+      buffer, type, valueCode,
+      // null + type checks are already handled above this loop
+      allowsNull: false,
+      requiresCast: false,
+    );
     buffer.write(')');
 
     // If we output the type condition at the top, prepare for the next condition.
@@ -570,8 +601,7 @@
   // Fill the final parens with a throw because if we fell through all of the
   // cases then the value we had didn't match any of the types in the union.
   if (hasIncompleteCondition) {
-    var interpolation =
-        requiresBracesInInterpolation ? '\${$valueCode}' : '\$$valueCode';
+    var interpolation = '\$$valueCode';
     buffer.write(
         "throw '''$interpolation was not one of (${union.types.map((t) => t.dartTypeWithTypeArgs).join(', ')})'''");
   }
@@ -583,7 +613,7 @@
   final allFields = _getAllFields(interface);
   buffer
     ..writeIndentedln('static ${interface.nameWithTypeArgs} '
-        'fromJson${interface.typeArgsString}(Map<String, dynamic> json) {')
+        'fromJson${interface.typeArgsString}(Map<String, Object?> json) {')
     ..indent();
   // First check whether any of our subclasses can deserialise this.
   for (final subclassName in _subtypes[interface.name] ?? const <String>[]) {
@@ -597,10 +627,13 @@
       ..writeIndentedln('}');
   }
   for (final field in allFields) {
-    buffer.writeIndented('final ${field.name} = ');
-    _writeFromJsonCode(buffer, field.type, "json['${field.name}']",
-        allowsNull: field.allowsNull || field.allowsUndefined,
-        requiresBracesInInterpolation: true);
+    // Add a local variable to allow type promotion (and avoid multiple lookups).
+    final localName = _makeValidIdentifier(field.name);
+    final localNameJson = '${localName}Json';
+    buffer.writeIndented("final $localNameJson = json['${field.name}'];");
+    buffer.writeIndented('final $localName = ');
+    _writeFromJsonCode(buffer, field.type, localNameJson,
+        allowsNull: field.allowsNull || field.allowsUndefined);
     buffer.writeln(';');
   }
   buffer
@@ -760,9 +793,9 @@
   // It's important the name we use for the map here isn't in use in the object
   // already. 'result' was, so we prefix it with some underscores.
   buffer
-    ..writeIndentedln('Map<String, dynamic> toJson() {')
+    ..writeIndentedln('Map<String, Object?> toJson() {')
     ..indent()
-    ..writeIndentedln('var __result = <String, dynamic>{};');
+    ..writeIndentedln('var __result = <String, Object?>{};');
   // ResponseMessage must confirm to JSON-RPC which says only one of
   // result/error can be included. Since this isn't encoded in the types we
   // need to special-case it's toJson generation.
@@ -806,7 +839,7 @@
 
   final dartType = type.dartType;
   final fullDartType = type.dartTypeWithTypeArgs;
-  if (fullDartType == 'dynamic') {
+  if (fullDartType == 'Object?') {
     buffer.write('true');
   } else if (_isSimpleType(type)) {
     buffer.write('$valueCode is $fullDartType');
@@ -816,7 +849,7 @@
     buffer.write('$dartType.canParse($valueCode, $reporter)');
   } else if (type is ArrayType) {
     buffer.write('($valueCode is List');
-    if (fullDartType != 'dynamic') {
+    if (fullDartType != 'Object?') {
       // TODO(dantup): If we're happy to assume we never have two lists in a union
       // we could skip this bit.
       buffer.write(' && ($valueCode.every((item) => ');
@@ -827,7 +860,7 @@
     buffer.write(')');
   } else if (type is MapType) {
     buffer.write('($valueCode is Map');
-    if (fullDartType != 'dynamic') {
+    if (fullDartType != 'Object?') {
       buffer..write(' && (')..write('$valueCode.keys.every((item) => ');
       _writeTypeCheckCondition(
           buffer, interface, 'item', type.indexType, reporter);
diff --git a/pkg/analysis_server/tool/lsp_spec/typescript.dart b/pkg/analysis_server/tool/lsp_spec/typescript.dart
index 5ebb88d..e0b3812 100644
--- a/pkg/analysis_server/tool/lsp_spec/typescript.dart
+++ b/pkg/analysis_server/tool/lsp_spec/typescript.dart
@@ -98,7 +98,7 @@
     },
     'ResponseError': {
       'code': 'ErrorCodes',
-      // This is dynamic normally, but since this class can be serialised
+      // This is Object? normally, but since this class can be serialised
       // we will crash if it data is set to something that can't be converted to
       // JSON (for ex. Uri) so this forces anyone setting this to convert to a
       // String.
diff --git a/pkg/analysis_server/tool/lsp_spec/typescript_parser.dart b/pkg/analysis_server/tool/lsp_spec/typescript_parser.dart
index e3cc2c6..f889c0f 100644
--- a/pkg/analysis_server/tool/lsp_spec/typescript_parser.dart
+++ b/pkg/analysis_server/tool/lsp_spec/typescript_parser.dart
@@ -507,17 +507,17 @@
   /// Returns the next token without advancing.
   Token _peek() => _tokenAt(_current);
 
-  /// Remove any duplicate types (for ex. if we map multiple types into dynamic)
-  /// we don't want to end up with `dynamic | dynamic`. Key on dartType to
+  /// Remove any duplicate types (for ex. if we map multiple types into Object?)
+  /// we don't want to end up with `Object? | Object?`. Key on dartType to
   /// ensure we different types that will map down to the same type.
   TypeBase _simplifyUnionTypes(List<TypeBase> types) {
     final uniqueTypes = Map.fromEntries(
       types.map((t) => MapEntry(t.uniqueTypeIdentifier, t)),
     ).values.toList();
 
-    // If our list includes something that maps to dynamic as well as other
-    // types, we should just treat the whole thing as dynamic as we get no value
-    // typing Either4<bool, String, num, dynamic> but it becomes much more
+    // If our list includes something that maps to Object? as well as other
+    // types, we should just treat the whole thing as Object? as we get no value
+    // typing Either4<bool, String, num, Object?> but it becomes much more
     // difficult to use.
     if (uniqueTypes.any(isAnyType)) {
       return uniqueTypes.firstWhere(isAnyType);
@@ -954,8 +954,8 @@
       'number': 'num',
       'integer': 'int',
       'uinteger': 'int',
-      'any': 'dynamic',
-      'object': 'dynamic',
+      'any': 'Object?',
+      'object': 'Object?',
       // Simplify MarkedString from
       //     string | { language: string; value: string }
       // to just String
@@ -1001,7 +1001,7 @@
   String get typeArgsString;
 
   /// A unique identifier for this type. Used for folding types together
-  /// (for example two types that resolve to "dynamic" in Dart).
+  /// (for example two types that resolve to "Object?" in Dart).
   String get uniqueTypeIdentifier => dartTypeWithTypeArgs;
 }
 
diff --git a/pkg/analyzer/lib/src/pubspec/pubspec_validator.dart b/pkg/analyzer/lib/src/pubspec/pubspec_validator.dart
index b0ab45b..012f7e2 100644
--- a/pkg/analyzer/lib/src/pubspec/pubspec_validator.dart
+++ b/pkg/analyzer/lib/src/pubspec/pubspec_validator.dart
@@ -95,6 +95,8 @@
 
   /// Validate the given [contents].
   List<AnalysisError> validate(Map<dynamic, YamlNode> contents) {
+    // TODO(brianwilkerson) This method needs to take a `YamlDocument` rather
+    //  than the contents of the document so that it can validate an empty file.
     RecordingErrorListener recorder = RecordingErrorListener();
     ErrorReporter reporter = ErrorReporter(
       recorder,
diff --git a/pkg/analyzer_plugin/lib/src/utilities/change_builder/change_builder_core.dart b/pkg/analyzer_plugin/lib/src/utilities/change_builder/change_builder_core.dart
index 8341d33..15c9c4f 100644
--- a/pkg/analyzer_plugin/lib/src/utilities/change_builder/change_builder_core.dart
+++ b/pkg/analyzer_plugin/lib/src/utilities/change_builder/change_builder_core.dart
@@ -11,9 +11,12 @@
 import 'package:analyzer/src/generated/source.dart';
 import 'package:analyzer_plugin/protocol/protocol_common.dart';
 import 'package:analyzer_plugin/src/utilities/change_builder/change_builder_dart.dart';
+import 'package:analyzer_plugin/src/utilities/change_builder/change_builder_yaml.dart';
 import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
 import 'package:analyzer_plugin/utilities/change_builder/change_builder_dart.dart';
+import 'package:analyzer_plugin/utilities/change_builder/change_builder_yaml.dart';
 import 'package:analyzer_plugin/utilities/change_builder/change_workspace.dart';
+import 'package:yaml/yaml.dart';
 
 /// A builder used to build a [SourceChange].
 class ChangeBuilderImpl implements ChangeBuilder {
@@ -45,6 +48,9 @@
   /// A map of absolute normalized path to Dart file edit builders.
   final Map<String, DartFileEditBuilderImpl> _dartFileEditBuilders = {};
 
+  /// A map of absolute normalized path to YAML file edit builders.
+  final Map<String, YamlFileEditBuilderImpl> _yamlFileEditBuilders = {};
+
   /// Initialize a newly created change builder. If the builder will be used to
   /// create changes for Dart files, then either a [session] or a [workspace]
   /// must be provided (but not both).
@@ -71,6 +77,12 @@
         builder.finalize();
       }
     }
+    for (var builder in _yamlFileEditBuilders.values) {
+      if (builder.hasEdits) {
+        change.addFileEdit(builder.fileEdit);
+        builder.finalize();
+      }
+    }
     _linkedEditGroups.forEach((String name, LinkedEditGroup group) {
       change.addLinkedEditGroup(group);
     });
@@ -89,6 +101,10 @@
       throw StateError("Can't create both a generic file edit and a dart file "
           'edit for the same file');
     }
+    if (_yamlFileEditBuilders.containsKey(path)) {
+      throw StateError("Can't create both a yaml file edit and a dart file "
+          'edit for the same file');
+    }
     var builder = _dartFileEditBuilders[path];
     if (builder == null) {
       builder = await _createDartFileEditBuilder(path);
@@ -106,7 +122,11 @@
   Future<void> addGenericFileEdit(
       String path, void Function(FileEditBuilder builder) buildFileEdit) async {
     if (_dartFileEditBuilders.containsKey(path)) {
-      throw StateError("Can't create both a generic file edit and a dart file "
+      throw StateError("Can't create both a dart file edit and a generic file "
+          'edit for the same file');
+    }
+    if (_yamlFileEditBuilders.containsKey(path)) {
+      throw StateError("Can't create both a yaml file edit and a generic file "
           'edit for the same file');
     }
     var builder = _genericFileEditBuilders[path];
@@ -118,6 +138,35 @@
   }
 
   @override
+  Future<void> addYamlFileEdit(String path,
+      void Function(YamlFileEditBuilder builder) buildFileEdit) async {
+    if (_dartFileEditBuilders.containsKey(path)) {
+      throw StateError("Can't create both a dart file edit and a yaml file "
+          'edit for the same file');
+    }
+    if (_genericFileEditBuilders.containsKey(path)) {
+      throw StateError("Can't create both a generic file edit and a yaml file "
+          'edit for the same file');
+    }
+    var builder = _yamlFileEditBuilders[path];
+    if (builder == null) {
+      builder = YamlFileEditBuilderImpl(
+          this,
+          path,
+          loadYamlDocument(
+              workspace
+                  .getSession(path)!
+                  .resourceProvider
+                  .getFile(path)
+                  .readAsStringSync(),
+              recover: true),
+          0);
+      _yamlFileEditBuilders[path] = builder;
+    }
+    buildFileEdit(builder);
+  }
+
+  @override
   ChangeBuilder copy() {
     var copy = ChangeBuilderImpl(workspace: workspace, eol: eol);
     for (var entry in _linkedEditGroups.entries) {
@@ -154,6 +203,9 @@
         copy._dartFileEditBuilders[entry.key] = newBuilder;
       }
     }
+    for (var entry in _yamlFileEditBuilders.entries) {
+      copy._yamlFileEditBuilders[entry.key] = entry.value.copyWith(copy);
+    }
     return copy;
   }
 
diff --git a/pkg/analyzer_plugin/lib/src/utilities/change_builder/change_builder_yaml.dart b/pkg/analyzer_plugin/lib/src/utilities/change_builder/change_builder_yaml.dart
new file mode 100644
index 0000000..6e37763
--- /dev/null
+++ b/pkg/analyzer_plugin/lib/src/utilities/change_builder/change_builder_yaml.dart
@@ -0,0 +1,82 @@
+// 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:analyzer/src/generated/source.dart';
+import 'package:analyzer_plugin/src/utilities/change_builder/change_builder_core.dart';
+import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
+import 'package:analyzer_plugin/utilities/change_builder/change_builder_yaml.dart';
+import 'package:yaml/yaml.dart';
+
+/// An [EditBuilder] used to build edits in YAML files.
+class YamlEditBuilderImpl extends EditBuilderImpl implements YamlEditBuilder {
+  /// Initialize a newly created builder to build a source edit.
+  YamlEditBuilderImpl(
+      YamlFileEditBuilderImpl sourceFileEditBuilder, int offset, int length)
+      : super(sourceFileEditBuilder, offset, length);
+
+  YamlFileEditBuilderImpl get dartFileEditBuilder =>
+      fileEditBuilder as YamlFileEditBuilderImpl;
+
+  @override
+  void addLinkedEdit(String groupName,
+          void Function(YamlLinkedEditBuilder builder) buildLinkedEdit) =>
+      super.addLinkedEdit(groupName,
+          (builder) => buildLinkedEdit(builder as YamlLinkedEditBuilder));
+
+  @override
+  LinkedEditBuilderImpl createLinkedEditBuilder() {
+    return YamlLinkedEditBuilderImpl(this);
+  }
+
+  /// Returns the indentation with the given [level].
+  String getIndent(int level) => '  ' * level;
+}
+
+/// A [FileEditBuilder] used to build edits for YAML files.
+class YamlFileEditBuilderImpl extends FileEditBuilderImpl
+    implements YamlFileEditBuilder {
+  /// The document parsed from the file contents.
+  final YamlDocument document;
+
+  /// Initialize a newly created builder to build a source file edit within the
+  /// change being built by the given [changeBuilder]. The file being edited has
+  /// the given [filePath], [document], and [timeStamp].
+  YamlFileEditBuilderImpl(ChangeBuilderImpl changeBuilder, String filePath,
+      this.document, int timeStamp)
+      : super(changeBuilder, filePath, timeStamp);
+
+  @override
+  void addInsertion(
+          int offset, void Function(YamlEditBuilder builder) buildEdit) =>
+      super.addInsertion(
+          offset, (builder) => buildEdit(builder as YamlEditBuilder));
+
+  @override
+  void addReplacement(SourceRange range,
+          void Function(YamlEditBuilder builder) buildEdit) =>
+      super.addReplacement(
+          range, (builder) => buildEdit(builder as YamlEditBuilder));
+
+  @override
+  YamlFileEditBuilderImpl copyWith(ChangeBuilderImpl changeBuilder,
+      {Map<YamlFileEditBuilderImpl, YamlFileEditBuilderImpl> editBuilderMap =
+          const {}}) {
+    var copy = YamlFileEditBuilderImpl(
+        changeBuilder, fileEdit.file, document, fileEdit.fileStamp);
+    copy.fileEdit.edits.addAll(fileEdit.edits);
+    return copy;
+  }
+
+  @override
+  EditBuilderImpl createEditBuilder(int offset, int length) {
+    return YamlEditBuilderImpl(this, offset, length);
+  }
+}
+
+/// A [LinkedEditBuilder] used to build linked edits for YAML files.
+class YamlLinkedEditBuilderImpl extends LinkedEditBuilderImpl
+    implements YamlLinkedEditBuilder {
+  /// Initialize a newly created linked edit builder.
+  YamlLinkedEditBuilderImpl(EditBuilderImpl editBuilder) : super(editBuilder);
+}
diff --git a/pkg/analyzer_plugin/lib/utilities/change_builder/change_builder_core.dart b/pkg/analyzer_plugin/lib/utilities/change_builder/change_builder_core.dart
index d64f540..e407543 100644
--- a/pkg/analyzer_plugin/lib/utilities/change_builder/change_builder_core.dart
+++ b/pkg/analyzer_plugin/lib/utilities/change_builder/change_builder_core.dart
@@ -7,6 +7,7 @@
 import 'package:analyzer_plugin/protocol/protocol_common.dart';
 import 'package:analyzer_plugin/src/utilities/change_builder/change_builder_core.dart';
 import 'package:analyzer_plugin/utilities/change_builder/change_builder_dart.dart';
+import 'package:analyzer_plugin/utilities/change_builder/change_builder_yaml.dart';
 import 'package:analyzer_plugin/utilities/change_builder/change_workspace.dart';
 
 /// A builder used to build a [SourceChange].
@@ -49,6 +50,15 @@
   Future<void> addGenericFileEdit(
       String path, void Function(FileEditBuilder builder) buildFileEdit);
 
+  /// Use the [buildFileEdit] function to create a collection of edits to the
+  /// file with the given [path]. The edits will be added to the source change
+  /// that is being built.
+  ///
+  /// The builder passed to the [buildFileEdit] function has additional support
+  /// for working with YAML source files.
+  Future<void> addYamlFileEdit(
+      String path, void Function(YamlFileEditBuilder builder) buildFileEdit);
+
   /// Return a copy of this change builder that is constructed in such as was
   /// that changes to the copy will not effect this change builder.
   ChangeBuilder copy();
diff --git a/pkg/analyzer_plugin/lib/utilities/change_builder/change_builder_yaml.dart b/pkg/analyzer_plugin/lib/utilities/change_builder/change_builder_yaml.dart
new file mode 100644
index 0000000..581516e
--- /dev/null
+++ b/pkg/analyzer_plugin/lib/utilities/change_builder/change_builder_yaml.dart
@@ -0,0 +1,33 @@
+// 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:analyzer/src/generated/source.dart';
+import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
+
+/// An [EditBuilder] used to build edits in YAML files.
+///
+/// Clients may not extend, implement or mix-in this class.
+abstract class YamlEditBuilder implements EditBuilder {
+  @override
+  void addLinkedEdit(String groupName,
+      void Function(YamlLinkedEditBuilder builder) buildLinkedEdit);
+}
+
+/// A [FileEditBuilder] used to build edits for YAML files.
+///
+/// Clients may not extend, implement or mix-in this class.
+abstract class YamlFileEditBuilder implements FileEditBuilder {
+  @override
+  void addInsertion(
+      int offset, void Function(YamlEditBuilder builder) buildEdit);
+
+  @override
+  void addReplacement(
+      SourceRange range, void Function(YamlEditBuilder builder) buildEdit);
+}
+
+/// A [LinkedEditBuilder] used to build linked edits for YAML files.
+///
+/// Clients may not extend, implement or mix-in this class.
+abstract class YamlLinkedEditBuilder implements LinkedEditBuilder {}
diff --git a/pkg/analyzer_plugin/pubspec.yaml b/pkg/analyzer_plugin/pubspec.yaml
index 1a166c4..1ee70fe 100644
--- a/pkg/analyzer_plugin/pubspec.yaml
+++ b/pkg/analyzer_plugin/pubspec.yaml
@@ -11,6 +11,7 @@
   collection: ^1.15.0
   dart_style: ^2.0.0
   pub_semver: ^2.0.0
+  yaml: ^3.0.0
 
 dev_dependencies:
   analyzer_utilities:
diff --git a/pkg/analyzer_plugin/test/src/utilities/change_builder/change_builder_core_test.dart b/pkg/analyzer_plugin/test/src/utilities/change_builder/change_builder_core_test.dart
index 4d1c17e..a571f04 100644
--- a/pkg/analyzer_plugin/test/src/utilities/change_builder/change_builder_core_test.dart
+++ b/pkg/analyzer_plugin/test/src/utilities/change_builder/change_builder_core_test.dart
@@ -2,6 +2,7 @@
 // for 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/file_system/memory_file_system.dart';
 import 'package:analyzer/src/generated/source.dart';
 import 'package:analyzer_plugin/protocol/protocol_common.dart';
 import 'package:analyzer_plugin/src/utilities/change_builder/change_builder_core.dart';
@@ -21,10 +22,19 @@
   });
 }
 
+abstract class AbstractChangeBuilderTest {
+  MemoryResourceProvider resourceProvider = MemoryResourceProvider();
+
+  late ChangeBuilderImpl builder;
+
+  void setUp() {
+    builder = ChangeBuilderImpl(session: MockAnalysisSession(resourceProvider));
+  }
+}
+
 @reflectiveTest
-class ChangeBuilderImplTest {
+class ChangeBuilderImplTest extends AbstractChangeBuilderTest {
   void test_copy_empty() {
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     var copy = builder.copy() as ChangeBuilderImpl;
     expect(identical(copy, builder), isFalse);
     expect(copy.workspace, builder.workspace);
@@ -32,7 +42,6 @@
   }
 
   Future<void> test_copy_newEdit() async {
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     await builder.addGenericFileEdit('/test.dart', (builder) {
       builder.addSimpleInsertion(0, 'x');
     });
@@ -45,7 +54,6 @@
   }
 
   Future<void> test_copy_newFile() async {
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     await builder.addGenericFileEdit('/test1.dart', (builder) {
       builder.addSimpleInsertion(0, 'x');
     });
@@ -58,7 +66,6 @@
   }
 
   Future<void> test_copy_newLinkedEditGroup() async {
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     await builder.addGenericFileEdit('/test.dart', (builder) {
       builder.addLinkedPosition(SourceRange(1, 2), 'a');
     });
@@ -71,7 +78,6 @@
   }
 
   Future<void> test_copy_newLinkedPosition() async {
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     await builder.addGenericFileEdit('/test.dart', (builder) {
       builder.addLinkedPosition(SourceRange(1, 2), 'a');
     });
@@ -84,7 +90,6 @@
   }
 
   Future<void> test_copy_selection() async {
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     builder.setSelection(Position('/test.dart', 5));
     var copy = builder.copy() as ChangeBuilderImpl;
     copy.setSelection(Position('/test.dart', 10));
@@ -93,7 +98,6 @@
   }
 
   void test_getLinkedEditGroup() {
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     var group = builder.getLinkedEditGroup('a');
     expect(identical(builder.getLinkedEditGroup('b'), group), isFalse);
     expect(identical(builder.getLinkedEditGroup('a'), group), isTrue);
@@ -101,13 +105,11 @@
 
   void test_setSelection() {
     var position = Position('test.dart', 3);
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     builder.setSelection(position);
     expect(builder.sourceChange.selection, position);
   }
 
   void test_sourceChange_emptyEdit() async {
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     var path = '/test.dart';
     await builder.addGenericFileEdit(path, (builder) {});
     var sourceChange = builder.sourceChange;
@@ -119,7 +121,6 @@
   }
 
   void test_sourceChange_noEdits() {
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     var sourceChange = builder.sourceChange;
     expect(sourceChange, isNotNull);
     expect(sourceChange.edits, isEmpty);
@@ -129,7 +130,6 @@
   }
 
   Future<void> test_sourceChange_oneChange() async {
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     var path = '/test.dart';
     await builder.addGenericFileEdit(path, (builder) {
       builder.addSimpleInsertion(0, '_');
@@ -145,11 +145,10 @@
 }
 
 @reflectiveTest
-class EditBuilderImplTest {
+class EditBuilderImplTest extends AbstractChangeBuilderTest {
   String path = '/test.dart';
 
   Future<void> test_addLinkedEdit() async {
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     var offset = 10;
     var text = 'content';
     await builder.addGenericFileEdit(path, (builder) {
@@ -174,7 +173,6 @@
   }
 
   Future<void> test_addSimpleLinkedEdit() async {
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     var offset = 10;
     var text = 'content';
     await builder.addGenericFileEdit(path, (builder) {
@@ -197,7 +195,6 @@
   }
 
   Future<void> test_createLinkedEditBuilder() async {
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     await builder.addGenericFileEdit(path, (builder) {
       builder.addInsertion(10, (builder) {
         var linkBuilder =
@@ -208,7 +205,6 @@
   }
 
   Future<void> test_selectHere() async {
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     await builder.addGenericFileEdit(path, (builder) {
       builder.addInsertion(10, (EditBuilder builder) {
         builder.selectHere();
@@ -218,7 +214,6 @@
   }
 
   Future<void> test_write() async {
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     var offset = 10;
     var text = 'write';
     await builder.addGenericFileEdit(path, (builder) {
@@ -246,7 +241,6 @@
   }
 
   Future<void> test_writeln_withoutText() async {
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     var offset = 52;
     var length = 12;
     await builder.addGenericFileEdit(path, (builder) {
@@ -274,7 +268,6 @@
   }
 
   Future<void> test_writeln_withText() async {
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     var offset = 52;
     var length = 12;
     var text = 'writeln';
@@ -305,13 +298,12 @@
 }
 
 @reflectiveTest
-class FileEditBuilderImplTest {
+class FileEditBuilderImplTest extends AbstractChangeBuilderTest {
   String path = '/test.dart';
 
   Future<void> test_addDeletion() async {
     var offset = 23;
     var length = 7;
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     await builder.addGenericFileEdit(path, (builder) {
       builder.addDeletion(SourceRange(offset, length));
     });
@@ -330,7 +322,6 @@
     var firstLength = 7;
     var secondOffset = 30;
     var secondLength = 5;
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     await builder.addGenericFileEdit(path, (builder) {
       builder.addDeletion(SourceRange(firstOffset, firstLength));
       builder.addDeletion(SourceRange(secondOffset, secondLength));
@@ -353,7 +344,6 @@
     var firstLength = 7;
     var secondOffset = 30;
     var secondLength = 5;
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     await builder.addGenericFileEdit(path, (builder) {
       builder.addDeletion(SourceRange(secondOffset, secondLength));
       builder.addDeletion(SourceRange(firstOffset, firstLength));
@@ -375,7 +365,6 @@
     var firstLength = 7;
     var secondOffset = 27;
     var secondLength = 8;
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     await builder.addGenericFileEdit(path, (builder) {
       builder.addDeletion(SourceRange(firstOffset, firstLength));
       builder.addDeletion(SourceRange(secondOffset, secondLength));
@@ -388,7 +377,6 @@
   }
 
   Future<void> test_addInsertion() async {
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     await builder.addGenericFileEdit(path, (builder) {
       builder.addInsertion(10, (builder) {
         expect(builder, isNotNull);
@@ -397,7 +385,6 @@
   }
 
   Future<void> test_addLinkedPosition() async {
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     var groupName = 'a';
     await builder.addGenericFileEdit(path, (builder) {
       builder.addLinkedPosition(SourceRange(3, 6), groupName);
@@ -413,7 +400,6 @@
   }
 
   Future<void> test_addReplacement() async {
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     await builder.addGenericFileEdit(path, (builder) {
       builder.addReplacement(SourceRange(4, 5), (builder) {
         expect(builder, isNotNull);
@@ -424,7 +410,6 @@
   Future<void> test_addSimpleInsertion() async {
     var offset = 23;
     var text = 'xyz';
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     await builder.addGenericFileEdit(path, (builder) {
       builder.addSimpleInsertion(offset, text);
     });
@@ -438,7 +423,6 @@
   Future<void> test_addSimpleInsertion_sameOffset() async {
     var offset = 23;
     var text = 'xyz';
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     await builder.addGenericFileEdit(path, (builder) {
       builder.addSimpleInsertion(offset, text);
       builder.addSimpleInsertion(offset, 'abc');
@@ -457,7 +441,6 @@
     var offset = 23;
     var length = 7;
     var text = 'xyz';
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     await builder.addGenericFileEdit(path, (builder) {
       builder.addSimpleReplacement(SourceRange(offset, length), text);
     });
@@ -474,7 +457,6 @@
     var secondOffset = firstOffset + firstLength;
     var secondLength = 5;
     var text = 'xyz';
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     await builder.addGenericFileEdit(path, (builder) {
       builder.addSimpleReplacement(SourceRange(firstOffset, firstLength), text);
       builder.addSimpleReplacement(
@@ -494,7 +476,6 @@
     var offset = 23;
     var length = 7;
     var text = 'xyz';
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     await builder.addGenericFileEdit(path, (builder) {
       builder.addSimpleReplacement(SourceRange(offset, length), text);
       expect(() {
@@ -512,7 +493,6 @@
     var offset = 23;
     var length = 7;
     var text = 'xyz';
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     await builder.addGenericFileEdit(path, (builder) {
       builder.addSimpleReplacement(SourceRange(offset, length), text);
       expect(() {
@@ -527,7 +507,6 @@
   }
 
   Future<void> test_createEditBuilder() async {
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     await builder.addGenericFileEdit(path, (builder) {
       var offset = 4;
       var length = 5;
@@ -543,12 +522,11 @@
 }
 
 @reflectiveTest
-class LinkedEditBuilderImplTest {
+class LinkedEditBuilderImplTest extends AbstractChangeBuilderTest {
   String path = '/test.dart';
 
   Future<void> test_addSuggestion() async {
     var groupName = 'a';
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     await builder.addGenericFileEdit(path, (builder) {
       builder.addInsertion(10, (builder) {
         builder.addLinkedEdit(groupName, (builder) {
@@ -564,7 +542,6 @@
 
   Future<void> test_addSuggestion_zeroLength() async {
     var groupName = 'a';
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     await builder.addGenericFileEdit(path, (builder) {
       builder.addInsertion(10, (builder) {
         builder.addLinkedEdit(groupName, (builder) {
@@ -578,7 +555,6 @@
 
   Future<void> test_addSuggestions() async {
     var groupName = 'a';
-    var builder = ChangeBuilderImpl(session: MockAnalysisSession());
     await builder.addGenericFileEdit(path, (builder) {
       builder.addInsertion(10, (builder) {
         builder.addLinkedEdit(groupName, (builder) {
diff --git a/pkg/analyzer_plugin/test/src/utilities/change_builder/change_builder_yaml_test.dart b/pkg/analyzer_plugin/test/src/utilities/change_builder/change_builder_yaml_test.dart
new file mode 100644
index 0000000..866316c
--- /dev/null
+++ b/pkg/analyzer_plugin/test/src/utilities/change_builder/change_builder_yaml_test.dart
@@ -0,0 +1,107 @@
+// 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:analyzer/src/generated/source.dart';
+import 'package:analyzer_plugin/protocol/protocol_common.dart';
+import 'package:analyzer_plugin/src/utilities/change_builder/change_builder_yaml.dart';
+import 'package:analyzer_plugin/utilities/range_factory.dart';
+import 'package:test/test.dart';
+import 'package:test_reflective_loader/test_reflective_loader.dart';
+
+import 'change_builder_core_test.dart';
+
+void main() {
+  defineReflectiveSuite(() {
+    defineReflectiveTests(ChangeBuilderImplTest);
+    defineReflectiveTests(YamlEditBuilderImplTest);
+    defineReflectiveTests(YamlFileEditBuilderImplTest);
+    defineReflectiveTests(YamlLinkedEditBuilderImplTest);
+  });
+}
+
+class AbstractYamlChangeBuilderTest extends AbstractChangeBuilderTest {
+  String get testFilePath => '/home/my/pubspec.yaml';
+
+  void createPubspec(String content) {
+    resourceProvider.newFile(testFilePath, content);
+  }
+}
+
+@reflectiveTest
+class ChangeBuilderImplTest extends AbstractYamlChangeBuilderTest {
+  Future<void> test_addYamlFileEdit() async {
+    createPubspec('''
+name: my
+''');
+    await builder.addYamlFileEdit(testFilePath, (builder) {
+      expect(builder, isA<YamlFileEditBuilderImpl>());
+    });
+  }
+}
+
+@reflectiveTest
+class YamlEditBuilderImplTest extends AbstractYamlChangeBuilderTest {
+  Future<void> test_addLinkedEdit() async {
+    createPubspec('''
+name: my
+''');
+    await builder.addYamlFileEdit(testFilePath, (builder) {
+      builder.addReplacement(range.startOffsetEndOffset(6, 8), (builder) {
+        expect(builder, isA<YamlEditBuilderImpl>());
+        builder.addLinkedEdit('group', (builder) {
+          expect(builder, isA<YamlLinkedEditBuilderImpl>());
+          builder.write('test');
+        });
+      });
+    });
+    var sourceChange = builder.sourceChange;
+    expect(sourceChange, isNotNull);
+    var groups = sourceChange.linkedEditGroups;
+    expect(groups, hasLength(1));
+    var group = groups[0];
+    expect(group, isNotNull);
+    expect(group.length, 4);
+    var positions = group.positions;
+    expect(positions, hasLength(1));
+    expect(positions[0].offset, 6);
+  }
+}
+
+@reflectiveTest
+class YamlFileEditBuilderImplTest extends AbstractYamlChangeBuilderTest {
+  Future<void> test_addDeletion() async {
+    createPubspec('''
+name: my test
+''');
+    await builder.addGenericFileEdit(testFilePath, (builder) {
+      builder.addDeletion(SourceRange(6, 3));
+    });
+    var edits = builder.sourceChange.edits[0].edits;
+    expect(edits, hasLength(1));
+    expect(edits[0].offset, 6);
+    expect(edits[0].length, 3);
+    expect(edits[0].replacement, isEmpty);
+  }
+}
+
+@reflectiveTest
+class YamlLinkedEditBuilderImplTest extends AbstractYamlChangeBuilderTest {
+  Future<void> test_addSuggestion() async {
+    createPubspec('''
+name: my
+''');
+    var groupName = 'group';
+    await builder.addYamlFileEdit(testFilePath, (builder) {
+      builder.addReplacement(range.startOffsetEndOffset(6, 8), (builder) {
+        builder.addLinkedEdit(groupName, (builder) {
+          builder.write('test');
+          builder.addSuggestion(
+              LinkedEditSuggestionKind.VARIABLE, 'suggestion');
+        });
+      });
+    });
+    var group = builder.getLinkedEditGroup(groupName);
+    expect(group.suggestions, hasLength(1));
+  }
+}
diff --git a/pkg/analyzer_plugin/test/src/utilities/change_builder/mocks.dart b/pkg/analyzer_plugin/test/src/utilities/change_builder/mocks.dart
index 5d31e68..3526ae0 100644
--- a/pkg/analyzer_plugin/test/src/utilities/change_builder/mocks.dart
+++ b/pkg/analyzer_plugin/test/src/utilities/change_builder/mocks.dart
@@ -1,13 +1,53 @@
+// 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:analyzer/dart/analysis/analysis_context.dart';
+import 'package:analyzer/dart/analysis/context_root.dart';
 import 'package:analyzer/dart/analysis/session.dart';
+import 'package:analyzer/file_system/file_system.dart';
 import 'package:analyzer_plugin/src/utilities/change_builder/change_builder_core.dart';
 
+class MockAnalysisContext implements AnalysisContext {
+  @override
+  ContextRoot contextRoot;
+
+  MockAnalysisContext(ResourceProvider resourceProvider)
+      : contextRoot = MockContextRoot(resourceProvider);
+
+  @override
+  dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
+}
+
 class MockAnalysisSession implements AnalysisSession {
   @override
+  ResourceProvider resourceProvider;
+
+  @override
+  AnalysisContext analysisContext;
+
+  MockAnalysisSession(this.resourceProvider)
+      : analysisContext = MockAnalysisContext(resourceProvider);
+
+  @override
   dynamic noSuchMethod(Invocation invocation) {
     return super.noSuchMethod(invocation);
   }
 }
 
+class MockContextRoot implements ContextRoot {
+  @override
+  ResourceProvider resourceProvider;
+
+  MockContextRoot(this.resourceProvider);
+
+  @override
+  bool isAnalyzed(String filePath) => true;
+
+  @override
+  dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
+}
+
 class MockEditBuilderImpl implements EditBuilderImpl {
   @override
   dynamic noSuchMethod(Invocation invocation) {
diff --git a/pkg/analyzer_plugin/test/src/utilities/change_builder/test_all.dart b/pkg/analyzer_plugin/test/src/utilities/change_builder/test_all.dart
index 59d3e82..acd7bdb 100644
--- a/pkg/analyzer_plugin/test/src/utilities/change_builder/test_all.dart
+++ b/pkg/analyzer_plugin/test/src/utilities/change_builder/test_all.dart
@@ -4,14 +4,16 @@
 
 import 'package:test_reflective_loader/test_reflective_loader.dart';
 
-import 'change_builder_core_test.dart' as change_builder_core_test;
-import 'change_builder_dart_test.dart' as change_builder_dart_test;
+import 'change_builder_core_test.dart' as change_builder_core;
+import 'change_builder_dart_test.dart' as change_builder_dart;
+import 'change_builder_yaml_test.dart' as change_builder_yaml;
 import 'dart/test_all.dart' as dart_all;
 
 void main() {
   defineReflectiveSuite(() {
-    change_builder_core_test.main();
-    change_builder_dart_test.main();
+    change_builder_core.main();
+    change_builder_dart.main();
+    change_builder_yaml.main();
     dart_all.main();
   });
 }
diff --git a/pkg/front_end/lib/src/api_prototype/front_end.dart b/pkg/front_end/lib/src/api_prototype/front_end.dart
index 1ef9263..3830dbe 100644
--- a/pkg/front_end/lib/src/api_prototype/front_end.dart
+++ b/pkg/front_end/lib/src/api_prototype/front_end.dart
@@ -2,8 +2,6 @@
 // for 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
-
 /// The Dart Front End contains logic to build summaries and kernel programs
 /// from Dart sources. The APIs exposed here are designed for tools in the Dart
 /// ecosystem that need to load sources and convert them to these formats.
diff --git a/pkg/front_end/lib/src/api_prototype/kernel_generator.dart b/pkg/front_end/lib/src/api_prototype/kernel_generator.dart
index 6e80dc5..ca6286c 100644
--- a/pkg/front_end/lib/src/api_prototype/kernel_generator.dart
+++ b/pkg/front_end/lib/src/api_prototype/kernel_generator.dart
@@ -2,8 +2,6 @@
 // for 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
-
 /// Defines the front-end API for converting source code to Dart Kernel objects.
 library front_end.kernel_generator;
 
@@ -47,12 +45,12 @@
 /// The input [source] is expected to be a script with a main method, otherwise
 /// an error is reported.
 // TODO(sigmund): rename to kernelForScript?
-Future<CompilerResult> kernelForProgram(
+Future<CompilerResult?> kernelForProgram(
     Uri source, CompilerOptions options) async {
   return (await kernelForProgramInternal(source, options));
 }
 
-Future<CompilerResult> kernelForProgramInternal(
+Future<CompilerResult?> kernelForProgramInternal(
     Uri source, CompilerOptions options,
     {bool retainDataForTesting: false, bool requireMain: true}) async {
   ProcessedOptions pOptions =
@@ -61,7 +59,7 @@
     CompilerResult result = await generateKernelInternal(
         includeHierarchyAndCoreTypes: true,
         retainDataForTesting: retainDataForTesting);
-    Component component = result?.component;
+    Component? component = result.component;
     if (component == null) return null;
 
     if (requireMain && component.mainMethod == null) {
@@ -104,12 +102,12 @@
 /// Result object for [kernelForProgram] and [kernelForModule].
 abstract class CompilerResult {
   /// The generated summary bytes, if it was requested.
-  List<int> get summary;
+  List<int>? get summary;
 
   /// The generated component, if it was requested.
-  Component get component;
+  Component? get component;
 
-  Component get sdkComponent;
+  Component? get sdkComponent;
 
   /// The components loaded from dill (excluding the sdk).
   List<Component> get loadedComponents;
@@ -121,8 +119,8 @@
   List<Uri> get deps;
 
   /// The [ClassHierarchy] for the compiled [component], if it was requested.
-  ClassHierarchy get classHierarchy;
+  ClassHierarchy? get classHierarchy;
 
   /// The [CoreTypes] object for the compiled [component], if it was requested.
-  CoreTypes get coreTypes;
+  CoreTypes? get coreTypes;
 }
diff --git a/pkg/front_end/lib/src/api_prototype/lowering_predicates.dart b/pkg/front_end/lib/src/api_prototype/lowering_predicates.dart
index 2f9f6df..cf307b8 100644
--- a/pkg/front_end/lib/src/api_prototype/lowering_predicates.dart
+++ b/pkg/front_end/lib/src/api_prototype/lowering_predicates.dart
@@ -2,8 +2,6 @@
 // for 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 'package:kernel/ast.dart';
 import '../fasta/kernel/late_lowering.dart';
 import '../fasta/source/source_extension_builder.dart' show extensionThisName;
@@ -28,6 +26,7 @@
 /// The default value of this field is `null`.
 bool isLateLoweredField(Field node) {
   return node.isInternalImplementation &&
+      // ignore: unnecessary_null_comparison
       node.name != null &&
       node.name.text.startsWith(lateFieldPrefix) &&
       !node.name.text.endsWith(lateIsSetSuffix);
@@ -56,7 +55,7 @@
   assert(isLateLoweredField(node));
   String prefix = lateFieldPrefix;
   if (node.isInstanceMember) {
-    prefix = '$prefix${node.enclosingClass.name}#';
+    prefix = '$prefix${node.enclosingClass!.name}#';
   }
   return new Name(node.name.text.substring(prefix.length), node.name.library);
 }
@@ -83,6 +82,7 @@
 /// The default value of this field is `false`.
 bool isLateLoweredIsSetField(Field node) {
   return node.isInternalImplementation &&
+      // ignore: unnecessary_null_comparison
       node.name != null &&
       node.name.text.startsWith(lateFieldPrefix) &&
       node.name.text.endsWith(lateIsSetSuffix);
@@ -114,7 +114,7 @@
   assert(isLateLoweredIsSetField(node));
   String prefix = lateFieldPrefix;
   if (node.isInstanceMember) {
-    prefix = '$prefix${node.enclosingClass.name}#';
+    prefix = '$prefix${node.enclosingClass!.name}#';
   }
   return new Name(
       node.name.text.substring(
@@ -143,7 +143,7 @@
 /// result should be cached on the use site if queried repeatedly.
 bool isLateLoweredFieldGetter(Procedure node) {
   if (node.kind == ProcedureKind.Getter) {
-    TreeNode parent = node.parent;
+    TreeNode? parent = node.parent;
     if (parent is Class) {
       return parent.fields.any((Field field) =>
           isLateLoweredField(field) &&
@@ -202,7 +202,7 @@
 /// result should be cached on the use site if queried repeatedly.
 bool isLateLoweredFieldSetter(Procedure node) {
   if (node.kind == ProcedureKind.Setter) {
-    TreeNode parent = node.parent;
+    TreeNode? parent = node.parent;
     if (parent is Class) {
       return parent.fields.any((Field field) =>
           isLateLoweredField(field) &&
@@ -265,19 +265,21 @@
 /// If the original late field had no initializer, `null` is returned.
 ///
 /// If [node] is not part of a late field lowering, `null` is returned.
-Expression getLateFieldInitializer(Member node) {
-  Procedure lateFieldGetter = _getLateFieldTarget(node);
+Expression? getLateFieldInitializer(Member node) {
+  Procedure? lateFieldGetter = _getLateFieldTarget(node);
   if (lateFieldGetter != null) {
-    Statement body = lateFieldGetter.function.body;
+    Statement body = lateFieldGetter.function.body!;
+    // TODO(johnniwinther): Rewrite to avoid `as X`.
     if (body is Block &&
         body.statements.length == 2 &&
         body.statements.first is IfStatement) {
-      IfStatement ifStatement = body.statements.first;
+      IfStatement ifStatement = body.statements.first as IfStatement;
       if (ifStatement.then is Block) {
-        Block block = ifStatement.then;
+        Block block = ifStatement.then as Block;
         if (block.statements.isNotEmpty &&
             block.statements.first is ExpressionStatement) {
-          ExpressionStatement firstStatement = block.statements.first;
+          ExpressionStatement firstStatement =
+              block.statements.first as ExpressionStatement;
           if (firstStatement.expression is PropertySet) {
             // We have
             //
@@ -290,7 +292,7 @@
             //    }
             //
             // in case `<init>` is the initializer.
-            PropertySet propertySet = firstStatement.expression;
+            PropertySet propertySet = firstStatement.expression as PropertySet;
             assert(propertySet.interfaceTarget == getLateFieldTarget(node));
             return propertySet.value;
           } else if (firstStatement.expression is InstanceSet) {
@@ -305,7 +307,7 @@
             //    }
             //
             // in case `<init>` is the initializer.
-            InstanceSet instanceSet = firstStatement.expression;
+            InstanceSet instanceSet = firstStatement.expression as InstanceSet;
             assert(instanceSet.interfaceTarget == getLateFieldTarget(node));
             return instanceSet.value;
           } else if (firstStatement.expression is StaticSet) {
@@ -320,7 +322,7 @@
             //    }
             //
             // in case `<init>` is the initializer.
-            StaticSet staticSet = firstStatement.expression;
+            StaticSet staticSet = firstStatement.expression as StaticSet;
             assert(staticSet.target == getLateFieldTarget(node));
             return staticSet.value;
           }
@@ -339,13 +341,14 @@
           //    }
           //
           // in case `<init>` is the initializer.
-          VariableDeclaration variableDeclaration = block.statements.first;
+          VariableDeclaration variableDeclaration =
+              block.statements.first as VariableDeclaration;
           return variableDeclaration.initializer;
         }
       }
       return null;
     } else if (body is ReturnStatement) {
-      Expression expression = body.expression;
+      Expression? expression = body.expression;
       if (expression is ConditionalExpression &&
           expression.otherwise is Throw) {
         // We have
@@ -416,8 +419,8 @@
 /// either the field holding the value, the field holding the marker for whether
 /// it has been set or not, getter for reading the value, or the setter for
 /// setting the value of the field.
-Procedure _getLateFieldTarget(Member node) {
-  Name lateFieldName;
+Procedure? _getLateFieldTarget(Member node) {
+  Name? lateFieldName;
   if (node is Procedure) {
     if (isLateLoweredFieldGetter(node)) {
       return node;
@@ -432,14 +435,14 @@
     }
   }
   if (lateFieldName != null) {
-    TreeNode parent = node.parent;
-    List<Procedure> procedures;
+    TreeNode? parent = node.parent;
+    List<Procedure>? procedures;
     if (parent is Class) {
       procedures = parent.procedures;
     } else if (parent is Library) {
       procedures = parent.procedures;
     }
-    return procedures.singleWhere((Procedure procedure) =>
+    return procedures!.singleWhere((Procedure procedure) =>
         isLateLoweredFieldGetter(procedure) &&
         extractFieldNameFromLateLoweredFieldGetter(procedure) == lateFieldName);
   }
@@ -469,8 +472,8 @@
 /// field.
 ///
 /// If [node] is not part of a late field lowering, `null` is returned.
-Field getLateFieldTarget(Member node) {
-  Name lateFieldName;
+Field? getLateFieldTarget(Member node) {
+  Name? lateFieldName;
   if (node is Procedure) {
     if (isLateLoweredFieldGetter(node)) {
       lateFieldName = extractFieldNameFromLateLoweredFieldGetter(node);
@@ -485,14 +488,14 @@
     }
   }
   if (lateFieldName != null) {
-    TreeNode parent = node.parent;
-    List<Field> fields;
+    TreeNode? parent = node.parent;
+    List<Field>? fields;
     if (parent is Class) {
       fields = parent.fields;
     } else if (parent is Library) {
       fields = parent.fields;
     }
-    return fields.singleWhere((Field field) =>
+    return fields!.singleWhere((Field field) =>
         isLateLoweredField(field) &&
         extractFieldNameFromLateLoweredField(field) == lateFieldName);
   }
@@ -520,8 +523,8 @@
 bool isLateLoweredLocal(VariableDeclaration node) {
   assert(node.isLowered ||
       node.name == null ||
-      !isLateLoweredLocalName(node.name));
-  return node.isLowered && isLateLoweredLocalName(node.name);
+      !isLateLoweredLocalName(node.name!));
+  return node.isLowered && isLateLoweredLocalName(node.name!);
 }
 
 /// Returns `true` if [name] is the name of a local variable holding the value
@@ -565,8 +568,8 @@
 bool isLateLoweredIsSetLocal(VariableDeclaration node) {
   assert(node.isLowered ||
       node.name == null ||
-      !isLateLoweredIsSetLocalName(node.name));
-  return node.isLowered && isLateLoweredIsSetLocalName(node.name);
+      !isLateLoweredIsSetLocalName(node.name!));
+  return node.isLowered && isLateLoweredIsSetLocalName(node.name!);
 }
 
 /// Returns `true` if [name] is the name of a local variable holding the marker
@@ -604,8 +607,8 @@
 bool isLateLoweredLocalGetter(VariableDeclaration node) {
   assert(node.isLowered ||
       node.name == null ||
-      !isLateLoweredLocalGetterName(node.name));
-  return node.isLowered && isLateLoweredLocalGetterName(node.name);
+      !isLateLoweredLocalGetterName(node.name!));
+  return node.isLowered && isLateLoweredLocalGetterName(node.name!);
 }
 
 /// Returns `true` if [name] is the name of the local variable for the local
@@ -645,8 +648,8 @@
 bool isLateLoweredLocalSetter(VariableDeclaration node) {
   assert(node.isLowered ||
       node.name == null ||
-      !isLateLoweredLocalSetterName(node.name));
-  return node.isLowered && isLateLoweredLocalSetterName(node.name);
+      !isLateLoweredLocalSetterName(node.name!));
+  return node.isLowered && isLateLoweredLocalSetterName(node.name!);
 }
 
 /// Returns `true` if [name] is the name of the local variable for the local
@@ -688,7 +691,7 @@
 
 /// Returns `true` if [name] is the name of the synthetic parameter holding the
 /// `this` value in the encoding of extension instance members.
-bool isExtensionThisName(String name) {
+bool isExtensionThisName(String? name) {
   return name == extensionThisName;
 }
 
@@ -708,9 +711,9 @@
 ///
 /// Note that the name can be `null` in case of a synthetic variable created
 /// for instance for encoding of `?.`.
-String extractLocalNameFromVariable(VariableDeclaration node) {
+String? extractLocalNameFromVariable(VariableDeclaration node) {
   if (node.isLowered) {
-    String name = _extractLocalName(node.name);
+    String? name = _extractLocalName(node.name!);
     if (name == null) {
       throw new UnsupportedError("Unrecognized lowered local $node");
     }
@@ -732,7 +735,7 @@
 /// Returns the original name of a lowered variable by the given [name].
 ///
 /// If [name] doesn't correspond to a lowered name `null` is returned.
-String _extractLocalName(String name) {
+String? _extractLocalName(String name) {
   if (isExtensionThisName(name)) {
     return extractLocalNameForExtensionThis(name);
   } else if (isLateLoweredLocalName(name)) {
diff --git a/pkg/front_end/lib/src/api_prototype/summary_generator.dart b/pkg/front_end/lib/src/api_prototype/summary_generator.dart
index 0492289..dc0260b 100644
--- a/pkg/front_end/lib/src/api_prototype/summary_generator.dart
+++ b/pkg/front_end/lib/src/api_prototype/summary_generator.dart
@@ -2,8 +2,6 @@
 // for 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
-
 /// Defines the front-end API for converting source code to summaries.
 library front_end.summary_generator;
 
@@ -30,12 +28,12 @@
 /// was compiled from sources.
 ///
 /// The return value is a list of bytes to write to the summary file.
-Future<List<int>> summaryFor(List<Uri> sources, CompilerOptions options,
+Future<List<int>?> summaryFor(List<Uri> sources, CompilerOptions options,
     {bool truncate: false}) async {
   return (await generateKernel(
           new ProcessedOptions(options: options, inputs: sources),
           buildSummary: true,
           buildComponent: false,
           truncateSummary: truncate))
-      ?.summary;
+      .summary;
 }
diff --git a/pkg/front_end/lib/src/base/processed_options.dart b/pkg/front_end/lib/src/base/processed_options.dart
index 68d1a44..a430965c 100644
--- a/pkg/front_end/lib/src/base/processed_options.dart
+++ b/pkg/front_end/lib/src/base/processed_options.dart
@@ -427,7 +427,7 @@
 
   /// Get an outline component that summarizes the SDK, if any.
   // TODO(sigmund): move, this doesn't feel like an "option".
-  Future<Component?> loadSdkSummary(CanonicalName nameRoot) async {
+  Future<Component?> loadSdkSummary(CanonicalName? nameRoot) async {
     if (_sdkSummaryComponent == null) {
       if (sdkSummary == null) return null;
       List<int>? bytes = await loadSdkSummaryBytes();
@@ -478,7 +478,7 @@
   }
 
   /// Helper to load a .dill file from [uri] using the existing [nameRoot].
-  Component loadComponent(List<int> bytes, CanonicalName nameRoot,
+  Component loadComponent(List<int> bytes, CanonicalName? nameRoot,
       {bool? alwaysCreateNewNamedNodes, Uri? fileUri}) {
     Component component =
         target.configureComponent(new Component(nameRoot: nameRoot));
diff --git a/pkg/front_end/lib/src/fasta/builder/builder.dart b/pkg/front_end/lib/src/fasta/builder/builder.dart
index 95953c7..a0539e8 100644
--- a/pkg/front_end/lib/src/fasta/builder/builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/builder.dart
@@ -200,7 +200,7 @@
 
   /// Resolve constructors (lookup names in scope) recorded in this builder and
   /// return the number of constructors resolved.
-  int resolveConstructors(covariant Builder parent);
+  int resolveConstructors(covariant Builder? parent);
 
   /// Return `true` if this builder is a duplicate of another with the same
   /// name. This is `false` for the builder first declared amongst duplicates.
diff --git a/pkg/front_end/lib/src/fasta/builder/builtin_type_declaration_builder.dart b/pkg/front_end/lib/src/fasta/builder/builtin_type_declaration_builder.dart
index 7f39862..e516b79 100644
--- a/pkg/front_end/lib/src/fasta/builder/builtin_type_declaration_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/builtin_type_declaration_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.builtin_type_builder;
 
 import 'package:kernel/ast.dart' show DartType, Nullability;
@@ -18,13 +16,17 @@
     extends TypeDeclarationBuilderImpl {
   final DartType type;
 
+  @override
+  final Uri fileUri;
+
   BuiltinTypeDeclarationBuilder(
       String name, this.type, LibraryBuilder compilationUnit, int charOffset)
-      : super(null, 0, name, compilationUnit, charOffset);
+      : fileUri = compilationUnit.fileUri,
+        super(null, 0, name, compilationUnit, charOffset);
 
   DartType buildType(LibraryBuilder library,
-      NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments,
-      [bool notInstanceContext]) {
+      NullabilityBuilder nullabilityBuilder, List<TypeBuilder>? arguments,
+      {bool? nonInstanceContext}) {
     return type.withDeclaredNullability(nullabilityBuilder.build(library));
   }
 
diff --git a/pkg/front_end/lib/src/fasta/builder/class_builder.dart b/pkg/front_end/lib/src/fasta/builder/class_builder.dart
index 5357d8b..0f577ff 100644
--- a/pkg/front_end/lib/src/fasta/builder/class_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/class_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.class_builder;
 
 import 'package:kernel/ast.dart'
@@ -21,6 +19,7 @@
         NullType,
         Nullability,
         Supertype,
+        TreeNode,
         TypeParameter,
         getAsTypeArguments;
 
@@ -84,29 +83,30 @@
 
 abstract class ClassBuilder implements DeclarationBuilder {
   /// The type variables declared on a class, extension or mixin declaration.
-  List<TypeVariableBuilder> typeVariables;
+  List<TypeVariableBuilder>? get typeVariables;
 
   /// The type in the `extends` clause of a class declaration.
   ///
   /// Currently this also holds the synthesized super class for a mixin
   /// declaration.
-  TypeBuilder supertypeBuilder;
+  abstract TypeBuilder? supertypeBuilder;
 
   /// The type in the `implements` clause of a class or mixin declaration.
-  List<TypeBuilder> interfaceBuilders;
+  abstract List<TypeBuilder>? interfaceBuilders;
 
   /// The types in the `on` clause of an extension or mixin declaration.
-  List<TypeBuilder> onTypes;
+  List<TypeBuilder>? get onTypes;
 
   ConstructorScope get constructors;
 
   ConstructorScopeBuilder get constructorScopeBuilder;
 
-  Map<String, ConstructorRedirection> redirectingConstructors;
+  abstract ClassBuilder? actualOrigin;
 
-  ClassBuilder actualOrigin;
+  @override
+  Uri get fileUri;
 
-  ClassBuilder get patchForTesting;
+  ClassBuilder? get patchForTesting;
 
   bool get isAbstract;
 
@@ -118,20 +118,18 @@
 
   bool get isAnonymousMixinApplication;
 
-  TypeBuilder get mixedInTypeBuilder;
+  abstract TypeBuilder? mixedInTypeBuilder;
 
-  void set mixedInTypeBuilder(TypeBuilder mixin);
-
-  List<ConstructorReferenceBuilder> get constructorReferences;
-
-  void buildOutlineExpressions(LibraryBuilder library, CoreTypes coreTypes,
+  void buildOutlineExpressions(
+      SourceLibraryBuilder library,
+      CoreTypes coreTypes,
       List<DelayedActionPerformer> delayedActionPerformers);
 
   /// Registers a constructor redirection for this class and returns true if
   /// this redirection gives rise to a cycle that has not been reported before.
   bool checkConstructorCyclic(String source, String target);
 
-  MemberBuilder findConstructorOrFactory(
+  MemberBuilder? findConstructorOrFactory(
       String name, int charOffset, Uri uri, LibraryBuilder accessingLibrary);
 
   void forEach(void f(String name, Builder builder));
@@ -143,16 +141,6 @@
       void Function(String name, ConstructorBuilder constructorBuilder)
           callback);
 
-  /// Find the first member of this class with [name]. This method isn't
-  /// suitable for scope lookups as it will throw an error if the name isn't
-  /// declared. The [scope] should be used for that. This method is used to
-  /// find a member that is known to exist and it will pick the first
-  /// declaration if the name is ambiguous.
-  ///
-  /// For example, this method is convenient for use when building synthetic
-  /// members, such as those of an enum.
-  MemberBuilder firstMemberNamed(String name);
-
   /// The [Class] built by this builder.
   ///
   /// For a patch class the origin class is returned.
@@ -163,7 +151,10 @@
 
   Class get actualCls;
 
-  bool isNullClass;
+  abstract bool isNullClass;
+
+  @override
+  InterfaceType get thisType;
 
   InterfaceType get legacyRawType;
 
@@ -174,13 +165,14 @@
   InterfaceType rawType(Nullability nullability);
 
   List<DartType> buildTypeArguments(
-      LibraryBuilder library, List<TypeBuilder> arguments,
-      [bool notInstanceContext]);
+      LibraryBuilder library, List<TypeBuilder>? arguments,
+      {bool? nonInstanceContext});
 
-  Supertype buildSupertype(LibraryBuilder library, List<TypeBuilder> arguments);
+  Supertype buildSupertype(
+      LibraryBuilder library, List<TypeBuilder>? arguments);
 
   Supertype buildMixedInType(
-      LibraryBuilder library, List<TypeBuilder> arguments);
+      LibraryBuilder library, List<TypeBuilder>? arguments);
 
   void checkSupertypes(CoreTypes coreTypes);
 
@@ -194,7 +186,7 @@
 
   // Computes the function type of a given redirection target. Returns [null] if
   // the type of the target could not be computed.
-  FunctionType computeRedirecteeType(
+  FunctionType? computeRedirecteeType(
       RedirectingFactoryBuilder factory, TypeEnvironment typeEnvironment);
 
   String computeRedirecteeName(ConstructorReferenceBuilder redirectionTarget);
@@ -236,14 +228,14 @@
   /// If this class builder is a patch, interface members declared in this
   /// patch are searched before searching the interface members in the origin
   /// class.
-  Member lookupInstanceMember(ClassHierarchy hierarchy, Name name,
+  Member? lookupInstanceMember(ClassHierarchy hierarchy, Name name,
       {bool isSetter: false, bool isSuper: false});
 
   /// Looks up the constructor by [name] on the the class built by this class
   /// builder.
   ///
   /// If [isSuper] is `true`, constructors in the superclass are searched.
-  Constructor lookupConstructor(Name name, {bool isSuper: false});
+  Constructor? lookupConstructor(Name name, {bool isSuper: false});
 
   /// Calls [f] for each constructor declared in this class.
   ///
@@ -256,16 +248,16 @@
 abstract class ClassBuilderImpl extends DeclarationBuilderImpl
     implements ClassBuilder {
   @override
-  List<TypeVariableBuilder> typeVariables;
+  List<TypeVariableBuilder>? typeVariables;
 
   @override
-  TypeBuilder supertypeBuilder;
+  TypeBuilder? supertypeBuilder;
 
   @override
-  List<TypeBuilder> interfaceBuilders;
+  List<TypeBuilder>? interfaceBuilders;
 
   @override
-  List<TypeBuilder> onTypes;
+  List<TypeBuilder>? onTypes;
 
   @override
   final ConstructorScope constructors;
@@ -273,26 +265,25 @@
   @override
   final ConstructorScopeBuilder constructorScopeBuilder;
 
-  @override
-  Map<String, ConstructorRedirection> redirectingConstructors;
+  Map<String, ConstructorRedirection>? _redirectingConstructors;
 
   @override
-  ClassBuilder actualOrigin;
+  ClassBuilder? actualOrigin;
 
   @override
-  ClassBuilder get patchForTesting => _patchBuilder;
+  ClassBuilder? get patchForTesting => _patchBuilder;
 
   @override
   bool isNullClass = false;
 
-  InterfaceType _legacyRawType;
-  InterfaceType _nullableRawType;
-  InterfaceType _nonNullableRawType;
-  InterfaceType _thisType;
-  ClassBuilder _patchBuilder;
+  InterfaceType? _legacyRawType;
+  InterfaceType? _nullableRawType;
+  InterfaceType? _nonNullableRawType;
+  InterfaceType? _thisType;
+  ClassBuilder? _patchBuilder;
 
   ClassBuilderImpl(
-      List<MetadataBuilder> metadata,
+      List<MetadataBuilder>? metadata,
       int modifiers,
       String name,
       this.typeVariables,
@@ -330,18 +321,15 @@
   bool get declaresConstConstructor =>
       (modifiers & declaresConstConstructorMask) != 0;
 
-  @override
-  List<ConstructorReferenceBuilder> get constructorReferences => null;
-
   void forEachConstructor(void Function(String, MemberBuilder) f,
       {bool includeInjectedConstructors: false}) {
     if (isPatch) {
-      actualOrigin.forEachConstructor(f,
+      actualOrigin!.forEachConstructor(f,
           includeInjectedConstructors: includeInjectedConstructors);
     } else {
       constructors.forEach(f);
-      if (includeInjectedConstructors && _patchBuilder != null) {
-        _patchBuilder.constructors
+      if (includeInjectedConstructors) {
+        _patchBuilder?.constructors
             .forEach((String name, MemberBuilder builder) {
           if (!builder.isPatch) {
             f(name, builder);
@@ -352,10 +340,12 @@
   }
 
   @override
-  void buildOutlineExpressions(LibraryBuilder library, CoreTypes coreTypes,
+  void buildOutlineExpressions(
+      SourceLibraryBuilder library,
+      CoreTypes coreTypes,
       List<DelayedActionPerformer> delayedActionPerformers) {
     void build(String ignore, Builder declaration) {
-      MemberBuilder member = declaration;
+      MemberBuilder member = declaration as MemberBuilder;
       member.buildOutlineExpressions(
           library, coreTypes, delayedActionPerformers);
     }
@@ -363,8 +353,8 @@
     MetadataBuilder.buildAnnotations(
         isPatch ? origin.cls : cls, metadata, library, this, null, fileUri);
     if (typeVariables != null) {
-      for (int i = 0; i < typeVariables.length; i++) {
-        typeVariables[i].buildOutlineExpressions(
+      for (int i = 0; i < typeVariables!.length; i++) {
+        typeVariables![i].buildOutlineExpressions(
             library, this, null, coreTypes, delayedActionPerformers);
       }
     }
@@ -376,22 +366,22 @@
   /// Registers a constructor redirection for this class and returns true if
   /// this redirection gives rise to a cycle that has not been reported before.
   bool checkConstructorCyclic(String source, String target) {
-    ConstructorRedirection redirect = new ConstructorRedirection(target);
-    redirectingConstructors ??= <String, ConstructorRedirection>{};
-    redirectingConstructors[source] = redirect;
+    ConstructorRedirection? redirect = new ConstructorRedirection(target);
+    _redirectingConstructors ??= <String, ConstructorRedirection>{};
+    _redirectingConstructors![source] = redirect;
     while (redirect != null) {
       if (redirect.cycleReported) return false;
       if (redirect.target == source) {
         redirect.cycleReported = true;
         return true;
       }
-      redirect = redirectingConstructors[redirect.target];
+      redirect = _redirectingConstructors![redirect.target];
     }
     return false;
   }
 
   @override
-  Builder findStaticBuilder(
+  Builder? findStaticBuilder(
       String name, int charOffset, Uri fileUri, LibraryBuilder accessingLibrary,
       {bool isSetter: false}) {
     if (accessingLibrary.nameOriginBuilder.origin !=
@@ -399,7 +389,7 @@
         name.startsWith("_")) {
       return null;
     }
-    Builder declaration = isSetter
+    Builder? declaration = isSetter
         ? scope.lookupSetter(name, charOffset, fileUri, isInstanceScope: false)
         : scope.lookup(name, charOffset, fileUri, isInstanceScope: false);
     if (declaration == null && isPatch) {
@@ -411,14 +401,14 @@
   }
 
   @override
-  MemberBuilder findConstructorOrFactory(
+  MemberBuilder? findConstructorOrFactory(
       String name, int charOffset, Uri uri, LibraryBuilder accessingLibrary) {
     if (accessingLibrary.nameOriginBuilder.origin !=
             library.nameOriginBuilder.origin &&
         name.startsWith("_")) {
       return null;
     }
-    MemberBuilder declaration = constructors.lookup(name, charOffset, uri);
+    MemberBuilder? declaration = constructors.lookup(name, charOffset, uri);
     if (declaration == null && isPatch) {
       return origin.findConstructorOrFactory(
           name, charOffset, uri, accessingLibrary);
@@ -447,7 +437,7 @@
     // and from the patch don't intersect.
     assert(
         _patchBuilder == null ||
-            _patchBuilder.scope.localMembers
+            _patchBuilder!.scope.localMembers
                 .where((b) => b is FieldBuilder)
                 .map((b) => (b as FieldBuilder).name)
                 .toSet()
@@ -457,7 +447,7 @@
                     .toSet())
                 .isEmpty,
         "Detected an attempt to patch a field.");
-    _patchBuilder?.scope?.forEach(callbackFilteringFieldBuilders);
+    _patchBuilder?.scope.forEach(callbackFilteringFieldBuilders);
     scope.forEach(callbackFilteringFieldBuilders);
   }
 
@@ -476,14 +466,14 @@
     // Constructors can be patched, so iterate first over constructors in the
     // patch, and then over constructors in the original declaration skipping
     // those with the names that are in the patch.
-    _patchBuilder?.constructors?.forEach(callbackFilteringFieldBuilders);
+    _patchBuilder?.constructors.forEach(callbackFilteringFieldBuilders);
     constructors.forEach(callbackFilteringFieldBuilders);
   }
 
   @override
-  Builder lookupLocalMember(String name,
+  Builder? lookupLocalMember(String name,
       {bool setter: false, bool required: false}) {
-    Builder builder = scope.lookupLocalMember(name, setter: setter);
+    Builder? builder = scope.lookupLocalMember(name, setter: setter);
     if (builder == null && isPatch) {
       builder = origin.scope.lookupLocalMember(name, setter: setter);
     }
@@ -497,11 +487,19 @@
     return builder;
   }
 
-  @override
-  MemberBuilder firstMemberNamed(String name) {
-    Builder declaration = lookupLocalMember(name, required: true);
+  /// Find the first member of this class with [name]. This method isn't
+  /// suitable for scope lookups as it will throw an error if the name isn't
+  /// declared. The [scope] should be used for that. This method is used to
+  /// find a member that is known to exist and it will pick the first
+  /// declaration if the name is ambiguous.
+  ///
+  /// For example, this method is convenient for use when building synthetic
+  /// members, such as those of an enum.
+  MemberBuilder? firstMemberNamed(String name) {
+    MemberBuilder declaration =
+        lookupLocalMember(name, required: true) as MemberBuilder;
     while (declaration.next != null) {
-      declaration = declaration.next;
+      declaration = declaration.next as MemberBuilder;
     }
     return declaration;
   }
@@ -552,17 +550,17 @@
 
   @override
   DartType buildTypesWithBuiltArguments(LibraryBuilder library,
-      Nullability nullability, List<DartType> arguments) {
+      Nullability nullability, List<DartType>? arguments) {
     assert(arguments == null || cls.typeParameters.length == arguments.length);
     if (isNullClass) {
       return const NullType();
     }
     if (name == "FutureOr") {
-      LibraryBuilder parentLibrary = parent;
+      LibraryBuilder parentLibrary = parent as LibraryBuilder;
       if (parentLibrary.importUri.scheme == "dart" &&
           parentLibrary.importUri.path == "async") {
         assert(arguments != null && arguments.length == 1);
-        return new FutureOrType(arguments.single, nullability);
+        return new FutureOrType(arguments!.single, nullability);
       }
     }
     return arguments == null
@@ -575,18 +573,16 @@
 
   @override
   List<DartType> buildTypeArguments(
-      LibraryBuilder library, List<TypeBuilder> arguments,
-      [bool notInstanceContext]) {
+      LibraryBuilder library, List<TypeBuilder>? arguments,
+      {bool? nonInstanceContext}) {
     if (arguments == null && typeVariables == null) {
       return <DartType>[];
     }
 
     if (arguments == null && typeVariables != null) {
-      List<DartType> result =
-          new List<DartType>.filled(typeVariables.length, null, growable: true);
-      for (int i = 0; i < result.length; ++i) {
-        result[i] = typeVariables[i].defaultType.build(library);
-      }
+      List<DartType> result = new List<DartType>.generate(typeVariables!.length,
+          (int i) => typeVariables![i].defaultType!.build(library),
+          growable: true);
       if (library is SourceLibraryBuilder) {
         library.inferredTypes.addAll(result);
       }
@@ -604,28 +600,27 @@
           null);
     }
 
-    assert(arguments.length == typeVariablesCount);
-    List<DartType> result =
-        new List<DartType>.filled(arguments.length, null, growable: true);
-    for (int i = 0; i < result.length; ++i) {
-      result[i] = arguments[i].build(library);
-    }
+    assert(arguments!.length == typeVariablesCount);
+    List<DartType> result = new List<DartType>.generate(
+        arguments!.length, (int i) => arguments[i].build(library),
+        growable: true);
     return result;
   }
 
   @override
   DartType buildType(LibraryBuilder library,
-      NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments,
-      [bool notInstanceContext]) {
+      NullabilityBuilder nullabilityBuilder, List<TypeBuilder>? arguments,
+      {bool? nonInstanceContext}) {
     return buildTypesWithBuiltArguments(
         library,
         nullabilityBuilder.build(library),
-        buildTypeArguments(library, arguments, notInstanceContext));
+        buildTypeArguments(library, arguments,
+            nonInstanceContext: nonInstanceContext));
   }
 
   @override
   Supertype buildSupertype(
-      LibraryBuilder library, List<TypeBuilder> arguments) {
+      LibraryBuilder library, List<TypeBuilder>? arguments) {
     Class cls = isPatch ? origin.cls : this.cls;
     List<DartType> typeArguments = buildTypeArguments(library, arguments);
     if (!library.isNonNullableByDefault) {
@@ -638,7 +633,7 @@
 
   @override
   Supertype buildMixedInType(
-      LibraryBuilder library, List<TypeBuilder> arguments) {
+      LibraryBuilder library, List<TypeBuilder>? arguments) {
     Class cls = isPatch ? origin.cls : this.cls;
     if (arguments != null) {
       return new Supertype(cls, buildTypeArguments(library, arguments));
@@ -660,7 +655,7 @@
     // supertypes.
 
     void fail(NamedTypeBuilder target, Message message,
-        TypeAliasBuilder aliasBuilder) {
+        TypeAliasBuilder? aliasBuilder) {
       int nameOffset = target.nameOffset;
       int nameLength = target.nameLength;
       // TODO(eernst): nameOffset not fully implemented; use backup.
@@ -679,16 +674,16 @@
     }
 
     // Extract and check superclass (if it exists).
-    ClassBuilder superClass;
-    TypeBuilder superClassType = supertypeBuilder;
+    ClassBuilder? superClass;
+    TypeBuilder? superClassType = supertypeBuilder;
     if (superClassType is NamedTypeBuilder) {
-      TypeDeclarationBuilder decl = superClassType.declaration;
-      TypeAliasBuilder aliasBuilder; // Non-null if a type alias is use.
+      TypeDeclarationBuilder? decl = superClassType.declaration;
+      TypeAliasBuilder? aliasBuilder; // Non-null if a type alias is use.
       if (decl is TypeAliasBuilder) {
         aliasBuilder = decl;
         decl = aliasBuilder.unaliasDeclaration(superClassType.arguments,
             isUsedAsClass: true,
-            usedAsClassCharOffset: supertypeBuilder.charOffset,
+            usedAsClassCharOffset: superClassType.charOffset,
             usedAsClassFileUri: superClassType.fileUri);
       }
       // TODO(eernst): Should gather 'restricted supertype' checks in one place,
@@ -704,15 +699,15 @@
     if (interfaceBuilders == null) return;
 
     // Validate interfaces.
-    Map<ClassBuilder, int> problems;
-    Map<ClassBuilder, int> problemsOffsets;
+    Map<ClassBuilder, int>? problems;
+    Map<ClassBuilder, int>? problemsOffsets;
     Set<ClassBuilder> implemented = new Set<ClassBuilder>();
-    for (TypeBuilder type in interfaceBuilders) {
+    for (TypeBuilder type in interfaceBuilders!) {
       if (type is NamedTypeBuilder) {
-        int charOffset = type.charOffset;
-        TypeDeclarationBuilder typeDeclaration = type.declaration;
-        TypeDeclarationBuilder decl;
-        TypeAliasBuilder aliasBuilder; // Non-null if a type alias is used.
+        int? charOffset = type.charOffset;
+        TypeDeclarationBuilder? typeDeclaration = type.declaration;
+        TypeDeclarationBuilder? decl;
+        TypeAliasBuilder? aliasBuilder; // Non-null if a type alias is used.
         if (typeDeclaration is TypeAliasBuilder) {
           aliasBuilder = typeDeclaration;
           decl = aliasBuilder.unaliasDeclaration(type.arguments,
@@ -735,11 +730,11 @@
             addProblem(messageImplementsFutureOr, this.charOffset, noLength);
           } else if (implemented.contains(interface)) {
             // Aggregate repetitions.
-            problems ??= new Map<ClassBuilder, int>();
+            problems ??= <ClassBuilder, int>{};
             problems[interface] ??= 0;
-            problems[interface] += 1;
-            problemsOffsets ??= new Map<ClassBuilder, int>();
-            problemsOffsets[interface] ??= charOffset;
+            problems[interface] = problems[interface]! + 1;
+            problemsOffsets ??= <ClassBuilder, int>{};
+            problemsOffsets[interface] ??= charOffset ?? TreeNode.noOffset;
           } else {
             implemented.add(interface);
           }
@@ -759,7 +754,7 @@
         addProblem(
             templateImplementsRepeated.withArguments(
                 interface.name, repetitions),
-            problemsOffsets[interface],
+            problemsOffsets![interface]!,
             noLength);
       });
     }
@@ -770,12 +765,12 @@
       callback(Member interfaceMember, bool isSetter)) {
     // When a parameter is covariant we have to check that we also
     // override the same member in all parents.
-    for (Supertype supertype in interfaceMember.enclosingClass.supers) {
-      Member m = types.hierarchy.getInterfaceMember(
+    for (Supertype supertype in interfaceMember.enclosingClass!.supers) {
+      Member? member = types.hierarchy.getInterfaceMember(
           supertype.classNode, interfaceMember.name,
           setter: isSetter);
-      if (m != null) {
-        callback(m, isSetter);
+      if (member != null) {
+        callback(member, isSetter);
       }
     }
   }
@@ -783,15 +778,15 @@
   @override
   bool hasUserDefinedNoSuchMethod(
       Class klass, ClassHierarchy hierarchy, Class objectClass) {
-    Member noSuchMethod = hierarchy.getDispatchTarget(klass, noSuchMethodName);
+    Member? noSuchMethod = hierarchy.getDispatchTarget(klass, noSuchMethodName);
     return noSuchMethod != null && noSuchMethod.enclosingClass != objectClass;
   }
 
   @override
   String get fullNameForErrors {
     return isMixinApplication && !isNamedMixinApplication
-        ? "${supertypeBuilder.fullNameForErrors} with "
-            "${mixedInTypeBuilder.fullNameForErrors}"
+        ? "${supertypeBuilder!.fullNameForErrors} with "
+            "${mixedInTypeBuilder!.fullNameForErrors}"
         : name;
   }
 
@@ -800,12 +795,12 @@
     TypeEnvironment typeEnvironment = new TypeEnvironment(coreTypes, hierarchy);
     // A mixin declaration can only be applied to a class that implements all
     // the declaration's superclass constraints.
-    InterfaceType supertype = cls.supertype.asInterfaceType;
-    Substitution substitution = Substitution.fromSupertype(cls.mixedInType);
-    for (Supertype constraint in cls.mixedInClass.superclassConstraints()) {
+    InterfaceType supertype = cls.supertype!.asInterfaceType;
+    Substitution substitution = Substitution.fromSupertype(cls.mixedInType!);
+    for (Supertype constraint in cls.mixedInClass!.superclassConstraints()) {
       InterfaceType requiredInterface =
           substitution.substituteSupertype(constraint).asInterfaceType;
-      InterfaceType implementedInterface = hierarchy.getTypeAsInstanceOf(
+      InterfaceType? implementedInterface = hierarchy.getTypeAsInstanceOf(
           supertype, requiredInterface.classNode, library.library);
       if (implementedInterface == null ||
           !typeEnvironment.areMutualSubtypes(
@@ -818,7 +813,7 @@
             templateMixinApplicationIncompatibleSupertype.withArguments(
                 supertype,
                 requiredInterface,
-                cls.mixedInType.asInterfaceType,
+                cls.mixedInType!.asInterfaceType,
                 library.isNonNullableByDefault),
             cls.fileOffset,
             noLength,
@@ -834,20 +829,21 @@
       _patchBuilder = patch;
       // TODO(ahe): Complain if `patch.supertype` isn't null.
       scope.forEachLocalMember((String name, Builder member) {
-        Builder memberPatch =
+        Builder? memberPatch =
             patch.scope.lookupLocalMember(name, setter: false);
         if (memberPatch != null) {
           member.applyPatch(memberPatch);
         }
       });
       scope.forEachLocalSetter((String name, Builder member) {
-        Builder memberPatch = patch.scope.lookupLocalMember(name, setter: true);
+        Builder? memberPatch =
+            patch.scope.lookupLocalMember(name, setter: true);
         if (memberPatch != null) {
           member.applyPatch(memberPatch);
         }
       });
       constructors.local.forEach((String name, Builder member) {
-        Builder memberPatch = patch.constructors.local[name];
+        Builder? memberPatch = patch.constructors.local[name];
         if (memberPatch != null) {
           member.applyPatch(memberPatch);
         }
@@ -862,8 +858,8 @@
         ]);
       } else if (typeVariables != null) {
         int count = 0;
-        for (TypeVariableBuilder t in patch.typeVariables) {
-          typeVariables[count++].applyPatch(t);
+        for (TypeVariableBuilder t in patch.typeVariables!) {
+          typeVariables![count++].applyPatch(t);
         }
       }
     } else {
@@ -876,16 +872,15 @@
   }
 
   @override
-  FunctionType computeRedirecteeType(
+  FunctionType? computeRedirecteeType(
       RedirectingFactoryBuilder factory, TypeEnvironment typeEnvironment) {
     ConstructorReferenceBuilder redirectionTarget = factory.redirectionTarget;
-    FunctionNode target;
-    if (redirectionTarget.target == null) return null;
-    if (redirectionTarget.target is FunctionBuilder) {
-      FunctionBuilder targetBuilder = redirectionTarget.target;
-      target = targetBuilder.function;
-    } else if (redirectionTarget.target is DillConstructorBuilder) {
-      DillConstructorBuilder targetBuilder = redirectionTarget.target;
+    Builder? targetBuilder = redirectionTarget.target;
+    FunctionNode targetNode;
+    if (targetBuilder == null) return null;
+    if (targetBuilder is FunctionBuilder) {
+      targetNode = targetBuilder.function;
+    } else if (targetBuilder is DillConstructorBuilder) {
       // It seems that the [redirectionTarget.target] is an instance of
       // [DillMemberBuilder] whenever the redirectee is an implicit constructor,
       // e.g.
@@ -895,9 +890,8 @@
       //   }
       //   class B implements A {}
       //
-      target = targetBuilder.constructor.function;
-    } else if (redirectionTarget.target is DillFactoryBuilder) {
-      DillFactoryBuilder targetBuilder = redirectionTarget.target;
+      targetNode = targetBuilder.constructor.function;
+    } else if (targetBuilder is DillFactoryBuilder) {
       // It seems that the [redirectionTarget.target] is an instance of
       // [DillMemberBuilder] whenever the redirectee is an implicit constructor,
       // e.g.
@@ -907,8 +901,8 @@
       //   }
       //   class B implements A {}
       //
-      target = targetBuilder.procedure.function;
-    } else if (redirectionTarget.target is AmbiguousBuilder) {
+      targetNode = targetBuilder.procedure.function;
+    } else if (targetBuilder is AmbiguousBuilder) {
       // Multiple definitions with the same name: An error has already been
       // issued.
       // TODO(http://dartbug.com/35294): Unfortunate error; see also
@@ -919,10 +913,10 @@
           charOffset, fileUri);
     }
 
-    List<DartType> typeArguments =
-        getRedirectingFactoryBody(factory.procedure).typeArguments;
+    List<DartType>? typeArguments =
+        getRedirectingFactoryBody(factory.procedure)!.typeArguments;
     FunctionType targetFunctionType =
-        target.computeFunctionType(library.nonNullable);
+        targetNode.computeFunctionType(library.nonNullable);
     if (typeArguments != null &&
         targetFunctionType.typeParameters.length != typeArguments.length) {
       addProblem(
@@ -935,7 +929,7 @@
 
     // Compute the substitution of the target class type parameters if
     // [redirectionTarget] has any type arguments.
-    Substitution substitution;
+    Substitution? substitution;
     bool hasProblem = false;
     if (typeArguments != null && typeArguments.length > 0) {
       substitution = Substitution.fromPairs(
@@ -1000,7 +994,7 @@
   String computeRedirecteeName(ConstructorReferenceBuilder redirectionTarget) {
     String targetName = redirectionTarget.fullNameForErrors;
     if (targetName == "") {
-      return redirectionTarget.target.parent.fullNameForErrors;
+      return redirectionTarget.target!.parent!.fullNameForErrors;
     } else {
       return targetName;
     }
@@ -1015,7 +1009,7 @@
     FunctionType factoryType = factory.procedure.function
         .computeThisFunctionType(library.nonNullable)
         .withoutTypeParameters;
-    FunctionType redirecteeType =
+    FunctionType? redirecteeType =
         computeRedirecteeType(factory, typeEnvironment);
 
     // TODO(hillerstrom): It would be preferable to know whether a failure
@@ -1046,28 +1040,26 @@
   @override
   void checkRedirectingFactories(TypeEnvironment typeEnvironment) {
     Map<String, MemberBuilder> constructors = this.constructors.local;
-    Iterable<String> names = constructors.keys;
-    for (String name in names) {
-      Builder constructor = constructors[name];
+    for (Builder? constructor in constructors.values) {
       do {
         if (constructor is RedirectingFactoryBuilder) {
           checkRedirectingFactory(constructor, typeEnvironment);
         }
-        constructor = constructor.next;
+        constructor = constructor!.next;
       } while (constructor != null);
     }
   }
 
   @override
   Map<TypeParameter, DartType> getSubstitutionMap(Class superclass) {
-    Supertype supertype = cls.supertype;
+    Supertype? supertype = cls.supertype;
     Map<TypeParameter, DartType> substitutionMap = <TypeParameter, DartType>{};
     List<DartType> arguments;
     List<TypeParameter> variables;
-    Class classNode;
+    Class? classNode;
 
     while (classNode != superclass) {
-      classNode = supertype.classNode;
+      classNode = supertype!.classNode;
       arguments = supertype.typeArguments;
       variables = classNode.typeParameters;
       supertype = classNode.supertype;
@@ -1077,6 +1069,7 @@
         for (int i = 0; i < variables.length; i++) {
           DartType argument =
               i < arguments.length ? arguments[i] : const DynamicType();
+          // ignore: unnecessary_null_comparison
           if (substitutionMap != null) {
             // TODO(ahe): Investigate if requiring the caller to use
             // `substituteDeep` from `package:kernel/type_algebra.dart` instead
@@ -1093,9 +1086,9 @@
   }
 
   @override
-  Member lookupInstanceMember(ClassHierarchy hierarchy, Name name,
+  Member? lookupInstanceMember(ClassHierarchy hierarchy, Name name,
       {bool isSetter: false, bool isSuper: false}) {
-    Class instanceClass = cls;
+    Class? instanceClass = cls;
     if (isPatch) {
       assert(identical(instanceClass, origin.cls),
           "Found ${origin.cls} expected $instanceClass");
@@ -1103,7 +1096,7 @@
         // The super class is only correctly found through the origin class.
         instanceClass = origin.cls;
       } else {
-        Member member =
+        Member? member =
             hierarchy.getInterfaceMember(instanceClass, name, setter: isSetter);
         if (member?.parent == instanceClass) {
           // Only if the member is found in the patch can we use it.
@@ -1119,7 +1112,7 @@
       instanceClass = instanceClass.superclass;
       if (instanceClass == null) return null;
     }
-    Member target = isSuper
+    Member? target = isSuper
         ? hierarchy.getDispatchTarget(instanceClass, name, setter: isSetter)
         : hierarchy.getInterfaceMember(instanceClass, name, setter: isSetter);
     if (isSuper && target == null) {
@@ -1134,8 +1127,8 @@
   }
 
   @override
-  Constructor lookupConstructor(Name name, {bool isSuper: false}) {
-    Class instanceClass = cls;
+  Constructor? lookupConstructor(Name name, {bool isSuper: false}) {
+    Class? instanceClass = cls;
     if (isSuper) {
       instanceClass = instanceClass.superclass;
     }
@@ -1147,18 +1140,18 @@
 
     /// Performs a similar lookup to [lookupConstructor], but using a slower
     /// implementation.
-    Constructor lookupConstructorWithPatches(Name name, bool isSuper) {
-      ClassBuilder builder = this.origin;
+    Constructor? lookupConstructorWithPatches(Name name, bool isSuper) {
+      ClassBuilder? builder = this.origin;
 
-      ClassBuilder getSuperclass(ClassBuilder builder) {
+      ClassBuilder? getSuperclass(ClassBuilder builder) {
         // This way of computing the superclass is slower than using the kernel
         // objects directly.
-        Object supertype = builder.supertypeBuilder;
+        TypeBuilder? supertype = builder.supertypeBuilder;
         if (supertype is NamedTypeBuilder) {
-          Object builder = supertype.declaration;
+          TypeDeclarationBuilder? builder = supertype.declaration;
           if (builder is ClassBuilder) return builder;
           if (builder is TypeAliasBuilder) {
-            TypeDeclarationBuilder declarationBuilder =
+            TypeDeclarationBuilder? declarationBuilder =
                 builder.unaliasDeclaration(supertype.arguments,
                     isUsedAsClass: true,
                     usedAsClassCharOffset: supertype.charOffset,
diff --git a/pkg/front_end/lib/src/fasta/builder/constructor_builder.dart b/pkg/front_end/lib/src/fasta/builder/constructor_builder.dart
index d478a69..86e0021 100644
--- a/pkg/front_end/lib/src/fasta/builder/constructor_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/constructor_builder.dart
@@ -2,8 +2,6 @@
 // for 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 'package:_fe_analyzer_shared/src/scanner/token.dart' show Token;
 
 import 'package:kernel/ast.dart';
@@ -36,34 +34,25 @@
 
 import '../source/source_class_builder.dart';
 import '../source/source_library_builder.dart' show SourceLibraryBuilder;
+import '../type_inference/type_schema.dart';
 import '../util/helpers.dart' show DelayedActionPerformer;
 
 import 'builder.dart';
-import 'class_builder.dart';
 import 'field_builder.dart';
 import 'formal_parameter_builder.dart';
 import 'function_builder.dart';
-import 'library_builder.dart';
 import 'member_builder.dart';
 import 'metadata_builder.dart';
 import 'type_builder.dart';
 import 'type_variable_builder.dart';
 
 abstract class ConstructorBuilder implements FunctionBuilder {
-  int get charOpenParenOffset;
-
-  bool hasMovedSuperInitializer;
-
-  SuperInitializer superInitializer;
-
-  RedirectingInitializer redirectingInitializer;
-
-  Token beginInitializers;
+  abstract Token? beginInitializers;
 
   @override
-  ConstructorBuilder get actualOrigin;
+  ConstructorBuilder? get actualOrigin;
 
-  ConstructorBuilder get patchForTesting;
+  ConstructorBuilder? get patchForTesting;
 
   Constructor get actualConstructor;
 
@@ -97,50 +86,46 @@
   /// Returns the set of fields previously registered via
   /// [registerInitializedField] and passes on the ownership of the collection
   /// to the caller.
-  Set<FieldBuilder> takeInitializedFields();
+  Set<FieldBuilder>? takeInitializedFields();
 }
 
 class ConstructorBuilderImpl extends FunctionBuilderImpl
     implements ConstructorBuilder {
   final Constructor _constructor;
 
-  Set<FieldBuilder> _initializedFields;
+  Set<FieldBuilder>? _initializedFields;
 
-  @override
   final int charOpenParenOffset;
 
-  @override
   bool hasMovedSuperInitializer = false;
 
-  @override
-  SuperInitializer superInitializer;
+  SuperInitializer? superInitializer;
+
+  RedirectingInitializer? redirectingInitializer;
 
   @override
-  RedirectingInitializer redirectingInitializer;
+  Token? beginInitializers;
 
   @override
-  Token beginInitializers;
-
-  @override
-  ConstructorBuilder actualOrigin;
+  ConstructorBuilder? actualOrigin;
 
   @override
   Constructor get actualConstructor => _constructor;
 
   ConstructorBuilderImpl(
-      List<MetadataBuilder> metadata,
+      List<MetadataBuilder>? metadata,
       int modifiers,
-      TypeBuilder returnType,
+      TypeBuilder? returnType,
       String name,
-      List<TypeVariableBuilder> typeVariables,
-      List<FormalParameterBuilder> formals,
+      List<TypeVariableBuilder>? typeVariables,
+      List<FormalParameterBuilder>? formals,
       SourceLibraryBuilder compilationUnit,
       int startCharOffset,
       int charOffset,
       this.charOpenParenOffset,
       int charEndOffset,
-      Member referenceFrom,
-      [String nativeMethodName])
+      Member? referenceFrom,
+      [String? nativeMethodName])
       : _constructor = new Constructor(new FunctionNode(null),
             name: new Name(name, compilationUnit.library),
             fileUri: compilationUnit.fileUri,
@@ -153,10 +138,10 @@
             compilationUnit, charOffset, nativeMethodName);
 
   @override
-  Member get readTarget => null;
+  Member? get readTarget => null;
 
   @override
-  Member get writeTarget => null;
+  Member? get writeTarget => null;
 
   @override
   Member get invokeTarget => constructor;
@@ -170,7 +155,8 @@
   ConstructorBuilder get origin => actualOrigin ?? this;
 
   @override
-  ConstructorBuilder get patchForTesting => dataForTesting?.patchForTesting;
+  ConstructorBuilder? get patchForTesting =>
+      dataForTesting?.patchForTesting as ConstructorBuilder?;
 
   @override
   bool get isDeclarationInstanceMember => false;
@@ -185,7 +171,7 @@
   AsyncMarker get asyncModifier => AsyncMarker.Sync;
 
   @override
-  ProcedureKind get kind => null;
+  ProcedureKind? get kind => null;
 
   @override
   bool get isRedirectingGenerativeConstructor {
@@ -194,7 +180,7 @@
 
   @override
   void buildMembers(
-      LibraryBuilder library, void Function(Member, BuiltMemberKind) f) {
+      SourceLibraryBuilder library, void Function(Member, BuiltMemberKind) f) {
     Member member = build(library);
     f(member, BuiltMemberKind.Constructor);
   }
@@ -215,9 +201,9 @@
     }
     if (formals != null) {
       bool needsInference = false;
-      for (FormalParameterBuilder formal in formals) {
+      for (FormalParameterBuilder formal in formals!) {
         if (formal.type == null && formal.isInitializingFormal) {
-          formal.variable.type = null;
+          formal.variable!.type = const UnknownType();
           needsInference = true;
         }
       }
@@ -236,28 +222,29 @@
   @override
   void inferFormalTypes() {
     if (formals != null) {
-      for (FormalParameterBuilder formal in formals) {
+      for (FormalParameterBuilder formal in formals!) {
         if (formal.type == null && formal.isInitializingFormal) {
-          formal.finalizeInitializingFormal(classBuilder);
+          formal.finalizeInitializingFormal(classBuilder!);
         }
       }
     }
   }
 
   @override
-  void buildOutlineExpressions(LibraryBuilder library, CoreTypes coreTypes,
+  void buildOutlineExpressions(
+      SourceLibraryBuilder library,
+      CoreTypes coreTypes,
       List<DelayedActionPerformer> delayedActionPerformers) {
     super.buildOutlineExpressions(library, coreTypes, delayedActionPerformers);
 
     // For modular compilation purposes we need to include initializers
     // for const constructors into the outline.
     if (isConst && beginInitializers != null) {
-      ClassBuilder classBuilder = parent;
       BodyBuilder bodyBuilder = library.loader
           .createBodyBuilderForOutlineExpression(
-              library, classBuilder, this, classBuilder.scope, fileUri);
+              library, classBuilder!, this, classBuilder!.scope, fileUri);
       bodyBuilder.constantContext = ConstantContext.required;
-      bodyBuilder.parseInitializers(beginInitializers);
+      bodyBuilder.parseInitializers(beginInitializers!);
       bodyBuilder.resolveRedirectingFactoryTargets();
     }
     beginInitializers = null;
@@ -268,8 +255,7 @@
     // According to the specification §9.3 the return type of a constructor
     // function is its enclosing class.
     super.buildFunction(library);
-    ClassBuilder enclosingClassBuilder = parent;
-    Class enclosingClass = enclosingClassBuilder.cls;
+    Class enclosingClass = classBuilder!.cls;
     List<DartType> typeParameterTypes = <DartType>[];
     for (int i = 0; i < enclosingClass.typeParameters.length; i++) {
       TypeParameter typeParameter = enclosingClass.typeParameters[i];
@@ -323,7 +309,7 @@
         // Point to the existing super initializer.
         injectInvalidInitializer(
             messageRedirectingConstructorWithSuperInitializer,
-            superInitializer.fileOffset,
+            superInitializer!.fileOffset,
             "super".length,
             helper);
       } else if (redirectingInitializer != null) {
@@ -438,33 +424,33 @@
   }
 
   @override
-  Set<FieldBuilder> takeInitializedFields() {
-    Set<FieldBuilder> result = _initializedFields;
+  Set<FieldBuilder>? takeInitializedFields() {
+    Set<FieldBuilder>? result = _initializedFields;
     _initializedFields = null;
     return result;
   }
 }
 
 class SyntheticConstructorBuilder extends DillConstructorBuilder {
-  MemberBuilderImpl _origin;
-  ClonedFunctionNode _clonedFunctionNode;
+  MemberBuilderImpl? _origin;
+  ClonedFunctionNode? _clonedFunctionNode;
 
   SyntheticConstructorBuilder(
       SourceClassBuilder parent, Constructor constructor,
-      {MemberBuilder origin, ClonedFunctionNode clonedFunctionNode})
+      {MemberBuilderImpl? origin, ClonedFunctionNode? clonedFunctionNode})
       : _origin = origin,
         _clonedFunctionNode = clonedFunctionNode,
         super(constructor, parent);
 
   void buildOutlineExpressions(
-      LibraryBuilder libraryBuilder,
+      SourceLibraryBuilder libraryBuilder,
       CoreTypes coreTypes,
       List<DelayedActionPerformer> delayedActionPerformers) {
     if (_origin != null) {
       // Ensure that default value expressions have been created for [_origin].
-      _origin.buildOutlineExpressions(
+      _origin!.buildOutlineExpressions(
           libraryBuilder, coreTypes, delayedActionPerformers);
-      _clonedFunctionNode.cloneDefaultValues();
+      _clonedFunctionNode!.cloneDefaultValues();
       _clonedFunctionNode = null;
       _origin = null;
     }
diff --git a/pkg/front_end/lib/src/fasta/builder/constructor_reference_builder.dart b/pkg/front_end/lib/src/fasta/builder/constructor_reference_builder.dart
index 79ece35..c5f6728 100644
--- a/pkg/front_end/lib/src/fasta/builder/constructor_reference_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/constructor_reference_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.constructor_reference_builder;
 
 import '../messages.dart' show noLength, templateConstructorNotFound;
@@ -26,16 +24,16 @@
 
   final Object name;
 
-  final List<TypeBuilder> typeArguments;
+  final List<TypeBuilder>? typeArguments;
 
   /// This is the name of a named constructor. As `bar` in `new Foo<T>.bar()`.
-  final String suffix;
+  final String? suffix;
 
-  Builder target;
+  Builder? target;
 
   ConstructorReferenceBuilder(this.name, this.typeArguments, this.suffix,
       Builder parent, this.charOffset)
-      : fileUri = parent.fileUri;
+      : fileUri = parent.fileUri!;
 
   String get fullNameForErrors {
     return "${flattenName(name, charOffset, fileUri)}"
@@ -44,9 +42,9 @@
 
   void resolveIn(Scope scope, LibraryBuilder accessingLibrary) {
     final Object name = this.name;
-    Builder declaration;
+    Builder? declaration;
     if (name is QualifiedName) {
-      String prefix = name.qualifier;
+      String prefix = name.qualifier as String;
       String middle = name.name;
       declaration = scope.lookup(prefix, charOffset, fileUri);
       if (declaration is TypeAliasBuilder) {
@@ -66,7 +64,7 @@
         }
       }
     } else {
-      declaration = scope.lookup(name, charOffset, fileUri);
+      declaration = scope.lookup(name as String, charOffset, fileUri);
       if (declaration is TypeAliasBuilder) {
         TypeAliasBuilder aliasBuilder = declaration;
         declaration = aliasBuilder.unaliasDeclaration(typeArguments);
diff --git a/pkg/front_end/lib/src/fasta/builder/declaration_builder.dart b/pkg/front_end/lib/src/fasta/builder/declaration_builder.dart
index ed02387..4490af2 100644
--- a/pkg/front_end/lib/src/fasta/builder/declaration_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/declaration_builder.dart
@@ -2,8 +2,6 @@
 // for 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 'package:kernel/ast.dart';
 
 import '../messages.dart';
@@ -22,25 +20,25 @@
   LibraryBuilder get library;
 
   /// Lookup a member accessed statically through this declaration.
-  Builder findStaticBuilder(
+  Builder? findStaticBuilder(
       String name, int charOffset, Uri fileUri, LibraryBuilder accessingLibrary,
       {bool isSetter: false});
 
   void addProblem(Message message, int charOffset, int length,
-      {bool wasHandled: false, List<LocatedMessage> context});
+      {bool wasHandled: false, List<LocatedMessage>? context});
 
   /// Returns the type of `this` in an instance of this declaration.
   ///
   /// This is non-null for class and mixin declarations and `null` for
   /// extension declarations.
-  InterfaceType get thisType;
+  InterfaceType? get thisType;
 
   /// Lookups the member [name] declared in this declaration.
   ///
   /// If [setter] is `true` the sought member is a setter or assignable field.
   /// If [required] is `true` and no member is found an internal problem is
   /// reported.
-  Builder lookupLocalMember(String name,
+  Builder? lookupLocalMember(String name,
       {bool setter: false, bool required: false});
 }
 
@@ -52,20 +50,24 @@
   @override
   final ScopeBuilder scopeBuilder;
 
-  DeclarationBuilderImpl(List<MetadataBuilder> metadata, int modifiers,
+  @override
+  final Uri fileUri;
+
+  DeclarationBuilderImpl(List<MetadataBuilder>? metadata, int modifiers,
       String name, LibraryBuilder parent, int charOffset, this.scope)
       : scopeBuilder = new ScopeBuilder(scope),
+        fileUri = parent.fileUri,
         super(metadata, modifiers, name, parent, charOffset);
 
   @override
   LibraryBuilder get library {
-    LibraryBuilder library = parent;
+    LibraryBuilder library = parent as LibraryBuilder;
     return library.partOfLibrary ?? library;
   }
 
   @override
   void addProblem(Message message, int charOffset, int length,
-      {bool wasHandled: false, List<LocatedMessage> context}) {
+      {bool wasHandled: false, List<LocatedMessage>? context}) {
     library.addProblem(message, charOffset, length, fileUri,
         wasHandled: wasHandled, context: context);
   }
diff --git a/pkg/front_end/lib/src/fasta/builder/dynamic_type_declaration_builder.dart b/pkg/front_end/lib/src/fasta/builder/dynamic_type_declaration_builder.dart
index cdc6f30..b5e9b80 100644
--- a/pkg/front_end/lib/src/fasta/builder/dynamic_type_declaration_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/dynamic_type_declaration_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.dynamic_type_builder;
 
 import 'package:kernel/ast.dart' show DartType;
diff --git a/pkg/front_end/lib/src/fasta/builder/enum_builder.dart b/pkg/front_end/lib/src/fasta/builder/enum_builder.dart
index f381e96..9d294ec 100644
--- a/pkg/front_end/lib/src/fasta/builder/enum_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/enum_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.enum_builder;
 
 import 'package:kernel/ast.dart'
@@ -31,6 +29,7 @@
         SuperInitializer,
         ThisExpression,
         VariableGet;
+import 'package:kernel/core_types.dart';
 
 import 'package:kernel/reference_from_index.dart' show IndexedClass;
 
@@ -43,6 +42,8 @@
         templateDuplicatedDeclarationSyntheticCause,
         templateEnumConstantSameNameAsEnclosing;
 
+import '../util/helpers.dart';
+
 import '../modifier.dart'
     show
         constMask,
@@ -71,7 +72,7 @@
 import 'type_builder.dart';
 
 class EnumBuilder extends SourceClassBuilder {
-  final List<EnumConstantInfo> enumConstantInfos;
+  final List<EnumConstantInfo?>? enumConstantInfos;
 
   final NamedTypeBuilder intType;
 
@@ -84,7 +85,7 @@
   final NamedTypeBuilder listType;
 
   EnumBuilder.internal(
-      List<MetadataBuilder> metadata,
+      List<MetadataBuilder>? metadata,
       String name,
       Scope scope,
       ConstructorScope constructors,
@@ -95,54 +96,51 @@
       this.objectType,
       this.enumType,
       this.stringType,
-      LibraryBuilder parent,
-      int startCharOffset,
-      int charOffset,
-      int charEndOffset,
-      Class referencesFrom,
-      IndexedClass referencesFromIndexed)
-      : super(
-            metadata,
-            0,
-            name,
-            null,
-            null,
-            null,
-            null,
-            scope,
-            constructors,
-            parent,
-            null,
-            startCharOffset,
-            charOffset,
-            charEndOffset,
-            referencesFrom,
-            referencesFromIndexed,
-            cls: cls);
-
-  factory EnumBuilder(
-      List<MetadataBuilder> metadata,
-      String name,
-      List<EnumConstantInfo> enumConstantInfos,
       SourceLibraryBuilder parent,
       int startCharOffset,
       int charOffset,
       int charEndOffset,
-      Class referencesFrom,
-      IndexedClass referencesFromIndexed) {
+      IndexedClass? referencesFromIndexed)
+      : super(
+            metadata,
+            0,
+            name,
+            /* typeVariable = */ null,
+            /* supertype = */ null,
+            /* interfaces = */ null,
+            /* onTypes = */ null,
+            scope,
+            constructors,
+            parent,
+            /* constructorReferences = */ null,
+            startCharOffset,
+            charOffset,
+            charEndOffset,
+            referencesFromIndexed,
+            cls: cls);
+
+  factory EnumBuilder(
+      List<MetadataBuilder>? metadata,
+      String name,
+      List<EnumConstantInfo?>? enumConstantInfos,
+      SourceLibraryBuilder parent,
+      int startCharOffset,
+      int charOffset,
+      int charEndOffset,
+      IndexedClass? referencesFromIndexed) {
     assert(enumConstantInfos == null || enumConstantInfos.isNotEmpty);
 
     Uri fileUri = parent.fileUri;
 
     // TODO(ahe): These types shouldn't be looked up in scope, they come
     // directly from dart:core.
-    TypeBuilder intType = new NamedTypeBuilder(
+    NamedTypeBuilder intType = new NamedTypeBuilder(
         "int",
         const NullabilityBuilder.omitted(),
         /* arguments = */ null,
         /* fileUri = */ null,
         /* charOffset = */ null);
-    TypeBuilder stringType = new NamedTypeBuilder(
+    NamedTypeBuilder stringType = new NamedTypeBuilder(
         "String",
         const NullabilityBuilder.omitted(),
         /* arguments = */ null,
@@ -161,7 +159,9 @@
         /* fileUri = */ null,
         /* charOffset = */ null);
     Class cls = new Class(
-        name: name, reference: referencesFrom?.reference, fileUri: fileUri);
+        name: name,
+        reference: referencesFromIndexed?.cls.reference,
+        fileUri: fileUri);
     Map<String, MemberBuilder> members = <String, MemberBuilder>{};
     Map<String, MemberBuilder> constructors = <String, MemberBuilder>{};
     NamedTypeBuilder selfType = new NamedTypeBuilder(
@@ -170,7 +170,7 @@
         /* arguments = */ null,
         /* fileUri = */ null,
         /* charOffset = */ null);
-    TypeBuilder listType = new NamedTypeBuilder(
+    NamedTypeBuilder listType = new NamedTypeBuilder(
         "List",
         const NullabilityBuilder.omitted(),
         <TypeBuilder>[selfType],
@@ -193,7 +193,7 @@
         className: name,
         isExtensionMember: false,
         extensionName: null,
-        libraryReference: referencesFrom != null
+        libraryReference: referencesFromIndexed != null
             ? referencesFromIndexed.library.reference
             : parent.library.reference);
 
@@ -202,7 +202,7 @@
         className: name,
         isExtensionMember: false,
         extensionName: null,
-        libraryReference: referencesFrom != null
+        libraryReference: referencesFromIndexed != null
             ? referencesFromIndexed.library.reference
             : parent.library.reference);
 
@@ -210,21 +210,21 @@
         isStatic: false,
         isExtensionMember: false,
         extensionName: null,
-        libraryReference: referencesFrom != null
+        libraryReference: referencesFromIndexed != null
             ? referencesFromIndexed.library.reference
             : parent.library.reference);
 
-    Constructor constructorReference;
-    Reference toStringReference;
-    Reference indexGetterReference;
-    Reference indexSetterReference;
-    Reference _nameGetterReference;
-    Reference _nameSetterReference;
-    Reference valuesGetterReference;
-    Reference valuesSetterReference;
-    if (referencesFrom != null) {
+    Constructor? constructorReference;
+    Reference? toStringReference;
+    Reference? indexGetterReference;
+    Reference? indexSetterReference;
+    Reference? _nameGetterReference;
+    Reference? _nameSetterReference;
+    Reference? valuesGetterReference;
+    Reference? valuesSetterReference;
+    if (referencesFromIndexed != null) {
       constructorReference =
-          referencesFromIndexed.lookupConstructor(new Name(""));
+          referencesFromIndexed.lookupConstructor(new Name("")) as Constructor;
       toStringReference =
           referencesFromIndexed.lookupGetterReference(new Name("toString"));
       Name indexName = new Name("index");
@@ -243,8 +243,8 @@
           referencesFromIndexed.lookupSetterReference(valuesName);
     }
 
-    members["index"] = new SourceFieldBuilder(
-        null,
+    FieldBuilder indexBuilder = new SourceFieldBuilder(
+        /* metadata = */ null,
         intType,
         "index",
         finalMask | hasInitializerMask,
@@ -256,8 +256,9 @@
         isInstanceMember: true,
         fieldGetterReference: indexGetterReference,
         fieldSetterReference: indexSetterReference);
-    members["_name"] = new SourceFieldBuilder(
-        null,
+    members["index"] = indexBuilder;
+    FieldBuilder nameBuilder = new SourceFieldBuilder(
+        /* metadata = */ null,
         stringType,
         "_name",
         finalMask | hasInitializerMask,
@@ -269,12 +270,13 @@
         isInstanceMember: true,
         fieldGetterReference: _nameGetterReference,
         fieldSetterReference: _nameSetterReference);
+    members["_name"] = nameBuilder;
     ConstructorBuilder constructorBuilder = new ConstructorBuilderImpl(
-        null,
+        /* metadata = */ null,
         constMask,
-        null,
+        /* returnType = */ null,
         "",
-        null,
+        /* typeParameters = */ null,
         <FormalParameterBuilder>[
           new FormalParameterBuilder(null, initializingFormalMask, intType,
               "index", parent, charOffset),
@@ -289,7 +291,7 @@
         constructorReference);
     constructors[""] = constructorBuilder;
     FieldBuilder valuesBuilder = new SourceFieldBuilder(
-        null,
+        /* metadata = */ null,
         listType,
         "values",
         constMask | staticMask | hasInitializerMask,
@@ -303,11 +305,11 @@
         fieldSetterReference: valuesSetterReference);
     members["values"] = valuesBuilder;
     constructorBuilder
-      ..registerInitializedField(members["_name"])
-      ..registerInitializedField(members["index"])
+      ..registerInitializedField(nameBuilder)
+      ..registerInitializedField(indexBuilder)
       ..registerInitializedField(valuesBuilder);
     ProcedureBuilder toStringBuilder = new SourceProcedureBuilder(
-        null,
+        /* metadata = */ null,
         0,
         stringType,
         "toString",
@@ -329,10 +331,10 @@
     String className = name;
     if (enumConstantInfos != null) {
       for (int i = 0; i < enumConstantInfos.length; i++) {
-        EnumConstantInfo enumConstantInfo = enumConstantInfos[i];
-        List<MetadataBuilder> metadata = enumConstantInfo.metadata;
+        EnumConstantInfo enumConstantInfo = enumConstantInfos[i]!;
+        List<MetadataBuilder>? metadata = enumConstantInfo.metadata;
         String name = enumConstantInfo.name;
-        MemberBuilder existing = members[name];
+        MemberBuilder? existing = members[name];
         if (existing != null) {
           // The existing declaration is synthetic if it has the same
           // charOffset as the enclosing enum.
@@ -361,8 +363,8 @@
               name.length,
               parent.fileUri);
         }
-        Reference getterReference;
-        Reference setterReference;
+        Reference? getterReference;
+        Reference? setterReference;
         if (referencesFromIndexed != null) {
           Name nameName = new Name(name, referencesFromIndexed.library);
           getterReference =
@@ -408,13 +410,13 @@
         startCharOffsetComputed,
         charOffset,
         charEndOffset,
-        referencesFrom,
         referencesFromIndexed);
-    void setParent(String name, MemberBuilder builder) {
-      do {
+
+    void setParent(String name, MemberBuilder? builder) {
+      while (builder != null) {
         builder.parent = enumBuilder;
-        builder = builder.next;
-      } while (builder != null);
+        builder = builder.next as MemberBuilder?;
+      }
     }
 
     members.forEach(setParent);
@@ -423,11 +425,13 @@
     return enumBuilder;
   }
 
-  TypeBuilder get mixedInTypeBuilder => null;
+  @override
+  TypeBuilder? get mixedInTypeBuilder => null;
 
+  @override
   InterfaceType buildType(LibraryBuilder library,
-      NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments,
-      [bool notInstanceContext]) {
+      NullabilityBuilder nullabilityBuilder, List<TypeBuilder>? arguments,
+      {bool? nonInstanceContext}) {
     return rawType(nullabilityBuilder.build(library));
   }
 
@@ -443,15 +447,18 @@
     listType.resolveIn(coreLibrary.scope, charOffset, fileUri, libraryBuilder);
 
     cls.implementedTypes
-        .add(enumType.buildSupertype(libraryBuilder, charOffset, fileUri));
+        .add(enumType.buildSupertype(libraryBuilder, charOffset, fileUri)!);
 
-    SourceFieldBuilder indexFieldBuilder = firstMemberNamed("index");
+    SourceFieldBuilder indexFieldBuilder =
+        firstMemberNamed("index") as SourceFieldBuilder;
     indexFieldBuilder.build(libraryBuilder);
     Field indexField = indexFieldBuilder.field;
-    SourceFieldBuilder nameFieldBuilder = firstMemberNamed("_name");
+    SourceFieldBuilder nameFieldBuilder =
+        firstMemberNamed("_name") as SourceFieldBuilder;
     nameFieldBuilder.build(libraryBuilder);
     Field nameField = nameFieldBuilder.field;
-    ProcedureBuilder toStringBuilder = firstMemberNamed("toString");
+    ProcedureBuilder toStringBuilder =
+        firstMemberNamed("toString") as ProcedureBuilder;
     if (libraryBuilder
         .loader.target.backendTarget.supportsNewMethodInvocationEncoding) {
       toStringBuilder.body = new ReturnStatement(new InstanceGet(
@@ -463,25 +470,22 @@
     }
     List<Expression> values = <Expression>[];
     if (enumConstantInfos != null) {
-      for (EnumConstantInfo enumConstantInfo in enumConstantInfos) {
+      for (EnumConstantInfo? enumConstantInfo in enumConstantInfos!) {
         if (enumConstantInfo != null) {
-          Builder declaration = firstMemberNamed(enumConstantInfo.name);
+          Builder declaration = firstMemberNamed(enumConstantInfo.name)!;
           if (declaration.isField) {
-            SourceFieldBuilder fieldBuilder = declaration;
+            SourceFieldBuilder fieldBuilder = declaration as SourceFieldBuilder;
             fieldBuilder.build(libraryBuilder);
             values.add(new StaticGet(fieldBuilder.field));
           }
         }
       }
     }
-    SourceFieldBuilder valuesBuilder = firstMemberNamed("values");
+    SourceFieldBuilder valuesBuilder =
+        firstMemberNamed("values") as SourceFieldBuilder;
     valuesBuilder.build(libraryBuilder);
-    valuesBuilder.buildBody(
-        // TODO(johnniwinther): Create the bodies only when we have core types.
-        null,
-        new ListLiteral(values,
-            typeArgument: rawType(library.nonNullable), isConst: true));
-    ConstructorBuilderImpl constructorBuilder = constructorScopeBuilder[""];
+    ConstructorBuilderImpl constructorBuilder =
+        constructorScopeBuilder[""] as ConstructorBuilderImpl;
     Constructor constructor = constructorBuilder.build(libraryBuilder);
     constructor.initializers.insert(
         0,
@@ -493,8 +497,8 @@
         new FieldInitializer(nameField,
             new VariableGet(constructor.function.positionalParameters[1]))
           ..parent = constructor);
-    ClassBuilder objectClass = objectType.declaration;
-    MemberBuilder superConstructor = objectClass.findConstructorOrFactory(
+    ClassBuilder objectClass = objectType.declaration as ClassBuilder;
+    MemberBuilder? superConstructor = objectClass.findConstructorOrFactory(
         "", charOffset, fileUri, libraryBuilder);
     if (superConstructor == null || !superConstructor.isConstructor) {
       // TODO(ahe): Ideally, we would also want to check that [Object]'s
@@ -504,19 +508,49 @@
       library.addProblem(messageNoUnnamedConstructorInObject,
           objectClass.charOffset, objectClass.name.length, objectClass.fileUri);
     } else {
-      constructor.initializers.add(
-          new SuperInitializer(superConstructor.member, new Arguments.empty())
-            ..parent = constructor);
+      constructor.initializers.add(new SuperInitializer(
+          superConstructor.member as Constructor, new Arguments.empty())
+        ..parent = constructor);
     }
+    return super.build(libraryBuilder, coreLibrary);
+  }
+
+  @override
+  void buildOutlineExpressions(
+      SourceLibraryBuilder libraryBuilder,
+      CoreTypes coreTypes,
+      List<DelayedActionPerformer> delayedActionPerformers) {
+    List<Expression> values = <Expression>[];
+    if (enumConstantInfos != null) {
+      for (EnumConstantInfo? enumConstantInfo in enumConstantInfos!) {
+        if (enumConstantInfo != null) {
+          Builder declaration = firstMemberNamed(enumConstantInfo.name)!;
+          if (declaration.isField) {
+            SourceFieldBuilder fieldBuilder = declaration as SourceFieldBuilder;
+            fieldBuilder.build(libraryBuilder);
+            values.add(new StaticGet(fieldBuilder.field));
+          }
+        }
+      }
+    }
+    SourceFieldBuilder valuesBuilder =
+        firstMemberNamed("values") as SourceFieldBuilder;
+    valuesBuilder.buildBody(
+        coreTypes,
+        new ListLiteral(values,
+            typeArgument: rawType(library.nonNullable), isConst: true));
+    ConstructorBuilderImpl constructorBuilder =
+        constructorScopeBuilder[""] as ConstructorBuilderImpl;
+    Constructor constructor = constructorBuilder.constructor;
     int index = 0;
     if (enumConstantInfos != null) {
-      for (EnumConstantInfo enumConstantInfo in enumConstantInfos) {
+      for (EnumConstantInfo? enumConstantInfo in enumConstantInfos!) {
         if (enumConstantInfo != null) {
           String constant = enumConstantInfo.name;
-          Builder declaration = firstMemberNamed(constant);
+          Builder declaration = firstMemberNamed(constant)!;
           FieldBuilder field;
           if (declaration.isField) {
-            field = declaration;
+            field = declaration as FieldBuilder;
           } else {
             continue;
           }
@@ -524,26 +558,23 @@
             new IntLiteral(index++),
             new StringLiteral("$name.$constant")
           ]);
-          field.buildBody(
-              // TODO(johnniwinther): Create the bodies only when we have core
-              //  types.
-              null,
+          field.buildBody(coreTypes,
               new ConstructorInvocation(constructor, arguments, isConst: true));
         }
       }
     }
-    return super.build(libraryBuilder, coreLibrary);
+    super.buildOutlineExpressions(library, coreTypes, delayedActionPerformers);
   }
 
   @override
-  MemberBuilder findConstructorOrFactory(
+  MemberBuilder? findConstructorOrFactory(
       String name, int charOffset, Uri uri, LibraryBuilder library) {
     return null;
   }
 }
 
 class EnumConstantInfo {
-  final List<MetadataBuilder> metadata;
+  final List<MetadataBuilder>? metadata;
   final String name;
   final int charOffset;
   const EnumConstantInfo(this.metadata, this.name, this.charOffset);
diff --git a/pkg/front_end/lib/src/fasta/builder/extension_builder.dart b/pkg/front_end/lib/src/fasta/builder/extension_builder.dart
index f233bb3..0ca4e45 100644
--- a/pkg/front_end/lib/src/fasta/builder/extension_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/extension_builder.dart
@@ -2,8 +2,6 @@
 // for 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 'package:kernel/ast.dart';
 import 'package:kernel/core_types.dart';
 
@@ -24,13 +22,20 @@
 import 'type_variable_builder.dart';
 
 abstract class ExtensionBuilder implements DeclarationBuilder {
-  List<TypeVariableBuilder> get typeParameters;
+  /// Type parameters declared on the extension.
+  ///
+  /// This is `null` if the extension is not generic.
+  List<TypeVariableBuilder>? get typeParameters;
+
+  /// The type of the on-clause of the extension declaration.
   TypeBuilder get onType;
 
   /// Return the [Extension] built by this builder.
   Extension get extension;
 
-  void buildOutlineExpressions(LibraryBuilder library, CoreTypes coreTypes,
+  void buildOutlineExpressions(
+      SourceLibraryBuilder library,
+      CoreTypes coreTypes,
       List<DelayedActionPerformer> delayedActionPerformers);
 
   /// Looks up extension member by [name] taking privacy into account.
@@ -43,7 +48,7 @@
   // TODO(johnniwinther): Support [AmbiguousBuilder] here and in instance
   // member lookup to avoid reporting that the member doesn't exist when it is
   // duplicate.
-  Builder lookupLocalMemberByName(Name name,
+  Builder? lookupLocalMemberByName(Name name,
       {bool setter: false, bool required: false});
 
   /// Calls [f] for each member declared in this extension.
@@ -52,26 +57,13 @@
 
 abstract class ExtensionBuilderImpl extends DeclarationBuilderImpl
     implements ExtensionBuilder {
-  @override
-  final List<TypeVariableBuilder> typeParameters;
-
-  @override
-  final TypeBuilder onType;
-
-  ExtensionBuilderImpl(
-      List<MetadataBuilder> metadata,
-      int modifiers,
-      String name,
-      LibraryBuilder parent,
-      int charOffset,
-      Scope scope,
-      this.typeParameters,
-      this.onType)
+  ExtensionBuilderImpl(List<MetadataBuilder>? metadata, int modifiers,
+      String name, LibraryBuilder parent, int charOffset, Scope scope)
       : super(metadata, modifiers, name, parent, charOffset, scope);
 
   /// Lookup a static member of this declaration.
   @override
-  Builder findStaticBuilder(
+  Builder? findStaticBuilder(
       String name, int charOffset, Uri fileUri, LibraryBuilder accessingLibrary,
       {bool isSetter: false}) {
     if (accessingLibrary.nameOriginBuilder.origin !=
@@ -79,7 +71,7 @@
         name.startsWith("_")) {
       return null;
     }
-    Builder declaration = isSetter
+    Builder? declaration = isSetter
         ? scope.lookupSetter(name, charOffset, fileUri, isInstanceScope: false)
         : scope.lookup(name, charOffset, fileUri, isInstanceScope: false);
     // TODO(johnniwinther): Handle patched extensions.
@@ -88,14 +80,15 @@
 
   @override
   DartType buildType(LibraryBuilder library,
-      NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments,
-      [bool notInstanceContext]) {
+      NullabilityBuilder nullabilityBuilder, List<TypeBuilder>? arguments,
+      {bool? nonInstanceContext}) {
     if (library is SourceLibraryBuilder &&
         library.enableExtensionTypesInLibrary) {
       return buildTypesWithBuiltArguments(
           library,
           nullabilityBuilder.build(library),
-          buildTypeArguments(library, arguments, notInstanceContext));
+          buildTypeArguments(library, arguments,
+              nonInstanceContext: nonInstanceContext));
     } else {
       throw new UnsupportedError("ExtensionBuilder.buildType is not supported"
           "in library '${library.importUri}'.");
@@ -119,19 +112,17 @@
   int get typeVariablesCount => typeParameters?.length ?? 0;
 
   List<DartType> buildTypeArguments(
-      LibraryBuilder library, List<TypeBuilder> arguments,
-      [bool notInstanceContext]) {
+      LibraryBuilder library, List<TypeBuilder>? arguments,
+      {bool? nonInstanceContext}) {
     if (arguments == null && typeParameters == null) {
       return <DartType>[];
     }
 
     if (arguments == null && typeParameters != null) {
-      List<DartType> result = new List<DartType>.filled(
-          typeParameters.length, null,
-          growable: true);
-      for (int i = 0; i < result.length; ++i) {
-        result[i] = typeParameters[i].defaultType.build(library);
-      }
+      List<DartType> result =
+          new List<DartType>.generate(typeParameters!.length, (int i) {
+        return typeParameters![i].defaultType!.build(library);
+      }, growable: true);
       if (library is SourceLibraryBuilder) {
         library.inferredTypes.addAll(result);
       }
@@ -149,12 +140,11 @@
           null);
     }
 
-    assert(arguments.length == typeVariablesCount);
+    assert(arguments!.length == typeVariablesCount);
     List<DartType> result =
-        new List<DartType>.filled(arguments.length, null, growable: true);
-    for (int i = 0; i < result.length; ++i) {
-      result[i] = arguments[i].build(library);
-    }
+        new List<DartType>.generate(arguments!.length, (int i) {
+      return arguments[i].build(library);
+    }, growable: true);
     return result;
   }
 
@@ -167,13 +157,13 @@
   bool get isExtension => true;
 
   @override
-  InterfaceType get thisType => null;
+  InterfaceType? get thisType => null;
 
   @override
-  Builder lookupLocalMember(String name,
+  Builder? lookupLocalMember(String name,
       {bool setter: false, bool required: false}) {
     // TODO(johnniwinther): Support patching on extensions.
-    Builder builder = scope.lookupLocalMember(name, setter: setter);
+    Builder? builder = scope.lookupLocalMember(name, setter: setter);
     if (required && builder == null) {
       internalProblem(
           templateInternalProblemNotFoundIn.withArguments(
@@ -185,9 +175,9 @@
   }
 
   @override
-  Builder lookupLocalMemberByName(Name name,
+  Builder? lookupLocalMemberByName(Name name,
       {bool setter: false, bool required: false}) {
-    Builder builder =
+    Builder? builder =
         lookupLocalMember(name.text, setter: setter, required: required);
     if (builder != null) {
       if (name.isPrivate && library.library != name.library) {
diff --git a/pkg/front_end/lib/src/fasta/builder/field_builder.dart b/pkg/front_end/lib/src/fasta/builder/field_builder.dart
index a0854b8..12b9103 100644
--- a/pkg/front_end/lib/src/fasta/builder/field_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/field_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.field_builder;
 
 import 'package:_fe_analyzer_shared/src/scanner/scanner.dart' show Token;
@@ -38,7 +36,6 @@
 import '../util/helpers.dart' show DelayedActionPerformer;
 
 import 'class_builder.dart';
-import 'library_builder.dart';
 import 'member_builder.dart';
 import 'metadata_builder.dart';
 import 'type_builder.dart';
@@ -46,11 +43,9 @@
 abstract class FieldBuilder implements MemberBuilder {
   Field get field;
 
-  List<MetadataBuilder> get metadata;
+  List<MetadataBuilder>? get metadata;
 
-  TypeBuilder get type;
-
-  Token get constInitializerToken;
+  TypeBuilder? get type;
 
   bool get isCovariant;
 
@@ -66,13 +61,13 @@
 
   /// Builds the body of this field using [initializer] as the initializer
   /// expression.
-  void buildBody(CoreTypes coreTypes, Expression initializer);
+  void buildBody(CoreTypes coreTypes, Expression? initializer);
 
   /// Builds the field initializers for each field used to encode this field
   /// using the [fileOffset] for the created nodes and [value] as the initial
   /// field value.
   List<Initializer> buildInitializer(int fileOffset, Expression value,
-      {bool isSynthetic});
+      {required bool isSynthetic});
 
   bool get isEligibleForInference;
 
@@ -80,7 +75,7 @@
 
   DartType inferType();
 
-  DartType fieldType;
+  DartType get fieldType;
 }
 
 class SourceFieldBuilder extends MemberBuilderImpl implements FieldBuilder {
@@ -90,16 +85,15 @@
   @override
   final int modifiers;
 
-  FieldEncoding _fieldEncoding;
+  late FieldEncoding _fieldEncoding;
 
   @override
-  final List<MetadataBuilder> metadata;
+  final List<MetadataBuilder>? metadata;
 
   @override
-  final TypeBuilder type;
+  final TypeBuilder? type;
 
-  @override
-  Token constInitializerToken;
+  Token? _constInitializerToken;
 
   bool hadTypesInferred = false;
 
@@ -121,17 +115,20 @@
       int charOffset,
       int charEndOffset,
       FieldNameScheme fieldNameScheme,
-      {bool isInstanceMember,
-      Reference fieldGetterReference,
-      Reference fieldSetterReference,
-      Reference lateIsSetGetterReference,
-      Reference lateIsSetSetterReference,
-      Reference lateGetterReference,
-      Reference lateSetterReference})
-      : super(libraryBuilder, charOffset) {
+      {required bool isInstanceMember,
+      Reference? fieldGetterReference,
+      Reference? fieldSetterReference,
+      Reference? lateIsSetGetterReference,
+      Reference? lateIsSetSetterReference,
+      Reference? lateGetterReference,
+      Reference? lateSetterReference,
+      Token? constInitializerToken})
+      : _constInitializerToken = constInitializerToken,
+        super(libraryBuilder, charOffset) {
+    // ignore: unnecessary_null_comparison
     assert(isInstanceMember != null);
 
-    Uri fileUri = libraryBuilder?.fileUri;
+    Uri fileUri = libraryBuilder.fileUri;
     // If in mixed mode, late lowerings cannot use `null` as a sentinel on
     // non-nullable fields since they can be assigned from legacy code.
     late_lowering.IsSetStrategy isSetStrategy =
@@ -281,7 +278,7 @@
   bool get isLateLowered => _fieldEncoding.isLateLowering;
 
   bool _typeEnsured = false;
-  Set<ClassMember> _overrideDependencies;
+  Set<ClassMember>? _overrideDependencies;
 
   void registerOverrideDependency(Set<ClassMember> overriddenMembers) {
     assert(
@@ -289,13 +286,13 @@
             overriddenMember.classBuilder != classBuilder),
         "Unexpected override dependencies for $this: $overriddenMembers");
     _overrideDependencies ??= {};
-    _overrideDependencies.addAll(overriddenMembers);
+    _overrideDependencies!.addAll(overriddenMembers);
   }
 
   void _ensureType(ClassHierarchyBuilder hierarchy) {
     if (_typeEnsured) return;
     if (_overrideDependencies != null) {
-      hierarchy.inferFieldType(this, _overrideDependencies);
+      hierarchy.inferFieldType(this, _overrideDependencies!);
       _overrideDependencies = null;
     } else {
       inferType();
@@ -303,7 +300,7 @@
     _typeEnsured = true;
   }
 
-  SourceLibraryBuilder get library => super.library;
+  SourceLibraryBuilder get library => super.library as SourceLibraryBuilder;
 
   Member get member => _fieldEncoding.field;
 
@@ -321,7 +318,7 @@
   bool get hasInitializer => (modifiers & hasInitializerMask) != 0;
 
   @override
-  void buildBody(CoreTypes coreTypes, Expression initializer) {
+  void buildBody(CoreTypes coreTypes, Expression? initializer) {
     assert(!hasBodyBeenBuilt);
     hasBodyBeenBuilt = true;
     if (!hasInitializer &&
@@ -341,7 +338,7 @@
 
   @override
   List<Initializer> buildInitializer(int fileOffset, Expression value,
-      {bool isSynthetic}) {
+      {required bool isSynthetic}) {
     return _fieldEncoding.createInitializer(fileOffset, value,
         isSynthetic: isSynthetic);
   }
@@ -369,7 +366,7 @@
   Member get readTarget => _fieldEncoding.readTarget;
 
   @override
-  Member get writeTarget {
+  Member? get writeTarget {
     return isAssignable ? _fieldEncoding.writeTarget : null;
   }
 
@@ -381,7 +378,7 @@
 
   @override
   void buildMembers(
-      LibraryBuilder library, void Function(Member, BuiltMemberKind) f) {
+      SourceLibraryBuilder library, void Function(Member, BuiltMemberKind) f) {
     build(library);
     _fieldEncoding.registerMembers(library, this, f);
   }
@@ -391,18 +388,19 @@
     if (type != null) {
       // notInstanceContext is set to true for extension fields as they
       // ultimately become static.
-      fieldType =
-          type.build(libraryBuilder, null, isStatic || isExtensionMember);
+      fieldType = type!.build(libraryBuilder,
+          nonInstanceContext: isStatic || isExtensionMember);
     }
     _fieldEncoding.build(libraryBuilder, this);
   }
 
   @override
-  void buildOutlineExpressions(LibraryBuilder library, CoreTypes coreTypes,
+  void buildOutlineExpressions(
+      SourceLibraryBuilder library,
+      CoreTypes coreTypes,
       List<DelayedActionPerformer> delayedActionPerformers) {
     _fieldEncoding.completeSignature(coreTypes);
 
-    ClassBuilder classBuilder = isClassMember ? parent : null;
     for (Annotatable annotatable in _fieldEncoding.annotatables) {
       MetadataBuilder.buildAnnotations(
           annotatable, metadata, library, classBuilder, this, fileUri);
@@ -415,18 +413,18 @@
             (isFinal &&
                 !isStatic &&
                 isClassMember &&
-                classBuilder.declaresConstConstructor)) &&
-        constInitializerToken != null) {
+                classBuilder!.declaresConstConstructor)) &&
+        _constInitializerToken != null) {
       Scope scope = classBuilder?.scope ?? library.scope;
       BodyBuilder bodyBuilder = library.loader
           .createBodyBuilderForOutlineExpression(
               library, classBuilder, this, scope, fileUri);
       bodyBuilder.constantContext =
           isConst ? ConstantContext.inferred : ConstantContext.required;
-      Expression initializer = bodyBuilder.typeInferrer?.inferFieldInitializer(
+      Expression initializer = bodyBuilder.typeInferrer.inferFieldInitializer(
           bodyBuilder,
           fieldType,
-          bodyBuilder.parseFieldInitializer(constInitializerToken));
+          bodyBuilder.parseFieldInitializer(_constInitializerToken!));
       if (library.loader is SourceLoader &&
           (bodyBuilder.transformSetLiterals ||
               bodyBuilder.transformCollections)) {
@@ -444,7 +442,7 @@
         delayedActionPerformers.add(bodyBuilder);
       }
     }
-    constInitializerToken = null;
+    _constInitializerToken = null;
   }
 
   DartType get fieldType => _fieldEncoding.type;
@@ -452,8 +450,7 @@
   void set fieldType(DartType value) {
     _fieldEncoding.type = value;
     if (!isFinal && !isConst && parent is ClassBuilder) {
-      ClassBuilder enclosingClassBuilder = parent;
-      Class enclosingClass = enclosingClassBuilder.cls;
+      Class enclosingClass = classBuilder!.cls;
       if (enclosingClass.typeParameters.isNotEmpty) {
         IncludesTypeParametersNonCovariantly needsCheckVisitor =
             new IncludesTypeParametersNonCovariantly(
@@ -477,7 +474,7 @@
       return fieldType;
     }
 
-    ImplicitFieldType implicitFieldType = fieldType;
+    ImplicitFieldType implicitFieldType = fieldType as ImplicitFieldType;
     DartType inferredType = implicitFieldType.computeType();
     if (fieldType is ImplicitFieldType) {
       // `fieldType` may have changed if a circularity was detected when
@@ -487,10 +484,9 @@
       }
       fieldType = implicitFieldType.checkInferred(inferredType);
 
-      IncludesTypeParametersNonCovariantly needsCheckVisitor;
+      IncludesTypeParametersNonCovariantly? needsCheckVisitor;
       if (parent is ClassBuilder) {
-        ClassBuilder enclosingClassBuilder = parent;
-        Class enclosingClass = enclosingClassBuilder.cls;
+        Class enclosingClass = classBuilder!.cls;
         if (enclosingClass.typeParameters.isNotEmpty) {
           needsCheckVisitor = new IncludesTypeParametersNonCovariantly(
               enclosingClass.typeParameters,
@@ -511,8 +507,8 @@
 
   DartType get builtType => fieldType;
 
-  List<ClassMember> _localMembers;
-  List<ClassMember> _localSetters;
+  List<ClassMember>? _localMembers;
+  List<ClassMember>? _localSetters;
 
   @override
   List<ClassMember> get localMembers =>
@@ -523,17 +519,19 @@
       _localSetters ??= _fieldEncoding.getLocalSetters(this);
 
   static String createFieldName(FieldNameType type, String name,
-      {bool isInstanceMember,
-      String className,
+      {required bool isInstanceMember,
+      required String? className,
       bool isExtensionMethod: false,
-      String extensionName,
+      String? extensionName,
       bool isSynthesized: false}) {
     assert(isSynthesized || type == FieldNameType.Field,
         "Unexpected field name type for non-synthesized field: $type");
+    // ignore: unnecessary_null_comparison
     assert(isExtensionMethod || isInstanceMember != null,
         "`isInstanceMember` is null for class member.");
     assert(!(isExtensionMethod && extensionName == null),
         "No extension name provided for extension member.");
+    // ignore: unnecessary_null_comparison
     assert(isInstanceMember == null || !(isInstanceMember && className == null),
         "No class name provided for instance member.");
     String baseName;
@@ -561,7 +559,6 @@
           return "$namePrefix$baseName${late_lowering.lateIsSetSuffix}";
       }
     }
-    throw new UnsupportedError("Unhandled case for field name.");
   }
 }
 
@@ -569,23 +566,28 @@
 
 class FieldNameScheme {
   final bool isInstanceMember;
-  final String className;
+  final String? className;
   final bool isExtensionMember;
-  final String extensionName;
-  final Reference libraryReference;
+  final String? extensionName;
+  final Reference? libraryReference;
 
   FieldNameScheme(
-      {this.isInstanceMember,
-      this.className,
-      this.isExtensionMember,
-      this.extensionName,
-      this.libraryReference})
+      {required this.isInstanceMember,
+      required this.className,
+      required this.isExtensionMember,
+      required this.extensionName,
+      required this.libraryReference})
+      // ignore: unnecessary_null_comparison
       : assert(isInstanceMember != null),
+        // ignore: unnecessary_null_comparison
         assert(isExtensionMember != null),
+        // ignore: unnecessary_null_comparison
         assert(!isExtensionMember || extensionName != null),
+        // ignore: unnecessary_null_comparison
         assert(libraryReference != null);
 
-  Name getName(FieldNameType type, String name, {bool isSynthesized}) {
+  Name getName(FieldNameType type, String name, {required bool isSynthesized}) {
+    // ignore: unnecessary_null_comparison
     assert(isSynthesized != null);
     String text = SourceFieldBuilder.createFieldName(type, name,
         isInstanceMember: isInstanceMember,
@@ -603,18 +605,18 @@
 /// and setters.
 abstract class FieldEncoding {
   /// The type of the declared field.
-  DartType type;
+  abstract DartType type;
 
   /// Creates the bodies needed for the field encoding using [initializer] as
   /// the declared initializer expression.
   ///
   /// This method is not called for fields in outlines unless their are constant
   /// or part of a const constructor.
-  void createBodies(CoreTypes coreTypes, Expression initializer,
+  void createBodies(CoreTypes coreTypes, Expression? initializer,
       bool useNewMethodInvocationEncoding);
 
   List<Initializer> createInitializer(int fileOffset, Expression value,
-      {bool isSynthetic});
+      {required bool isSynthetic});
 
   /// Registers that the (implicit) setter associated with this field needs to
   /// contain a runtime type check to deal with generic covariance.
@@ -630,7 +632,7 @@
   Member get readTarget;
 
   /// Returns the member used to write to the field.
-  Member get writeTarget;
+  Member? get writeTarget;
 
   /// Returns the generated members that are visible through exports.
   Iterable<Member> get exportedMembers;
@@ -665,20 +667,24 @@
 }
 
 class RegularFieldEncoding implements FieldEncoding {
-  Field _field;
+  late final Field _field;
 
   RegularFieldEncoding(String name, FieldNameScheme fieldNameScheme,
       Uri fileUri, int charOffset, int charEndOffset,
-      {bool isFinal,
-      bool isConst,
-      bool isLate,
-      bool hasInitializer,
-      bool isNonNullableByDefault,
-      Reference getterReference,
-      Reference setterReference}) {
+      {required bool isFinal,
+      required bool isConst,
+      required bool isLate,
+      required bool hasInitializer,
+      required bool isNonNullableByDefault,
+      required Reference? getterReference,
+      required Reference? setterReference}) {
+    // ignore: unnecessary_null_comparison
     assert(isFinal != null);
+    // ignore: unnecessary_null_comparison
     assert(isConst != null);
+    // ignore: unnecessary_null_comparison
     assert(isLate != null);
+    // ignore: unnecessary_null_comparison
     assert(hasInitializer != null);
     bool isImmutable =
         isLate ? (isFinal && hasInitializer) : (isFinal || isConst);
@@ -717,7 +723,7 @@
   void completeSignature(CoreTypes coreTypes) {}
 
   @override
-  void createBodies(CoreTypes coreTypes, Expression initializer,
+  void createBodies(CoreTypes coreTypes, Expression? initializer,
       bool useNewMethodInvocationEncoding) {
     if (initializer != null) {
       _field.initializer = initializer..parent = _field;
@@ -726,7 +732,7 @@
 
   @override
   List<Initializer> createInitializer(int fileOffset, Expression value,
-      {bool isSynthetic}) {
+      {required bool isSynthetic}) {
     return <Initializer>[
       new FieldInitializer(_field, value)
         ..fileOffset = fileOffset
@@ -803,12 +809,13 @@
   @override
   final SourceFieldBuilder memberBuilder;
 
-  Covariance _covariance;
+  Covariance? _covariance;
 
   @override
   final bool forSetter;
 
-  SourceFieldMember(this.memberBuilder, {this.forSetter})
+  SourceFieldMember(this.memberBuilder, {required this.forSetter})
+      // ignore: unnecessary_null_comparison
       : assert(forSetter != null);
 
   @override
@@ -850,19 +857,19 @@
   final String name;
   final int fileOffset;
   final int fileEndOffset;
-  DartType _type;
-  Field _field;
-  Field _lateIsSetField;
-  Procedure _lateGetter;
-  Procedure _lateSetter;
+  DartType? _type;
+  late final Field _field;
+  Field? _lateIsSetField;
+  late Procedure _lateGetter;
+  Procedure? _lateSetter;
 
   // If `true`, an isSet field is used even when the type of the field is
   // not potentially nullable.
   //
   // This is used to force use isSet fields in mixed mode encoding since
   // we cannot trust non-nullable fields to be initialized with non-null values.
-  late_lowering.IsSetStrategy _isSetStrategy;
-  late_lowering.IsSetEncoding _isSetEncoding;
+  final late_lowering.IsSetStrategy _isSetStrategy;
+  late_lowering.IsSetEncoding? _isSetEncoding;
 
   // If `true`, the is-set field was register before the type was known to be
   // nullable or non-nullable. In this case we do not try to remove it from
@@ -879,12 +886,12 @@
       Uri fileUri,
       int charOffset,
       int charEndOffset,
-      Reference fieldGetterReference,
-      Reference fieldSetterReference,
-      Reference lateIsSetGetterReference,
-      Reference lateIsSetSetterReference,
-      Reference lateGetterReference,
-      Reference lateSetterReference,
+      Reference? fieldGetterReference,
+      Reference? fieldSetterReference,
+      Reference? lateIsSetGetterReference,
+      Reference? lateIsSetSetterReference,
+      Reference? lateGetterReference,
+      Reference? lateSetterReference,
       bool isCovariant,
       late_lowering.IsSetStrategy isSetStrategy)
       : fileOffset = charOffset,
@@ -944,23 +951,21 @@
   late_lowering.IsSetEncoding get isSetEncoding {
     assert(_type != null, "Type has not been computed for field $name.");
     return _isSetEncoding ??=
-        late_lowering.computeIsSetEncoding(_type, _isSetStrategy);
+        late_lowering.computeIsSetEncoding(_type!, _isSetStrategy);
   }
 
   @override
   void completeSignature(CoreTypes coreTypes) {
-    if (_lateIsSetField != null) {
-      _lateIsSetField.type = coreTypes.boolRawType(Nullability.nonNullable);
-    }
+    _lateIsSetField?.type = coreTypes.boolRawType(Nullability.nonNullable);
   }
 
   @override
-  void createBodies(CoreTypes coreTypes, Expression initializer,
+  void createBodies(CoreTypes coreTypes, Expression? initializer,
       bool useNewMethodInvocationEncoding) {
     assert(_type != null, "Type has not been computed for field $name.");
     if (isSetEncoding == late_lowering.IsSetEncoding.useSentinel) {
       _field.initializer = new StaticInvocation(coreTypes.createSentinelMethod,
-          new Arguments([], types: [_type])..fileOffset = fileOffset)
+          new Arguments([], types: [_type!])..fileOffset = fileOffset)
         ..fileOffset = fileOffset
         ..parent = _field;
     } else {
@@ -969,7 +974,7 @@
         ..parent = _field;
     }
     if (_lateIsSetField != null) {
-      _lateIsSetField.initializer = new BoolLiteral(false)
+      _lateIsSetField!.initializer = new BoolLiteral(false)
         ..fileOffset = fileOffset
         ..parent = _lateIsSetField;
     }
@@ -977,22 +982,22 @@
         coreTypes, name, initializer, useNewMethodInvocationEncoding)
       ..parent = _lateGetter.function;
     if (_lateSetter != null) {
-      _lateSetter.function.body = _createSetterBody(
+      _lateSetter!.function.body = _createSetterBody(
           coreTypes,
           name,
-          _lateSetter.function.positionalParameters.first,
+          _lateSetter!.function.positionalParameters.first,
           useNewMethodInvocationEncoding)
-        ..parent = _lateSetter.function;
+        ..parent = _lateSetter!.function;
     }
   }
 
   @override
   List<Initializer> createInitializer(int fileOffset, Expression value,
-      {bool isSynthetic}) {
+      {required bool isSynthetic}) {
     List<Initializer> initializers = <Initializer>[];
     if (_lateIsSetField != null) {
       initializers.add(new FieldInitializer(
-          _lateIsSetField, new BoolLiteral(true)..fileOffset = fileOffset)
+          _lateIsSetField!, new BoolLiteral(true)..fileOffset = fileOffset)
         ..fileOffset = fileOffset
         ..isSynthetic = isSynthetic);
     }
@@ -1010,10 +1015,11 @@
   /// nullability.
   Expression _createFieldRead(bool useNewMethodInvocationEncoding,
       {bool needsPromotion: false}) {
+    assert(_type != null, "Type has not been computed for field $name.");
     if (needsPromotion) {
       VariableDeclaration variable = new VariableDeclaration.forValue(
           _createFieldGet(_field, useNewMethodInvocationEncoding),
-          type: _type.withDeclaredNullability(Nullability.nullable))
+          type: _type!.withDeclaredNullability(Nullability.nullable))
         ..fileOffset = fileOffset;
       return new Let(
           variable, new VariableGet(variable, _type)..fileOffset = fileOffset);
@@ -1062,11 +1068,12 @@
   }
 
   Statement _createGetterBody(CoreTypes coreTypes, String name,
-      Expression initializer, bool useNewMethodInvocationEncoding);
+      Expression? initializer, bool useNewMethodInvocationEncoding);
 
-  Procedure _createSetter(
-      Name name, Uri fileUri, int charOffset, Reference reference,
-      {bool isCovariant}) {
+  Procedure? _createSetter(
+      Name name, Uri fileUri, int charOffset, Reference? reference,
+      {required bool isCovariant}) {
+    // ignore: unnecessary_null_comparison
     assert(isCovariant != null);
     VariableDeclaration parameter = new VariableDeclaration(null)
       ..isCovariant = isCovariant
@@ -1089,7 +1096,10 @@
       VariableDeclaration parameter, bool useNewMethodInvocationEncoding);
 
   @override
-  DartType get type => _type;
+  DartType get type {
+    assert(_type != null, "Type has not been computed for field $name.");
+    return _type!;
+  }
 
   @override
   void set type(DartType value) {
@@ -1100,9 +1110,9 @@
       _field.type = value.withDeclaredNullability(Nullability.nullable);
       _lateGetter.function.returnType = value;
       if (_lateSetter != null) {
-        _lateSetter.function.positionalParameters.single.type = value;
+        _lateSetter!.function.positionalParameters.single.type = value;
       }
-      if (!_type.isPotentiallyNullable && !_forceIncludeIsSetField) {
+      if (!_type!.isPotentiallyNullable && !_forceIncludeIsSetField) {
         // We only need the is-set field if the field is potentially nullable.
         //  Otherwise we use `null` to signal that the field is uninitialized.
         _lateIsSetField = null;
@@ -1113,10 +1123,8 @@
   @override
   void setGenericCovariantImpl() {
     _field.isGenericCovariantImpl = true;
-    if (_lateSetter != null) {
-      _lateSetter.function.positionalParameters.single.isGenericCovariantImpl =
-          true;
-    }
+    _lateSetter?.function.positionalParameters.single.isGenericCovariantImpl =
+        true;
   }
 
   @override
@@ -1126,7 +1134,7 @@
   Iterable<Annotatable> get annotatables {
     List<Annotatable> list = [_lateGetter];
     if (_lateSetter != null) {
-      list.add(_lateSetter);
+      list.add(_lateSetter!);
     }
     return list;
   }
@@ -1135,12 +1143,12 @@
   Member get readTarget => _lateGetter;
 
   @override
-  Member get writeTarget => _lateSetter;
+  Member? get writeTarget => _lateSetter;
 
   @override
   Iterable<Member> get exportedMembers {
     if (_lateSetter != null) {
-      return [_lateGetter, _lateSetter];
+      return [_lateGetter, _lateSetter!];
     }
     return [_lateGetter];
   }
@@ -1163,21 +1171,21 @@
     }
     updatePrivateMemberName(_field, libraryBuilder);
     if (_lateIsSetField != null) {
-      _lateIsSetField
+      _lateIsSetField!
         ..isStatic = !isInstanceMember
         ..isStatic = _field.isStatic
         ..isExtensionMember = isExtensionMember;
-      updatePrivateMemberName(_lateIsSetField, libraryBuilder);
+      updatePrivateMemberName(_lateIsSetField!, libraryBuilder);
     }
     _lateGetter
       ..isStatic = !isInstanceMember
       ..isExtensionMember = isExtensionMember;
     updatePrivateMemberName(_lateGetter, libraryBuilder);
     if (_lateSetter != null) {
-      _lateSetter
+      _lateSetter!
         ..isStatic = !isInstanceMember
         ..isExtensionMember = isExtensionMember;
-      updatePrivateMemberName(_lateSetter, libraryBuilder);
+      updatePrivateMemberName(_lateSetter!, libraryBuilder);
     }
   }
 
@@ -1193,11 +1201,11 @@
             : BuiltMemberKind.Field);
     if (_lateIsSetField != null) {
       _forceIncludeIsSetField = true;
-      f(_lateIsSetField, BuiltMemberKind.LateIsSetField);
+      f(_lateIsSetField!, BuiltMemberKind.LateIsSetField);
     }
     f(_lateGetter, BuiltMemberKind.LateGetter);
     if (_lateSetter != null) {
-      f(_lateSetter, BuiltMemberKind.LateSetter);
+      f(_lateSetter!, BuiltMemberKind.LateSetter);
     }
   }
 
@@ -1213,7 +1221,7 @@
     ];
     if (_lateIsSetField != null) {
       list.add(new _SynthesizedFieldClassMember(
-          fieldBuilder, _lateIsSetField, _SynthesizedFieldMemberKind.LateIsSet,
+          fieldBuilder, _lateIsSetField!, _SynthesizedFieldMemberKind.LateIsSet,
           isInternalImplementation: true));
     }
     return list;
@@ -1228,11 +1236,11 @@
     ];
     if (_lateIsSetField != null) {
       list.add(new _SynthesizedFieldClassMember(
-          fieldBuilder, _lateIsSetField, _SynthesizedFieldMemberKind.LateIsSet,
+          fieldBuilder, _lateIsSetField!, _SynthesizedFieldMemberKind.LateIsSet,
           forSetter: true, isInternalImplementation: true));
     }
     if (_lateSetter != null) {
-      list.add(new _SynthesizedFieldClassMember(fieldBuilder, _lateSetter,
+      list.add(new _SynthesizedFieldClassMember(fieldBuilder, _lateSetter!,
           _SynthesizedFieldMemberKind.LateGetterSetter,
           forSetter: true, isInternalImplementation: false));
     }
@@ -1249,12 +1257,12 @@
       VariableDeclaration parameter, bool useNewMethodInvocationEncoding) {
     assert(_type != null, "Type has not been computed for field $name.");
     return late_lowering.createSetterBody(
-        coreTypes, fileOffset, name, parameter, _type,
+        coreTypes, fileOffset, name, parameter, _type!,
         shouldReturnValue: false,
         createVariableWrite: (Expression value) =>
             _createFieldSet(_field, value, useNewMethodInvocationEncoding),
         createIsSetWrite: (Expression value) => _createFieldSet(
-            _lateIsSetField, value, useNewMethodInvocationEncoding),
+            _lateIsSetField!, value, useNewMethodInvocationEncoding),
         isSetEncoding: isSetEncoding);
   }
 }
@@ -1262,13 +1270,13 @@
 mixin LateWithoutInitializer on AbstractLateFieldEncoding {
   @override
   Statement _createGetterBody(CoreTypes coreTypes, String name,
-      Expression initializer, bool useNewMethodInvocationEncoding) {
+      Expression? initializer, bool useNewMethodInvocationEncoding) {
     assert(_type != null, "Type has not been computed for field $name.");
     return late_lowering.createGetterBodyWithoutInitializer(
         coreTypes, fileOffset, name, type, useNewMethodInvocationEncoding,
         createVariableRead: _createFieldRead,
         createIsSetRead: () =>
-            _createFieldGet(_lateIsSetField, useNewMethodInvocationEncoding),
+            _createFieldGet(_lateIsSetField!, useNewMethodInvocationEncoding),
         isSetEncoding: isSetEncoding,
         forField: true);
   }
@@ -1282,12 +1290,12 @@
       Uri fileUri,
       int charOffset,
       int charEndOffset,
-      Reference fieldGetterReference,
-      Reference fieldSetterReference,
-      Reference lateIsSetGetterReference,
-      Reference lateIsSetSetterReference,
-      Reference lateGetterReference,
-      Reference lateSetterReference,
+      Reference? fieldGetterReference,
+      Reference? fieldSetterReference,
+      Reference? lateIsSetGetterReference,
+      Reference? lateIsSetSetterReference,
+      Reference? lateGetterReference,
+      Reference? lateSetterReference,
       bool isCovariant,
       late_lowering.IsSetStrategy isSetStrategy)
       : super(
@@ -1314,12 +1322,12 @@
       Uri fileUri,
       int charOffset,
       int charEndOffset,
-      Reference fieldGetterReference,
-      Reference fieldSetterReference,
-      Reference lateIsSetGetterReference,
-      Reference lateIsSetSetterReference,
-      Reference lateGetterReference,
-      Reference lateSetterReference,
+      Reference? fieldGetterReference,
+      Reference? fieldSetterReference,
+      Reference? lateIsSetGetterReference,
+      Reference? lateIsSetSetterReference,
+      Reference? lateGetterReference,
+      Reference? lateSetterReference,
       bool isCovariant,
       late_lowering.IsSetStrategy isSetStrategy)
       : super(
@@ -1339,17 +1347,17 @@
 
   @override
   Statement _createGetterBody(CoreTypes coreTypes, String name,
-      Expression initializer, bool useNewMethodInvocationEncoding) {
+      Expression? initializer, bool useNewMethodInvocationEncoding) {
     assert(_type != null, "Type has not been computed for field $name.");
     return late_lowering.createGetterWithInitializer(coreTypes, fileOffset,
-        name, _type, initializer, useNewMethodInvocationEncoding,
+        name, _type!, initializer!, useNewMethodInvocationEncoding,
         createVariableRead: _createFieldRead,
         createVariableWrite: (Expression value) =>
             _createFieldSet(_field, value, useNewMethodInvocationEncoding),
         createIsSetRead: () =>
-            _createFieldGet(_lateIsSetField, useNewMethodInvocationEncoding),
+            _createFieldGet(_lateIsSetField!, useNewMethodInvocationEncoding),
         createIsSetWrite: (Expression value) => _createFieldSet(
-            _lateIsSetField, value, useNewMethodInvocationEncoding),
+            _lateIsSetField!, value, useNewMethodInvocationEncoding),
         isSetEncoding: isSetEncoding);
   }
 }
@@ -1362,12 +1370,12 @@
       Uri fileUri,
       int charOffset,
       int charEndOffset,
-      Reference fieldGetterReference,
-      Reference fieldSetterReference,
-      Reference lateIsSetGetterReference,
-      Reference lateIsSetSetterReference,
-      Reference lateGetterReference,
-      Reference lateSetterReference,
+      Reference? fieldGetterReference,
+      Reference? fieldSetterReference,
+      Reference? lateIsSetGetterReference,
+      Reference? lateIsSetSetterReference,
+      Reference? lateGetterReference,
+      Reference? lateSetterReference,
       bool isCovariant,
       late_lowering.IsSetStrategy isSetStrategy)
       : super(
@@ -1397,9 +1405,9 @@
         createVariableWrite: (Expression value) =>
             _createFieldSet(_field, value, useNewMethodInvocationEncoding),
         createIsSetRead: () =>
-            _createFieldGet(_lateIsSetField, useNewMethodInvocationEncoding),
+            _createFieldGet(_lateIsSetField!, useNewMethodInvocationEncoding),
         createIsSetWrite: (Expression value) => _createFieldSet(
-            _lateIsSetField, value, useNewMethodInvocationEncoding),
+            _lateIsSetField!, value, useNewMethodInvocationEncoding),
         isSetEncoding: isSetEncoding,
         forField: true);
   }
@@ -1412,12 +1420,12 @@
       Uri fileUri,
       int charOffset,
       int charEndOffset,
-      Reference fieldGetterReference,
-      Reference fieldSetterReference,
-      Reference lateIsSetGetterReference,
-      Reference lateIsSetSetterReference,
-      Reference lateGetterReference,
-      Reference lateSetterReference,
+      Reference? fieldGetterReference,
+      Reference? fieldSetterReference,
+      Reference? lateIsSetGetterReference,
+      Reference? lateIsSetSetterReference,
+      Reference? lateGetterReference,
+      Reference? lateSetterReference,
       bool isCovariant,
       late_lowering.IsSetStrategy isSetStrategy)
       : super(
@@ -1436,31 +1444,32 @@
             isSetStrategy);
   @override
   Statement _createGetterBody(CoreTypes coreTypes, String name,
-      Expression initializer, bool useNewMethodInvocationEncoding) {
+      Expression? initializer, bool useNewMethodInvocationEncoding) {
     assert(_type != null, "Type has not been computed for field $name.");
     return late_lowering.createGetterWithInitializerWithRecheck(coreTypes,
-        fileOffset, name, _type, initializer, useNewMethodInvocationEncoding,
+        fileOffset, name, _type!, initializer!, useNewMethodInvocationEncoding,
         createVariableRead: _createFieldRead,
         createVariableWrite: (Expression value) =>
             _createFieldSet(_field, value, useNewMethodInvocationEncoding),
         createIsSetRead: () =>
-            _createFieldGet(_lateIsSetField, useNewMethodInvocationEncoding),
+            _createFieldGet(_lateIsSetField!, useNewMethodInvocationEncoding),
         createIsSetWrite: (Expression value) => _createFieldSet(
-            _lateIsSetField, value, useNewMethodInvocationEncoding),
+            _lateIsSetField!, value, useNewMethodInvocationEncoding),
         isSetEncoding: isSetEncoding,
         forField: true);
   }
 
   @override
-  Procedure _createSetter(
-          Name name, Uri fileUri, int charOffset, Reference reference,
-          {bool isCovariant}) =>
+  Procedure? _createSetter(
+          Name name, Uri fileUri, int charOffset, Reference? reference,
+          {required bool isCovariant}) =>
       null;
 
   @override
   Statement _createSetterBody(CoreTypes coreTypes, String name,
           VariableDeclaration parameter, bool useNewMethodInvocationEncoding) =>
-      null;
+      throw new UnsupportedError(
+          '$runtimeType._createSetterBody is not supported.');
 }
 
 class _SynthesizedFieldClassMember implements ClassMember {
@@ -1469,7 +1478,7 @@
 
   final Member _member;
 
-  Covariance _covariance;
+  Covariance? _covariance;
 
   @override
   final bool forSetter;
@@ -1478,7 +1487,8 @@
   final bool isInternalImplementation;
 
   _SynthesizedFieldClassMember(this.fieldBuilder, this._member, this._kind,
-      {this.forSetter: false, this.isInternalImplementation})
+      {this.forSetter: false, required this.isInternalImplementation})
+      // ignore: unnecessary_null_comparison
       : assert(isInternalImplementation != null);
 
   Member getMember(ClassHierarchyBuilder hierarchy) {
@@ -1509,7 +1519,7 @@
   bool get isProperty => isField || isGetter || isSetter;
 
   @override
-  ClassBuilder get classBuilder => fieldBuilder.classBuilder;
+  ClassBuilder get classBuilder => fieldBuilder.classBuilder!;
 
   @override
   bool isObjectMember(ClassBuilder objectClass) {
@@ -1561,7 +1571,8 @@
   @override
   String get fullName {
     String suffix = isSetter ? "=" : "";
-    String className = classBuilder?.fullNameForErrors;
+    String className = classBuilder.fullNameForErrors;
+    // ignore: unnecessary_null_comparison
     return className == null
         ? "${fullNameForErrors}$suffix"
         : "${className}.${fullNameForErrors}$suffix";
@@ -1609,8 +1620,8 @@
   final bool isAbstract;
   final bool isExternal;
 
-  Procedure _getter;
-  Procedure _setter;
+  late Procedure _getter;
+  Procedure? _setter;
 
   AbstractOrExternalFieldEncoding(
       String name,
@@ -1618,17 +1629,22 @@
       Uri fileUri,
       int charOffset,
       int charEndOffset,
-      Reference getterReference,
-      Reference setterReference,
-      {this.isAbstract,
-      this.isExternal,
-      bool isFinal,
-      bool isCovariant,
-      bool isNonNullableByDefault})
+      Reference? getterReference,
+      Reference? setterReference,
+      {required this.isAbstract,
+      required this.isExternal,
+      required bool isFinal,
+      required bool isCovariant,
+      required bool isNonNullableByDefault})
+      // ignore: unnecessary_null_comparison
       : assert(isAbstract != null),
+        // ignore: unnecessary_null_comparison
         assert(isExternal != null),
+        // ignore: unnecessary_null_comparison
         assert(isFinal != null),
+        // ignore: unnecessary_null_comparison
         assert(isCovariant != null),
+        // ignore: unnecessary_null_comparison
         assert(isNonNullableByDefault != null) {
     _getter = new Procedure(
         fieldNameScheme.getName(FieldNameType.Getter, name,
@@ -1667,23 +1683,21 @@
   @override
   void set type(DartType value) {
     _getter.function.returnType = value;
-    if (_setter != null) {
-      _setter.function.positionalParameters.first.type = value;
-    }
+    _setter?.function.positionalParameters.first.type = value;
   }
 
   @override
   void completeSignature(CoreTypes coreTypes) {}
 
   @override
-  void createBodies(CoreTypes coreTypes, Expression initializer,
+  void createBodies(CoreTypes coreTypes, Expression? initializer,
       bool useNewMethodInvocationEncoding) {
     //assert(initializer != null);
   }
 
   @override
   List<Initializer> createInitializer(int fileOffset, Expression value,
-      {bool isSynthetic}) {
+      {required bool isSynthetic}) {
     throw new UnsupportedError('ExternalFieldEncoding.createInitializer');
   }
 
@@ -1703,12 +1717,12 @@
     updatePrivateMemberName(_getter, libraryBuilder);
 
     if (_setter != null) {
-      _setter
+      _setter!
         ..isStatic = !isInstanceMember
         ..isExtensionMember = isExtensionMember
         ..isAbstract = isAbstract && !isExternal
         ..isExternal = isExternal;
-      updatePrivateMemberName(_setter, libraryBuilder);
+      updatePrivateMemberName(_setter!, libraryBuilder);
     }
   }
 
@@ -1724,7 +1738,7 @@
             : BuiltMemberKind.Method);
     if (_setter != null) {
       f(
-          _setter,
+          _setter!,
           fieldBuilder.isExtensionMember
               ? BuiltMemberKind.ExtensionSetter
               : BuiltMemberKind.Method);
@@ -1733,7 +1747,7 @@
 
   @override
   void setGenericCovariantImpl() {
-    _setter.function.positionalParameters.first.isGenericCovariantImpl = true;
+    _setter!.function.positionalParameters.first.isGenericCovariantImpl = true;
   }
 
   @override
@@ -1745,7 +1759,7 @@
   Iterable<Annotatable> get annotatables {
     List<Annotatable> list = [_getter];
     if (_setter != null) {
-      list.add(_setter);
+      list.add(_setter!);
     }
     return list;
   }
@@ -1754,12 +1768,12 @@
   Member get readTarget => _getter;
 
   @override
-  Member get writeTarget => _setter;
+  Member? get writeTarget => _setter;
 
   @override
   Iterable<Member> get exportedMembers {
     if (_setter != null) {
-      return [_getter, _setter];
+      return [_getter, _setter!];
     }
     return [_getter];
   }
@@ -1776,7 +1790,7 @@
   List<ClassMember> getLocalSetters(SourceFieldBuilder fieldBuilder) =>
       _setter != null
           ? <ClassMember>[
-              new _SynthesizedFieldClassMember(fieldBuilder, _setter,
+              new _SynthesizedFieldClassMember(fieldBuilder, _setter!,
                   _SynthesizedFieldMemberKind.AbstractExternalGetterSetter,
                   forSetter: true, isInternalImplementation: false)
             ]
diff --git a/pkg/front_end/lib/src/fasta/builder/fixed_type_builder.dart b/pkg/front_end/lib/src/fasta/builder/fixed_type_builder.dart
index d405be6..d9894e4 100644
--- a/pkg/front_end/lib/src/fasta/builder/fixed_type_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/fixed_type_builder.dart
@@ -2,8 +2,6 @@
 // for 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 'package:kernel/ast.dart';
 
 import '../problems.dart';
@@ -26,7 +24,7 @@
     return this;
   }
 
-  Object get name => null;
+  Object? get name => null;
 
   NullabilityBuilder get nullabilityBuilder =>
       new NullabilityBuilder.fromNullability(type.nullability);
@@ -41,7 +39,7 @@
   }
 
   DartType build(LibraryBuilder library,
-      [TypedefType origin, bool notInstanceContext]) {
+      {TypedefType? origin, bool? nonInstanceContext}) {
     return type;
   }
 
diff --git a/pkg/front_end/lib/src/fasta/builder/formal_parameter_builder.dart b/pkg/front_end/lib/src/fasta/builder/formal_parameter_builder.dart
index 306222e..c1c89d3 100644
--- a/pkg/front_end/lib/src/fasta/builder/formal_parameter_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/formal_parameter_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.formal_parameter_builder;
 
 import 'package:_fe_analyzer_shared/src/parser/formal_parameter_kind.dart'
@@ -54,26 +52,29 @@
 class FormalParameterBuilder extends ModifierBuilderImpl
     implements VariableBuilder {
   /// List of metadata builders for the metadata declared on this parameter.
-  final List<MetadataBuilder> metadata;
+  final List<MetadataBuilder>? metadata;
 
   final int modifiers;
 
-  final TypeBuilder type;
+  final TypeBuilder? type;
 
   final String name;
 
+  @override
+  final Uri? fileUri;
+
   /// The kind of this parameter, i.e. if it's required, positional optional,
   /// or named optional.
   FormalParameterKind kind = FormalParameterKind.mandatory;
 
   /// The variable declaration created for this formal parameter.
-  VariableDeclaration variable;
+  VariableDeclaration? variable;
 
   /// The first token of the default value, if any.
   ///
   /// This is stored until outlines have been built through
   /// [buildOutlineExpressions].
-  Token initializerToken;
+  Token? initializerToken;
 
   bool initializerWasInferred = false;
 
@@ -83,9 +84,10 @@
   final bool isExtensionThis;
 
   FormalParameterBuilder(this.metadata, this.modifiers, this.type, this.name,
-      LibraryBuilder compilationUnit, int charOffset,
-      {Uri fileUri, this.isExtensionThis: false})
-      : super(compilationUnit, charOffset, fileUri);
+      LibraryBuilder? compilationUnit, int charOffset,
+      {Uri? fileUri, this.isExtensionThis: false})
+      : this.fileUri = fileUri ?? compilationUnit?.fileUri,
+        super(compilationUnit, charOffset);
 
   String get debugName => "FormalParameterBuilder";
 
@@ -114,16 +116,17 @@
   // An initializing formal parameter might be final without its
   // VariableDeclaration being final. See
   // [ProcedureBuilder.computeFormalParameterInitializerScope]..
-  bool get isAssignable => variable.isAssignable && !isInitializingFormal;
+  bool get isAssignable => variable!.isAssignable && !isInitializingFormal;
 
   @override
   String get fullNameForErrors => name;
 
   VariableDeclaration build(
       SourceLibraryBuilder library, int functionNestingLevel,
-      [bool notInstanceContext]) {
+      {bool? nonInstanceContext}) {
     if (variable == null) {
-      DartType builtType = type?.build(library, null, notInstanceContext);
+      DartType? builtType =
+          type?.build(library, nonInstanceContext: nonInstanceContext);
       if (!library.isNonNullableByDefault && builtType != null) {
         builtType = legacyErasure(builtType);
       }
@@ -138,7 +141,7 @@
           isLowered: isExtensionThis)
         ..fileOffset = charOffset;
     }
-    return variable;
+    return variable!;
   }
 
   FormalParameterBuilder clone(
@@ -152,7 +155,7 @@
         modifiers,
         type?.clone(newTypes, contextLibrary, contextDeclaration),
         name,
-        parent,
+        parent as LibraryBuilder?,
         charOffset,
         fileUri: fileUri,
         isExtensionThis: isExtensionThis)
@@ -160,6 +163,7 @@
   }
 
   FormalParameterBuilder forFormalParameterInitializerScope() {
+    // ignore: unnecessary_null_comparison
     assert(variable != null);
     return !isInitializingFormal
         ? this
@@ -177,18 +181,17 @@
   }
 
   void finalizeInitializingFormal(ClassBuilder classBuilder) {
-    assert(variable.type == null);
-    Builder fieldBuilder = classBuilder.lookupLocalMember(name);
+    Builder? fieldBuilder = classBuilder.lookupLocalMember(name);
     if (fieldBuilder is FieldBuilder) {
-      variable.type = fieldBuilder.inferType();
+      variable!.type = fieldBuilder.inferType();
     } else {
-      variable.type = const DynamicType();
+      variable!.type = const DynamicType();
     }
   }
 
   /// Builds the default value from this [initializerToken] if this is a
   /// formal parameter on a const constructor or instance method.
-  void buildOutlineExpressions(LibraryBuilder library,
+  void buildOutlineExpressions(SourceLibraryBuilder library,
       List<DelayedActionPerformer> delayedActionPerformers) {
     if (initializerToken != null) {
       // For modular compilation we need to include initializers for optional
@@ -198,27 +201,27 @@
       // be needed to generated noSuchMethod forwarders.
       bool isConstConstructorParameter = false;
       if (parent is ConstructorBuilder) {
-        isConstConstructorParameter = parent.isConst;
+        isConstConstructorParameter = parent!.isConst;
       } else if (parent is ProcedureBuilder) {
-        isConstConstructorParameter = parent.isFactory && parent.isConst;
+        isConstConstructorParameter = parent!.isFactory && parent!.isConst;
       }
-      if (isConstConstructorParameter || parent.isClassInstanceMember) {
-        final ClassBuilder classBuilder = parent.parent;
+      if (isConstConstructorParameter || parent!.isClassInstanceMember) {
+        final ClassBuilder classBuilder = parent!.parent as ClassBuilder;
         Scope scope = classBuilder.scope;
         BodyBuilder bodyBuilder = library.loader
             .createBodyBuilderForOutlineExpression(
-                library, classBuilder, this, scope, fileUri);
+                library, classBuilder, this, scope, fileUri!);
         bodyBuilder.constantContext = ConstantContext.required;
         assert(!initializerWasInferred);
         Expression initializer =
-            bodyBuilder.parseFieldInitializer(initializerToken);
-        initializer = bodyBuilder.typeInferrer?.inferParameterInitializer(
-            bodyBuilder, initializer, variable.type, hasDeclaredInitializer);
-        variable.initializer = initializer..parent = variable;
+            bodyBuilder.parseFieldInitializer(initializerToken!);
+        initializer = bodyBuilder.typeInferrer.inferParameterInitializer(
+            bodyBuilder, initializer, variable!.type, hasDeclaredInitializer);
+        variable!.initializer = initializer..parent = variable;
         if (library.loader is SourceLoader) {
           SourceLoader loader = library.loader;
           loader.transformPostInference(
-              variable,
+              variable!,
               bodyBuilder.transformSetLiterals,
               bodyBuilder.transformCollections,
               library.library);
diff --git a/pkg/front_end/lib/src/fasta/builder/function_builder.dart b/pkg/front_end/lib/src/fasta/builder/function_builder.dart
index 7d11b18..1fee4be 100644
--- a/pkg/front_end/lib/src/fasta/builder/function_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/function_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.procedure_builder;
 
 import 'package:front_end/src/fasta/kernel/kernel_api.dart';
@@ -52,17 +50,17 @@
 
 /// Common base class for constructor and procedure builders.
 abstract class FunctionBuilder implements MemberBuilder {
-  List<MetadataBuilder> get metadata;
+  List<MetadataBuilder>? get metadata;
 
-  TypeBuilder get returnType;
+  TypeBuilder? get returnType;
 
-  List<TypeVariableBuilder> get typeVariables;
+  List<TypeVariableBuilder>? get typeVariables;
 
-  List<FormalParameterBuilder> get formals;
+  List<FormalParameterBuilder>? get formals;
 
   AsyncMarker get asyncModifier;
 
-  ProcedureKind get kind;
+  ProcedureKind? get kind;
 
   bool get isAbstract;
 
@@ -89,17 +87,17 @@
   /// to support generic methods.
   Scope computeTypeParameterScope(Scope parent);
 
-  FormalParameterBuilder getFormal(Identifier identifier);
+  FormalParameterBuilder? getFormal(Identifier identifier);
 
-  String get nativeMethodName;
+  String? get nativeMethodName;
 
   FunctionNode get function;
 
-  FunctionBuilder get actualOrigin;
+  FunctionBuilder? get actualOrigin;
 
-  Statement get body;
+  Statement? get body;
 
-  void set body(Statement newBody);
+  void set body(Statement? newBody);
 
   void setRedirectingFactoryBody(Member target, List<DartType> typeArguments);
 
@@ -118,15 +116,15 @@
   ///
   /// This is used to update the default value for the closure parameter when
   /// it has been computed for the original parameter.
-  VariableDeclaration getExtensionTearOffParameter(int index);
+  VariableDeclaration? getExtensionTearOffParameter(int index);
 
   /// Returns the parameter for 'this' synthetically added to extension
   /// instance members.
-  VariableDeclaration get extensionThis;
+  VariableDeclaration? get extensionThis;
 
   /// Returns a list of synthetic type parameters added to extension instance
   /// members.
-  List<TypeParameter> get extensionTypeParameters;
+  List<TypeParameter>? get extensionTypeParameters;
 
   void becomeNative(Loader loader);
 
@@ -139,31 +137,31 @@
 abstract class FunctionBuilderImpl extends MemberBuilderImpl
     implements FunctionBuilder {
   @override
-  final List<MetadataBuilder> metadata;
+  final List<MetadataBuilder>? metadata;
 
   @override
   final int modifiers;
 
   @override
-  final TypeBuilder returnType;
+  final TypeBuilder? returnType;
 
   @override
   final String name;
 
   @override
-  final List<TypeVariableBuilder> typeVariables;
+  final List<TypeVariableBuilder>? typeVariables;
 
   @override
-  final List<FormalParameterBuilder> formals;
+  final List<FormalParameterBuilder>? formals;
 
   /// If this procedure is an extension instance member, [_extensionThis] holds
   /// the synthetically added `this` parameter.
-  VariableDeclaration _extensionThis;
+  VariableDeclaration? _extensionThis;
 
   /// If this procedure is an extension instance member,
   /// [_extensionTypeParameters] holds the type parameters copied from the
   /// extension declaration.
-  List<TypeParameter> _extensionTypeParameters;
+  List<TypeParameter>? _extensionTypeParameters;
 
   FunctionBuilderImpl(
       this.metadata,
@@ -177,8 +175,8 @@
       this.nativeMethodName)
       : super(compilationUnit, charOffset) {
     if (formals != null) {
-      for (int i = 0; i < formals.length; i++) {
-        formals[i].parent = this;
+      for (int i = 0; i < formals!.length; i++) {
+        formals![i].parent = this;
       }
     }
   }
@@ -220,7 +218,7 @@
   Scope computeFormalParameterScope(Scope parent) {
     if (formals == null) return parent;
     Map<String, Builder> local = <String, Builder>{};
-    for (FormalParameterBuilder formal in formals) {
+    for (FormalParameterBuilder formal in formals!) {
       if (!isConstructor || !formal.isInitializingFormal) {
         local[formal.name] = formal;
       }
@@ -251,7 +249,7 @@
 
     if (formals == null) return parent;
     Map<String, Builder> local = <String, Builder>{};
-    for (FormalParameterBuilder formal in formals) {
+    for (FormalParameterBuilder formal in formals!) {
       local[formal.name] = formal.forFormalParameterInitializerScope();
     }
     return new Scope(
@@ -265,7 +263,7 @@
   Scope computeTypeParameterScope(Scope parent) {
     if (typeVariables == null) return parent;
     Map<String, Builder> local = <String, Builder>{};
-    for (TypeVariableBuilder variable in typeVariables) {
+    for (TypeVariableBuilder variable in typeVariables!) {
       local[variable.name] = variable;
     }
     return new Scope(
@@ -276,9 +274,9 @@
   }
 
   @override
-  FormalParameterBuilder getFormal(Identifier identifier) {
+  FormalParameterBuilder? getFormal(Identifier identifier) {
     if (formals != null) {
-      for (FormalParameterBuilder formal in formals) {
+      for (FormalParameterBuilder formal in formals!) {
         if (formal.name == identifier.name &&
             formal.charOffset == identifier.charOffset) {
           return formal;
@@ -291,12 +289,12 @@
   }
 
   @override
-  final String nativeMethodName;
+  final String? nativeMethodName;
 
-  Statement bodyInternal;
+  Statement? bodyInternal;
 
   @override
-  void set body(Statement newBody) {
+  void set body(Statement? newBody) {
 //    if (newBody != null) {
 //      if (isAbstract) {
 //        // TODO(danrubel): Is this check needed?
@@ -309,7 +307,7 @@
     // but which needs to have a forwarding stub body in order to ensure that
     // covariance checks occur.  We don't want to replace the forwarding stub
     // body with null.
-    TreeNode parent = function.parent;
+    TreeNode? parent = function.parent;
     if (!(newBody == null &&
         parent is Procedure &&
         parent.isForwardingSemiStub)) {
@@ -327,12 +325,12 @@
     function.body = bodyInternal;
     bodyInternal?.parent = function;
     if (isPatch) {
-      actualOrigin.setRedirectingFactoryBody(target, typeArguments);
+      actualOrigin!.setRedirectingFactoryBody(target, typeArguments);
     }
   }
 
   @override
-  Statement get body => bodyInternal ??= new EmptyStatement();
+  Statement? get body => bodyInternal ??= new EmptyStatement();
 
   @override
   bool get isNative => nativeMethodName != null;
@@ -341,10 +339,9 @@
     function.asyncMarker = asyncModifier;
     function.body = body;
     body?.parent = function;
-    IncludesTypeParametersNonCovariantly needsCheckVisitor;
+    IncludesTypeParametersNonCovariantly? needsCheckVisitor;
     if (!isConstructor && !isFactory && parent is ClassBuilder) {
-      ClassBuilder enclosingClassBuilder = parent;
-      Class enclosingClass = enclosingClassBuilder.cls;
+      Class enclosingClass = classBuilder!.cls;
       if (enclosingClass.typeParameters.isNotEmpty) {
         needsCheckVisitor = new IncludesTypeParametersNonCovariantly(
             enclosingClass.typeParameters,
@@ -354,7 +351,7 @@
       }
     }
     if (typeVariables != null) {
-      for (TypeVariableBuilder t in typeVariables) {
+      for (TypeVariableBuilder t in typeVariables!) {
         TypeParameter parameter = t.parameter;
         function.typeParameters.add(parameter);
         if (needsCheckVisitor != null) {
@@ -366,9 +363,9 @@
       setParents(function.typeParameters, function);
     }
     if (formals != null) {
-      for (FormalParameterBuilder formal in formals) {
-        VariableDeclaration parameter = formal.build(
-            library, 0, !isConstructor && !isDeclarationInstanceMember);
+      for (FormalParameterBuilder formal in formals!) {
+        VariableDeclaration parameter = formal.build(library, 0,
+            nonInstanceContext: !isConstructor && !isDeclarationInstanceMember);
         if (needsCheckVisitor != null) {
           if (parameter.type.accept(needsCheckVisitor)) {
             parameter.isGenericCovariantImpl = true;
@@ -399,7 +396,7 @@
     }
     if (!isExtensionInstanceMember &&
         isSetter &&
-        (formals?.length != 1 || formals[0].isOptional)) {
+        (formals?.length != 1 || formals![0].isOptional)) {
       // Replace illegal parameters by single dummy parameter.
       // Do this after building the parameters, since the diet listener
       // assumes that parameters are built, even if illegal in number.
@@ -412,31 +409,31 @@
       function.requiredParameterCount = 1;
     }
     if (returnType != null) {
-      function.returnType = returnType.build(
-          library, null, !isConstructor && !isDeclarationInstanceMember);
+      function.returnType = returnType!.build(library,
+          nonInstanceContext: !isConstructor && !isDeclarationInstanceMember);
     }
     if (!isConstructor && !isDeclarationInstanceMember) {
-      List<TypeParameter> typeParameters;
+      List<TypeParameter>? typeParameters;
       if (parent is ClassBuilder) {
-        ClassBuilder enclosingClassBuilder = parent;
+        ClassBuilder enclosingClassBuilder = parent as ClassBuilder;
         typeParameters = enclosingClassBuilder.cls.typeParameters;
       } else if (parent is ExtensionBuilder) {
-        ExtensionBuilder enclosingExtensionBuilder = parent;
+        ExtensionBuilder enclosingExtensionBuilder = parent as ExtensionBuilder;
         typeParameters = enclosingExtensionBuilder.extension.typeParameters;
       }
 
       if (typeParameters != null && typeParameters.isNotEmpty) {
-        Map<TypeParameter, DartType> substitution;
+        Map<TypeParameter, DartType>? substitution;
         DartType removeTypeVariables(DartType type) {
           if (substitution == null) {
             substitution = <TypeParameter, DartType>{};
-            for (TypeParameter parameter in typeParameters) {
-              substitution[parameter] = const DynamicType();
+            for (TypeParameter parameter in typeParameters!) {
+              substitution![parameter] = const DynamicType();
             }
           }
           library.addProblem(
               messageNonInstanceTypeVariableUse, charOffset, noLength, fileUri);
-          return substitute(type, substitution);
+          return substitute(type, substitution!);
         }
 
         Set<TypeParameter> set = typeParameters.toSet();
@@ -456,14 +453,13 @@
       }
     }
     if (isExtensionInstanceMember) {
-      ExtensionBuilder extensionBuilder = parent;
+      ExtensionBuilder extensionBuilder = parent as ExtensionBuilder;
       _extensionThis = function.positionalParameters.first;
       if (extensionBuilder.typeParameters != null) {
-        int count = extensionBuilder.typeParameters.length;
-        _extensionTypeParameters = new List<TypeParameter>.filled(count, null);
-        for (int index = 0; index < count; index++) {
-          _extensionTypeParameters[index] = function.typeParameters[index];
-        }
+        int count = extensionBuilder.typeParameters!.length;
+        _extensionTypeParameters = new List<TypeParameter>.generate(
+            count, (int index) => function.typeParameters[index],
+            growable: false);
       }
     }
   }
@@ -471,24 +467,24 @@
   @override
   VariableDeclaration getFormalParameter(int index) {
     if (isExtensionInstanceMember) {
-      return formals[index + 1].variable;
+      return formals![index + 1].variable!;
     } else {
-      return formals[index].variable;
+      return formals![index].variable!;
     }
   }
 
   @override
-  VariableDeclaration getExtensionTearOffParameter(int index) => null;
+  VariableDeclaration? getExtensionTearOffParameter(int index) => null;
 
   @override
-  VariableDeclaration get extensionThis {
+  VariableDeclaration? get extensionThis {
     assert(_extensionThis != null || !isExtensionInstanceMember,
         "ProcedureBuilder.extensionThis has not been set.");
     return _extensionThis;
   }
 
   @override
-  List<TypeParameter> get extensionTypeParameters {
+  List<TypeParameter>? get extensionTypeParameters {
     // Use [_extensionThis] as marker for whether extension type parameters have
     // been computed.
     assert(_extensionThis != null || !isExtensionInstanceMember,
@@ -499,16 +495,20 @@
   bool _hasBuiltOutlineExpressions = false;
 
   @override
-  void buildOutlineExpressions(LibraryBuilder library, CoreTypes coreTypes,
+  void buildOutlineExpressions(
+      SourceLibraryBuilder library,
+      CoreTypes coreTypes,
       List<DelayedActionPerformer> delayedActionPerformers) {
     if (!_hasBuiltOutlineExpressions) {
-      DeclarationBuilder classOrExtensionBuilder =
-          isClassMember || isExtensionMember ? parent : null;
+      DeclarationBuilder? classOrExtensionBuilder =
+          isClassMember || isExtensionMember
+              ? parent as DeclarationBuilder
+              : null;
       MetadataBuilder.buildAnnotations(
           member, metadata, library, classOrExtensionBuilder, this, fileUri);
       if (typeVariables != null) {
-        for (int i = 0; i < typeVariables.length; i++) {
-          typeVariables[i].buildOutlineExpressions(
+        for (int i = 0; i < typeVariables!.length; i++) {
+          typeVariables![i].buildOutlineExpressions(
               library,
               classOrExtensionBuilder,
               this,
@@ -522,7 +522,7 @@
         // into the outline. For all other formals we need to call
         // buildOutlineExpressions to clear initializerToken to prevent
         // consuming too much memory.
-        for (FormalParameterBuilder formal in formals) {
+        for (FormalParameterBuilder formal in formals!) {
           formal.buildOutlineExpressions(library, delayedActionPerformers);
         }
       }
@@ -536,14 +536,16 @@
   void becomeNative(Loader loader) {
     MemberBuilder constructor = loader.getNativeAnnotation();
     Arguments arguments =
-        new Arguments(<Expression>[new StringLiteral(nativeMethodName)]);
+        new Arguments(<Expression>[new StringLiteral(nativeMethodName!)]);
     Expression annotation;
     if (constructor.isConstructor) {
-      annotation = new ConstructorInvocation(constructor.member, arguments)
+      annotation = new ConstructorInvocation(
+          constructor.member as Constructor, arguments)
         ..isConst = true;
     } else {
-      annotation = new StaticInvocation(constructor.member, arguments)
-        ..isConst = true;
+      annotation =
+          new StaticInvocation(constructor.member as Procedure, arguments)
+            ..isConst = true;
     }
     member.addAnnotation(annotation);
   }
@@ -552,7 +554,7 @@
   bool checkPatch(FunctionBuilder patch) {
     if (!isExternal) {
       patch.library.addProblem(
-          messagePatchNonExternal, patch.charOffset, noLength, patch.fileUri,
+          messagePatchNonExternal, patch.charOffset, noLength, patch.fileUri!,
           context: [
             messagePatchDeclarationOrigin.withLocation(
                 fileUri, charOffset, noLength)
@@ -565,7 +567,7 @@
   @override
   void reportPatchMismatch(Builder patch) {
     library.addProblem(messagePatchDeclarationMismatch, patch.charOffset,
-        noLength, patch.fileUri, context: [
+        noLength, patch.fileUri!, context: [
       messagePatchDeclarationOrigin.withLocation(fileUri, charOffset, noLength)
     ]);
   }
diff --git a/pkg/front_end/lib/src/fasta/builder/function_type_builder.dart b/pkg/front_end/lib/src/fasta/builder/function_type_builder.dart
index 2204d0d..54d2a6a 100644
--- a/pkg/front_end/lib/src/fasta/builder/function_type_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/function_type_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.function_type_builder;
 
 import 'package:kernel/ast.dart'
@@ -27,18 +25,18 @@
 import 'type_variable_builder.dart';
 
 class FunctionTypeBuilder extends TypeBuilder {
-  final TypeBuilder returnType;
-  final List<TypeVariableBuilder> typeVariables;
-  final List<FormalParameterBuilder> formals;
+  final TypeBuilder? returnType;
+  final List<TypeVariableBuilder>? typeVariables;
+  final List<FormalParameterBuilder>? formals;
   final NullabilityBuilder nullabilityBuilder;
-  final Uri fileUri;
+  final Uri? fileUri;
   final int charOffset;
 
   FunctionTypeBuilder(this.returnType, this.typeVariables, this.formals,
       this.nullabilityBuilder, this.fileUri, this.charOffset);
 
   @override
-  String get name => null;
+  String? get name => null;
 
   @override
   String get debugName => "Function";
@@ -50,7 +48,7 @@
     if (typeVariables != null) {
       buffer.write("<");
       bool isFirst = true;
-      for (TypeVariableBuilder t in typeVariables) {
+      for (TypeVariableBuilder t in typeVariables!) {
         if (!isFirst) {
           buffer.write(", ");
         } else {
@@ -63,7 +61,7 @@
     buffer.write("(");
     if (formals != null) {
       bool isFirst = true;
-      for (FormalParameterBuilder t in formals) {
+      for (FormalParameterBuilder t in formals!) {
         if (!isFirst) {
           buffer.write(", ");
         } else {
@@ -80,16 +78,17 @@
   }
 
   FunctionType build(LibraryBuilder library,
-      [TypedefType origin, bool notInstanceContext]) {
+      {TypedefType? origin, bool? nonInstanceContext}) {
     DartType builtReturnType =
-        returnType?.build(library, null, notInstanceContext) ??
+        returnType?.build(library, nonInstanceContext: nonInstanceContext) ??
             const DynamicType();
     List<DartType> positionalParameters = <DartType>[];
-    List<NamedType> namedParameters;
+    List<NamedType>? namedParameters;
     int requiredParameterCount = 0;
     if (formals != null) {
-      for (FormalParameterBuilder formal in formals) {
-        DartType type = formal.type?.build(library, null, notInstanceContext) ??
+      for (FormalParameterBuilder formal in formals!) {
+        DartType type = formal.type
+                ?.build(library, nonInstanceContext: nonInstanceContext) ??
             const DynamicType();
         if (formal.isPositional) {
           positionalParameters.add(type);
@@ -104,13 +103,13 @@
         namedParameters.sort();
       }
     }
-    List<TypeParameter> typeParameters;
+    List<TypeParameter>? typeParameters;
     if (typeVariables != null) {
       typeParameters = <TypeParameter>[];
-      for (TypeVariableBuilder t in typeVariables) {
+      for (TypeVariableBuilder t in typeVariables!) {
         typeParameters.add(t.parameter);
         // Build the bound to detect cycles in typedefs.
-        t.bound?.build(library, origin);
+        t.bound?.build(library, origin: origin);
       }
     }
     return new FunctionType(positionalParameters, builtReturnType,
@@ -121,14 +120,14 @@
         typedefType: origin);
   }
 
-  Supertype buildSupertype(
+  Supertype? buildSupertype(
       LibraryBuilder library, int charOffset, Uri fileUri) {
     library.addProblem(
         messageSupertypeIsFunction, charOffset, noLength, fileUri);
     return null;
   }
 
-  Supertype buildMixedInType(
+  Supertype? buildMixedInType(
       LibraryBuilder library, int charOffset, Uri fileUri) {
     return buildSupertype(library, charOffset, fileUri);
   }
@@ -137,20 +136,18 @@
       List<TypeBuilder> newTypes,
       SourceLibraryBuilder contextLibrary,
       TypeParameterScopeBuilder contextDeclaration) {
-    List<TypeVariableBuilder> clonedTypeVariables;
+    List<TypeVariableBuilder>? clonedTypeVariables;
     if (typeVariables != null) {
       clonedTypeVariables =
-          contextLibrary.copyTypeVariables(typeVariables, contextDeclaration);
+          contextLibrary.copyTypeVariables(typeVariables!, contextDeclaration);
     }
-    List<FormalParameterBuilder> clonedFormals;
+    List<FormalParameterBuilder>? clonedFormals;
     if (formals != null) {
       clonedFormals =
-          new List<FormalParameterBuilder>.filled(formals.length, null);
-      for (int i = 0; i < clonedFormals.length; i++) {
-        FormalParameterBuilder formal = formals[i];
-        clonedFormals[i] =
-            formal.clone(newTypes, contextLibrary, contextDeclaration);
-      }
+          new List<FormalParameterBuilder>.generate(formals!.length, (int i) {
+        FormalParameterBuilder formal = formals![i];
+        return formal.clone(newTypes, contextLibrary, contextDeclaration);
+      }, growable: false);
     }
     FunctionTypeBuilder newType = new FunctionTypeBuilder(
         returnType?.clone(newTypes, contextLibrary, contextDeclaration),
diff --git a/pkg/front_end/lib/src/fasta/builder/future_or_type_declaration_builder.dart b/pkg/front_end/lib/src/fasta/builder/future_or_type_declaration_builder.dart
index 3e3e050..a54a5b3 100644
--- a/pkg/front_end/lib/src/fasta/builder/future_or_type_declaration_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/future_or_type_declaration_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.future_or_type_builder;
 
 import 'package:kernel/ast.dart' show DartType, FutureOrType, Nullability;
@@ -21,10 +19,11 @@
   String get debugName => "FutureOrTypeDeclarationBuilder";
 
   DartType buildType(LibraryBuilder library,
-      NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments,
-      [bool notInstanceContext]) {
+      NullabilityBuilder nullabilityBuilder, List<TypeBuilder>? arguments,
+      {bool? nonInstanceContext}) {
     return new FutureOrType(
-        arguments.single.build(library, null, notInstanceContext),
+        arguments!.single
+            .build(library, nonInstanceContext: nonInstanceContext),
         nullabilityBuilder.build(library));
   }
 
diff --git a/pkg/front_end/lib/src/fasta/builder/invalid_type_declaration_builder.dart b/pkg/front_end/lib/src/fasta/builder/invalid_type_declaration_builder.dart
index bce176c5..7226d05 100644
--- a/pkg/front_end/lib/src/fasta/builder/invalid_type_declaration_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/invalid_type_declaration_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.invalid_type_builder;
 
 import 'package:kernel/ast.dart' show DartType, InvalidType, Nullability;
@@ -22,23 +20,28 @@
 
   final LocatedMessage message;
 
-  final List<LocatedMessage> context;
+  final List<LocatedMessage>? context;
 
   final bool suppressMessage;
 
   InvalidTypeDeclarationBuilder(String name, this.message,
       {this.context, this.suppressMessage: true})
-      : super(null, 0, name, null, message.charOffset, message.uri);
+      : super(null, 0, name, null, message.charOffset);
 
+  @override
+  Uri? get fileUri => message.uri;
+
+  @override
   DartType buildType(LibraryBuilder library,
-      NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments,
-      [bool notInstanceContext]) {
+      NullabilityBuilder nullabilityBuilder, List<TypeBuilder>? arguments,
+      {bool? nonInstanceContext}) {
     return buildTypesWithBuiltArguments(library, null, null);
   }
 
   /// [Arguments] have already been built.
+  @override
   DartType buildTypesWithBuiltArguments(LibraryBuilder library,
-      Nullability nullability, List<DartType> arguments) {
+      Nullability? nullability, List<DartType>? arguments) {
     if (!suppressMessage) {
       library.addProblem(message.messageObject, message.charOffset,
           message.length, message.uri,
diff --git a/pkg/front_end/lib/src/fasta/builder/library_builder.dart b/pkg/front_end/lib/src/fasta/builder/library_builder.dart
index ec8fad3..2c6badc0 100644
--- a/pkg/front_end/lib/src/fasta/builder/library_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/library_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.library_builder;
 
 import 'package:_fe_analyzer_shared/src/messages/severity.dart' show Severity;
@@ -51,11 +49,11 @@
 
   List<Export> get exporters;
 
-  LibraryBuilder partOfLibrary;
+  abstract LibraryBuilder? partOfLibrary;
 
   LibraryBuilder get nameOriginBuilder;
 
-  bool mayImplementRestrictedTypes;
+  abstract bool mayImplementRestrictedTypes;
 
   bool get isPart;
 
@@ -64,6 +62,9 @@
   /// Returns the [Library] built by this builder.
   Library get library;
 
+  @override
+  Uri get fileUri;
+
   /// Returns the import uri for the library.
   ///
   /// This is the canonical uri for the library, for instance 'dart:core'.
@@ -73,10 +74,10 @@
 
   NameIterator get nameIterator;
 
-  Builder addBuilder(String name, Builder declaration, int charOffset);
+  Builder? addBuilder(String? name, Builder declaration, int charOffset);
 
   void addExporter(
-      LibraryBuilder exporter, List<Combinator> combinators, int charOffset);
+      LibraryBuilder exporter, List<Combinator>? combinators, int charOffset);
 
   /// Add a problem with a severity determined by the severity of the message.
   ///
@@ -84,11 +85,11 @@
   ///
   /// See `Loader.addMessage` for an explanation of the
   /// arguments passed to this method.
-  FormattedMessage addProblem(
-      Message message, int charOffset, int length, Uri fileUri,
+  FormattedMessage? addProblem(
+      Message message, int charOffset, int length, Uri? fileUri,
       {bool wasHandled: false,
-      List<LocatedMessage> context,
-      Severity severity,
+      List<LocatedMessage>? context,
+      Severity? severity,
       bool problemOnLibrary: false});
 
   /// Returns true if the export scope was modified.
@@ -150,9 +151,9 @@
   ///
   /// If [required] is `true` and no member is found an internal problem is
   /// reported.
-  Builder lookupLocalMember(String name, {bool required: false});
+  Builder? lookupLocalMember(String name, {bool required: false});
 
-  Builder lookup(String name, int charOffset, Uri fileUri);
+  Builder? lookup(String name, int charOffset, Uri fileUri);
 
   /// If this is a patch library, apply its patches to [origin].
   void applyPatches();
@@ -161,7 +162,7 @@
 
   void buildOutlineExpressions();
 
-  List<FieldBuilder> takeImplicitlyTypedFields();
+  List<FieldBuilder>? takeImplicitlyTypedFields();
 
   bool get isNonNullableByDefault;
 
@@ -196,21 +197,24 @@
   final List<Export> exporters = <Export>[];
 
   @override
-  LibraryBuilder partOfLibrary;
+  final Uri fileUri;
+
+  @override
+  LibraryBuilder? partOfLibrary;
 
   @override
   bool mayImplementRestrictedTypes = false;
 
-  LibraryBuilderImpl(Uri fileUri, this.scope, this.exportScope)
+  LibraryBuilderImpl(this.fileUri, this.scope, this.exportScope)
       : scopeBuilder = new ScopeBuilder(scope),
         exportScopeBuilder = new ScopeBuilder(exportScope),
-        super(null, -1, fileUri);
+        super(null, -1);
 
   @override
   bool get isSynthetic => false;
 
   @override
-  Builder get parent => null;
+  Builder? get parent => null;
 
   @override
   bool get isPart => false;
@@ -239,16 +243,16 @@
 
   @override
   void addExporter(
-      LibraryBuilder exporter, List<Combinator> combinators, int charOffset) {
+      LibraryBuilder exporter, List<Combinator>? combinators, int charOffset) {
     exporters.add(new Export(exporter, this, combinators, charOffset));
   }
 
   @override
-  FormattedMessage addProblem(
-      Message message, int charOffset, int length, Uri fileUri,
+  FormattedMessage? addProblem(
+      Message message, int charOffset, int length, Uri? fileUri,
       {bool wasHandled: false,
-      List<LocatedMessage> context,
-      Severity severity,
+      List<LocatedMessage>? context,
+      Severity? severity,
       bool problemOnLibrary: false}) {
     fileUri ??= this.fileUri;
 
@@ -263,7 +267,7 @@
   bool addToExportScope(String name, Builder member, [int charOffset = -1]) {
     if (name.startsWith("_")) return false;
     if (member is PrefixBuilder) return false;
-    Builder existing =
+    Builder? existing =
         exportScope.lookupLocalMember(name, setter: member.isSetter);
     if (existing == member) {
       return false;
@@ -295,7 +299,7 @@
 
   @override
   MemberBuilder getConstructor(String className,
-      {String constructorName, bool bypassLibraryPrivacy: false}) {
+      {String? constructorName, bool bypassLibraryPrivacy: false}) {
     constructorName ??= "";
     if (constructorName.startsWith("_") && !bypassLibraryPrivacy) {
       return internalProblem(
@@ -304,8 +308,8 @@
           -1,
           null);
     }
-    Builder cls = (bypassLibraryPrivacy ? scope : exportScope)
-        .lookup(className, -1, null);
+    Builder? cls = (bypassLibraryPrivacy ? scope : exportScope)
+        .lookup(className, -1, fileUri);
     if (cls is TypeAliasBuilder) {
       TypeAliasBuilder aliasBuilder = cls;
       // No type arguments are available, but this method is only called in
@@ -316,8 +320,8 @@
     if (cls is ClassBuilder) {
       // TODO(ahe): This code is similar to code in `endNewExpression` in
       // `body_builder.dart`, try to share it.
-      MemberBuilder constructor =
-          cls.findConstructorOrFactory(constructorName, -1, null, this);
+      MemberBuilder? constructor =
+          cls.findConstructorOrFactory(constructorName, -1, fileUri, this);
       if (constructor == null) {
         // Fall-through to internal error below.
       } else if (constructor.isConstructor) {
@@ -361,8 +365,8 @@
   }
 
   @override
-  Builder lookupLocalMember(String name, {bool required: false}) {
-    Builder builder = scope.lookupLocalMember(name, setter: false);
+  Builder? lookupLocalMember(String name, {bool required: false}) {
+    Builder? builder = scope.lookupLocalMember(name, setter: false);
     if (required && builder == null) {
       internalProblem(
           templateInternalProblemNotFoundIn.withArguments(
@@ -374,7 +378,7 @@
   }
 
   @override
-  Builder lookup(String name, int charOffset, Uri fileUri) {
+  Builder? lookup(String name, int charOffset, Uri fileUri) {
     return scope.lookup(name, charOffset, fileUri);
   }
 
@@ -391,7 +395,7 @@
   void buildOutlineExpressions() {}
 
   @override
-  List<FieldBuilder> takeImplicitlyTypedFields() => null;
+  List<FieldBuilder>? takeImplicitlyTypedFields() => null;
 
   @override
   Nullability get nullable {
diff --git a/pkg/front_end/lib/src/fasta/builder/member_builder.dart b/pkg/front_end/lib/src/fasta/builder/member_builder.dart
index 54f26f8..14ae7c9 100644
--- a/pkg/front_end/lib/src/fasta/builder/member_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/member_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.member_builder;
 
 import 'package:kernel/ast.dart';
@@ -14,6 +12,7 @@
 import '../kernel/class_hierarchy_builder.dart';
 import '../modifier.dart';
 import '../problems.dart' show unsupported;
+import '../source/source_library_builder.dart';
 import '../type_inference/type_inference_engine.dart'
     show InferenceDataForTesting;
 import '../util/helpers.dart' show DelayedActionPerformer;
@@ -26,9 +25,12 @@
 import 'modifier_builder.dart';
 
 abstract class MemberBuilder implements ModifierBuilder {
+  @override
+  String get name;
+
   bool get isAssignable;
 
-  void set parent(Builder value);
+  void set parent(Builder? value);
 
   LibraryBuilder get library;
 
@@ -40,20 +42,20 @@
   /// For a field, a getter or a regular method this is the [member] itself.
   /// For an instance extension method this is special tear-off function. For
   /// a constructor, an operator, a factory or a setter this is `null`.
-  Member get readTarget;
+  Member? get readTarget;
 
   /// The [Member] to use when write to this member builder.
   ///
   /// For an assignable field or a setter this is the [member] itself. For
   /// a constructor, a non-assignable field, a getter, an operator or a regular
   /// method this is `null`.
-  Member get writeTarget;
+  Member? get writeTarget;
 
   /// The [Member] to use when invoking this member builder.
   ///
   /// For a constructor, a field, a regular method, a getter an operator or
   /// a factory this is the [member] itself. For a setter this is `null`.
-  Member get invokeTarget;
+  Member? get invokeTarget;
 
   /// The members from this builder that are accessible in exports through
   /// the name of the builder.
@@ -63,7 +65,7 @@
   Iterable<Member> get exportedMembers;
 
   // TODO(johnniwinther): Remove this and create a [ProcedureBuilder] interface.
-  ProcedureKind get kind;
+  ProcedureKind? get kind;
 
   bool get isExternal;
 
@@ -73,7 +75,9 @@
   /// setter of a field.
   bool get isConflictingSetter;
 
-  void buildOutlineExpressions(LibraryBuilder library, CoreTypes coreTypes,
+  void buildOutlineExpressions(
+      SourceLibraryBuilder library,
+      CoreTypes coreTypes,
       List<DelayedActionPerformer> delayedActionPerformers);
 
   /// Returns the [ClassMember]s for the non-setter members created for this
@@ -97,17 +101,21 @@
   /// construction. However, for class members, the parent is initially the
   /// library and updated later.
   @override
-  Builder parent;
+  Builder? parent;
 
   @override
   String get name;
 
-  MemberDataForTesting dataForTesting;
+  @override
+  final Uri fileUri;
 
-  MemberBuilderImpl(this.parent, int charOffset, [Uri fileUri])
+  MemberDataForTesting? dataForTesting;
+
+  MemberBuilderImpl(this.parent, int charOffset, [Uri? fileUri])
       : dataForTesting =
             retainDataForTesting ? new MemberDataForTesting() : null,
-        super(parent, charOffset, fileUri);
+        this.fileUri = (fileUri ?? parent?.fileUri)!,
+        super(parent, charOffset);
 
   @override
   bool get isDeclarationInstanceMember => isDeclarationMember && !isStatic;
@@ -141,7 +149,7 @@
   @override
   bool get isAbstract => (modifiers & abstractMask) != 0;
 
-  bool _isConflictingSetter;
+  bool? _isConflictingSetter;
 
   @override
   bool get isConflictingSetter {
@@ -157,28 +165,30 @@
   @override
   LibraryBuilder get library {
     if (parent is LibraryBuilder) {
-      LibraryBuilder library = parent;
+      LibraryBuilder library = parent as LibraryBuilder;
       return library.partOfLibrary ?? library;
     } else if (parent is ExtensionBuilder) {
-      ExtensionBuilder extension = parent;
+      ExtensionBuilder extension = parent as ExtensionBuilder;
       return extension.library;
     } else {
-      ClassBuilder cls = parent;
+      ClassBuilder cls = parent as ClassBuilder;
       return cls.library;
     }
   }
 
   // TODO(johnniwinther): Remove this and create a [ProcedureBuilder] interface.
   @override
-  ProcedureKind get kind => unsupported("kind", charOffset, fileUri);
+  ProcedureKind? get kind => unsupported("kind", charOffset, fileUri);
 
   @override
-  void buildOutlineExpressions(LibraryBuilder library, CoreTypes coreTypes,
+  void buildOutlineExpressions(
+      SourceLibraryBuilder library,
+      CoreTypes coreTypes,
       List<DelayedActionPerformer> delayedActionPerformers) {}
 
   /// Builds the core AST structures for this member as needed for the outline.
   void buildMembers(
-      LibraryBuilder library, void Function(Member, BuiltMemberKind) f);
+      SourceLibraryBuilder library, void Function(Member, BuiltMemberKind) f);
 
   @override
   String get fullNameForErrors => name;
@@ -186,14 +196,15 @@
   @override
   StringBuffer printOn(StringBuffer buffer) {
     if (isClassMember) {
-      buffer.write(classBuilder.name);
+      buffer.write(classBuilder!.name);
       buffer.write('.');
     }
     buffer.write(name);
     return buffer;
   }
 
-  ClassBuilder get classBuilder => parent is ClassBuilder ? parent : null;
+  ClassBuilder? get classBuilder =>
+      parent is ClassBuilder ? parent as ClassBuilder : null;
 }
 
 enum BuiltMemberKind {
@@ -215,7 +226,7 @@
 class MemberDataForTesting {
   final InferenceDataForTesting inferenceData = new InferenceDataForTesting();
 
-  MemberBuilder patchForTesting;
+  MemberBuilder? patchForTesting;
 }
 
 /// Base class for implementing [ClassMember] for a [MemberBuilder].
@@ -226,7 +237,7 @@
   int get charOffset => memberBuilder.charOffset;
 
   @override
-  ClassBuilder get classBuilder => memberBuilder.classBuilder;
+  ClassBuilder get classBuilder => memberBuilder.classBuilder!;
 
   @override
   Uri get fileUri => memberBuilder.fileUri;
@@ -237,7 +248,8 @@
   @override
   String get fullName {
     String suffix = isSetter ? "=" : "";
-    String className = classBuilder?.fullNameForErrors;
+    String className = classBuilder.fullNameForErrors;
+    // ignore: unnecessary_null_comparison
     return className == null
         ? "${fullNameForErrors}$suffix"
         : "${className}.${fullNameForErrors}$suffix";
diff --git a/pkg/front_end/lib/src/fasta/builder/metadata_builder.dart b/pkg/front_end/lib/src/fasta/builder/metadata_builder.dart
index 00998c8..21d767b 100644
--- a/pkg/front_end/lib/src/fasta/builder/metadata_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/metadata_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.metadata_builder;
 
 import 'package:_fe_analyzer_shared/src/scanner/scanner.dart' show Token;
@@ -28,10 +26,10 @@
 
   static void buildAnnotations(
       Annotatable parent,
-      List<MetadataBuilder> metadata,
+      List<MetadataBuilder>? metadata,
       SourceLibraryBuilder library,
-      DeclarationBuilder classOrExtensionBuilder,
-      MemberBuilder member,
+      DeclarationBuilder? classOrExtensionBuilder,
+      MemberBuilder? member,
       Uri fileUri) {
     if (metadata == null) return;
     Scope scope = parent is Library ||
@@ -41,8 +39,8 @@
         ? library.scope
         : classOrExtensionBuilder.scope;
     BodyBuilder bodyBuilder = library.loader
-        .createBodyBuilderForOutlineExpression(
-            library, classOrExtensionBuilder, member, scope, fileUri);
+        .createBodyBuilderForOutlineExpression(library, classOrExtensionBuilder,
+            member ?? classOrExtensionBuilder ?? library, scope, fileUri);
     for (int i = 0; i < metadata.length; ++i) {
       MetadataBuilder annotationBuilder = metadata[i];
       parent.addAnnotation(
diff --git a/pkg/front_end/lib/src/fasta/builder/mixin_application_builder.dart b/pkg/front_end/lib/src/fasta/builder/mixin_application_builder.dart
index 2ea95bb..7a769e4 100644
--- a/pkg/front_end/lib/src/fasta/builder/mixin_application_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/mixin_application_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.mixin_application_builder;
 
 import 'package:kernel/ast.dart' show InterfaceType, Supertype, TypedefType;
@@ -17,18 +15,18 @@
 import 'type_variable_builder.dart';
 
 class MixinApplicationBuilder extends TypeBuilder {
-  final TypeBuilder supertype;
+  final TypeBuilder? supertype;
   final List<TypeBuilder> mixins;
   final Uri fileUri;
   final int charOffset;
-  Supertype builtType;
+  Supertype? builtType;
 
-  List<TypeVariableBuilder> typeVariables;
+  List<TypeVariableBuilder>? typeVariables;
 
   MixinApplicationBuilder(
       this.supertype, this.mixins, this.fileUri, this.charOffset);
 
-  String get name => null;
+  String? get name => null;
 
   NullabilityBuilder get nullabilityBuilder {
     return unsupported("nullabilityBuilder", -1, null);
@@ -52,9 +50,9 @@
 
   @override
   InterfaceType build(LibraryBuilder library,
-      [TypedefType origin, bool notInstanceContext]) {
+      {TypedefType? origin, bool? nonInstanceContext}) {
     int charOffset = -1; // TODO(ahe): Provide these.
-    Uri fileUri = null; // TODO(ahe): Provide these.
+    Uri? fileUri = null; // TODO(ahe): Provide these.
     return unsupported("build", charOffset, fileUri);
   }
 
@@ -81,7 +79,7 @@
       SourceLibraryBuilder contextLibrary,
       TypeParameterScopeBuilder contextDeclaration) {
     int charOffset = -1; // TODO(dmitryas): Provide these.
-    Uri fileUri = null; // TODO(dmitryas): Provide these.
+    Uri? fileUri = null; // TODO(dmitryas): Provide these.
     return unsupported("clone", charOffset, fileUri);
   }
 }
diff --git a/pkg/front_end/lib/src/fasta/builder/modifier_builder.dart b/pkg/front_end/lib/src/fasta/builder/modifier_builder.dart
index fae5ee3..d211689 100644
--- a/pkg/front_end/lib/src/fasta/builder/modifier_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/modifier_builder.dart
@@ -26,12 +26,7 @@
   @override
   final int charOffset;
 
-  @override
-  final Uri? fileUri;
-
-  ModifierBuilderImpl(Builder? parent, this.charOffset, [Uri? fileUri])
-      : this.fileUri = fileUri ?? parent?.fileUri,
-        this.parent = parent;
+  ModifierBuilderImpl(Builder? parent, this.charOffset) : this.parent = parent;
 
   @override
   bool get isConst => (modifiers & constMask) != 0;
@@ -46,7 +41,7 @@
   bool get isNative => false;
 
   StringBuffer printOn(StringBuffer buffer) {
-    return buffer..write(name ?? fullNameForErrors);
+    return buffer..write(name);
   }
 
   @override
diff --git a/pkg/front_end/lib/src/fasta/builder/named_type_builder.dart b/pkg/front_end/lib/src/fasta/builder/named_type_builder.dart
index be9a558..fd75e28 100644
--- a/pkg/front_end/lib/src/fasta/builder/named_type_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/named_type_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.named_type_builder;
 
 import 'package:kernel/ast.dart';
@@ -52,24 +50,24 @@
 class NamedTypeBuilder extends TypeBuilder {
   final Object name;
 
-  List<TypeBuilder> arguments;
+  List<TypeBuilder>? arguments;
 
   final NullabilityBuilder nullabilityBuilder;
 
   @override
-  final Uri fileUri;
+  final Uri? fileUri;
 
   @override
-  final int charOffset;
+  final int? charOffset;
 
   @override
-  TypeDeclarationBuilder declaration;
+  TypeDeclarationBuilder? declaration;
 
   NamedTypeBuilder(this.name, this.nullabilityBuilder, this.arguments,
       this.fileUri, this.charOffset);
 
   NamedTypeBuilder.fromTypeDeclarationBuilder(
-      this.declaration, this.nullabilityBuilder,
+      TypeDeclarationBuilder this.declaration, this.nullabilityBuilder,
       [this.arguments, this.fileUri, this.charOffset])
       : this.name = declaration.name;
 
@@ -77,12 +75,12 @@
 
   @override
   void bind(TypeDeclarationBuilder declaration) {
-    this.declaration = declaration?.origin;
+    this.declaration = declaration.origin as TypeDeclarationBuilder;
   }
 
   int get nameOffset {
     if (name is Identifier) {
-      Identifier identifier = name;
+      Identifier identifier = name as Identifier;
       return identifier.charOffset;
     }
     return -1; // TODO(eernst): make it possible to get offset.
@@ -90,10 +88,10 @@
 
   int get nameLength {
     if (name is Identifier) {
-      Identifier identifier = name;
+      Identifier identifier = name as Identifier;
       return identifier.name.length;
     } else if (name is String) {
-      String nameString = name;
+      String nameString = name as String;
       return nameString.length;
     } else {
       return noLength;
@@ -105,11 +103,11 @@
       Scope scope, int charOffset, Uri fileUri, LibraryBuilder library) {
     if (declaration != null) return;
     final Object name = this.name;
-    Builder member;
+    Builder? member;
     if (name is QualifiedName) {
       Object qualifier = name.qualifier;
       String prefixName = flattenName(qualifier, charOffset, fileUri);
-      Builder prefix = scope.lookup(prefixName, charOffset, fileUri);
+      Builder? prefix = scope.lookup(prefixName, charOffset, fileUri);
       if (prefix is PrefixBuilder) {
         member = prefix.lookup(name.name, name.charOffset, fileUri);
       }
@@ -127,7 +125,7 @@
           typeName = name.name;
           typeNameOffset = name.charOffset;
         } else {
-          typeName = name;
+          typeName = name as String;
           typeNameOffset = charOffset;
         }
         Message message =
@@ -138,8 +136,8 @@
       }
       return;
     } else if (member is TypeDeclarationBuilder) {
-      declaration = member.origin;
-      if (!declaration.isExtension ||
+      declaration = member.origin as TypeDeclarationBuilder;
+      if (!declaration!.isExtension ||
           library is SourceLibraryBuilder &&
               library.enableExtensionTypesInLibrary) {
         return;
@@ -148,10 +146,10 @@
     Template<Message Function(String name)> template =
         member == null ? templateTypeNotFound : templateNotAType;
     String flatName = flattenName(name, charOffset, fileUri);
-    List<LocatedMessage> context;
+    List<LocatedMessage>? context;
     if (member != null) {
       context = <LocatedMessage>[
-        messageNotATypeContext.withLocation(member.fileUri, member.charOffset,
+        messageNotATypeContext.withLocation(member.fileUri!, member.charOffset,
             name is Identifier ? name.name.length : "$name".length)
       ];
     }
@@ -167,9 +165,9 @@
   @override
   void check(LibraryBuilder library, int charOffset, Uri fileUri) {
     if (arguments != null &&
-        arguments.length != declaration.typeVariablesCount) {
+        arguments!.length != declaration!.typeVariablesCount) {
       Message message = templateTypeArgumentMismatch
-          .withArguments(declaration.typeVariablesCount);
+          .withArguments(declaration!.typeVariablesCount);
       library.addProblem(message, charOffset, noLength, fileUri);
       declaration = buildInvalidTypeDeclarationBuilder(
           message.withLocation(fileUri, charOffset, noLength));
@@ -179,11 +177,11 @@
   String get debugName => "NamedTypeBuilder";
 
   StringBuffer printOn(StringBuffer buffer) {
-    buffer.write(flattenName(name, charOffset, fileUri));
+    buffer.write(flattenName(name, charOffset ?? TreeNode.noOffset, fileUri));
     if (arguments?.isEmpty ?? true) return buffer;
     buffer.write("<");
     bool first = true;
-    for (TypeBuilder t in arguments) {
+    for (TypeBuilder t in arguments!) {
       if (!first) buffer.write(", ");
       first = false;
       t.printOn(buffer);
@@ -195,7 +193,7 @@
 
   InvalidTypeDeclarationBuilder buildInvalidTypeDeclarationBuilder(
       LocatedMessage message,
-      {List<LocatedMessage> context}) {
+      {List<LocatedMessage>? context}) {
     // TODO(ahe): Consider if it makes sense to pass a QualifiedName to
     // InvalidTypeBuilder?
     return new InvalidTypeDeclarationBuilder(
@@ -203,10 +201,10 @@
         context: context);
   }
 
-  Supertype handleInvalidSupertype(
+  Supertype? handleInvalidSupertype(
       LibraryBuilder library, int charOffset, Uri fileUri) {
     Template<Message Function(String name)> template =
-        declaration.isTypeVariable
+        declaration!.isTypeVariable
             ? templateSupertypeIsTypeVariable
             : templateSupertypeIsIllegal;
     library.addProblem(template.withArguments(fullNameForErrors), charOffset,
@@ -214,60 +212,73 @@
     return null;
   }
 
-  Supertype handleInvalidAliasedSupertype(
+  Supertype? handleInvalidAliasedSupertype(
       LibraryBuilder library,
       int charOffset,
       Uri fileUri,
       TypeAliasBuilder aliasBuilder,
       DartType type) {
-    Template<Message Function(String name, DartType type, bool)> template =
-        declaration.isTypeVariable
-            ? templateSupertypeIsTypeVariable
-            : (type != null && type.nullability == Nullability.nullable
-                ? templateSupertypeIsNullableAliased
-                : templateSupertypeIsIllegalAliased);
-    library.addProblem(
-        template.withArguments(
-            fullNameForErrors, type, library.isNonNullableByDefault),
-        charOffset,
-        noLength,
-        fileUri,
-        context: [
-          messageTypedefCause.withLocation(
-              aliasBuilder.fileUri, aliasBuilder.charOffset, noLength),
-        ]);
+    Message message;
+    if (declaration!.isTypeVariable) {
+      message =
+          templateSupertypeIsTypeVariable.withArguments(fullNameForErrors);
+    } else
+    // ignore: unnecessary_null_comparison
+    if (type != null && type.nullability == Nullability.nullable) {
+      message = templateSupertypeIsNullableAliased.withArguments(
+          fullNameForErrors, type, library.isNonNullableByDefault);
+    } else {
+      message = templateSupertypeIsIllegalAliased.withArguments(
+          fullNameForErrors, type, library.isNonNullableByDefault);
+    }
+    library.addProblem(message, charOffset, noLength, fileUri, context: [
+      messageTypedefCause.withLocation(
+          aliasBuilder.fileUri, aliasBuilder.charOffset, noLength),
+    ]);
     return null;
   }
 
   @override
   DartType build(LibraryBuilder library,
-      [TypedefType origin, bool notInstanceContext]) {
-    return buildInternal(library, origin, notInstanceContext, false);
+      {TypedefType? origin, bool? nonInstanceContext}) {
+    return buildInternal(library,
+        origin: origin,
+        nonInstanceContext: nonInstanceContext,
+        forTypeLiteral: false);
   }
 
   @override
   DartType buildTypeLiteralType(LibraryBuilder library,
-      [TypedefType origin, bool notInstanceContext]) {
-    return buildInternal(library, origin, notInstanceContext, true);
+      {TypedefType? origin, bool? nonInstanceContext}) {
+    return buildInternal(library,
+        origin: origin,
+        nonInstanceContext: nonInstanceContext,
+        forTypeLiteral: true);
   }
 
-  DartType declarationBuildType(
-      LibraryBuilder library, bool notInstanceContext, bool forTypeLiteral) {
+  DartType declarationBuildType(LibraryBuilder library,
+      {bool? nonInstanceContext, required bool forTypeLiteral}) {
     if (forTypeLiteral) {
-      return declaration.buildTypeLiteralType(
-          library, nullabilityBuilder, arguments, notInstanceContext);
+      return declaration!.buildTypeLiteralType(
+          library, nullabilityBuilder, arguments,
+          nonInstanceContext: nonInstanceContext);
     } else {
-      return declaration.buildType(
-          library, nullabilityBuilder, arguments, notInstanceContext);
+      return declaration!.buildType(library, nullabilityBuilder, arguments,
+          nonInstanceContext: nonInstanceContext);
     }
   }
 
   // TODO(johnniwinther): Store [origin] on the built type.
   DartType buildInternal(LibraryBuilder library,
-      [TypedefType origin, bool notInstanceContext, bool forTypeLiteral]) {
+      {TypedefType? origin,
+      bool? nonInstanceContext,
+      required bool forTypeLiteral}) {
     assert(declaration != null, "Declaration has not been resolved on $this.");
-    if (notInstanceContext == true && declaration.isTypeVariable) {
-      TypeVariableBuilder typeParameterBuilder = declaration;
+    // TODO(johnniwinther): Change `nonInstanceContext == true` to
+    // `nonInstanceContext` when it's passed everywhere.
+    if (nonInstanceContext == true && declaration!.isTypeVariable) {
+      TypeVariableBuilder typeParameterBuilder =
+          declaration as TypeVariableBuilder;
       TypeParameter typeParameter = typeParameterBuilder.parameter;
       if (typeParameter.parent is Class || typeParameter.parent is Extension) {
         library.addProblem(
@@ -281,25 +292,30 @@
 
     if (library is SourceLibraryBuilder) {
       int uncheckedTypedefTypeCount = library.uncheckedTypedefTypes.length;
-      DartType builtType =
-          declarationBuildType(library, notInstanceContext, forTypeLiteral);
+      DartType builtType = declarationBuildType(library,
+          nonInstanceContext: nonInstanceContext,
+          forTypeLiteral: forTypeLiteral);
       // Set locations for new unchecked TypedefTypes for error reporting.
       for (int i = uncheckedTypedefTypeCount;
           i < library.uncheckedTypedefTypes.length;
           ++i) {
+        // TODO(johnniwinther): Pass the uri/offset through the build methods
+        // to avoid this.
         library.uncheckedTypedefTypes[i]
           ..fileUri ??= fileUri
           ..offset ??= charOffset;
       }
       return builtType;
     } else {
-      return declarationBuildType(library, notInstanceContext, forTypeLiteral);
+      return declarationBuildType(library,
+          nonInstanceContext: nonInstanceContext,
+          forTypeLiteral: forTypeLiteral);
     }
   }
 
-  Supertype buildSupertype(
+  Supertype? buildSupertype(
       LibraryBuilder library, int charOffset, Uri fileUri) {
-    TypeDeclarationBuilder declaration = this.declaration;
+    TypeDeclarationBuilder declaration = this.declaration!;
     if (declaration is ClassBuilder) {
       if (declaration.isNullClass && !library.mayImplementRestrictedTypes) {
         library.addProblem(
@@ -311,8 +327,7 @@
       return declaration.buildSupertype(library, arguments);
     } else if (declaration is TypeAliasBuilder) {
       TypeAliasBuilder aliasBuilder = declaration;
-      DartType type =
-          declaration.buildType(library, library.nonNullableBuilder, arguments);
+      DartType type = build(library);
       if (type is InterfaceType && type.nullability != Nullability.nullable) {
         return new Supertype(type.classNode, type.typeArguments);
       } else if (type is NullType) {
@@ -321,14 +336,13 @@
         // referencing the deprecated class.
         // TODO(dmitryas): Remove the dependency on the deprecated Null class
         // from ClassHierarchyBuilder.
-        TypeDeclarationBuilder unaliasedDeclaration = this.declaration;
+        TypeDeclarationBuilder? unaliasedDeclaration = this.declaration;
         // The following code assumes that the declaration is a TypeAliasBuilder
         // that through a chain of other TypeAliasBuilders (possibly, the chian
         // length is 0) references a ClassBuilder of the Null class.  Otherwise,
         // it won't produce the NullType on the output.
         while (unaliasedDeclaration is TypeAliasBuilder) {
-          unaliasedDeclaration =
-              (unaliasedDeclaration as TypeAliasBuilder).type.declaration;
+          unaliasedDeclaration = unaliasedDeclaration.type?.declaration;
           assert(unaliasedDeclaration != null);
         }
         assert(unaliasedDeclaration is ClassBuilder &&
@@ -343,14 +357,13 @@
         // any inheritable members.
         // TODO(dmitryas): Remove the dependency on the deprecated FutureOr
         // class from ClassHierarchyBuilder.
-        TypeDeclarationBuilder unaliasedDeclaration = this.declaration;
+        TypeDeclarationBuilder? unaliasedDeclaration = this.declaration;
         // The following code assumes that the declaration is a TypeAliasBuilder
         // that through a chain of other TypeAliasBuilders (possibly, the chian
         // length is 0) references a ClassBuilder of the FutureOr class.
         // Otherwise, it won't produce the FutureOrType on the output.
         while (unaliasedDeclaration is TypeAliasBuilder) {
-          unaliasedDeclaration =
-              (unaliasedDeclaration as TypeAliasBuilder).type.declaration;
+          unaliasedDeclaration = unaliasedDeclaration.type?.declaration;
           assert(unaliasedDeclaration != null);
         }
         assert(unaliasedDeclaration is ClassBuilder &&
@@ -372,15 +385,14 @@
     return handleInvalidSupertype(library, charOffset, fileUri);
   }
 
-  Supertype buildMixedInType(
+  Supertype? buildMixedInType(
       LibraryBuilder library, int charOffset, Uri fileUri) {
-    TypeDeclarationBuilder declaration = this.declaration;
+    TypeDeclarationBuilder declaration = this.declaration!;
     if (declaration is ClassBuilder) {
       return declaration.buildMixedInType(library, arguments);
     } else if (declaration is TypeAliasBuilder) {
       TypeAliasBuilder aliasBuilder = declaration;
-      DartType type =
-          declaration.buildType(library, library.nonNullableBuilder, arguments);
+      DartType type = build(library);
       if (type is InterfaceType && type.nullability != Nullability.nullable) {
         return new Supertype(type.classNode, type.typeArguments);
       }
@@ -399,17 +411,17 @@
   }
 
   TypeBuilder subst(Map<TypeVariableBuilder, TypeBuilder> substitution) {
-    TypeBuilder result = substitution[declaration];
+    TypeBuilder? result = substitution[declaration];
     if (result != null) {
       assert(declaration is TypeVariableBuilder);
       return result;
-    } else if (arguments != null) {
-      List<TypeBuilder> arguments;
+    } else if (this.arguments != null) {
+      List<TypeBuilder>? arguments;
       int i = 0;
-      for (TypeBuilder argument in this.arguments) {
+      for (TypeBuilder argument in this.arguments!) {
         TypeBuilder type = argument.subst(substitution);
         if (type != argument) {
-          arguments ??= this.arguments.toList();
+          arguments ??= this.arguments!.toList();
           arguments[i] = type;
         }
         i++;
@@ -418,7 +430,7 @@
         NamedTypeBuilder result = new NamedTypeBuilder(
             name, nullabilityBuilder, arguments, fileUri, charOffset);
         if (declaration != null) {
-          result.bind(declaration);
+          result.bind(declaration!);
         } else {
           throw new UnsupportedError("Unbound type in substitution: $result.");
         }
@@ -432,13 +444,13 @@
       List<TypeBuilder> newTypes,
       SourceLibraryBuilder contextLibrary,
       TypeParameterScopeBuilder contextDeclaration) {
-    List<TypeBuilder> clonedArguments;
+    List<TypeBuilder>? clonedArguments;
     if (arguments != null) {
-      clonedArguments = new List<TypeBuilder>.filled(arguments.length, null);
-      for (int i = 0; i < clonedArguments.length; i++) {
-        clonedArguments[i] =
-            arguments[i].clone(newTypes, contextLibrary, contextDeclaration);
-      }
+      clonedArguments =
+          new List<TypeBuilder>.generate(arguments!.length, (int i) {
+        return arguments![i]
+            .clone(newTypes, contextLibrary, contextDeclaration);
+      }, growable: false);
     }
     NamedTypeBuilder newType = new NamedTypeBuilder(
         name, nullabilityBuilder, clonedArguments, fileUri, charOffset);
@@ -454,6 +466,6 @@
       NullabilityBuilder nullabilityBuilder) {
     return new NamedTypeBuilder(
         name, nullabilityBuilder, arguments, fileUri, charOffset)
-      ..bind(declaration);
+      ..bind(declaration!);
   }
 }
diff --git a/pkg/front_end/lib/src/fasta/builder/never_type_declaration_builder.dart b/pkg/front_end/lib/src/fasta/builder/never_type_declaration_builder.dart
index 61bcbc8..7a2c3cb 100644
--- a/pkg/front_end/lib/src/fasta/builder/never_type_declaration_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/never_type_declaration_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.never_type_builder;
 
 import 'package:kernel/ast.dart' show DartType, Nullability;
@@ -24,8 +22,8 @@
   String get debugName => "NeverTypeDeclarationBuilder";
 
   DartType buildType(LibraryBuilder library,
-      NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments,
-      [bool notInstanceContext]) {
+      NullabilityBuilder nullabilityBuilder, List<TypeBuilder>? arguments,
+      {bool? nonInstanceContext}) {
     return type.withDeclaredNullability(nullabilityBuilder.build(library));
   }
 
diff --git a/pkg/front_end/lib/src/fasta/builder/null_type_declaration_builder.dart b/pkg/front_end/lib/src/fasta/builder/null_type_declaration_builder.dart
index 4e81719..914bbe3 100644
--- a/pkg/front_end/lib/src/fasta/builder/null_type_declaration_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/null_type_declaration_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.null_type_declaration_builder;
 
 import 'package:kernel/ast.dart' show DartType, Nullability;
@@ -21,8 +19,8 @@
   String get debugName => "NullTypeBuilder";
 
   DartType buildType(LibraryBuilder library,
-      NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments,
-      [bool notInstanceContext]) {
+      NullabilityBuilder nullabilityBuilder, List<TypeBuilder>? arguments,
+      {bool? nonInstanceContext}) {
     return type;
   }
 
diff --git a/pkg/front_end/lib/src/fasta/builder/nullability_builder.dart b/pkg/front_end/lib/src/fasta/builder/nullability_builder.dart
index 4270ba8..2789417 100644
--- a/pkg/front_end/lib/src/fasta/builder/nullability_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/nullability_builder.dart
@@ -2,13 +2,8 @@
 // for 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 'package:kernel/ast.dart';
 
-import '../kernel/body_builder.dart';
-import '../problems.dart';
-
 import 'library_builder.dart';
 
 /// Represents the nullability modifiers encountered while parsing the types.
@@ -50,6 +45,7 @@
   }
 
   Nullability build(LibraryBuilder libraryBuilder) {
+    // ignore: unnecessary_null_comparison
     assert(libraryBuilder != null);
 
     Nullability ifOmitted = libraryBuilder.isNonNullableByDefault
@@ -63,8 +59,6 @@
       case SyntacticNullability.omitted:
         return ifOmitted;
     }
-    return unhandled(
-        "$_syntacticNullability", "buildNullability", noLocation, null);
   }
 
   void writeNullabilityOn(StringBuffer sb) {
@@ -79,7 +73,6 @@
         // Do nothing.
         return;
     }
-    unhandled("$_syntacticNullability", "writeNullabilityOn", noLocation, null);
   }
 
   String toString() {
diff --git a/pkg/front_end/lib/src/fasta/builder/prefix_builder.dart b/pkg/front_end/lib/src/fasta/builder/prefix_builder.dart
index 0635ea9..70c5bbd 100644
--- a/pkg/front_end/lib/src/fasta/builder/prefix_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/prefix_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.prefix_builder;
 
 import 'package:kernel/ast.dart' show LibraryDependency;
@@ -13,17 +11,17 @@
 import '../fasta_codes.dart';
 
 import '../scope.dart';
+import '../source/source_library_builder.dart';
 
 import 'builder.dart';
 import 'extension_builder.dart';
-import 'library_builder.dart';
 
 class PrefixBuilder extends BuilderImpl {
   final String name;
 
   final Scope exportScope = new Scope.top();
 
-  final LibraryBuilder parent;
+  final SourceLibraryBuilder parent;
 
   final bool deferred;
 
@@ -32,22 +30,22 @@
 
   final int importIndex;
 
-  final LibraryDependency dependency;
+  final LibraryDependency? dependency;
 
-  LoadLibraryBuilder loadLibraryBuilder;
+  LoadLibraryBuilder? loadLibraryBuilder;
 
   PrefixBuilder(this.name, this.deferred, this.parent, this.dependency,
       this.charOffset, this.importIndex) {
     if (deferred) {
       loadLibraryBuilder =
-          new LoadLibraryBuilder(parent, dependency, charOffset);
-      addToExportScope('loadLibrary', loadLibraryBuilder, charOffset);
+          new LoadLibraryBuilder(parent, dependency!, charOffset);
+      addToExportScope('loadLibrary', loadLibraryBuilder!, charOffset);
     }
   }
 
   Uri get fileUri => parent.fileUri;
 
-  Builder lookup(String name, int charOffset, Uri fileUri) {
+  Builder? lookup(String name, int charOffset, Uri fileUri) {
     return exportScope.lookup(name, charOffset, fileUri);
   }
 
@@ -57,7 +55,7 @@
           charOffset, noLength, fileUri);
     }
 
-    Builder existing =
+    Builder? existing =
         exportScope.lookupLocalMember(name, setter: member.isSetter);
     Builder result;
     if (existing != null) {
diff --git a/pkg/front_end/lib/src/fasta/builder/procedure_builder.dart b/pkg/front_end/lib/src/fasta/builder/procedure_builder.dart
index a7659a2..a6c464e 100644
--- a/pkg/front_end/lib/src/fasta/builder/procedure_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/procedure_builder.dart
@@ -2,15 +2,14 @@
 // for 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 'package:front_end/src/fasta/dill/dill_member_builder.dart';
-import 'package:front_end/src/fasta/kernel/kernel_api.dart';
 import 'package:kernel/ast.dart';
 
+import '../dill/dill_member_builder.dart';
+
 import '../kernel/class_hierarchy_builder.dart';
 import '../kernel/forest.dart';
 import '../kernel/internal_ast.dart';
+import '../kernel/kernel_api.dart';
 import '../kernel/member_covariance.dart';
 import '../kernel/redirecting_factory_body.dart' show RedirectingFactoryBody;
 
@@ -42,9 +41,9 @@
 abstract class ProcedureBuilder implements FunctionBuilder {
   int get charOpenParenOffset;
 
-  ProcedureBuilder get patchForTesting;
+  ProcedureBuilder? get patchForTesting;
 
-  AsyncMarker actualAsyncModifier;
+  AsyncMarker get actualAsyncModifier;
 
   Procedure get procedure;
 
@@ -65,7 +64,7 @@
 
 abstract class ProcedureBuilderImpl extends FunctionBuilderImpl
     implements ProcedureBuilder {
-  Procedure _procedure;
+  late Procedure _procedure;
 
   @override
   final int charOpenParenOffset;
@@ -77,7 +76,7 @@
   AsyncMarker actualAsyncModifier = AsyncMarker.Sync;
 
   @override
-  ProcedureBuilder actualOrigin;
+  ProcedureBuilder? actualOrigin;
 
   @override
   Procedure get actualProcedure => _procedure;
@@ -85,24 +84,26 @@
   final bool isExtensionInstanceMember;
 
   ProcedureBuilderImpl(
-      List<MetadataBuilder> metadata,
+      List<MetadataBuilder>? metadata,
       int modifiers,
-      TypeBuilder returnType,
+      TypeBuilder? returnType,
       String name,
-      List<TypeVariableBuilder> typeVariables,
-      List<FormalParameterBuilder> formals,
+      List<TypeVariableBuilder>? typeVariables,
+      List<FormalParameterBuilder>? formals,
       this.kind,
       SourceLibraryBuilder libraryBuilder,
       int startCharOffset,
       int charOffset,
       this.charOpenParenOffset,
       int charEndOffset,
-      Reference procedureReference,
+      Reference? procedureReference,
       ProcedureNameScheme procedureNameScheme,
-      {bool isExtensionMember,
-      bool isInstanceMember,
-      String nativeMethodName})
+      {required bool isExtensionMember,
+      required bool isInstanceMember,
+      String? nativeMethodName})
+      // ignore: unnecessary_null_comparison
       : assert(isExtensionMember != null),
+        // ignore: unnecessary_null_comparison
         assert(isInstanceMember != null),
         this.isExtensionInstanceMember = isInstanceMember && isExtensionMember,
         super(metadata, modifiers, returnType, name, typeVariables, formals,
@@ -125,13 +126,14 @@
   ProcedureBuilder get origin => actualOrigin ?? this;
 
   @override
-  ProcedureBuilder get patchForTesting => dataForTesting?.patchForTesting;
+  ProcedureBuilder? get patchForTesting =>
+      dataForTesting?.patchForTesting as ProcedureBuilder?;
 
   @override
   AsyncMarker get asyncModifier => actualAsyncModifier;
 
   @override
-  Statement get body {
+  Statement? get body {
     if (bodyInternal == null && !isAbstract && !isExternal) {
       bodyInternal = new EmptyStatement();
     }
@@ -150,7 +152,7 @@
     if (isDeclarationInstanceMember) {
       if (returnType == null) return true;
       if (formals != null) {
-        for (FormalParameterBuilder formal in formals) {
+        for (FormalParameterBuilder formal in formals!) {
           if (formal.type == null) return true;
         }
       }
@@ -211,11 +213,11 @@
 }
 
 class SourceProcedureBuilder extends ProcedureBuilderImpl {
-  final Reference _tearOffReference;
+  final Reference? _tearOffReference;
 
   /// If this is an extension instance method then [_extensionTearOff] holds
   /// the synthetically created tear off function.
-  Procedure _extensionTearOff;
+  Procedure? _extensionTearOff;
 
   /// If this is an extension instance method then
   /// [_extensionTearOffParameterMap] holds a map from the parameters of
@@ -223,28 +225,28 @@
   ///
   /// This map is used to set the default values on the closure parameters when
   /// these have been built.
-  Map<VariableDeclaration, VariableDeclaration> _extensionTearOffParameterMap;
+  Map<VariableDeclaration, VariableDeclaration>? _extensionTearOffParameterMap;
 
   SourceProcedureBuilder(
-      List<MetadataBuilder> metadata,
+      List<MetadataBuilder>? metadata,
       int modifiers,
-      TypeBuilder returnType,
+      TypeBuilder? returnType,
       String name,
-      List<TypeVariableBuilder> typeVariables,
-      List<FormalParameterBuilder> formals,
+      List<TypeVariableBuilder>? typeVariables,
+      List<FormalParameterBuilder>? formals,
       ProcedureKind kind,
       SourceLibraryBuilder libraryBuilder,
       int startCharOffset,
       int charOffset,
       int charOpenParenOffset,
       int charEndOffset,
-      Reference procedureReference,
+      Reference? procedureReference,
       this._tearOffReference,
       AsyncMarker asyncModifier,
       ProcedureNameScheme procedureNameScheme,
-      {bool isExtensionMember,
-      bool isInstanceMember,
-      String nativeMethodName})
+      {required bool isExtensionMember,
+      required bool isInstanceMember,
+      String? nativeMethodName})
       : super(
             metadata,
             modifiers,
@@ -278,7 +280,7 @@
   }
 
   bool _typeEnsured = false;
-  Set<ClassMember> _overrideDependencies;
+  Set<ClassMember>? _overrideDependencies;
 
   void registerOverrideDependency(Set<ClassMember> overriddenMembers) {
     assert(
@@ -286,18 +288,18 @@
             overriddenMember.classBuilder != classBuilder),
         "Unexpected override dependencies for $this: $overriddenMembers");
     _overrideDependencies ??= {};
-    _overrideDependencies.addAll(overriddenMembers);
+    _overrideDependencies!.addAll(overriddenMembers);
   }
 
   void _ensureTypes(ClassHierarchyBuilder hierarchy) {
     if (_typeEnsured) return;
     if (_overrideDependencies != null) {
       if (isGetter) {
-        hierarchy.inferGetterType(this, _overrideDependencies);
+        hierarchy.inferGetterType(this, _overrideDependencies!);
       } else if (isSetter) {
-        hierarchy.inferSetterType(this, _overrideDependencies);
+        hierarchy.inferSetterType(this, _overrideDependencies!);
       } else {
-        hierarchy.inferMethodType(this, _overrideDependencies);
+        hierarchy.inferMethodType(this, _overrideDependencies!);
       }
       _overrideDependencies = null;
     }
@@ -305,7 +307,7 @@
   }
 
   @override
-  Member get readTarget {
+  Member? get readTarget {
     switch (kind) {
       case ProcedureKind.Method:
         return extensionTearOff ?? procedure;
@@ -316,11 +318,10 @@
       case ProcedureKind.Factory:
         return null;
     }
-    throw unhandled('ProcedureKind', '$kind', charOffset, fileUri);
   }
 
   @override
-  Member get writeTarget {
+  Member? get writeTarget {
     switch (kind) {
       case ProcedureKind.Setter:
         return procedure;
@@ -330,11 +331,10 @@
       case ProcedureKind.Factory:
         return null;
     }
-    throw unhandled('ProcedureKind', '$kind', charOffset, fileUri);
   }
 
   @override
-  Member get invokeTarget {
+  Member? get invokeTarget {
     switch (kind) {
       case ProcedureKind.Method:
       case ProcedureKind.Getter:
@@ -344,7 +344,6 @@
       case ProcedureKind.Setter:
         return null;
     }
-    throw unhandled('ProcedureKind', '$kind', charOffset, fileUri);
   }
 
   @override
@@ -352,7 +351,7 @@
 
   @override
   void buildMembers(
-      LibraryBuilder library, void Function(Member, BuiltMemberKind) f) {
+      SourceLibraryBuilder library, void Function(Member, BuiltMemberKind) f) {
     Member member = build(library);
     if (isExtensionMethod) {
       switch (kind) {
@@ -373,7 +372,7 @@
               'Unexpected extension method kind ${kind}');
       }
       if (extensionTearOff != null) {
-        f(extensionTearOff, BuiltMemberKind.ExtensionTearOff);
+        f(extensionTearOff!, BuiltMemberKind.ExtensionTearOff);
       }
     } else {
       f(member, BuiltMemberKind.Method);
@@ -399,14 +398,14 @@
       _procedure.isStatic = isStatic;
     }
     if (extensionTearOff != null) {
-      _buildExtensionTearOff(libraryBuilder, parent);
-      updatePrivateMemberName(extensionTearOff, libraryBuilder);
+      _buildExtensionTearOff(libraryBuilder, parent as ExtensionBuilder);
+      updatePrivateMemberName(extensionTearOff!, libraryBuilder);
     }
     return _procedure;
   }
 
   static String createProcedureName(bool isExtensionMethod, bool isStatic,
-      ProcedureKind kind, String extensionName, String name) {
+      ProcedureKind kind, String? extensionName, String name) {
     if (isExtensionMethod) {
       String kindInfix = '';
       if (!isStatic) {
@@ -495,13 +494,13 @@
 
     VariableDeclaration copyParameter(
         VariableDeclaration parameter, DartType type,
-        {bool isOptional}) {
+        {required bool isOptional}) {
       VariableDeclaration newParameter = new VariableDeclaration(parameter.name,
           type: type,
           isFinal: parameter.isFinal,
           isLowered: parameter.isLowered)
         ..fileOffset = parameter.fileOffset;
-      _extensionTearOffParameterMap[parameter] = newParameter;
+      _extensionTearOffParameterMap![parameter] = newParameter;
       return newParameter;
     }
 
@@ -539,7 +538,7 @@
       VariableDeclaration newParameter =
           copyParameter(parameter, type, isOptional: true);
       closureNamedParameters.add(newParameter);
-      closureNamedArguments.add(new NamedExpression(parameter.name,
+      closureNamedArguments.add(new NamedExpression(parameter.name!,
           new VariableGet(newParameter)..fileOffset = fileOffset));
     }
 
@@ -563,7 +562,7 @@
           ..fileEndOffset = fileEndOffset)
       ..fileOffset = fileOffset;
 
-    _extensionTearOff
+    _extensionTearOff!
       ..function = (new FunctionNode(
           new ReturnStatement(closure)..fileOffset = fileOffset,
           typeParameters: tearOffTypeParameters,
@@ -575,21 +574,18 @@
       ..fileUri = fileUri
       ..fileOffset = fileOffset
       ..fileEndOffset = fileEndOffset;
-    _extensionTearOff.function.parent = _extensionTearOff;
+    _extensionTearOff!.function.parent = _extensionTearOff;
   }
 
-  Procedure get extensionTearOff => _extensionTearOff;
+  Procedure? get extensionTearOff => _extensionTearOff;
 
   @override
-  VariableDeclaration getExtensionTearOffParameter(int index) {
-    if (_extensionTearOffParameterMap != null) {
-      return _extensionTearOffParameterMap[getFormalParameter(index)];
-    }
-    return null;
+  VariableDeclaration? getExtensionTearOffParameter(int index) {
+    return _extensionTearOffParameterMap?[getFormalParameter(index)];
   }
 
-  List<ClassMember> _localMembers;
-  List<ClassMember> _localSetters;
+  List<ClassMember>? _localMembers;
+  List<ClassMember>? _localSetters;
 
   @override
   List<ClassMember> get localMembers => _localMembers ??= isSetter
@@ -607,7 +603,7 @@
   @override
   final SourceProcedureBuilder memberBuilder;
 
-  Covariance _covariance;
+  Covariance? _covariance;
 
   SourceProcedureMember(this.memberBuilder);
 
@@ -653,24 +649,24 @@
 
 class RedirectingFactoryBuilder extends ProcedureBuilderImpl {
   final ConstructorReferenceBuilder redirectionTarget;
-  List<DartType> typeArguments;
+  List<DartType>? typeArguments;
 
   RedirectingFactoryBuilder(
-      List<MetadataBuilder> metadata,
+      List<MetadataBuilder>? metadata,
       int modifiers,
       TypeBuilder returnType,
       String name,
       List<TypeVariableBuilder> typeVariables,
-      List<FormalParameterBuilder> formals,
+      List<FormalParameterBuilder>? formals,
       SourceLibraryBuilder compilationUnit,
       int startCharOffset,
       int charOffset,
       int charOpenParenOffset,
       int charEndOffset,
-      Reference reference,
+      Reference? reference,
       ProcedureNameScheme procedureNameScheme,
-      [String nativeMethodName,
-      this.redirectionTarget])
+      String? nativeMethodName,
+      this.redirectionTarget)
       : super(
             metadata,
             modifiers,
@@ -691,19 +687,19 @@
             nativeMethodName: nativeMethodName);
 
   @override
-  Member get readTarget => null;
+  Member? get readTarget => null;
 
   @override
-  Member get writeTarget => null;
+  Member? get writeTarget => null;
 
   @override
-  Member get invokeTarget => procedure;
+  Member? get invokeTarget => procedure;
 
   @override
   Iterable<Member> get exportedMembers => [procedure];
 
   @override
-  Statement get body => bodyInternal;
+  Statement? get body => bodyInternal;
 
   @override
   void setRedirectingFactoryBody(Member target, List<DartType> typeArguments) {
@@ -722,27 +718,25 @@
     bodyInternal?.parent = function;
     procedure.isRedirectingFactoryConstructor = true;
     if (isPatch) {
+      // ignore: unnecessary_null_comparison
       if (function.typeParameters != null) {
         Map<TypeParameter, DartType> substitution = <TypeParameter, DartType>{};
         for (int i = 0; i < function.typeParameters.length; i++) {
           substitution[function.typeParameters[i]] =
               new TypeParameterType.withDefaultNullabilityForLibrary(
-                  actualOrigin.function.typeParameters[i], library.library);
+                  actualOrigin!.function.typeParameters[i], library.library);
         }
-        List<DartType> newTypeArguments =
-            new List<DartType>.filled(typeArguments.length, null);
-        for (int i = 0; i < newTypeArguments.length; i++) {
-          newTypeArguments[i] = substitute(typeArguments[i], substitution);
-        }
-        typeArguments = newTypeArguments;
+        typeArguments = new List<DartType>.generate(typeArguments.length,
+            (int i) => substitute(typeArguments[i], substitution),
+            growable: false);
       }
-      actualOrigin.setRedirectingFactoryBody(target, typeArguments);
+      actualOrigin!.setRedirectingFactoryBody(target, typeArguments);
     }
   }
 
   @override
   void buildMembers(
-      LibraryBuilder library, void Function(Member, BuiltMemberKind) f) {
+      SourceLibraryBuilder library, void Function(Member, BuiltMemberKind) f) {
     Member member = build(library);
     f(member, BuiltMemberKind.RedirectingFactory);
   }
@@ -758,32 +752,35 @@
     _procedure.isStatic = isStatic;
     _procedure.isRedirectingFactoryConstructor = true;
     if (redirectionTarget.typeArguments != null) {
-      typeArguments = new List<DartType>.filled(
-          redirectionTarget.typeArguments.length, null);
-      for (int i = 0; i < typeArguments.length; i++) {
-        typeArguments[i] = redirectionTarget.typeArguments[i].build(library);
-      }
+      typeArguments = new List<DartType>.generate(
+          redirectionTarget.typeArguments!.length,
+          (int i) => redirectionTarget.typeArguments![i].build(library),
+          growable: false);
     }
     updatePrivateMemberName(_procedure, libraryBuilder);
     return _procedure;
   }
 
   @override
-  void buildOutlineExpressions(LibraryBuilder library, CoreTypes coreTypes,
+  void buildOutlineExpressions(
+      SourceLibraryBuilder library,
+      CoreTypes coreTypes,
       List<DelayedActionPerformer> delayedActionPerformers) {
     super.buildOutlineExpressions(library, coreTypes, delayedActionPerformers);
     LibraryBuilder thisLibrary = this.library;
     if (thisLibrary is SourceLibraryBuilder) {
-      RedirectingFactoryBody redirectingFactoryBody = procedure.function.body;
+      RedirectingFactoryBody redirectingFactoryBody =
+          procedure.function.body as RedirectingFactoryBody;
       if (redirectingFactoryBody.typeArguments != null &&
-          redirectingFactoryBody.typeArguments.any((t) => t is UnknownType)) {
+          redirectingFactoryBody.typeArguments!.any((t) => t is UnknownType)) {
         TypeInferrerImpl inferrer = thisLibrary.loader.typeInferenceEngine
-            .createLocalTypeInferrer(
-                fileUri, classBuilder.thisType, thisLibrary, null);
+                .createLocalTypeInferrer(
+                    fileUri, classBuilder!.thisType, thisLibrary, null)
+            as TypeInferrerImpl;
         inferrer.helper = thisLibrary.loader
             .createBodyBuilderForOutlineExpression(
-                this.library, classBuilder, this, classBuilder.scope, fileUri);
-        Builder targetBuilder = redirectionTarget.target;
+                thisLibrary, classBuilder, this, classBuilder!.scope, fileUri);
+        Builder? targetBuilder = redirectionTarget.target;
         Member target;
         if (targetBuilder is FunctionBuilder) {
           target = targetBuilder.member;
@@ -797,28 +794,28 @@
         {
           List<Expression> positionalArguments = <Expression>[];
           for (VariableDeclaration parameter
-              in member.function.positionalParameters) {
-            inferrer.flowAnalysis?.declare(parameter, true);
+              in procedure.function.positionalParameters) {
+            inferrer.flowAnalysis.declare(parameter, true);
             positionalArguments.add(
                 new VariableGetImpl(parameter, forNullGuardedAccess: false));
           }
           List<NamedExpression> namedArguments = <NamedExpression>[];
           for (VariableDeclaration parameter
-              in member.function.namedParameters) {
-            inferrer.flowAnalysis?.declare(parameter, true);
-            namedArguments.add(new NamedExpression(parameter.name,
+              in procedure.function.namedParameters) {
+            inferrer.flowAnalysis.declare(parameter, true);
+            namedArguments.add(new NamedExpression(parameter.name!,
                 new VariableGetImpl(parameter, forNullGuardedAccess: false)));
           }
           // If arguments are created using [Forest.createArguments], and the
           // type arguments are omitted, they are to be inferred.
           targetInvocationArguments = const Forest().createArguments(
-              member.fileOffset, positionalArguments,
+              procedure.fileOffset, positionalArguments,
               named: namedArguments);
         }
         InvocationInferenceResult result = inferrer.inferInvocation(
             function.returnType,
             charOffset,
-            target.function.computeFunctionType(Nullability.nonNullable),
+            target.function!.computeFunctionType(Nullability.nonNullable),
             targetInvocationArguments,
             staticTarget: target);
         List<DartType> typeArguments;
@@ -828,10 +825,10 @@
           // Assume that the error is reported elsewhere, use 'dynamic' for
           // recovery.
           typeArguments = new List<DartType>.filled(
-              target.enclosingClass.typeParameters.length, const DynamicType(),
+              target.enclosingClass!.typeParameters.length, const DynamicType(),
               growable: true);
         }
-        member.function.body =
+        member.function!.body =
             new RedirectingFactoryBody(target, typeArguments);
       }
     }
@@ -851,8 +848,8 @@
 
     super.finishPatch();
 
-    if (origin is RedirectingFactoryBuilder) {
-      RedirectingFactoryBuilder redirectingOrigin = origin;
+    ProcedureBuilder redirectingOrigin = origin;
+    if (redirectingOrigin is RedirectingFactoryBuilder) {
       redirectingOrigin.typeArguments = typeArguments;
     }
 
@@ -863,20 +860,25 @@
 class ProcedureNameScheme {
   final bool isExtensionMember;
   final bool isStatic;
-  final String extensionName;
+  final String? extensionName;
   final Reference libraryReference;
 
   ProcedureNameScheme(
-      {this.isExtensionMember,
-      this.isStatic,
+      {required this.isExtensionMember,
+      required this.isStatic,
       this.extensionName,
-      this.libraryReference})
+      required this.libraryReference})
+      // ignore: unnecessary_null_comparison
       : assert(isExtensionMember != null),
+        // ignore: unnecessary_null_comparison
         assert(isStatic != null),
+        // ignore: unnecessary_null_comparison
         assert(!isExtensionMember || extensionName != null),
+        // ignore: unnecessary_null_comparison
         assert(libraryReference != null);
 
   Name getName(ProcedureKind kind, String name) {
+    // ignore: unnecessary_null_comparison
     assert(kind != null);
     return new Name.byReference(
         SourceProcedureBuilder.createProcedureName(
diff --git a/pkg/front_end/lib/src/fasta/builder/type_alias_builder.dart b/pkg/front_end/lib/src/fasta/builder/type_alias_builder.dart
index c5bf0a1..526e78c 100644
--- a/pkg/front_end/lib/src/fasta/builder/type_alias_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/type_alias_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.function_type_alias_builder;
 
 import 'package:kernel/ast.dart';
@@ -34,12 +32,12 @@
 import 'type_variable_builder.dart';
 
 abstract class TypeAliasBuilder implements TypeDeclarationBuilder {
-  TypeBuilder get type;
+  TypeBuilder? get type;
 
   /// The [Typedef] built by this builder.
   Typedef get typedef;
 
-  DartType thisType;
+  DartType? thisType;
 
   String get debugName;
 
@@ -47,7 +45,9 @@
 
   LibraryBuilder get library;
 
-  List<TypeVariableBuilder> get typeVariables;
+  Uri get fileUri;
+
+  List<TypeVariableBuilder>? get typeVariables;
 
   int varianceAt(int index);
 
@@ -57,19 +57,19 @@
 
   /// [arguments] have already been built.
   DartType buildTypesWithBuiltArguments(LibraryBuilder library,
-      Nullability nullability, List<DartType> arguments);
+      Nullability nullability, List<DartType>? arguments);
 
   List<DartType> buildTypeArguments(
-      LibraryBuilder library, List<TypeBuilder> arguments,
-      [bool notInstanceContext]);
+      LibraryBuilder library, List<TypeBuilder>? arguments,
+      {bool? nonInstanceContext});
 
   /// Returns `true` if this typedef is an alias of the `Null` type.
   bool get isNullAlias;
 
   @override
   DartType buildType(LibraryBuilder library,
-      NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments,
-      [bool notInstanceContext]);
+      NullabilityBuilder nullabilityBuilder, List<TypeBuilder>? arguments,
+      {bool? nonInstanceContext});
 
   /// Returns the [TypeDeclarationBuilder] for the type aliased by `this`,
   /// based on the given [typeArguments]. It expands type aliases repeatedly
@@ -90,10 +90,10 @@
   /// `const InvalidType()`). If `this` type alias expands to a
   /// [TypeVariableBuilder] then the type alias cannot be used in a constructor
   /// invocation. Then an error is emitted and `this` is returned.
-  TypeDeclarationBuilder unaliasDeclaration(List<TypeBuilder> typeArguments,
+  TypeDeclarationBuilder? unaliasDeclaration(List<TypeBuilder>? typeArguments,
       {bool isUsedAsClass = false,
-      int usedAsClassCharOffset,
-      Uri usedAsClassFileUri});
+      int? usedAsClassCharOffset,
+      Uri? usedAsClassFileUri});
 
   /// Compute type arguments passed to [ClassBuilder] from unaliasDeclaration.
   /// This method does not check for cycles and may only be called if an
@@ -109,36 +109,46 @@
   /// [this], such that the returned [TypeBuilder]s are appropriate type
   /// arguments for passing to the [ClassBuilder] which is the end of the
   /// unaliasing chain.
-  List<TypeBuilder> unaliasTypeArguments(List<TypeBuilder> typeArguments);
+  // TODO(johnniwinther): Should we enforce that [typeArguments] are non-null
+  // as stated in the docs? It is not needed for the implementation.
+  List<TypeBuilder>? unaliasTypeArguments(List<TypeBuilder>? typeArguments);
 
-  void buildOutlineExpressions(LibraryBuilder library, CoreTypes coreTypes,
+  void buildOutlineExpressions(
+      SourceLibraryBuilder library,
+      CoreTypes coreTypes,
       List<DelayedActionPerformer> delayedActionPerformers);
 }
 
 abstract class TypeAliasBuilderImpl extends TypeDeclarationBuilderImpl
     implements TypeAliasBuilder {
-  TypeAliasBuilderImpl(List<MetadataBuilder> metadata, String name,
+  @override
+  final Uri fileUri;
+
+  TypeAliasBuilderImpl(List<MetadataBuilder>? metadata, String name,
       LibraryBuilder parent, int charOffset)
-      : super(metadata, 0, name, parent, charOffset);
+      : fileUri = parent.fileUri,
+        super(metadata, 0, name, parent, charOffset);
 
   String get debugName => "TypeAliasBuilder";
 
-  LibraryBuilder get parent => super.parent;
+  LibraryBuilder get parent => super.parent as LibraryBuilder;
 
-  LibraryBuilder get library => super.parent;
+  LibraryBuilder get library => super.parent as LibraryBuilder;
 
   /// [arguments] have already been built.
   DartType buildTypesWithBuiltArguments(LibraryBuilder library,
-      Nullability nullability, List<DartType> arguments) {
+      Nullability nullability, List<DartType>? arguments) {
     DartType thisType = buildThisType();
     if (const DynamicType() == thisType) return thisType;
     Nullability adjustedNullability =
         isNullAlias ? Nullability.nullable : nullability;
     DartType result = thisType.withDeclaredNullability(adjustedNullability);
+    // TODO(johnniwinther): Couldn't [arguments] be null and
+    // `typedef.typeParameters` be non-empty?
     if (typedef.typeParameters.isEmpty && arguments == null) return result;
     Map<TypeParameter, DartType> substitution = <TypeParameter, DartType>{};
     for (int i = 0; i < typedef.typeParameters.length; i++) {
-      substitution[typedef.typeParameters[i]] = arguments[i];
+      substitution[typedef.typeParameters[i]] = arguments![i];
     }
     // The following adds the built type to the list of unchecked typedef types
     // of the client library. It is needed because the type is built unaliased,
@@ -146,7 +156,7 @@
     // arguments to the generic typedef conform to the bounds without preserving
     // the TypedefType for the delayed check.
     if (library is SourceLibraryBuilder &&
-        arguments.isNotEmpty &&
+        arguments!.isNotEmpty &&
         thisType is! FunctionType) {
       library.uncheckedTypedefTypes.add(new UncheckedTypedefType(
           new TypedefType(typedef, nullability, arguments)));
@@ -156,23 +166,23 @@
 
   @override
   DartType buildType(LibraryBuilder library,
-      NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments,
-      [bool notInstanceContext]) {
-    return buildTypeInternal(
-        library, nullabilityBuilder, arguments, notInstanceContext, true);
+      NullabilityBuilder nullabilityBuilder, List<TypeBuilder>? arguments,
+      {bool? nonInstanceContext}) {
+    return buildTypeInternal(library, nullabilityBuilder, arguments,
+        nonInstanceContext: nonInstanceContext, performLegacyErasure: true);
   }
 
   @override
   DartType buildTypeLiteralType(LibraryBuilder library,
-      NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments,
-      [bool notInstanceContext]) {
-    return buildTypeInternal(
-        library, nullabilityBuilder, arguments, notInstanceContext, false);
+      NullabilityBuilder nullabilityBuilder, List<TypeBuilder>? arguments,
+      {bool? nonInstanceContext}) {
+    return buildTypeInternal(library, nullabilityBuilder, arguments,
+        nonInstanceContext: nonInstanceContext, performLegacyErasure: false);
   }
 
   DartType buildTypeInternal(LibraryBuilder library,
-      NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments,
-      [bool notInstanceContext, bool performLegacyErasure]) {
+      NullabilityBuilder nullabilityBuilder, List<TypeBuilder>? arguments,
+      {bool? nonInstanceContext, required bool performLegacyErasure}) {
     DartType thisType = buildThisType();
     if (thisType is InvalidType) return thisType;
 
@@ -205,7 +215,7 @@
     return result;
   }
 
-  TypeDeclarationBuilder _cachedUnaliasedDeclaration;
+  TypeDeclarationBuilder? _cachedUnaliasedDeclaration;
 
   /// Returns the [TypeDeclarationBuilder] for the type aliased by `this`,
   /// based on the given [typeArguments]. It expands type aliases repeatedly
@@ -233,16 +243,18 @@
   /// `const InvalidType()`). If `this` type alias expands to a
   /// [TypeVariableBuilder] then the type alias cannot be used as a class, in
   /// which case an error is emitted and `this` is returned.
-  TypeDeclarationBuilder unaliasDeclaration(List<TypeBuilder> typeArguments,
+  TypeDeclarationBuilder? unaliasDeclaration(List<TypeBuilder>? typeArguments,
       {bool isUsedAsClass = false,
-      int usedAsClassCharOffset,
-      Uri usedAsClassFileUri}) {
-    if (_cachedUnaliasedDeclaration != null) return _cachedUnaliasedDeclaration;
+      int? usedAsClassCharOffset,
+      Uri? usedAsClassFileUri}) {
+    if (_cachedUnaliasedDeclaration != null) {
+      return _cachedUnaliasedDeclaration;
+    }
     Set<TypeDeclarationBuilder> builders = {this};
     TypeDeclarationBuilder current = this;
     while (current is TypeAliasBuilder) {
       TypeAliasBuilder currentAliasBuilder = current;
-      TypeDeclarationBuilder next = currentAliasBuilder.type?.declaration;
+      TypeDeclarationBuilder? next = currentAliasBuilder.type?.declaration;
       if (next != null) {
         current = next;
       } else {
@@ -273,7 +285,7 @@
         if (isUsedAsClass) {
           List<TypeBuilder> freshTypeArguments = [
             if (typeVariables != null)
-              for (TypeVariableBuilder typeVariable in typeVariables)
+              for (TypeVariableBuilder typeVariable in typeVariables!)
                 new NamedTypeBuilder.fromTypeDeclarationBuilder(
                   typeVariable,
                   library.nonNullableBuilder,
@@ -282,7 +294,7 @@
                   charOffset,
                 ),
           ];
-          TypeDeclarationBuilder typeDeclarationBuilder =
+          TypeDeclarationBuilder? typeDeclarationBuilder =
               _unaliasDeclaration(freshTypeArguments);
           bool found = false;
           for (TypeBuilder typeBuilder in freshTypeArguments) {
@@ -292,11 +304,14 @@
             }
           }
           if (found) {
-            library.addProblem(messageTypedefTypeVariableNotConstructor,
-                usedAsClassCharOffset, noLength, usedAsClassFileUri,
+            library.addProblem(
+                messageTypedefTypeVariableNotConstructor,
+                usedAsClassCharOffset ?? TreeNode.noOffset,
+                noLength,
+                usedAsClassFileUri,
                 context: [
                   messageTypedefTypeVariableNotConstructorCause.withLocation(
-                      current.fileUri, current.charOffset, noLength),
+                      current.fileUri!, current.charOffset, noLength),
                 ]);
             return this;
           }
@@ -326,26 +341,24 @@
   // arguments, for all i in 1 .. k-1, and the right hand side of F_k is a type
   // variable. In this case, the unaliased declaration must be obtained from
   // the type argument, which is the reason why we must trace them.
-  TypeDeclarationBuilder _unaliasDeclaration(List<TypeBuilder> typeArguments) {
-    TypeDeclarationBuilder currentDeclarationBuilder = this;
-    TypeAliasBuilder previousAliasBuilder = null;
-    List<TypeBuilder> currentTypeArguments = typeArguments;
+  TypeDeclarationBuilder? _unaliasDeclaration(
+      List<TypeBuilder>? typeArguments) {
+    TypeDeclarationBuilder? currentDeclarationBuilder = this;
+    TypeAliasBuilder? previousAliasBuilder = null;
+    List<TypeBuilder>? currentTypeArguments = typeArguments;
     while (currentDeclarationBuilder is TypeAliasBuilder) {
       TypeAliasBuilder currentAliasBuilder = currentDeclarationBuilder;
-      TypeBuilder nextTypeBuilder = currentAliasBuilder.type;
+      TypeBuilder? nextTypeBuilder = currentAliasBuilder.type;
       if (nextTypeBuilder is NamedTypeBuilder) {
         Map<TypeVariableBuilder, TypeBuilder> substitution = {};
         int index = 0;
         if (currentTypeArguments == null || currentTypeArguments.isEmpty) {
           if (currentAliasBuilder.typeVariables != null) {
             List<TypeBuilder> defaultTypeArguments =
-                new List<TypeBuilder>.filled(
-                    currentAliasBuilder.typeVariables.length, null,
-                    growable: true);
-            for (int i = 0; i < defaultTypeArguments.length; ++i) {
-              defaultTypeArguments[i] =
-                  currentAliasBuilder.typeVariables[i].defaultType;
-            }
+                new List<TypeBuilder>.generate(
+                    currentAliasBuilder.typeVariables!.length, (int i) {
+              return currentAliasBuilder.typeVariables![i].defaultType!;
+            }, growable: true);
             currentTypeArguments = defaultTypeArguments;
           } else {
             currentTypeArguments = <TypeBuilder>[];
@@ -374,7 +387,7 @@
           substitution[typeVariableBuilder] = currentTypeArguments[index];
           ++index;
         }
-        TypeDeclarationBuilder nextDeclarationBuilder =
+        TypeDeclarationBuilder? nextDeclarationBuilder =
             nextTypeBuilder.declaration;
         TypeBuilder substitutedBuilder = nextTypeBuilder.subst(substitution);
         if (nextDeclarationBuilder is TypeVariableBuilder) {
@@ -385,7 +398,7 @@
           // cyclic; we want to do it as well, because the result could be
           // cached.
           if (substitutedBuilder is NamedTypeBuilder) {
-            TypeDeclarationBuilder declarationBuilder =
+            TypeDeclarationBuilder? declarationBuilder =
                 substitutedBuilder.declaration;
             if (declarationBuilder is TypeAliasBuilder) {
               return declarationBuilder
@@ -397,7 +410,7 @@
           return substitutedBuilder.declaration;
         }
         // Not yet at the end of the chain, more named builders to come.
-        NamedTypeBuilder namedBuilder = substitutedBuilder;
+        NamedTypeBuilder namedBuilder = substitutedBuilder as NamedTypeBuilder;
         currentDeclarationBuilder = namedBuilder.declaration;
         currentTypeArguments = namedBuilder.arguments;
         previousAliasBuilder = currentAliasBuilder;
@@ -424,25 +437,24 @@
   /// [this], such that the returned [TypeBuilder]s are appropriate type
   /// arguments for passing to the [ClassBuilder] which is the end of the
   /// unaliasing chain.
-  List<TypeBuilder> unaliasTypeArguments(List<TypeBuilder> typeArguments) {
-    TypeDeclarationBuilder currentDeclarationBuilder = this;
-    List<TypeBuilder> currentTypeArguments = typeArguments;
+  List<TypeBuilder>? unaliasTypeArguments(List<TypeBuilder>? typeArguments) {
+    TypeDeclarationBuilder? currentDeclarationBuilder = this;
+    List<TypeBuilder>? currentTypeArguments = typeArguments;
     while (currentDeclarationBuilder is TypeAliasBuilder) {
       TypeAliasBuilder currentAliasBuilder = currentDeclarationBuilder;
-      TypeBuilder nextTypeBuilder = currentAliasBuilder.type;
+      TypeBuilder? nextTypeBuilder = currentAliasBuilder.type;
       assert(nextTypeBuilder is NamedTypeBuilder);
-      NamedTypeBuilder namedNextTypeBuilder = nextTypeBuilder;
+      NamedTypeBuilder namedNextTypeBuilder =
+          nextTypeBuilder as NamedTypeBuilder;
       Map<TypeVariableBuilder, TypeBuilder> substitution = {};
       int index = 0;
       if (currentTypeArguments == null || currentTypeArguments.isEmpty) {
         if (currentAliasBuilder.typeVariables != null) {
-          List<TypeBuilder> defaultTypeArguments = new List<TypeBuilder>.filled(
-              currentAliasBuilder.typeVariables.length, null,
-              growable: true);
-          for (int i = 0; i < defaultTypeArguments.length; ++i) {
-            defaultTypeArguments[i] =
-                currentAliasBuilder.typeVariables[i].defaultType;
-          }
+          List<TypeBuilder> defaultTypeArguments =
+              new List<TypeBuilder>.generate(
+                  currentAliasBuilder.typeVariables!.length, (int i) {
+            return currentAliasBuilder.typeVariables![i].defaultType!;
+          }, growable: false);
           currentTypeArguments = defaultTypeArguments;
         } else {
           currentTypeArguments = <TypeBuilder>[];
@@ -455,7 +467,7 @@
         substitution[typeVariableBuilder] = currentTypeArguments[index];
         ++index;
       }
-      TypeDeclarationBuilder nextDeclarationBuilder =
+      TypeDeclarationBuilder? nextDeclarationBuilder =
           namedNextTypeBuilder.declaration;
       TypeBuilder substitutedBuilder = nextTypeBuilder.subst(substitution);
       if (nextDeclarationBuilder is TypeVariableBuilder) {
@@ -463,8 +475,9 @@
         // type argument, which may become a type alias, possibly with its
         // own similar chain.
         assert(substitutedBuilder is NamedTypeBuilder);
-        NamedTypeBuilder namedSubstitutedBuilder = substitutedBuilder;
-        TypeDeclarationBuilder declarationBuilder =
+        NamedTypeBuilder namedSubstitutedBuilder =
+            substitutedBuilder as NamedTypeBuilder;
+        TypeDeclarationBuilder? declarationBuilder =
             namedSubstitutedBuilder.declaration;
         if (declarationBuilder is TypeAliasBuilder) {
           return declarationBuilder
@@ -474,7 +487,7 @@
         return namedSubstitutedBuilder.arguments ?? [];
       }
       // Not yet at the end of the chain, more named builders to come.
-      NamedTypeBuilder namedBuilder = substitutedBuilder;
+      NamedTypeBuilder namedBuilder = substitutedBuilder as NamedTypeBuilder;
       currentDeclarationBuilder = namedBuilder.declaration;
       currentTypeArguments = namedBuilder.arguments ?? [];
     }
diff --git a/pkg/front_end/lib/src/fasta/builder/type_builder.dart b/pkg/front_end/lib/src/fasta/builder/type_builder.dart
index 38ca1a7..11098cb 100644
--- a/pkg/front_end/lib/src/fasta/builder/type_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/type_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.type_builder;
 
 import 'package:kernel/ast.dart' show DartType, Supertype, TypedefType;
@@ -18,15 +16,15 @@
 abstract class TypeBuilder {
   const TypeBuilder();
 
-  TypeDeclarationBuilder get declaration => null;
+  TypeDeclarationBuilder? get declaration => null;
 
   /// Returns the Uri for the file in which this type annotation occurred, or
   /// `null` if the type was synthesized.
-  Uri get fileUri;
+  Uri? get fileUri;
 
   /// Returns the character offset with [fileUri] at which this type annotation
   /// occurred, or `null` if the type was synthesized.
-  int get charOffset;
+  int? get charOffset;
 
   void resolveIn(
       Scope scope, int charOffset, Uri fileUri, LibraryBuilder library) {}
@@ -37,7 +35,7 @@
   void bind(TypeDeclarationBuilder builder) {}
 
   /// May return null, for example, for mixin applications.
-  Object get name;
+  Object? get name;
 
   NullabilityBuilder get nullabilityBuilder;
 
@@ -70,16 +68,18 @@
   String get fullNameForErrors => "${printOn(new StringBuffer())}";
 
   DartType build(LibraryBuilder library,
-      [TypedefType origin, bool notInstanceContext]);
+      {TypedefType? origin, bool? nonInstanceContext});
 
   DartType buildTypeLiteralType(LibraryBuilder library,
-      [TypedefType origin, bool notInstanceContext]) {
-    return build(library, origin, notInstanceContext);
+      {TypedefType? origin, bool? nonInstanceContext}) {
+    return build(library,
+        origin: origin, nonInstanceContext: nonInstanceContext);
   }
 
-  Supertype buildSupertype(LibraryBuilder library, int charOffset, Uri fileUri);
+  Supertype? buildSupertype(
+      LibraryBuilder library, int charOffset, Uri fileUri);
 
-  Supertype buildMixedInType(
+  Supertype? buildMixedInType(
       LibraryBuilder library, int charOffset, Uri fileUri);
 
   TypeBuilder withNullabilityBuilder(NullabilityBuilder nullabilityBuilder);
diff --git a/pkg/front_end/lib/src/fasta/builder/type_declaration_builder.dart b/pkg/front_end/lib/src/fasta/builder/type_declaration_builder.dart
index 6490a73..727888b 100644
--- a/pkg/front_end/lib/src/fasta/builder/type_declaration_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/type_declaration_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.type_declaration_builder;
 
 import 'package:kernel/ast.dart' show DartType, Nullability;
@@ -16,21 +14,24 @@
 import 'type_builder.dart';
 
 abstract class TypeDeclarationBuilder implements ModifierBuilder {
+  @override
+  String get name;
+
   bool get isNamedMixinApplication;
 
-  void set parent(Builder value);
+  void set parent(Builder? value);
 
-  List<MetadataBuilder> get metadata;
+  List<MetadataBuilder>? get metadata;
 
   int get typeVariablesCount => 0;
 
   DartType buildType(LibraryBuilder library,
-      NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments,
-      [bool notInstanceContext]);
+      NullabilityBuilder nullabilityBuilder, List<TypeBuilder>? arguments,
+      {bool? nonInstanceContext});
 
   DartType buildTypeLiteralType(LibraryBuilder library,
-      NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments,
-      [bool notInstanceContext]);
+      NullabilityBuilder nullabilityBuilder, List<TypeBuilder>? arguments,
+      {bool? nonInstanceContext});
 
   /// [arguments] have already been built.
   DartType buildTypesWithBuiltArguments(LibraryBuilder library,
@@ -40,7 +41,7 @@
 abstract class TypeDeclarationBuilderImpl extends ModifierBuilderImpl
     implements TypeDeclarationBuilder {
   @override
-  final List<MetadataBuilder> metadata;
+  final List<MetadataBuilder>? metadata;
 
   @override
   final int modifiers;
@@ -49,10 +50,10 @@
   final String name;
 
   TypeDeclarationBuilderImpl(
-      this.metadata, this.modifiers, this.name, Builder parent, int charOffset,
-      [Uri fileUri])
+      this.metadata, this.modifiers, this.name, Builder? parent, int charOffset)
+      // ignore: unnecessary_null_comparison
       : assert(modifiers != null),
-        super(parent, charOffset, fileUri);
+        super(parent, charOffset);
 
   @override
   bool get isNamedMixinApplication => false;
@@ -68,9 +69,9 @@
 
   @override
   DartType buildTypeLiteralType(LibraryBuilder library,
-      NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments,
-      [bool notInstanceContext]) {
-    return buildType(
-        library, nullabilityBuilder, arguments, notInstanceContext);
+      NullabilityBuilder nullabilityBuilder, List<TypeBuilder>? arguments,
+      {bool? nonInstanceContext}) {
+    return buildType(library, nullabilityBuilder, arguments,
+        nonInstanceContext: nonInstanceContext);
   }
 }
diff --git a/pkg/front_end/lib/src/fasta/builder/type_variable_builder.dart b/pkg/front_end/lib/src/fasta/builder/type_variable_builder.dart
index c396c39..9d91421 100644
--- a/pkg/front_end/lib/src/fasta/builder/type_variable_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/type_variable_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.type_variable_builder;
 
 import 'package:kernel/ast.dart'
@@ -18,6 +16,7 @@
 import '../source/source_library_builder.dart';
 import '../util/helpers.dart';
 
+import 'builder.dart';
 import 'class_builder.dart';
 import 'declaration_builder.dart';
 import 'library_builder.dart';
@@ -29,26 +28,34 @@
 import 'type_declaration_builder.dart';
 
 class TypeVariableBuilder extends TypeDeclarationBuilderImpl {
-  TypeBuilder bound;
+  /// Sentinel value used to indicate that the variable has no name. This is
+  /// used for error recovery.
+  static const String noNameSentinel = 'no name sentinel';
 
-  TypeBuilder defaultType;
+  TypeBuilder? bound;
+
+  TypeBuilder? defaultType;
 
   final TypeParameter actualParameter;
 
-  TypeVariableBuilder actualOrigin;
+  TypeVariableBuilder? actualOrigin;
 
   final bool isExtensionTypeParameter;
 
-  TypeVariableBuilder(String name, SourceLibraryBuilder compilationUnit,
-      int charOffset, Uri fileUri,
+  @override
+  final Uri? fileUri;
+
+  TypeVariableBuilder(
+      String name, Builder? compilationUnit, int charOffset, this.fileUri,
       {this.bound,
       this.isExtensionTypeParameter: false,
-      int variableVariance,
-      List<MetadataBuilder> metadata})
-      : actualParameter = new TypeParameter(name, null)
-          ..fileOffset = charOffset
-          ..variance = variableVariance,
-        super(metadata, 0, name, compilationUnit, charOffset, fileUri);
+      int? variableVariance,
+      List<MetadataBuilder>? metadata})
+      : actualParameter =
+            new TypeParameter(name == noNameSentinel ? null : name, null)
+              ..fileOffset = charOffset
+              ..variance = variableVariance,
+        super(metadata, 0, name, compilationUnit, charOffset);
 
   TypeVariableBuilder.fromKernel(
       TypeParameter parameter, LibraryBuilder compilationUnit)
@@ -56,7 +63,9 @@
         // TODO(johnniwinther): Do we need to support synthesized type
         //  parameters from kernel?
         this.isExtensionTypeParameter = false,
-        super(null, 0, parameter.name, compilationUnit, parameter.fileOffset);
+        fileUri = compilationUnit.fileUri,
+        super(null, 0, parameter.name ?? '', compilationUnit,
+            parameter.fileOffset);
 
   bool get isTypeVariable => true;
 
@@ -66,7 +75,7 @@
     buffer.write(name);
     if (bound != null) {
       buffer.write(" extends ");
-      bound.printOn(buffer);
+      bound!.printOn(buffer);
     }
     return buffer;
   }
@@ -85,11 +94,11 @@
   }
 
   DartType buildType(LibraryBuilder library,
-      NullabilityBuilder nullabilityBuilder, List<TypeBuilder> arguments,
-      [bool notInstanceContext]) {
+      NullabilityBuilder nullabilityBuilder, List<TypeBuilder>? arguments,
+      {bool? nonInstanceContext}) {
     if (arguments != null) {
       int charOffset = -1; // TODO(ahe): Provide these.
-      Uri fileUri = null; // TODO(ahe): Provide these.
+      Uri? fileUri = null; // TODO(ahe): Provide these.
       library.addProblem(
           templateTypeArgumentsOnTypeVariable.withArguments(name),
           charOffset,
@@ -112,14 +121,15 @@
     } else {
       nullability = nullabilityBuilder.build(library);
     }
-    DartType type = buildTypesWithBuiltArguments(library, nullability, null);
+    TypeParameterType type =
+        buildTypesWithBuiltArguments(library, nullability, null);
     if (needsPostUpdate) {
       if (library is SourceLibraryBuilder) {
-        library.registerPendingNullability(fileUri, charOffset, type);
+        library.registerPendingNullability(fileUri!, charOffset, type);
       } else {
         library.addProblem(
             templateInternalProblemUnfinishedTypeVariable.withArguments(
-                name, library?.importUri),
+                name, library.importUri),
             charOffset,
             name.length,
             fileUri);
@@ -128,11 +138,11 @@
     return type;
   }
 
-  DartType buildTypesWithBuiltArguments(LibraryBuilder library,
-      Nullability nullability, List<DartType> arguments) {
+  TypeParameterType buildTypesWithBuiltArguments(LibraryBuilder library,
+      Nullability nullability, List<DartType>? arguments) {
     if (arguments != null) {
       int charOffset = -1; // TODO(ahe): Provide these.
-      Uri fileUri = null; // TODO(ahe): Provide these.
+      Uri? fileUri = null; // TODO(ahe): Provide these.
       library.addProblem(
           templateTypeArgumentsOnTypeVariable.withArguments(name),
           charOffset,
@@ -151,9 +161,8 @@
   void finish(
       LibraryBuilder library, ClassBuilder object, TypeBuilder dynamicType) {
     if (isPatch) return;
-    // TODO(jensj): Provide correct notInstanceContext.
     DartType objectType =
-        object.buildType(library, library.nullableBuilder, null, null);
+        object.buildType(library, library.nullableBuilder, null);
     if (identical(parameter.bound, TypeParameter.unsetBoundSentinel)) {
       parameter.bound = bound?.build(library) ?? objectType;
     }
@@ -181,19 +190,19 @@
     // TODO(dmitryas): Figure out if using [charOffset] here is a good idea.
     // An alternative is to use the offset of the node the cloned type variable
     // is declared on.
-    return new TypeVariableBuilder(name, parent, charOffset, fileUri,
+    return new TypeVariableBuilder(name, parent!, charOffset, fileUri,
         bound: bound?.clone(newTypes, contextLibrary, contextDeclaration),
         variableVariance: variance);
   }
 
   void buildOutlineExpressions(
-      LibraryBuilder libraryBuilder,
-      DeclarationBuilder classOrExtensionBuilder,
-      MemberBuilder memberBuilder,
+      SourceLibraryBuilder libraryBuilder,
+      DeclarationBuilder? classOrExtensionBuilder,
+      MemberBuilder? memberBuilder,
       CoreTypes coreTypes,
       List<DelayedActionPerformer> delayedActionPerformers) {
     MetadataBuilder.buildAnnotations(parameter, metadata, libraryBuilder,
-        classOrExtensionBuilder, memberBuilder, fileUri);
+        classOrExtensionBuilder, memberBuilder, fileUri!);
   }
 
   @override
@@ -204,14 +213,11 @@
   @override
   int get hashCode => parameter.hashCode;
 
-  static List<TypeParameter> typeParametersFromBuilders(
-      List<TypeVariableBuilder> builders) {
+  static List<TypeParameter>? typeParametersFromBuilders(
+      List<TypeVariableBuilder>? builders) {
     if (builders == null) return null;
-    List<TypeParameter> result =
-        new List<TypeParameter>.filled(builders.length, null, growable: true);
-    for (int i = 0; i < builders.length; i++) {
-      result[i] = builders[i].parameter;
-    }
-    return result;
+    return new List<TypeParameter>.generate(
+        builders.length, (int i) => builders[i].parameter,
+        growable: true);
   }
 }
diff --git a/pkg/front_end/lib/src/fasta/builder/unresolved_type.dart b/pkg/front_end/lib/src/fasta/builder/unresolved_type.dart
index 8925e6b..2639164 100644
--- a/pkg/front_end/lib/src/fasta/builder/unresolved_type.dart
+++ b/pkg/front_end/lib/src/fasta/builder/unresolved_type.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.unresolved_type;
 
 import '../scope.dart';
@@ -19,8 +17,9 @@
 
   UnresolvedType(this.builder, this.charOffset, this.fileUri);
 
-  void resolveIn(Scope scope, LibraryBuilder library) =>
-      builder.resolveIn(scope, charOffset, fileUri, library);
+  void resolveIn(Scope scope, LibraryBuilder library) {
+    builder.resolveIn(scope, charOffset, fileUri, library);
+  }
 
   /// Performs checks on the type after it's resolved.
   void checkType(LibraryBuilder library) {
diff --git a/pkg/front_end/lib/src/fasta/builder/variable_builder.dart b/pkg/front_end/lib/src/fasta/builder/variable_builder.dart
index cc006cb..9fe37eb 100644
--- a/pkg/front_end/lib/src/fasta/builder/variable_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/variable_builder.dart
@@ -9,7 +9,7 @@
 import '../builder/builder.dart';
 
 abstract class VariableBuilder implements Builder {
-  VariableDeclaration get variable;
+  VariableDeclaration? get variable;
 
   bool get isAssignable;
 }
diff --git a/pkg/front_end/lib/src/fasta/builder/void_type_declaration_builder.dart b/pkg/front_end/lib/src/fasta/builder/void_type_declaration_builder.dart
index b50507a..25c6760 100644
--- a/pkg/front_end/lib/src/fasta/builder/void_type_declaration_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/void_type_declaration_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.void_type_builder;
 
 import 'package:kernel/ast.dart' show DartType;
diff --git a/pkg/front_end/lib/src/fasta/crash.dart b/pkg/front_end/lib/src/fasta/crash.dart
index cc692ad..87f406a 100644
--- a/pkg/front_end/lib/src/fasta/crash.dart
+++ b/pkg/front_end/lib/src/fasta/crash.dart
@@ -115,7 +115,7 @@
 }
 
 Future<T> withCrashReporting<T>(
-    Future<T> Function() action, Uri Function() currentUri) async {
+    Future<T> Function() action, Uri? Function() currentUri) async {
   resetCrashReporting();
   try {
     return await action();
diff --git a/pkg/front_end/lib/src/fasta/dill/dill_class_builder.dart b/pkg/front_end/lib/src/fasta/dill/dill_class_builder.dart
index ea2e411..1918210 100644
--- a/pkg/front_end/lib/src/fasta/dill/dill_class_builder.dart
+++ b/pkg/front_end/lib/src/fasta/dill/dill_class_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.dill_class_builder;
 
 import 'package:kernel/ast.dart';
@@ -47,8 +45,10 @@
             parent,
             cls.fileOffset);
 
-  List<TypeVariableBuilder> get typeVariables {
-    List<TypeVariableBuilder> typeVariables = super.typeVariables;
+  DillLibraryBuilder get library => super.library as DillLibraryBuilder;
+
+  List<TypeVariableBuilder>? get typeVariables {
+    List<TypeVariableBuilder>? typeVariables = super.typeVariables;
     if (typeVariables == null && cls.typeParameters.isNotEmpty) {
       typeVariables = super.typeVariables =
           computeTypeVariableBuilders(library, cls.typeParameters);
@@ -58,10 +58,10 @@
 
   Uri get fileUri => cls.fileUri;
 
-  TypeBuilder get supertypeBuilder {
-    TypeBuilder supertype = super.supertypeBuilder;
+  TypeBuilder? get supertypeBuilder {
+    TypeBuilder? supertype = super.supertypeBuilder;
     if (supertype == null) {
-      Supertype targetSupertype = cls.supertype;
+      Supertype? targetSupertype = cls.supertype;
       if (targetSupertype == null) return null;
       super.supertypeBuilder =
           supertype = computeTypeBuilder(library, targetSupertype);
@@ -112,28 +112,23 @@
 
   @override
   List<DartType> buildTypeArguments(
-      LibraryBuilder library, List<TypeBuilder> arguments,
-      [bool notInstanceContext]) {
+      LibraryBuilder library, List<TypeBuilder>? arguments,
+      {bool? nonInstanceContext}) {
     // For performance reasons, [typeVariables] aren't restored from [target].
     // So, if [arguments] is null, the default types should be retrieved from
     // [cls.typeParameters].
     if (arguments == null) {
-      List<DartType> result = new List<DartType>.filled(
-          cls.typeParameters.length, null,
+      return new List<DartType>.generate(cls.typeParameters.length,
+          (int i) => cls.typeParameters[i].defaultType,
           growable: true);
-      for (int i = 0; i < result.length; ++i) {
-        result[i] = cls.typeParameters[i].defaultType;
-      }
-      return result;
     }
 
     // [arguments] != null
-    List<DartType> result =
-        new List<DartType>.filled(arguments.length, null, growable: true);
-    for (int i = 0; i < result.length; ++i) {
-      result[i] = arguments[i].build(library, null, notInstanceContext);
-    }
-    return result;
+    return new List<DartType>.generate(
+        arguments.length,
+        (int i) =>
+            arguments[i].build(library, nonInstanceContext: nonInstanceContext),
+        growable: true);
   }
 
   /// Returns true if this class is the result of applying a mixin to its
@@ -143,27 +138,28 @@
   @override
   bool get declaresConstConstructor => cls.hasConstConstructor;
 
-  TypeBuilder get mixedInTypeBuilder {
+  @override
+  TypeBuilder? get mixedInTypeBuilder {
     return computeTypeBuilder(library, cls.mixedInType);
   }
 
-  List<TypeBuilder> get interfaceBuilders {
+  @override
+  void set mixedInTypeBuilder(TypeBuilder? mixin) {
+    unimplemented("mixedInType=", -1, null);
+  }
+
+  List<TypeBuilder>? get interfaceBuilders {
     if (cls.implementedTypes.isEmpty) return null;
     if (super.interfaceBuilders == null) {
-      List<TypeBuilder> result =
-          new List<TypeBuilder>.filled(cls.implementedTypes.length, null);
-      for (int i = 0; i < result.length; i++) {
-        result[i] = computeTypeBuilder(library, cls.implementedTypes[i]);
-      }
+      List<TypeBuilder> result = new List<TypeBuilder>.generate(
+          cls.implementedTypes.length,
+          (int i) => computeTypeBuilder(library, cls.implementedTypes[i])!,
+          growable: false);
       super.interfaceBuilders = result;
     }
     return super.interfaceBuilders;
   }
 
-  void set mixedInTypeBuilder(TypeBuilder mixin) {
-    unimplemented("mixedInType=", -1, null);
-  }
-
   void clearCachedValues() {
     supertypeBuilder = null;
     interfaceBuilders = null;
@@ -175,26 +171,24 @@
   if (cls.isAbstract) {
     modifiers |= abstractMask;
   }
+  // ignore: unnecessary_null_comparison
   if (cls.isMixinApplication && cls.name != null) {
     modifiers |= namedMixinApplicationMask;
   }
   return modifiers;
 }
 
-TypeBuilder computeTypeBuilder(
-    DillLibraryBuilder library, Supertype supertype) {
+TypeBuilder? computeTypeBuilder(
+    DillLibraryBuilder library, Supertype? supertype) {
   return supertype == null
       ? null
       : library.loader.computeTypeBuilder(supertype.asInterfaceType);
 }
 
-List<TypeVariableBuilder> computeTypeVariableBuilders(
-    DillLibraryBuilder library, List<TypeParameter> typeParameters) {
+List<TypeVariableBuilder>? computeTypeVariableBuilders(
+    LibraryBuilder library, List<TypeParameter>? typeParameters) {
   if (typeParameters == null || typeParameters.length == 0) return null;
-  List<TypeVariableBuilder> result =
-      new List.filled(typeParameters.length, null);
-  for (int i = 0; i < result.length; i++) {
-    result[i] = new TypeVariableBuilder.fromKernel(typeParameters[i], library);
-  }
-  return result;
+  return new List.generate(typeParameters.length,
+      (int i) => new TypeVariableBuilder.fromKernel(typeParameters[i], library),
+      growable: false);
 }
diff --git a/pkg/front_end/lib/src/fasta/dill/dill_extension_builder.dart b/pkg/front_end/lib/src/fasta/dill/dill_extension_builder.dart
index 8da14de..94e7b8c 100644
--- a/pkg/front_end/lib/src/fasta/dill/dill_extension_builder.dart
+++ b/pkg/front_end/lib/src/fasta/dill/dill_extension_builder.dart
@@ -2,9 +2,6 @@
 // for 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 'package:front_end/src/fasta/util/helpers.dart';
 import 'package:kernel/ast.dart';
 import 'package:kernel/core_types.dart';
 
@@ -16,17 +13,19 @@
 
 import '../scope.dart';
 
+import '../util/helpers.dart';
+
 import 'dill_class_builder.dart';
 import 'dill_extension_member_builder.dart';
 
 class DillExtensionBuilder extends ExtensionBuilderImpl {
   final Extension extension;
-  List<TypeVariableBuilder> _typeParameters;
-  TypeBuilder _onType;
+  List<TypeVariableBuilder>? _typeParameters;
+  TypeBuilder? _onType;
 
   DillExtensionBuilder(this.extension, LibraryBuilder parent)
       : super(
-            null,
+            /* metadata = */ null,
             0,
             extension.name,
             parent,
@@ -36,11 +35,9 @@
                 setters: <String, MemberBuilder>{},
                 parent: parent.scope,
                 debugName: "extension ${extension.name}",
-                isModifiable: false),
-            null,
-            null) {
+                isModifiable: false)) {
     Map<Name, ExtensionMemberDescriptor> _methods = {};
-    Map<Name, Member> _tearOffs = {};
+    Map<Name, Procedure> _tearOffs = {};
     for (ExtensionMemberDescriptor descriptor in extension.members) {
       Name name = descriptor.name;
       switch (descriptor.kind) {
@@ -56,7 +53,7 @@
           }
           break;
         case ExtensionMemberKind.TearOff:
-          _tearOffs[name] = descriptor.member.asMember;
+          _tearOffs[name] = descriptor.member.asProcedure;
           break;
         case ExtensionMemberKind.Getter:
           Procedure procedure = descriptor.member.asProcedure;
@@ -87,12 +84,12 @@
       scopeBuilder.addMember(
           name.text,
           new DillExtensionInstanceMethodBuilder(
-              procedure, descriptor, this, _tearOffs[name]));
+              procedure, descriptor, this, _tearOffs[name]!));
     });
   }
 
   @override
-  List<TypeVariableBuilder> get typeParameters {
+  List<TypeVariableBuilder>? get typeParameters {
     if (_typeParameters == null && extension.typeParameters.isNotEmpty) {
       _typeParameters =
           computeTypeVariableBuilders(library, extension.typeParameters);
@@ -102,10 +99,7 @@
 
   @override
   TypeBuilder get onType {
-    if (_onType == null) {
-      _onType = library.loader.computeTypeBuilder(extension.onType);
-    }
-    return _onType;
+    return _onType ??= library.loader.computeTypeBuilder(extension.onType);
   }
 
   @override
diff --git a/pkg/front_end/lib/src/fasta/dill/dill_extension_member_builder.dart b/pkg/front_end/lib/src/fasta/dill/dill_extension_member_builder.dart
index 07a6d6a..c35ec2c 100644
--- a/pkg/front_end/lib/src/fasta/dill/dill_extension_member_builder.dart
+++ b/pkg/front_end/lib/src/fasta/dill/dill_extension_member_builder.dart
@@ -2,8 +2,6 @@
 // for 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 'package:kernel/ast.dart';
 
 import '../builder/builder.dart';
@@ -25,7 +23,7 @@
   String get name => _descriptor.name.text;
 
   @override
-  ProcedureKind get kind {
+  ProcedureKind? get kind {
     switch (_descriptor.kind) {
       case ExtensionMemberKind.Method:
         return ProcedureKind.Method;
@@ -55,7 +53,7 @@
   Member get readTarget => field;
 
   @override
-  Member get writeTarget => isAssignable ? field : null;
+  Member? get writeTarget => isAssignable ? field : null;
 
   @override
   Member get invokeTarget => field;
@@ -78,13 +76,13 @@
   Member get member => procedure;
 
   @override
-  Member get readTarget => null;
+  Member? get readTarget => null;
 
   @override
   Member get writeTarget => procedure;
 
   @override
-  Member get invokeTarget => null;
+  Member? get invokeTarget => null;
 }
 
 class DillExtensionGetterBuilder extends DillExtensionMemberBuilder {
@@ -101,7 +99,7 @@
   Member get readTarget => procedure;
 
   @override
-  Member get writeTarget => null;
+  Member? get writeTarget => null;
 
   @override
   Member get invokeTarget => procedure;
@@ -118,10 +116,10 @@
   Member get member => procedure;
 
   @override
-  Member get readTarget => null;
+  Member? get readTarget => null;
 
   @override
-  Member get writeTarget => null;
+  Member? get writeTarget => null;
 
   @override
   Member get invokeTarget => procedure;
@@ -143,7 +141,7 @@
   Member get readTarget => procedure;
 
   @override
-  Member get writeTarget => null;
+  Member? get writeTarget => null;
 
   @override
   Member get invokeTarget => procedure;
@@ -173,7 +171,7 @@
   Member get readTarget => _extensionTearOff;
 
   @override
-  Member get writeTarget => null;
+  Member? get writeTarget => null;
 
   @override
   Member get invokeTarget => procedure;
diff --git a/pkg/front_end/lib/src/fasta/dill/dill_library_builder.dart b/pkg/front_end/lib/src/fasta/dill/dill_library_builder.dart
index 031a9ea..c899e3df 100644
--- a/pkg/front_end/lib/src/fasta/dill/dill_library_builder.dart
+++ b/pkg/front_end/lib/src/fasta/dill/dill_library_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.dill_library_builder;
 
 import 'dart:convert' show jsonDecode;
@@ -14,6 +12,7 @@
         ConstantExpression,
         DartType,
         DynamicType,
+        Expression,
         Extension,
         Field,
         FunctionType,
@@ -67,7 +66,7 @@
 import 'dill_type_alias_builder.dart' show DillTypeAliasBuilder;
 
 class LazyLibraryScope extends LazyScope {
-  DillLibraryBuilder libraryBuilder;
+  DillLibraryBuilder? libraryBuilder;
 
   LazyLibraryScope.top({bool isModifiable: false})
       : super(<String, Builder>{}, <String, MemberBuilder>{}, null, "top",
@@ -76,7 +75,7 @@
   @override
   void ensureScope() {
     if (libraryBuilder == null) throw new StateError("No library builder.");
-    libraryBuilder.ensureLoaded();
+    libraryBuilder!.ensureLoaded();
   }
 }
 
@@ -90,7 +89,7 @@
   ///
   /// The elements of this map are documented in
   /// [../kernel/kernel_library_builder.dart].
-  Map<String, String> unserializableExports;
+  Map<String, String>? unserializableExports;
 
   // TODO(jensj): These 5 booleans could potentially be merged into a single
   // state field.
@@ -103,9 +102,9 @@
   DillLibraryBuilder(this.library, this.loader)
       : super(library.fileUri, new LazyLibraryScope.top(),
             new LazyLibraryScope.top()) {
-    LazyLibraryScope lazyScope = scope;
+    LazyLibraryScope lazyScope = scope as LazyLibraryScope;
     lazyScope.libraryBuilder = this;
-    LazyLibraryScope lazyExportScope = exportScope;
+    LazyLibraryScope lazyExportScope = exportScope as LazyLibraryScope;
     lazyExportScope.libraryBuilder = this;
   }
 
@@ -145,7 +144,7 @@
   Uri get fileUri => library.fileUri;
 
   @override
-  String get name => library.name;
+  String? get name => library.name;
 
   @override
   LibraryBuilder get nameOriginBuilder => this;
@@ -174,9 +173,10 @@
     cls.constructors.forEach(classBulder.addMember);
     for (Field field in cls.fields) {
       if (isRedirectingFactoryField(field)) {
-        ListLiteral initializer = field.initializer;
-        for (StaticGet get in initializer.expressions) {
-          RedirectingFactoryBody.restoreFromDill(get.target);
+        ListLiteral initializer = field.initializer as ListLiteral;
+        for (Expression expression in initializer.expressions) {
+          StaticGet get = expression as StaticGet;
+          RedirectingFactoryBody.restoreFromDill(get.target as Procedure);
         }
       } else {
         classBulder.addMember(field);
@@ -196,17 +196,18 @@
     }
     String name = member.name.text;
     if (name == "_exports#") {
-      Field field = member;
+      Field field = member as Field;
       String stringValue;
       if (field.initializer is ConstantExpression) {
-        ConstantExpression constantExpression = field.initializer;
-        StringConstant string = constantExpression.constant;
+        ConstantExpression constantExpression =
+            field.initializer as ConstantExpression;
+        StringConstant string = constantExpression.constant as StringConstant;
         stringValue = string.value;
       } else {
-        StringLiteral string = field.initializer;
+        StringLiteral string = field.initializer as StringLiteral;
         stringValue = string.value;
       }
-      Map<dynamic, dynamic> json = jsonDecode(stringValue);
+      Map<dynamic, dynamic>? json = jsonDecode(stringValue);
       unserializableExports =
           json != null ? new Map<String, String>.from(json) : null;
     } else {
@@ -246,21 +247,21 @@
   }
 
   @override
-  Builder addBuilder(String name, Builder declaration, int charOffset) {
+  Builder? addBuilder(String? name, Builder declaration, int charOffset) {
     if (name == null || name.isEmpty) return null;
 
     bool isSetter = declaration.isSetter;
     if (isSetter) {
-      scopeBuilder.addSetter(name, declaration);
+      scopeBuilder.addSetter(name, declaration as MemberBuilder);
     } else {
       scopeBuilder.addMember(name, declaration);
     }
     if (declaration.isExtension) {
-      scopeBuilder.addExtension(declaration);
+      scopeBuilder.addExtension(declaration as ExtensionBuilder);
     }
     if (!name.startsWith("_") && !name.contains('#')) {
       if (isSetter) {
-        exportScopeBuilder.addSetter(name, declaration);
+        exportScopeBuilder.addSetter(name, declaration as MemberBuilder);
       } else {
         exportScopeBuilder.addMember(name, declaration);
       }
@@ -269,7 +270,7 @@
   }
 
   void addTypedef(Typedef typedef) {
-    DartType type = typedef.type;
+    DartType? type = typedef.type;
     if (type is FunctionType && type.typedefType == null) {
       unhandled("null", "addTypedef", typedef.fileOffset, typedef.fileUri);
     }
@@ -321,10 +322,11 @@
         case "void":
           // TODO(ahe): It's likely that we shouldn't be exporting these types
           // from dart:core, and this case can be removed.
-          declaration = loader.coreLibrary.exportScopeBuilder[name];
+          declaration = loader.coreLibrary.exportScopeBuilder[name]!;
           break;
 
         default:
+          // ignore: unnecessary_null_comparison
           Message message = messageText == null
               ? templateTypeNotFound.withArguments(name)
               : templateUnspecified.withArguments(messageText);
@@ -337,24 +339,25 @@
       exportScopeBuilder.addMember(name, declaration);
     });
 
-    Map<Reference, Builder> sourceBuildersMap =
+    Map<Reference, Builder>? sourceBuildersMap =
         loader.currentSourceLoader?.buildersCreatedWithReferences;
     for (Reference reference in library.additionalExports) {
-      NamedNode node = reference.node;
+      NamedNode node = reference.node as NamedNode;
       Builder declaration;
       String name;
       if (sourceBuildersMap?.containsKey(reference) == true) {
-        declaration = sourceBuildersMap[reference];
+        declaration = sourceBuildersMap![reference]!;
+        // ignore: unnecessary_null_comparison
         assert(declaration != null);
         if (declaration is ModifierBuilder) {
-          name = declaration.name;
+          name = declaration.name!;
         } else {
           throw new StateError(
               "Unexpected: $declaration (${declaration.runtimeType}");
         }
 
         if (declaration.isSetter) {
-          exportScopeBuilder.addSetter(name, declaration);
+          exportScopeBuilder.addSetter(name, declaration as MemberBuilder);
         } else {
           exportScopeBuilder.addMember(name, declaration);
         }
@@ -380,7 +383,7 @@
         } else {
           unhandled("${node.runtimeType}", "finalizeExports", -1, fileUri);
         }
-        LibraryBuilder library = loader.builders[libraryUri];
+        LibraryBuilder? library = loader.builders[libraryUri];
         if (library == null) {
           internalProblem(
               templateUnspecified
@@ -390,13 +393,14 @@
         }
         if (isSetter) {
           declaration =
-              library.exportScope.lookupLocalMember(name, setter: true);
-          exportScopeBuilder.addSetter(name, declaration);
+              library.exportScope.lookupLocalMember(name, setter: true)!;
+          exportScopeBuilder.addSetter(name, declaration as MemberBuilder);
         } else {
           declaration =
-              library.exportScope.lookupLocalMember(name, setter: false);
+              library.exportScope.lookupLocalMember(name, setter: false)!;
           exportScopeBuilder.addMember(name, declaration);
         }
+        // ignore: unnecessary_null_comparison
         if (declaration == null) {
           internalProblem(
               templateUnspecified.withArguments(
diff --git a/pkg/front_end/lib/src/fasta/dill/dill_loader.dart b/pkg/front_end/lib/src/fasta/dill/dill_loader.dart
index 6835a1b..e76b8e2 100644
--- a/pkg/front_end/lib/src/fasta/dill/dill_loader.dart
+++ b/pkg/front_end/lib/src/fasta/dill/dill_loader.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.dill_loader;
 
 import 'package:kernel/ast.dart' show Class, Component, DartType, Library;
@@ -30,7 +28,7 @@
 import 'dill_target.dart' show DillTarget;
 
 class DillLoader extends Loader {
-  SourceLoader currentSourceLoader;
+  SourceLoader? currentSourceLoader;
 
   DillLoader(TargetImplementation target) : super(target);
 
@@ -40,11 +38,11 @@
   /// Append compiled libraries from the given [component]. If the [filter] is
   /// provided, append only libraries whose [Uri] is accepted by the [filter].
   List<DillLibraryBuilder> appendLibraries(Component component,
-      {bool filter(Uri uri), int byteCount: 0}) {
+      {bool Function(Uri uri)? filter, int byteCount: 0}) {
     List<Library> componentLibraries = component.libraries;
     List<Uri> requestedLibraries = <Uri>[];
     List<Uri> requestedLibrariesFileUri = <Uri>[];
-    DillTarget target = this.target;
+    DillTarget target = this.target as DillTarget;
     for (int i = 0; i < componentLibraries.length; i++) {
       Library library = componentLibraries[i];
       Uri uri = library.importUri;
@@ -57,8 +55,9 @@
     }
     List<DillLibraryBuilder> result = <DillLibraryBuilder>[];
     for (int i = 0; i < requestedLibraries.length; i++) {
-      result.add(read(requestedLibraries[i], -1,
-          fileUri: requestedLibrariesFileUri[i]));
+      result.add(
+          read(requestedLibraries[i], -1, fileUri: requestedLibrariesFileUri[i])
+              as DillLibraryBuilder);
     }
     target.uriToSource.addAll(component.uriToSource);
     this.byteCount += byteCount;
@@ -74,16 +73,18 @@
     libraries.add(library);
 
     // Weird interaction begins.
-    DillTarget target = this.target;
+    DillTarget target = this.target as DillTarget;
     // Create dill library builder (adds it to a map where it's fetched
     // again momentarily).
     target.addLibrary(library);
     // Set up the dill library builder (fetch it from the map again, add it to
     // another map and setup some auxiliary things).
-    return read(library.importUri, -1, fileUri: library.fileUri);
+    return read(library.importUri, -1, fileUri: library.fileUri)
+        as DillLibraryBuilder;
   }
 
   Future<Null> buildOutline(DillLibraryBuilder builder) async {
+    // ignore: unnecessary_null_comparison
     if (builder.library == null) {
       unhandled("null", "builder.library", 0, builder.fileUri);
     }
@@ -96,7 +97,7 @@
 
   void finalizeExports({bool suppressFinalizationErrors: false}) {
     for (LibraryBuilder builder in builders.values) {
-      DillLibraryBuilder library = builder;
+      DillLibraryBuilder library = builder as DillLibraryBuilder;
       library.markAsReadyToFinalizeExports(
           suppressFinalizationErrors: suppressFinalizationErrors);
     }
@@ -105,11 +106,11 @@
   @override
   ClassBuilder computeClassBuilderFromTargetClass(Class cls) {
     Library kernelLibrary = cls.enclosingLibrary;
-    LibraryBuilder library = builders[kernelLibrary.importUri];
+    LibraryBuilder? library = builders[kernelLibrary.importUri];
     if (library == null) {
       library = currentSourceLoader?.builders[kernelLibrary.importUri];
     }
-    return library.lookupLocalMember(cls.name, required: true);
+    return library!.lookupLocalMember(cls.name, required: true) as ClassBuilder;
   }
 
   @override
diff --git a/pkg/front_end/lib/src/fasta/dill/dill_member_builder.dart b/pkg/front_end/lib/src/fasta/dill/dill_member_builder.dart
index 9dcc279..37dd939 100644
--- a/pkg/front_end/lib/src/fasta/dill/dill_member_builder.dart
+++ b/pkg/front_end/lib/src/fasta/dill/dill_member_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.dill_member_builder;
 
 import 'package:kernel/ast.dart'
@@ -41,7 +39,7 @@
 
   bool get isConstructor => member is Constructor;
 
-  ProcedureKind get kind {
+  ProcedureKind? get kind {
     final Member member = this.member;
     return member is Procedure ? member.kind : null;
   }
@@ -58,7 +56,7 @@
 
   bool get isRedirectingGenerativeConstructor {
     return isConstructor &&
-        isRedirectingGenerativeConstructorImplementation(member);
+        isRedirectingGenerativeConstructorImplementation(member as Constructor);
   }
 
   bool get isSynthetic {
@@ -75,8 +73,8 @@
     throw new UnsupportedError('DillMemberBuilder.buildMembers');
   }
 
-  List<ClassMember> _localMembers;
-  List<ClassMember> _localSetters;
+  List<ClassMember>? _localMembers;
+  List<ClassMember>? _localSetters;
 
   @override
   List<ClassMember> get localMembers => _localMembers ??= isSetter
@@ -98,12 +96,13 @@
   Member get member => field;
 
   @override
-  Member get readTarget => field;
-  @override
-  Member get writeTarget => isAssignable ? field : null;
+  Member? get readTarget => field;
 
   @override
-  Member get invokeTarget => field;
+  Member? get writeTarget => isAssignable ? field : null;
+
+  @override
+  Member? get invokeTarget => field;
 
   bool get isField => true;
 
@@ -124,7 +123,7 @@
   Member get readTarget => procedure;
 
   @override
-  Member get writeTarget => null;
+  Member? get writeTarget => null;
 
   @override
   Member get invokeTarget => procedure;
@@ -140,13 +139,13 @@
   Member get member => procedure;
 
   @override
-  Member get readTarget => null;
+  Member? get readTarget => null;
 
   @override
   Member get writeTarget => procedure;
 
   @override
-  Member get invokeTarget => null;
+  Member? get invokeTarget => null;
 }
 
 class DillMethodBuilder extends DillMemberBuilder {
@@ -162,7 +161,7 @@
   Member get readTarget => procedure;
 
   @override
-  Member get writeTarget => null;
+  Member? get writeTarget => null;
 
   @override
   Member get invokeTarget => procedure;
@@ -178,10 +177,10 @@
   Member get member => procedure;
 
   @override
-  Member get readTarget => null;
+  Member? get readTarget => null;
 
   @override
-  Member get writeTarget => null;
+  Member? get writeTarget => null;
 
   @override
   Member get invokeTarget => procedure;
@@ -195,10 +194,10 @@
   Member get member => procedure;
 
   @override
-  Member get readTarget => null;
+  Member? get readTarget => null;
 
   @override
-  Member get writeTarget => null;
+  Member? get writeTarget => null;
 
   @override
   Member get invokeTarget => procedure;
@@ -214,10 +213,10 @@
   Constructor get member => constructor;
 
   @override
-  Member get readTarget => null;
+  Member? get readTarget => null;
 
   @override
-  Member get writeTarget => null;
+  Member? get writeTarget => null;
 
   @override
   Constructor get invokeTarget => constructor;
@@ -227,12 +226,13 @@
   @override
   final DillMemberBuilder memberBuilder;
 
-  Covariance _covariance;
+  Covariance? _covariance;
 
   @override
   final bool forSetter;
 
-  DillClassMember(this.memberBuilder, {this.forSetter})
+  DillClassMember(this.memberBuilder, {required this.forSetter})
+      // ignore: unnecessary_null_comparison
       : assert(forSetter != null);
 
   @override
diff --git a/pkg/front_end/lib/src/fasta/dill/dill_target.dart b/pkg/front_end/lib/src/fasta/dill/dill_target.dart
index 002f35d..089e3d4 100644
--- a/pkg/front_end/lib/src/fasta/dill/dill_target.dart
+++ b/pkg/front_end/lib/src/fasta/dill/dill_target.dart
@@ -2,19 +2,16 @@
 // for 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
-
 library fasta.dill_target;
 
-import 'package:front_end/src/fasta/builder/library_builder.dart'
-    show LibraryBuilder;
-
 import 'package:kernel/ast.dart' show Library;
 
 import 'package:kernel/target/targets.dart' show Target;
 
 import '../builder/class_builder.dart';
 
+import '../builder/library_builder.dart' show LibraryBuilder;
+
 import '../problems.dart' show unsupported;
 
 import '../source/source_library_builder.dart' show LanguageVersion;
@@ -35,7 +32,7 @@
 
   bool isLoaded = false;
 
-  DillLoader loader;
+  late final DillLoader loader;
 
   DillTarget(Ticker ticker, UriTranslator uriTranslator, Target backendTarget)
       : super(ticker, uriTranslator, backendTarget) {
@@ -67,14 +64,16 @@
   DillLibraryBuilder createLibraryBuilder(
       Uri uri,
       Uri fileUri,
-      Uri packageUri,
+      Uri? packageUri,
       LanguageVersion packageLanguageVersion,
-      LibraryBuilder origin,
-      Library referencesFrom,
-      bool referenceIsPartOwner) {
+      LibraryBuilder? origin,
+      Library? referencesFrom,
+      bool? referenceIsPartOwner) {
     assert(origin == null);
     assert(referencesFrom == null);
-    DillLibraryBuilder libraryBuilder = libraryBuilders.remove(uri);
+    DillLibraryBuilder libraryBuilder =
+        libraryBuilders.remove(uri) as DillLibraryBuilder;
+    // ignore: unnecessary_null_comparison
     assert(libraryBuilder != null, "No library found for $uri.");
     return libraryBuilder;
   }
diff --git a/pkg/front_end/lib/src/fasta/dill/dill_type_alias_builder.dart b/pkg/front_end/lib/src/fasta/dill/dill_type_alias_builder.dart
index 6b7b54b..f78420c 100644
--- a/pkg/front_end/lib/src/fasta/dill/dill_type_alias_builder.dart
+++ b/pkg/front_end/lib/src/fasta/dill/dill_type_alias_builder.dart
@@ -2,11 +2,8 @@
 // for 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
-
 library fasta.dill_typedef_builder;
 
-import 'package:front_end/src/fasta/util/helpers.dart';
 import 'package:kernel/ast.dart' show DartType, InvalidType, NullType, Typedef;
 import 'package:kernel/core_types.dart';
 
@@ -18,16 +15,18 @@
 
 import '../problems.dart' show unimplemented;
 
+import '../util/helpers.dart';
+
 import 'dill_class_builder.dart' show computeTypeVariableBuilders;
 import 'dill_library_builder.dart' show DillLibraryBuilder;
 
 class DillTypeAliasBuilder extends TypeAliasBuilderImpl {
   final Typedef typedef;
 
-  List<TypeVariableBuilder> _typeVariables;
-  TypeBuilder _type;
+  List<TypeVariableBuilder>? _typeVariables;
+  TypeBuilder? _type;
 
-  DartType thisType;
+  DartType? thisType;
 
   DillTypeAliasBuilder(this.typedef, DillLibraryBuilder parent)
       : super(null, typedef.name, parent, typedef.fileOffset);
@@ -36,7 +35,7 @@
     return unimplemented("metadata", -1, null);
   }
 
-  List<TypeVariableBuilder> get typeVariables {
+  List<TypeVariableBuilder>? get typeVariables {
     if (_typeVariables == null && typedef.typeParameters.isNotEmpty) {
       _typeVariables =
           computeTypeVariableBuilders(library, typedef.typeParameters);
@@ -54,41 +53,39 @@
   int get typeVariablesCount => typedef.typeParameters.length;
 
   @override
-  TypeBuilder get type {
+  TypeBuilder? get type {
     if (_type == null && typedef.type is! InvalidType) {
-      _type = library.loader.computeTypeBuilder(typedef.type);
+      _type = library.loader.computeTypeBuilder(typedef.type!);
     }
+    // TODO(johnniwinther): Support TypeBuilder for InvalidType.
     return _type;
   }
 
   @override
   DartType buildThisType() {
-    return thisType ??= typedef.type;
+    return thisType ??= typedef.type!;
   }
 
   @override
   List<DartType> buildTypeArguments(
-      LibraryBuilder library, List<TypeBuilder> arguments,
-      [bool notInstanceContext]) {
+      LibraryBuilder library, List<TypeBuilder>? arguments,
+      {bool? nonInstanceContext}) {
     // For performance reasons, [typeVariables] aren't restored from [target].
     // So, if [arguments] is null, the default types should be retrieved from
     // [cls.typeParameters].
     if (arguments == null) {
-      List<DartType> result = new List<DartType>.filled(
-          typedef.typeParameters.length, null,
-          growable: true);
-      for (int i = 0; i < result.length; ++i) {
-        result[i] = typedef.typeParameters[i].defaultType;
-      }
+      List<DartType> result =
+          new List<DartType>.generate(typedef.typeParameters.length, (int i) {
+        return typedef.typeParameters[i].defaultType;
+      }, growable: true);
       return result;
     }
 
     // [arguments] != null
     List<DartType> result =
-        new List<DartType>.filled(arguments.length, null, growable: true);
-    for (int i = 0; i < result.length; ++i) {
-      result[i] = arguments[i].build(library);
-    }
+        new List<DartType>.generate(arguments.length, (int i) {
+      return arguments[i].build(library);
+    }, growable: true);
     return result;
   }
 
diff --git a/pkg/front_end/lib/src/fasta/export.dart b/pkg/front_end/lib/src/fasta/export.dart
index 8ed7105..34a0ba9 100644
--- a/pkg/front_end/lib/src/fasta/export.dart
+++ b/pkg/front_end/lib/src/fasta/export.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.export;
 
 import 'builder/builder.dart';
@@ -19,7 +17,7 @@
   /// The library being exported.
   LibraryBuilder exported;
 
-  final List<Combinator> combinators;
+  final List<Combinator>? combinators;
 
   final int charOffset;
 
@@ -29,7 +27,7 @@
 
   bool addToExportScope(String name, Builder member) {
     if (combinators != null) {
-      for (Combinator combinator in combinators) {
+      for (Combinator combinator in combinators!) {
         if (combinator.isShow && !combinator.names.contains(name)) return false;
         if (combinator.isHide && combinator.names.contains(name)) return false;
       }
@@ -38,7 +36,7 @@
     if (changed) {
       if (exporter.isNonNullableByDefault) {
         // TODO(johnniwinther): Add a common interface for exportable builders.
-        Builder memberLibrary = member.parent;
+        Builder? memberLibrary = member.parent;
         if (memberLibrary is LibraryBuilder &&
             !memberLibrary.isNonNullableByDefault) {
           exporter.addProblem(
diff --git a/pkg/front_end/lib/src/fasta/identifiers.dart b/pkg/front_end/lib/src/fasta/identifiers.dart
index 422569a..1a8f681 100644
--- a/pkg/front_end/lib/src/fasta/identifiers.dart
+++ b/pkg/front_end/lib/src/fasta/identifiers.dart
@@ -64,7 +64,7 @@
 }
 
 void flattenQualifiedNameOn(
-    QualifiedName name, StringBuffer buffer, int charOffset, Uri fileUri) {
+    QualifiedName name, StringBuffer buffer, int charOffset, Uri? fileUri) {
   final Object qualifier = name.qualifier;
   if (qualifier is QualifiedName) {
     flattenQualifiedNameOn(qualifier, buffer, charOffset, fileUri);
@@ -80,7 +80,7 @@
   buffer.write(name.name);
 }
 
-String flattenName(Object name, int charOffset, Uri fileUri) {
+String flattenName(Object name, int charOffset, Uri? fileUri) {
   if (name is String) {
     return name;
   } else if (name is QualifiedName) {
diff --git a/pkg/front_end/lib/src/fasta/ignored_parser_errors.dart b/pkg/front_end/lib/src/fasta/ignored_parser_errors.dart
index fbd01f9..a711e7f 100644
--- a/pkg/front_end/lib/src/fasta/ignored_parser_errors.dart
+++ b/pkg/front_end/lib/src/fasta/ignored_parser_errors.dart
@@ -10,7 +10,7 @@
 
 import 'fasta_codes.dart' show Code, codeNonPartOfDirectiveInPart;
 
-bool isIgnoredParserError(Code<Object> code, Token token) {
+bool isIgnoredParserError(Code<dynamic> code, Token token) {
   if (code == codeNonPartOfDirectiveInPart) {
     // Ignored. This error is handled in the outline phase (part resolution).
     return optional("part", token);
diff --git a/pkg/front_end/lib/src/fasta/import.dart b/pkg/front_end/lib/src/fasta/import.dart
index 6a51033..439ec37 100644
--- a/pkg/front_end/lib/src/fasta/import.dart
+++ b/pkg/front_end/lib/src/fasta/import.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.import;
 
 import 'package:kernel/ast.dart' show LibraryDependency;
@@ -18,22 +16,24 @@
 
 import 'configuration.dart' show Configuration;
 
+import 'source/source_library_builder.dart';
+
 class Import {
   /// The library that is importing [imported];
-  final LibraryBuilder importer;
+  final SourceLibraryBuilder importer;
 
   /// The library being imported.
-  LibraryBuilder imported;
+  LibraryBuilder? imported;
 
-  final PrefixBuilder prefixBuilder;
+  final PrefixBuilder? prefixBuilder;
 
   final bool deferred;
 
-  final String prefix;
+  final String? prefix;
 
-  final List<Combinator> combinators;
+  final List<Combinator>? combinators;
 
-  final List<Configuration> configurations;
+  final List<Configuration>? configurations;
 
   final int charOffset;
 
@@ -41,7 +41,7 @@
 
   // The LibraryBuilder for the imported library ('imported') may be null when
   // this field is set.
-  final String nativeImportPath;
+  final String? nativeImportPath;
 
   Import(
       this.importer,
@@ -68,12 +68,12 @@
       };
     } else {
       add = (String name, Builder member) {
-        prefixBuilder.addToExportScope(name, member, charOffset);
+        prefixBuilder!.addToExportScope(name, member, charOffset);
       };
     }
-    imported.exportScope.forEach((String name, Builder member) {
+    imported!.exportScope.forEach((String name, Builder member) {
       if (combinators != null) {
-        for (Combinator combinator in combinators) {
+        for (Combinator combinator in combinators!) {
           if (combinator.isShow && !combinator.names.contains(name)) return;
           if (combinator.isHide && combinator.names.contains(name)) return;
         }
@@ -81,28 +81,28 @@
       add(name, member);
     });
     if (prefixBuilder != null) {
-      Builder existing =
-          importer.addBuilder(prefix, prefixBuilder, prefixCharOffset);
+      Builder? existing =
+          importer.addBuilder(prefix, prefixBuilder!, prefixCharOffset);
       if (existing == prefixBuilder) {
-        importer.addToScope(prefix, prefixBuilder, prefixCharOffset, true);
+        importer.addToScope(prefix!, prefixBuilder!, prefixCharOffset, true);
       }
     }
   }
 }
 
-PrefixBuilder createPrefixBuilder(
-    String prefix,
-    LibraryBuilder importer,
-    LibraryBuilder imported,
-    List<Combinator> combinators,
+PrefixBuilder? createPrefixBuilder(
+    String? prefix,
+    SourceLibraryBuilder importer,
+    LibraryBuilder? imported,
+    List<Combinator>? combinators,
     bool deferred,
     int charOffset,
     int prefixCharOffset,
     int importIndex) {
   if (prefix == null) return null;
-  LibraryDependency dependency = null;
+  LibraryDependency? dependency = null;
   if (deferred) {
-    dependency = new LibraryDependency.deferredImport(imported.library, prefix,
+    dependency = new LibraryDependency.deferredImport(imported!.library, prefix,
         combinators: toKernelCombinators(combinators))
       ..fileOffset = charOffset;
   }
diff --git a/pkg/front_end/lib/src/fasta/kernel/body_builder.dart b/pkg/front_end/lib/src/fasta/kernel/body_builder.dart
index e0342ae..2c4b9da 100644
--- a/pkg/front_end/lib/src/fasta/kernel/body_builder.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/body_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.body_builder;
 
 import 'package:_fe_analyzer_shared/src/flow_analysis/flow_analysis.dart';
@@ -34,7 +32,6 @@
 import 'package:_fe_analyzer_shared/src/parser/value_kind.dart';
 
 import 'package:_fe_analyzer_shared/src/scanner/scanner.dart' show Token;
-
 import 'package:_fe_analyzer_shared/src/scanner/token_impl.dart'
     show isBinaryOperator, isMinusOperator, isUserDefinableOperator;
 
@@ -50,6 +47,7 @@
 import '../builder/enum_builder.dart';
 import '../builder/extension_builder.dart';
 import '../builder/field_builder.dart';
+import '../builder/fixed_type_builder.dart';
 import '../builder/formal_parameter_builder.dart';
 import '../builder/function_builder.dart';
 import '../builder/function_type_builder.dart';
@@ -86,6 +84,8 @@
 import '../identifiers.dart'
     show Identifier, InitializedIdentifier, QualifiedName, flattenName;
 
+import '../kernel/utils.dart';
+
 import '../messages.dart' as messages show getLocationFromUri;
 
 import '../modifier.dart'
@@ -169,10 +169,10 @@
 
   /// The class, mixin or extension declaration in which [member] is declared,
   /// if any.
-  final DeclarationBuilder declarationBuilder;
+  final DeclarationBuilder? declarationBuilder;
 
   /// The class or mixin declaration in which [member] is declared, if any.
-  final ClassBuilder classBuilder;
+  final ClassBuilder? classBuilder;
 
   final ClassHierarchy hierarchy;
 
@@ -217,7 +217,7 @@
   ///    initializer. This avoids cascading errors.
   bool needsImplicitSuperInitializer;
 
-  Scope formalParameterScope;
+  Scope? formalParameterScope;
 
   /// This is set to true when we start parsing an initializer. We use this to
   /// find the correct scope for initializers like in this example:
@@ -280,7 +280,7 @@
 
   Link<bool> _localInitializerState = const Link<bool>().prepend(false);
 
-  List<Initializer> _initializers;
+  List<Initializer>? _initializers;
 
   bool inCatchClause = false;
 
@@ -296,15 +296,15 @@
   // transformed because the backend target does not support set literals.
   bool transformSetLiterals = false;
 
-  Statement problemInLoopOrSwitch;
+  Statement? problemInLoopOrSwitch;
 
-  Scope switchScope;
+  Scope? switchScope;
 
-  CloneVisitorNotMembers cloner;
+  CloneVisitorNotMembers? cloner;
 
   ConstantContext constantContext = ConstantContext.none;
 
-  UnresolvedType currentLocalVariableType;
+  UnresolvedType? currentLocalVariableType;
 
   // Using non-null value to initialize this field based on performance advice
   // from VM engineers. TODO(ahe): Does this still apply?
@@ -312,18 +312,20 @@
 
   /// If non-null, records instance fields which have already been initialized
   /// and where that was.
-  Map<String, int> initializedFields;
+  Map<String, int>? initializedFields;
 
   /// List of built redirecting factory invocations.  The targets of the
   /// invocations are to be resolved in a separate step.
-  final List<Expression> redirectingFactoryInvocations = <Expression>[];
+  final List<StaticInvocation> redirectingFactoryInvocations =
+      <StaticInvocation>[];
 
   /// List of redirecting factory invocations delayed for resolution.
   ///
   /// A resolution of a redirecting factory invocation can be delayed because
   /// the inference in the declaration of the redirecting factory isn't done
   /// yet.
-  final List<Expression> delayedRedirectingFactoryInvocations = <Expression>[];
+  final List<StaticInvocation> delayedRedirectingFactoryInvocations =
+      <StaticInvocation>[];
 
   /// List of built type aliased generative constructor invocations that
   /// require unaliasing.
@@ -337,32 +339,32 @@
 
   /// Variables with metadata.  Their types need to be inferred late, for
   /// example, in [finishFunction].
-  List<VariableDeclaration> variablesWithMetadata;
+  List<VariableDeclaration>? variablesWithMetadata;
 
   /// More than one variable declared in a single statement that has metadata.
   /// Their types need to be inferred late, for example, in [finishFunction].
-  List<List<VariableDeclaration>> multiVariablesWithMetadata;
+  List<List<VariableDeclaration>>? multiVariablesWithMetadata;
 
   /// If the current member is an instance member in an extension declaration,
   /// [extensionThis] holds the synthetically add parameter holding the value
   /// for `this`.
-  final VariableDeclaration extensionThis;
+  final VariableDeclaration? extensionThis;
 
-  final List<TypeParameter> extensionTypeParameters;
+  final List<TypeParameter>? extensionTypeParameters;
 
   BodyBuilder(
-      {this.libraryBuilder,
-      this.member,
-      this.enclosingScope,
+      {required this.libraryBuilder,
+      required this.member,
+      required this.enclosingScope,
       this.formalParameterScope,
-      this.hierarchy,
-      this.coreTypes,
+      required this.hierarchy,
+      required this.coreTypes,
       this.declarationBuilder,
-      this.isDeclarationInstanceMember,
+      required this.isDeclarationInstanceMember,
       this.extensionThis,
       this.extensionTypeParameters,
-      this.uri,
-      this.typeInferrer})
+      required this.uri,
+      required this.typeInferrer})
       : forest = const Forest(),
         classBuilder =
             declarationBuilder is ClassBuilder ? declarationBuilder : null,
@@ -375,17 +377,17 @@
                 (libraryBuilder.importUri.path == "_builtin" ||
                     libraryBuilder.importUri.path == "ui"),
         needsImplicitSuperInitializer = declarationBuilder is ClassBuilder &&
-            coreTypes?.objectClass != declarationBuilder.cls,
+            coreTypes.objectClass != declarationBuilder.cls,
         super(enclosingScope) {
     formalParameterScope?.forEach((String name, Builder builder) {
       if (builder is VariableBuilder) {
-        typeInferrer?.assignedVariables?.declare(builder.variable);
+        typeInferrer.assignedVariables.declare(builder.variable!);
       }
     });
   }
 
   BodyBuilder.withParents(FieldBuilder field, SourceLibraryBuilder part,
-      DeclarationBuilder declarationBuilder, TypeInferrer typeInferrer)
+      DeclarationBuilder? declarationBuilder, TypeInferrer typeInferrer)
       : this(
             libraryBuilder: part,
             member: field,
@@ -396,21 +398,23 @@
             declarationBuilder: declarationBuilder,
             isDeclarationInstanceMember: field.isDeclarationInstanceMember,
             extensionThis: null,
-            uri: field.fileUri,
+            uri: field.fileUri!,
             typeInferrer: typeInferrer);
 
   BodyBuilder.forField(FieldBuilder field, TypeInferrer typeInferrer)
       : this.withParents(
             field,
             field.parent is DeclarationBuilder
-                ? field.parent.parent
-                : field.parent,
-            field.parent is DeclarationBuilder ? field.parent : null,
+                ? field.parent!.parent as SourceLibraryBuilder
+                : field.parent as SourceLibraryBuilder,
+            field.parent is DeclarationBuilder
+                ? field.parent as DeclarationBuilder
+                : null,
             typeInferrer);
 
   BodyBuilder.forOutlineExpression(
       SourceLibraryBuilder library,
-      DeclarationBuilder declarationBuilder,
+      DeclarationBuilder? declarationBuilder,
       ModifierBuilder member,
       Scope scope,
       Uri fileUri)
@@ -422,12 +426,11 @@
             hierarchy: library.loader.hierarchy,
             coreTypes: library.loader.coreTypes,
             declarationBuilder: declarationBuilder,
-            isDeclarationInstanceMember:
-                member?.isDeclarationInstanceMember ?? false,
+            isDeclarationInstanceMember: member.isDeclarationInstanceMember,
             extensionThis: null,
             uri: fileUri,
             typeInferrer: library.loader.typeInferenceEngine
-                ?.createLocalTypeInferrer(
+                .createLocalTypeInferrer(
                     fileUri, declarationBuilder?.thisType, library, null));
 
   bool get inConstructor {
@@ -438,7 +441,7 @@
     return isDeclarationInstanceMember || member is ConstructorBuilder;
   }
 
-  TypeEnvironment get typeEnvironment => typeInferrer?.typeSchemaEnvironment;
+  TypeEnvironment get typeEnvironment => typeInferrer.typeSchemaEnvironment;
 
   DartType get implicitTypeArgument => const ImplicitTypeArgument();
 
@@ -463,24 +466,25 @@
   }
 
   void _exitLocalState() {
-    _localInitializerState = _localInitializerState.tail;
+    _localInitializerState = _localInitializerState.tail!;
   }
 
   @override
   void registerVariableAssignment(VariableDeclaration variable) {
-    typeInferrer?.assignedVariables?.write(variable);
+    typeInferrer.assignedVariables.write(variable);
   }
 
   @override
-  VariableDeclaration createVariableDeclarationForValue(Expression expression) {
-    VariableDeclaration variable =
+  VariableDeclarationImpl createVariableDeclarationForValue(
+      Expression expression) {
+    VariableDeclarationImpl variable =
         forest.createVariableDeclarationForValue(expression);
-    typeInferrer?.assignedVariables?.declare(variable);
+    typeInferrer.assignedVariables.declare(variable);
     return variable;
   }
 
   @override
-  void push(Object node) {
+  void push(Object? node) {
     if (node is DartType) {
       unhandled("DartType", "push", -1, uri);
     }
@@ -492,12 +496,12 @@
 
   Expression popForEffect() => toEffect(pop());
 
-  Expression popForValueIfNotNull(Object value) {
+  Expression? popForValueIfNotNull(Object? value) {
     return value == null ? null : popForValue();
   }
 
   @override
-  Expression toValue(Object node) {
+  Expression toValue(Object? node) {
     if (node is Generator) {
       return node.buildSimpleRead();
     } else if (node is Expression) {
@@ -512,14 +516,14 @@
     }
   }
 
-  Expression toEffect(Object node) {
+  Expression toEffect(Object? node) {
     if (node is Generator) return node.buildForEffect();
     return toValue(node);
   }
 
   List<Expression> popListForValue(int n) {
     List<Expression> list =
-        new List<Expression>.filled(n, null, growable: true);
+        new List<Expression>.filled(n, dummyExpression, growable: true);
     for (int i = n - 1; i >= 0; i--) {
       list[i] = popForValue();
     }
@@ -528,25 +532,27 @@
 
   List<Expression> popListForEffect(int n) {
     List<Expression> list =
-        new List<Expression>.filled(n, null, growable: true);
+        new List<Expression>.filled(n, dummyExpression, growable: true);
     for (int i = n - 1; i >= 0; i--) {
       list[i] = popForEffect();
     }
     return list;
   }
 
-  Statement popBlock(int count, Token openBrace, Token closeBrace) {
+  Statement popBlock(int count, Token openBrace, Token? closeBrace) {
     return forest.createBlock(
         offsetForToken(openBrace),
         offsetForToken(closeBrace),
-        const GrowableList<Statement>().pop(stack, count) ?? <Statement>[]);
+        const GrowableList<Statement>()
+                .popNonNullable(stack, count, dummyStatement) ??
+            <Statement>[]);
   }
 
-  Statement popStatementIfNotNull(Object value) {
+  Statement? popStatementIfNotNull(Object? value) {
     return value == null ? null : popStatement();
   }
 
-  Statement popStatement() => forest.wrapVariables(pop());
+  Statement popStatement() => forest.wrapVariables(pop() as Statement);
 
   void enterSwitchScope() {
     push(switchScope ?? NullValue.SwitchScope);
@@ -554,13 +560,13 @@
   }
 
   void exitSwitchScope() {
-    Scope outerSwitchScope = pop();
-    if (switchScope.unclaimedForwardDeclarations != null) {
-      switchScope.unclaimedForwardDeclarations
+    Scope? outerSwitchScope = pop() as Scope?;
+    if (switchScope!.unclaimedForwardDeclarations != null) {
+      switchScope!.unclaimedForwardDeclarations!
           .forEach((String name, JumpTarget declaration) {
         if (outerSwitchScope == null) {
           for (Statement statement in declaration.users) {
-            statement.parent.replaceChild(
+            statement.parent!.replaceChild(
                 statement,
                 wrapInProblemStatement(statement,
                     fasta.templateLabelNotFound.withArguments(name)));
@@ -577,7 +583,7 @@
       VariableDeclaration variable,
       Template<Message Function(String name)> template,
       List<LocatedMessage> context) {
-    String name = variable.name;
+    String name = variable.name!;
     int offset = variable.fileOffset;
     Message message = template.withArguments(name);
     if (variable.initializer == null) {
@@ -586,15 +592,15 @@
             ..parent = variable;
     } else {
       variable.initializer = wrapInLocatedProblem(
-          variable.initializer, message.withLocation(uri, offset, name.length),
+          variable.initializer!, message.withLocation(uri, offset, name.length),
           context: context)
         ..parent = variable;
     }
   }
 
   void declareVariable(VariableDeclaration variable, Scope scope) {
-    String name = variable.name;
-    Builder existing = scope.lookupLocalMember(name, setter: false);
+    String name = variable.name!;
+    Builder? existing = scope.lookupLocalMember(name, setter: false);
     if (existing != null) {
       // This reports an error for duplicated declarations in the same scope:
       // `{ var x; var x; }`
@@ -606,11 +612,8 @@
       ]);
       return;
     }
-    LocatedMessage context = scope.declare(
-        variable.name,
-        new VariableBuilderImpl(
-            variable, member ?? classBuilder ?? libraryBuilder, uri),
-        uri);
+    LocatedMessage? context = scope.declare(
+        variable.name!, new VariableBuilderImpl(variable, member, uri), uri);
     if (context != null) {
       // This case is different from the above error. In this case, the problem
       // is using `x` before it's declared: `{ var x; { print(x); var x;
@@ -625,12 +628,13 @@
 
   @override
   JumpTarget createJumpTarget(JumpTargetKind kind, int charOffset) {
-    return new JumpTarget(kind, functionNestingLevel, member, charOffset);
+    return new JumpTarget(
+        kind, functionNestingLevel, member as MemberBuilder, charOffset);
   }
 
-  void inferAnnotations(TreeNode parent, List<Expression> annotations) {
+  void inferAnnotations(TreeNode? parent, List<Expression>? annotations) {
     if (annotations != null) {
-      typeInferrer?.inferMetadata(this, parent, annotations);
+      typeInferrer.inferMetadata(this, parent, annotations);
       libraryBuilder.loader.transformListPostInference(annotations,
           transformSetLiterals, transformCollections, libraryBuilder.library);
     }
@@ -644,37 +648,37 @@
   }
 
   @override
-  void endMetadata(Token beginToken, Token periodBeforeName, Token endToken) {
+  void endMetadata(Token beginToken, Token? periodBeforeName, Token endToken) {
     debugEvent("Metadata");
-    Arguments arguments = pop();
-    pushQualifiedReference(beginToken.next, periodBeforeName);
+    Arguments? arguments = pop() as Arguments?;
+    pushQualifiedReference(beginToken.next!, periodBeforeName);
     if (arguments != null) {
       push(arguments);
       _buildConstructorReferenceInvocation(
-          beginToken.next, beginToken.offset, Constness.explicitConst,
+          beginToken.next!, beginToken.offset, Constness.explicitConst,
           inMetadata: true);
       push(popForValue());
     } else {
       pop(); // Name last identifier
-      String name = pop();
+      String? name = pop() as String?;
       pop(); // Type arguments (ignored, already reported by parser).
-      Object expression = pop();
+      Object? expression = pop();
       if (expression is Identifier) {
         Identifier identifier = expression;
         expression = new UnresolvedNameGenerator(this, identifier.token,
             new Name(identifier.name, libraryBuilder.nameOrigin));
       }
       if (name?.isNotEmpty ?? false) {
-        Token period = periodBeforeName ?? beginToken.next.next;
-        Generator generator = expression;
+        Token period = periodBeforeName ?? beginToken.next!.next!;
+        Generator generator = expression as Generator;
         expression = generator.buildPropertyAccess(
             new IncompletePropertyAccessGenerator(
-                this, period.next, new Name(name, libraryBuilder.nameOrigin)),
-            period.next.offset,
+                this, period.next!, new Name(name!, libraryBuilder.nameOrigin)),
+            period.next!.offset,
             false);
       }
 
-      ConstantContext savedConstantContext = pop();
+      ConstantContext savedConstantContext = pop() as ConstantContext;
       if (expression is! StaticAccessGenerator &&
           expression is! VariableUseGenerator &&
           // TODO(johnniwinther): Stop using the type of the generator here.
@@ -705,11 +709,11 @@
 
   @override
   void endTopLevelFields(
-      Token externalToken,
-      Token staticToken,
-      Token covariantToken,
-      Token lateToken,
-      Token varFinalOrConst,
+      Token? externalToken,
+      Token? staticToken,
+      Token? covariantToken,
+      Token? lateToken,
+      Token? varFinalOrConst,
       int count,
       Token beginToken,
       Token endToken) {
@@ -726,12 +730,12 @@
 
   @override
   void endClassFields(
-      Token abstractToken,
-      Token externalToken,
-      Token staticToken,
-      Token covariantToken,
-      Token lateToken,
-      Token varFinalOrConst,
+      Token? abstractToken,
+      Token? externalToken,
+      Token? staticToken,
+      Token? covariantToken,
+      Token? lateToken,
+      Token? varFinalOrConst,
       int count,
       Token beginToken,
       Token endToken) {
@@ -753,22 +757,22 @@
   @override
   void finishFields() {
     debugEvent("finishFields");
-    int count = pop();
+    int count = pop() as int;
     List<FieldBuilder> fields = <FieldBuilder>[];
     for (int i = 0; i < count; i++) {
-      Expression initializer = pop();
-      Identifier identifier = pop();
+      Expression? initializer = pop() as Expression?;
+      Identifier identifier = pop() as Identifier;
       String name = identifier.name;
       Builder declaration;
       if (declarationBuilder != null) {
         declaration =
-            declarationBuilder.lookupLocalMember(name, required: true);
+            declarationBuilder!.lookupLocalMember(name, required: true)!;
       } else {
-        declaration = libraryBuilder.lookupLocalMember(name, required: true);
+        declaration = libraryBuilder.lookupLocalMember(name, required: true)!;
       }
       FieldBuilder fieldBuilder;
       if (declaration.isField && declaration.next == null) {
-        fieldBuilder = declaration;
+        fieldBuilder = declaration as FieldBuilder;
       } else {
         continue;
       }
@@ -783,7 +787,7 @@
           // outline, like constant field initializers) so we do not need to
           // perform type inference or transformations.
         } else {
-          initializer = typeInferrer?.inferFieldInitializer(
+          initializer = typeInferrer.inferFieldInitializer(
               this, fieldBuilder.builtType, initializer);
 
           if (transformCollections || transformSetLiterals) {
@@ -811,7 +815,10 @@
       // not calling [buildDartType] leads to a missing compile-time
       // error. Also, notice that the type of the problematic field isn't
       // `invalid-type`.
-      buildDartType(pop()); // Type.
+      UnresolvedType? type = pop() as UnresolvedType?;
+      if (type != null) {
+        buildDartType(type);
+      }
     }
     pop(); // Annotations.
 
@@ -825,7 +832,7 @@
   }
 
   @override
-  void endBlockFunctionBody(int count, Token openBrace, Token closeBrace) {
+  void endBlockFunctionBody(int count, Token? openBrace, Token closeBrace) {
     debugEvent("BlockFunctionBody");
     if (openBrace == null) {
       assert(count == 0);
@@ -838,12 +845,12 @@
   }
 
   void prepareInitializers() {
-    FunctionBuilder member = this.member;
+    FunctionBuilder member = this.member as FunctionBuilder;
     scope = member.computeFormalParameterInitializerScope(scope);
     if (member is ConstructorBuilder) {
       member.prepareInitializers();
       if (member.formals != null) {
-        for (FormalParameterBuilder formal in member.formals) {
+        for (FormalParameterBuilder formal in member.formals!) {
           if (formal.isInitializingFormal) {
             List<Initializer> initializers;
             if (member.isExternal) {
@@ -860,7 +867,7 @@
                   formal.name,
                   formal.charOffset,
                   formal.charOffset,
-                  new VariableGet(formal.variable),
+                  new VariableGet(formal.variable!),
                   formal: formal);
             }
             for (Initializer initializer in initializers) {
@@ -877,7 +884,7 @@
     debugEvent("NoInitializers");
     if (functionNestingLevel == 0) {
       prepareInitializers();
-      scope = formalParameterScope;
+      scope = formalParameterScope ?? new Scope.immutable();
     }
   }
 
@@ -893,7 +900,7 @@
   void endInitializers(int count, Token beginToken, Token endToken) {
     debugEvent("Initializers");
     if (functionNestingLevel == 0) {
-      scope = formalParameterScope;
+      scope = formalParameterScope ?? new Scope.immutable();
     }
   }
 
@@ -909,7 +916,7 @@
     debugEvent("endInitializer");
     inFieldInitializer = false;
     assert(!inInitializer);
-    Object node = pop();
+    Object? node = pop();
     List<Initializer> initializers;
 
     final ModifierBuilder member = this.member;
@@ -932,11 +939,13 @@
             value.fileOffset, noLength);
       }
       initializers = <Initializer>[
-        buildInvalidInitializer(node, token.charOffset)
+        // TODO(johnniwinther): This should probably be [value] instead of
+        //  [node].
+        buildInvalidInitializer(node as Expression, token.charOffset)
       ];
     }
     _initializers ??= <Initializer>[];
-    _initializers.addAll(initializers);
+    _initializers!.addAll(initializers);
   }
 
   DartType _computeReturnTypeContext(MemberBuilder member) {
@@ -950,22 +959,22 @@
 
   @override
   void finishFunction(
-      FormalParameters formals, AsyncMarker asyncModifier, Statement body) {
+      FormalParameters? formals, AsyncMarker asyncModifier, Statement? body) {
     debugEvent("finishFunction");
-    typeInferrer?.assignedVariables?.finish();
+    typeInferrer.assignedVariables.finish();
 
-    FunctionBuilder builder = member;
+    final FunctionBuilder builder = member as FunctionBuilder;
     if (extensionThis != null) {
-      typeInferrer?.flowAnalysis?.declare(extensionThis, true);
+      typeInferrer.flowAnalysis.declare(extensionThis!, true);
     }
     if (formals?.parameters != null) {
-      for (int i = 0; i < formals.parameters.length; i++) {
-        FormalParameterBuilder parameter = formals.parameters[i];
-        typeInferrer?.flowAnalysis?.declare(parameter.variable, true);
+      for (int i = 0; i < formals!.parameters!.length; i++) {
+        FormalParameterBuilder parameter = formals.parameters![i];
+        typeInferrer.flowAnalysis.declare(parameter.variable!, true);
       }
-      for (int i = 0; i < formals.parameters.length; i++) {
-        FormalParameterBuilder parameter = formals.parameters[i];
-        Expression initializer = parameter.variable.initializer;
+      for (int i = 0; i < formals.parameters!.length; i++) {
+        FormalParameterBuilder parameter = formals.parameters![i];
+        Expression? initializer = parameter.variable!.initializer;
         if (parameter.isOptional || initializer != null) {
           if (!parameter.initializerWasInferred) {
             parameter.initializerWasInferred = true;
@@ -976,9 +985,9 @@
                   noLocation);
             }
             VariableDeclaration originParameter = builder.getFormalParameter(i);
-            initializer = typeInferrer?.inferParameterInitializer(
+            initializer = typeInferrer.inferParameterInitializer(
                 this,
-                initializer,
+                initializer!,
                 originParameter.type,
                 parameter.hasDeclaredInitializer);
             originParameter.initializer = initializer..parent = originParameter;
@@ -989,11 +998,11 @@
                 libraryBuilder.library);
           }
 
-          VariableDeclaration extensionTearOffParameter =
+          VariableDeclaration? extensionTearOffParameter =
               builder.getExtensionTearOffParameter(i);
           if (extensionTearOffParameter != null) {
             cloner ??= new CloneVisitorNotMembers();
-            Expression tearOffInitializer = cloner.clone(initializer);
+            Expression tearOffInitializer = cloner!.clone(initializer!);
             extensionTearOffParameter.initializer = tearOffInitializer
               ..parent = extensionTearOffParameter;
             libraryBuilder.loader.transformPostInference(
@@ -1014,12 +1023,12 @@
           builder.fileUri);
     }
 
-    InferredFunctionBody inferredFunctionBody;
+    InferredFunctionBody? inferredFunctionBody;
     if (body != null) {
-      inferredFunctionBody = typeInferrer?.inferFunctionBody(
+      inferredFunctionBody = typeInferrer.inferFunctionBody(
           this,
-          member.charOffset,
-          _computeReturnTypeContext(member),
+          builder.charOffset,
+          _computeReturnTypeContext(builder),
           asyncModifier,
           body);
       body = inferredFunctionBody.body;
@@ -1030,13 +1039,13 @@
 
     if (builder.returnType != null) {
       checkAsyncReturnType(asyncModifier, builder.function.returnType,
-          member.charOffset, member.name.length);
+          builder.charOffset, builder.name.length);
     }
 
     if (builder.kind == ProcedureKind.Setter) {
       if (formals?.parameters == null ||
-          formals.parameters.length != 1 ||
-          formals.parameters.single.isOptional) {
+          formals!.parameters!.length != 1 ||
+          formals.parameters!.single.isOptional) {
         int charOffset = formals?.charOffset ??
             body?.fileOffset ??
             builder.member.fileOffset;
@@ -1047,8 +1056,8 @@
           // Illegal parameters were removed by the function builder.
           // Add them as local variable to put them in scope of the body.
           List<Statement> statements = <Statement>[];
-          for (FormalParameterBuilder parameter in builder.formals) {
-            statements.add(parameter.variable);
+          for (FormalParameterBuilder parameter in builder.formals!) {
+            statements.add(parameter.variable!);
           }
           statements.add(body);
           body = forest.createBlock(charOffset, noLocation, statements);
@@ -1097,7 +1106,7 @@
     // for every T.
 
     // We use [problem == null] to signal success.
-    Message problem;
+    Message? problem;
     switch (asyncModifier) {
       case AsyncMarker.Async:
         DartType futureBottomType = libraryBuilder.loader.futureOfBottom;
@@ -1132,7 +1141,6 @@
       case AsyncMarker.SyncYielding:
         unexpected("async, async*, sync, or sync*", "$asyncModifier",
             member.charOffset, uri);
-        break;
     }
 
     if (problem != null) {
@@ -1151,10 +1159,10 @@
   ///    transformation needed has been performed); and
   /// b) The library is correctly marked as being used to allow for proper
   ///    'dependency pruning'.
-  void ensureLoaded(Member member) {
+  void ensureLoaded(Member? member) {
     if (member == null) return;
     Library ensureLibraryLoaded = member.enclosingLibrary;
-    LibraryBuilder builder =
+    LibraryBuilder? builder =
         libraryBuilder.loader.builders[ensureLibraryLoaded.importUri] ??
             libraryBuilder.loader.target.dillTarget.loader
                 .builders[ensureLibraryLoaded.importUri];
@@ -1168,10 +1176,10 @@
   /// This is designed for use with asserts.
   /// See [ensureLoaded] for a description of what 'loaded' means and the ideas
   /// behind that.
-  bool isLoaded(Member member) {
+  bool isLoaded(Member? member) {
     if (member == null) return true;
     Library ensureLibraryLoaded = member.enclosingLibrary;
-    LibraryBuilder builder =
+    LibraryBuilder? builder =
         libraryBuilder.loader.builders[ensureLibraryLoaded.importUri] ??
             libraryBuilder.loader.target.dillTarget.loader
                 .builders[ensureLibraryLoaded.importUri];
@@ -1195,14 +1203,14 @@
   /// [target], `.arguments` is [arguments], `.fileOffset` is [fileOffset],
   /// and `.isConst` is [isConst].
   /// Returns null if the invocation can't be resolved.
-  Expression _resolveRedirectingFactoryTarget(
+  Expression? _resolveRedirectingFactoryTarget(
       Procedure target, Arguments arguments, int fileOffset, bool isConst) {
     Procedure initialTarget = target;
     Expression replacementNode;
 
-    RedirectionTarget redirectionTarget =
+    RedirectionTarget? redirectionTarget =
         getRedirectionTarget(initialTarget, this);
-    Member resolvedTarget = redirectionTarget?.target;
+    Member? resolvedTarget = redirectionTarget?.target;
     if (redirectionTarget != null &&
         redirectionTarget.typeArguments.any((type) => type is UnknownType)) {
       return null;
@@ -1210,7 +1218,7 @@
 
     if (resolvedTarget == null) {
       String name = constructorNameForDiagnostics(initialTarget.name.text,
-          className: initialTarget.enclosingClass.name);
+          className: initialTarget.enclosingClass!.name);
       // TODO(dmitryas): Report this error earlier.
       replacementNode = buildProblem(
           fasta.templateCyclicRedirectingFactoryConstructors
@@ -1228,13 +1236,13 @@
               resolvedTarget.enclosingClass.name,
               initialTarget.fileOffset));
     } else {
-      RedirectingFactoryBody redirectingFactoryBody =
+      RedirectingFactoryBody? redirectingFactoryBody =
           getRedirectingFactoryBody(resolvedTarget);
       if (redirectingFactoryBody != null) {
         // If the redirection target is itself a redirecting factory, it means
         // that it is unresolved.
         assert(redirectingFactoryBody.isUnresolved);
-        String errorName = redirectingFactoryBody.unresolvedName;
+        String errorName = redirectingFactoryBody.unresolvedName!;
         replacementNode = buildProblem(
             fasta.templateMethodNotFound.withArguments(errorName),
             fileOffset,
@@ -1244,7 +1252,7 @@
         Substitution substitution = Substitution.fromPairs(
             initialTarget.function.typeParameters, arguments.types);
         arguments.types.clear();
-        arguments.types.length = redirectionTarget.typeArguments.length;
+        arguments.types.length = redirectionTarget!.typeArguments.length;
         for (int i = 0; i < arguments.types.length; i++) {
           arguments.types[i] =
               substitution.substituteType(redirectionTarget.typeArguments[i]);
@@ -1265,8 +1273,8 @@
   }
 
   void _resolveRedirectingFactoryTargets(
-      List<Expression> redirectingFactoryInvocations,
-      List<Expression> delayedRedirectingFactoryInvocations) {
+      List<StaticInvocation> redirectingFactoryInvocations,
+      List<StaticInvocation>? delayedRedirectingFactoryInvocations) {
     for (StaticInvocation invocation in redirectingFactoryInvocations) {
       // If the invocation was invalid, it or its parent has already been
       // desugared into an exception throwing expression.  There is nothing to
@@ -1275,19 +1283,20 @@
       // set its inferredType field.  If type inference is disabled, reach to
       // the outermost parent to check if the node is a dead code.
       if (invocation.parent == null) continue;
+      // ignore: unnecessary_null_comparison
       if (typeInferrer != null) {
         if (invocation is FactoryConstructorInvocationJudgment &&
             !invocation.hasBeenInferred) {
           continue;
         }
       } else {
-        TreeNode parent = invocation.parent;
+        TreeNode? parent = invocation.parent;
         while (parent is! Component && parent != null) {
           parent = parent.parent;
         }
         if (parent == null) continue;
       }
-      Expression replacement = _resolveRedirectingFactoryTarget(
+      Expression? replacement = _resolveRedirectingFactoryTarget(
           invocation.target,
           invocation.arguments,
           invocation.fileOffset,
@@ -1313,7 +1322,7 @@
           aliasedType, typeEnvironment, uri, invocation.fileOffset,
           allowSuperBounded: false, inferred: inferred);
       DartType unaliasedType = aliasedType.unalias;
-      List<DartType> invocationTypeArguments = null;
+      List<DartType>? invocationTypeArguments = null;
       if (unaliasedType is InterfaceType) {
         invocationTypeArguments = unaliasedType.typeArguments;
       }
@@ -1339,7 +1348,7 @@
           aliasedType, typeEnvironment, uri, invocation.fileOffset,
           allowSuperBounded: false, inferred: inferred);
       DartType unaliasedType = aliasedType.unalias;
-      List<DartType> invocationTypeArguments = null;
+      List<DartType>? invocationTypeArguments = null;
       if (unaliasedType is InterfaceType) {
         invocationTypeArguments = unaliasedType.typeArguments;
       }
@@ -1350,7 +1359,7 @@
           hasExplicitTypeArguments:
               hasExplicitTypeArguments(invocation.arguments));
       invocation.replaceWith(_resolveRedirectingFactoryTarget(invocation.target,
-          invocationArguments, invocation.fileOffset, invocation.isConst));
+          invocationArguments, invocation.fileOffset, invocation.isConst)!);
     }
     typeAliasedFactoryInvocations.clear();
   }
@@ -1383,10 +1392,10 @@
   }
 
   void finishVariableMetadata() {
-    List<VariableDeclaration> variablesWithMetadata =
+    List<VariableDeclaration>? variablesWithMetadata =
         this.variablesWithMetadata;
     this.variablesWithMetadata = null;
-    List<List<VariableDeclaration>> multiVariablesWithMetadata =
+    List<List<VariableDeclaration>>? multiVariablesWithMetadata =
         this.multiVariablesWithMetadata;
     this.multiVariablesWithMetadata = null;
 
@@ -1405,7 +1414,7 @@
           cloner ??= new CloneVisitorNotMembers();
           VariableDeclaration variable = variables[i];
           for (int i = 0; i < annotations.length; i++) {
-            variable.addAnnotation(cloner.clone(annotations[i]));
+            variable.addAnnotation(cloner!.clone(annotations[i]));
           }
         }
       }
@@ -1413,8 +1422,8 @@
   }
 
   @override
-  List<Expression> finishMetadata(Annotatable parent) {
-    List<Expression> expressions = pop();
+  List<Expression> finishMetadata(Annotatable? parent) {
+    List<Expression> expressions = pop() as List<Expression>;
     inferAnnotations(parent, expressions);
 
     // The invocation of [resolveRedirectingFactoryTargets] below may change the
@@ -1422,7 +1431,7 @@
     // the annotation nodes before the resolution is performed, to collect and
     // return them later.  If [parent] is not provided, [temporaryParent] is
     // used.
-    ListLiteral temporaryParent;
+    ListLiteral? temporaryParent;
 
     if (parent != null) {
       for (Expression expression in expressions) {
@@ -1441,7 +1450,7 @@
       Parser parser, Token token, FunctionNode parameters) {
     assert(redirectingFactoryInvocations.isEmpty);
     int fileOffset = offsetForToken(token);
-    List<TypeVariableBuilder> typeParameterBuilders;
+    List<TypeVariableBuilder>? typeParameterBuilders;
     for (TypeParameter typeParameter in parameters.typeParameters) {
       typeParameterBuilders ??= <TypeVariableBuilder>[];
       typeParameterBuilders.add(
@@ -1449,27 +1458,26 @@
     }
     enterFunctionTypeScope(typeParameterBuilders);
 
-    List<FormalParameterBuilder> formals =
+    List<FormalParameterBuilder>? formals =
         parameters.positionalParameters.length == 0
             ? null
-            : new List<FormalParameterBuilder>.filled(
-                parameters.positionalParameters.length, null);
-    for (int i = 0; i < parameters.positionalParameters.length; i++) {
-      VariableDeclaration formal = parameters.positionalParameters[i];
-      formals[i] = new FormalParameterBuilder(
-          null, 0, null, formal.name, libraryBuilder, formal.fileOffset,
-          fileUri: uri)
-        ..variable = formal;
-    }
+            : new List<FormalParameterBuilder>.generate(
+                parameters.positionalParameters.length, (int i) {
+                VariableDeclaration formal = parameters.positionalParameters[i];
+                return new FormalParameterBuilder(null, 0, null, formal.name!,
+                    libraryBuilder, formal.fileOffset,
+                    fileUri: uri)
+                  ..variable = formal;
+              }, growable: false);
     enterLocalScope(
-        null,
+        'formalParameters',
         new FormalParameters(formals, fileOffset, noLength, uri)
             .computeFormalParameterScope(scope, member, this));
 
     token = parser.parseExpression(parser.syntheticPreviousToken(token));
 
     Expression expression = popForValue();
-    Token eof = token.next;
+    Token eof = token.next!;
 
     if (!eof.isEof) {
       expression = wrapInLocatedProblem(
@@ -1481,10 +1489,10 @@
     ReturnStatementImpl fakeReturn = new ReturnStatementImpl(true, expression);
     if (formals != null) {
       for (int i = 0; i < formals.length; i++) {
-        typeInferrer?.flowAnalysis?.declare(formals[i].variable, true);
+        typeInferrer.flowAnalysis.declare(formals[i].variable!, true);
       }
     }
-    InferredFunctionBody inferredFunctionBody = typeInferrer?.inferFunctionBody(
+    InferredFunctionBody inferredFunctionBody = typeInferrer.inferFunctionBody(
         this, fileOffset, const DynamicType(), AsyncMarker.Sync, fakeReturn);
     assert(
         fakeReturn == inferredFunctionBody.body,
@@ -1495,7 +1503,7 @@
     libraryBuilder.loader.transformPostInference(fakeReturn,
         transformSetLiterals, transformCollections, libraryBuilder.library);
 
-    return fakeReturn.expression;
+    return fakeReturn.expression!;
   }
 
   void parseInitializers(Token token) {
@@ -1508,7 +1516,7 @@
     }
     // We are passing [AsyncMarker.Sync] because the error will be reported
     // already.
-    finishConstructor(member, AsyncMarker.Sync, null);
+    finishConstructor(member as ConstructorBuilder, AsyncMarker.Sync, null);
   }
 
   Expression parseFieldInitializer(Token token) {
@@ -1522,51 +1530,51 @@
   Expression parseAnnotation(Token token) {
     Parser parser = new Parser(this);
     token = parser.parseMetadata(parser.syntheticPreviousToken(token));
-    Expression annotation = pop();
+    Expression annotation = pop() as Expression;
     checkEmpty(token.charOffset);
     return annotation;
   }
 
   void finishConstructor(
-      ConstructorBuilder builder, AsyncMarker asyncModifier, Statement body) {
+      ConstructorBuilder builder, AsyncMarker asyncModifier, Statement? body) {
     /// Quotes below are from [Dart Programming Language Specification, 4th
     /// Edition](
     /// https://ecma-international.org/publications/files/ECMA-ST/ECMA-408.pdf).
     assert(builder == member);
     Constructor constructor = builder.actualConstructor;
-    List<FormalParameterBuilder> formals = builder.formals;
+    List<FormalParameterBuilder>? formals = builder.formals;
     if (formals != null) {
       for (int i = 0; i < formals.length; i++) {
         FormalParameterBuilder parameter = formals[i];
-        typeInferrer?.flowAnalysis?.declare(parameter.variable, true);
+        typeInferrer.flowAnalysis.declare(parameter.variable!, true);
       }
     }
     if (_initializers != null) {
-      for (Initializer initializer in _initializers) {
-        typeInferrer?.inferInitializer(this, initializer);
+      for (Initializer initializer in _initializers!) {
+        typeInferrer.inferInitializer(this, initializer);
       }
       if (!builder.isExternal) {
-        for (Initializer initializer in _initializers) {
+        for (Initializer initializer in _initializers!) {
           builder.addInitializer(initializer, this);
         }
       }
     }
     if (asyncModifier != AsyncMarker.Sync) {
       constructor.initializers.add(buildInvalidInitializer(buildProblem(
-          fasta.messageConstructorNotSync, body.fileOffset, noLength)));
+          fasta.messageConstructorNotSync, body!.fileOffset, noLength)));
     }
     if (needsImplicitSuperInitializer) {
       /// >If no superinitializer is provided, an implicit superinitializer
       /// >of the form super() is added at the end of k’s initializer list,
       /// >unless the enclosing class is class Object.
-      Constructor superTarget = lookupConstructor(emptyName, isSuper: true);
+      Constructor? superTarget = lookupConstructor(emptyName, isSuper: true);
       Initializer initializer;
       Arguments arguments = forest.createArgumentsEmpty(noLocation);
       if (superTarget == null ||
           checkArgumentsForFunction(superTarget.function, arguments,
                   builder.charOffset, const <TypeParameter>[]) !=
               null) {
-        String superclass = classBuilder.supertypeBuilder.fullNameForErrors;
+        String superclass = classBuilder!.supertypeBuilder!.fullNameForErrors;
         int length = constructor.name.text.length;
         if (length == 0) {
           length = (constructor.parent as Class).name.length;
@@ -1591,8 +1599,8 @@
       /// >If a generative constructor c is not a redirecting constructor
       /// >and no body is provided, then c implicitly has an empty body {}.
       /// We use an empty statement instead.
-      constructor.function.body = new EmptyStatement();
-      constructor.function.body.parent = constructor.function;
+      constructor.function.body = new EmptyStatement()
+        ..parent = constructor.function;
     }
   }
 
@@ -1606,7 +1614,7 @@
   @override
   void endArguments(int count, Token beginToken, Token endToken) {
     debugEvent("Arguments");
-    List<Object> arguments = count == 0
+    List<Object?>? arguments = count == 0
         ? <Object>[]
         : const FixedNullableList<Object>().pop(stack, count);
     if (arguments == null) {
@@ -1615,7 +1623,7 @@
     }
     int firstNamedArgumentIndex = arguments.length;
     for (int i = 0; i < arguments.length; i++) {
-      Object node = arguments[i];
+      Object? node = arguments[i];
       if (node is NamedExpression) {
         firstNamedArgumentIndex =
             i < firstNamedArgumentIndex ? i : firstNamedArgumentIndex;
@@ -1666,7 +1674,7 @@
       // 64-bits.
       push(value..isParenthesized = true);
     } else {
-      push(new ParenthesizedExpressionGenerator(this, token.endGroup, value));
+      push(new ParenthesizedExpressionGenerator(this, token.endGroup!, value));
     }
   }
 
@@ -1684,9 +1692,9 @@
       ])
     ]));
     debugEvent("Send");
-    Arguments arguments = pop();
-    List<UnresolvedType> typeArguments = pop();
-    Object receiver = pop();
+    Arguments? arguments = pop() as Arguments?;
+    List<UnresolvedType>? typeArguments = pop() as List<UnresolvedType>?;
+    Object receiver = pop()!;
     // Delay adding [typeArguments] to [forest] for type aliases: They
     // must be unaliased to the type arguments of the denoted type.
     bool isInForest = arguments != null &&
@@ -1713,7 +1721,8 @@
             isTypeArgumentsInForest: isInForest));
       }
     } else if (receiver is ParserRecovery) {
-      push(new ParserErrorGenerator(this, null, fasta.messageSyntheticToken));
+      push(new ParserErrorGenerator(
+          this, beginToken, fasta.messageSyntheticToken));
     } else if (arguments == null) {
       push(receiver);
     } else {
@@ -1731,8 +1740,8 @@
   }
 
   @override
-  finishSend(Object receiver, List<UnresolvedType> typeArguments,
-      Arguments arguments, int charOffset,
+  /* Expression | Generator | Initializer */ finishSend(Object receiver,
+      List<UnresolvedType>? typeArguments, Arguments arguments, int charOffset,
       {bool isTypeArgumentsInForest = false}) {
     if (receiver is Generator) {
       return receiver.doInvocation(charOffset, typeArguments, arguments,
@@ -1769,7 +1778,7 @@
   void endCascade() {
     debugEvent("endCascade");
     Expression expression = popForEffect();
-    Cascade cascadeReceiver = pop();
+    Cascade cascadeReceiver = pop() as Cascade;
     cascadeReceiver.addCascadeExpression(expression);
     push(cascadeReceiver);
   }
@@ -1785,7 +1794,7 @@
   void endCaseExpression(Token colon) {
     debugEvent("endCaseExpression");
     Expression expression = popForValue();
-    constantContext = pop();
+    constantContext = pop() as ConstantContext;
     super.push(expression);
   }
 
@@ -1797,7 +1806,7 @@
       // This is matched by the call to [endNode] in
       // [doLogicalExpression].
       if (isAnd) {
-        typeInferrer?.assignedVariables?.beginNode();
+        typeInferrer.assignedVariables.beginNode();
       }
       push(lhs);
     }
@@ -1835,9 +1844,9 @@
       ]),
     ]));
     Expression right = popForValue();
-    Object left = pop();
+    Object? left = pop();
     int fileOffset = offsetForToken(token);
-    String operator = token.stringValue;
+    String operator = token.stringValue!;
     bool isNot = identical("!=", operator);
     if (isNot || identical("==", operator)) {
       if (left is Generator) {
@@ -1848,7 +1857,8 @@
           left = buildProblem(problem.message, problem.charOffset, noLength);
         }
         assert(left is Expression);
-        push(forest.createEquals(fileOffset, left, right, isNot: isNot));
+        push(forest.createEquals(fileOffset, left as Expression, right,
+            isNot: isNot));
       }
     } else {
       Name name = new Name(operator);
@@ -1870,7 +1880,7 @@
           left = buildProblem(problem.message, problem.charOffset, noLength);
         }
         assert(left is Expression);
-        push(forest.createBinary(fileOffset, left, name, right));
+        push(forest.createBinary(fileOffset, left as Expression, name, right));
       }
     }
   }
@@ -1878,14 +1888,14 @@
   /// Handle `a && b` and `a || b`.
   void doLogicalExpression(Token token) {
     Expression argument = popForValue();
-    Expression receiver = pop();
+    Expression receiver = pop() as Expression;
     Expression logicalExpression = forest.createLogicalExpression(
-        offsetForToken(token), receiver, token.stringValue, argument);
+        offsetForToken(token), receiver, token.stringValue!, argument);
     push(logicalExpression);
     if (optional("&&", token)) {
       // This is matched by the call to [beginNode] in
       // [beginBinaryExpression].
-      typeInferrer?.assignedVariables?.endNode(logicalExpression);
+      typeInferrer.assignedVariables.endNode(logicalExpression);
     }
   }
 
@@ -1898,25 +1908,25 @@
 
   /// Handle `a?.b(...)`.
   void doIfNotNull(Token token) {
-    Object send = pop();
+    Object? send = pop();
     if (send is IncompleteSendGenerator) {
       push(send.withReceiver(pop(), token.charOffset, isNullAware: true));
     } else {
       pop();
-      token = token.next;
+      token = token.next!;
       push(buildProblem(fasta.templateExpectedIdentifier.withArguments(token),
           offsetForToken(token), lengthForToken(token)));
     }
   }
 
   void doDotOrCascadeExpression(Token token) {
-    Object send = pop();
+    Object? send = pop();
     if (send is IncompleteSendGenerator) {
-      Object receiver = optional(".", token) ? pop() : popForValue();
+      Object? receiver = optional(".", token) ? pop() : popForValue();
       push(send.withReceiver(receiver, token.charOffset));
     } else {
       pop();
-      token = token.next;
+      token = token.next!;
       push(buildProblem(fasta.templateExpectedIdentifier.withArguments(token),
           offsetForToken(token), lengthForToken(token)));
     }
@@ -1930,21 +1940,21 @@
   @override
   Expression throwNoSuchMethodError(
       Expression receiver, String name, Arguments arguments, int charOffset,
-      {Member candidate,
+      {Member? candidate,
       bool isSuper: false,
       bool isGetter: false,
       bool isSetter: false,
       bool isStatic: false,
-      LocatedMessage message}) {
+      LocatedMessage? message}) {
     int length = name.length;
     int periodIndex = name.lastIndexOf(".");
     if (periodIndex != -1) {
       length -= periodIndex + 1;
     }
     Name kernelName = new Name(name, libraryBuilder.nameOrigin);
-    List<LocatedMessage> context;
+    List<LocatedMessage>? context;
     if (candidate != null && candidate.location != null) {
-      Uri uri = candidate.location.file;
+      Uri uri = candidate.location!.file;
       int offset = candidate.fileOffset;
       Message contextMessage;
       int length = noLength;
@@ -1992,7 +2002,7 @@
   Message warnUnresolvedGet(Name name, int charOffset,
       {bool isSuper: false,
       bool reportWarning: true,
-      List<LocatedMessage> context}) {
+      List<LocatedMessage>? context}) {
     Message message = isSuper
         ? fasta.templateSuperclassHasNoGetter.withArguments(name.text)
         : fasta.templateGetterNotFound.withArguments(name.text);
@@ -2007,7 +2017,7 @@
   Message warnUnresolvedSet(Name name, int charOffset,
       {bool isSuper: false,
       bool reportWarning: true,
-      List<LocatedMessage> context}) {
+      List<LocatedMessage>? context}) {
     Message message = isSuper
         ? fasta.templateSuperclassHasNoSetter.withArguments(name.text)
         : fasta.templateSetterNotFound.withArguments(name.text);
@@ -2022,7 +2032,7 @@
   Message warnUnresolvedMethod(Name name, int charOffset,
       {bool isSuper: false,
       bool reportWarning: true,
-      List<LocatedMessage> context}) {
+      List<LocatedMessage>? context}) {
     String plainName = name.text;
     int dotIndex = plainName.lastIndexOf(".");
     if (dotIndex != -1) {
@@ -2052,15 +2062,15 @@
   }
 
   @override
-  Member lookupInstanceMember(Name name,
+  Member? lookupInstanceMember(Name name,
       {bool isSetter: false, bool isSuper: false}) {
-    return classBuilder.lookupInstanceMember(hierarchy, name,
+    return classBuilder!.lookupInstanceMember(hierarchy, name,
         isSetter: isSetter, isSuper: isSuper);
   }
 
   @override
-  Constructor lookupConstructor(Name name, {bool isSuper}) {
-    return classBuilder.lookupConstructor(name, isSuper: isSuper);
+  Constructor? lookupConstructor(Name name, {bool isSuper: false}) {
+    return classBuilder!.lookupConstructor(name, isSuper: isSuper);
   }
 
   @override
@@ -2082,7 +2092,7 @@
             ? ConstantContext.inferred
             : !member.isStatic &&
                     classBuilder != null &&
-                    classBuilder.declaresConstConstructor
+                    classBuilder!.declaresConstConstructor
                 ? ConstantContext.required
                 : ConstantContext.none;
       }
@@ -2104,7 +2114,7 @@
   VariableGet createVariableGet(VariableDeclaration variable, int charOffset,
       {bool forNullGuardedAccess: false}) {
     if (!(variable as VariableDeclarationImpl).isLocalFunction) {
-      typeInferrer?.assignedVariables?.read(variable);
+      typeInferrer.assignedVariables.read(variable);
     }
     return new VariableGetImpl(variable,
         forNullGuardedAccess: forNullGuardedAccess)
@@ -2118,10 +2128,10 @@
       VariableDeclaration variable,
       Token token,
       int charOffset,
-      String name,
+      String? name,
       ReadOnlyAccessKind kind) {
     return new ReadOnlyAccessGenerator(
-        this, token, createVariableGet(variable, charOffset), name, kind);
+        this, token, createVariableGet(variable, charOffset), name ?? '', kind);
   }
 
   /// Look up [name] in [scope] using [token] as location information (both to
@@ -2130,18 +2140,19 @@
   /// implies that it shouldn't be turned into a [ThisPropertyAccessGenerator]
   /// if the name doesn't resolve in the scope).
   @override
-  scopeLookup(Scope scope, String name, Token token,
-      {bool isQualified: false, PrefixBuilder prefix}) {
+  /*Generator|Expression|Builder*/ scopeLookup(
+      Scope scope, String name, Token token,
+      {bool isQualified: false, PrefixBuilder? prefix}) {
     int charOffset = offsetForToken(token);
     if (token.isSynthetic) {
       return new ParserErrorGenerator(this, token, fasta.messageSyntheticToken);
     }
-    Builder declaration = scope.lookup(name, charOffset, uri);
+    Builder? declaration = scope.lookup(name, charOffset, uri);
     if (declaration == null &&
         prefix == null &&
         (classBuilder?.isPatch ?? false)) {
       // The scope of a patched method includes the origin class.
-      declaration = classBuilder.origin
+      declaration = classBuilder!.origin
           .findStaticBuilder(name, charOffset, uri, libraryBuilder);
     }
     if (declaration != null &&
@@ -2177,14 +2188,14 @@
           // If we are in an extension instance member we interpret this as an
           // implicit access on the 'this' parameter.
           return PropertyAccessGenerator.make(this, token,
-              createVariableGet(extensionThis, charOffset), n, false);
+              createVariableGet(extensionThis!, charOffset), n, false);
         } else {
           // This is an implicit access on 'this'.
           return new ThisPropertyAccessGenerator(this, token, n);
         }
       } else if (ignoreMainInGetMainClosure &&
           name == "main" &&
-          member?.name == "_getMainClosure") {
+          member.name == "_getMainClosure") {
         return forest.createNullLiteral(charOffset);
       } else {
         return new UnresolvedNameGenerator(this, token, n);
@@ -2194,9 +2205,10 @@
         AccessErrorBuilder accessError = declaration;
         declaration = accessError.builder;
       }
-      return new TypeUseGenerator(this, token, declaration, name);
+      return new TypeUseGenerator(
+          this, token, declaration as TypeDeclarationBuilder, name);
     } else if (declaration.isLocal) {
-      VariableBuilder variableBuilder = declaration;
+      VariableBuilder variableBuilder = declaration as VariableBuilder;
       if (constantContext != ConstantContext.none &&
           !variableBuilder.isConst &&
           !member.isConstructor &&
@@ -2204,7 +2216,7 @@
         return new IncompleteErrorGenerator(
             this, token, fasta.messageNotAConstantExpression);
       }
-      VariableDeclaration variable = variableBuilder.variable;
+      VariableDeclaration variable = variableBuilder.variable!;
       if (!variableBuilder.isAssignable) {
         return _createReadOnlyVariableAccess(
             variable,
@@ -2231,8 +2243,9 @@
       Name n = new Name(name, libraryBuilder.nameOrigin);
       return new ThisPropertyAccessGenerator(this, token, n);
     } else if (declaration.isExtensionInstanceMember) {
-      ExtensionBuilder extensionBuilder = declarationBuilder;
-      MemberBuilder setterBuilder =
+      ExtensionBuilder extensionBuilder =
+          declarationBuilder as ExtensionBuilder;
+      MemberBuilder? setterBuilder =
           _getCorrespondingSetterBuilder(scope, declaration, name, charOffset);
       // TODO(johnniwinther): Check for constantContext like below?
       if (declaration.isField) {
@@ -2246,20 +2259,20 @@
         return new UnresolvedNameGenerator(
             this, token, new Name(name, libraryBuilder.nameOrigin));
       }
-      MemberBuilder getterBuilder =
+      MemberBuilder? getterBuilder =
           declaration is MemberBuilder ? declaration : null;
       return new ExtensionInstanceAccessGenerator.fromBuilder(
           this,
           token,
           extensionBuilder.extension,
           name,
-          extensionThis,
+          extensionThis!,
           extensionTypeParameters,
           getterBuilder,
           setterBuilder);
     } else if (declaration.isRegularMethod) {
       assert(declaration.isStatic || declaration.isTopLevel);
-      MemberBuilder memberBuilder = declaration;
+      MemberBuilder memberBuilder = declaration as MemberBuilder;
       return new StaticAccessGenerator(
           this, token, name, memberBuilder.member, null);
     } else if (declaration is PrefixBuilder) {
@@ -2270,15 +2283,15 @@
     } else if (declaration.hasProblem && declaration is! AccessErrorBuilder) {
       return declaration;
     } else {
-      MemberBuilder setterBuilder =
+      MemberBuilder? setterBuilder =
           _getCorrespondingSetterBuilder(scope, declaration, name, charOffset);
-      MemberBuilder getterBuilder =
+      MemberBuilder? getterBuilder =
           declaration is MemberBuilder ? declaration : null;
       assert(getterBuilder != null || setterBuilder != null);
       StaticAccessGenerator generator = new StaticAccessGenerator.fromBuilder(
           this, name, token, getterBuilder, setterBuilder);
       if (constantContext != ConstantContext.none) {
-        Member readTarget = generator.readTarget;
+        Member? readTarget = generator.readTarget;
         if (!(readTarget is Field && readTarget.isConst ||
             // Static tear-offs are also compile time constants.
             readTarget is Procedure)) {
@@ -2292,15 +2305,15 @@
 
   /// Returns the setter builder corresponding to [declaration] using the
   /// [name] and [charOffset] for the lookup into [scope] if necessary.
-  MemberBuilder _getCorrespondingSetterBuilder(
+  MemberBuilder? _getCorrespondingSetterBuilder(
       Scope scope, Builder declaration, String name, int charOffset) {
-    Builder setter;
+    Builder? setter;
     if (declaration.isSetter) {
       setter = declaration;
     } else if (declaration.isGetter) {
       setter = scope.lookupSetter(name, charOffset, uri);
     } else if (declaration.isField) {
-      MemberBuilder fieldBuilder = declaration;
+      MemberBuilder fieldBuilder = declaration as MemberBuilder;
       if (!fieldBuilder.isAssignable) {
         setter = scope.lookupSetter(name, charOffset, uri);
       } else {
@@ -2313,15 +2326,15 @@
   @override
   void handleQualified(Token period) {
     debugEvent("Qualified");
-    Object node = pop();
-    Object qualifier = pop();
+    Object? node = pop();
+    Object? qualifier = pop();
     if (qualifier is ParserRecovery) {
       push(qualifier);
     } else if (node is ParserRecovery) {
       push(node);
     } else {
-      Identifier identifier = node;
-      push(identifier.withQualifier(qualifier));
+      Identifier identifier = node as Identifier;
+      push(identifier.withQualifier(qualifier!));
     }
   }
 
@@ -2341,18 +2354,21 @@
   void endLiteralString(int interpolationCount, Token endToken) {
     debugEvent("endLiteralString");
     if (interpolationCount == 0) {
-      Token token = pop();
+      Token token = pop() as Token;
       String value = unescapeString(token.lexeme, token, this);
       push(forest.createStringLiteral(offsetForToken(token), value));
     } else {
       int count = 1 + interpolationCount * 2;
-      List<Object> parts = const FixedNullableList<Object>().pop(stack, count);
+      List<Object>? parts = const FixedNullableList<Object>().popNonNullable(
+          stack,
+          count,
+          /* dummyValue = */ 0);
       if (parts == null) {
         push(new ParserRecovery(endToken.charOffset));
         return;
       }
-      Token first = parts.first;
-      Token last = parts.last;
+      Token first = parts.first as Token;
+      Token last = parts.last as Token;
       Quote quote = analyzeQuote(first.lexeme);
       List<Expression> expressions = <Expression>[];
       // Contains more than just \' or \".
@@ -2407,7 +2423,7 @@
   void handleStringJuxtaposition(Token startToken, int literalCount) {
     debugEvent("StringJuxtaposition");
     List<Expression> parts = popListForValue(literalCount);
-    List<Expression> expressions;
+    List<Expression>? expressions;
     // Flatten string juxtapositions of string interpolation.
     for (int i = 0; i < parts.length; i++) {
       Expression part = parts[i];
@@ -2431,7 +2447,7 @@
   @override
   void handleLiteralInt(Token token) {
     debugEvent("LiteralInt");
-    int value = int.tryParse(token.lexeme);
+    int? value = int.tryParse(token.lexeme);
     // Postpone parsing of literals resulting in a negative value
     // (hex literals >= 2^63). These are only allowed when not negated.
     if (value == null || value < 0) {
@@ -2448,16 +2464,16 @@
   }
 
   @override
-  void handleExpressionFunctionBody(Token arrowToken, Token endToken) {
+  void handleExpressionFunctionBody(Token arrowToken, Token? endToken) {
     debugEvent("ExpressionFunctionBody");
-    endReturnStatement(true, arrowToken.next, endToken);
+    endReturnStatement(true, arrowToken.next!, endToken);
   }
 
   @override
   void endReturnStatement(
-      bool hasExpression, Token beginToken, Token endToken) {
+      bool hasExpression, Token beginToken, Token? endToken) {
     debugEvent("ReturnStatement");
-    Expression expression = hasExpression ? popForValue() : null;
+    Expression? expression = hasExpression ? popForValue() : null;
     if (expression != null && inConstructor) {
       push(buildProblemStatement(
           fasta.messageConstructorWithReturnType, beginToken.charOffset));
@@ -2472,7 +2488,7 @@
     Expression condition = popForValue();
     // This is matched by the call to [deferNode] in
     // [endThenStatement].
-    typeInferrer?.assignedVariables?.beginNode();
+    typeInferrer.assignedVariables.beginNode();
     push(condition);
     super.beginThenStatement(token);
   }
@@ -2483,21 +2499,21 @@
     // This is matched by the call to [beginNode] in
     // [beginThenStatement] and by the call to [storeInfo] in
     // [endIfStatement].
-    push(typeInferrer?.assignedVariables?.deferNode());
+    push(typeInferrer.assignedVariables.deferNode());
   }
 
   @override
-  void endIfStatement(Token ifToken, Token elseToken) {
-    Statement elsePart = popStatementIfNotNull(elseToken);
+  void endIfStatement(Token ifToken, Token? elseToken) {
+    Statement? elsePart = popStatementIfNotNull(elseToken);
     AssignedVariablesNodeInfo<VariableDeclaration> assignedVariablesInfo =
-        pop();
+        pop() as AssignedVariablesNodeInfo<VariableDeclaration>;
     Statement thenPart = popStatement();
-    Expression condition = pop();
+    Expression condition = pop() as Expression;
     Statement node = forest.createIfStatement(
         offsetForToken(ifToken), condition, thenPart, elsePart);
     // This is matched by the call to [deferNode] in
     // [endThenStatement].
-    typeInferrer?.assignedVariables?.storeInfo(node, assignedVariablesInfo);
+    typeInferrer.assignedVariables.storeInfo(node, assignedVariablesInfo);
     push(node);
   }
 
@@ -2505,7 +2521,7 @@
   void beginVariableInitializer(Token token) {
     if ((currentLocalVariableModifiers & lateMask) != 0) {
       // This is matched by the call to [endNode] in [endVariableInitializer].
-      typeInferrer?.assignedVariables?.beginNode();
+      typeInferrer.assignedVariables.beginNode();
     }
   }
 
@@ -2513,19 +2529,19 @@
   void endVariableInitializer(Token assignmentOperator) {
     debugEvent("VariableInitializer");
     assert(assignmentOperator.stringValue == "=");
-    AssignedVariablesNodeInfo<VariableDeclaration> assignedVariablesInfo;
+    AssignedVariablesNodeInfo<VariableDeclaration>? assignedVariablesInfo;
     bool isLate = (currentLocalVariableModifiers & lateMask) != 0;
     Expression initializer = popForValue();
     if (isLate) {
-      assignedVariablesInfo = typeInferrer?.assignedVariables
-          ?.deferNode(isClosureOrLateVariableInitializer: true);
+      assignedVariablesInfo = typeInferrer.assignedVariables
+          .deferNode(isClosureOrLateVariableInitializer: true);
     }
     pushNewLocalVariable(initializer, equalsToken: assignmentOperator);
     if (isLate) {
-      VariableDeclaration node = peek();
+      VariableDeclaration node = peek() as VariableDeclaration;
       // This is matched by the call to [beginNode] in
       // [beginVariableInitializer].
-      typeInferrer?.assignedVariables?.storeInfo(node, assignedVariablesInfo);
+      typeInferrer.assignedVariables.storeInfo(node, assignedVariablesInfo!);
     }
   }
 
@@ -2535,8 +2551,8 @@
     bool isConst = (currentLocalVariableModifiers & constMask) != 0;
     bool isFinal = (currentLocalVariableModifiers & finalMask) != 0;
     bool isLate = (currentLocalVariableModifiers & lateMask) != 0;
-    Expression initializer;
-    if (!optional("in", token.next)) {
+    Expression? initializer;
+    if (!optional("in", token.next!)) {
       // A for-in loop-variable can't have an initializer. So let's remain
       // silent if the next token is `in`. Since a for-in loop can only have
       // one variable it must be followed by `in`.
@@ -2562,13 +2578,13 @@
     pushNewLocalVariable(initializer);
   }
 
-  void pushNewLocalVariable(Expression initializer, {Token equalsToken}) {
-    Object node = pop();
+  void pushNewLocalVariable(Expression? initializer, {Token? equalsToken}) {
+    Object? node = pop();
     if (node is ParserRecovery) {
       push(node);
       return;
     }
-    Identifier identifier = node;
+    Identifier identifier = node as Identifier;
     assert(currentLocalVariableModifiers != -1);
     bool isConst = (currentLocalVariableModifiers & constMask) != 0;
     bool isFinal = (currentLocalVariableModifiers & finalMask) != 0;
@@ -2579,7 +2595,9 @@
         identifier.name, functionNestingLevel,
         forSyntheticToken: identifier.token.isSynthetic,
         initializer: initializer,
-        type: buildDartType(currentLocalVariableType),
+        type: currentLocalVariableType != null
+            ? buildDartType(currentLocalVariableType!)
+            : null,
         isFinal: isFinal,
         isConst: isConst,
         isLate: isLate,
@@ -2590,7 +2608,7 @@
             initializer == null)
       ..fileOffset = identifier.charOffset
       ..fileEqualsOffset = offsetForToken(equalsToken);
-    typeInferrer?.assignedVariables?.declare(variable);
+    typeInferrer.assignedVariables.declare(variable);
     libraryBuilder.checkBoundsInVariableDeclaration(
         variable, typeEnvironment, uri);
     push(variable);
@@ -2600,7 +2618,7 @@
   void beginFieldInitializer(Token token) {
     inFieldInitializer = true;
     if (member is FieldBuilder) {
-      FieldBuilder fieldBuilder = member;
+      FieldBuilder fieldBuilder = member as FieldBuilder;
       inLateFieldInitializer = fieldBuilder.isLate;
       if (fieldBuilder.isAbstract) {
         addProblem(
@@ -2638,12 +2656,12 @@
   void endInitializedIdentifier(Token nameToken) {
     // TODO(ahe): Use [InitializedIdentifier] here?
     debugEvent("InitializedIdentifier");
-    Object node = pop();
+    Object? node = pop();
     if (node is ParserRecovery) {
       push(node);
       return;
     }
-    VariableDeclaration variable = node;
+    VariableDeclaration variable = node as VariableDeclaration;
     variable.fileOffset = nameToken.charOffset;
     push(variable);
     declareVariable(variable, scope);
@@ -2651,12 +2669,12 @@
 
   @override
   void beginVariablesDeclaration(
-      Token token, Token lateToken, Token varFinalOrConst) {
+      Token token, Token? lateToken, Token? varFinalOrConst) {
     debugEvent("beginVariablesDeclaration");
     if (!libraryBuilder.isNonNullableByDefault) {
       reportNonNullableModifierError(lateToken);
     }
-    UnresolvedType type = pop();
+    UnresolvedType type = pop() as UnresolvedType;
     int modifiers = (lateToken != null ? lateMask : 0) |
         Modifier.validateVarFinalOrConst(varFinalOrConst?.lexeme);
     _enterLocalState(inLateLocalInitializer: lateToken != null);
@@ -2671,19 +2689,19 @@
   }
 
   @override
-  void endVariablesDeclaration(int count, Token endToken) {
+  void endVariablesDeclaration(int count, Token? endToken) {
     debugEvent("VariablesDeclaration");
     if (count == 1) {
-      Object node = pop();
-      constantContext = pop();
-      currentLocalVariableType = pop();
-      currentLocalVariableModifiers = pop();
-      List<Expression> annotations = pop();
+      Object? node = pop();
+      constantContext = pop() as ConstantContext;
+      currentLocalVariableType = pop() as UnresolvedType?;
+      currentLocalVariableModifiers = pop() as int;
+      List<Expression>? annotations = pop() as List<Expression>?;
       if (node is ParserRecovery) {
         push(node);
         return;
       }
-      VariableDeclaration variable = node;
+      VariableDeclaration variable = node as VariableDeclaration;
       if (annotations != null) {
         for (int i = 0; i < annotations.length; i++) {
           variable.addAnnotation(annotations[i]);
@@ -2692,12 +2710,13 @@
       }
       push(variable);
     } else {
-      List<VariableDeclaration> variables =
-          const FixedNullableList<VariableDeclaration>().pop(stack, count);
-      constantContext = pop();
-      currentLocalVariableType = pop();
-      currentLocalVariableModifiers = pop();
-      List<Expression> annotations = pop();
+      List<VariableDeclaration>? variables =
+          const FixedNullableList<VariableDeclaration>()
+              .popNonNullable(stack, count, dummyVariableDeclaration);
+      constantContext = pop() as ConstantContext;
+      currentLocalVariableType = pop() as UnresolvedType?;
+      currentLocalVariableModifiers = pop() as int;
+      List<Expression>? annotations = pop() as List<Expression>?;
       if (variables == null) {
         push(new ParserRecovery(offsetForToken(endToken)));
         return;
@@ -2729,11 +2748,11 @@
   void beginBlock(Token token, BlockKind blockKind) {
     if (blockKind == BlockKind.tryStatement) {
       // This is matched by the call to [endNode] in [endBlock].
-      typeInferrer?.assignedVariables?.beginNode();
+      typeInferrer.assignedVariables.beginNode();
     } else if (blockKind == BlockKind.finallyClause) {
       // This is matched by the call to [beginNode] in [beginTryStatement].
       tryStatementInfoStack = tryStatementInfoStack
-          .prepend(typeInferrer?.assignedVariables?.deferNode());
+          .prepend(typeInferrer.assignedVariables.deferNode());
     }
     super.beginBlock(token, blockKind);
   }
@@ -2747,7 +2766,7 @@
     push(block);
     if (blockKind == BlockKind.tryStatement) {
       // This is matched by the call to [beginNode] in [beginBlock].
-      typeInferrer?.assignedVariables?.endNode(block);
+      typeInferrer.assignedVariables.endNode(block);
     }
   }
 
@@ -2774,20 +2793,20 @@
     ]));
     debugEvent("AssignmentExpression");
     Expression value = popForValue();
-    Object generator = pop();
+    Object? generator = pop();
     if (generator is! Generator) {
       push(buildProblem(fasta.messageNotAnLvalue, offsetForToken(token),
           lengthForToken(token)));
     } else {
       push(new DelayedAssignment(
-          this, token, generator, value, token.stringValue));
+          this, token, generator, value, token.stringValue!));
     }
   }
 
   @override
   void enterLoop(int charOffset) {
     if (peek() is LabelTarget) {
-      LabelTarget target = peek();
+      LabelTarget target = peek() as LabelTarget;
       enterBreakTarget(charOffset, target.breakTarget);
       enterContinueTarget(charOffset, target.continueTarget);
     } else {
@@ -2805,7 +2824,7 @@
     }
   }
 
-  List<VariableDeclaration> _buildForLoopVariableDeclarations(
+  List<VariableDeclaration>? _buildForLoopVariableDeclarations(
       variableOrExpression) {
     // TODO(ahe): This can be simplified now that we have the events
     // `handleForInitializer...` events.
@@ -2831,7 +2850,7 @@
     } else if (variableOrExpression is List<Object>) {
       List<VariableDeclaration> variables = <VariableDeclaration>[];
       for (Object v in variableOrExpression) {
-        variables.addAll(_buildForLoopVariableDeclarations(v));
+        variables.addAll(_buildForLoopVariableDeclarations(v)!);
       }
       return variables;
     } else if (variableOrExpression == null) {
@@ -2846,7 +2865,7 @@
     push(NullValue.Expression);
     // This is matched by the call to [deferNode] in [endForStatement] or
     // [endForControlFlow].
-    typeInferrer?.assignedVariables?.beginNode();
+    typeInferrer.assignedVariables.beginNode();
   }
 
   @override
@@ -2855,7 +2874,7 @@
     if (!forIn) {
       // This is matched by the call to [deferNode] in [endForStatement] or
       // [endForControlFlow].
-      typeInferrer?.assignedVariables?.beginNode();
+      typeInferrer.assignedVariables.beginNode();
     }
   }
 
@@ -2865,14 +2884,14 @@
     if (forIn) {
       // If the declaration is of the form `for (final x in ...)`, then we may
       // have erroneously set the `isStaticLate` flag, so un-set it.
-      Object declaration = peek();
+      Object? declaration = peek();
       if (declaration is VariableDeclarationImpl) {
         declaration.isStaticLate = false;
       }
     } else {
       // This is matched by the call to [deferNode] in [endForStatement] or
       // [endForControlFlow].
-      typeInferrer?.assignedVariables?.beginNode();
+      typeInferrer.assignedVariables.beginNode();
     }
   }
 
@@ -2888,18 +2907,18 @@
   @override
   void endForControlFlow(Token token) {
     debugEvent("ForControlFlow");
-    Object entry = pop();
-    int updateExpressionCount = pop();
+    Object? entry = pop();
+    int updateExpressionCount = pop() as int;
     pop(); // left separator
     pop(); // left parenthesis
-    Token forToken = pop();
+    Token forToken = pop() as Token;
     List<Expression> updates = popListForEffect(updateExpressionCount);
     Statement conditionStatement = popStatement(); // condition
 
     if (constantContext != ConstantContext.none) {
       pop(); // Pop variable or expression.
       exitLocalScope();
-      typeInferrer?.assignedVariables?.discardNode();
+      typeInferrer.assignedVariables.discardNode();
 
       handleRecoverableError(
           fasta.templateCantUseControlFlowOrSpreadAsConstant
@@ -2915,16 +2934,16 @@
     // [handleForInitializerExpressionStatement], and
     // [handleForInitializerLocalVariableDeclaration].
     AssignedVariablesNodeInfo<VariableDeclaration> assignedVariablesNodeInfo =
-        typeInferrer?.assignedVariables?.popNode();
+        typeInferrer.assignedVariables.popNode();
 
-    Object variableOrExpression = pop();
+    Object? variableOrExpression = pop();
     exitLocalScope();
 
     transformCollections = true;
     List<VariableDeclaration> variables =
-        _buildForLoopVariableDeclarations(variableOrExpression);
-    typeInferrer?.assignedVariables?.pushNode(assignedVariablesNodeInfo);
-    Expression condition;
+        _buildForLoopVariableDeclarations(variableOrExpression)!;
+    typeInferrer.assignedVariables.pushNode(assignedVariablesNodeInfo);
+    Expression? condition;
     if (conditionStatement is ExpressionStatement) {
       condition = conditionStatement.expression;
     } else {
@@ -2933,12 +2952,12 @@
     if (entry is MapLiteralEntry) {
       ForMapEntry result = forest.createForMapEntry(
           offsetForToken(forToken), variables, condition, updates, entry);
-      typeInferrer?.assignedVariables?.endNode(result);
+      typeInferrer.assignedVariables.endNode(result);
       push(result);
     } else {
       ForElement result = forest.createForElement(offsetForToken(forToken),
           variables, condition, updates, toValue(entry));
-      typeInferrer?.assignedVariables?.endNode(result);
+      typeInferrer.assignedVariables.endNode(result);
       push(result);
     }
   }
@@ -2955,10 +2974,10 @@
     debugEvent("ForStatement");
     Statement body = popStatement();
 
-    int updateExpressionCount = pop();
+    int updateExpressionCount = pop() as int;
     pop(); // Left separator.
     pop(); // Left parenthesis.
-    Token forKeyword = pop();
+    Token forKeyword = pop() as Token;
 
     assert(checkState(endToken, <ValueKind>[
       /* expressions */ ...repeatedKinds(
@@ -2982,20 +3001,22 @@
     // [handleForInitializerExpressionStatement], and
     // [handleForInitializerLocalVariableDeclaration].
     AssignedVariablesNodeInfo<VariableDeclaration> assignedVariablesNodeInfo =
-        typeInferrer?.assignedVariables?.deferNode();
+        typeInferrer.assignedVariables.deferNode();
 
-    Object variableOrExpression = pop();
-    List<VariableDeclaration> variables =
+    Object? variableOrExpression = pop();
+    List<VariableDeclaration>? variables =
         _buildForLoopVariableDeclarations(variableOrExpression);
     exitLocalScope();
-    JumpTarget continueTarget = exitContinueTarget();
-    JumpTarget breakTarget = exitBreakTarget();
-    List<BreakStatementImpl> continueStatements;
+    JumpTarget continueTarget = exitContinueTarget() as JumpTarget;
+    JumpTarget breakTarget = exitBreakTarget() as JumpTarget;
+    List<BreakStatementImpl>? continueStatements;
     if (continueTarget.hasUsers) {
-      body = forest.createLabeledStatement(body);
-      continueStatements = continueTarget.resolveContinues(forest, body);
+      LabeledStatement labeledStatement = forest.createLabeledStatement(body);
+      continueStatements =
+          continueTarget.resolveContinues(forest, labeledStatement);
+      body = labeledStatement;
     }
-    Expression condition;
+    Expression? condition;
     if (conditionStatement is ExpressionStatement) {
       condition = conditionStatement.expression;
     } else {
@@ -3003,8 +3024,8 @@
     }
     Statement forStatement = forest.createForStatement(
         offsetForToken(forKeyword), variables, condition, updates, body);
-    typeInferrer?.assignedVariables
-        ?.storeInfo(forStatement, assignedVariablesNodeInfo);
+    typeInferrer.assignedVariables
+        .storeInfo(forStatement, assignedVariablesNodeInfo);
     if (continueStatements != null) {
       for (BreakStatementImpl continueStatement in continueStatements) {
         continueStatement.targetStatement = forStatement;
@@ -3012,8 +3033,9 @@
     }
     Statement result = forStatement;
     if (breakTarget.hasUsers) {
-      result = forest.createLabeledStatement(result);
-      breakTarget.resolveBreaks(forest, result, forStatement);
+      LabeledStatement labeledStatement = forest.createLabeledStatement(result);
+      breakTarget.resolveBreaks(forest, labeledStatement, forStatement);
+      result = labeledStatement;
     }
     if (variableOrExpression is ParserRecovery) {
       problemInLoopOrSwitch ??= buildProblemStatement(
@@ -3045,7 +3067,7 @@
   }
 
   @override
-  void endInvalidYieldStatement(Token keyword, Token starToken, Token endToken,
+  void endInvalidYieldStatement(Token keyword, Token? starToken, Token endToken,
       fasta.MessageCode errorCode) {
     debugEvent("YieldStatement");
     popForValue();
@@ -3053,14 +3075,14 @@
   }
 
   @override
-  void handleAsyncModifier(Token asyncToken, Token starToken) {
+  void handleAsyncModifier(Token? asyncToken, Token? starToken) {
     debugEvent("AsyncModifier");
     push(asyncMarkerFromTokens(asyncToken, starToken));
   }
 
   @override
   void handleLiteralList(
-      int count, Token leftBracket, Token constKeyword, Token rightBracket) {
+      int count, Token leftBracket, Token? constKeyword, Token rightBracket) {
     debugEvent("LiteralList");
 
     if (constantContext == ConstantContext.required && constKeyword == null) {
@@ -3071,9 +3093,9 @@
     // TODO(danrubel): Replace this with popListForValue
     // when control flow and spread collections have been enabled by default
     List<Expression> expressions =
-        new List<Expression>.filled(count, null, growable: true);
+        new List<Expression>.filled(count, dummyExpression, growable: true);
     for (int i = count - 1; i >= 0; i--) {
-      Object elem = pop();
+      Object? elem = pop();
       if (elem != invalidCollectionElement) {
         expressions[i] = toValue(elem);
       } else {
@@ -3081,7 +3103,7 @@
       }
     }
 
-    List<UnresolvedType> typeArguments = pop();
+    List<UnresolvedType>? typeArguments = pop() as List<UnresolvedType>?;
 
     DartType typeArgument;
     if (typeArguments != null) {
@@ -3100,7 +3122,7 @@
       typeArgument = implicitTypeArgument;
     }
 
-    Expression node = forest.createListLiteral(
+    ListLiteral node = forest.createListLiteral(
         // TODO(johnniwinther): The file offset computed below will not be
         // correct if there are type arguments but no `const` keyword.
         offsetForToken(constKeyword ?? leftBracket),
@@ -3112,8 +3134,8 @@
     push(node);
   }
 
-  void buildLiteralSet(List<UnresolvedType> typeArguments, Token constKeyword,
-      Token leftBrace, List<dynamic> setOrMapEntries) {
+  void buildLiteralSet(List<UnresolvedType>? typeArguments, Token? constKeyword,
+      Token leftBrace, List<dynamic>? setOrMapEntries) {
     DartType typeArgument;
     if (typeArguments != null) {
       typeArgument = buildDartType(typeArguments.single);
@@ -3138,7 +3160,7 @@
       }
     }
 
-    Expression node = forest.createSetLiteral(
+    SetLiteral node = forest.createSetLiteral(
         // TODO(johnniwinther): The file offset computed below will not be
         // correct if there are type arguments but no `const` keyword.
         offsetForToken(constKeyword ?? leftBrace),
@@ -3154,7 +3176,7 @@
   void handleLiteralSetOrMap(
     int count,
     Token leftBrace,
-    Token constKeyword,
+    Token? constKeyword,
     Token rightBrace,
     // TODO(danrubel): hasSetEntry parameter exists for replicating existing
     // behavior and will be removed once unified collection has been enabled
@@ -3170,7 +3192,7 @@
     List<dynamic> setOrMapEntries =
         new List<dynamic>.filled(count, null, growable: true);
     for (int i = count - 1; i >= 0; i--) {
-      Object elem = pop();
+      Object? elem = pop();
       // TODO(danrubel): Revise this to handle control flow and spread
       if (elem == invalidCollectionElement) {
         setOrMapEntries.removeAt(i);
@@ -3180,7 +3202,7 @@
         setOrMapEntries[i] = toValue(elem);
       }
     }
-    List<UnresolvedType> typeArguments = pop();
+    List<UnresolvedType>? typeArguments = pop() as List<UnresolvedType>?;
 
     // Replicate existing behavior that has been removed from the parser.
     // This will be removed once unified collections is implemented.
@@ -3189,8 +3211,8 @@
     // TODO(danrubel): Since type resolution is needed to disambiguate
     // set or map in some situations, consider always deferring determination
     // until the type resolution phase.
-    final int typeArgCount = typeArguments?.length;
-    bool isSet = typeArgCount == 1
+    final int? typeArgCount = typeArguments?.length;
+    bool? isSet = typeArgCount == 1
         ? true
         : typeArgCount != null
             ? false
@@ -3212,14 +3234,14 @@
     if (isSet) {
       buildLiteralSet(typeArguments, constKeyword, leftBrace, setOrMapEntries);
     } else {
-      List<MapLiteralEntry> mapEntries =
-          new List<MapLiteralEntry>.filled(setOrMapEntries.length, null);
+      List<MapLiteralEntry> mapEntries = new List<MapLiteralEntry>.filled(
+          setOrMapEntries.length, dummyMapLiteralEntry);
       for (int i = 0; i < setOrMapEntries.length; ++i) {
         if (setOrMapEntries[i] is MapLiteralEntry) {
           mapEntries[i] = setOrMapEntries[i];
         } else {
           mapEntries[i] = convertToMapEntry(setOrMapEntries[i], this,
-              typeInferrer?.assignedVariables?.reassignInfo);
+              typeInferrer.assignedVariables.reassignInfo);
         }
       }
       buildLiteralMap(typeArguments, constKeyword, leftBrace, mapEntries);
@@ -3247,7 +3269,7 @@
     push(forest.createNullLiteral(offsetForToken(token)));
   }
 
-  void buildLiteralMap(List<UnresolvedType> typeArguments, Token constKeyword,
+  void buildLiteralMap(List<UnresolvedType>? typeArguments, Token? constKeyword,
       Token leftBrace, List<MapLiteralEntry> entries) {
     DartType keyType;
     DartType valueType;
@@ -3269,7 +3291,7 @@
       valueType = implicitTypeArgument;
     }
 
-    Expression node = forest.createMapLiteral(
+    MapLiteral node = forest.createMapLiteral(
         // TODO(johnniwinther): The file offset computed below will not be
         // correct if there are type arguments but no `const` keyword.
         offsetForToken(constKeyword ?? leftBrace),
@@ -3304,7 +3326,7 @@
   void endLiteralSymbol(Token hashToken, int identifierCount) {
     debugEvent("LiteralSymbol");
     if (identifierCount == 1) {
-      Object part = pop();
+      Object? part = pop();
       if (part is ParserRecovery) {
         push(new ParserErrorGenerator(
             this, hashToken, fasta.messageSyntheticToken));
@@ -3313,8 +3335,8 @@
             offsetForToken(hashToken), symbolPartToString(part)));
       }
     } else {
-      List<Identifier> parts =
-          const FixedNullableList<Identifier>().pop(stack, identifierCount);
+      List<Identifier>? parts = const FixedNullableList<Identifier>()
+          .popNonNullable(stack, identifierCount, dummyIdentifier);
       if (parts == null) {
         push(new ParserErrorGenerator(
             this, hashToken, fasta.messageSyntheticToken));
@@ -3346,15 +3368,15 @@
   }
 
   @override
-  void handleType(Token beginToken, Token questionMark) {
+  void handleType(Token beginToken, Token? questionMark) {
     // TODO(ahe): The scope is wrong for return types of generic functions.
     debugEvent("Type");
     if (!libraryBuilder.isNonNullableByDefault) {
       reportErrorIfNullableType(questionMark);
     }
     bool isMarkedAsNullable = questionMark != null;
-    List<UnresolvedType> arguments = pop();
-    Object name = pop();
+    List<UnresolvedType>? arguments = pop() as List<UnresolvedType>?;
+    Object? name = pop();
     if (name is QualifiedName) {
       QualifiedName qualified = name;
       Object prefix = qualified.qualifier;
@@ -3384,10 +3406,11 @@
         return;
       }
     }
-    TypeBuilder result;
+    TypeBuilder? result;
     if (name is Generator) {
       result = name.buildTypeWithResolvedArguments(
           libraryBuilder.nullableBuilderIfTrue(isMarkedAsNullable), arguments);
+      // ignore: unnecessary_null_comparison
       if (result == null) {
         unhandled("null", "result", beginToken.charOffset, uri);
       }
@@ -3417,15 +3440,16 @@
     debugEvent("beginFunctionType");
   }
 
-  void enterFunctionTypeScope(List<TypeVariableBuilder> typeVariables) {
+  void enterFunctionTypeScope(List<TypeVariableBuilder>? typeVariables) {
     debugEvent("enterFunctionTypeScope");
-    enterLocalScope(null,
+    enterLocalScope('FunctionTypeScope',
         scope.createNestedScope("function-type scope", isModifiable: true));
     if (typeVariables != null) {
       ScopeBuilder scopeBuilder = new ScopeBuilder(scope);
       for (TypeVariableBuilder builder in typeVariables) {
         String name = builder.name;
-        TypeVariableBuilder existing = scopeBuilder[name];
+        TypeVariableBuilder? existing =
+            scopeBuilder[name] as TypeVariableBuilder?;
         if (existing == null) {
           scopeBuilder.addMember(name, builder);
         } else {
@@ -3436,14 +3460,15 @@
   }
 
   @override
-  void endFunctionType(Token functionToken, Token questionMark) {
+  void endFunctionType(Token functionToken, Token? questionMark) {
     debugEvent("FunctionType");
     if (!libraryBuilder.isNonNullableByDefault) {
       reportErrorIfNullableType(questionMark);
     }
-    FormalParameters formals = pop();
-    UnresolvedType returnType = pop();
-    List<TypeVariableBuilder> typeVariables = pop();
+    FormalParameters formals = pop() as FormalParameters;
+    UnresolvedType? returnType = pop() as UnresolvedType?;
+    List<TypeVariableBuilder>? typeVariables =
+        pop() as List<TypeVariableBuilder>?;
     if (typeVariables != null) {
       for (TypeVariableBuilder builder in typeVariables) {
         if (builder.parameter.annotations.isNotEmpty) {
@@ -3497,13 +3522,13 @@
 
   @override
   void endAsOperatorType(Token operator) {
-    _isOrAsOperatorTypeState = _isOrAsOperatorTypeState.tail;
+    _isOrAsOperatorTypeState = _isOrAsOperatorTypeState.tail!;
   }
 
   @override
   void handleAsOperator(Token operator) {
     debugEvent("AsOperator");
-    DartType type = buildDartType(pop(),
+    DartType type = buildDartType(pop() as UnresolvedType,
         allowPotentiallyConstantType: libraryBuilder.isNonNullableByDefault);
     libraryBuilder.checkBoundsInType(
         type, typeEnvironment, uri, operator.charOffset);
@@ -3521,13 +3546,13 @@
 
   @override
   void endIsOperatorType(Token operator) {
-    _isOrAsOperatorTypeState = _isOrAsOperatorTypeState.tail;
+    _isOrAsOperatorTypeState = _isOrAsOperatorTypeState.tail!;
   }
 
   @override
-  void handleIsOperator(Token isOperator, Token not) {
+  void handleIsOperator(Token isOperator, Token? not) {
     debugEvent("IsOperator");
-    DartType type = buildDartType(pop(),
+    DartType type = buildDartType(pop() as UnresolvedType,
         allowPotentiallyConstantType: libraryBuilder.isNonNullableByDefault);
     Expression operand = popForValue();
     Expression isExpression = forest.createIsExpression(
@@ -3544,7 +3569,7 @@
     Expression condition = popForValue();
     // This is matched by the call to [deferNode] in
     // [handleConditionalExpressionColon].
-    typeInferrer?.assignedVariables?.beginNode();
+    typeInferrer.assignedVariables.beginNode();
     push(condition);
     super.beginConditionalExpression(question);
   }
@@ -3555,7 +3580,7 @@
     // This is matched by the call to [beginNode] in
     // [beginConditionalExpression] and by the call to [storeInfo] in
     // [endConditionalExpression].
-    push(typeInferrer?.assignedVariables?.deferNode());
+    push(typeInferrer.assignedVariables.deferNode());
     push(then);
     super.handleConditionalExpressionColon();
   }
@@ -3564,16 +3589,16 @@
   void endConditionalExpression(Token question, Token colon) {
     debugEvent("ConditionalExpression");
     Expression elseExpression = popForValue();
-    Expression thenExpression = pop();
+    Expression thenExpression = pop() as Expression;
     AssignedVariablesNodeInfo<VariableDeclaration> assignedVariablesInfo =
-        pop();
-    Expression condition = pop();
+        pop() as AssignedVariablesNodeInfo<VariableDeclaration>;
+    Expression condition = pop() as Expression;
     Expression node = forest.createConditionalExpression(
         offsetForToken(question), condition, thenExpression, elseExpression);
     push(node);
     // This is matched by the call to [deferNode] in
     // [handleConditionalExpressionColon].
-    typeInferrer?.assignedVariables?.storeInfo(node, assignedVariablesInfo);
+    typeInferrer.assignedVariables.storeInfo(node, assignedVariablesInfo);
   }
 
   @override
@@ -3591,8 +3616,8 @@
   }
 
   @override
-  void beginFormalParameter(Token token, MemberKind kind, Token requiredToken,
-      Token covariantToken, Token varFinalOrConst) {
+  void beginFormalParameter(Token token, MemberKind kind, Token? requiredToken,
+      Token? covariantToken, Token? varFinalOrConst) {
     // TODO(danrubel): handle required token
     if (!libraryBuilder.isNonNullableByDefault) {
       reportNonNullableModifierError(requiredToken);
@@ -3604,11 +3629,11 @@
 
   @override
   void endFormalParameter(
-      Token thisKeyword,
-      Token periodAfterThis,
+      Token? thisKeyword,
+      Token? periodAfterThis,
       Token nameToken,
-      Token initializerStart,
-      Token initializerEnd,
+      Token? initializerStart,
+      Token? initializerEnd,
       FormalParameterKind kind,
       MemberKind memberKind) {
     debugEvent("FormalParameter");
@@ -3619,9 +3644,9 @@
         thisKeyword = null;
       }
     }
-    Object nameNode = pop();
-    UnresolvedType type = pop();
-    if (functionNestingLevel == 0) {
+    Object? nameNode = pop();
+    UnresolvedType? type = pop() as UnresolvedType?;
+    if (functionNestingLevel == 0 && type != null) {
       // TODO(ahe): The type we compute here may be different from what is
       // computed in the outline phase. We should make sure that the outline
       // phase computes the same type. See
@@ -3631,22 +3656,22 @@
       // `invalid-type`.
       buildDartType(type);
     }
-    int modifiers = pop();
+    int modifiers = pop() as int;
     if (inCatchClause) {
       modifiers |= finalMask;
     }
-    List<Expression> annotations = pop();
+    List<Expression>? annotations = pop() as List<Expression>?;
     if (nameNode is ParserRecovery) {
       push(nameNode);
       return;
     }
-    Identifier name = nameNode;
-    FormalParameterBuilder parameter;
+    Identifier? name = nameNode as Identifier?;
+    FormalParameterBuilder? parameter;
     if (!inCatchClause &&
         functionNestingLevel == 0 &&
         memberKind != MemberKind.GeneralizedFunctionType) {
-      FunctionBuilder member = this.member;
-      parameter = member.getFormal(name);
+      FunctionBuilder member = this.member as FunctionBuilder;
+      parameter = member.getFormal(name!);
       if (parameter == null) {
         // This happens when the list of formals (originally) contains a
         // ParserRecovery - then the popped list becomes null.
@@ -3655,16 +3680,17 @@
       }
     } else {
       parameter = new FormalParameterBuilder(null, modifiers, type?.builder,
-          name?.name, libraryBuilder, offsetForToken(nameToken),
+          name?.name ?? '', libraryBuilder, offsetForToken(nameToken),
           fileUri: uri)
         ..hasDeclaredInitializer = (initializerStart != null);
     }
     VariableDeclaration variable = parameter.build(
-        libraryBuilder, functionNestingLevel, !isDeclarationInstanceContext);
-    Expression initializer = name?.initializer;
+        libraryBuilder, functionNestingLevel,
+        nonInstanceContext: !isDeclarationInstanceContext);
+    Expression? initializer = name?.initializer;
     if (initializer != null) {
       if (member is RedirectingFactoryBuilder) {
-        RedirectingFactoryBuilder factory = member;
+        RedirectingFactoryBuilder factory = member as RedirectingFactoryBuilder;
         addProblem(
             fasta.templateDefaultValueInRedirectingFactoryConstructor
                 .withArguments(factory.redirectionTarget.fullNameForErrors),
@@ -3689,7 +3715,7 @@
       }
     }
     push(parameter);
-    typeInferrer?.assignedVariables?.declare(variable);
+    typeInferrer.assignedVariables.declare(variable);
   }
 
   @override
@@ -3703,8 +3729,9 @@
     // 0. It might be simpler if the parser didn't call this method in that
     // case, however, then [beginOptionalFormalParameters] wouldn't always be
     // matched by this method.
-    List<FormalParameterBuilder> parameters =
-        const FixedNullableList<FormalParameterBuilder>().pop(stack, count);
+    List<FormalParameterBuilder>? parameters =
+        const FixedNullableList<FormalParameterBuilder>()
+            .popNonNullable(stack, count, dummyFormalParameterBuilder);
     if (parameters == null) {
       push(new ParserRecovery(offsetForToken(beginToken)));
     } else {
@@ -3722,14 +3749,15 @@
   }
 
   @override
-  void endFunctionTypedFormalParameter(Token nameToken, Token question) {
+  void endFunctionTypedFormalParameter(Token nameToken, Token? question) {
     debugEvent("FunctionTypedFormalParameter");
     if (inCatchClause || functionNestingLevel != 0) {
       exitLocalScope();
     }
-    FormalParameters formals = pop();
-    UnresolvedType returnType = pop();
-    List<TypeVariableBuilder> typeVariables = pop();
+    FormalParameters formals = pop() as FormalParameters;
+    UnresolvedType? returnType = pop() as UnresolvedType?;
+    List<TypeVariableBuilder>? typeVariables =
+        pop() as List<TypeVariableBuilder>?;
     if (!libraryBuilder.isNonNullableByDefault) {
       reportErrorIfNullableType(question);
     }
@@ -3749,8 +3777,8 @@
   @override
   void endFormalParameterDefaultValueExpression() {
     debugEvent("FormalParameterDefaultValueExpression");
-    Object defaultValueExpression = pop();
-    constantContext = pop();
+    Object? defaultValueExpression = pop();
+    constantContext = pop() as ConstantContext;
     push(defaultValueExpression);
   }
 
@@ -3758,11 +3786,11 @@
   void handleValuedFormalParameter(Token equals, Token token) {
     debugEvent("ValuedFormalParameter");
     Expression initializer = popForValue();
-    Object name = pop();
+    Object? name = pop();
     if (name is ParserRecovery) {
       push(name);
     } else {
-      push(new InitializedIdentifier(name, initializer));
+      push(new InitializedIdentifier(name as Identifier, initializer));
     }
   }
 
@@ -3781,30 +3809,28 @@
   void endFormalParameters(
       int count, Token beginToken, Token endToken, MemberKind kind) {
     debugEvent("FormalParameters");
-    List<FormalParameterBuilder> optionals;
+    List<FormalParameterBuilder>? optionals;
     int optionalsCount = 0;
     if (count > 0 && peek() is List<FormalParameterBuilder>) {
-      optionals = pop();
+      optionals = pop() as List<FormalParameterBuilder>;
       count--;
       optionalsCount = optionals.length;
     }
-    List<FormalParameterBuilder> parameters =
-        const FixedNullableList<FormalParameterBuilder>()
-            .popPadded(stack, count, optionalsCount);
+    List<FormalParameterBuilder>? parameters =
+        const FixedNullableList<FormalParameterBuilder>().popPaddedNonNullable(
+            stack, count, optionalsCount, dummyFormalParameterBuilder);
     if (optionals != null && parameters != null) {
       parameters.setRange(count, count + optionalsCount, optionals);
     }
     assert(parameters?.isNotEmpty ?? true);
     FormalParameters formals = new FormalParameters(parameters,
         offsetForToken(beginToken), lengthOfSpan(beginToken, endToken), uri);
-    constantContext = pop();
+    constantContext = pop() as ConstantContext;
     push(formals);
     if ((inCatchClause || functionNestingLevel != 0) &&
         kind != MemberKind.GeneralizedFunctionType) {
-      enterLocalScope(
-          null,
-          formals.computeFormalParameterScope(
-              scope, member ?? classBuilder ?? libraryBuilder, this));
+      enterLocalScope('formalParameters',
+          formals.computeFormalParameterScope(scope, member, this));
     }
   }
 
@@ -3823,29 +3849,36 @@
   }
 
   @override
-  void handleCatchBlock(Token onKeyword, Token catchKeyword, Token comma) {
+  void handleCatchBlock(Token? onKeyword, Token? catchKeyword, Token? comma) {
     debugEvent("CatchBlock");
-    Statement body = pop();
-    inCatchBlock = pop();
+    Statement body = pop() as Statement;
+    inCatchBlock = pop() as bool;
     if (catchKeyword != null) {
       exitLocalScope();
     }
-    FormalParameters catchParameters = popIfNotNull(catchKeyword);
-    DartType exceptionType = buildDartType(popIfNotNull(onKeyword)) ??
-        (libraryBuilder.isNonNullableByDefault
-            ? coreTypes.objectNonNullableRawType
-            : const DynamicType());
-    FormalParameterBuilder exception;
-    FormalParameterBuilder stackTrace;
-    List<Statement> compileTimeErrors;
+    FormalParameters? catchParameters =
+        popIfNotNull(catchKeyword) as FormalParameters?;
+    UnresolvedType? unresolvedExceptionType =
+        popIfNotNull(onKeyword) as UnresolvedType?;
+    DartType exceptionType;
+    if (unresolvedExceptionType != null) {
+      exceptionType = buildDartType(unresolvedExceptionType);
+    } else {
+      exceptionType = (libraryBuilder.isNonNullableByDefault
+          ? coreTypes.objectNonNullableRawType
+          : const DynamicType());
+    }
+    FormalParameterBuilder? exception;
+    FormalParameterBuilder? stackTrace;
+    List<Statement>? compileTimeErrors;
     if (catchParameters?.parameters != null) {
-      int parameterCount = catchParameters.parameters.length;
+      int parameterCount = catchParameters!.parameters!.length;
       if (parameterCount > 0) {
-        exception = catchParameters.parameters[0];
+        exception = catchParameters.parameters![0];
         exception.build(libraryBuilder, functionNestingLevel).type =
             exceptionType;
         if (parameterCount > 1) {
-          stackTrace = catchParameters.parameters[1];
+          stackTrace = catchParameters.parameters![1];
           stackTrace.build(libraryBuilder, functionNestingLevel).type =
               coreTypes.stackTraceRawType(libraryBuilder.nonNullable);
         }
@@ -3854,7 +3887,7 @@
         // If parameterCount is 0, the parser reported an error already.
         if (parameterCount != 0) {
           for (int i = 2; i < parameterCount; i++) {
-            FormalParameterBuilder parameter = catchParameters.parameters[i];
+            FormalParameterBuilder parameter = catchParameters.parameters![i];
             compileTimeErrors ??= <Statement>[];
             compileTimeErrors.add(buildProblemStatement(
                 fasta.messageCatchSyntaxExtraParameters, parameter.charOffset,
@@ -3880,28 +3913,30 @@
   @override
   void beginTryStatement(Token token) {
     // This is matched by the call to [endNode] in [endTryStatement].
-    typeInferrer?.assignedVariables?.beginNode();
+    typeInferrer.assignedVariables.beginNode();
   }
 
   @override
-  void endTryStatement(int catchCount, Token tryKeyword, Token finallyKeyword) {
-    Statement finallyBlock;
+  void endTryStatement(
+      int catchCount, Token tryKeyword, Token? finallyKeyword) {
+    Statement? finallyBlock;
     if (finallyKeyword != null) {
-      finallyBlock = pop();
+      finallyBlock = pop() as Statement;
     } else {
       // This is matched by the call to [beginNode] in [beginTryStatement].
       tryStatementInfoStack = tryStatementInfoStack
-          .prepend(typeInferrer?.assignedVariables?.deferNode());
+          .prepend(typeInferrer.assignedVariables.deferNode());
     }
-    List<Catch> catchBlocks;
-    List<Statement> compileTimeErrors;
+    List<Catch>? catchBlocks;
+    List<Statement>? compileTimeErrors;
     if (catchCount != 0) {
-      List<Object> catchBlocksAndErrors =
-          const FixedNullableList<Object>().pop(stack, catchCount * 2);
-      catchBlocks = new List<Catch>.filled(catchCount, null, growable: true);
+      List<Object?> catchBlocksAndErrors =
+          const FixedNullableList<Object?>().pop(stack, catchCount * 2)!;
+      catchBlocks =
+          new List<Catch>.filled(catchCount, dummyCatch, growable: true);
       for (int i = 0; i < catchCount; i++) {
-        catchBlocks[i] = catchBlocksAndErrors[i * 2];
-        Statement error = catchBlocksAndErrors[i * 2 + 1];
+        catchBlocks[i] = catchBlocksAndErrors[i * 2] as Catch;
+        Statement? error = catchBlocksAndErrors[i * 2 + 1] as Statement?;
         if (error != null) {
           compileTimeErrors ??= <Statement>[];
           compileTimeErrors.add(error);
@@ -3912,9 +3947,9 @@
     int fileOffset = offsetForToken(tryKeyword);
     Statement result = forest.createTryStatement(
         fileOffset, tryBlock, catchBlocks, finallyBlock);
-    typeInferrer?.assignedVariables
-        ?.storeInfo(result, tryStatementInfoStack.head);
-    tryStatementInfoStack = tryStatementInfoStack.tail;
+    typeInferrer.assignedVariables
+        .storeInfo(result, tryStatementInfoStack.head);
+    tryStatementInfoStack = tryStatementInfoStack.tail!;
 
     if (compileTimeErrors != null) {
       compileTimeErrors.add(result);
@@ -3926,7 +3961,7 @@
 
   @override
   void handleIndexedExpression(
-      Token question, Token openSquareBracket, Token closeSquareBracket) {
+      Token? question, Token openSquareBracket, Token closeSquareBracket) {
     assert(checkState(openSquareBracket, [
       unionOfKinds([ValueKinds.Expression, ValueKinds.Generator]),
       unionOfKinds(
@@ -3934,7 +3969,7 @@
     ]));
     debugEvent("IndexedExpression");
     Expression index = popForValue();
-    Object receiver = pop();
+    Object? receiver = pop();
     bool isNullAware = question != null;
     if (isNullAware && !libraryBuilder.isNonNullableByDefault) {
       reportMissingNonNullableSupport(openSquareBracket);
@@ -3963,11 +3998,11 @@
       ]),
     ]));
     debugEvent("UnaryPrefixExpression");
-    Object receiver = pop();
+    Object? receiver = pop();
     if (optional("!", token)) {
       push(forest.createNot(offsetForToken(token), toValue(receiver)));
     } else {
-      String operator = token.stringValue;
+      String operator = token.stringValue!;
       if (optional("-", token)) {
         operator = "unary-";
       }
@@ -3977,7 +4012,7 @@
         push(receiver.buildUnaryOperation(token, name));
       } else {
         assert(receiver is Expression);
-        push(forest.createUnary(fileOffset, name, receiver));
+        push(forest.createUnary(fileOffset, name, receiver as Expression));
       }
     }
   }
@@ -3991,7 +4026,7 @@
   @override
   void handleUnaryPrefixAssignmentExpression(Token token) {
     debugEvent("UnaryPrefixAssignmentExpression");
-    Object generator = pop();
+    Object? generator = pop();
     if (generator is Generator) {
       push(generator.buildPrefixIncrement(incrementOperator(token),
           offset: token.charOffset));
@@ -4005,7 +4040,7 @@
   @override
   void handleUnaryPostfixAssignmentExpression(Token token) {
     debugEvent("UnaryPostfixAssignmentExpression");
-    Object generator = pop();
+    Object? generator = pop();
     if (generator is Generator) {
       push(new DelayedPostfixIncrement(
           this, token, generator, incrementOperator(token)));
@@ -4018,7 +4053,7 @@
 
   @override
   void endConstructorReference(
-      Token start, Token periodBeforeName, Token endToken) {
+      Token start, Token? periodBeforeName, Token endToken) {
     debugEvent("ConstructorReference");
     pushQualifiedReference(start, periodBeforeName);
   }
@@ -4056,7 +4091,7 @@
   /// stack and pushes 3 values: a generator (the type in a constructor
   /// reference, or an expression in metadata), a list of type arguments, and a
   /// name.
-  void pushQualifiedReference(Token start, Token periodBeforeName) {
+  void pushQualifiedReference(Token start, Token? periodBeforeName) {
     assert(checkState(start, [
       /*suffix*/ if (periodBeforeName != null)
         unionOfKinds([ValueKinds.Identifier, ValueKinds.ParserRecovery]),
@@ -4068,8 +4103,8 @@
         ValueKinds.ParserRecovery
       ])
     ]));
-    Object suffixObject = popIfNotNull(periodBeforeName);
-    Identifier suffix;
+    Object? suffixObject = popIfNotNull(periodBeforeName);
+    Identifier? suffix;
     if (suffixObject is Identifier) {
       suffix = suffixObject;
     } else {
@@ -4080,9 +4115,9 @@
       // There was a `.` without a suffix.
     }
 
-    Identifier identifier;
-    List<UnresolvedType> typeArguments = pop();
-    Object type = pop();
+    Identifier? identifier;
+    List<UnresolvedType>? typeArguments = pop() as List<UnresolvedType>?;
+    Object? type = pop();
     if (type is QualifiedName) {
       identifier = type;
       QualifiedName qualified = type;
@@ -4138,18 +4173,18 @@
   @override
   Expression buildStaticInvocation(Member target, Arguments arguments,
       {Constness constness: Constness.implicit,
-      TypeAliasBuilder typeAliasBuilder,
+      TypeAliasBuilder? typeAliasBuilder,
       int charOffset: -1,
       int charLength: noLength}) {
     // The argument checks for the initial target of redirecting factories
     // invocations are skipped in Dart 1.
-    List<TypeParameter> typeParameters = target.function.typeParameters;
+    List<TypeParameter> typeParameters = target.function!.typeParameters;
     if (target is Constructor) {
       assert(!target.enclosingClass.isAbstract);
       typeParameters = target.enclosingClass.typeParameters;
     }
-    LocatedMessage argMessage = checkArgumentsForFunction(
-        target.function, arguments, charOffset, typeParameters);
+    LocatedMessage? argMessage = checkArgumentsForFunction(
+        target.function!, arguments, charOffset, typeParameters);
     if (argMessage != null) {
       return throwNoSuchMethodError(forest.createNullLiteral(charOffset),
           target.name.text, arguments, charOffset,
@@ -4174,17 +4209,18 @@
         libraryBuilder.checkBoundsInConstructorInvocation(
             node, typeEnvironment, uri);
       } else {
-        node = new TypeAliasedConstructorInvocationJudgment(
-            typeAliasBuilder, target, arguments,
-            isConst: isConst)
-          ..fileOffset = charOffset;
+        TypeAliasedConstructorInvocationJudgment constructorInvocation =
+            node = new TypeAliasedConstructorInvocationJudgment(
+                typeAliasBuilder, target, arguments,
+                isConst: isConst)
+              ..fileOffset = charOffset;
         // No type arguments were passed, so we need not check bounds.
         assert(arguments.types.isEmpty);
-        typeAliasedConstructorInvocations.add(node);
+        typeAliasedConstructorInvocations.add(constructorInvocation);
       }
       return node;
     } else {
-      Procedure procedure = target;
+      Procedure procedure = target as Procedure;
       if (procedure.isFactory) {
         if (constantContext == ConstantContext.required &&
             constness == Constness.implicit) {
@@ -4203,13 +4239,15 @@
               node, typeEnvironment, uri,
               inferred: !hasExplicitTypeArguments(arguments));
         } else {
-          node = new TypeAliasedFactoryInvocationJudgment(
-              typeAliasBuilder, target, arguments,
-              isConst: isConst)
-            ..fileOffset = charOffset;
+          TypeAliasedFactoryInvocationJudgment constructorInvocation =
+              new TypeAliasedFactoryInvocationJudgment(
+                  typeAliasBuilder, target, arguments,
+                  isConst: isConst)
+                ..fileOffset = charOffset;
           // No type arguments were passed, so we need not check bounds.
           assert(arguments.types.isEmpty);
-          typeAliasedFactoryInvocations.add(node);
+          typeAliasedFactoryInvocations.add(constructorInvocation);
+          node = constructorInvocation;
         }
         return node;
       } else {
@@ -4222,9 +4260,9 @@
 
   Expression buildExtensionMethodInvocation(
       int fileOffset, Procedure target, Arguments arguments,
-      {bool isTearOff}) {
+      {required bool isTearOff}) {
     List<TypeParameter> typeParameters = target.function.typeParameters;
-    LocatedMessage argMessage = checkArgumentsForFunction(
+    LocatedMessage? argMessage = checkArgumentsForFunction(
         target.function, arguments, fileOffset, typeParameters,
         isExtensionMemberInvocation: true);
     if (argMessage != null) {
@@ -4244,7 +4282,7 @@
   }
 
   @override
-  LocatedMessage checkArgumentsForFunction(FunctionNode function,
+  LocatedMessage? checkArgumentsForFunction(FunctionNode function,
       Arguments arguments, int offset, List<TypeParameter> typeParameters,
       {bool isExtensionMemberInvocation = false}) {
     int requiredPositionalParameterCountToReport =
@@ -4291,7 +4329,7 @@
         for (VariableDeclaration parameter in function.namedParameters) {
           if (parameter.isRequired && !argumentNames.contains(parameter.name)) {
             return fasta.templateValueForRequiredParameterNotProvidedError
-                .withArguments(parameter.name)
+                .withArguments(parameter.name!)
                 .withLocation(uri, arguments.fileOffset, fasta.noLength);
           }
         }
@@ -4316,7 +4354,7 @@
   }
 
   @override
-  LocatedMessage checkArgumentsForType(
+  LocatedMessage? checkArgumentsForType(
       FunctionType function, Arguments arguments, int offset,
       {bool isExtensionMemberInvocation = false}) {
     int requiredPositionalParameterCountToReport =
@@ -4418,8 +4456,8 @@
   @override
   void endConstLiteral(Token token) {
     debugEvent("endConstLiteral");
-    Object literal = pop();
-    constantContext = pop();
+    Object? literal = pop();
+    constantContext = pop() as ConstantContext;
     push(literal);
   }
 
@@ -4427,13 +4465,13 @@
   void endNewExpression(Token token) {
     debugEvent("NewExpression");
     _buildConstructorReferenceInvocation(
-        token.next, token.offset, Constness.explicitNew,
+        token.next!, token.offset, Constness.explicitNew,
         inMetadata: false);
   }
 
   void _buildConstructorReferenceInvocation(
       Token nameToken, int offset, Constness constness,
-      {bool inMetadata}) {
+      {required bool inMetadata}) {
     assert(checkState(nameToken, [
       /*arguments*/ ValueKinds.Arguments,
       /*constructor name identifier*/ ValueKinds.IdentifierOrNull,
@@ -4445,21 +4483,21 @@
         ValueKinds.ParserRecovery
       ]),
     ]));
-    Arguments arguments = pop();
-    Identifier nameLastIdentifier = pop(NullValue.Identifier);
+    Arguments arguments = pop() as Arguments;
+    Identifier? nameLastIdentifier = pop(NullValue.Identifier) as Identifier?;
     Token nameLastToken = nameLastIdentifier?.token ?? nameToken;
-    String name = pop();
-    List<UnresolvedType> typeArguments = pop();
+    String name = pop() as String;
+    List<UnresolvedType>? typeArguments = pop() as List<UnresolvedType>?;
     if (inMetadata && typeArguments != null) {
       if (!libraryBuilder.enableGenericMetadataInLibrary) {
         handleRecoverableError(fasta.messageMetadataTypeArguments,
-            nameLastToken.next, nameLastToken.next);
+            nameLastToken.next!, nameLastToken.next!);
       }
     }
 
-    Object type = pop();
+    Object? type = pop();
 
-    ConstantContext savedConstantContext = pop();
+    ConstantContext savedConstantContext = pop() as ConstantContext;
     if (type is Generator) {
       push(type.invokeConstructor(
           typeArguments, name, arguments, nameToken, nameLastToken, constness));
@@ -4467,12 +4505,12 @@
       push(new ParserErrorGenerator(
           this, nameToken, fasta.messageSyntheticToken));
     } else {
-      String typeName;
+      String? typeName;
       if (type is ProblemBuilder) {
         typeName = type.fullNameForErrors;
       }
       push(throwNoSuchMethodError(forest.createNullLiteral(offset),
-          debugName(typeName, name), arguments, nameToken.charOffset));
+          debugName(typeName!, name), arguments, nameToken.charOffset));
     }
     constantContext = savedConstantContext;
   }
@@ -4481,22 +4519,22 @@
   void endImplicitCreationExpression(Token token) {
     debugEvent("ImplicitCreationExpression");
     _buildConstructorReferenceInvocation(
-        token.next, token.offset, Constness.implicit,
+        token.next!, token.offset, Constness.implicit,
         inMetadata: false);
   }
 
   @override
   Expression buildConstructorInvocation(
-      TypeDeclarationBuilder type,
+      TypeDeclarationBuilder? type,
       Token nameToken,
       Token nameLastToken,
-      Arguments arguments,
+      Arguments? arguments,
       String name,
-      List<UnresolvedType> typeArguments,
+      List<UnresolvedType>? typeArguments,
       int charOffset,
       Constness constness,
       {bool isTypeArgumentsInForest = false,
-      TypeDeclarationBuilder typeAliasBuilder}) {
+      TypeDeclarationBuilder? typeAliasBuilder}) {
     if (arguments == null) {
       return buildProblem(fasta.messageMissingArgumentList,
           nameToken.charOffset, nameToken.length);
@@ -4507,8 +4545,8 @@
           nameToken.charOffset, nameToken.length);
     }
 
-    String errorName;
-    LocatedMessage message;
+    String? errorName;
+    LocatedMessage? message;
 
     if (type is TypeAliasBuilder) {
       errorName = debugName(type.name, name);
@@ -4533,7 +4571,7 @@
       List<TypeBuilder> typeArgumentBuilders = [];
       if (typeArguments != null) {
         for (UnresolvedType unresolvedType in typeArguments) {
-          typeArgumentBuilders.add(unresolvedType?.builder);
+          typeArgumentBuilders.add(unresolvedType.builder);
         }
       } else {
         if (aliasBuilder.typeVariablesCount > 0) {
@@ -4548,18 +4586,15 @@
                   arguments,
                   buildProblem(message.messageObject, nameToken.charOffset,
                       nameToken.lexeme.length));
-            } else {
-              errorName ??= debugName(type.fullNameForErrors, name);
             }
-            errorName ??= name;
 
             return throwNoSuchMethodError(forest.createNullLiteral(charOffset),
                 errorName, arguments, nameLastToken.charOffset,
                 message: message);
           }
-          MemberBuilder b = classBuilder.findConstructorOrFactory(
+          MemberBuilder? b = classBuilder.findConstructorOrFactory(
               name, charOffset, uri, libraryBuilder);
-          Member target = b?.member;
+          Member? target = b?.member;
           if (b == null) {
             // Not found. Reported below.
           } else if (b is AmbiguousMemberBuilder) {
@@ -4578,14 +4613,13 @@
           if (target is Constructor ||
               (target is Procedure && target.kind == ProcedureKind.Factory)) {
             Expression invocation;
-            invocation = buildStaticInvocation(target, arguments,
+            invocation = buildStaticInvocation(target!, arguments,
                 constness: constness,
                 typeAliasBuilder: aliasBuilder,
                 charOffset: nameToken.charOffset,
                 charLength: nameToken.length);
             return invocation;
           } else {
-            errorName ??= debugName(type.name, name);
             return throwNoSuchMethodError(forest.createNullLiteral(charOffset),
                 errorName, arguments, nameLastToken.charOffset,
                 message: message);
@@ -4594,7 +4628,7 @@
           // Empty `typeArguments` and `aliasBuilder``is non-generic, but it
           // may still unalias to a class type with some type arguments.
           if (type is ClassBuilder) {
-            List<TypeBuilder> unaliasedTypeArgumentBuilders =
+            List<TypeBuilder>? unaliasedTypeArgumentBuilders =
                 aliasBuilder.unaliasTypeArguments(const []);
             if (unaliasedTypeArgumentBuilders == null) {
               // TODO(eernst): This is a wrong number of type arguments,
@@ -4619,6 +4653,7 @@
       }
 
       List<DartType> typeArgumentsToCheck = const <DartType>[];
+      // ignore: unnecessary_null_comparison
       if (typeArgumentBuilders != null && typeArgumentBuilders.isNotEmpty) {
         typeArgumentsToCheck = new List.filled(
             typeArgumentBuilders.length, const DynamicType(),
@@ -4647,7 +4682,7 @@
                     nameToken.charOffset,
                     nameToken.length));
           }
-          List<TypeBuilder> unaliasedTypeArgumentBuilders =
+          List<TypeBuilder>? unaliasedTypeArgumentBuilders =
               aliasBuilder.unaliasTypeArguments(typeArgumentBuilders);
           if (unaliasedTypeArgumentBuilders == null) {
             // TODO(eernst): This is a wrong number of type arguments,
@@ -4668,19 +4703,18 @@
           assert(forest.argumentsTypeArguments(arguments).isEmpty);
           forest.argumentsSetTypeArguments(arguments, dartTypeArguments);
         } else {
-          if (type.typeVariables?.isEmpty ?? true) {
+          ClassBuilder cls = type;
+          if (cls.typeVariables?.isEmpty ?? true) {
             assert(forest.argumentsTypeArguments(arguments).isEmpty);
             forest.argumentsSetTypeArguments(arguments, []);
           } else {
             if (forest.argumentsTypeArguments(arguments).isEmpty) {
               // No type arguments provided to unaliased class, use defaults.
-              List<DartType> result = new List<DartType>.filled(
-                  type.typeVariables.length, null,
+              List<DartType> result = new List<DartType>.generate(
+                  cls.typeVariables!.length,
+                  (int i) =>
+                      cls.typeVariables![i].defaultType!.build(cls.library),
                   growable: true);
-              for (int i = 0; i < result.length; ++i) {
-                result[i] =
-                    type.typeVariables[i].defaultType?.build(type.library);
-              }
               forest.argumentsSetTypeArguments(arguments, result);
             }
           }
@@ -4698,9 +4732,9 @@
         return buildProblem(fasta.messageEnumInstantiation,
             nameToken.charOffset, nameToken.length);
       }
-      MemberBuilder b =
+      MemberBuilder? b =
           type.findConstructorOrFactory(name, charOffset, uri, libraryBuilder);
-      Member target = b?.member;
+      Member? target;
       if (b == null) {
         // Not found. Reported below.
       } else if (b is AmbiguousMemberBuilder) {
@@ -4715,16 +4749,19 @@
                   type.name,
                   nameToken.charOffset));
         }
+        target = b.member;
+      } else {
+        target = b.member;
       }
       if (target is Constructor ||
           (target is Procedure && target.kind == ProcedureKind.Factory)) {
         Expression invocation;
 
-        invocation = buildStaticInvocation(target, arguments,
+        invocation = buildStaticInvocation(target!, arguments,
             constness: constness,
             charOffset: nameToken.charOffset,
             charLength: nameToken.length,
-            typeAliasBuilder: typeAliasBuilder);
+            typeAliasBuilder: typeAliasBuilder as TypeAliasBuilder?);
 
         if (invocation is StaticInvocation &&
             isRedirectingFactory(target, helper: this)) {
@@ -4742,9 +4779,8 @@
           buildProblem(message.messageObject, nameToken.charOffset,
               nameToken.lexeme.length));
     } else {
-      errorName ??= debugName(type.fullNameForErrors, name);
+      errorName ??= debugName(type!.fullNameForErrors, name);
     }
-    errorName ??= name;
 
     return throwNoSuchMethodError(forest.createNullLiteral(charOffset),
         errorName, arguments, nameLastToken.charOffset,
@@ -4755,7 +4791,7 @@
   void endConstExpression(Token token) {
     debugEvent("endConstExpression");
     _buildConstructorReferenceInvocation(
-        token.next, token.offset, Constness.explicitConst,
+        token.next!, token.offset, Constness.explicitConst,
         inMetadata: false);
   }
 
@@ -4781,7 +4817,7 @@
     // This is matched by the call to [deferNode] in
     // [handleElseControlFlow] and by the call to [endNode] in
     // [endIfControlFlow].
-    typeInferrer?.assignedVariables?.beginNode();
+    typeInferrer.assignedVariables.beginNode();
     push(condition);
     super.handleThenControlFlow(token);
   }
@@ -4790,21 +4826,21 @@
   void handleElseControlFlow(Token elseToken) {
     // Resolve the top of the stack so that if it's a delayed assignment it
     // happens before we go into the else block.
-    Object node = pop();
+    Object? node = pop();
     if (node is! MapLiteralEntry) node = toValue(node);
     // This is matched by the call to [beginNode] in
     // [handleThenControlFlow] and by the call to [storeInfo] in
     // [endIfElseControlFlow].
-    push(typeInferrer?.assignedVariables?.deferNode());
+    push(typeInferrer.assignedVariables.deferNode());
     push(node);
   }
 
   @override
   void endIfControlFlow(Token token) {
     debugEvent("endIfControlFlow");
-    Object entry = pop();
-    Object condition = pop(); // parenthesized expression
-    Token ifToken = pop();
+    Object? entry = pop();
+    Object? condition = pop(); // parenthesized expression
+    Token ifToken = pop() as Token;
 
     transformCollections = true;
     TreeNode node;
@@ -4818,18 +4854,18 @@
     push(node);
     // This is matched by the call to [beginNode] in
     // [handleThenControlFlow].
-    typeInferrer?.assignedVariables?.endNode(node);
+    typeInferrer.assignedVariables.endNode(node);
   }
 
   @override
   void endIfElseControlFlow(Token token) {
     debugEvent("endIfElseControlFlow");
-    Object elseEntry = pop(); // else entry
-    Object thenEntry = pop(); // then entry
+    Object? elseEntry = pop(); // else entry
+    Object? thenEntry = pop(); // then entry
     AssignedVariablesNodeInfo<VariableDeclaration> assignedVariablesInfo =
-        pop();
-    Object condition = pop(); // parenthesized expression
-    Token ifToken = pop();
+        pop() as AssignedVariablesNodeInfo<VariableDeclaration>;
+    Object? condition = pop(); // parenthesized expression
+    Token ifToken = pop() as Token;
 
     transformCollections = true;
     TreeNode node;
@@ -4838,8 +4874,8 @@
         node = forest.createIfMapEntry(
             offsetForToken(ifToken), toValue(condition), thenEntry, elseEntry);
       } else if (elseEntry is ControlFlowElement) {
-        MapLiteralEntry elseMapEntry = elseEntry
-            .toMapLiteralEntry(typeInferrer?.assignedVariables?.reassignInfo);
+        MapLiteralEntry? elseMapEntry = elseEntry
+            .toMapLiteralEntry(typeInferrer.assignedVariables.reassignInfo);
         if (elseMapEntry != null) {
           node = forest.createIfMapEntry(offsetForToken(ifToken),
               toValue(condition), thenEntry, elseMapEntry);
@@ -4865,8 +4901,8 @@
       }
     } else if (elseEntry is MapLiteralEntry) {
       if (thenEntry is ControlFlowElement) {
-        MapLiteralEntry thenMapEntry = thenEntry
-            .toMapLiteralEntry(typeInferrer?.assignedVariables?.reassignInfo);
+        MapLiteralEntry? thenMapEntry = thenEntry
+            .toMapLiteralEntry(typeInferrer.assignedVariables.reassignInfo);
         if (thenMapEntry != null) {
           node = forest.createIfMapEntry(offsetForToken(ifToken),
               toValue(condition), thenMapEntry, elseEntry);
@@ -4897,13 +4933,13 @@
     push(node);
     // This is matched by the call to [deferNode] in
     // [handleElseControlFlow].
-    typeInferrer?.assignedVariables?.storeInfo(node, assignedVariablesInfo);
+    typeInferrer.assignedVariables.storeInfo(node, assignedVariablesInfo);
   }
 
   @override
   void handleSpreadExpression(Token spreadToken) {
     debugEvent("SpreadExpression");
-    Object expression = pop();
+    Object? expression = pop();
     transformCollections = true;
     push(forest.createSpreadElement(
         offsetForToken(spreadToken), toValue(expression),
@@ -4928,7 +4964,7 @@
     debugEvent("ThisExpression");
     if (context.isScopeReference && isDeclarationInstanceContext) {
       if (extensionThis != null) {
-        push(_createReadOnlyVariableAccess(extensionThis, token,
+        push(_createReadOnlyVariableAccess(extensionThis!, token,
             offsetForToken(token), 'this', ReadOnlyAccessKind.ExtensionThis));
       } else {
         push(new ThisAccessGenerator(this, token, inInitializer,
@@ -4946,7 +4982,7 @@
     if (context.isScopeReference &&
         isDeclarationInstanceContext &&
         extensionThis == null) {
-      MemberBuilder memberBuilder = member;
+      MemberBuilder memberBuilder = member as MemberBuilder;
       memberBuilder.member.transformerFlags |= TransformerFlag.superCalls;
       push(new ThisAccessGenerator(this, token, inInitializer,
           inFieldInitializer, inLateFieldInitializer,
@@ -4961,7 +4997,7 @@
   void handleNamedArgument(Token colon) {
     debugEvent("NamedArgument");
     Expression value = popForValue();
-    Identifier identifier = pop();
+    Identifier identifier = pop() as Identifier;
     push(new NamedExpression(identifier.name, value)
       ..fileOffset = identifier.charOffset);
   }
@@ -4969,7 +5005,7 @@
   @override
   void endFunctionName(Token beginToken, Token token) {
     debugEvent("FunctionName");
-    Identifier name = pop();
+    Identifier name = pop() as Identifier;
     Token nameToken = name.token;
     VariableDeclaration variable = new VariableDeclarationImpl(
         name.name, functionNestingLevel,
@@ -4979,7 +5015,7 @@
       ..fileOffset = name.charOffset;
     // TODO(ahe): Why are we looking up in local scope, but declaring in parent
     // scope?
-    Builder existing = scope.lookupLocalMember(name.name, setter: false);
+    Builder? existing = scope.lookupLocalMember(name.name, setter: false);
     if (existing != null) {
       reportDuplicatedDeclaration(existing, name.name, name.charOffset);
     }
@@ -4988,7 +5024,7 @@
         // The real function node is created later.
         dummyFunctionNode)
       ..fileOffset = beginToken.charOffset);
-    declareVariable(variable, scope.parent);
+    declareVariable(variable, scope.parent!);
   }
 
   void enterFunction() {
@@ -5001,15 +5037,16 @@
     inCatchBlock = false;
     // This is matched by the call to [endNode] in [pushNamedFunction] or
     // [endFunctionExpression].
-    typeInferrer?.assignedVariables?.beginNode();
+    typeInferrer.assignedVariables.beginNode();
   }
 
   void exitFunction() {
     debugEvent("exitFunction");
     functionNestingLevel--;
-    inCatchBlock = pop();
-    switchScope = pop();
-    List<TypeVariableBuilder> typeVariables = pop();
+    inCatchBlock = pop() as bool;
+    switchScope = pop() as Scope?;
+    List<TypeVariableBuilder>? typeVariables =
+        pop() as List<TypeVariableBuilder>?;
     exitLocalScope();
     push(typeVariables ?? NullValue.TypeVariables);
     _exitLocalState();
@@ -5024,7 +5061,8 @@
   @override
   void beginNamedFunctionExpression(Token token) {
     debugEvent("beginNamedFunctionExpression");
-    List<TypeVariableBuilder> typeVariables = pop();
+    List<TypeVariableBuilder>? typeVariables =
+        pop() as List<TypeVariableBuilder>?;
     // Create an additional scope in which the named function expression is
     // declared.
     enterLocalScope("named function");
@@ -5040,26 +5078,22 @@
 
   void pushNamedFunction(Token token, bool isFunctionExpression) {
     Statement body = popStatement();
-    AsyncMarker asyncModifier = pop();
+    AsyncMarker asyncModifier = pop() as AsyncMarker;
     exitLocalScope();
-    FormalParameters formals = pop();
-    Object declaration = pop();
-    UnresolvedType returnType = pop();
+    FormalParameters formals = pop() as FormalParameters;
+    Object? declaration = pop();
+    UnresolvedType? returnType = pop() as UnresolvedType?;
     bool hasImplicitReturnType = returnType == null;
     exitFunction();
-    List<TypeVariableBuilder> typeParameters = pop();
-    List<Expression> annotations;
+    List<TypeVariableBuilder>? typeParameters =
+        pop() as List<TypeVariableBuilder>?;
+    List<Expression>? annotations;
     if (!isFunctionExpression) {
-      annotations = pop(); // Metadata.
+      annotations = pop() as List<Expression>?; // Metadata.
     }
-    FunctionNode function = formals.buildFunctionNode(
-        libraryBuilder,
-        returnType,
-        typeParameters,
-        asyncModifier,
-        body,
-        token.charOffset,
-        !isDeclarationInstanceContext);
+    FunctionNode function = formals.buildFunctionNode(libraryBuilder,
+        returnType, typeParameters, asyncModifier, body, token.charOffset,
+        nonInstanceContext: !isDeclarationInstanceContext);
 
     if (declaration is FunctionDeclaration) {
       VariableDeclaration variable = declaration.variable;
@@ -5069,21 +5103,21 @@
         }
       }
       FunctionDeclarationImpl.setHasImplicitReturnType(
-          declaration, hasImplicitReturnType);
+          declaration as FunctionDeclarationImpl, hasImplicitReturnType);
       if (!hasImplicitReturnType) {
         checkAsyncReturnType(asyncModifier, function.returnType,
-            variable.fileOffset, variable.name.length);
+            variable.fileOffset, variable.name!.length);
       }
 
       variable.type = function.computeFunctionType(libraryBuilder.nonNullable);
       if (isFunctionExpression) {
-        Expression oldInitializer = variable.initializer;
+        Expression? oldInitializer = variable.initializer;
         variable.initializer = new FunctionExpression(function)
           ..parent = variable
           ..fileOffset = formals.charOffset;
         exitLocalScope();
         // This is matched by the call to [beginNode] in [enterFunction].
-        typeInferrer?.assignedVariables?.endNode(variable.initializer,
+        typeInferrer.assignedVariables.endNode(variable.initializer!,
             isClosureOrLateVariableInitializer: true);
         Expression expression = new NamedFunctionExpressionJudgment(variable);
         if (oldInitializer != null) {
@@ -5103,12 +5137,12 @@
         function.parent = declaration;
         if (variable.initializer != null) {
           // This must have been a compile-time error.
-          assert(isErroneousNode(variable.initializer));
+          assert(isErroneousNode(variable.initializer!));
 
           push(forest
               .createBlock(declaration.fileOffset, noLocation, <Statement>[
             forest.createExpressionStatement(
-                offsetForToken(token), variable.initializer),
+                offsetForToken(token), variable.initializer!),
             declaration
           ]));
           variable.initializer = null;
@@ -5116,11 +5150,11 @@
           push(declaration);
         }
         // This is matched by the call to [beginNode] in [enterFunction].
-        typeInferrer?.assignedVariables
-            ?.endNode(declaration, isClosureOrLateVariableInitializer: true);
+        typeInferrer.assignedVariables
+            .endNode(declaration, isClosureOrLateVariableInitializer: true);
       }
     } else {
-      return unhandled("${declaration.runtimeType}", "pushNamedFunction",
+      unhandled("${declaration.runtimeType}", "pushNamedFunction",
           token.charOffset, uri);
     }
   }
@@ -5141,19 +5175,15 @@
   void endFunctionExpression(Token beginToken, Token token) {
     debugEvent("FunctionExpression");
     Statement body = popStatement();
-    AsyncMarker asyncModifier = pop();
+    AsyncMarker asyncModifier = pop() as AsyncMarker;
     exitLocalScope();
-    FormalParameters formals = pop();
+    FormalParameters formals = pop() as FormalParameters;
     exitFunction();
-    List<TypeVariableBuilder> typeParameters = pop();
-    FunctionNode function = formals.buildFunctionNode(
-        libraryBuilder,
-        null,
-        typeParameters,
-        asyncModifier,
-        body,
-        token.charOffset,
-        !isDeclarationInstanceContext)
+    List<TypeVariableBuilder>? typeParameters =
+        pop() as List<TypeVariableBuilder>?;
+    FunctionNode function = formals.buildFunctionNode(libraryBuilder, null,
+        typeParameters, asyncModifier, body, token.charOffset,
+        nonInstanceContext: !isDeclarationInstanceContext)
       ..fileOffset = beginToken.charOffset;
 
     Expression result;
@@ -5166,14 +5196,14 @@
     }
     push(result);
     // This is matched by the call to [beginNode] in [enterFunction].
-    typeInferrer?.assignedVariables
-        ?.endNode(result, isClosureOrLateVariableInitializer: true);
+    typeInferrer.assignedVariables
+        .endNode(result, isClosureOrLateVariableInitializer: true);
   }
 
   @override
   void beginDoWhileStatement(Token token) {
     // This is matched by the [endNode] call in [endDoWhileStatement].
-    typeInferrer?.assignedVariables?.beginNode();
+    typeInferrer.assignedVariables.beginNode();
     super.beginDoWhileStatement(token);
   }
 
@@ -5183,17 +5213,19 @@
     debugEvent("DoWhileStatement");
     Expression condition = popForValue();
     Statement body = popStatement();
-    JumpTarget continueTarget = exitContinueTarget();
-    JumpTarget breakTarget = exitBreakTarget();
-    List<BreakStatementImpl> continueStatements;
+    JumpTarget continueTarget = exitContinueTarget()!;
+    JumpTarget breakTarget = exitBreakTarget()!;
+    List<BreakStatementImpl>? continueStatements;
     if (continueTarget.hasUsers) {
-      body = forest.createLabeledStatement(body);
-      continueStatements = continueTarget.resolveContinues(forest, body);
+      LabeledStatement labeledStatement = forest.createLabeledStatement(body);
+      continueStatements =
+          continueTarget.resolveContinues(forest, labeledStatement);
+      body = labeledStatement;
     }
     Statement doStatement =
         forest.createDoStatement(offsetForToken(doKeyword), body, condition);
     // This is matched by the [beginNode] call in [beginDoWhileStatement].
-    typeInferrer?.assignedVariables?.endNode(doStatement);
+    typeInferrer.assignedVariables.endNode(doStatement);
     if (continueStatements != null) {
       for (BreakStatementImpl continueStatement in continueStatements) {
         continueStatement.targetStatement = doStatement;
@@ -5201,15 +5233,16 @@
     }
     Statement result = doStatement;
     if (breakTarget.hasUsers) {
-      result = forest.createLabeledStatement(result);
-      breakTarget.resolveBreaks(forest, result, doStatement);
+      LabeledStatement labeledStatement = forest.createLabeledStatement(result);
+      breakTarget.resolveBreaks(forest, labeledStatement, doStatement);
+      result = labeledStatement;
     }
     exitLoopOrSwitch(result);
   }
 
   @override
   void beginForInExpression(Token token) {
-    enterLocalScope(null, scope.parent);
+    enterLocalScope('forIn', scope.parent);
   }
 
   @override
@@ -5217,33 +5250,33 @@
     debugEvent("ForInExpression");
     Expression expression = popForValue();
     exitLocalScope();
-    push(expression ?? NullValue.Expression);
+    push(expression);
   }
 
   @override
-  void handleForInLoopParts(Token awaitToken, Token forToken,
+  void handleForInLoopParts(Token? awaitToken, Token forToken,
       Token leftParenthesis, Token inKeyword) {
     push(awaitToken ?? NullValue.AwaitToken);
     push(forToken);
     push(inKeyword);
     // This is matched by the call to [deferNode] in [endForIn] or
     // [endForInControlFlow].
-    typeInferrer?.assignedVariables?.beginNode();
+    typeInferrer.assignedVariables.beginNode();
   }
 
   @override
   void endForInControlFlow(Token token) {
     debugEvent("ForInControlFlow");
-    Object entry = pop();
-    Token inToken = pop();
-    Token forToken = pop();
-    Token awaitToken = pop(NullValue.AwaitToken);
+    Object? entry = pop();
+    Token inToken = pop() as Token;
+    Token forToken = pop() as Token;
+    Token? awaitToken = pop(NullValue.AwaitToken) as Token?;
 
     if (constantContext != ConstantContext.none) {
       popForValue(); // Pop iterable
       pop(); // Pop lvalue
       exitLocalScope();
-      typeInferrer?.assignedVariables?.discardNode();
+      typeInferrer.assignedVariables.discardNode();
 
       handleRecoverableError(
           fasta.templateCantUseControlFlowOrSpreadAsConstant
@@ -5256,18 +5289,18 @@
 
     // This is matched by the call to [beginNode] in [handleForInLoopParts].
     AssignedVariablesNodeInfo<VariableDeclaration> assignedVariablesNodeInfo =
-        typeInferrer?.assignedVariables?.popNode();
+        typeInferrer.assignedVariables.popNode();
 
     Expression iterable = popForValue();
-    Object lvalue = pop(); // lvalue
+    Object? lvalue = pop(); // lvalue
     exitLocalScope();
 
     transformCollections = true;
     ForInElements elements =
         _computeForInElements(forToken, inToken, lvalue, null);
-    typeInferrer?.assignedVariables?.pushNode(assignedVariablesNodeInfo);
+    typeInferrer.assignedVariables.pushNode(assignedVariablesNodeInfo);
     VariableDeclaration variable = elements.variable;
-    Expression problem = elements.expressionProblem;
+    Expression? problem = elements.expressionProblem;
     if (entry is MapLiteralEntry) {
       ForInMapEntry result = forest.createForInMapEntry(
           offsetForToken(forToken),
@@ -5278,7 +5311,7 @@
           entry,
           problem,
           isAsync: awaitToken != null);
-      typeInferrer?.assignedVariables?.endNode(result);
+      typeInferrer.assignedVariables.endNode(result);
       push(result);
     } else {
       ForInElement result = forest.createForInElement(
@@ -5290,13 +5323,13 @@
           toValue(entry),
           problem,
           isAsync: awaitToken != null);
-      typeInferrer?.assignedVariables?.endNode(result);
+      typeInferrer.assignedVariables.endNode(result);
       push(result);
     }
   }
 
   ForInElements _computeForInElements(
-      Token forToken, Token inToken, Object lvalue, Statement body) {
+      Token forToken, Token inToken, Object? lvalue, Statement? body) {
     ForInElements elements = new ForInElements();
     if (lvalue is VariableDeclaration) {
       // Late for-in variables are not supported. An error has already been
@@ -5307,7 +5340,7 @@
         elements.expressionProblem = buildProblem(
             fasta.messageForInLoopWithConstVariable,
             lvalue.fileOffset,
-            lvalue.name.length);
+            lvalue.name!.length);
       }
     } else {
       VariableDeclaration variable = elements.syntheticVariableDeclaration =
@@ -5333,7 +5366,7 @@
         Message message = forest.isVariablesDeclaration(lvalue)
             ? fasta.messageForInLoopExactlyOneVariable
             : fasta.messageForInLoopNotAssignable;
-        Token token = forToken.next.next;
+        Token token = forToken.next!.next!;
         elements.expressionProblem =
             buildProblem(message, offsetForToken(token), lengthForToken(token));
         Statement effects;
@@ -5345,7 +5378,8 @@
               new List<Statement>.from(
                   forest.variablesDeclarationExtractDeclarations(lvalue)));
         } else {
-          effects = forest.createExpressionStatement(noLocation, lvalue);
+          effects = forest.createExpressionStatement(
+              noLocation, lvalue as Expression);
         }
         elements.expressionEffects = combineStatements(
             forest.createExpressionStatement(
@@ -5363,28 +5397,30 @@
     debugEvent("ForIn");
     Statement body = popStatement();
 
-    Token inKeyword = pop();
-    Token forToken = pop();
-    Token awaitToken = pop(NullValue.AwaitToken);
+    Token inKeyword = pop() as Token;
+    Token forToken = pop() as Token;
+    Token? awaitToken = pop(NullValue.AwaitToken) as Token?;
 
     // This is matched by the call to [beginNode] in [handleForInLoopParts].
     AssignedVariablesNodeInfo<VariableDeclaration> assignedVariablesNodeInfo =
-        typeInferrer?.assignedVariables?.deferNode();
+        typeInferrer.assignedVariables.deferNode();
 
     Expression expression = popForValue();
-    Object lvalue = pop();
+    Object? lvalue = pop();
     exitLocalScope();
-    JumpTarget continueTarget = exitContinueTarget();
-    JumpTarget breakTarget = exitBreakTarget();
-    List<BreakStatementImpl> continueStatements;
+    JumpTarget continueTarget = exitContinueTarget()!;
+    JumpTarget breakTarget = exitBreakTarget()!;
+    List<BreakStatementImpl>? continueStatements;
     if (continueTarget.hasUsers) {
-      body = forest.createLabeledStatement(body);
-      continueStatements = continueTarget.resolveContinues(forest, body);
+      LabeledStatement labeledStatement = forest.createLabeledStatement(body);
+      continueStatements =
+          continueTarget.resolveContinues(forest, labeledStatement);
+      body = labeledStatement;
     }
     ForInElements elements =
         _computeForInElements(forToken, inKeyword, lvalue, body);
     VariableDeclaration variable = elements.variable;
-    Expression problem = elements.expressionProblem;
+    Expression? problem = elements.expressionProblem;
     Statement forInStatement;
     if (elements.explicitVariableDeclaration != null) {
       forInStatement = new ForInStatement(variable, expression, body,
@@ -5403,8 +5439,8 @@
         ..fileOffset = awaitToken?.charOffset ?? forToken.charOffset
         ..bodyOffset = body.fileOffset; // TODO(ahe): Isn't this redundant?
     }
-    typeInferrer?.assignedVariables
-        ?.storeInfo(forInStatement, assignedVariablesNodeInfo);
+    typeInferrer.assignedVariables
+        .storeInfo(forInStatement, assignedVariablesNodeInfo);
     if (continueStatements != null) {
       for (BreakStatementImpl continueStatement in continueStatements) {
         continueStatement.targetStatement = forInStatement;
@@ -5412,8 +5448,9 @@
     }
     Statement result = forInStatement;
     if (breakTarget.hasUsers) {
-      result = forest.createLabeledStatement(result);
-      breakTarget.resolveBreaks(forest, result, forInStatement);
+      LabeledStatement labeledStatement = forest.createLabeledStatement(result);
+      breakTarget.resolveBreaks(forest, labeledStatement, forInStatement);
+      result = labeledStatement;
     }
     if (problem != null) {
       result = combineStatements(
@@ -5425,18 +5462,18 @@
   @override
   void handleLabel(Token token) {
     debugEvent("Label");
-    Identifier identifier = pop();
+    Identifier identifier = pop() as Identifier;
     push(new Label(identifier.name, identifier.charOffset));
   }
 
   @override
   void beginLabeledStatement(Token token, int labelCount) {
     debugEvent("beginLabeledStatement");
-    List<Label> labels =
-        const FixedNullableList<Label>().pop(stack, labelCount);
-    enterLocalScope(null, scope.createNestedLabelScope());
-    LabelTarget target =
-        new LabelTarget(member, functionNestingLevel, token.charOffset);
+    List<Label>? labels = const FixedNullableList<Label>()
+        .popNonNullable(stack, labelCount, dummyLabel);
+    enterLocalScope('labeledStatement', scope.createNestedLabelScope());
+    LabelTarget target = new LabelTarget(
+        member as MemberBuilder, functionNestingLevel, token.charOffset);
     if (labels != null) {
       for (Label label in labels) {
         scope.declareLabel(label.name, target);
@@ -5448,8 +5485,8 @@
   @override
   void endLabeledStatement(int labelCount) {
     debugEvent("LabeledStatement");
-    Statement statement = pop();
-    LabelTarget target = pop();
+    Statement statement = pop() as Statement;
+    LabelTarget target = pop() as LabelTarget;
     exitLocalScope();
     if (target.breakTarget.hasUsers || target.continueTarget.hasUsers) {
       if (forest.isVariablesDeclaration(statement)) {
@@ -5462,7 +5499,7 @@
         statement = forest.createLabeledStatement(statement);
       }
       target.breakTarget.resolveBreaks(forest, statement, statement);
-      List<BreakStatementImpl> continueStatements =
+      List<BreakStatementImpl>? continueStatements =
           target.continueTarget.resolveContinues(forest, statement);
       if (continueStatements != null) {
         for (BreakStatementImpl continueStatement in continueStatements) {
@@ -5495,7 +5532,7 @@
   @override
   void beginWhileStatement(Token token) {
     // This is matched by the [endNode] call in [endWhileStatement].
-    typeInferrer?.assignedVariables?.beginNode();
+    typeInferrer.assignedVariables.beginNode();
     super.beginWhileStatement(token);
   }
 
@@ -5504,12 +5541,14 @@
     debugEvent("WhileStatement");
     Statement body = popStatement();
     Expression condition = popForValue();
-    JumpTarget continueTarget = exitContinueTarget();
-    JumpTarget breakTarget = exitBreakTarget();
-    List<BreakStatementImpl> continueStatements;
+    JumpTarget continueTarget = exitContinueTarget()!;
+    JumpTarget breakTarget = exitBreakTarget()!;
+    List<BreakStatementImpl>? continueStatements;
     if (continueTarget.hasUsers) {
-      body = forest.createLabeledStatement(body);
-      continueStatements = continueTarget.resolveContinues(forest, body);
+      LabeledStatement labeledStatement = forest.createLabeledStatement(body);
+      continueStatements =
+          continueTarget.resolveContinues(forest, labeledStatement);
+      body = labeledStatement;
     }
     Statement whileStatement = forest.createWhileStatement(
         offsetForToken(whileKeyword), condition, body);
@@ -5520,12 +5559,13 @@
     }
     Statement result = whileStatement;
     if (breakTarget.hasUsers) {
-      result = forest.createLabeledStatement(result);
-      breakTarget.resolveBreaks(forest, result, whileStatement);
+      LabeledStatement labeledStatement = forest.createLabeledStatement(result);
+      breakTarget.resolveBreaks(forest, labeledStatement, whileStatement);
+      result = labeledStatement;
     }
     exitLoopOrSwitch(result);
     // This is matched by the [beginNode] call in [beginWhileStatement].
-    typeInferrer?.assignedVariables?.endNode(whileStatement);
+    typeInferrer.assignedVariables.endNode(whileStatement);
   }
 
   @override
@@ -5545,14 +5585,14 @@
 
   @override
   void endAssert(Token assertKeyword, Assert kind, Token leftParenthesis,
-      Token commaToken, Token semicolonToken) {
+      Token? commaToken, Token semicolonToken) {
     debugEvent("Assert");
-    Expression message = popForValueIfNotNull(commaToken);
+    Expression? message = popForValueIfNotNull(commaToken);
     Expression condition = popForValue();
     int fileOffset = offsetForToken(assertKeyword);
 
     /// Return a representation of an assert that appears as a statement.
-    Statement createAssertStatement() {
+    AssertStatement createAssertStatement() {
       // Compute start and end offsets for the condition expression.
       // This code is a temporary workaround because expressions don't carry
       // their start and end offsets currently.
@@ -5560,16 +5600,16 @@
       // The token that follows leftParenthesis is considered to be the
       // first token of the condition.
       // TODO(ahe): this really should be condition.fileOffset.
-      int startOffset = leftParenthesis.next.offset;
+      int startOffset = leftParenthesis.next!.offset;
       int endOffset;
 
       // Search forward from leftParenthesis to find the last token of
       // the condition - which is a token immediately followed by a commaToken,
       // right parenthesis or a trailing comma.
-      Token conditionBoundary = commaToken ?? leftParenthesis.endGroup;
+      Token? conditionBoundary = commaToken ?? leftParenthesis.endGroup;
       Token conditionLastToken = leftParenthesis;
       while (!conditionLastToken.isEof) {
-        Token nextToken = conditionLastToken.next;
+        Token nextToken = conditionLastToken.next!;
         if (nextToken == conditionBoundary) {
           break;
         } else if (optional(',', nextToken) &&
@@ -5610,7 +5650,7 @@
   }
 
   @override
-  void endYieldStatement(Token yieldToken, Token starToken, Token endToken) {
+  void endYieldStatement(Token yieldToken, Token? starToken, Token endToken) {
     debugEvent("YieldStatement");
     push(forest.createYieldStatement(offsetForToken(yieldToken), popForValue(),
         isYieldStar: starToken != null));
@@ -5620,7 +5660,7 @@
   void beginSwitchBlock(Token token) {
     debugEvent("beginSwitchBlock");
     // This is matched by the [endNode] call in [endSwitchStatement].
-    typeInferrer?.assignedVariables?.beginNode();
+    typeInferrer.assignedVariables.beginNode();
     enterLocalScope("switch block");
     enterSwitchScope();
     enterBreakTarget(token.charOffset);
@@ -5630,20 +5670,21 @@
   void beginSwitchCase(int labelCount, int expressionCount, Token firstToken) {
     debugEvent("beginSwitchCase");
     int count = labelCount + expressionCount;
-    List<Object> labelsAndExpressions =
-        const FixedNullableList<Object>().pop(stack, count);
-    List<Label> labels =
-        labelCount == 0 ? null : new List<Label>.filled(labelCount, null);
-    List<Expression> expressions =
-        new List<Expression>.filled(expressionCount, null, growable: true);
+    List<Object>? labelsAndExpressions = const FixedNullableList<Object>()
+        .popNonNullable(stack, count, dummyLabel);
+    List<Label>? labels =
+        labelCount == 0 ? null : new List<Label>.filled(labelCount, dummyLabel);
+    List<Expression> expressions = new List<Expression>.filled(
+        expressionCount, dummyExpression,
+        growable: true);
     int labelIndex = 0;
     int expressionIndex = 0;
     if (labelsAndExpressions != null) {
       for (Object labelOrExpression in labelsAndExpressions) {
         if (labelOrExpression is Label) {
-          labels[labelIndex++] = labelOrExpression;
+          labels![labelIndex++] = labelOrExpression;
         } else {
-          expressions[expressionIndex++] = labelOrExpression;
+          expressions[expressionIndex++] = labelOrExpression as Expression;
         }
       }
     }
@@ -5675,8 +5716,8 @@
   void endSwitchCase(
       int labelCount,
       int expressionCount,
-      Token defaultKeyword,
-      Token colonAfterDefault,
+      Token? defaultKeyword,
+      Token? colonAfterDefault,
       int statementCount,
       Token firstToken,
       Token endToken) {
@@ -5686,8 +5727,8 @@
     // check this switch case to see if it falls through to the next case.
     Statement block = popBlock(statementCount, firstToken, null);
     exitLocalScope();
-    List<Label> labels = pop();
-    List<Expression> expressions = pop();
+    List<Label>? labels = pop() as List<Label>?;
+    List<Expression> expressions = pop() as List<Expression>;
     List<int> expressionOffsets = <int>[];
     for (Expression expression in expressions) {
       expressionOffsets.add(expression.fileOffset);
@@ -5703,8 +5744,8 @@
   void endSwitchStatement(Token switchKeyword, Token endToken) {
     debugEvent("SwitchStatement");
 
-    List<SwitchCase> cases = pop();
-    JumpTarget target = exitBreakTarget();
+    List<SwitchCase> cases = pop() as List<SwitchCase>;
+    JumpTarget target = exitBreakTarget()!;
     exitSwitchScope();
     exitLocalScope();
     Expression expression = popForValue();
@@ -5712,25 +5753,27 @@
       ..fileOffset = switchKeyword.charOffset;
     Statement result = switchStatement;
     if (target.hasUsers) {
-      result = forest.createLabeledStatement(result);
-      target.resolveBreaks(forest, result, switchStatement);
+      LabeledStatement labeledStatement = forest.createLabeledStatement(result);
+      target.resolveBreaks(forest, labeledStatement, switchStatement);
+      result = labeledStatement;
     }
     exitLoopOrSwitch(result);
     // This is matched by the [beginNode] call in [beginSwitchBlock].
-    typeInferrer?.assignedVariables?.endNode(switchStatement);
+    typeInferrer.assignedVariables.endNode(switchStatement);
   }
 
   @override
   void endSwitchBlock(int caseCount, Token beginToken, Token endToken) {
     debugEvent("SwitchBlock");
     List<SwitchCase> cases =
-        new List<SwitchCase>.filled(caseCount, null, growable: true);
+        new List<SwitchCase>.filled(caseCount, dummySwitchCase, growable: true);
     for (int i = caseCount - 1; i >= 0; i--) {
-      List<Label> labels = pop();
-      SwitchCase current = cases[i] = pop();
+      List<Label>? labels = pop() as List<Label>?;
+      SwitchCase current = cases[i] = pop() as SwitchCase;
       if (labels != null) {
         for (Label label in labels) {
-          JumpTarget target = switchScope.lookupLabel(label.name);
+          JumpTarget? target =
+              switchScope!.lookupLabel(label.name) as JumpTarget?;
           if (target != null) {
             target.resolveGotos(forest, current);
           }
@@ -5739,12 +5782,12 @@
     }
     for (int i = 0; i < caseCount - 1; i++) {
       SwitchCase current = cases[i];
-      Block block = current.body;
+      Block block = current.body as Block;
       // [block] is a synthetic block that is added to handle variable
       // declarations in the switch case.
-      TreeNode lastNode =
+      TreeNode? lastNode =
           block.statements.isEmpty ? null : block.statements.last;
-      if (forest.isBlock(lastNode)) {
+      if (lastNode is Block) {
         // This is a non-synthetic block.
         Block block = lastNode;
         lastNode = block.statements.isEmpty ? null : block.statements.last;
@@ -5783,13 +5826,13 @@
   void handleBreakStatement(
       bool hasTarget, Token breakKeyword, Token endToken) {
     debugEvent("BreakStatement");
-    JumpTarget target = breakTarget;
-    Identifier identifier;
-    String name;
+    JumpTarget? target = breakTarget;
+    Identifier? identifier;
+    String? name;
     if (hasTarget) {
-      identifier = pop();
+      identifier = pop() as Identifier;
       name = identifier.name;
-      target = scope.lookupLabel(name);
+      target = scope.lookupLabel(name) as JumpTarget?;
     }
     if (target == null && name == null) {
       push(problemInLoopOrSwitch = buildProblemStatement(
@@ -5797,9 +5840,9 @@
     } else if (target == null ||
         target is! JumpTarget ||
         !target.isBreakTarget) {
-      Token labelToken = breakKeyword.next;
+      Token labelToken = breakKeyword.next!;
       push(problemInLoopOrSwitch = buildProblemStatement(
-          fasta.templateInvalidBreakTarget.withArguments(name),
+          fasta.templateInvalidBreakTarget.withArguments(name!),
           labelToken.charOffset,
           length: labelToken.length));
     } else if (target.functionNestingLevel != functionNestingLevel) {
@@ -5812,7 +5855,8 @@
     }
   }
 
-  Statement buildProblemTargetOutsideLocalFunction(String name, Token keyword) {
+  Statement buildProblemTargetOutsideLocalFunction(
+      String? name, Token keyword) {
     Statement problem;
     bool isBreak = optional("break", keyword);
     if (name != null) {
@@ -5837,35 +5881,36 @@
   void handleContinueStatement(
       bool hasTarget, Token continueKeyword, Token endToken) {
     debugEvent("ContinueStatement");
-    JumpTarget target = continueTarget;
-    Identifier identifier;
-    String name;
+    JumpTarget? target = continueTarget;
+    Identifier? identifier;
+    String? name;
     if (hasTarget) {
-      identifier = pop();
+      identifier = pop() as Identifier;
       name = identifier.name;
-      Builder namedTarget = scope.lookupLabel(identifier.name);
+      Builder? namedTarget = scope.lookupLabel(identifier.name);
       if (namedTarget != null && namedTarget is! JumpTarget) {
-        Token labelToken = continueKeyword.next;
+        Token labelToken = continueKeyword.next!;
         push(problemInLoopOrSwitch = buildProblemStatement(
             fasta.messageContinueLabelNotTarget, labelToken.charOffset,
             length: labelToken.length));
         return;
       }
-      target = namedTarget;
+      target = namedTarget as JumpTarget?;
       if (target == null) {
         if (switchScope == null) {
           push(buildProblemStatement(
               fasta.templateLabelNotFound.withArguments(name),
-              continueKeyword.next.charOffset));
+              continueKeyword.next!.charOffset));
           return;
         }
-        switchScope.forwardDeclareLabel(
+        switchScope!.forwardDeclareLabel(
             identifier.name, target = createGotoTarget(identifier.charOffset));
       }
       if (target.isGotoTarget &&
           target.functionNestingLevel == functionNestingLevel) {
-        ContinueSwitchStatement statement = new ContinueSwitchStatement(null)
-          ..fileOffset = continueKeyword.charOffset;
+        ContinueSwitchStatement statement =
+            new ContinueSwitchStatement(dummySwitchCase)
+              ..fileOffset = continueKeyword.charOffset;
         target.addGoto(statement);
         push(statement);
         return;
@@ -5876,9 +5921,9 @@
           fasta.messageContinueWithoutLabelInCase, continueKeyword.charOffset,
           length: continueKeyword.length));
     } else if (!target.isContinueTarget) {
-      Token labelToken = continueKeyword.next;
+      Token labelToken = continueKeyword.next!;
       push(problemInLoopOrSwitch = buildProblemStatement(
-          fasta.templateInvalidContinueTarget.withArguments(name),
+          fasta.templateInvalidContinueTarget.withArguments(name!),
           labelToken.charOffset,
           length: labelToken.length));
     } else if (target.functionNestingLevel != functionNestingLevel) {
@@ -5898,18 +5943,18 @@
       unionOfKinds([ValueKinds.Identifier, ValueKinds.ParserRecovery]),
       ValueKinds.AnnotationListOrNull,
     ]));
-    Object name = pop();
-    List<Expression> annotations = pop();
-    String typeVariableName;
+    Object? name = pop();
+    List<Expression>? annotations = pop() as List<Expression>?;
+    String? typeVariableName;
     int typeVariableCharOffset;
     if (name is Identifier) {
       typeVariableName = name.name;
       typeVariableCharOffset = name.charOffset;
     } else if (name is ParserRecovery) {
-      typeVariableName = null;
+      typeVariableName = TypeVariableBuilder.noNameSentinel;
       typeVariableCharOffset = name.charOffset;
     } else {
-      return unhandled("${name.runtimeType}", "beginTypeVariable.name",
+      unhandled("${name.runtimeType}", "beginTypeVariable.name",
           token.charOffset, uri);
     }
     TypeVariableBuilder variable = new TypeVariableBuilder(
@@ -5927,19 +5972,21 @@
   void handleTypeVariablesDefined(Token token, int count) {
     debugEvent("handleTypeVariablesDefined");
     assert(count > 0);
-    List<TypeVariableBuilder> typeVariables =
-        const FixedNullableList<TypeVariableBuilder>().pop(stack, count);
+    List<TypeVariableBuilder>? typeVariables =
+        const FixedNullableList<TypeVariableBuilder>()
+            .popNonNullable(stack, count, dummyTypeVariableBuilder);
     enterFunctionTypeScope(typeVariables);
     push(typeVariables);
   }
 
   @override
   void endTypeVariable(
-      Token token, int index, Token extendsOrSuper, Token variance) {
+      Token token, int index, Token? extendsOrSuper, Token? variance) {
     debugEvent("TypeVariable");
-    UnresolvedType bound = pop();
+    UnresolvedType? bound = pop() as UnresolvedType?;
     // Peek to leave type parameters on top of stack.
-    List<TypeVariableBuilder> typeVariables = peek();
+    List<TypeVariableBuilder> typeVariables =
+        peek() as List<TypeVariableBuilder>;
 
     TypeVariableBuilder variable = typeVariables[index];
     variable.bound = bound?.builder;
@@ -5955,7 +6002,8 @@
   void endTypeVariables(Token beginToken, Token endToken) {
     debugEvent("TypeVariables");
     // Peek to leave type parameters on top of stack.
-    List<TypeVariableBuilder> typeVariables = peek();
+    List<TypeVariableBuilder> typeVariables =
+        peek() as List<TypeVariableBuilder>;
 
     List<TypeBuilder> unboundTypes = [];
     List<TypeVariableBuilder> unboundTypeVariables = [];
@@ -5970,8 +6018,11 @@
         "Found a type not bound to a declaration in BodyBuilder.");
     for (int i = 0; i < typeVariables.length; ++i) {
       typeVariables[i].defaultType = calculatedBounds[i];
-      typeVariables[i].defaultType.resolveIn(scope, typeVariables[i].charOffset,
-          typeVariables[i].fileUri, libraryBuilder);
+      typeVariables[i].defaultType!.resolveIn(
+          scope,
+          typeVariables[i].charOffset,
+          typeVariables[i].fileUri!,
+          libraryBuilder);
       typeVariables[i].finish(
           libraryBuilder,
           libraryBuilder.loader.target.objectClassBuilder,
@@ -5993,29 +6044,24 @@
     push(NullValue.TypeVariables);
   }
 
-  List<TypeParameter> typeVariableBuildersToKernel(
-      List<TypeVariableBuilder> typeVariableBuilders) {
+  List<TypeParameter>? typeVariableBuildersToKernel(
+      List<TypeVariableBuilder>? typeVariableBuilders) {
     if (typeVariableBuilders == null) return null;
-    List<TypeParameter> typeParameters = new List<TypeParameter>.filled(
-        typeVariableBuilders.length, null,
+    return new List<TypeParameter>.generate(typeVariableBuilders.length,
+        (int i) => typeVariableBuilders[i].parameter,
         growable: true);
-    int i = 0;
-    for (TypeVariableBuilder builder in typeVariableBuilders) {
-      typeParameters[i++] = builder.parameter;
-    }
-    return typeParameters;
   }
 
   @override
   void handleInvalidStatement(Token token, Message message) {
-    Statement statement = pop();
+    Statement statement = pop() as Statement;
     push(new ExpressionStatement(
         buildProblem(message, statement.fileOffset, noLength)));
   }
 
   @override
   Expression buildProblem(Message message, int charOffset, int length,
-      {List<LocatedMessage> context, bool suppressMessage: false}) {
+      {List<LocatedMessage>? context, bool suppressMessage: false}) {
     if (!suppressMessage) {
       addProblem(message, charOffset, length,
           wasHandled: true, context: context);
@@ -6031,7 +6077,7 @@
   @override
   Expression wrapInProblem(
       Expression expression, Message message, int fileOffset, int length,
-      {List<LocatedMessage> context}) {
+      {List<LocatedMessage>? context}) {
     Severity severity = message.code.severity;
     if (severity == Severity.error) {
       return wrapInLocatedProblem(
@@ -6045,7 +6091,7 @@
 
   @override
   Expression wrapInLocatedProblem(Expression expression, LocatedMessage message,
-      {List<LocatedMessage> context}) {
+      {List<LocatedMessage>? context}) {
     // TODO(askesc): Produce explicit error expression wrapping the original.
     // See [issue 29717](https://github.com/dart-lang/sdk/issues/29717)
     int offset = expression.fileOffset;
@@ -6070,7 +6116,7 @@
     // be moved to [Forest] or conditional on `forest is Fangorn`.
 
     // TODO(ahe): Compute a LocatedMessage above instead?
-    Location location = messages.getLocationFromUri(uri, charOffset);
+    Location? location = messages.getLocationFromUri(uri, charOffset);
 
     return forest.createThrow(
         charOffset,
@@ -6103,7 +6149,9 @@
   }
 
   Statement buildProblemStatement(Message message, int charOffset,
-      {List<LocatedMessage> context, int length, bool suppressMessage: false}) {
+      {List<LocatedMessage>? context,
+      int? length,
+      bool suppressMessage: false}) {
     length ??= noLength;
     return new ExpressionStatement(buildProblem(message, charOffset, length,
         context: context, suppressMessage: suppressMessage));
@@ -6149,8 +6197,8 @@
   @override
   List<Initializer> buildFieldInitializer(String name, int fieldNameOffset,
       int assignmentOffset, Expression expression,
-      {FormalParameterBuilder formal}) {
-    Builder builder = declarationBuilder.lookupLocalMember(name);
+      {FormalParameterBuilder? formal}) {
+    Builder? builder = declarationBuilder!.lookupLocalMember(name);
     if (builder?.next != null) {
       // Duplicated name, already reported.
       return <Initializer>[
@@ -6163,13 +6211,13 @@
       ];
     } else if (builder is FieldBuilder && builder.isDeclarationInstanceMember) {
       initializedFields ??= <String, int>{};
-      if (initializedFields.containsKey(name)) {
+      if (initializedFields!.containsKey(name)) {
         return <Initializer>[
           buildDuplicatedInitializer(builder.field, expression, name,
-              assignmentOffset, initializedFields[name])
+              assignmentOffset, initializedFields![name]!)
         ];
       }
-      initializedFields[name] = assignmentOffset;
+      initializedFields![name] = assignmentOffset;
       if (builder.isAbstract) {
         return <Initializer>[
           buildInvalidInitializer(
@@ -6214,7 +6262,7 @@
         ];
       } else {
         if (formal != null && formal.type != null) {
-          DartType formalType = formal.variable.type;
+          DartType formalType = formal.variable!.type;
           if (!typeEnvironment.isSubtypeOf(formalType, builder.fieldType,
               SubtypeCheckMode.withNullabilities)) {
             libraryBuilder.addProblem(
@@ -6228,11 +6276,11 @@
                 uri,
                 context: [
                   fasta.messageInitializingFormalTypeMismatchField.withLocation(
-                      builder.fileUri, builder.charOffset, noLength)
+                      builder.fileUri!, builder.charOffset, noLength)
                 ]);
           }
         }
-        ConstructorBuilder constructorBuilder = member;
+        ConstructorBuilder constructorBuilder = member as ConstructorBuilder;
         constructorBuilder.registerInitializedField(builder);
         return builder.buildInitializer(assignmentOffset, expression,
             isSynthetic: formal != null);
@@ -6267,8 +6315,8 @@
   Initializer buildRedirectingInitializer(
       Constructor constructor, Arguments arguments,
       [int charOffset = -1]) {
-    if (classBuilder.checkConstructorCyclic(
-        member.name, constructor.name.text)) {
+    if (classBuilder!
+        .checkConstructorCyclic(member.name!, constructor.name.text)) {
       int length = constructor.name.text.length;
       if (length == 0) length = "this".length;
       addProblem(fasta.messageConstructorCyclic, charOffset, length);
@@ -6311,9 +6359,10 @@
       ValueKinds.TypeArguments,
       unionOfKinds([ValueKinds.Generator, ValueKinds.Expression])
     ]));
-    List<UnresolvedType> typeArguments = pop(); // typeArguments
+    List<UnresolvedType>? typeArguments =
+        pop() as List<UnresolvedType>?; // typeArguments
     if (libraryBuilder.enableConstructorTearOffsInLibrary) {
-      Object operand = pop();
+      Object? operand = pop();
       if (operand is Generator) {
         push(operand.applyTypeArguments(
             openAngleBracket.charOffset, typeArguments));
@@ -6335,76 +6384,86 @@
 
   @override
   UnresolvedType validateTypeUse(UnresolvedType unresolved,
-      {bool nonInstanceAccessIsError, bool allowPotentiallyConstantType}) {
+      {required bool nonInstanceAccessIsError,
+      required bool allowPotentiallyConstantType}) {
+    // ignore: unnecessary_null_comparison
     assert(nonInstanceAccessIsError != null);
+    // ignore: unnecessary_null_comparison
     assert(allowPotentiallyConstantType != null);
     TypeBuilder builder = unresolved.builder;
-    if (builder is NamedTypeBuilder && builder.declaration.isTypeVariable) {
-      TypeVariableBuilder typeParameterBuilder = builder.declaration;
+    if (builder is NamedTypeBuilder && builder.declaration!.isTypeVariable) {
+      TypeVariableBuilder typeParameterBuilder =
+          builder.declaration as TypeVariableBuilder;
       TypeParameter typeParameter = typeParameterBuilder.parameter;
-      LocatedMessage message = _validateTypeUseIsInternal(
+      LocatedMessage? message = _validateTypeUseIsInternal(
           builder, unresolved.fileUri, unresolved.charOffset,
           allowPotentiallyConstantType: allowPotentiallyConstantType);
       if (message == null) return unresolved;
       return new UnresolvedType(
           new NamedTypeBuilder(
-              typeParameter.name,
+              typeParameter.name!,
               builder.nullabilityBuilder,
               /* arguments = */ null,
               unresolved.fileUri,
               unresolved.charOffset)
-            ..bind(
-                new InvalidTypeDeclarationBuilder(typeParameter.name, message)),
+            ..bind(new InvalidTypeDeclarationBuilder(
+                typeParameter.name!, message)),
           unresolved.charOffset,
           unresolved.fileUri);
     } else if (builder is FunctionTypeBuilder) {
-      LocatedMessage message = _validateTypeUseIsInternal(
+      LocatedMessage? message = _validateTypeUseIsInternal(
           builder, unresolved.fileUri, unresolved.charOffset,
           allowPotentiallyConstantType: allowPotentiallyConstantType);
       if (message == null) return unresolved;
-      // TODO(CFE Team): This should probably be some kind of InvalidType
-      // instead of null.
+      // TODO(johnniwinther): We should either remove this method completely and
+      // fully handle this with `nonInstanceContext`, or fully handle all types
+      // and remove `nonInstanceContext`.
       return new UnresolvedType(
-          null, unresolved.charOffset, unresolved.fileUri);
+          new FixedTypeBuilder(
+              const InvalidType(), unresolved.fileUri, unresolved.charOffset),
+          unresolved.charOffset,
+          unresolved.fileUri);
     }
     return unresolved;
   }
 
-  LocatedMessage _validateTypeUseIsInternal(
-      TypeBuilder builder, Uri fileUri, int charOffset,
-      {bool allowPotentiallyConstantType}) {
+  LocatedMessage? _validateTypeUseIsInternal(
+      TypeBuilder? builder, Uri fileUri, int charOffset,
+      {required bool allowPotentiallyConstantType}) {
+    // ignore: unnecessary_null_comparison
     assert(allowPotentiallyConstantType != null);
-    if (builder is NamedTypeBuilder && builder.declaration.isTypeVariable) {
-      TypeVariableBuilder typeParameterBuilder = builder.declaration;
+    if (builder is NamedTypeBuilder && builder.declaration!.isTypeVariable) {
+      TypeVariableBuilder typeParameterBuilder =
+          builder.declaration as TypeVariableBuilder;
       TypeParameter typeParameter = typeParameterBuilder.parameter;
       LocatedMessage message;
-      bool extensionField =
-          (member?.isExtensionMember ?? false) && member.isField;
+      bool extensionField = member.isExtensionMember && member.isField;
       if ((extensionField || !isDeclarationInstanceContext) &&
           (typeParameter.parent is Class ||
               typeParameter.parent is Extension)) {
         message = fasta.messageTypeVariableInStaticContext.withLocation(
             builder.fileUri ?? fileUri,
             builder.charOffset ?? charOffset,
-            typeParameter.name.length);
+            typeParameter.name!.length);
       } else if (constantContext == ConstantContext.inferred &&
           !allowPotentiallyConstantType) {
         message = fasta.messageTypeVariableInConstantContext
-            .withLocation(fileUri, charOffset, typeParameter.name.length);
+            .withLocation(fileUri, charOffset, typeParameter.name!.length);
       } else {
         return null;
       }
       addProblem(message.messageObject, message.charOffset, message.length);
       return message;
     } else if (builder is FunctionTypeBuilder) {
-      LocatedMessage result = _validateTypeUseIsInternal(
+      LocatedMessage? result = _validateTypeUseIsInternal(
           builder.returnType, fileUri, charOffset,
           allowPotentiallyConstantType: allowPotentiallyConstantType);
       if (result != null) {
         return result;
       }
       if (builder.formals != null) {
-        for (FormalParameterBuilder formalParameterBuilder in builder.formals) {
+        for (FormalParameterBuilder formalParameterBuilder
+            in builder.formals!) {
           result = _validateTypeUseIsInternal(
               formalParameterBuilder.type, fileUri, charOffset,
               allowPotentiallyConstantType: allowPotentiallyConstantType);
@@ -6419,7 +6478,7 @@
 
   @override
   Expression evaluateArgumentsBefore(
-      Arguments arguments, Expression expression) {
+      Arguments? arguments, Expression expression) {
     if (arguments == null) return expression;
     List<Expression> expressions =
         new List<Expression>.from(forest.argumentsPositional(arguments));
@@ -6437,7 +6496,7 @@
   }
 
   @override
-  bool isIdentical(Member member) => member == coreTypes.identicalProcedure;
+  bool isIdentical(Member? member) => member == coreTypes.identicalProcedure;
 
   @override
   Expression buildMethodInvocation(
@@ -6457,12 +6516,12 @@
     if (isSuper) {
       // We can ignore [isNullAware] on super sends.
       assert(forest.isThisExpression(receiver));
-      Member target = lookupInstanceMember(name, isSuper: true);
+      Member? target = lookupInstanceMember(name, isSuper: true);
 
       if (target == null || (target is Procedure && !target.isAccessor)) {
         if (target == null) {
           warnUnresolvedMethod(name, offset, isSuper: true);
-        } else if (!areArgumentsCompatible(target.function, arguments)) {
+        } else if (!areArgumentsCompatible(target.function!, arguments)) {
           target = null;
           addProblemErrorIfConst(
               fasta.templateSuperclassMethodArgumentMismatch
@@ -6470,7 +6529,7 @@
               offset,
               name.text.length);
         }
-        return new SuperMethodInvocation(name, arguments, target)
+        return new SuperMethodInvocation(name, arguments, target as Procedure?)
           ..fileOffset = offset;
       }
 
@@ -6480,7 +6539,7 @@
     }
 
     if (isNullAware) {
-      VariableDeclaration variable =
+      VariableDeclarationImpl variable =
           createVariableDeclarationForValue(receiver);
       return new NullAwareMethodInvocation(
           variable,
@@ -6500,15 +6559,15 @@
   @override
   void addProblem(Message message, int charOffset, int length,
       {bool wasHandled: false,
-      List<LocatedMessage> context,
-      Severity severity}) {
+      List<LocatedMessage>? context,
+      Severity? severity}) {
     libraryBuilder.addProblem(message, charOffset, length, uri,
         wasHandled: wasHandled, context: context, severity: severity);
   }
 
   @override
   void addProblemErrorIfConst(Message message, int charOffset, int length,
-      {bool wasHandled: false, List<LocatedMessage> context}) {
+      {bool wasHandled: false, List<LocatedMessage>? context}) {
     // TODO(askesc): Instead of deciding on the severity, this method should
     // take two messages: one to use when a constant expression is
     // required and one to use otherwise.
@@ -6523,7 +6582,7 @@
   @override
   Expression buildProblemErrorIfConst(
       Message message, int charOffset, int length,
-      {bool wasHandled: false, List<LocatedMessage> context}) {
+      {bool wasHandled: false, List<LocatedMessage>? context}) {
     addProblemErrorIfConst(message, charOffset, length,
         wasHandled: wasHandled, context: context);
     String text = libraryBuilder.loader.target.context
@@ -6537,13 +6596,13 @@
   @override
   void reportDuplicatedDeclaration(
       Builder existing, String name, int charOffset) {
-    List<LocatedMessage> context = existing.isSynthetic
+    List<LocatedMessage>? context = existing.isSynthetic
         ? null
         : <LocatedMessage>[
             fasta.templateDuplicatedDeclarationCause
                 .withArguments(name)
                 .withLocation(
-                    existing.fileUri, existing.charOffset, name.length)
+                    existing.fileUri!, existing.charOffset, name.length)
           ];
     addProblem(fasta.templateDuplicatedDeclaration.withArguments(name),
         charOffset, name.length,
@@ -6564,7 +6623,7 @@
   Expression wrapInDeferredCheck(
       Expression expression, PrefixBuilder prefix, int charOffset) {
     VariableDeclaration check = new VariableDeclaration.forValue(
-        forest.checkLibraryIsLoaded(charOffset, prefix.dependency));
+        forest.checkLibraryIsLoaded(charOffset, prefix.dependency!));
     return new DeferredCheck(check, expression)..fileOffset = charOffset;
   }
 
@@ -6577,46 +6636,41 @@
   DartType buildDartType(UnresolvedType unresolvedType,
       {bool nonInstanceAccessIsError: false,
       bool allowPotentiallyConstantType: false}) {
-    if (unresolvedType == null) return null;
     return validateTypeUse(unresolvedType,
             nonInstanceAccessIsError: nonInstanceAccessIsError,
             allowPotentiallyConstantType: allowPotentiallyConstantType)
         .builder
-        ?.build(libraryBuilder);
+        .build(libraryBuilder);
   }
 
   @override
   DartType buildTypeLiteralDartType(UnresolvedType unresolvedType,
       {bool nonInstanceAccessIsError: false,
       bool allowPotentiallyConstantType: false}) {
-    if (unresolvedType == null) return null;
     return validateTypeUse(unresolvedType,
             nonInstanceAccessIsError: nonInstanceAccessIsError,
             allowPotentiallyConstantType: allowPotentiallyConstantType)
         .builder
-        ?.buildTypeLiteralType(libraryBuilder);
+        .buildTypeLiteralType(libraryBuilder);
   }
 
   @override
-  List<DartType> buildDartTypeArguments(List<UnresolvedType> unresolvedTypes) {
+  List<DartType> buildDartTypeArguments(List<UnresolvedType>? unresolvedTypes) {
     if (unresolvedTypes == null) return <DartType>[];
-    List<DartType> types =
-        new List<DartType>.filled(unresolvedTypes.length, null, growable: true);
-    for (int i = 0; i < types.length; i++) {
-      types[i] = buildDartType(unresolvedTypes[i]);
-    }
-    return types;
+    return new List<DartType>.generate(
+        unresolvedTypes.length, (int i) => buildDartType(unresolvedTypes[i]),
+        growable: true);
   }
 
   @override
   String constructorNameForDiagnostics(String name,
-      {String className, bool isSuper: false}) {
+      {String? className, bool isSuper: false}) {
     if (className == null) {
-      Class cls = classBuilder.cls;
+      Class cls = classBuilder!.cls;
       if (isSuper) {
-        cls = cls.superclass;
+        cls = cls.superclass!;
         while (cls.isMixinApplication) {
-          cls = cls.superclass;
+          cls = cls.superclass!;
         }
       }
       className = cls.name;
@@ -6637,13 +6691,13 @@
 }
 
 abstract class EnsureLoaded {
-  void ensureLoaded(Member member);
-  bool isLoaded(Member member);
+  void ensureLoaded(Member? member);
+  bool isLoaded(Member? member);
 }
 
 class Operator {
   final Token token;
-  String get name => token.stringValue;
+  String get name => token.stringValue!;
 
   final int charOffset;
 
@@ -6669,7 +6723,7 @@
       this.kind, this.functionNestingLevel, this.parent, this.charOffset);
 
   @override
-  Uri get fileUri => parent.fileUri;
+  Uri get fileUri => parent.fileUri!;
 
   bool get isBreakTarget => kind == JumpTargetKind.Break;
 
@@ -6695,21 +6749,24 @@
   }
 
   void resolveBreaks(
-      Forest forest, Statement target, Statement targetStatement) {
+      Forest forest, LabeledStatement target, Statement targetStatement) {
     assert(isBreakTarget);
-    for (BreakStatementImpl user in users) {
-      user.target = target;
-      user.targetStatement = targetStatement;
+    for (Statement user in users) {
+      BreakStatementImpl breakStatement = user as BreakStatementImpl;
+      breakStatement.target = target;
+      breakStatement.targetStatement = targetStatement;
     }
     users.clear();
   }
 
-  List<BreakStatementImpl> resolveContinues(Forest forest, Statement target) {
+  List<BreakStatementImpl>? resolveContinues(
+      Forest forest, LabeledStatement target) {
     assert(isContinueTarget);
     List<BreakStatementImpl> statements = <BreakStatementImpl>[];
-    for (BreakStatementImpl user in users) {
-      user.target = target;
-      statements.add(user);
+    for (Statement user in users) {
+      BreakStatementImpl breakStatement = user as BreakStatementImpl;
+      breakStatement.target = target;
+      statements.add(breakStatement);
     }
     users.clear();
     return statements;
@@ -6717,8 +6774,10 @@
 
   void resolveGotos(Forest forest, SwitchCase target) {
     assert(isGotoTarget);
-    for (ContinueSwitchStatement user in users) {
-      user.target = target;
+    for (Statement user in users) {
+      ContinueSwitchStatement continueSwitchStatement =
+          user as ContinueSwitchStatement;
+      continueSwitchStatement.target = target;
     }
     users.clear();
   }
@@ -6747,7 +6806,7 @@
             JumpTargetKind.Continue, functionNestingLevel, parent, charOffset);
 
   @override
-  Uri get fileUri => parent.fileUri;
+  Uri get fileUri => parent.fileUri!;
 
   bool get hasUsers => breakTarget.hasUsers || continueTarget.hasUsers;
 
@@ -6774,11 +6833,12 @@
   }
 
   void resolveBreaks(
-      Forest forest, Statement target, Statement targetStatement) {
+      Forest forest, LabeledStatement target, Statement targetStatement) {
     breakTarget.resolveBreaks(forest, target, targetStatement);
   }
 
-  List<BreakStatementImpl> resolveContinues(Forest forest, Statement target) {
+  List<BreakStatementImpl>? resolveContinues(
+      Forest forest, LabeledStatement target) {
     return continueTarget.resolveContinues(forest, target);
   }
 
@@ -6791,7 +6851,7 @@
 }
 
 class FormalParameters {
-  final List<FormalParameterBuilder> parameters;
+  final List<FormalParameterBuilder>? parameters;
   final int charOffset;
   final int length;
   final Uri uri;
@@ -6804,28 +6864,28 @@
 
   FunctionNode buildFunctionNode(
       SourceLibraryBuilder library,
-      UnresolvedType returnType,
-      List<TypeVariableBuilder> typeParameters,
+      UnresolvedType? returnType,
+      List<TypeVariableBuilder>? typeParameters,
       AsyncMarker asyncModifier,
       Statement body,
       int fileEndOffset,
-      bool notInstanceContext) {
+      {required bool nonInstanceContext}) {
     FunctionType type = toFunctionType(
             returnType, const NullabilityBuilder.omitted(), typeParameters)
         .builder
-        .build(library, null, notInstanceContext);
+        .build(library, nonInstanceContext: nonInstanceContext) as FunctionType;
     List<VariableDeclaration> positionalParameters = <VariableDeclaration>[];
     List<VariableDeclaration> namedParameters = <VariableDeclaration>[];
     if (parameters != null) {
-      for (FormalParameterBuilder parameter in parameters) {
+      for (FormalParameterBuilder parameter in parameters!) {
         if (parameter.isNamed) {
-          namedParameters.add(parameter.variable);
+          namedParameters.add(parameter.variable!);
         } else {
-          positionalParameters.add(parameter.variable);
+          positionalParameters.add(parameter.variable!);
         }
       }
       namedParameters.sort((VariableDeclaration a, VariableDeclaration b) {
-        return a.name.compareTo(b.name);
+        return a.name!.compareTo(b.name!);
       });
     }
     return new FunctionNode(body,
@@ -6840,8 +6900,8 @@
   }
 
   UnresolvedType toFunctionType(
-      UnresolvedType returnType, NullabilityBuilder nullabilityBuilder,
-      [List<TypeVariableBuilder> typeParameters]) {
+      UnresolvedType? returnType, NullabilityBuilder nullabilityBuilder,
+      [List<TypeVariableBuilder>? typeParameters]) {
     return new UnresolvedType(
         new FunctionTypeBuilder(returnType?.builder, typeParameters, parameters,
             nullabilityBuilder, uri, charOffset),
@@ -6852,11 +6912,11 @@
   Scope computeFormalParameterScope(
       Scope parent, Builder declaration, ExpressionGeneratorHelper helper) {
     if (parameters == null) return parent;
-    assert(parameters.isNotEmpty);
+    assert(parameters!.isNotEmpty);
     Map<String, Builder> local = <String, Builder>{};
 
-    for (FormalParameterBuilder parameter in parameters) {
-      Builder existing = local[parameter.name];
+    for (FormalParameterBuilder parameter in parameters!) {
+      Builder? existing = local[parameter.name];
       if (existing != null) {
         helper.reportDuplicatedDeclaration(
             existing, parameter.name, parameter.charOffset);
@@ -6916,7 +6976,7 @@
 ///   debugName("", ""),
 ///   ""
 /// )
-String debugName(String className, String name, [String prefix]) {
+String debugName(String className, String name, [String? prefix]) {
   String result = name.isEmpty ? className : "$className.$name";
   return prefix == null ? result : "$prefix.$result";
 }
@@ -6947,12 +7007,12 @@
 }
 
 class ForInElements {
-  VariableDeclaration explicitVariableDeclaration;
-  VariableDeclaration syntheticVariableDeclaration;
-  Expression syntheticAssignment;
-  Expression expressionProblem;
-  Statement expressionEffects;
+  VariableDeclaration? explicitVariableDeclaration;
+  VariableDeclaration? syntheticVariableDeclaration;
+  Expression? syntheticAssignment;
+  Expression? expressionProblem;
+  Statement? expressionEffects;
 
   VariableDeclaration get variable =>
-      explicitVariableDeclaration ?? syntheticVariableDeclaration;
+      (explicitVariableDeclaration ?? syntheticVariableDeclaration)!;
 }
diff --git a/pkg/front_end/lib/src/fasta/kernel/class_hierarchy_builder.dart b/pkg/front_end/lib/src/fasta/kernel/class_hierarchy_builder.dart
index 2e0f2fb..ccd60c9 100644
--- a/pkg/front_end/lib/src/fasta/kernel/class_hierarchy_builder.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/class_hierarchy_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.class_hierarchy_builder;
 
 import 'package:kernel/ast.dart';
@@ -86,7 +84,7 @@
 
 import 'forwarding_node.dart' show ForwardingNode;
 
-const DebugLogger debug =
+const DebugLogger? debug =
     const bool.fromEnvironment("debug.hierarchy") ? const DebugLogger() : null;
 
 class DebugLogger {
@@ -115,53 +113,59 @@
 
 class Tuple {
   final Name name;
-  ClassMember _declaredMember;
-  ClassMember _declaredSetter;
-  ClassMember _mixedInMember;
-  ClassMember _mixedInSetter;
-  ClassMember _extendedMember;
-  ClassMember _extendedSetter;
-  List<ClassMember> _implementedMembers;
-  List<ClassMember> _implementedSetters;
+  ClassMember? _declaredMember;
+  ClassMember? _declaredSetter;
+  ClassMember? _mixedInMember;
+  ClassMember? _mixedInSetter;
+  ClassMember? _extendedMember;
+  ClassMember? _extendedSetter;
+  List<ClassMember>? _implementedMembers;
+  List<ClassMember>? _implementedSetters;
 
-  Tuple.declareMember(this._declaredMember)
-      : assert(!_declaredMember.forSetter),
-        this.name = _declaredMember.name;
+  Tuple.declareMember(ClassMember declaredMember)
+      : assert(!declaredMember.forSetter),
+        this._declaredMember = declaredMember,
+        this.name = declaredMember.name;
 
-  Tuple.mixInMember(this._mixedInMember)
-      : assert(!_mixedInMember.forSetter),
-        this.name = _mixedInMember.name;
+  Tuple.mixInMember(ClassMember mixedInMember)
+      : assert(!mixedInMember.forSetter),
+        this._mixedInMember = mixedInMember,
+        this.name = mixedInMember.name;
 
-  Tuple.extendMember(this._extendedMember)
-      : assert(!_extendedMember.forSetter),
-        this.name = _extendedMember.name;
+  Tuple.extendMember(ClassMember extendedMember)
+      : assert(!extendedMember.forSetter),
+        this._extendedMember = extendedMember,
+        this.name = extendedMember.name;
 
   Tuple.implementMember(ClassMember implementedMember)
       : assert(!implementedMember.forSetter),
         this.name = implementedMember.name,
         _implementedMembers = <ClassMember>[implementedMember];
 
-  Tuple.declareSetter(this._declaredSetter)
-      : assert(_declaredSetter.forSetter),
-        this.name = _declaredSetter.name;
+  Tuple.declareSetter(ClassMember declaredSetter)
+      : assert(declaredSetter.forSetter),
+        this._declaredSetter = declaredSetter,
+        this.name = declaredSetter.name;
 
-  Tuple.mixInSetter(this._mixedInSetter)
-      : assert(_mixedInSetter.forSetter),
-        this.name = _mixedInSetter.name;
+  Tuple.mixInSetter(ClassMember mixedInSetter)
+      : assert(mixedInSetter.forSetter),
+        this._mixedInSetter = mixedInSetter,
+        this.name = mixedInSetter.name;
 
-  Tuple.extendSetter(this._extendedSetter)
-      : assert(_extendedSetter.forSetter),
-        this.name = _extendedSetter.name;
+  Tuple.extendSetter(ClassMember extendedSetter)
+      : assert(extendedSetter.forSetter),
+        this._extendedSetter = extendedSetter,
+        this.name = extendedSetter.name;
 
   Tuple.implementSetter(ClassMember implementedSetter)
       : assert(implementedSetter.forSetter),
         this.name = implementedSetter.name,
         _implementedSetters = <ClassMember>[implementedSetter];
 
-  ClassMember get declaredMember => _declaredMember;
+  ClassMember? get declaredMember => _declaredMember;
 
-  void set declaredMember(ClassMember value) {
-    assert(!value.forSetter);
+  void set declaredMember(ClassMember? value) {
+    assert(!value!.forSetter);
     assert(
         _declaredMember == null,
         "Declared member already set to $_declaredMember, "
@@ -169,10 +173,10 @@
     _declaredMember = value;
   }
 
-  ClassMember get declaredSetter => _declaredSetter;
+  ClassMember? get declaredSetter => _declaredSetter;
 
-  void set declaredSetter(ClassMember value) {
-    assert(value.forSetter);
+  void set declaredSetter(ClassMember? value) {
+    assert(value!.forSetter);
     assert(
         _declaredSetter == null,
         "Declared setter already set to $_declaredSetter, "
@@ -180,10 +184,10 @@
     _declaredSetter = value;
   }
 
-  ClassMember get extendedMember => _extendedMember;
+  ClassMember? get extendedMember => _extendedMember;
 
-  void set extendedMember(ClassMember value) {
-    assert(!value.forSetter);
+  void set extendedMember(ClassMember? value) {
+    assert(!value!.forSetter);
     assert(
         _extendedMember == null,
         "Extended member already set to $_extendedMember, "
@@ -191,10 +195,10 @@
     _extendedMember = value;
   }
 
-  ClassMember get extendedSetter => _extendedSetter;
+  ClassMember? get extendedSetter => _extendedSetter;
 
-  void set extendedSetter(ClassMember value) {
-    assert(value.forSetter);
+  void set extendedSetter(ClassMember? value) {
+    assert(value!.forSetter);
     assert(
         _extendedSetter == null,
         "Extended setter already set to $_extendedSetter, "
@@ -202,10 +206,10 @@
     _extendedSetter = value;
   }
 
-  ClassMember get mixedInMember => _mixedInMember;
+  ClassMember? get mixedInMember => _mixedInMember;
 
-  void set mixedInMember(ClassMember value) {
-    assert(!value.forSetter);
+  void set mixedInMember(ClassMember? value) {
+    assert(!value!.forSetter);
     assert(
         _mixedInMember == null,
         "Mixed in member already set to $_mixedInMember, "
@@ -213,10 +217,10 @@
     _mixedInMember = value;
   }
 
-  ClassMember get mixedInSetter => _mixedInSetter;
+  ClassMember? get mixedInSetter => _mixedInSetter;
 
-  void set mixedInSetter(ClassMember value) {
-    assert(value.forSetter);
+  void set mixedInSetter(ClassMember? value) {
+    assert(value!.forSetter);
     assert(
         _mixedInSetter == null,
         "Mixed in setter already set to $_mixedInSetter, "
@@ -224,20 +228,20 @@
     _mixedInSetter = value;
   }
 
-  List<ClassMember> get implementedMembers => _implementedMembers;
+  List<ClassMember>? get implementedMembers => _implementedMembers;
 
   void addImplementedMember(ClassMember value) {
     assert(!value.forSetter);
     _implementedMembers ??= <ClassMember>[];
-    _implementedMembers.add(value);
+    _implementedMembers!.add(value);
   }
 
-  List<ClassMember> get implementedSetters => _implementedSetters;
+  List<ClassMember>? get implementedSetters => _implementedSetters;
 
   void addImplementedSetter(ClassMember value) {
     assert(value.forSetter);
     _implementedSetters ??= <ClassMember>[];
-    _implementedSetters.add(value);
+    _implementedSetters!.add(value);
   }
 
   @override
@@ -419,13 +423,13 @@
   List<TypeParameter> bTypeParameters = b.typeParameters;
   int typeParameterCount = aTypeParameters.length;
   if (typeParameterCount != bTypeParameters.length) return false;
-  Substitution substitution;
+  Substitution? substitution;
   if (typeParameterCount != 0) {
-    List<DartType> types = new List<DartType>.filled(typeParameterCount, null);
-    for (int i = 0; i < typeParameterCount; i++) {
-      types[i] = new TypeParameterType.forAlphaRenaming(
-          bTypeParameters[i], aTypeParameters[i]);
-    }
+    List<DartType> types = new List<DartType>.generate(
+        typeParameterCount,
+        (int i) => new TypeParameterType.forAlphaRenaming(
+            bTypeParameters[i], aTypeParameters[i]),
+        growable: false);
     substitution = Substitution.fromPairs(bTypeParameters, types);
     for (int i = 0; i < typeParameterCount; i++) {
       DartType aBound = aTypeParameters[i].bound;
@@ -502,7 +506,7 @@
 
   final CoreTypes coreTypes;
 
-  Types types;
+  late Types types;
 
   ClassHierarchyBuilder(this.objectClassBuilder, this.loader, this.coreTypes)
       : objectClass = objectClassBuilder.cls,
@@ -561,8 +565,7 @@
       Iterable<ClassMember> overriddenMembers) {
     ClassHierarchyNodeBuilder.inferFieldType(
         this,
-        declaredMember.classBuilder,
-        substitutions[declaredMember.classBuilder],
+        declaredMember.classBuilder as SourceClassBuilder,
         declaredMember,
         overriddenMembers);
   }
@@ -571,8 +574,7 @@
       Iterable<ClassMember> overriddenMembers) {
     ClassHierarchyNodeBuilder.inferGetterType(
         this,
-        declaredMember.classBuilder,
-        substitutions[declaredMember.classBuilder],
+        declaredMember.classBuilder as SourceClassBuilder,
         declaredMember,
         overriddenMembers);
   }
@@ -581,8 +583,7 @@
       Iterable<ClassMember> overriddenMembers) {
     ClassHierarchyNodeBuilder.inferSetterType(
         this,
-        declaredMember.classBuilder,
-        substitutions[declaredMember.classBuilder],
+        declaredMember.classBuilder as SourceClassBuilder,
         declaredMember,
         overriddenMembers);
   }
@@ -591,8 +592,7 @@
       Iterable<ClassMember> overriddenMembers) {
     ClassHierarchyNodeBuilder.inferMethodType(
         this,
-        declaredMember.classBuilder,
-        substitutions[declaredMember.classBuilder],
+        declaredMember.classBuilder as SourceClassBuilder,
         declaredMember,
         overriddenMembers);
   }
@@ -603,8 +603,8 @@
         .build();
   }
 
-  ClassHierarchyNode getNodeFromTypeBuilder(TypeBuilder type) {
-    ClassBuilder cls = getClass(type);
+  ClassHierarchyNode? getNodeFromTypeBuilder(TypeBuilder type) {
+    ClassBuilder? cls = getClass(type);
     return cls == null ? null : getNodeFromClassBuilder(cls);
   }
 
@@ -613,7 +613,7 @@
         getNodeFromClassBuilder(loader.computeClassBuilderFromTargetClass(cls));
   }
 
-  Supertype asSupertypeOf(InterfaceType subtype, Class supertype) {
+  Supertype? asSupertypeOf(InterfaceType subtype, Class supertype) {
     if (subtype.classNode == supertype) {
       return new Supertype(supertype, subtype.typeArguments);
     }
@@ -642,12 +642,12 @@
   InterfaceType getTypeAsInstanceOf(
       InterfaceType type, Class superclass, Library clientLibrary) {
     if (type.classNode == superclass) return type;
-    return asSupertypeOf(type, superclass)
+    return asSupertypeOf(type, superclass)!
         .asInterfaceType
         .withDeclaredNullability(type.nullability);
   }
 
-  List<DartType> getTypeArgumentsAsInstanceOf(
+  List<DartType>? getTypeArgumentsAsInstanceOf(
       InterfaceType type, Class superclass) {
     if (type.classNode == superclass) return type.typeArguments;
     return asSupertypeOf(type, superclass)?.typeArguments;
@@ -679,6 +679,7 @@
 
     for (int i = 0; i < nodes2.length; i++) {
       ClassHierarchyNode node = nodes2[i];
+      // ignore: unnecessary_null_comparison
       if (node == null) continue;
       if (node.classBuilder.cls.isAnonymousMixin) {
         // Never find unnamed mixin application in least upper bound.
@@ -717,13 +718,13 @@
         uniteNullabilities(type1.nullability, type2.nullability));
   }
 
-  Member getInterfaceMember(Class cls, Name name, {bool setter: false}) {
+  Member? getInterfaceMember(Class cls, Name name, {bool setter: false}) {
     return getNodeFromClass(cls)
         .getInterfaceMember(name, setter)
         ?.getMember(this);
   }
 
-  ClassMember getInterfaceClassMember(Class cls, Name name,
+  ClassMember? getInterfaceClassMember(Class cls, Name name,
       {bool setter: false}) {
     return getNodeFromClass(cls).getInterfaceMember(name, setter);
   }
@@ -774,7 +775,7 @@
   bool get shouldModifyKernel =>
       classBuilder.library.loader == hierarchy.loader;
 
-  ClassMember checkInheritanceConflict(ClassMember a, ClassMember b) {
+  ClassMember? checkInheritanceConflict(ClassMember a, ClassMember b) {
     if (a.isStatic || a.isProperty != b.isProperty) {
       reportInheritanceConflict(a, b);
       return a;
@@ -784,17 +785,16 @@
 
   static void inferMethodType(
       ClassHierarchyBuilder hierarchy,
-      ClassBuilder classBuilder,
-      Map<Class, Substitution> substitutions,
+      SourceClassBuilder classBuilder,
       SourceProcedureBuilder declaredMember,
       Iterable<ClassMember> overriddenMembers) {
     assert(!declaredMember.isGetter && !declaredMember.isSetter);
     if (declaredMember.classBuilder == classBuilder &&
         (declaredMember.returnType == null ||
             declaredMember.formals != null &&
-                declaredMember.formals
+                declaredMember.formals!
                     .any((parameter) => parameter.type == null))) {
-      Procedure declaredProcedure = declaredMember.member;
+      Procedure declaredProcedure = declaredMember.member as Procedure;
       FunctionNode declaredFunction = declaredProcedure.function;
       List<TypeParameter> declaredTypeParameters =
           declaredFunction.typeParameters;
@@ -804,20 +804,21 @@
           declaredFunction.namedParameters;
       declaredNamed = declaredNamed.toList()..sort(compareNamedParameters);
 
-      DartType inferredReturnType;
-      Map<FormalParameterBuilder, DartType> inferredParameterTypes = {};
+      DartType? inferredReturnType;
+      Map<FormalParameterBuilder, DartType?> inferredParameterTypes = {};
 
       Set<ClassMember> overriddenMemberSet =
-          toSet(declaredMember.classBuilder, overriddenMembers);
+          toSet(classBuilder, overriddenMembers);
       CombinedClassMemberSignature combinedMemberSignature =
           new CombinedClassMemberSignature(
               hierarchy, classBuilder, overriddenMemberSet.toList(),
               forSetter: false);
-      FunctionType combinedMemberSignatureType = combinedMemberSignature
-          .getCombinedSignatureTypeInContext(declaredTypeParameters);
+      FunctionType? combinedMemberSignatureType = combinedMemberSignature
+              .getCombinedSignatureTypeInContext(declaredTypeParameters)
+          as FunctionType?;
 
       bool cantInferReturnType = false;
-      List<FormalParameterBuilder> cantInferParameterTypes;
+      List<FormalParameterBuilder>? cantInferParameterTypes;
 
       if (declaredMember.returnType == null) {
         if (combinedMemberSignatureType == null) {
@@ -829,12 +830,12 @@
       }
       if (declaredMember.formals != null) {
         for (int i = 0; i < declaredPositional.length; i++) {
-          FormalParameterBuilder declaredParameter = declaredMember.formals[i];
+          FormalParameterBuilder declaredParameter = declaredMember.formals![i];
           if (declaredParameter.type != null) {
             continue;
           }
 
-          DartType inferredParameterType;
+          DartType? inferredParameterType;
           if (combinedMemberSignatureType == null) {
             inferredParameterType = const InvalidType();
             cantInferParameterTypes ??= [];
@@ -847,16 +848,16 @@
           inferredParameterTypes[declaredParameter] = inferredParameterType;
         }
 
-        Map<String, DartType> namedParameterTypes;
+        Map<String, DartType>? namedParameterTypes;
         for (int i = declaredPositional.length;
-            i < declaredMember.formals.length;
+            i < declaredMember.formals!.length;
             i++) {
-          FormalParameterBuilder declaredParameter = declaredMember.formals[i];
+          FormalParameterBuilder declaredParameter = declaredMember.formals![i];
           if (declaredParameter.type != null) {
             continue;
           }
 
-          DartType inferredParameterType;
+          DartType? inferredParameterType;
           if (combinedMemberSignatureType == null) {
             inferredParameterType = const InvalidType();
             cantInferParameterTypes ??= [];
@@ -894,12 +895,12 @@
       }
       if (declaredMember.formals != null) {
         for (FormalParameterBuilder declaredParameter
-            in declaredMember.formals) {
+            in declaredMember.formals!) {
           if (declaredParameter.type == null) {
             DartType inferredParameterType =
                 inferredParameterTypes[declaredParameter] ??
                     const DynamicType();
-            declaredParameter.variable.type = inferredParameterType;
+            declaredParameter.variable!.type = inferredParameterType;
           }
         }
       }
@@ -910,7 +911,8 @@
       ClassMember declaredMember, Iterable<ClassMember> overriddenMembers) {
     assert(!declaredMember.isGetter && !declaredMember.isSetter);
     // Trigger computation of method type.
-    Procedure declaredProcedure = declaredMember.getMember(hierarchy);
+    Procedure declaredProcedure =
+        declaredMember.getMember(hierarchy) as Procedure;
     for (ClassMember overriddenMember
         in toSet(declaredMember.classBuilder, overriddenMembers)) {
       Covariance covariance = overriddenMember.getCovariance(hierarchy);
@@ -930,7 +932,7 @@
       ClassMember declaredMember, Iterable<ClassMember> overriddenMembers) {
     assert(declaredMember.isSetter);
     // Trigger computation of the getter type.
-    Procedure declaredSetter = declaredMember.getMember(hierarchy);
+    Procedure declaredSetter = declaredMember.getMember(hierarchy) as Procedure;
     for (ClassMember overriddenMember
         in toSet(declaredMember.classBuilder, overriddenMembers)) {
       Covariance covariance = overriddenMember.getCovariance(hierarchy);
@@ -940,14 +942,13 @@
 
   static void inferGetterType(
       ClassHierarchyBuilder hierarchy,
-      ClassBuilder classBuilder,
-      Map<Class, Substitution> substitutions,
+      SourceClassBuilder classBuilder,
       SourceProcedureBuilder declaredMember,
       Iterable<ClassMember> overriddenMembers) {
     assert(declaredMember.isGetter);
     if (declaredMember.classBuilder == classBuilder &&
         declaredMember.returnType == null) {
-      DartType inferredType;
+      DartType? inferredType;
       overriddenMembers = toSet(classBuilder, overriddenMembers);
 
       List<ClassMember> overriddenGetters = [];
@@ -960,12 +961,13 @@
         }
       }
 
-      void inferFrom(List<ClassMember> members, {bool forSetter}) {
+      void inferFrom(List<ClassMember> members, {required bool forSetter}) {
+        // ignore: unnecessary_null_comparison
         assert(forSetter != null);
         CombinedClassMemberSignature combinedMemberSignature =
             new CombinedClassMemberSignature(hierarchy, classBuilder, members,
                 forSetter: forSetter);
-        DartType combinedMemberSignatureType =
+        DartType? combinedMemberSignatureType =
             combinedMemberSignature.combinedMemberSignatureType;
         if (combinedMemberSignatureType == null) {
           inferredType = const InvalidType();
@@ -995,21 +997,20 @@
         inferFrom(overriddenSetters, forSetter: true);
       }
 
-      inferredType ??= const DynamicType();
-      declaredMember.procedure.function.returnType = inferredType;
+      declaredMember.procedure.function.returnType =
+          inferredType ?? const DynamicType();
     }
   }
 
   static void inferSetterType(
       ClassHierarchyBuilder hierarchy,
-      ClassBuilder classBuilder,
-      Map<Class, Substitution> substitutions,
+      SourceClassBuilder classBuilder,
       SourceProcedureBuilder declaredMember,
       Iterable<ClassMember> overriddenMembers) {
     assert(declaredMember.isSetter);
-    FormalParameterBuilder parameter = declaredMember.formals.first;
+    FormalParameterBuilder parameter = declaredMember.formals!.first;
     if (declaredMember.classBuilder == classBuilder && parameter.type == null) {
-      DartType inferredType;
+      DartType? inferredType;
 
       overriddenMembers = toSet(classBuilder, overriddenMembers);
 
@@ -1023,12 +1024,13 @@
         }
       }
 
-      void inferFrom(List<ClassMember> members, {bool forSetter}) {
+      void inferFrom(List<ClassMember> members, {required bool forSetter}) {
+        // ignore: unnecessary_null_comparison
         assert(forSetter != null);
         CombinedClassMemberSignature combinedMemberSignature =
             new CombinedClassMemberSignature(hierarchy, classBuilder, members,
                 forSetter: forSetter);
-        DartType combinedMemberSignatureType =
+        DartType? combinedMemberSignatureType =
             combinedMemberSignature.combinedMemberSignatureType;
         if (combinedMemberSignatureType == null) {
           inferredType = const InvalidType();
@@ -1058,8 +1060,7 @@
         inferFrom(overriddenGetters, forSetter: false);
       }
 
-      inferredType ??= const DynamicType();
-      parameter.variable.type = inferredType;
+      parameter.variable!.type = inferredType ?? const DynamicType();
     }
   }
 
@@ -1067,10 +1068,10 @@
   /// nnbd-top-merge or legacy-top-merge depending on whether [classBuilder] is
   /// defined in an opt-in or opt-out library. If the types could not be merged
   /// `null` is returned and an error should be reported by the caller.
-  static DartType mergeTypeInLibrary(
+  static DartType? mergeTypeInLibrary(
       ClassHierarchyBuilder hierarchy,
       ClassBuilder classBuilder,
-      DartType inferredType,
+      DartType? inferredType,
       DartType inheritedType) {
     if (classBuilder.library.isNonNullableByDefault) {
       if (inferredType == null) {
@@ -1104,13 +1105,12 @@
   /// Infers the field type of [fieldBuilder] based on [overriddenMembers].
   static void inferFieldType(
       ClassHierarchyBuilder hierarchy,
-      ClassBuilder classBuilder,
-      Map<Class, Substitution> substitutions,
+      SourceClassBuilder classBuilder,
       SourceFieldBuilder fieldBuilder,
       Iterable<ClassMember> overriddenMembers) {
     if (fieldBuilder.classBuilder == classBuilder &&
         fieldBuilder.type == null) {
-      DartType inferredType;
+      DartType? inferredType;
 
       overriddenMembers = toSet(classBuilder, overriddenMembers);
       List<ClassMember> overriddenGetters = [];
@@ -1123,7 +1123,9 @@
         }
       }
 
-      DartType inferFrom(List<ClassMember> members, {bool forSetter}) {
+      DartType? inferFrom(List<ClassMember> members,
+          {required bool forSetter}) {
+        // ignore: unnecessary_null_comparison
         assert(forSetter != null);
         CombinedClassMemberSignature combinedMemberSignature =
             new CombinedClassMemberSignature(hierarchy, classBuilder, members,
@@ -1131,7 +1133,7 @@
         return combinedMemberSignature.combinedMemberSignatureType;
       }
 
-      DartType combinedMemberSignatureType;
+      DartType? combinedMemberSignatureType;
       if (fieldBuilder.isAssignable &&
           overriddenGetters.isNotEmpty &&
           overriddenSetters.isNotEmpty) {
@@ -1142,8 +1144,8 @@
         // combined member signature of said getter in the direct
         // superinterfaces. If the types are not the same then inference fails
         // with an error.
-        DartType getterType = inferFrom(overriddenGetters, forSetter: false);
-        DartType setterType = inferFrom(overriddenSetters, forSetter: true);
+        DartType? getterType = inferFrom(overriddenGetters, forSetter: false);
+        DartType? setterType = inferFrom(overriddenSetters, forSetter: true);
         if (getterType == setterType) {
           combinedMemberSignatureType = getterType;
         }
@@ -1175,7 +1177,6 @@
         inferredType = combinedMemberSignatureType;
       }
 
-      inferredType ??= const DynamicType();
       fieldBuilder.fieldType = inferredType;
     }
   }
@@ -1184,7 +1185,7 @@
   /// [overriddenMembers].
   void inferFieldSignature(ClassHierarchyBuilder hierarchy,
       ClassMember declaredMember, Iterable<ClassMember> overriddenMembers) {
-    Field declaredField = declaredMember.getMember(hierarchy);
+    Field declaredField = declaredMember.getMember(hierarchy) as Field;
     for (ClassMember overriddenMember
         in toSet(declaredMember.classBuilder, overriddenMembers)) {
       Covariance covariance = overriddenMember.getCovariance(hierarchy);
@@ -1264,13 +1265,14 @@
 
   ClassHierarchyNode build() {
     assert(!classBuilder.isPatch);
-    ClassHierarchyNode supernode;
+    ClassHierarchyNode? supernode;
     if (objectClass != classBuilder.origin) {
       supernode =
-          hierarchy.getNodeFromTypeBuilder(classBuilder.supertypeBuilder);
+          hierarchy.getNodeFromTypeBuilder(classBuilder.supertypeBuilder!);
       if (supernode == null) {
         supernode = hierarchy.getNodeFromClassBuilder(objectClass);
       }
+      // ignore: unnecessary_null_comparison
       assert(supernode != null);
     }
 
@@ -1286,12 +1288,13 @@
 
     Scope scope = classBuilder.scope;
 
-    for (MemberBuilder memberBuilder in scope.localMembers) {
+    for (Builder builder in scope.localMembers) {
+      MemberBuilder memberBuilder = builder as MemberBuilder;
       for (ClassMember classMember in memberBuilder.localMembers) {
         if (classMember.isAbstract) {
           hasInterfaces = true;
         }
-        Tuple tuple = memberMap[classMember.name];
+        Tuple? tuple = memberMap[classMember.name];
         if (tuple == null) {
           memberMap[classMember.name] = new Tuple.declareMember(classMember);
         } else {
@@ -1302,7 +1305,7 @@
         if (classMember.isAbstract) {
           hasInterfaces = true;
         }
-        Tuple tuple = memberMap[classMember.name];
+        Tuple? tuple = memberMap[classMember.name];
         if (tuple == null) {
           memberMap[classMember.name] = new Tuple.declareSetter(classMember);
         } else {
@@ -1316,7 +1319,7 @@
         if (classMember.isAbstract) {
           hasInterfaces = true;
         }
-        Tuple tuple = memberMap[classMember.name];
+        Tuple? tuple = memberMap[classMember.name];
         if (tuple == null) {
           memberMap[classMember.name] = new Tuple.declareMember(classMember);
         } else {
@@ -1327,7 +1330,7 @@
         if (classMember.isAbstract) {
           hasInterfaces = true;
         }
-        Tuple tuple = memberMap[classMember.name];
+        Tuple? tuple = memberMap[classMember.name];
         if (tuple == null) {
           memberMap[classMember.name] = new Tuple.declareSetter(classMember);
         } else {
@@ -1337,31 +1340,32 @@
     }
 
     if (classBuilder.isMixinApplication) {
-      TypeBuilder mixedInTypeBuilder = classBuilder.mixedInTypeBuilder;
-      TypeDeclarationBuilder mixin = mixedInTypeBuilder.declaration;
+      TypeBuilder mixedInTypeBuilder = classBuilder.mixedInTypeBuilder!;
+      TypeDeclarationBuilder mixin = mixedInTypeBuilder.declaration!;
       inferMixinApplication();
       while (mixin.isNamedMixinApplication) {
-        ClassBuilder named = mixin;
-        mixedInTypeBuilder = named.mixedInTypeBuilder;
-        mixin = mixedInTypeBuilder.declaration;
+        ClassBuilder named = mixin as ClassBuilder;
+        mixedInTypeBuilder = named.mixedInTypeBuilder!;
+        mixin = mixedInTypeBuilder.declaration!;
       }
       if (mixin is TypeAliasBuilder) {
         TypeAliasBuilder aliasBuilder = mixin;
-        NamedTypeBuilder namedBuilder = mixedInTypeBuilder;
+        NamedTypeBuilder namedBuilder = mixedInTypeBuilder as NamedTypeBuilder;
         mixin = aliasBuilder.unaliasDeclaration(namedBuilder.arguments,
             isUsedAsClass: true,
             usedAsClassCharOffset: namedBuilder.charOffset,
-            usedAsClassFileUri: namedBuilder.fileUri);
+            usedAsClassFileUri: namedBuilder.fileUri)!;
       }
       if (mixin is ClassBuilder) {
         scope = mixin.scope.computeMixinScope();
 
-        for (MemberBuilder memberBuilder in scope.localMembers) {
+        for (Builder builder in scope.localMembers) {
+          MemberBuilder memberBuilder = builder as MemberBuilder;
           for (ClassMember classMember in memberBuilder.localMembers) {
             if (classMember.isAbstract) {
               hasInterfaces = true;
             }
-            Tuple tuple = memberMap[classMember.name];
+            Tuple? tuple = memberMap[classMember.name];
             if (tuple == null) {
               memberMap[classMember.name] = new Tuple.mixInMember(classMember);
             } else {
@@ -1372,7 +1376,7 @@
             if (classMember.isAbstract) {
               hasInterfaces = true;
             }
-            Tuple tuple = memberMap[classMember.name];
+            Tuple? tuple = memberMap[classMember.name];
             if (tuple == null) {
               memberMap[classMember.name] = new Tuple.mixInSetter(classMember);
             } else {
@@ -1386,7 +1390,7 @@
             if (classMember.isAbstract) {
               hasInterfaces = true;
             }
-            Tuple tuple = memberMap[classMember.name];
+            Tuple? tuple = memberMap[classMember.name];
             if (tuple == null) {
               memberMap[classMember.name] = new Tuple.mixInMember(classMember);
             } else {
@@ -1397,7 +1401,7 @@
             if (classMember.isAbstract) {
               hasInterfaces = true;
             }
-            Tuple tuple = memberMap[classMember.name];
+            Tuple? tuple = memberMap[classMember.name];
             if (tuple == null) {
               memberMap[classMember.name] = new Tuple.mixInSetter(classMember);
             } else {
@@ -1414,11 +1418,12 @@
 
     int maxInheritancePath;
 
-    void extend(Map<Name, ClassMember> superClassMembers) {
+    void extend(Map<Name, ClassMember>? superClassMembers) {
       if (superClassMembers == null) return;
-      for (Name name in superClassMembers.keys) {
-        ClassMember superClassMember = superClassMembers[name];
-        Tuple tuple = memberMap[name];
+      for (MapEntry<Name, ClassMember> entry in superClassMembers.entries) {
+        Name name = entry.key;
+        ClassMember superClassMember = entry.value;
+        Tuple? tuple = memberMap[name];
         if (tuple != null) {
           if (superClassMember.forSetter) {
             tuple.extendedSetter = superClassMember;
@@ -1435,11 +1440,12 @@
       }
     }
 
-    void implement(Map<Name, ClassMember> superInterfaceMembers) {
+    void implement(Map<Name, ClassMember>? superInterfaceMembers) {
       if (superInterfaceMembers == null) return;
-      for (Name name in superInterfaceMembers.keys) {
-        ClassMember superInterfaceMember = superInterfaceMembers[name];
-        Tuple tuple = memberMap[name];
+      for (MapEntry<Name, ClassMember> entry in superInterfaceMembers.entries) {
+        Name name = entry.key;
+        ClassMember superInterfaceMember = entry.value;
+        Tuple? tuple = memberMap[name];
         if (tuple != null) {
           if (superInterfaceMember.forSetter) {
             tuple.addImplementedSetter(superInterfaceMember);
@@ -1460,15 +1466,15 @@
 
     if (supernode == null) {
       // This should be Object.
-      superclasses = new List<Supertype>.filled(0, null);
-      interfaces = new List<Supertype>.filled(0, null);
+      superclasses = new List<Supertype>.filled(0, dummySupertype);
+      interfaces = new List<Supertype>.filled(0, dummySupertype);
       maxInheritancePath = 0;
     } else {
       maxInheritancePath = supernode.maxInheritancePath + 1;
 
-      superclasses =
-          new List<Supertype>.filled(supernode.superclasses.length + 1, null);
-      Supertype supertype = classBuilder.supertypeBuilder.buildSupertype(
+      superclasses = new List<Supertype>.filled(
+          supernode.superclasses.length + 1, dummySupertype);
+      Supertype? supertype = classBuilder.supertypeBuilder!.buildSupertype(
           classBuilder.library, classBuilder.charOffset, classBuilder.fileUri);
       if (supertype == null) {
         // If the superclass is not an interface type we use Object instead.
@@ -1486,21 +1492,22 @@
         }
       }
 
-      List<TypeBuilder> directInterfaceBuilders =
+      List<TypeBuilder>? directInterfaceBuilders =
           ignoreFunction(classBuilder.interfaceBuilders);
       if (classBuilder.isMixinApplication) {
         if (directInterfaceBuilders == null) {
           directInterfaceBuilders = <TypeBuilder>[
-            classBuilder.mixedInTypeBuilder
+            classBuilder.mixedInTypeBuilder!
           ];
         } else {
           directInterfaceBuilders = <TypeBuilder>[
-            classBuilder.mixedInTypeBuilder
+            classBuilder.mixedInTypeBuilder!
           ]..addAll(directInterfaceBuilders);
         }
       }
 
       List<Supertype> superclassInterfaces = supernode.interfaces;
+      // ignore: unnecessary_null_comparison
       if (superclassInterfaces != null) {
         superclassInterfaces = substSupertypes(supertype, superclassInterfaces);
       }
@@ -1520,7 +1527,7 @@
 
       if (directInterfaceBuilders != null) {
         for (int i = 0; i < directInterfaceBuilders.length; i++) {
-          ClassHierarchyNode interfaceNode =
+          ClassHierarchyNode? interfaceNode =
               hierarchy.getNodeFromTypeBuilder(directInterfaceBuilders[i]);
           if (interfaceNode != null) {
             hasInterfaces = true;
@@ -1533,6 +1540,7 @@
         }
 
         interfaces = <Supertype>[];
+        // ignore: unnecessary_null_comparison
         if (superclassInterfaces != null) {
           for (int i = 0; i < superclassInterfaces.length; i++) {
             addInterface(interfaces, superclasses, superclassInterfaces[i]);
@@ -1540,14 +1548,14 @@
         }
 
         for (int i = 0; i < directInterfaceBuilders.length; i++) {
-          Supertype directInterface = directInterfaceBuilders[i].buildSupertype(
-              classBuilder.library,
-              classBuilder.charOffset,
-              classBuilder.fileUri);
+          Supertype? directInterface = directInterfaceBuilders[i]
+              .buildSupertype(classBuilder.library, classBuilder.charOffset,
+                  classBuilder.fileUri);
           if (directInterface != null) {
             addInterface(interfaces, superclasses, directInterface);
             ClassHierarchyNode interfaceNode =
                 hierarchy.getNodeFromClass(directInterface.classNode);
+            // ignore: unnecessary_null_comparison
             if (interfaceNode != null) {
               if (maxInheritancePath < interfaceNode.maxInheritancePath + 1) {
                 maxInheritancePath = interfaceNode.maxInheritancePath + 1;
@@ -1558,6 +1566,7 @@
               for (int i = 0; i < types.length; i++) {
                 addInterface(interfaces, superclasses, types[i]);
               }
+              // ignore: unnecessary_null_comparison
               if (interfaceNode.interfaces != null) {
                 List<Supertype> types =
                     substSupertypes(directInterface, interfaceNode.interfaces);
@@ -1568,6 +1577,7 @@
             }
           }
         }
+        // ignore: unnecessary_null_comparison
       } else if (superclassInterfaces != null &&
           !classBuilder.library.isNonNullableByDefault &&
           supernode.classBuilder.library.isNonNullableByDefault) {
@@ -1583,6 +1593,7 @@
     for (Supertype superclass in superclasses) {
       recordSupertype(superclass);
     }
+    // ignore: unnecessary_null_comparison
     if (interfaces != null) {
       for (Supertype superinterface in interfaces) {
         recordSupertype(superinterface);
@@ -1601,13 +1612,13 @@
     /// static members. If no interfaces are implemented by this class or its
     /// superclasses this is identical to [classMemberMap] and we do not store
     /// it in the [ClassHierarchyNode].
-    Map<Name, ClassMember> interfaceMemberMap = {};
+    Map<Name, ClassMember>? interfaceMemberMap = {};
 
     /// Setters inherited from interfaces. This contains no static setters. If
     /// no interfaces are implemented by this class or its superclasses this is
     /// identical to [classSetterMap] and we do not store it in the
     /// [ClassHierarchyNode].
-    Map<Name, ClassMember> interfaceSetterMap = {};
+    Map<Name, ClassMember>? interfaceSetterMap = {};
 
     /// Map for members declared in this class to the members that they
     /// override. This is used for checking valid overrides and to ensure that
@@ -1629,9 +1640,9 @@
     /// In case this class is concrete, this holds the interface members
     /// without a corresponding class member. These are either reported as
     /// missing implementations or trigger insertion of noSuchMethod forwarders.
-    List<ClassMember> abstractMembers = [];
+    List<ClassMember>? abstractMembers = [];
 
-    ClassHierarchyNodeDataForTesting dataForTesting;
+    ClassHierarchyNodeDataForTesting? dataForTesting;
     if (retainDataForTesting) {
       dataForTesting = new ClassHierarchyNodeDataForTesting(
           abstractMembers,
@@ -1711,13 +1722,14 @@
     /// `Interface.method` by being a valid override of it.
     void registerInheritedImplements(
         ClassMember inheritedMember, Set<ClassMember> overrides,
-        {ClassMember aliasForTesting}) {
+        {required ClassMember aliasForTesting}) {
       if (classBuilder is SourceClassBuilder) {
         assert(
             inheritedMember.classBuilder != classBuilder,
             "Only inherited members can implement by inheritance: "
             "${inheritedMember}");
         inheritedImplementsMap[inheritedMember] = overrides;
+        // ignore: unnecessary_null_comparison
         if (dataForTesting != null && aliasForTesting != null) {
           dataForTesting.aliasMap[aliasForTesting] = inheritedMember;
         }
@@ -1758,17 +1770,17 @@
       /// Conflicts between [definingGetable] and [definingSetable] are reported
       /// afterwards.
 
-      ClassMember definingGetable;
-      ClassMember definingSetable;
+      ClassMember? definingGetable;
+      ClassMember? definingSetable;
 
-      ClassMember declaredGetable = tuple.declaredMember;
+      ClassMember? declaredGetable = tuple.declaredMember;
       if (declaredGetable != null) {
         /// class Class {
         ///   method() {}
         /// }
         definingGetable = declaredGetable;
       }
-      ClassMember declaredSetable = tuple.declaredSetter;
+      ClassMember? declaredSetable = tuple.declaredSetter;
       if (declaredSetable != null) {
         /// class Class {
         ///   set setter(value) {}
@@ -1776,11 +1788,12 @@
         definingSetable = declaredSetable;
       }
 
-      ClassMember mixedInGetable;
-      if (tuple.mixedInMember != null &&
-          !tuple.mixedInMember.isStatic &&
-          !tuple.mixedInMember.isDuplicate &&
-          !tuple.mixedInMember.isSynthesized) {
+      ClassMember? mixedInGetable;
+      ClassMember? tupleMixedInMember = tuple.mixedInMember;
+      if (tupleMixedInMember != null &&
+          !tupleMixedInMember.isStatic &&
+          !tupleMixedInMember.isDuplicate &&
+          !tupleMixedInMember.isSynthesized) {
         /// We treat
         ///
         ///   opt-in:
@@ -1827,7 +1840,7 @@
           ///   method() {}
           /// }
           /// class Class with Mixin {}
-          definingGetable = mixedInGetable = tuple.mixedInMember;
+          definingGetable = mixedInGetable = tupleMixedInMember;
         } else if (!definingGetable.isDuplicate) {
           // This case is currently unreachable from source code since classes
           // cannot both declare and mix in members. From dill, this can occur
@@ -1835,18 +1848,19 @@
           //
           // The case is handled for consistency.
           if (definingGetable.isStatic ||
-              definingGetable.isProperty != tuple.mixedInMember.isProperty) {
-            reportInheritanceConflict(definingGetable, tuple.mixedInMember);
+              definingGetable.isProperty != tupleMixedInMember.isProperty) {
+            reportInheritanceConflict(definingGetable, tupleMixedInMember);
           } else {
-            mixedInGetable = tuple.mixedInMember;
+            mixedInGetable = tupleMixedInMember;
           }
         }
       }
-      ClassMember mixedInSetable;
-      if (tuple.mixedInSetter != null &&
-          !tuple.mixedInSetter.isStatic &&
-          !tuple.mixedInSetter.isDuplicate &&
-          !tuple.mixedInSetter.isSynthesized) {
+      ClassMember? mixedInSetable;
+      ClassMember? tupleMixedInSetter = tuple.mixedInSetter;
+      if (tupleMixedInSetter != null &&
+          !tupleMixedInSetter.isStatic &&
+          !tupleMixedInSetter.isDuplicate &&
+          !tupleMixedInSetter.isSynthesized) {
         /// We treat
         ///
         ///   class Mixin {
@@ -1888,21 +1902,22 @@
           ///   set setter(value) {}
           /// }
           /// class Class with Mixin {}
-          definingSetable = mixedInSetable = tuple.mixedInSetter;
+          definingSetable = mixedInSetable = tupleMixedInSetter;
         } else if (!definingSetable.isDuplicate) {
           if (definingSetable.isStatic ||
-              definingSetable.isProperty != tuple.mixedInSetter.isProperty) {
-            reportInheritanceConflict(definingGetable, tuple.mixedInSetter);
+              definingSetable.isProperty != tupleMixedInSetter.isProperty) {
+            reportInheritanceConflict(definingSetable, tupleMixedInSetter);
           } else {
-            mixedInSetable = tuple.mixedInSetter;
+            mixedInSetable = tupleMixedInSetter;
           }
         }
       }
 
-      ClassMember extendedGetable;
-      if (tuple.extendedMember != null &&
-          !tuple.extendedMember.isStatic &&
-          !tuple.extendedMember.isDuplicate) {
+      ClassMember? extendedGetable;
+      ClassMember? tupleExtendedMember = tuple.extendedMember;
+      if (tupleExtendedMember != null &&
+          !tupleExtendedMember.isStatic &&
+          !tupleExtendedMember.isDuplicate) {
         /// We treat
         ///
         ///   class Super {
@@ -1922,10 +1937,10 @@
           ///   method() {}
           /// }
           /// class Class extends Super {}
-          definingGetable = extendedGetable = tuple.extendedMember;
+          definingGetable = extendedGetable = tupleExtendedMember;
         } else if (!definingGetable.isDuplicate) {
           if (definingGetable.isStatic ||
-              definingGetable.isProperty != tuple.extendedMember.isProperty) {
+              definingGetable.isProperty != tupleExtendedMember.isProperty) {
             ///   class Super {
             ///     method() {}
             ///   }
@@ -1941,16 +1956,17 @@
             ///   class Class extends Super {
             ///     get getter => 0;
             ///   }
-            reportInheritanceConflict(definingGetable, tuple.extendedMember);
+            reportInheritanceConflict(definingGetable, tupleExtendedMember);
           } else {
-            extendedGetable = tuple.extendedMember;
+            extendedGetable = tupleExtendedMember;
           }
         }
       }
-      ClassMember extendedSetable;
-      if (tuple.extendedSetter != null &&
-          !tuple.extendedSetter.isStatic &&
-          !tuple.extendedSetter.isDuplicate) {
+      ClassMember? extendedSetable;
+      ClassMember? tupleExtendedSetter = tuple.extendedSetter;
+      if (tupleExtendedSetter != null &&
+          !tupleExtendedSetter.isStatic &&
+          !tupleExtendedSetter.isDuplicate) {
         /// We treat
         ///
         ///   class Super {
@@ -1970,13 +1986,13 @@
           ///   set setter(value) {}
           /// }
           /// class Class extends Super {}
-          definingSetable = extendedSetable = tuple.extendedSetter;
+          definingSetable = extendedSetable = tupleExtendedSetter;
         } else if (!definingSetable.isDuplicate) {
           if (definingSetable.isStatic ||
-              definingSetable.isProperty != tuple.extendedSetter.isProperty) {
-            reportInheritanceConflict(definingSetable, tuple.extendedSetter);
+              definingSetable.isProperty != tupleExtendedSetter.isProperty) {
+            reportInheritanceConflict(definingSetable, tupleExtendedSetter);
           } else {
-            extendedSetable = tuple.extendedSetter;
+            extendedSetable = tupleExtendedSetter;
           }
         }
       }
@@ -1984,12 +2000,13 @@
       // TODO(johnniwinther): Remove extended and mixed in members/setters
       // from implemented members/setters. Mixin applications always implement
       // the mixin class leading to unnecessary interface members.
-      List<ClassMember> implementedGetables;
-      if (tuple.implementedMembers != null &&
+      List<ClassMember>? implementedGetables;
+      List<ClassMember>? tupleImplementedMembers = tuple.implementedMembers;
+      if (tupleImplementedMembers != null &&
           // Skip implemented members if we already have a duplicate.
           !(definingGetable != null && definingGetable.isDuplicate)) {
-        for (int i = 0; i < tuple.implementedMembers.length; i++) {
-          ClassMember implementedGetable = tuple.implementedMembers[i];
+        for (int i = 0; i < tupleImplementedMembers.length; i++) {
+          ClassMember? implementedGetable = tupleImplementedMembers[i];
           if (implementedGetable.isStatic || implementedGetable.isDuplicate) {
             /// We treat
             ///
@@ -2036,7 +2053,7 @@
           }
           if (implementedGetable == null) {
             // On the first skipped member we add all previous.
-            implementedGetables ??= tuple.implementedMembers.take(i).toList();
+            implementedGetables ??= tupleImplementedMembers.take(i).toList();
           } else if (implementedGetables != null) {
             // If already skipping members we add [implementedGetable]
             // explicitly.
@@ -2045,19 +2062,20 @@
         }
         if (implementedGetables == null) {
           // No members were skipped so we use the full list.
-          implementedGetables = tuple.implementedMembers;
+          implementedGetables = tupleImplementedMembers;
         } else if (implementedGetables.isEmpty) {
           // No members were included.
           implementedGetables = null;
         }
       }
 
-      List<ClassMember> implementedSetables;
-      if (tuple.implementedSetters != null &&
+      List<ClassMember>? implementedSetables;
+      List<ClassMember>? tupleImplementedSetters = tuple.implementedSetters;
+      if (tupleImplementedSetters != null &&
           // Skip implemented setters if we already have a duplicate.
           !(definingSetable != null && definingSetable.isDuplicate)) {
-        for (int i = 0; i < tuple.implementedSetters.length; i++) {
-          ClassMember implementedSetable = tuple.implementedSetters[i];
+        for (int i = 0; i < tupleImplementedSetters.length; i++) {
+          ClassMember? implementedSetable = tupleImplementedSetters[i];
           if (implementedSetable.isStatic || implementedSetable.isDuplicate) {
             /// We treat
             ///
@@ -2095,7 +2113,7 @@
           }
           if (implementedSetable == null) {
             // On the first skipped setter we add all previous.
-            implementedSetables ??= tuple.implementedSetters.take(i).toList();
+            implementedSetables ??= tupleImplementedSetters.take(i).toList();
           } else if (implementedSetables != null) {
             // If already skipping setters we add [implementedSetable]
             // explicitly.
@@ -2104,7 +2122,7 @@
         }
         if (implementedSetables == null) {
           // No setters were skipped so we use the full list.
-          implementedSetables = tuple.implementedSetters;
+          implementedSetables = tupleImplementedSetters;
         } else if (implementedSetables.isEmpty) {
           // No setters were included.
           implementedSetables = null;
@@ -2136,13 +2154,13 @@
 
       /// Declared methods, getters and setters registered in
       /// [registerDeclaredOverride].
-      ClassMember declaredMethod;
-      List<ClassMember> declaredProperties;
+      ClassMember? declaredMethod;
+      List<ClassMember>? declaredProperties;
 
       /// Declared methods, getters and setters registered in
       /// [registerDeclaredOverride].
-      ClassMember mixedInMethod;
-      List<ClassMember> mixedInProperties;
+      ClassMember? mixedInMethod;
+      List<ClassMember>? mixedInProperties;
 
       /// Registers that [declaredMember] overrides extended and implemented
       /// members.
@@ -2166,7 +2184,7 @@
       /// Here the parameter type of the setter `Class.property` must be
       /// inferred from the type of the getter `Super.property`.
       void registerDeclaredOverride(ClassMember declaredMember,
-          {ClassMember aliasForTesting}) {
+          {ClassMember? aliasForTesting}) {
         if (classBuilder is SourceClassBuilder && !declaredMember.isStatic) {
           assert(
               declaredMember.isSourceDeclaration &&
@@ -2175,7 +2193,7 @@
           hasDeclaredMembers = true;
           if (declaredMember.isProperty) {
             declaredProperties ??= [];
-            declaredProperties.add(declaredMember);
+            declaredProperties!.add(declaredMember);
           } else {
             assert(
                 declaredMethod == null,
@@ -2213,14 +2231,14 @@
       /// inferred from the type of the getter `Super.property`, but should
       /// instead default to `dynamic`.
       void registerMixedInOverride(ClassMember mixedInMember,
-          {ClassMember aliasForTesting}) {
+          {ClassMember? aliasForTesting}) {
         assert(mixedInMember.classBuilder != classBuilder,
             "Only mixin members can override by application: ${mixedInMember}");
         if (classBuilder is SourceClassBuilder) {
           hasDeclaredMembers = true;
           if (mixedInMember.isProperty) {
             mixedInProperties ??= [];
-            mixedInProperties.add(mixedInMember);
+            mixedInProperties!.add(mixedInMember);
           } else {
             assert(
                 mixedInMethod == null,
@@ -2248,16 +2266,16 @@
       ///
       /// The computed class and interface members are added to [classMemberMap]
       /// and [interfaceMemberMap], respectively.
-      ClassMember computeMembers(
-          {ClassMember definingMember,
-          ClassMember declaredMember,
-          ClassMember mixedInMember,
-          ClassMember extendedMember,
-          List<ClassMember> implementedMembers,
-          Map<Name, ClassMember> classMemberMap,
-          Map<Name, ClassMember> interfaceMemberMap}) {
-        ClassMember classMember;
-        ClassMember interfaceMember;
+      ClassMember? computeMembers(
+          {required ClassMember definingMember,
+          required ClassMember? declaredMember,
+          required ClassMember? mixedInMember,
+          required ClassMember? extendedMember,
+          required List<ClassMember>? implementedMembers,
+          required Map<Name, ClassMember> classMemberMap,
+          required Map<Name, ClassMember>? interfaceMemberMap}) {
+        ClassMember? classMember;
+        ClassMember? interfaceMember;
 
         if (mixedInMember != null) {
           if (mixedInMember.isAbstract) {
@@ -2852,12 +2870,12 @@
           interfaceMember ??= classMember.interfaceMember;
         }
         if (interfaceMember != null) {
-          interfaceMemberMap[name] = interfaceMember;
+          interfaceMemberMap![name] = interfaceMember;
         }
         return interfaceMember;
       }
 
-      ClassMember interfaceGetable;
+      ClassMember? interfaceGetable;
       if (definingGetable != null) {
         interfaceGetable = computeMembers(
             definingMember: definingGetable,
@@ -2868,7 +2886,7 @@
             classMemberMap: classMemberMap,
             interfaceMemberMap: interfaceMemberMap);
       }
-      ClassMember interfaceSetable;
+      ClassMember? interfaceSetable;
       if (definingSetable != null) {
         interfaceSetable = computeMembers(
             definingMember: definingSetable,
@@ -2908,7 +2926,9 @@
           /// `Super.property2` is _not_ a subtype of the setter
           /// `Mixin.property1`.
           hierarchy.registerGetterSetterCheck(
-              classBuilder, interfaceGetable, interfaceSetable);
+              classBuilder as SourceClassBuilder,
+              interfaceGetable,
+              interfaceSetable);
         }
       }
       if (hasDeclaredMembers) {
@@ -2966,7 +2986,7 @@
             ///    class Class extends Super {
             ///      method() {}
             ///    }
-            declaredOverridesMap[declaredMethod] = getableOverrides;
+            declaredOverridesMap[declaredMethod!] = getableOverrides;
           }
           if (declaredProperties != null) {
             Set<ClassMember> overrides;
@@ -2990,7 +3010,7 @@
               overrides = {...getableOverrides, ...setableOverrides};
             }
             if (overrides.isNotEmpty) {
-              for (ClassMember declaredMember in declaredProperties) {
+              for (ClassMember declaredMember in declaredProperties!) {
                 declaredOverridesMap[declaredMember] = overrides;
               }
             }
@@ -3003,7 +3023,7 @@
             ///      method() {}
             ///    }
             ///    class Class = Super with Mixin;
-            mixinApplicationOverridesMap[mixedInMethod] = getableOverrides;
+            mixinApplicationOverridesMap[mixedInMethod!] = getableOverrides;
           }
           if (mixedInProperties != null) {
             Set<ClassMember> overrides;
@@ -3026,7 +3046,7 @@
               overrides = {...getableOverrides, ...setableOverrides};
             }
             if (overrides.isNotEmpty) {
-              for (ClassMember mixedInMember in mixedInProperties) {
+              for (ClassMember mixedInMember in mixedInProperties!) {
                 mixinApplicationOverridesMap[mixedInMember] = overrides;
               }
             }
@@ -3067,7 +3087,7 @@
         /// Declared members must be checked to validly override the the
         /// overridden members.
         hierarchy.registerOverrideCheck(
-            classBuilder, classMember, overriddenMembers);
+            classBuilder as SourceClassBuilder, classMember, overriddenMembers);
       });
 
       mixinApplicationOverridesMap.forEach(
@@ -3075,7 +3095,7 @@
         /// Declared mixed in members must be checked to validly override the
         /// overridden members.
         hierarchy.registerOverrideCheck(
-            classBuilder, classMember, overriddenMembers);
+            classBuilder as SourceClassBuilder, classMember, overriddenMembers);
       });
 
       inheritedImplementsMap.forEach(
@@ -3083,7 +3103,7 @@
         /// Concrete members must be checked to validly override the overridden
         /// members in concrete classes.
         hierarchy.registerOverrideCheck(
-            classBuilder, classMember, overriddenMembers);
+            classBuilder as SourceClassBuilder, classMember, overriddenMembers);
       });
     }
 
@@ -3100,18 +3120,19 @@
           "$classSetterMap, interface setters: $interfaceSetterMap.");
       assert(
           classMemberMap.keys.every((Name name) =>
-              identical(classMemberMap[name], interfaceMemberMap[name])),
+              identical(classMemberMap[name], interfaceMemberMap?[name])),
           "Class/interface member mismatch. Class members: "
           "$classMemberMap, interface members: $interfaceMemberMap.");
       assert(
           classSetterMap.keys.every((Name name) =>
-              identical(classSetterMap[name], interfaceSetterMap[name])),
+              identical(classSetterMap[name], interfaceSetterMap?[name])),
           "Class/interface setter mismatch. Class setters: "
           "$classSetterMap, interface setters: $interfaceSetterMap.");
       interfaceMemberMap = null;
       interfaceSetterMap = null;
     }
 
+    // ignore: unnecessary_null_comparison
     if (abstractMembers != null && !classBuilder.isAbstract) {
       if (!hasNoSuchMethod) {
         reportMissingMembers(abstractMembers);
@@ -3143,9 +3164,9 @@
     } else {
       List<DartType> arguments = supertype.typeArguments;
       List<DartType> typeArguments =
-          new List<DartType>.filled(arguments.length, null);
+          new List<DartType>.filled(arguments.length, dummyDartType);
       List<TypeParameter> typeParameters =
-          new List<TypeParameter>.filled(arguments.length, null);
+          new List<TypeParameter>.filled(arguments.length, dummyTypeParameter);
       for (int i = 0; i < arguments.length; i++) {
         typeParameters[i] = supertypeTypeParameters[i];
         typeArguments[i] = arguments[i];
@@ -3170,7 +3191,7 @@
       map[typeVariables[i]] = arguments[i];
     }
     Substitution substitution = Substitution.fromMap(map);
-    List<Supertype> result;
+    List<Supertype>? result;
     for (int i = 0; i < supertypes.length; i++) {
       Supertype supertype = supertypes[i];
       Supertype substituted = substitution.substituteSupertype(supertype);
@@ -3189,15 +3210,17 @@
 
   void addInterface(List<Supertype> interfaces, List<Supertype> superclasses,
       Supertype type) {
+    // ignore: unnecessary_null_comparison
     if (type == null) return null;
     if (!classBuilder.library.isNonNullableByDefault) {
       type = legacyErasureSupertype(type);
     }
     ClassHierarchyNode node = hierarchy.getNodeFromClass(type.classNode);
+    // ignore: unnecessary_null_comparison
     if (node == null) return null;
     int depth = node.depth;
     int myDepth = superclasses.length;
-    Supertype superclass = depth < myDepth ? superclasses[depth] : null;
+    Supertype? superclass = depth < myDepth ? superclasses[depth] : null;
     if (superclass != null && superclass.classNode == type.classNode) {
       // This is a potential conflict.
       if (classBuilder.library.isNonNullableByDefault) {
@@ -3219,7 +3242,7 @@
       for (int i = 0; i < interfaces.length; i++) {
         // This is a quadratic algorithm, but normally, the number of
         // interfaces is really small.
-        Supertype interface = interfaces[i];
+        Supertype? interface = interfaces[i];
         if (interface.classNode == type.classNode) {
           // This is a potential conflict.
           if (classBuilder.library.isNonNullableByDefault) {
@@ -3248,7 +3271,7 @@
     for (ClassMember declaration in unfoldDeclarations(abstractMembers)) {
       if (isNameVisibleIn(declaration.name, classBuilder.library)) {
         String name = declaration.fullNameForErrors;
-        String className = declaration.classBuilder?.fullNameForErrors;
+        String className = declaration.classBuilder.fullNameForErrors;
         String displayName =
             declaration.isSetter ? "$className.$name=" : "$className.$name";
         contextMap[displayName] = templateMissingImplementationCause
@@ -3261,7 +3284,7 @@
     List<String> names = new List<String>.from(contextMap.keys)..sort();
     List<LocatedMessage> context = <LocatedMessage>[];
     for (int i = 0; i < names.length; i++) {
-      context.add(contextMap[names[i]]);
+      context.add(contextMap[names[i]]!);
     }
     classBuilder.addProblem(
         templateMissingImplementationNotAbstract.withArguments(
@@ -3277,7 +3300,7 @@
 
   void inferMixinApplication() {
     Class cls = classBuilder.cls;
-    Supertype mixedInType = cls.mixedInType;
+    Supertype? mixedInType = cls.mixedInType;
     if (mixedInType == null) return;
     List<DartType> typeArguments = mixedInType.typeArguments;
     if (typeArguments.isEmpty || typeArguments.first is! UnknownType) return;
@@ -3287,22 +3310,21 @@
             new TypeBuilderConstraintGatherer(hierarchy,
                 mixedInType.classNode.typeParameters, cls.enclosingLibrary))
         .infer(cls);
-    List<TypeBuilder> inferredArguments =
-        new List<TypeBuilder>.filled(typeArguments.length, null);
-    for (int i = 0; i < typeArguments.length; i++) {
-      inferredArguments[i] =
-          hierarchy.loader.computeTypeBuilder(typeArguments[i]);
-    }
-    NamedTypeBuilder mixedInTypeBuilder = classBuilder.mixedInTypeBuilder;
+    List<TypeBuilder> inferredArguments = new List<TypeBuilder>.generate(
+        typeArguments.length,
+        (int i) => hierarchy.loader.computeTypeBuilder(typeArguments[i]),
+        growable: false);
+    NamedTypeBuilder mixedInTypeBuilder =
+        classBuilder.mixedInTypeBuilder as NamedTypeBuilder;
     mixedInTypeBuilder.arguments = inferredArguments;
   }
 
   /// The class Function from dart:core is supposed to be ignored when used as
   /// an interface.
-  List<TypeBuilder> ignoreFunction(List<TypeBuilder> interfaces) {
+  List<TypeBuilder>? ignoreFunction(List<TypeBuilder>? interfaces) {
     if (interfaces == null) return null;
-    for (int i = 0; i < interfaces.length; i++) {
-      ClassBuilder classBuilder = getClass(interfaces[i]);
+    for (int i = 0; i < interfaces!.length; i++) {
+      ClassBuilder? classBuilder = getClass(interfaces[i]);
       if (classBuilder != null && classBuilder.cls == hierarchy.functionClass) {
         if (interfaces.length == 1) {
           return null;
@@ -3335,12 +3357,12 @@
   /// from interfaces.
   ///
   /// This may be null, in which case [classMembers] is the interface members.
-  final Map<Name, ClassMember> interfaceMemberMap;
+  final Map<Name, ClassMember>? interfaceMemberMap;
 
   /// Similar to [interfaceMembers] but for setters.
   ///
   /// This may be null, in which case [classSetters] is the interface setters.
-  final Map<Name, ClassMember> interfaceSetterMap;
+  final Map<Name, ClassMember>? interfaceSetterMap;
 
   /// All superclasses of [classBuilder] excluding itself. The classes are
   /// sorted by depth from the root (Object) in ascending order.
@@ -3357,7 +3379,7 @@
 
   final bool hasNoSuchMethod;
 
-  final ClassHierarchyNodeDataForTesting dataForTesting;
+  final ClassHierarchyNodeDataForTesting? dataForTesting;
 
   ClassHierarchyNode(
       this.classBuilder,
@@ -3374,18 +3396,17 @@
   /// Returns a list of all supertypes of [classBuilder], including this node.
   List<ClassHierarchyNode> computeAllSuperNodes(
       ClassHierarchyBuilder hierarchy) {
-    List<ClassHierarchyNode> result = new List<ClassHierarchyNode>.filled(
-        1 + superclasses.length + interfaces.length, null);
+    List<ClassHierarchyNode> result = [];
     for (int i = 0; i < superclasses.length; i++) {
       Supertype type = superclasses[i];
-      result[i] = hierarchy.getNodeFromClass(type.classNode);
+      result.add(hierarchy.getNodeFromClass(type.classNode));
     }
     for (int i = 0; i < interfaces.length; i++) {
       Supertype type = interfaces[i];
-      result[i + superclasses.length] =
-          hierarchy.getNodeFromClass(type.classNode);
+      result.add(hierarchy.getNodeFromClass(type.classNode));
     }
-    return result..last = this;
+    result.add(this);
+    return result;
   }
 
   String toString() {
@@ -3407,6 +3428,7 @@
       sb.writeln();
       depth++;
     }
+    // ignore: unnecessary_null_comparison
     if (interfaces != null) {
       sb.write("  interfaces:");
       bool first = true;
@@ -3421,10 +3443,10 @@
     printMemberMap(classMemberMap, sb, "classMembers");
     printMemberMap(classSetterMap, sb, "classSetters");
     if (interfaceMemberMap != null) {
-      printMemberMap(interfaceMemberMap, sb, "interfaceMembers");
+      printMemberMap(interfaceMemberMap!, sb, "interfaceMembers");
     }
     if (interfaceSetterMap != null) {
-      printMemberMap(interfaceSetterMap, sb, "interfaceSetters");
+      printMemberMap(interfaceSetterMap!, sb, "interfaceSetters");
     }
     return "$sb";
   }
@@ -3451,13 +3473,13 @@
     printMembers(members, sb, heading);
   }
 
-  ClassMember getInterfaceMember(Name name, bool isSetter) {
+  ClassMember? getInterfaceMember(Name name, bool isSetter) {
     return isSetter
         ? (interfaceSetterMap ?? classSetterMap)[name]
         : (interfaceMemberMap ?? classMemberMap)[name];
   }
 
-  ClassMember findMember(Name name, List<ClassMember> declarations) {
+  ClassMember? findMember(Name name, List<ClassMember> declarations) {
     // TODO(ahe): Consider creating a map or scope. The obvious choice would be
     // to use scopes, but they don't handle private names correctly.
 
@@ -3481,7 +3503,7 @@
     return null;
   }
 
-  ClassMember getDispatchTarget(Name name, bool isSetter) {
+  ClassMember? getDispatchTarget(Name name, bool isSetter) {
     return isSetter ? classSetterMap[name] : classMemberMap[name];
   }
 
@@ -3533,8 +3555,8 @@
       this.cls, CoreTypes coreTypes, TypeBuilderConstraintGatherer gatherer)
       : super(coreTypes, gatherer);
 
-  Supertype asInstantiationOf(Supertype type, Class superclass) {
-    List<DartType> arguments =
+  Supertype? asInstantiationOf(Supertype type, Class superclass) {
+    List<DartType>? arguments =
         gatherer.getTypeArgumentsAsInstanceOf(type.asInterfaceType, superclass);
     if (arguments == null) return null;
     return new Supertype(superclass, arguments);
@@ -3572,7 +3594,7 @@
   }
 
   @override
-  Member getInterfaceMember(Class class_, Name name, {bool setter: false}) {
+  Member? getInterfaceMember(Class class_, Name name, {bool setter: false}) {
     return null;
   }
 
@@ -3583,7 +3605,7 @@
   }
 
   @override
-  List<DartType> getTypeArgumentsAsInstanceOf(
+  List<DartType>? getTypeArgumentsAsInstanceOf(
       InterfaceType type, Class superclass) {
     return hierarchy.getTypeArgumentsAsInstanceOf(type, superclass);
   }
@@ -3651,7 +3673,7 @@
     ///    }
     ///
     bool declaredNeedsLegacyErasure =
-        needsLegacyErasure(_classBuilder.cls, declaredMember.enclosingClass);
+        needsLegacyErasure(_classBuilder.cls, declaredMember.enclosingClass!);
     void callback(Member interfaceMember, bool isSetter) {
       _classBuilder.checkOverride(
           hierarchy.types, declaredMember, interfaceMember, isSetter, callback,
@@ -3712,7 +3734,7 @@
 }
 
 int compareNamedParameters(VariableDeclaration a, VariableDeclaration b) {
-  return a.name.compareTo(b.name);
+  return a.name!.compareTo(b.name!);
 }
 
 void reportCantInferParameterType(
@@ -3849,11 +3871,11 @@
       context: context);
 }
 
-ClassBuilder getClass(TypeBuilder type) {
-  Builder declaration = type.declaration;
+ClassBuilder? getClass(TypeBuilder type) {
+  Builder? declaration = type.declaration;
   if (declaration is TypeAliasBuilder) {
     TypeAliasBuilder aliasBuilder = declaration;
-    NamedTypeBuilder namedBuilder = type;
+    NamedTypeBuilder namedBuilder = type as NamedTypeBuilder;
     declaration = aliasBuilder.unaliasDeclaration(namedBuilder.arguments);
   }
   return declaration is ClassBuilder ? declaration : null;
@@ -3908,8 +3930,10 @@
   final bool isProperty;
 
   SynthesizedMember(this.classBuilder, this.name,
-      {this.forSetter, this.isProperty})
+      {required this.forSetter, required this.isProperty})
+      // ignore: unnecessary_null_comparison
       : assert(forSetter != null),
+        // ignore: unnecessary_null_comparison
         assert(isProperty != null);
 
   @override
@@ -3980,7 +4004,7 @@
   ///      // Concrete forwarding stub calling [_superClassMember]:
   ///      method(covariant int i) => super.method(i);
   ///
-  final ClassMember _superClassMember;
+  final ClassMember? _superClassMember;
 
   /// The canonical member of the combined member signature if it is known by
   /// construction. The canonical member defines the type of combined member
@@ -4001,7 +4025,7 @@
   ///       //    method(covariant int i) => super.method(i);
   ///       method(int i);
   ///     }
-  final ClassMember _canonicalMember;
+  final ClassMember? _canonicalMember;
 
   /// The member in [declarations] that is mixed in, if any.
   ///
@@ -4046,22 +4070,22 @@
   ///    //   void method(covariant int i) => super.method(i);
   ///    class Class = Super with Mixin implements Interface;
   ///
-  final ClassMember _mixedInMember;
+  final ClassMember? _mixedInMember;
 
   /// If `true`, a stub should be inserted, if needed.
   final bool _shouldModifyKernel;
 
-  Member _member;
-  Covariance _covariance;
+  Member? _member;
+  Covariance? _covariance;
 
   SynthesizedInterfaceMember(
       ClassBuilder classBuilder, Name name, this.declarations,
-      {ClassMember superClassMember,
-      ClassMember canonicalMember,
-      ClassMember mixedInMember,
-      bool isProperty,
-      bool forSetter,
-      bool shouldModifyKernel})
+      {ClassMember? superClassMember,
+      ClassMember? canonicalMember,
+      ClassMember? mixedInMember,
+      required bool isProperty,
+      required bool forSetter,
+      required bool shouldModifyKernel})
       : this._superClassMember = superClassMember,
         this._canonicalMember = canonicalMember,
         this._mixedInMember = mixedInMember,
@@ -4077,8 +4101,8 @@
     }
     if (classBuilder.library is! SourceLibraryBuilder) {
       if (_canonicalMember != null) {
-        _member = _canonicalMember.getMember(hierarchy);
-        _covariance = _canonicalMember.getCovariance(hierarchy);
+        _member = _canonicalMember!.getMember(hierarchy);
+        _covariance = _canonicalMember!.getCovariance(hierarchy);
       } else {
         _member = declarations.first.getMember(hierarchy);
         _covariance = declarations.first.getCovariance(hierarchy);
@@ -4089,13 +4113,13 @@
     if (_canonicalMember != null) {
       combinedMemberSignature = new CombinedClassMemberSignature.internal(
           hierarchy,
-          classBuilder,
-          declarations.indexOf(_canonicalMember),
+          classBuilder as SourceClassBuilder,
+          declarations.indexOf(_canonicalMember!),
           declarations,
           forSetter: isSetter);
     } else {
       combinedMemberSignature = new CombinedClassMemberSignature(
-          hierarchy, classBuilder, declarations,
+          hierarchy, classBuilder as SourceClassBuilder, declarations,
           forSetter: isSetter);
 
       if (combinedMemberSignature.canonicalMember == null) {
@@ -4125,22 +4149,23 @@
     if (_shouldModifyKernel) {
       ProcedureKind kind = ProcedureKind.Method;
       Member canonicalMember =
-          combinedMemberSignature.canonicalMember.getMember(hierarchy);
-      if (combinedMemberSignature.canonicalMember.isProperty) {
+          combinedMemberSignature.canonicalMember!.getMember(hierarchy);
+      if (combinedMemberSignature.canonicalMember!.isProperty) {
         kind = isSetter ? ProcedureKind.Setter : ProcedureKind.Getter;
       } else if (canonicalMember is Procedure &&
           canonicalMember.kind == ProcedureKind.Operator) {
         kind = ProcedureKind.Operator;
       }
 
-      Procedure stub = new ForwardingNode(
+      Procedure? stub = new ForwardingNode(
               combinedMemberSignature, kind, _superClassMember, _mixedInMember)
           .finalize();
       if (stub != null) {
         assert(classBuilder.cls == stub.enclosingClass);
         assert(stub != canonicalMember);
         classBuilder.cls.addProcedure(stub);
-        SourceLibraryBuilder library = classBuilder.library;
+        SourceLibraryBuilder library =
+            classBuilder.library as SourceLibraryBuilder;
         if (canonicalMember is Procedure) {
           library.forwardersOrigins..add(stub)..add(canonicalMember);
         }
@@ -4148,28 +4173,28 @@
         _covariance = combinedMemberSignature.combinedMemberSignatureCovariance;
         assert(
             _covariance ==
-                new Covariance.fromMember(_member, forSetter: forSetter),
+                new Covariance.fromMember(_member!, forSetter: forSetter),
             "Unexpected covariance for combined members signature "
             "$_member. Found $_covariance, expected "
-            "${new Covariance.fromMember(_member, forSetter: forSetter)}.");
+            "${new Covariance.fromMember(_member!, forSetter: forSetter)}.");
         return;
       }
     }
 
-    _member = combinedMemberSignature.canonicalMember.getMember(hierarchy);
+    _member = combinedMemberSignature.canonicalMember!.getMember(hierarchy);
     _covariance = combinedMemberSignature.combinedMemberSignatureCovariance;
   }
 
   @override
   Member getMember(ClassHierarchyBuilder hierarchy) {
     _ensureMemberAndCovariance(hierarchy);
-    return _member;
+    return _member!;
   }
 
   @override
   Covariance getCovariance(ClassHierarchyBuilder hierarchy) {
     _ensureMemberAndCovariance(hierarchy);
-    return _covariance;
+    return _covariance!;
   }
 
   @override
@@ -4241,15 +4266,17 @@
   final ClassMember inheritedClassMember;
   final ClassMember implementedInterfaceMember;
 
-  Member _member;
-  Covariance _covariance;
+  Member? _member;
+  Covariance? _covariance;
 
   InheritedClassMemberImplementsInterface(ClassBuilder classBuilder, Name name,
-      {this.inheritedClassMember,
-      this.implementedInterfaceMember,
-      bool isProperty,
-      bool forSetter})
+      {required this.inheritedClassMember,
+      required this.implementedInterfaceMember,
+      required bool isProperty,
+      required bool forSetter})
+      // ignore: unnecessary_null_comparison
       : assert(inheritedClassMember != null),
+        // ignore: unnecessary_null_comparison
         assert(implementedInterfaceMember != null),
         super(classBuilder, name, isProperty: isProperty, forSetter: forSetter);
 
@@ -4308,13 +4335,13 @@
   @override
   Member getMember(ClassHierarchyBuilder hierarchy) {
     _ensureMemberAndCovariance(hierarchy);
-    return _member;
+    return _member!;
   }
 
   @override
   Covariance getCovariance(ClassHierarchyBuilder hierarchy) {
     _ensureMemberAndCovariance(hierarchy);
-    return _covariance;
+    return _covariance!;
   }
 
   @override
diff --git a/pkg/front_end/lib/src/fasta/kernel/collections.dart b/pkg/front_end/lib/src/fasta/kernel/collections.dart
index 29984f2..f5e8c18 100644
--- a/pkg/front_end/lib/src/fasta/kernel/collections.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/collections.dart
@@ -778,7 +778,7 @@
 /// [onConvertMapEntry] is called when a [ForMapEntry], [ForInMapEntry], or
 /// [IfMapEntry] is converted to a [ForElement], [ForInElement], or [IfElement],
 /// respectively.
-Expression convertToElement(MapLiteralEntry entry, InferenceHelper helper,
+Expression convertToElement(MapLiteralEntry entry, InferenceHelper? helper,
     void onConvertMapEntry(TreeNode from, TreeNode to)) {
   if (entry is SpreadMapEntry) {
     return new SpreadElement(entry.expression, isNullAware: entry.isNullAware)
@@ -823,7 +823,9 @@
       return key;
     }
   }
-  return helper.buildProblem(
+  // TODO(johnniwinther): How can this be triggered? This will fail if
+  // encountered in top level inference.
+  return helper!.buildProblem(
     templateExpectedButGot.withArguments(','),
     entry.fileOffset,
     1,
diff --git a/pkg/front_end/lib/src/fasta/kernel/combined_member_signature.dart b/pkg/front_end/lib/src/fasta/kernel/combined_member_signature.dart
index d3c6b5a..15b0460 100644
--- a/pkg/front_end/lib/src/fasta/kernel/combined_member_signature.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/combined_member_signature.dart
@@ -2,8 +2,6 @@
 // for 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 'package:kernel/ast.dart';
 
 import 'package:kernel/class_hierarchy.dart' show ClassHierarchyBase;
@@ -58,21 +56,21 @@
   /// For the nnbd computation, this is one of the members whose type define
   /// the combined member signature, and the indices of the remaining members
   /// are stored in [_mutualSubtypes].
-  int _canonicalMemberIndex;
+  int? _canonicalMemberIndex;
 
   /// For the nnbd computation, this maps each distinct but most specific member
   /// type to the index of one of the [members] with that type.
   ///
   /// If there is only one most specific member type, this is `null`.
-  Map<DartType, int> _mutualSubtypes;
+  Map<DartType, int>? _mutualSubtypes;
 
   /// Cache for the types of [members] as inherited into [classBuilder].
-  List<DartType> _memberTypes;
+  List<DartType?>? _memberTypes;
 
-  List<Covariance> _memberCovariances;
+  List<Covariance?>? _memberCovariances;
 
   /// Cache for the this type of [classBuilder].
-  DartType _thisType;
+  InterfaceType? _thisType;
 
   /// If `true` the combined member signature type has been computed.
   ///
@@ -83,13 +81,13 @@
   /// Cache the computed combined member signature type.
   ///
   /// If the combined member signature type is undefined this is set to `null`.
-  DartType _combinedMemberSignatureType;
+  DartType? _combinedMemberSignatureType;
 
   /// The indices for the members whose type needed legacy erasure.
   ///
   /// This is fully computed when [combinedMemberSignatureType] has been
   /// computed.
-  Set<int> _neededLegacyErasureIndices;
+  Set<int>? _neededLegacyErasureIndices;
 
   bool _neededNnbdTopMerge = false;
 
@@ -99,12 +97,13 @@
 
   bool _isCombinedMemberSignatureCovarianceComputed = false;
 
-  Covariance _combinedMemberSignatureCovariance;
+  Covariance? _combinedMemberSignatureCovariance;
 
   /// Creates a [CombinedClassMemberSignature] whose canonical member is already
   /// defined.
   CombinedMemberSignatureBase.internal(
       this.classBuilder, this._canonicalMemberIndex, this.forSetter)
+      // ignore: unnecessary_null_comparison
       : assert(forSetter != null);
 
   /// Creates a [CombinedClassMemberSignature] for [members] inherited into
@@ -113,15 +112,16 @@
   /// If [forSetter] is `true`, contravariance of the setter types is used to
   /// compute the most specific member type. Otherwise covariance of the getter
   /// types or function types is used.
-  CombinedMemberSignatureBase(this.classBuilder, {this.forSetter}) {
+  CombinedMemberSignatureBase(this.classBuilder, {required this.forSetter}) {
+    // ignore: unnecessary_null_comparison
     assert(forSetter != null);
-    int bestSoFarIndex;
+    int? bestSoFarIndex;
     if (members.length == 1) {
       bestSoFarIndex = 0;
     } else {
       bool isNonNullableByDefault = classBuilder.library.isNonNullableByDefault;
 
-      DartType bestTypeSoFar;
+      DartType? bestTypeSoFar;
       for (int candidateIndex = members.length - 1;
           candidateIndex >= 0;
           candidateIndex--) {
@@ -130,7 +130,7 @@
           bestTypeSoFar = candidateType;
           bestSoFarIndex = candidateIndex;
         } else {
-          if (_isMoreSpecific(candidateType, bestTypeSoFar, forSetter)) {
+          if (_isMoreSpecific(candidateType, bestTypeSoFar!, forSetter)) {
             if (isNonNullableByDefault &&
                 _isMoreSpecific(bestTypeSoFar, candidateType, forSetter)) {
               if (_mutualSubtypes == null) {
@@ -139,7 +139,7 @@
                   candidateType: candidateIndex
                 };
               } else {
-                _mutualSubtypes[candidateType] = candidateIndex;
+                _mutualSubtypes![candidateType] = candidateIndex;
               }
             } else {
               _mutualSubtypes = null;
@@ -159,8 +159,9 @@
             candidateIndex < members.length;
             candidateIndex++) {
           DartType candidateType = getMemberType(candidateIndex);
-          if (!_isMoreSpecific(bestTypeSoFar, candidateType, forSetter)) {
-            int favoredIndex = getOverlookedOverrideProblemChoice(classBuilder);
+          if (!_isMoreSpecific(bestTypeSoFar!, candidateType, forSetter)) {
+            int? favoredIndex =
+                getOverlookedOverrideProblemChoice(classBuilder);
             bestSoFarIndex = favoredIndex;
             _mutualSubtypes = null;
             break;
@@ -182,8 +183,8 @@
   /// For the nnbd computation, this is one of the members whose type define
   /// the combined member signature, and the indices of the all members whose
   /// type define the combined member signature are in [mutualSubtypeIndices].
-  T get canonicalMember =>
-      _canonicalMemberIndex != null ? members[_canonicalMemberIndex] : null;
+  T? get canonicalMember =>
+      _canonicalMemberIndex != null ? members[_canonicalMemberIndex!] : null;
 
   /// The index within [members] for the member whose type is the most specific
   /// among [members]. If `null`, the combined member signature is not defined
@@ -195,13 +196,13 @@
   /// For the nnbd computation, this is one of the members whose type define
   /// the combined member signature, and the indices of the all members whose
   /// type define the combined member signature are in [mutualSubtypeIndices].
-  int get canonicalMemberIndex => _canonicalMemberIndex;
+  int? get canonicalMemberIndex => _canonicalMemberIndex;
 
   /// For the nnbd computation, the indices of the [members] with most specific
   /// member type.
   ///
   /// If there is only one most specific member type, this is `null`.
-  Set<int> get mutualSubtypeIndices => _mutualSubtypes?.values?.toSet();
+  Set<int>? get mutualSubtypeIndices => _mutualSubtypes?.values.toSet();
 
   Member _getMember(int index);
 
@@ -264,7 +265,7 @@
   }
 
   /// The this type of [classBuilder].
-  DartType get thisType {
+  InterfaceType get thisType {
     return _thisType ??= _coreTypes.thisInterfaceType(
         classBuilder.cls, classBuilder.library.nonNullable);
   }
@@ -272,7 +273,7 @@
   /// Returns `true` if the canonical member is declared in [classBuilder].
   bool get isCanonicalMemberDeclared {
     return _canonicalMemberIndex != null &&
-        _getMember(_canonicalMemberIndex).enclosingClass == classBuilder.cls;
+        _getMember(_canonicalMemberIndex!).enclosingClass == classBuilder.cls;
   }
 
   /// Returns `true` if the canonical member is the 0th.
@@ -284,15 +285,16 @@
   /// Returns type of the [index]th member in [members] as inherited in
   /// [classBuilder].
   DartType getMemberType(int index) {
-    _memberTypes ??= new List<DartType>.filled(members.length, null);
-    DartType candidateType = _memberTypes[index];
+    _memberTypes ??= new List<DartType?>.filled(members.length, null);
+    DartType? candidateType = _memberTypes![index];
     if (candidateType == null) {
       Member target = _getMember(index);
+      // ignore: unnecessary_null_comparison
       assert(target != null,
           "No member computed for index ${index} in ${members}");
       candidateType = _computeMemberType(thisType, target);
       if (!classBuilder.library.isNonNullableByDefault) {
-        DartType legacyErasure;
+        DartType? legacyErasure;
         if (target == hierarchy.coreTypes.objectEquals) {
           // In legacy code we special case `Object.==` to infer `dynamic`
           // instead `Object!`.
@@ -303,11 +305,11 @@
         }
         if (legacyErasure != null) {
           _neededLegacyErasureIndices ??= {};
-          _neededLegacyErasureIndices.add(index);
+          _neededLegacyErasureIndices!.add(index);
           candidateType = legacyErasure;
         }
       }
-      _memberTypes[index] = candidateType;
+      _memberTypes![index] = candidateType;
     }
     return candidateType;
   }
@@ -319,23 +321,23 @@
         return null;
       }
       if (classBuilder.library.isNonNullableByDefault) {
-        DartType canonicalMemberType =
-            _combinedMemberSignatureType = getMemberType(_canonicalMemberIndex);
+        DartType canonicalMemberType = _combinedMemberSignatureType =
+            getMemberType(_canonicalMemberIndex!);
         _containsNnbdTypes =
-            _getMember(_canonicalMemberIndex).isNonNullableByDefault;
+            _getMember(_canonicalMemberIndex!).isNonNullableByDefault;
         if (_mutualSubtypes != null) {
           _combinedMemberSignatureType =
-              norm(_coreTypes, _combinedMemberSignatureType);
-          for (int index in _mutualSubtypes.values) {
+              norm(_coreTypes, _combinedMemberSignatureType!);
+          for (int index in _mutualSubtypes!.values) {
             if (_canonicalMemberIndex != index) {
               _combinedMemberSignatureType = nnbdTopMerge(
                   _coreTypes,
-                  _combinedMemberSignatureType,
+                  _combinedMemberSignatureType!,
                   norm(_coreTypes, getMemberType(index)));
               assert(
                   _combinedMemberSignatureType != null,
                   "No combined member signature found for "
-                  "${_mutualSubtypes.values.map((int i) => getMemberType(i))} "
+                  "${_mutualSubtypes!.values.map((int i) => getMemberType(i))} "
                   "for members ${members}");
             }
           }
@@ -344,13 +346,13 @@
           _containsNnbdTypes = _neededNnbdTopMerge;
         }
       } else {
-        _combinedMemberSignatureType = getMemberType(_canonicalMemberIndex);
+        _combinedMemberSignatureType = getMemberType(_canonicalMemberIndex!);
       }
     }
   }
 
   /// Returns the type of the combined member signature, if defined.
-  DartType get combinedMemberSignatureType {
+  DartType? get combinedMemberSignatureType {
     _ensureCombinedMemberSignatureType();
     return _combinedMemberSignatureType;
   }
@@ -365,14 +367,14 @@
       }
       Covariance canonicalMemberCovariance =
           _combinedMemberSignatureCovariance =
-              _getMemberCovariance(canonicalMemberIndex);
+              _getMemberCovariance(canonicalMemberIndex!);
       if (members.length == 1) {
         return;
       }
       for (int index = 0; index < members.length; index++) {
         if (index != canonicalMemberIndex) {
           _combinedMemberSignatureCovariance =
-              _combinedMemberSignatureCovariance
+              _combinedMemberSignatureCovariance!
                   .merge(_getMemberCovariance(index));
         }
       }
@@ -391,7 +393,7 @@
   }
 
   /// Returns [Covariance] for the combined member signature.
-  Covariance get combinedMemberSignatureCovariance {
+  Covariance? get combinedMemberSignatureCovariance {
     _ensureCombinedMemberSignatureCovariance();
     return _combinedMemberSignatureCovariance;
   }
@@ -401,9 +403,9 @@
   ///
   /// This is used for inferring types on a declared member from the type of the
   /// combined member signature.
-  DartType getCombinedSignatureTypeInContext(
+  DartType? getCombinedSignatureTypeInContext(
       List<TypeParameter> typeParameters) {
-    DartType type = combinedMemberSignatureType;
+    DartType? type = combinedMemberSignatureType;
     if (type == null) {
       return null;
     }
@@ -417,7 +419,7 @@
         return type;
       }
       List<DartType> types =
-          new List<DartType>.filled(typeParameterCount, null);
+          new List<DartType>.filled(typeParameterCount, dummyDartType);
       for (int i = 0; i < typeParameterCount; i++) {
         types[i] = new TypeParameterType.forAlphaRenaming(
             signatureTypeParameters[i], typeParameters[i]);
@@ -444,24 +446,24 @@
 
   /// Create a member signature with the [combinedMemberSignatureType] using the
   /// [canonicalMember] as member signature origin.
-  Procedure createMemberFromSignature({bool copyLocation: true}) {
+  Procedure? createMemberFromSignature({bool copyLocation: true}) {
     if (canonicalMemberIndex == null) {
       return null;
     }
-    Member member = _getMember(canonicalMemberIndex);
+    Member member = _getMember(canonicalMemberIndex!);
     Procedure combinedMemberSignature;
     if (member is Procedure) {
       switch (member.kind) {
         case ProcedureKind.Getter:
           combinedMemberSignature = _createGetterMemberSignature(
-              member, combinedMemberSignatureType,
+              member, combinedMemberSignatureType!,
               copyLocation: copyLocation);
           break;
         case ProcedureKind.Setter:
           VariableDeclaration parameter =
               member.function.positionalParameters.first;
           combinedMemberSignature = _createSetterMemberSignature(
-              member, combinedMemberSignatureType,
+              member, combinedMemberSignatureType!,
               isGenericCovariantImpl: parameter.isGenericCovariantImpl,
               isCovariant: parameter.isCovariant,
               parameterName: parameter.name,
@@ -470,7 +472,7 @@
         case ProcedureKind.Method:
         case ProcedureKind.Operator:
           combinedMemberSignature = _createMethodSignature(
-              member, combinedMemberSignatureType,
+              member, combinedMemberSignatureType as FunctionType,
               copyLocation: copyLocation);
           break;
         case ProcedureKind.Factory:
@@ -481,34 +483,33 @@
     } else if (member is Field) {
       if (forSetter) {
         combinedMemberSignature = _createSetterMemberSignature(
-            member, combinedMemberSignatureType,
+            member, combinedMemberSignatureType!,
             isGenericCovariantImpl: member.isGenericCovariantImpl,
             isCovariant: member.isCovariant,
             copyLocation: copyLocation);
       } else {
         combinedMemberSignature = _createGetterMemberSignature(
-            member, combinedMemberSignatureType,
+            member, combinedMemberSignatureType!,
             copyLocation: copyLocation);
       }
     } else {
       throw new UnsupportedError(
           'Unexpected canonical member $member (${member.runtimeType})');
     }
-    combinedMemberSignatureCovariance.applyCovariance(combinedMemberSignature);
+    combinedMemberSignatureCovariance!.applyCovariance(combinedMemberSignature);
     return combinedMemberSignature;
   }
 
   /// Creates a getter member signature for [member] with the given
   /// [type].
-  Member _createGetterMemberSignature(Member member, DartType type,
-      {bool copyLocation}) {
+  Procedure _createGetterMemberSignature(Member member, DartType type,
+      {required bool copyLocation}) {
+    // ignore: unnecessary_null_comparison
     assert(copyLocation != null);
     Class enclosingClass = classBuilder.cls;
-    Reference reference;
-    if (classBuilder.referencesFromIndexed != null) {
-      reference =
-          classBuilder.referencesFromIndexed.lookupGetterReference(member.name);
-    }
+    Reference? reference =
+        classBuilder.referencesFromIndexed?.lookupGetterReference(member.name);
+
     Uri fileUri;
     int startFileOffset;
     int fileOffset;
@@ -541,20 +542,20 @@
   /// Creates a setter member signature for [member] with the given
   /// [type]. The flags of parameter is set according to [isCovariant] and
   /// [isGenericCovariantImpl] and the [parameterName] is used, if provided.
-  Member _createSetterMemberSignature(Member member, DartType type,
-      {bool isCovariant,
-      bool isGenericCovariantImpl,
-      String parameterName,
-      bool copyLocation}) {
+  Procedure _createSetterMemberSignature(Member member, DartType type,
+      {required bool isCovariant,
+      required bool isGenericCovariantImpl,
+      String? parameterName,
+      required bool copyLocation}) {
+    // ignore: unnecessary_null_comparison
     assert(isCovariant != null);
+    // ignore: unnecessary_null_comparison
     assert(isGenericCovariantImpl != null);
+    // ignore: unnecessary_null_comparison
     assert(copyLocation != null);
     Class enclosingClass = classBuilder.cls;
-    Reference reference;
-    if (classBuilder.referencesFromIndexed != null) {
-      reference =
-          classBuilder.referencesFromIndexed.lookupSetterReference(member.name);
-    }
+    Reference? reference =
+        classBuilder.referencesFromIndexed?.lookupSetterReference(member.name);
     Uri fileUri;
     int startFileOffset;
     int fileOffset;
@@ -590,11 +591,13 @@
       ..parent = enclosingClass;
   }
 
-  Member _createMethodSignature(Procedure procedure, FunctionType functionType,
-      {bool copyLocation}) {
+  Procedure _createMethodSignature(
+      Procedure procedure, FunctionType functionType,
+      {required bool copyLocation}) {
+    // ignore: unnecessary_null_comparison
     assert(copyLocation != null);
     Class enclosingClass = classBuilder.cls;
-    Reference reference = classBuilder.referencesFromIndexed
+    Reference? reference = classBuilder.referencesFromIndexed
         ?.lookupGetterReference(procedure.name);
     Uri fileUri;
     int startFileOffset;
@@ -633,7 +636,7 @@
       }
       for (int i = 0; i < namedParameterCount; i++) {
         VariableDeclaration parameter = function.namedParameters[i];
-        NamedType namedParameterType = namedTypes[parameter.name];
+        NamedType namedParameterType = namedTypes[parameter.name]!;
         namedParameters.add(new VariableDeclaration(parameter.name,
             type: namedParameterType.type,
             isRequired: namedParameterType.isRequired,
@@ -663,7 +666,7 @@
       ..parent = enclosingClass;
   }
 
-  DartType _computeMemberType(DartType thisType, Member member) {
+  DartType _computeMemberType(InterfaceType thisType, Member member) {
     DartType type;
     if (member is Procedure) {
       if (member.isGetter) {
@@ -680,16 +683,16 @@
       unhandled("${member.runtimeType}", "$member", classBuilder.charOffset,
           classBuilder.fileUri);
     }
-    if (member.enclosingClass.typeParameters.isEmpty) {
+    if (member.enclosingClass!.typeParameters.isEmpty) {
       return type;
     }
-    InterfaceType instance = hierarchy.getTypeAsInstanceOf(
-        thisType, member.enclosingClass, classBuilder.library.library);
+    InterfaceType? instance = hierarchy.getTypeAsInstanceOf(
+        thisType, member.enclosingClass!, classBuilder.library.library);
     assert(
         instance != null,
         "No instance of $thisType as ${member.enclosingClass} found for "
         "$member.");
-    return Substitution.fromInterfaceType(instance).substituteType(type);
+    return Substitution.fromInterfaceType(instance!).substituteType(type);
   }
 
   bool _isMoreSpecific(DartType a, DartType b, bool forSetter) {
@@ -717,7 +720,7 @@
   /// defined.
   CombinedClassMemberSignature.internal(this.hierarchy,
       SourceClassBuilder classBuilder, int canonicalMemberIndex, this.members,
-      {bool forSetter})
+      {required bool forSetter})
       : super.internal(classBuilder, canonicalMemberIndex, forSetter);
 
   /// Creates a [CombinedClassMemberSignature] for [members] inherited into
@@ -728,7 +731,7 @@
   /// types or function types is used.
   CombinedClassMemberSignature(
       this.hierarchy, SourceClassBuilder classBuilder, this.members,
-      {bool forSetter})
+      {required bool forSetter})
       : super(classBuilder, forSetter: forSetter);
 
   @override
@@ -741,6 +744,7 @@
   Member _getMember(int index) {
     ClassMember candidate = members[index];
     Member target = candidate.getMember(hierarchy);
+    // ignore: unnecessary_null_comparison
     assert(target != null,
         "No member computed for ${candidate} (${candidate.runtimeType})");
     return target;
@@ -750,6 +754,7 @@
   Covariance _getMemberCovariance(int index) {
     ClassMember candidate = members[index];
     Covariance covariance = candidate.getCovariance(hierarchy);
+    // ignore: unnecessary_null_comparison
     assert(covariance != null,
         "No covariance computed for ${candidate} (${candidate.runtimeType})");
     return covariance;
@@ -771,7 +776,7 @@
 
   CombinedMemberSignatureBuilder(
       this.hierarchy, SourceClassBuilder classBuilder, this.members,
-      {bool forSetter})
+      {required bool forSetter})
       : _types = new Types(hierarchy),
         super(classBuilder, forSetter: forSetter);
 
@@ -783,10 +788,10 @@
 
   @override
   Covariance _getMemberCovariance(int index) {
-    _memberCovariances ??= new List<Covariance>.filled(members.length, null);
-    Covariance covariance = _memberCovariances[index];
+    _memberCovariances ??= new List<Covariance?>.filled(members.length, null);
+    Covariance? covariance = _memberCovariances![index];
     if (covariance == null) {
-      _memberCovariances[index] = covariance =
+      _memberCovariances![index] = covariance =
           new Covariance.fromMember(members[index], forSetter: forSetter);
     }
     return covariance;
diff --git a/pkg/front_end/lib/src/fasta/kernel/constant_evaluator.dart b/pkg/front_end/lib/src/fasta/kernel/constant_evaluator.dart
index d1d15bb..a3f7c13 100644
--- a/pkg/front_end/lib/src/fasta/kernel/constant_evaluator.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/constant_evaluator.dart
@@ -121,7 +121,7 @@
 ConstantCoverage transformLibraries(
     List<Library> libraries,
     ConstantsBackend backend,
-    Map<String, String> environmentDefines,
+    Map<String, String>? environmentDefines,
     TypeEnvironment typeEnvironment,
     ErrorReporter errorReporter,
     EvaluationMode evaluationMode,
@@ -160,7 +160,7 @@
 void transformProcedure(
     Procedure procedure,
     ConstantsBackend backend,
-    Map<String, String> environmentDefines,
+    Map<String, String>? environmentDefines,
     TypeEnvironment typeEnvironment,
     ErrorReporter errorReporter,
     EvaluationMode evaluationMode,
@@ -376,7 +376,7 @@
 
   ConstantsTransformer(
       this.backend,
-      Map<String, String> environmentDefines,
+      Map<String, String>? environmentDefines,
       this.evaluateAnnotations,
       this.enableTripleShift,
       this.enableConstFunctions,
diff --git a/pkg/front_end/lib/src/fasta/kernel/expression_generator.dart b/pkg/front_end/lib/src/fasta/kernel/expression_generator.dart
index cbe266a..e010bb0 100644
--- a/pkg/front_end/lib/src/fasta/kernel/expression_generator.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/expression_generator.dart
@@ -2,8 +2,6 @@
 // for 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
-
 /// A library to help generate expression.
 library fasta.expression_generator;
 
@@ -165,7 +163,7 @@
   /// (e.g. `a[b]`) with the generator on the receiver and [index] as the
   /// index expression.
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware});
+      {required bool isNullAware});
 
   /// Returns a [Expression] representing a compile-time error.
   ///
@@ -191,7 +189,7 @@
 
   Expression buildForEffect() => buildSimpleRead();
 
-  List<Initializer> buildFieldInitializer(Map<String, int> initializedFields) {
+  List<Initializer> buildFieldInitializer(Map<String, int>? initializedFields) {
     return <Initializer>[
       _helper.buildInvalidInitializer(
           _helper.buildProblem(
@@ -216,7 +214,7 @@
   /// If the invocation has explicit type arguments
   /// [buildTypeWithResolvedArguments] called instead.
   /* Expression | Generator | Initializer */ doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false});
 
   /* Expression | Generator */ buildPropertyAccess(
@@ -238,7 +236,8 @@
   }
 
   /*Expression | Generator*/ buildEqualsOperation(Token token, Expression right,
-      {bool isNot}) {
+      {required bool isNot}) {
+    // ignore: unnecessary_null_comparison
     assert(isNot != null);
     return _forest.createEquals(offsetForToken(token), buildSimpleRead(), right,
         isNot: isNot);
@@ -256,7 +255,7 @@
   }
 
   /*Expression|Generator*/ applyTypeArguments(
-      int fileOffset, List<UnresolvedType> typeArguments) {
+      int fileOffset, List<UnresolvedType>? typeArguments) {
     return new Instantiation(
         buildSimpleRead(), _helper.buildDartTypeArguments(typeArguments))
       ..fileOffset = fileOffset;
@@ -268,7 +267,7 @@
   /// The type arguments have not been resolved and should be resolved to
   /// create a [TypeBuilder] for a valid type.
   TypeBuilder buildTypeWithResolvedArguments(
-      NullabilityBuilder nullabilityBuilder, List<UnresolvedType> arguments) {
+      NullabilityBuilder nullabilityBuilder, List<UnresolvedType>? arguments) {
     // TODO(johnniwinther): Could we use a FixedTypeBuilder(InvalidType()) here?
     NamedTypeBuilder result = new NamedTypeBuilder(
         token.lexeme,
@@ -289,7 +288,7 @@
   }
 
   Expression invokeConstructor(
-      List<UnresolvedType> typeArguments,
+      List<UnresolvedType>? typeArguments,
       String name,
       Arguments arguments,
       Token nameToken,
@@ -339,7 +338,7 @@
 class VariableUseGenerator extends Generator {
   final VariableDeclaration variable;
 
-  final DartType promotedType;
+  final DartType? promotedType;
 
   VariableUseGenerator(
       ExpressionGeneratorHelper helper, Token token, this.variable,
@@ -351,7 +350,7 @@
   String get _debugName => "VariableUseGenerator";
 
   @override
-  String get _plainNameForRead => variable.name;
+  String get _plainNameForRead => variable.name!;
 
   @override
   Expression buildSimpleRead() {
@@ -400,18 +399,18 @@
       return buildCompoundAssignment(binaryOperator, value,
           offset: offset, voidContext: voidContext, isPostIncDec: true);
     }
-    VariableDeclaration read =
+    VariableDeclarationImpl read =
         _helper.createVariableDeclarationForValue(_createRead());
     Expression binary = _helper.forest.createBinary(offset,
         _helper.createVariableGet(read, fileOffset), binaryOperator, value);
-    VariableDeclaration write =
+    VariableDeclarationImpl write =
         _helper.createVariableDeclarationForValue(_createWrite(offset, binary));
     return new LocalPostIncDec(read, write)..fileOffset = offset;
   }
 
   @override
   Expression doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     return _helper.forest.createExpressionInvocation(
         adjustForImplicitCall(_plainNameForRead, offset),
@@ -421,7 +420,8 @@
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     return new IndexedAccessGenerator(_helper, token, buildSimpleRead(), index,
         isNullAware: isNullAware);
@@ -472,7 +472,7 @@
 
   @override
   Expression doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     return _helper.buildMethodInvocation(receiver, name, arguments, offset);
   }
@@ -527,14 +527,14 @@
       return buildCompoundAssignment(binaryOperator, value,
           offset: offset, voidContext: voidContext, isPostIncDec: true);
     }
-    VariableDeclaration variable =
+    VariableDeclarationImpl variable =
         _helper.createVariableDeclarationForValue(receiver);
-    VariableDeclaration read = _helper.createVariableDeclarationForValue(
+    VariableDeclarationImpl read = _helper.createVariableDeclarationForValue(
         _forest.createPropertyGet(fileOffset,
             _helper.createVariableGet(variable, receiver.fileOffset), name));
     Expression binary = _helper.forest.createBinary(offset,
         _helper.createVariableGet(read, fileOffset), binaryOperator, value);
-    VariableDeclaration write = _helper.createVariableDeclarationForValue(
+    VariableDeclarationImpl write = _helper.createVariableDeclarationForValue(
         _helper.forest.createPropertySet(
             fileOffset,
             _helper.createVariableGet(variable, receiver.fileOffset),
@@ -546,7 +546,8 @@
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     return new IndexedAccessGenerator(_helper, token, buildSimpleRead(), index,
         isNullAware: isNullAware);
@@ -601,7 +602,7 @@
   final Name name;
 
   /// The offset of `this` if explicit. Otherwise `null`.
-  final int thisOffset;
+  final int? thisOffset;
   final bool isNullAware;
 
   ThisPropertyAccessGenerator(
@@ -642,7 +643,8 @@
     return _createWrite(fileOffset, value, forEffect: voidContext);
   }
 
-  Expression _createWrite(int offset, Expression value, {bool forEffect}) {
+  Expression _createWrite(int offset, Expression value,
+      {required bool forEffect}) {
     return _helper.forest.createPropertySet(
         fileOffset, _forest.createThisExpression(fileOffset), name, value,
         forEffect: forEffect);
@@ -688,19 +690,19 @@
           offset: offset, voidContext: voidContext, isPostIncDec: true);
     }
     _reportNonNullableInNullAwareWarningIfNeeded();
-    VariableDeclaration read = _helper.createVariableDeclarationForValue(
+    VariableDeclarationImpl read = _helper.createVariableDeclarationForValue(
         _forest.createPropertyGet(
             fileOffset, _forest.createThisExpression(fileOffset), name));
     Expression binary = _helper.forest.createBinary(offset,
         _helper.createVariableGet(read, fileOffset), binaryOperator, value);
-    VariableDeclaration write = _helper.createVariableDeclarationForValue(
+    VariableDeclarationImpl write = _helper.createVariableDeclarationForValue(
         _createWrite(fileOffset, binary, forEffect: true));
     return new PropertyPostIncDec.onReadOnly(read, write)..fileOffset = offset;
   }
 
   @override
   Expression doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     return _helper.buildMethodInvocation(
         _forest.createThisExpression(fileOffset), name, arguments, offset);
@@ -708,7 +710,8 @@
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     return new IndexedAccessGenerator(_helper, token, buildSimpleRead(), index,
         isNullAware: isNullAware);
@@ -744,7 +747,7 @@
 
   @override
   Expression buildSimpleRead() {
-    VariableDeclaration variable =
+    VariableDeclarationImpl variable =
         _helper.createVariableDeclarationForValue(receiverExpression);
     PropertyGet read = _forest.createPropertyGet(
         fileOffset,
@@ -757,7 +760,7 @@
 
   @override
   Expression buildAssignment(Expression value, {bool voidContext = false}) {
-    VariableDeclaration variable =
+    VariableDeclarationImpl variable =
         _helper.createVariableDeclarationForValue(receiverExpression);
     PropertySet read = _helper.forest.createPropertySet(
         fileOffset,
@@ -804,14 +807,15 @@
 
   @override
   Expression doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     return unsupported("doInvocation", offset, _uri);
   }
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     return new IndexedAccessGenerator(_helper, token, buildSimpleRead(), index,
         isNullAware: isNullAware);
@@ -832,9 +836,9 @@
 class SuperPropertyAccessGenerator extends Generator {
   final Name name;
 
-  final Member getter;
+  final Member? getter;
 
-  final Member setter;
+  final Member? setter;
 
   SuperPropertyAccessGenerator(ExpressionGeneratorHelper helper, Token token,
       this.name, this.getter, this.setter)
@@ -891,11 +895,11 @@
       return buildCompoundAssignment(binaryOperator, value,
           offset: offset, voidContext: voidContext, isPostIncDec: true);
     }
-    VariableDeclaration read =
+    VariableDeclarationImpl read =
         _helper.createVariableDeclarationForValue(_createRead());
     Expression binary = _helper.forest.createBinary(offset,
         _helper.createVariableGet(read, fileOffset), binaryOperator, value);
-    VariableDeclaration write = _helper
+    VariableDeclarationImpl write = _helper
         .createVariableDeclarationForValue(_createWrite(fileOffset, binary));
     return new StaticPostIncDec(read, write)..fileOffset = offset;
   }
@@ -910,7 +914,7 @@
 
   @override
   Expression doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     if (_helper.constantContext != ConstantContext.none) {
       // TODO(brianwilkerson) Fix the length
@@ -928,7 +932,8 @@
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     return new IndexedAccessGenerator(_helper, token, buildSimpleRead(), index,
         isNullAware: isNullAware);
@@ -954,7 +959,8 @@
 
   IndexedAccessGenerator(
       ExpressionGeneratorHelper helper, Token token, this.receiver, this.index,
-      {this.isNullAware})
+      {required this.isNullAware})
+      // ignore: unnecessary_null_comparison
       : assert(isNullAware != null),
         super(helper, token);
 
@@ -966,7 +972,7 @@
 
   @override
   Expression buildSimpleRead() {
-    VariableDeclaration variable;
+    VariableDeclarationImpl? variable;
     Expression receiverValue;
     if (isNullAware) {
       variable = _helper.createVariableDeclarationForValue(receiver);
@@ -978,7 +984,7 @@
     Expression result =
         _forest.createIndexGet(fileOffset, receiverValue, index);
     if (isNullAware) {
-      result = new NullAwareMethodInvocation(variable, result)
+      result = new NullAwareMethodInvocation(variable!, result)
         ..fileOffset = fileOffset;
     }
     return result;
@@ -986,7 +992,7 @@
 
   @override
   Expression buildAssignment(Expression value, {bool voidContext: false}) {
-    VariableDeclaration variable;
+    VariableDeclarationImpl? variable;
     Expression receiverValue;
     if (isNullAware) {
       variable = _helper.createVariableDeclarationForValue(receiver);
@@ -999,7 +1005,7 @@
         fileOffset, receiverValue, index, value,
         forEffect: voidContext);
     if (isNullAware) {
-      result = new NullAwareMethodInvocation(variable, result)
+      result = new NullAwareMethodInvocation(variable!, result)
         ..fileOffset = fileOffset;
     }
     return result;
@@ -1008,7 +1014,7 @@
   @override
   Expression buildIfNullAssignment(Expression value, DartType type, int offset,
       {bool voidContext: false}) {
-    VariableDeclaration variable;
+    VariableDeclarationImpl? variable;
     Expression receiverValue;
     if (isNullAware) {
       variable = _helper.createVariableDeclarationForValue(receiver);
@@ -1025,7 +1031,7 @@
         forEffect: voidContext)
       ..fileOffset = offset;
     if (isNullAware) {
-      result = new NullAwareMethodInvocation(variable, result)
+      result = new NullAwareMethodInvocation(variable!, result)
         ..fileOffset = fileOffset;
     }
     return result;
@@ -1036,7 +1042,7 @@
       bool voidContext: false,
       bool isPreIncDec: false,
       bool isPostIncDec: false}) {
-    VariableDeclaration variable;
+    VariableDeclarationImpl? variable;
     Expression receiverValue;
     if (isNullAware) {
       variable = _helper.createVariableDeclarationForValue(receiver);
@@ -1054,7 +1060,7 @@
         forEffect: voidContext,
         forPostIncDec: isPostIncDec);
     if (isNullAware) {
-      result = new NullAwareMethodInvocation(variable, result)
+      result = new NullAwareMethodInvocation(variable!, result)
         ..fileOffset = fileOffset;
     }
     return result;
@@ -1070,7 +1076,7 @@
 
   @override
   Expression doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     return _helper.forest.createExpressionInvocation(
         arguments.fileOffset, buildSimpleRead(), arguments);
@@ -1078,7 +1084,8 @@
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     return new IndexedAccessGenerator(_helper, token, buildSimpleRead(), index,
         isNullAware: isNullAware);
@@ -1096,7 +1103,8 @@
 
   static Generator make(ExpressionGeneratorHelper helper, Token token,
       Expression receiver, Expression index,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     if (helper.forest.isThisExpression(receiver)) {
       return new ThisIndexedAccessGenerator(helper, token, index,
@@ -1113,7 +1121,7 @@
 class ThisIndexedAccessGenerator extends Generator {
   final Expression index;
 
-  final int thisOffset;
+  final int? thisOffset;
   final bool isNullAware;
 
   ThisIndexedAccessGenerator(
@@ -1190,7 +1198,7 @@
 
   @override
   Expression doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     return _helper.forest
         .createExpressionInvocation(offset, buildSimpleRead(), arguments);
@@ -1198,7 +1206,8 @@
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     return new IndexedAccessGenerator(_helper, token, buildSimpleRead(), index,
         isNullAware: isNullAware);
@@ -1215,9 +1224,9 @@
 class SuperIndexedAccessGenerator extends Generator {
   final Expression index;
 
-  final Member getter;
+  final Procedure? getter;
 
-  final Member setter;
+  final Procedure? setter;
 
   SuperIndexedAccessGenerator(ExpressionGeneratorHelper helper, Token token,
       this.index, this.getter, this.setter)
@@ -1291,7 +1300,7 @@
 
   @override
   Expression doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     return _helper.forest
         .createExpressionInvocation(offset, buildSimpleRead(), arguments);
@@ -1299,7 +1308,8 @@
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     return new IndexedAccessGenerator(_helper, token, buildSimpleRead(), index,
         isNullAware: isNullAware);
@@ -1359,22 +1369,23 @@
   /// This can be `null` if the subexpression doesn't have a readable target.
   /// For instance if the subexpression is a setter without a corresponding
   /// getter.
-  final Member readTarget;
+  final Member? readTarget;
 
   /// The static [Member] used for performing a write on this subexpression.
   ///
   /// This can be `null` if the subexpression doesn't have a writable target.
   /// For instance if the subexpression is a final field, a method, or a getter
   /// without a corresponding setter.
-  final Member writeTarget;
+  final Member? writeTarget;
 
   /// The offset of the type name if explicit. Otherwise `null`.
-  final int typeOffset;
+  final int? typeOffset;
   final bool isNullAware;
 
   StaticAccessGenerator(ExpressionGeneratorHelper helper, Token token,
       this.targetName, this.readTarget, this.writeTarget,
       {this.typeOffset, this.isNullAware: false})
+      // ignore: unnecessary_null_comparison
       : assert(targetName != null),
         assert(readTarget != null || writeTarget != null),
         super(helper, token);
@@ -1383,9 +1394,9 @@
       ExpressionGeneratorHelper helper,
       String targetName,
       Token token,
-      MemberBuilder getterBuilder,
-      MemberBuilder setterBuilder,
-      {int typeOffset,
+      MemberBuilder? getterBuilder,
+      MemberBuilder? setterBuilder,
+      {int? typeOffset,
       bool isNullAware: false}) {
     return new StaticAccessGenerator(helper, token, targetName,
         getterBuilder?.readTarget, setterBuilder?.writeTarget,
@@ -1394,7 +1405,7 @@
 
   void _reportNonNullableInNullAwareWarningIfNeeded() {
     if (isNullAware && _helper.libraryBuilder.isNonNullableByDefault) {
-      String className = (readTarget ?? writeTarget).enclosingClass.name;
+      String className = (readTarget ?? writeTarget)!.enclosingClass!.name;
       _helper.libraryBuilder.addProblem(
           templateClassInNullAwareReceiver.withArguments(className),
           typeOffset ?? fileOffset,
@@ -1420,7 +1431,7 @@
       read = _makeInvalidRead();
     } else {
       _reportNonNullableInNullAwareWarningIfNeeded();
-      read = _helper.makeStaticGet(readTarget, token);
+      read = _helper.makeStaticGet(readTarget!, token);
     }
     return read;
   }
@@ -1437,7 +1448,7 @@
       write = _makeInvalidWrite(value);
     } else {
       _reportNonNullableInNullAwareWarningIfNeeded();
-      write = new StaticSet(writeTarget, value)..fileOffset = offset;
+      write = new StaticSet(writeTarget!, value)..fileOffset = offset;
     }
     return write;
   }
@@ -1469,18 +1480,18 @@
       return buildCompoundAssignment(binaryOperator, value,
           offset: offset, voidContext: voidContext, isPostIncDec: true);
     }
-    VariableDeclaration read =
+    VariableDeclarationImpl read =
         _helper.createVariableDeclarationForValue(_createRead());
     Expression binary = _helper.forest.createBinary(offset,
         _helper.createVariableGet(read, fileOffset), binaryOperator, value);
-    VariableDeclaration write =
+    VariableDeclarationImpl write =
         _helper.createVariableDeclarationForValue(_createWrite(offset, binary));
     return new StaticPostIncDec(read, write)..fileOffset = offset;
   }
 
   @override
   Expression doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     if (_helper.constantContext != ConstantContext.none &&
         !_helper.isIdentical(readTarget) &&
@@ -1488,22 +1499,23 @@
       return _helper.buildProblem(
           templateNotConstantExpression.withArguments('Method invocation'),
           offset,
-          readTarget?.name?.text?.length ?? 0);
+          readTarget?.name.text.length ?? 0);
     }
-    if (readTarget == null || isFieldOrGetter(readTarget)) {
+    if (readTarget == null || isFieldOrGetter(readTarget!)) {
       return _helper.forest.createExpressionInvocation(
-          offset + (readTarget?.name?.text?.length ?? 0),
+          offset + (readTarget?.name.text.length ?? 0),
           buildSimpleRead(),
           arguments);
     } else {
-      return _helper.buildStaticInvocation(readTarget, arguments,
+      return _helper.buildStaticInvocation(readTarget as Procedure, arguments,
           charOffset: offset);
     }
   }
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     return new IndexedAccessGenerator(_helper, token, buildSimpleRead(), index,
         isNullAware: isNullAware);
@@ -1550,14 +1562,14 @@
   /// This can be `null` if the subexpression doesn't have a readable target.
   /// For instance if the subexpression is a setter without a corresponding
   /// getter.
-  final Procedure readTarget;
+  final Procedure? readTarget;
 
   /// The static [Member] generated for an instance extension member which is
   /// used for performing an invocation on this subexpression.
   ///
   /// This can be `null` if the subexpression doesn't have an invokable target.
   /// For instance if the subexpression is a getter or setter.
-  final Procedure invokeTarget;
+  final Procedure? invokeTarget;
 
   /// The static [Member] generated for an instance extension member which is
   /// used for performing a write on this subexpression.
@@ -1565,7 +1577,7 @@
   /// This can be `null` if the subexpression doesn't have a writable target.
   /// For instance if the subexpression is a final field, a method, or a getter
   /// without a corresponding setter.
-  final Procedure writeTarget;
+  final Procedure? writeTarget;
 
   /// The parameter holding the value for `this` within the current extension
   /// instance method.
@@ -1575,7 +1587,7 @@
 
   /// The type parameters synthetically added to  the current extension
   /// instance method.
-  final List<TypeParameter> extensionTypeParameters;
+  final List<TypeParameter>? extensionTypeParameters;
 
   ExtensionInstanceAccessGenerator(
       ExpressionGeneratorHelper helper,
@@ -1587,9 +1599,11 @@
       this.writeTarget,
       this.extensionThis,
       this.extensionTypeParameters)
+      // ignore: unnecessary_null_comparison
       : assert(targetName != null),
         assert(
             readTarget != null || invokeTarget != null || writeTarget != null),
+        // ignore: unnecessary_null_comparison
         assert(extensionThis != null),
         super(helper, token);
 
@@ -1597,31 +1611,31 @@
       ExpressionGeneratorHelper helper,
       Token token,
       Extension extension,
-      String targetName,
+      String? targetName,
       VariableDeclaration extensionThis,
-      List<TypeParameter> extensionTypeParameters,
-      MemberBuilder getterBuilder,
-      MemberBuilder setterBuilder) {
-    Procedure readTarget;
-    Procedure invokeTarget;
+      List<TypeParameter>? extensionTypeParameters,
+      MemberBuilder? getterBuilder,
+      MemberBuilder? setterBuilder) {
+    Procedure? readTarget;
+    Procedure? invokeTarget;
     if (getterBuilder != null) {
       if (getterBuilder.isGetter) {
         assert(!getterBuilder.isStatic);
-        readTarget = getterBuilder.readTarget;
+        readTarget = getterBuilder.readTarget as Procedure?;
       } else if (getterBuilder.isRegularMethod) {
         assert(!getterBuilder.isStatic);
-        readTarget = getterBuilder.readTarget;
-        invokeTarget = getterBuilder.invokeTarget;
+        readTarget = getterBuilder.readTarget as Procedure?;
+        invokeTarget = getterBuilder.invokeTarget as Procedure?;
       } else if (getterBuilder.isOperator) {
         assert(!getterBuilder.isStatic);
-        invokeTarget = getterBuilder.invokeTarget;
+        invokeTarget = getterBuilder.invokeTarget as Procedure?;
       }
     }
-    Procedure writeTarget;
+    Procedure? writeTarget;
     if (setterBuilder != null) {
       if (setterBuilder.isSetter) {
         assert(!setterBuilder.isStatic);
-        writeTarget = setterBuilder.writeTarget;
+        writeTarget = setterBuilder.writeTarget as Procedure?;
         targetName ??= setterBuilder.name;
       } else {
         return unhandled(
@@ -1635,7 +1649,7 @@
         helper,
         token,
         extension,
-        targetName,
+        targetName!,
         readTarget,
         invokeTarget,
         writeTarget,
@@ -1655,7 +1669,7 @@
     List<DartType> extensionTypeArguments = const <DartType>[];
     if (extensionTypeParameters != null) {
       extensionTypeArguments = [];
-      for (TypeParameter typeParameter in extensionTypeParameters) {
+      for (TypeParameter typeParameter in extensionTypeParameters!) {
         extensionTypeArguments.add(
             _forest.createTypeParameterTypeWithDefaultNullabilityForLibrary(
                 typeParameter, extension.enclosingLibrary));
@@ -1676,7 +1690,7 @@
     } else {
       read = _helper.buildExtensionMethodInvocation(
           fileOffset,
-          readTarget,
+          readTarget!,
           _helper.forest.createArgumentsForExtensionMethod(
               fileOffset,
               _extensionTypeParameterCount,
@@ -1693,7 +1707,8 @@
     return _createWrite(fileOffset, value, forEffect: voidContext);
   }
 
-  Expression _createWrite(int offset, Expression value, {bool forEffect}) {
+  Expression _createWrite(int offset, Expression value,
+      {required bool forEffect}) {
     Expression write;
     if (writeTarget == null) {
       write = _makeInvalidWrite(value);
@@ -1702,7 +1717,7 @@
           extension,
           _createExtensionTypeArguments(),
           _helper.createVariableGet(extensionThis, fileOffset),
-          writeTarget,
+          writeTarget!,
           value,
           forEffect: forEffect);
     }
@@ -1738,27 +1753,27 @@
       return buildCompoundAssignment(binaryOperator, value,
           offset: offset, voidContext: voidContext, isPostIncDec: true);
     }
-    VariableDeclaration read =
+    VariableDeclarationImpl read =
         _helper.createVariableDeclarationForValue(_createRead());
     Expression binary = _helper.forest.createBinary(offset,
         _helper.createVariableGet(read, fileOffset), binaryOperator, value);
-    VariableDeclaration write = _helper.createVariableDeclarationForValue(
+    VariableDeclarationImpl write = _helper.createVariableDeclarationForValue(
         _createWrite(fileOffset, binary, forEffect: true));
     return new PropertyPostIncDec.onReadOnly(read, write)..fileOffset = offset;
   }
 
   @override
   Expression doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     if (invokeTarget != null) {
       return _helper.buildExtensionMethodInvocation(
           offset,
-          invokeTarget,
+          invokeTarget!,
           _forest.createArgumentsForExtensionMethod(
               fileOffset,
               _extensionTypeParameterCount,
-              invokeTarget.function.typeParameters.length -
+              invokeTarget!.function.typeParameters.length -
                   _extensionTypeParameterCount,
               _helper.createVariableGet(extensionThis, offset),
               extensionTypeArguments: _createExtensionTypeArguments(),
@@ -1776,7 +1791,8 @@
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     return new IndexedAccessGenerator(_helper, token, buildSimpleRead(), index,
         isNullAware: isNullAware);
@@ -1830,14 +1846,14 @@
   /// This can be `null` if the subexpression doesn't have a readable target.
   /// For instance if the subexpression is a setter without a corresponding
   /// getter.
-  final Procedure readTarget;
+  final Procedure? readTarget;
 
   /// The static [Member] generated for an instance extension member which is
   /// used for performing an invocation on this subexpression.
   ///
   /// This can be `null` if the subexpression doesn't have an invokable target.
   /// For instance if the subexpression is a getter or setter.
-  final Procedure invokeTarget;
+  final Procedure? invokeTarget;
 
   /// The static [Member] generated for an instance extension member which is
   /// used for performing a write on this subexpression.
@@ -1845,7 +1861,7 @@
   /// This can be `null` if the subexpression doesn't have a writable target.
   /// For instance if the subexpression is a final field, a method, or a getter
   /// without a corresponding setter.
-  final Procedure writeTarget;
+  final Procedure? writeTarget;
 
   /// The expression holding the receiver value for the explicit extension
   /// access, that is, `a` in `Extension<int>(a).method<String>()`.
@@ -1853,7 +1869,7 @@
 
   /// The type arguments explicitly passed to the explicit extension access,
   /// like `<int>` in `Extension<int>(a).method<String>()`.
-  final List<DartType> explicitTypeArguments;
+  final List<DartType>? explicitTypeArguments;
 
   /// The number of type parameters declared on the extension declaration.
   final int extensionTypeParameterCount;
@@ -1873,11 +1889,14 @@
       this.receiver,
       this.explicitTypeArguments,
       this.extensionTypeParameterCount,
-      {this.isNullAware})
+      {required this.isNullAware})
+      // ignore: unnecessary_null_comparison
       : assert(targetName != null),
         assert(
             readTarget != null || invokeTarget != null || writeTarget != null),
+        // ignore: unnecessary_null_comparison
         assert(receiver != null),
+        // ignore: unnecessary_null_comparison
         assert(isNullAware != null),
         super(helper, token);
 
@@ -1887,15 +1906,15 @@
       int extensionTypeArgumentOffset,
       Extension extension,
       Name targetName,
-      Builder getterBuilder,
-      Builder setterBuilder,
+      Builder? getterBuilder,
+      Builder? setterBuilder,
       Expression receiver,
-      List<DartType> explicitTypeArguments,
+      List<DartType>? explicitTypeArguments,
       int extensionTypeParameterCount,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
     assert(getterBuilder != null || setterBuilder != null);
-    Procedure readTarget;
-    Procedure invokeTarget;
+    Procedure? readTarget;
+    Procedure? invokeTarget;
     if (getterBuilder != null) {
       assert(!getterBuilder.isStatic);
       if (getterBuilder is AccessErrorBuilder) {
@@ -1906,17 +1925,17 @@
         assert(getterBuilder.isSetter);
       } else if (getterBuilder.isGetter) {
         assert(!getterBuilder.isStatic);
-        MemberBuilder memberBuilder = getterBuilder;
-        readTarget = memberBuilder.readTarget;
+        MemberBuilder memberBuilder = getterBuilder as MemberBuilder;
+        readTarget = memberBuilder.readTarget as Procedure?;
       } else if (getterBuilder.isRegularMethod) {
         assert(!getterBuilder.isStatic);
-        MemberBuilder procedureBuilder = getterBuilder;
-        readTarget = procedureBuilder.readTarget;
-        invokeTarget = procedureBuilder.invokeTarget;
+        MemberBuilder procedureBuilder = getterBuilder as MemberBuilder;
+        readTarget = procedureBuilder.readTarget as Procedure?;
+        invokeTarget = procedureBuilder.invokeTarget as Procedure?;
       } else if (getterBuilder.isOperator) {
         assert(!getterBuilder.isStatic);
-        MemberBuilder memberBuilder = getterBuilder;
-        invokeTarget = memberBuilder.invokeTarget;
+        MemberBuilder memberBuilder = getterBuilder as MemberBuilder;
+        invokeTarget = memberBuilder.invokeTarget as Procedure?;
       } else {
         return unhandled(
             "$getterBuilder (${getterBuilder.runtimeType})",
@@ -1925,15 +1944,15 @@
             helper.uri);
       }
     }
-    Procedure writeTarget;
+    Procedure? writeTarget;
     if (setterBuilder != null) {
       assert(!setterBuilder.isStatic);
       if (setterBuilder is AccessErrorBuilder) {
         // No setter.
       } else if (setterBuilder.isSetter) {
         assert(!setterBuilder.isStatic);
-        MemberBuilder memberBuilder = setterBuilder;
-        writeTarget = memberBuilder.writeTarget;
+        MemberBuilder memberBuilder = setterBuilder as MemberBuilder;
+        writeTarget = memberBuilder.writeTarget as Procedure?;
       } else {
         return unhandled(
             "$setterBuilder (${setterBuilder.runtimeType})",
@@ -1977,7 +1996,7 @@
   @override
   Expression buildSimpleRead() {
     if (isNullAware) {
-      VariableDeclaration variable =
+      VariableDeclarationImpl variable =
           _helper.createVariableDeclarationForValue(receiver);
       return new NullAwareExtension(
           variable,
@@ -1996,7 +2015,7 @@
     } else {
       read = _helper.buildExtensionMethodInvocation(
           fileOffset,
-          readTarget,
+          readTarget!,
           _helper.forest.createArgumentsForExtensionMethod(
               fileOffset, extensionTypeParameterCount, 0, receiver,
               extensionTypeArguments: _createExtensionTypeArguments(),
@@ -2009,7 +2028,7 @@
   @override
   Expression buildAssignment(Expression value, {bool voidContext: false}) {
     if (isNullAware) {
-      VariableDeclaration variable =
+      VariableDeclarationImpl variable =
           _helper.createVariableDeclarationForValue(receiver);
       return new NullAwareExtension(
           variable,
@@ -2026,13 +2045,13 @@
   }
 
   Expression _createWrite(int offset, Expression receiver, Expression value,
-      {bool forEffect}) {
+      {required bool forEffect}) {
     Expression write;
     if (writeTarget == null) {
       write = _makeInvalidWrite(value);
     } else {
       write = new ExtensionSet(
-          extension, explicitTypeArguments, receiver, writeTarget, value,
+          extension, explicitTypeArguments, receiver, writeTarget!, value,
           forEffect: forEffect);
     }
     write.fileOffset = offset;
@@ -2043,7 +2062,7 @@
   Expression buildIfNullAssignment(Expression value, DartType type, int offset,
       {bool voidContext: false}) {
     if (isNullAware) {
-      VariableDeclaration variable =
+      VariableDeclarationImpl variable =
           _helper.createVariableDeclarationForValue(receiver);
       Expression read = _createRead(_helper.createVariableGet(
           variable, receiver.fileOffset,
@@ -2075,7 +2094,7 @@
       bool isPreIncDec: false,
       bool isPostIncDec: false}) {
     if (isNullAware) {
-      VariableDeclaration variable =
+      VariableDeclarationImpl variable =
           _helper.createVariableDeclarationForValue(receiver);
       Expression binary = _helper.forest.createBinary(
           offset,
@@ -2109,14 +2128,14 @@
       return buildCompoundAssignment(binaryOperator, value,
           offset: offset, voidContext: voidContext, isPostIncDec: true);
     } else if (isNullAware) {
-      VariableDeclaration variable =
+      VariableDeclarationImpl variable =
           _helper.createVariableDeclarationForValue(receiver);
-      VariableDeclaration read = _helper.createVariableDeclarationForValue(
+      VariableDeclarationImpl read = _helper.createVariableDeclarationForValue(
           _createRead(_helper.createVariableGet(variable, receiver.fileOffset,
               forNullGuardedAccess: true)));
       Expression binary = _helper.forest.createBinary(offset,
           _helper.createVariableGet(read, fileOffset), binaryOperator, value);
-      VariableDeclaration write = _helper.createVariableDeclarationForValue(
+      VariableDeclarationImpl write = _helper.createVariableDeclarationForValue(
           _createWrite(
               fileOffset,
               _helper.createVariableGet(variable, receiver.fileOffset,
@@ -2128,14 +2147,14 @@
           variable, new LocalPostIncDec(read, write)..fileOffset = offset)
         ..fileOffset = fileOffset;
     } else {
-      VariableDeclaration variable =
+      VariableDeclarationImpl variable =
           _helper.createVariableDeclarationForValue(receiver);
-      VariableDeclaration read = _helper.createVariableDeclarationForValue(
+      VariableDeclarationImpl read = _helper.createVariableDeclarationForValue(
           _createRead(
               _helper.createVariableGet(variable, receiver.fileOffset)));
       Expression binary = _helper.forest.createBinary(offset,
           _helper.createVariableGet(read, fileOffset), binaryOperator, value);
-      VariableDeclaration write = _helper.createVariableDeclarationForValue(
+      VariableDeclarationImpl write = _helper.createVariableDeclarationForValue(
           _createWrite(fileOffset,
               _helper.createVariableGet(variable, receiver.fileOffset), binary,
               forEffect: voidContext)
@@ -2146,9 +2165,9 @@
 
   @override
   Expression doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
-    VariableDeclaration receiverVariable;
+    VariableDeclarationImpl? receiverVariable;
     Expression receiverExpression = receiver;
     if (isNullAware) {
       receiverVariable = _helper.createVariableDeclarationForValue(receiver);
@@ -2160,11 +2179,11 @@
     if (invokeTarget != null) {
       invocation = _helper.buildExtensionMethodInvocation(
           fileOffset,
-          invokeTarget,
+          invokeTarget!,
           _forest.createArgumentsForExtensionMethod(
               fileOffset,
               extensionTypeParameterCount,
-              invokeTarget.function.typeParameters.length -
+              invokeTarget!.function.typeParameters.length -
                   extensionTypeParameterCount,
               receiverExpression,
               extensionTypeArguments: _createExtensionTypeArguments(),
@@ -2181,7 +2200,7 @@
     }
     if (isNullAware) {
       assert(receiverVariable != null);
-      return new NullAwareExtension(receiverVariable, invocation)
+      return new NullAwareExtension(receiverVariable!, invocation)
         ..fileOffset = fileOffset;
     } else {
       return invocation;
@@ -2190,7 +2209,8 @@
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     return new IndexedAccessGenerator(_helper, token, buildSimpleRead(), index,
         isNullAware: isNullAware);
@@ -2217,12 +2237,12 @@
   /// The static [Member] generated for the [] operation.
   ///
   /// This can be `null` if the extension doesn't have an [] method.
-  final Procedure readTarget;
+  final Procedure? readTarget;
 
   /// The static [Member] generated for the []= operation.
   ///
   /// This can be `null` if the extension doesn't have an []= method.
-  final Procedure writeTarget;
+  final Procedure? writeTarget;
 
   /// The expression holding the receiver value for the explicit extension
   /// access, that is, `a` in `Extension<int>(a)[index]`.
@@ -2233,7 +2253,7 @@
 
   /// The type arguments explicitly passed to the explicit extension access,
   /// like `<int>` in `Extension<int>(a)[b]`.
-  final List<DartType> explicitTypeArguments;
+  final List<DartType>? explicitTypeArguments;
 
   /// The number of type parameters declared on the extension declaration.
   final int extensionTypeParameterCount;
@@ -2251,9 +2271,11 @@
       this.index,
       this.explicitTypeArguments,
       this.extensionTypeParameterCount,
-      {this.isNullAware})
+      {required this.isNullAware})
       : assert(readTarget != null || writeTarget != null),
+        // ignore: unnecessary_null_comparison
         assert(receiver != null),
+        // ignore: unnecessary_null_comparison
         assert(isNullAware != null),
         super(helper, token);
 
@@ -2262,15 +2284,16 @@
       Token token,
       int extensionTypeArgumentOffset,
       Extension extension,
-      Builder getterBuilder,
-      Builder setterBuilder,
+      Builder? getterBuilder,
+      Builder? setterBuilder,
       Expression receiver,
       Expression index,
-      List<DartType> explicitTypeArguments,
+      List<DartType>? explicitTypeArguments,
       int extensionTypeParameterCount,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
-    Procedure readTarget;
+    Procedure? readTarget;
     if (getterBuilder != null) {
       if (getterBuilder is AccessErrorBuilder) {
         AccessErrorBuilder error = getterBuilder;
@@ -2280,7 +2303,7 @@
         assert(getterBuilder is MemberBuilder);
       } else if (getterBuilder is MemberBuilder) {
         MemberBuilder procedureBuilder = getterBuilder;
-        readTarget = procedureBuilder.member;
+        readTarget = procedureBuilder.member as Procedure?;
       } else {
         return unhandled(
             "${getterBuilder.runtimeType}",
@@ -2289,10 +2312,10 @@
             helper.uri);
       }
     }
-    Procedure writeTarget;
+    Procedure? writeTarget;
     if (setterBuilder is MemberBuilder) {
       MemberBuilder memberBuilder = setterBuilder;
-      writeTarget = memberBuilder.member;
+      writeTarget = memberBuilder.member as Procedure?;
     }
     return new ExplicitExtensionIndexedAccessGenerator(
         helper,
@@ -2321,7 +2344,7 @@
     if (readTarget == null) {
       return _makeInvalidRead();
     }
-    VariableDeclaration variable;
+    VariableDeclarationImpl? variable;
     Expression receiverValue;
     if (isNullAware) {
       variable = _helper.createVariableDeclarationForValue(receiver);
@@ -2332,7 +2355,7 @@
     }
     Expression result = _helper.buildExtensionMethodInvocation(
         fileOffset,
-        readTarget,
+        readTarget!,
         _forest.createArgumentsForExtensionMethod(
             fileOffset, extensionTypeParameterCount, 0, receiverValue,
             extensionTypeArguments: _createExtensionTypeArguments(),
@@ -2340,7 +2363,7 @@
             positionalArguments: <Expression>[index]),
         isTearOff: false);
     if (isNullAware) {
-      result = new NullAwareMethodInvocation(variable, result)
+      result = new NullAwareMethodInvocation(variable!, result)
         ..fileOffset = fileOffset;
     }
     return result;
@@ -2351,7 +2374,7 @@
     if (writeTarget == null) {
       return _makeInvalidWrite(value);
     }
-    VariableDeclaration variable;
+    VariableDeclarationImpl? variable;
     Expression receiverValue;
     if (isNullAware) {
       variable = _helper.createVariableDeclarationForValue(receiver);
@@ -2364,7 +2387,7 @@
     if (voidContext) {
       result = _helper.buildExtensionMethodInvocation(
           fileOffset,
-          writeTarget,
+          writeTarget!,
           _forest.createArgumentsForExtensionMethod(
               fileOffset, extensionTypeParameterCount, 0, receiverValue,
               extensionTypeArguments: _createExtensionTypeArguments(),
@@ -2373,11 +2396,11 @@
           isTearOff: false);
     } else {
       result = new ExtensionIndexSet(extension, explicitTypeArguments,
-          receiverValue, writeTarget, index, value)
+          receiverValue, writeTarget!, index, value)
         ..fileOffset = fileOffset;
     }
     if (isNullAware) {
-      result = new NullAwareMethodInvocation(variable, result)
+      result = new NullAwareMethodInvocation(variable!, result)
         ..fileOffset = fileOffset;
     }
     return result;
@@ -2386,7 +2409,7 @@
   @override
   Expression buildIfNullAssignment(Expression value, DartType type, int offset,
       {bool voidContext: false}) {
-    VariableDeclaration variable;
+    VariableDeclarationImpl? variable;
     Expression receiverValue;
     if (isNullAware) {
       variable = _helper.createVariableDeclarationForValue(receiver);
@@ -2409,7 +2432,7 @@
         forEffect: voidContext)
       ..fileOffset = offset;
     if (isNullAware) {
-      result = new NullAwareMethodInvocation(variable, result)
+      result = new NullAwareMethodInvocation(variable!, result)
         ..fileOffset = fileOffset;
     }
     return result;
@@ -2420,7 +2443,7 @@
       bool voidContext: false,
       bool isPreIncDec: false,
       bool isPostIncDec: false}) {
-    VariableDeclaration variable;
+    VariableDeclarationImpl? variable;
     Expression receiverValue;
     if (isNullAware) {
       variable = _helper.createVariableDeclarationForValue(receiver);
@@ -2444,7 +2467,7 @@
         forEffect: voidContext,
         forPostIncDec: isPostIncDec);
     if (isNullAware) {
-      result = new NullAwareMethodInvocation(variable, result)
+      result = new NullAwareMethodInvocation(variable!, result)
         ..fileOffset = fileOffset;
     }
     return result;
@@ -2460,7 +2483,7 @@
 
   @override
   Expression doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     return _helper.forest
         .createExpressionInvocation(offset, buildSimpleRead(), arguments);
@@ -2468,7 +2491,8 @@
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     return new IndexedAccessGenerator(_helper, token, buildSimpleRead(), index,
         isNullAware: isNullAware);
@@ -2512,7 +2536,7 @@
 class ExplicitExtensionAccessGenerator extends Generator {
   final ExtensionBuilder extensionBuilder;
   final Expression receiver;
-  final List<DartType> explicitTypeArguments;
+  final List<DartType>? explicitTypeArguments;
 
   ExplicitExtensionAccessGenerator(
       ExpressionGeneratorHelper helper,
@@ -2562,11 +2586,11 @@
 
   Generator _createInstanceAccess(Token token, Name name,
       {bool isNullAware: false}) {
-    Builder getter = extensionBuilder.lookupLocalMemberByName(name);
+    Builder? getter = extensionBuilder.lookupLocalMemberByName(name);
     if (getter != null && (getter.isStatic || getter.isField)) {
       getter = null;
     }
-    Builder setter =
+    Builder? setter =
         extensionBuilder.lookupLocalMemberByName(name, setter: true);
     if (setter != null && setter.isStatic) {
       setter = null;
@@ -2601,7 +2625,7 @@
         _createInstanceAccess(send.token, send.name, isNullAware: isNullAware);
     if (send.arguments != null) {
       return generator.doInvocation(
-          offsetForToken(send.token), send.typeArguments, send.arguments,
+          offsetForToken(send.token), send.typeArguments, send.arguments!,
           isTypeArgumentsInForest: send.isTypeArgumentsInForest);
     } else {
       return generator;
@@ -2626,7 +2650,7 @@
 
   @override
   doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     Generator generator = _createInstanceAccess(token, callName);
     return generator.doInvocation(offset, typeArguments, arguments,
@@ -2647,10 +2671,11 @@
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
-    Builder getter = extensionBuilder.lookupLocalMemberByName(indexGetName);
-    Builder setter = extensionBuilder.lookupLocalMemberByName(indexSetName);
+    Builder? getter = extensionBuilder.lookupLocalMemberByName(indexGetName);
+    Builder? setter = extensionBuilder.lookupLocalMemberByName(indexSetName);
     if (getter == null && setter == null) {
       return new UnresolvedNameGenerator(_helper, token, indexGetName);
     }
@@ -2738,7 +2763,7 @@
 
   @override
   Expression doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     if (_forest.argumentsPositional(arguments).length > 0 ||
         _forest.argumentsNamed(arguments).length > 0) {
@@ -2750,7 +2775,8 @@
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     return new IndexedAccessGenerator(_helper, token, buildSimpleRead(), index,
         isNullAware: isNullAware);
@@ -2831,7 +2857,7 @@
       return new DeferredAccessGenerator(
           _helper, token, prefixGenerator, propertyAccess);
     } else {
-      Expression expression = propertyAccess;
+      Expression expression = propertyAccess as Expression;
       return _helper.wrapInDeferredCheck(
           expression, prefixGenerator.prefix, token.charOffset);
     }
@@ -2847,7 +2873,7 @@
 
   @override
   TypeBuilder buildTypeWithResolvedArguments(
-      NullabilityBuilder nullabilityBuilder, List<UnresolvedType> arguments) {
+      NullabilityBuilder nullabilityBuilder, List<UnresolvedType>? arguments) {
     String name = "${prefixGenerator._plainNameForRead}."
         "${suffixGenerator._plainNameForRead}";
     TypeBuilder type = suffixGenerator.buildTypeWithResolvedArguments(
@@ -2855,7 +2881,8 @@
     LocatedMessage message;
     if (type is NamedTypeBuilder &&
         type.declaration is InvalidTypeDeclarationBuilder) {
-      InvalidTypeDeclarationBuilder declaration = type.declaration;
+      InvalidTypeDeclarationBuilder declaration =
+          type.declaration as InvalidTypeDeclarationBuilder;
       message = declaration.message;
     } else {
       int charOffset = offsetForToken(prefixGenerator.token);
@@ -2882,7 +2909,7 @@
 
   @override
   doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     Object suffix = suffixGenerator.doInvocation(
         offset, typeArguments, arguments,
@@ -2892,13 +2919,13 @@
           suffix, prefixGenerator.prefix, fileOffset);
     } else {
       return new DeferredAccessGenerator(
-          _helper, token, prefixGenerator, suffix);
+          _helper, token, prefixGenerator, suffix as Generator);
     }
   }
 
   @override
   Expression invokeConstructor(
-      List<UnresolvedType> typeArguments,
+      List<UnresolvedType>? typeArguments,
       String name,
       Arguments arguments,
       Token nameToken,
@@ -2913,7 +2940,8 @@
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     return new IndexedAccessGenerator(_helper, token, buildSimpleRead(), index,
         isNullAware: isNullAware);
@@ -2947,17 +2975,19 @@
 ///     T();        // a TypeUseGenerator is created for `T`.
 ///   }
 ///
-class TypeUseGenerator extends ReadOnlyAccessGenerator {
+class TypeUseGenerator extends AbstractReadOnlyAccessGenerator {
   final TypeDeclarationBuilder declaration;
-  List<UnresolvedType> typeArguments;
+  List<UnresolvedType>? typeArguments;
+
+  final String targetName;
+
+  Expression? _expression;
 
   TypeUseGenerator(ExpressionGeneratorHelper helper, Token token,
-      this.declaration, String targetName)
+      this.declaration, this.targetName)
       : super(
             helper,
             token,
-            null,
-            targetName,
             // TODO(johnniwinther): InvalidTypeDeclarationBuilder is currently
             // misused for import conflict.
             declaration is InvalidTypeDeclarationBuilder
@@ -2969,7 +2999,7 @@
 
   @override
   TypeBuilder buildTypeWithResolvedArguments(
-      NullabilityBuilder nullabilityBuilder, List<UnresolvedType> arguments) {
+      NullabilityBuilder nullabilityBuilder, List<UnresolvedType>? arguments) {
     if (declaration.isExtension && !_helper.enableExtensionTypesInLibrary) {
       // Extension declarations cannot be used as types.
       return super
@@ -2990,18 +3020,18 @@
       }
     }
 
-    List<TypeBuilder> argumentBuilders;
+    List<TypeBuilder>? argumentBuilders;
     if (arguments != null) {
-      argumentBuilders = new List<TypeBuilder>.filled(arguments.length, null);
-      for (int i = 0; i < argumentBuilders.length; i++) {
-        argumentBuilders[i] = _helper
-            .validateTypeUse(arguments[i],
+      argumentBuilders =
+          new List<TypeBuilder>.generate(arguments.length, (int i) {
+        return _helper
+            .validateTypeUse(arguments![i],
                 nonInstanceAccessIsError: false,
                 allowPotentiallyConstantType:
                     _helper.libraryBuilder.isNonNullableByDefault &&
                         _helper.inIsOrAsOperatorType)
             .builder;
-      }
+      }, growable: false);
     }
     return new NamedTypeBuilder(
         targetName, nullabilityBuilder, argumentBuilders, _uri, fileOffset)
@@ -3010,7 +3040,7 @@
 
   @override
   Expression invokeConstructor(
-      List<UnresolvedType> typeArguments,
+      List<UnresolvedType>? typeArguments,
       String name,
       Arguments arguments,
       Token nameToken,
@@ -3023,7 +3053,7 @@
         arguments,
         name,
         typeArguments,
-        offsetForToken(nameToken ?? token),
+        offsetForToken(nameToken),
         constness);
   }
 
@@ -3037,13 +3067,14 @@
 
   @override
   Expression get expression {
-    if (super.expression == null) {
+    if (_expression == null) {
       if (declaration is InvalidTypeDeclarationBuilder) {
-        InvalidTypeDeclarationBuilder declaration = this.declaration;
-        super.expression = _helper.buildProblemErrorIfConst(
+        InvalidTypeDeclarationBuilder declaration =
+            this.declaration as InvalidTypeDeclarationBuilder;
+        _expression = _helper.buildProblemErrorIfConst(
             declaration.message.messageObject, fileOffset, token.length);
       } else {
-        super.expression = _forest.createTypeLiteral(
+        _expression = _forest.createTypeLiteral(
             offsetForToken(token),
             _helper.buildTypeLiteralDartType(
                 new UnresolvedType(
@@ -3055,17 +3086,17 @@
                 nonInstanceAccessIsError: true));
       }
     }
-    return super.expression;
+    return _expression!;
   }
 
   @override
   buildPropertyAccess(
       IncompleteSendGenerator send, int operatorOffset, bool isNullAware) {
     Name name = send.name;
-    Arguments arguments = send.arguments;
+    Arguments? arguments = send.arguments;
 
-    TypeDeclarationBuilder declarationBuilder = declaration;
-    TypeAliasBuilder aliasBuilder;
+    TypeDeclarationBuilder? declarationBuilder = declaration;
+    TypeAliasBuilder? aliasBuilder;
     if (declarationBuilder is TypeAliasBuilder) {
       aliasBuilder = declarationBuilder;
       declarationBuilder = aliasBuilder.unaliasDeclaration(null,
@@ -3075,7 +3106,7 @@
     }
     if (declarationBuilder is DeclarationBuilder) {
       DeclarationBuilder declaration = declarationBuilder;
-      Builder member = declaration.findStaticBuilder(
+      Builder? member = declaration.findStaticBuilder(
           name.text, offsetForToken(send.token), _uri, _helper.libraryBuilder);
 
       Generator generator;
@@ -3084,11 +3115,9 @@
         if (send is IncompletePropertyAccessGenerator) {
           if (_helper.enableConstructorTearOffsInLibrary &&
               declarationBuilder is ClassBuilder) {
-            Builder constructor = declarationBuilder.findConstructorOrFactory(
-                name.text,
-                offsetForToken(send.token),
-                _uri,
-                _helper.libraryBuilder);
+            MemberBuilder? constructor =
+                declarationBuilder.findConstructorOrFactory(name.text,
+                    offsetForToken(send.token), _uri, _helper.libraryBuilder);
             if (constructor is ConstructorBuilder) {
               return _helper.forest.createConstructorTearOff(
                   token.charOffset, constructor.constructor);
@@ -3105,7 +3134,7 @@
               declaration,
               send.token,
               send.token,
-              arguments,
+              arguments!,
               name.text,
               send.typeArguments,
               token.charOffset,
@@ -3117,7 +3146,7 @@
         return _helper.buildProblem(
             member.message, member.charOffset, name.text.length);
       } else {
-        Builder setter;
+        Builder? setter;
         if (member.isSetter) {
           setter = member;
           member = null;
@@ -3126,7 +3155,7 @@
               name.text, fileOffset, _uri, _helper.libraryBuilder,
               isSetter: true);
         } else if (member.isField) {
-          MemberBuilder fieldBuilder = member;
+          MemberBuilder fieldBuilder = member as MemberBuilder;
           if (!fieldBuilder.isAssignable) {
             setter = declaration.findStaticBuilder(
                 name.text, fileOffset, _uri, _helper.libraryBuilder,
@@ -3159,15 +3188,15 @@
 
   @override
   doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     if (declaration.isExtension) {
-      ExtensionBuilder extensionBuilder = declaration;
+      ExtensionBuilder extensionBuilder = declaration as ExtensionBuilder;
       if (arguments.positional.length != 1 || arguments.named.isNotEmpty) {
         return _helper.buildProblem(messageExplicitExtensionArgumentMismatch,
             fileOffset, lengthForToken(token));
       }
-      List<DartType> explicitTypeArguments =
+      List<DartType>? explicitTypeArguments =
           getExplicitTypeArguments(arguments);
       if (explicitTypeArguments != null) {
         int typeParameterCount = extensionBuilder.typeParameters?.length ?? 0;
@@ -3180,8 +3209,12 @@
         }
       }
       // TODO(johnniwinther): Check argument and type argument count.
-      return new ExplicitExtensionAccessGenerator(_helper, token, declaration,
-          arguments.positional.single, explicitTypeArguments);
+      return new ExplicitExtensionAccessGenerator(
+          _helper,
+          token,
+          declaration as ExtensionBuilder,
+          arguments.positional.single,
+          explicitTypeArguments);
     } else {
       return _helper.buildConstructorInvocation(declaration, token, token,
           arguments, "", typeArguments, token.charOffset, Constness.implicit,
@@ -3190,7 +3223,7 @@
   }
 
   @override
-  applyTypeArguments(int fileOffset, List<UnresolvedType> typeArguments) {
+  applyTypeArguments(int fileOffset, List<UnresolvedType>? typeArguments) {
     return new TypeUseGenerator(_helper, token, declaration, targetName)
       ..typeArguments = typeArguments;
   }
@@ -3233,17 +3266,27 @@
 ///     }
 ///   }
 ///
-class ReadOnlyAccessGenerator extends Generator {
+class ReadOnlyAccessGenerator extends AbstractReadOnlyAccessGenerator {
   final String targetName;
 
   Expression expression;
 
+  ReadOnlyAccessGenerator(ExpressionGeneratorHelper helper, Token token,
+      this.expression, this.targetName, ReadOnlyAccessKind kind)
+      : super(helper, token, kind);
+}
+
+abstract class AbstractReadOnlyAccessGenerator extends Generator {
   final ReadOnlyAccessKind kind;
 
-  ReadOnlyAccessGenerator(ExpressionGeneratorHelper helper, Token token,
-      this.expression, this.targetName, this.kind)
+  AbstractReadOnlyAccessGenerator(
+      ExpressionGeneratorHelper helper, Token token, this.kind)
       : super(helper, token);
 
+  String get targetName;
+
+  Expression get expression;
+
   @override
   String get _debugName => "ReadOnlyAccessGenerator";
 
@@ -3258,12 +3301,14 @@
   Expression _makeInvalidWrite(Expression value) {
     switch (kind) {
       case ReadOnlyAccessKind.ConstVariable:
+        // ignore: unnecessary_null_comparison
         assert(targetName != null);
         return _helper.buildProblem(
             templateCannotAssignToConstVariable.withArguments(targetName),
             fileOffset,
             lengthForToken(token));
       case ReadOnlyAccessKind.FinalVariable:
+        // ignore: unnecessary_null_comparison
         assert(targetName != null);
         return _helper.buildProblem(
             templateCannotAssignToFinalVariable.withArguments(targetName),
@@ -3322,7 +3367,7 @@
 
   @override
   doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     return _helper.forest.createExpressionInvocation(
         adjustForImplicitCall(targetName, offset), _createRead(), arguments);
@@ -3330,7 +3375,8 @@
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     // TODO(johnniwinther): The read-only quality of the variable should be
     // passed on to the generator.
@@ -3365,10 +3411,12 @@
   @override
   String get _plainNameForRead => name.text;
 
-  withReceiver(Object receiver, int operatorOffset, {bool isNullAware}) => this;
+  withReceiver(Object? receiver, int operatorOffset,
+          {bool isNullAware: false}) =>
+      this;
 
   @override
-  List<Initializer> buildFieldInitializer(Map<String, int> initializedFields) {
+  List<Initializer> buildFieldInitializer(Map<String, int>? initializedFields) {
     return <Initializer>[
       _helper.buildInvalidInitializer(
           buildError(_forest.createArgumentsEmpty(fileOffset), isSetter: true))
@@ -3377,7 +3425,7 @@
 
   @override
   doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     return buildError(arguments, offset: offset);
   }
@@ -3450,7 +3498,7 @@
 
   @override
   Expression invokeConstructor(
-      List<UnresolvedType> typeArguments,
+      List<UnresolvedType>? typeArguments,
       String name,
       Arguments arguments,
       Token nameToken,
@@ -3466,7 +3514,8 @@
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     return new IndexedAccessGenerator(_helper, token, buildSimpleRead(), index,
         isNullAware: isNullAware);
@@ -3494,14 +3543,14 @@
 
   @override
   Expression doInvocation(
-      int charOffset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int charOffset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     return buildError(arguments, offset: charOffset);
   }
 
   @override
   Expression buildError(Arguments arguments,
-      {bool isGetter: false, bool isSetter: false, int offset}) {
+      {bool isGetter: false, bool isSetter: false, int? offset}) {
     offset ??= fileOffset;
     return _helper.throwNoSuchMethodError(
         _forest.createNullLiteral(offset), _plainNameForRead, arguments, offset,
@@ -3547,7 +3596,8 @@
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     return new IndexedAccessGenerator(_helper, token, buildSimpleRead(), index,
         isNullAware: isNullAware);
@@ -3568,7 +3618,7 @@
 
   @override
   Expression doInvocation(
-      int charOffset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int charOffset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     return unhandled("${runtimeType}", "doInvocation", charOffset, _uri);
   }
@@ -3611,14 +3661,15 @@
   }
 
   @override
-  Expression _makeInvalidWrite(Expression value) {
+  Expression _makeInvalidWrite(Expression? value) {
     return _helper.buildProblem(messageIllegalAssignmentToNonAssignable,
         fileOffset, lengthForToken(token));
   }
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     return new IndexedAccessGenerator(_helper, token, buildSimpleRead(), index,
         isNullAware: isNullAware);
@@ -3701,7 +3752,7 @@
   }
 
   @override
-  List<Initializer> buildFieldInitializer(Map<String, int> initializedFields) {
+  List<Initializer> buildFieldInitializer(Map<String, int>? initializedFields) {
     if (!identical("=", assignmentOperator) ||
         generator is! ThisPropertyAccessGenerator) {
       return generator.buildFieldInitializer(initializedFields);
@@ -3805,7 +3856,7 @@
           result = new DeferredAccessGenerator(_helper, name, this, result);
         }
       } else {
-        _helper.wrapInDeferredCheck(result, prefix, fileOffset);
+        _helper.wrapInDeferredCheck(result as Expression, prefix, fileOffset);
       }
     }
     return result;
@@ -3813,7 +3864,7 @@
 
   @override
   /* Expression | Generator | Initializer */ doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     return _helper.wrapInLocatedProblem(
         _helper.evaluateArgumentsBefore(
@@ -3857,7 +3908,8 @@
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     return new IndexedAccessGenerator(_helper, token, buildSimpleRead(), index,
         isNullAware: isNullAware);
@@ -3919,7 +3971,7 @@
 
   @override
   Expression doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     return _helper.throwNoSuchMethodError(_forest.createNullLiteral(offset),
         _plainNameForRead, arguments, fileOffset);
@@ -3927,7 +3979,7 @@
 
   @override
   TypeBuilder buildTypeWithResolvedArguments(
-      NullabilityBuilder nullabilityBuilder, List<UnresolvedType> arguments) {
+      NullabilityBuilder nullabilityBuilder, List<UnresolvedType>? arguments) {
     Template<Message Function(String, String)> template = isUnresolved
         ? templateUnresolvedPrefixInTypeAnnotation
         : templateNotAPrefixInTypeAnnotation;
@@ -3954,7 +4006,8 @@
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     return new IndexedAccessGenerator(_helper, token, buildSimpleRead(), index,
         isNullAware: isNullAware);
@@ -4021,12 +4074,12 @@
 
   Expression _makeInvalidWrite(Expression value) => buildProblem();
 
-  List<Initializer> buildFieldInitializer(Map<String, int> initializedFields) {
+  List<Initializer> buildFieldInitializer(Map<String, int>? initializedFields) {
     return <Initializer>[_helper.buildInvalidInitializer(buildProblem())];
   }
 
   Expression doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     return buildProblem();
   }
@@ -4037,7 +4090,7 @@
   }
 
   TypeBuilder buildTypeWithResolvedArguments(
-      NullabilityBuilder nullabilityBuilder, List<UnresolvedType> arguments) {
+      NullabilityBuilder nullabilityBuilder, List<UnresolvedType>? arguments) {
     // TODO(johnniwinther): Could we use a FixedTypeBuilder(InvalidType()) here?
     NamedTypeBuilder result = new NamedTypeBuilder(
         token.lexeme,
@@ -4056,7 +4109,7 @@
   }
 
   Expression invokeConstructor(
-      List<UnresolvedType> typeArguments,
+      List<UnresolvedType>? typeArguments,
       String name,
       Arguments arguments,
       Token nameToken,
@@ -4067,7 +4120,8 @@
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     return new IndexedAccessGenerator(_helper, token, buildSimpleRead(), index,
         isNullAware: isNullAware);
@@ -4159,7 +4213,7 @@
     }
   }
 
-  Expression buildFieldInitializerError(Map<String, int> initializedFields) {
+  Expression buildFieldInitializerError(Map<String, int>? initializedFields) {
     String keyword = isSuper ? "super" : "this";
     return _helper.buildProblem(
         templateThisOrSuperAccessInFieldInitializer.withArguments(keyword),
@@ -4168,7 +4222,7 @@
   }
 
   @override
-  List<Initializer> buildFieldInitializer(Map<String, int> initializedFields) {
+  List<Initializer> buildFieldInitializer(Map<String, int>? initializedFields) {
     Expression error = buildFieldInitializerError(initializedFields);
     return <Initializer>[
       _helper.buildInvalidInitializer(error, error.fileOffset)
@@ -4185,14 +4239,14 @@
   buildPropertyAccess(
       IncompleteSendGenerator send, int operatorOffset, bool isNullAware) {
     Name name = send.name;
-    Arguments arguments = send.arguments;
+    Arguments? arguments = send.arguments;
     int offset = offsetForToken(send.token);
     if (isInitializer && send is SendAccessGenerator) {
       if (isNullAware) {
         _helper.addProblem(
             messageInvalidUseOfNullAwareAccess, operatorOffset, 2);
       }
-      return buildConstructorInitializer(offset, name, arguments);
+      return buildConstructorInitializer(offset, name, arguments!);
     }
     if (inFieldInitializer && !inLateFieldInitializer && !isInitializer) {
       return buildFieldInitializerError(null);
@@ -4211,8 +4265,8 @@
           isSuper: isSuper);
     } else {
       if (isSuper) {
-        Member getter = _helper.lookupInstanceMember(name, isSuper: isSuper);
-        Member setter = _helper.lookupInstanceMember(name,
+        Member? getter = _helper.lookupInstanceMember(name, isSuper: isSuper);
+        Member? setter = _helper.lookupInstanceMember(name,
             isSuper: isSuper, isSetter: true);
         return new SuperPropertyAccessGenerator(
             _helper,
@@ -4234,7 +4288,7 @@
   }
 
   doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     if (isInitializer) {
       return buildConstructorInitializer(offset, new Name(""), arguments);
@@ -4247,7 +4301,8 @@
   }
 
   @override
-  buildEqualsOperation(Token token, Expression right, {bool isNot}) {
+  buildEqualsOperation(Token token, Expression right, {required bool isNot}) {
+    // ignore: unnecessary_null_comparison
     assert(isNot != null);
     if (isSuper) {
       int offset = offsetForToken(token);
@@ -4295,8 +4350,9 @@
 
   Initializer buildConstructorInitializer(
       int offset, Name name, Arguments arguments) {
-    Constructor constructor = _helper.lookupConstructor(name, isSuper: isSuper);
-    LocatedMessage message;
+    Constructor? constructor =
+        _helper.lookupConstructor(name, isSuper: isSuper);
+    LocatedMessage? message;
     if (constructor != null) {
       message = _helper.checkArgumentsForFunction(
           constructor.function, arguments, offset, <TypeParameter>[]);
@@ -4322,10 +4378,10 @@
           offset);
     } else if (isSuper) {
       return _helper.buildSuperInitializer(
-          false, constructor, arguments, offset);
+          false, constructor!, arguments, offset);
     } else {
       return _helper.buildRedirectingInitializer(
-          constructor, arguments, offset);
+          constructor!, arguments, offset);
     }
   }
 
@@ -4358,15 +4414,18 @@
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     if (isSuper) {
       return new SuperIndexedAccessGenerator(
           _helper,
           token,
           index,
-          _helper.lookupInstanceMember(indexGetName, isSuper: true),
-          _helper.lookupInstanceMember(indexSetName, isSuper: true));
+          _helper.lookupInstanceMember(indexGetName, isSuper: true)
+              as Procedure?,
+          _helper.lookupInstanceMember(indexSetName, isSuper: true)
+              as Procedure?);
     } else {
       return new ThisIndexedAccessGenerator(_helper, token, index,
           thisOffset: fileOffset, isNullAware: isNullAware);
@@ -4396,13 +4455,13 @@
 abstract class IncompleteSendGenerator implements Generator {
   Name get name;
 
-  withReceiver(Object receiver, int operatorOffset, {bool isNullAware});
+  withReceiver(Object? receiver, int operatorOffset, {bool isNullAware: false});
 
-  List<UnresolvedType> get typeArguments => null;
+  List<UnresolvedType>? get typeArguments => null;
 
   bool get isTypeArgumentsInForest => true;
 
-  Arguments get arguments => null;
+  Arguments? get arguments => null;
 }
 
 class IncompleteErrorGenerator extends ErroneousExpressionGenerator
@@ -4413,15 +4472,13 @@
       ExpressionGeneratorHelper helper, Token token, this.message)
       : super(helper, token);
 
-  Name get name => null;
-
   String get _plainNameForRead => token.lexeme;
 
   String get _debugName => "IncompleteErrorGenerator";
 
   @override
   Expression buildError(Arguments arguments,
-      {bool isGetter: false, bool isSetter: false, int offset}) {
+      {bool isGetter: false, bool isSetter: false, int? offset}) {
     int length = noLength;
     if (offset == null) {
       offset = fileOffset;
@@ -4432,7 +4489,7 @@
 
   @override
   doInvocation(
-          int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+          int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
           {bool isTypeArgumentsInForest = false}) =>
       this;
 
@@ -4455,7 +4512,7 @@
   final Name name;
 
   @override
-  final List<UnresolvedType> typeArguments;
+  final List<UnresolvedType>? typeArguments;
 
   @override
   final bool isTypeArgumentsInForest;
@@ -4469,6 +4526,7 @@
       this.typeArguments, this.arguments,
       {this.isPotentiallyConstant = false, this.isTypeArgumentsInForest = true})
       : super(helper, token) {
+    // ignore: unnecessary_null_comparison
     assert(arguments != null);
   }
 
@@ -4484,7 +4542,8 @@
     return unsupported("buildAssignment", fileOffset, _uri);
   }
 
-  withReceiver(Object receiver, int operatorOffset, {bool isNullAware: false}) {
+  withReceiver(Object? receiver, int operatorOffset,
+      {bool isNullAware: false}) {
     if (receiver is Generator) {
       return receiver.buildPropertyAccess(this, operatorOffset, isNullAware);
     }
@@ -4503,28 +4562,29 @@
       bool voidContext: false,
       bool isPreIncDec: false,
       bool isPostIncDec: false}) {
-    return unsupported("buildCompoundAssignment", offset ?? fileOffset, _uri);
+    return unsupported("buildCompoundAssignment", offset, _uri);
   }
 
   Expression buildPrefixIncrement(Name binaryOperator,
       {int offset: TreeNode.noOffset, bool voidContext: false}) {
-    return unsupported("buildPrefixIncrement", offset ?? fileOffset, _uri);
+    return unsupported("buildPrefixIncrement", offset, _uri);
   }
 
   Expression buildPostfixIncrement(Name binaryOperator,
       {int offset: TreeNode.noOffset, bool voidContext: false}) {
-    return unsupported("buildPostfixIncrement", offset ?? fileOffset, _uri);
+    return unsupported("buildPostfixIncrement", offset, _uri);
   }
 
   Expression doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     return unsupported("doInvocation", offset, _uri);
   }
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     return unsupported("buildIndexedAccess", offsetForToken(token), _uri);
   }
@@ -4563,7 +4623,8 @@
     return unsupported("buildAssignment", fileOffset, _uri);
   }
 
-  withReceiver(Object receiver, int operatorOffset, {bool isNullAware: false}) {
+  withReceiver(Object? receiver, int operatorOffset,
+      {bool isNullAware: false}) {
     if (receiver is Generator) {
       return receiver.buildPropertyAccess(this, operatorOffset, isNullAware);
     }
@@ -4581,28 +4642,29 @@
       bool voidContext: false,
       bool isPreIncDec: false,
       bool isPostIncDec: false}) {
-    return unsupported("buildCompoundAssignment", offset ?? fileOffset, _uri);
+    return unsupported("buildCompoundAssignment", offset, _uri);
   }
 
   Expression buildPrefixIncrement(Name binaryOperator,
       {int offset: TreeNode.noOffset, bool voidContext: false}) {
-    return unsupported("buildPrefixIncrement", offset ?? fileOffset, _uri);
+    return unsupported("buildPrefixIncrement", offset, _uri);
   }
 
   Expression buildPostfixIncrement(Name binaryOperator,
       {int offset: TreeNode.noOffset, bool voidContext: false}) {
-    return unsupported("buildPostfixIncrement", offset ?? fileOffset, _uri);
+    return unsupported("buildPostfixIncrement", offset, _uri);
   }
 
   Expression doInvocation(
-      int offset, List<UnresolvedType> typeArguments, Arguments arguments,
+      int offset, List<UnresolvedType>? typeArguments, Arguments arguments,
       {bool isTypeArgumentsInForest = false}) {
     return unsupported("doInvocation", offset, _uri);
   }
 
   @override
   Generator buildIndexedAccess(Expression index, Token token,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     return unsupported("buildIndexedAccess", offsetForToken(token), _uri);
   }
@@ -4629,11 +4691,15 @@
 ///
 // TODO(johnniwinther): Remove this in favor of [ParenthesizedExpression] when
 // the [TypePromoter] is replaced by [FlowAnalysis].
-class ParenthesizedExpressionGenerator extends ReadOnlyAccessGenerator {
+class ParenthesizedExpressionGenerator extends AbstractReadOnlyAccessGenerator {
+  final Expression expression;
+
   ParenthesizedExpressionGenerator(
-      ExpressionGeneratorHelper helper, Token token, Expression expression)
-      : super(helper, token, expression, null,
-            ReadOnlyAccessKind.ParenthesizedExpression);
+      ExpressionGeneratorHelper helper, Token token, this.expression)
+      : super(helper, token, ReadOnlyAccessKind.ParenthesizedExpression);
+
+  @override
+  String get targetName => '';
 
   @override
   Expression buildSimpleRead() => expression;
@@ -4663,12 +4729,12 @@
   }
 }
 
-int adjustForImplicitCall(String name, int offset) {
+int adjustForImplicitCall(String? name, int offset) {
   // Normally the offset is at the start of the token, but in this case,
   // because we insert a '.call', we want it at the end instead.
   return offset + (name?.length ?? 0);
 }
 
-bool isFieldOrGetter(Member member) {
+bool isFieldOrGetter(Member? member) {
   return member is Field || (member is Procedure && member.isGetter);
 }
diff --git a/pkg/front_end/lib/src/fasta/kernel/expression_generator_helper.dart b/pkg/front_end/lib/src/fasta/kernel/expression_generator_helper.dart
index 79ff03f..1ad1ecb 100644
--- a/pkg/front_end/lib/src/fasta/kernel/expression_generator_helper.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/expression_generator_helper.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.expression_generator_helper;
 
 import 'package:_fe_analyzer_shared/src/scanner/token.dart' show Token;
@@ -16,21 +14,14 @@
 import '../builder/unresolved_type.dart';
 
 import '../constant_context.dart' show ConstantContext;
-
 import '../fasta_codes.dart' show LocatedMessage;
-
 import '../messages.dart' show Message;
-
-import '../scope.dart' show Scope;
-
+import '../scope.dart';
 import '../type_inference/inference_helper.dart' show InferenceHelper;
 
 import 'constness.dart' show Constness;
-
 import 'forest.dart' show Forest;
-
-import '../scope.dart';
-
+import 'internal_ast.dart';
 import 'kernel_ast_api.dart'
     show
         Arguments,
@@ -43,6 +34,7 @@
         Name,
         Procedure,
         StaticGet,
+        TreeNode,
         TypeParameter,
         VariableDeclaration;
 
@@ -53,11 +45,11 @@
 
   Forest get forest;
 
-  Constructor lookupConstructor(Name name, {bool isSuper});
+  Constructor? lookupConstructor(Name name, {bool isSuper: false});
 
-  Expression toValue(node);
+  Expression toValue(Object? node);
 
-  Member lookupInstanceMember(Name name, {bool isSetter, bool isSuper});
+  Member? lookupInstanceMember(Name name, {bool isSetter, bool isSuper});
 
   /// `true` if we are in the type of an as expression.
   bool get inIsOrAsOperatorType;
@@ -68,33 +60,36 @@
 
   bool get enableConstructorTearOffsInLibrary;
 
-  scopeLookup(Scope scope, String name, Token token,
-      {bool isQualified: false, PrefixBuilder prefix});
+  /* Generator | Expression | Builder */ scopeLookup(
+      Scope scope, String name, Token token,
+      {bool isQualified: false, PrefixBuilder? prefix});
 
-  finishSend(Object receiver, List<UnresolvedType> typeArguments,
-      Arguments arguments, int offset,
+  /* Expression | Generator | Initializer */ finishSend(Object receiver,
+      List<UnresolvedType>? typeArguments, Arguments arguments, int offset,
       {bool isTypeArgumentsInForest = false});
 
-  Initializer buildInvalidInitializer(Expression expression, [int offset]);
+  Initializer buildInvalidInitializer(Expression expression,
+      [int offset = TreeNode.noOffset]);
 
   List<Initializer> buildFieldInitializer(String name, int fieldNameOffset,
       int assignmentOffset, Expression expression,
-      {FormalParameterBuilder formal});
+      {FormalParameterBuilder? formal});
 
   Initializer buildSuperInitializer(
       bool isSynthetic, Constructor constructor, Arguments arguments,
-      [int offset]);
+      [int offset = TreeNode.noOffset]);
 
   Initializer buildRedirectingInitializer(
       Constructor constructor, Arguments arguments,
-      [int charOffset = -1]);
+      [int charOffset = TreeNode.noOffset]);
 
-  Expression buildStaticInvocation(Procedure target, Arguments arguments,
-      {Constness constness, int charOffset});
+  Expression buildStaticInvocation(Member target, Arguments arguments,
+      {Constness constness: Constness.implicit,
+      int charOffset: TreeNode.noOffset});
 
   Expression buildExtensionMethodInvocation(
       int fileOffset, Procedure target, Arguments arguments,
-      {bool isTearOff});
+      {required bool isTearOff});
 
   Expression throwNoSuchMethodError(
       Expression receiver, String name, Arguments arguments, int offset,
@@ -105,7 +100,7 @@
       bool isStatic,
       LocatedMessage message});
 
-  LocatedMessage checkArgumentsForFunction(FunctionNode function,
+  LocatedMessage? checkArgumentsForFunction(FunctionNode function,
       Arguments arguments, int offset, List<TypeParameter> typeParameters);
 
   StaticGet makeStaticGet(Member readTarget, Token token);
@@ -113,59 +108,64 @@
   Expression wrapInDeferredCheck(
       Expression expression, PrefixBuilder prefix, int charOffset);
 
-  bool isIdentical(Member member);
+  bool isIdentical(Member? member);
 
   Expression buildMethodInvocation(
       Expression receiver, Name name, Arguments arguments, int offset,
-      {bool isConstantExpression, bool isNullAware, bool isSuper});
+      {bool isConstantExpression: false,
+      bool isNullAware: false,
+      bool isSuper: false});
 
   Expression buildConstructorInvocation(
       TypeDeclarationBuilder type,
       Token nameToken,
       Token nameLastToken,
-      Arguments arguments,
+      Arguments? arguments,
       String name,
-      List<UnresolvedType> typeArguments,
+      List<UnresolvedType>? typeArguments,
       int charOffset,
       Constness constness,
       {bool isTypeArgumentsInForest = false,
-      TypeDeclarationBuilder typeAliasBuilder});
+      TypeDeclarationBuilder? typeAliasBuilder});
 
   UnresolvedType validateTypeUse(UnresolvedType unresolved,
-      {bool nonInstanceAccessIsError, bool allowPotentiallyConstantType});
+      {required bool nonInstanceAccessIsError,
+      required bool allowPotentiallyConstantType});
 
   void addProblemErrorIfConst(Message message, int charOffset, int length);
 
   Expression buildProblemErrorIfConst(
       Message message, int charOffset, int length);
 
-  Message warnUnresolvedGet(Name name, int charOffset, {bool isSuper});
+  Message warnUnresolvedGet(Name name, int charOffset, {bool isSuper: false});
 
-  Message warnUnresolvedSet(Name name, int charOffset, {bool isSuper});
+  Message warnUnresolvedSet(Name name, int charOffset, {bool isSuper: false});
 
-  Message warnUnresolvedMethod(Name name, int charOffset, {bool isSuper});
+  Message warnUnresolvedMethod(Name name, int charOffset,
+      {bool isSuper: false});
 
   void warnTypeArgumentsMismatch(String name, int expected, int charOffset);
 
   Expression wrapInLocatedProblem(Expression expression, LocatedMessage message,
-      {List<LocatedMessage> context});
+      {List<LocatedMessage>? context});
 
   Expression evaluateArgumentsBefore(
       Arguments arguments, Expression expression);
 
   DartType buildDartType(UnresolvedType unresolvedType,
-      {bool nonInstanceAccessIsError});
+      {bool nonInstanceAccessIsError: false});
 
   DartType buildTypeLiteralDartType(UnresolvedType unresolvedType,
       {bool nonInstanceAccessIsError});
 
-  List<DartType> buildDartTypeArguments(List<UnresolvedType> unresolvedTypes);
+  List<DartType> buildDartTypeArguments(List<UnresolvedType>? unresolvedTypes);
 
   void reportDuplicatedDeclaration(
       Builder existing, String name, int charOffset);
 
   /// Creates a synthetic variable declaration for the value of [expression].
-  VariableDeclaration createVariableDeclarationForValue(Expression expression);
+  VariableDeclarationImpl createVariableDeclarationForValue(
+      Expression expression);
 
   /// Creates a [VariableGet] of the [variable] using [charOffset] as the file
   /// offset of the created node.
diff --git a/pkg/front_end/lib/src/fasta/kernel/forest.dart b/pkg/front_end/lib/src/fasta/kernel/forest.dart
index f6be413..b53d108 100644
--- a/pkg/front_end/lib/src/fasta/kernel/forest.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/forest.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.fangorn;
 
 import 'package:kernel/ast.dart';
@@ -11,6 +9,8 @@
 
 import '../problems.dart' show unsupported;
 
+import '../type_inference/type_schema.dart';
+
 import 'collections.dart'
     show
         ForElement,
@@ -28,17 +28,19 @@
   const Forest();
 
   Arguments createArguments(int fileOffset, List<Expression> positional,
-      {List<DartType> types,
-      List<NamedExpression> named,
+      {List<DartType>? types,
+      List<NamedExpression>? named,
       bool hasExplicitTypeArguments = true}) {
+    // ignore: unnecessary_null_comparison
+    assert(fileOffset != null);
     if (!hasExplicitTypeArguments) {
       ArgumentsImpl arguments =
           new ArgumentsImpl(positional, types: <DartType>[], named: named);
-      arguments.types.addAll(types);
+      arguments.types.addAll(types!);
       return arguments;
     } else {
       return new ArgumentsImpl(positional, types: types, named: named)
-        ..fileOffset = fileOffset ?? TreeNode.noOffset;
+        ..fileOffset = fileOffset;
     }
   }
 
@@ -48,10 +50,11 @@
       int typeParameterCount,
       Expression receiver,
       {List<DartType> extensionTypeArguments = const <DartType>[],
-      int extensionTypeArgumentOffset,
+      int? extensionTypeArgumentOffset,
       List<DartType> typeArguments = const <DartType>[],
       List<Expression> positionalArguments = const <Expression>[],
       List<NamedExpression> namedArguments = const <NamedExpression>[]}) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new ArgumentsImpl.forExtensionMethod(
         extensionTypeParameterCount, typeParameterCount, receiver,
@@ -60,10 +63,11 @@
         typeArguments: typeArguments,
         positionalArguments: positionalArguments,
         namedArguments: namedArguments)
-      ..fileOffset = fileOffset ?? TreeNode.noOffset;
+      ..fileOffset = fileOffset;
   }
 
   Arguments createArgumentsEmpty(int fileOffset) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return createArguments(fileOffset, <Expression>[]);
   }
@@ -81,12 +85,14 @@
   }
 
   void argumentsSetTypeArguments(Arguments arguments, List<DartType> types) {
-    ArgumentsImpl.setNonInferrableArgumentTypes(arguments, types);
+    ArgumentsImpl.setNonInferrableArgumentTypes(
+        arguments as ArgumentsImpl, types);
   }
 
   /// Return a representation of a boolean literal at the given [fileOffset].
   /// The literal has the given [value].
   BoolLiteral createBoolLiteral(int fileOffset, bool value) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new BoolLiteral(value)..fileOffset = fileOffset;
   }
@@ -94,18 +100,21 @@
   /// Return a representation of a double literal at the given [fileOffset]. The
   /// literal has the given [value].
   DoubleLiteral createDoubleLiteral(int fileOffset, double value) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new DoubleLiteral(value)..fileOffset = fileOffset;
   }
 
   /// Return a representation of an integer literal at the given [fileOffset].
   /// The literal has the given [value].
-  IntLiteral createIntLiteral(int fileOffset, int value, [String literal]) {
+  IntLiteral createIntLiteral(int fileOffset, int value, [String? literal]) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new IntJudgment(value, literal)..fileOffset = fileOffset;
   }
 
   IntLiteral createIntLiteralLarge(int fileOffset, String literal) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new ShadowLargeIntLiteral(literal, fileOffset);
   }
@@ -119,8 +128,10 @@
   /// representations of the list elements.
   ListLiteral createListLiteral(
       int fileOffset, DartType typeArgument, List<Expression> expressions,
-      {bool isConst}) {
+      {required bool isConst}) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
+    // ignore: unnecessary_null_comparison
     assert(isConst != null);
     return new ListLiteral(expressions,
         typeArgument: typeArgument, isConst: isConst)
@@ -136,8 +147,10 @@
   /// representations of the set elements.
   SetLiteral createSetLiteral(
       int fileOffset, DartType typeArgument, List<Expression> expressions,
-      {bool isConst}) {
+      {required bool isConst}) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
+    // ignore: unnecessary_null_comparison
     assert(isConst != null);
     return new SetLiteral(expressions,
         typeArgument: typeArgument, isConst: isConst)
@@ -155,8 +168,10 @@
   /// list of the representations of the map entries.
   MapLiteral createMapLiteral(int fileOffset, DartType keyType,
       DartType valueType, List<MapLiteralEntry> entries,
-      {bool isConst}) {
+      {required bool isConst}) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
+    // ignore: unnecessary_null_comparison
     assert(isConst != null);
     return new MapLiteral(entries,
         keyType: keyType, valueType: valueType, isConst: isConst)
@@ -165,6 +180,7 @@
 
   /// Return a representation of a null literal at the given [fileOffset].
   NullLiteral createNullLiteral(int fileOffset) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new NullLiteral()..fileOffset = fileOffset;
   }
@@ -173,6 +189,7 @@
   /// [fileOffset]. The literal has the given [value]. This does not include
   /// either adjacent strings or interpolated strings.
   StringLiteral createStringLiteral(int fileOffset, String value) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new StringLiteral(value)..fileOffset = fileOffset;
   }
@@ -180,11 +197,13 @@
   /// Return a representation of a symbol literal defined by [value] at the
   /// given [fileOffset].
   SymbolLiteral createSymbolLiteral(int fileOffset, String value) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new SymbolLiteral(value)..fileOffset = fileOffset;
   }
 
   TypeLiteral createTypeLiteral(int fileOffset, DartType type) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new TypeLiteral(type)..fileOffset = fileOffset;
   }
@@ -195,26 +214,31 @@
   /// to compute the value.
   MapLiteralEntry createMapEntry(
       int fileOffset, Expression key, Expression value) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new MapLiteralEntry(key, value)..fileOffset = fileOffset;
   }
 
-  Expression createLoadLibrary(
-      int fileOffset, LibraryDependency dependency, Arguments arguments) {
+  LoadLibrary createLoadLibrary(
+      int fileOffset, LibraryDependency dependency, Arguments? arguments) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new LoadLibraryImpl(dependency, arguments)..fileOffset = fileOffset;
   }
 
   Expression checkLibraryIsLoaded(
       int fileOffset, LibraryDependency dependency) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new CheckLibraryIsLoaded(dependency)..fileOffset = fileOffset;
   }
 
   Expression createAsExpression(
       int fileOffset, Expression expression, DartType type,
-      {bool forNonNullableByDefault}) {
+      {required bool forNonNullableByDefault}) {
+    // ignore: unnecessary_null_comparison
     assert(forNonNullableByDefault != null);
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new AsExpression(expression, type)
       ..fileOffset = fileOffset
@@ -222,8 +246,10 @@
   }
 
   Expression createSpreadElement(int fileOffset, Expression expression,
-      {bool isNullAware}) {
+      {required bool isNullAware}) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
+    // ignore: unnecessary_null_comparison
     assert(isNullAware != null);
     return new SpreadElement(expression, isNullAware: isNullAware)
       ..fileOffset = fileOffset;
@@ -231,49 +257,54 @@
 
   Expression createIfElement(
       int fileOffset, Expression condition, Expression then,
-      [Expression otherwise]) {
+      [Expression? otherwise]) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new IfElement(condition, then, otherwise)..fileOffset = fileOffset;
   }
 
   MapLiteralEntry createIfMapEntry(
       int fileOffset, Expression condition, MapLiteralEntry then,
-      [MapLiteralEntry otherwise]) {
+      [MapLiteralEntry? otherwise]) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new IfMapEntry(condition, then, otherwise)..fileOffset = fileOffset;
   }
 
-  Expression createForElement(
+  ForElement createForElement(
       int fileOffset,
       List<VariableDeclaration> variables,
-      Expression condition,
+      Expression? condition,
       List<Expression> updates,
       Expression body) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new ForElement(variables, condition, updates, body)
       ..fileOffset = fileOffset;
   }
 
-  MapLiteralEntry createForMapEntry(
+  ForMapEntry createForMapEntry(
       int fileOffset,
       List<VariableDeclaration> variables,
-      Expression condition,
+      Expression? condition,
       List<Expression> updates,
       MapLiteralEntry body) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new ForMapEntry(variables, condition, updates, body)
       ..fileOffset = fileOffset;
   }
 
-  Expression createForInElement(
+  ForInElement createForInElement(
       int fileOffset,
       VariableDeclaration variable,
       Expression iterable,
-      Expression synthesizedAssignment,
-      Statement expressionEffects,
+      Expression? synthesizedAssignment,
+      Statement? expressionEffects,
       Expression body,
-      Expression problem,
+      Expression? problem,
       {bool isAsync: false}) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new ForInElement(variable, iterable, synthesizedAssignment,
         expressionEffects, body, problem,
@@ -281,15 +312,16 @@
       ..fileOffset = fileOffset;
   }
 
-  MapLiteralEntry createForInMapEntry(
+  ForInMapEntry createForInMapEntry(
       int fileOffset,
       VariableDeclaration variable,
       Expression iterable,
-      Expression synthesizedAssignment,
-      Statement expressionEffects,
+      Expression? synthesizedAssignment,
+      Statement? expressionEffects,
       MapLiteralEntry body,
-      Expression problem,
+      Expression? problem,
       {bool isAsync: false}) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new ForInMapEntry(variable, iterable, synthesizedAssignment,
         expressionEffects, body, problem,
@@ -301,13 +333,15 @@
   /// initializer list.
   AssertInitializer createAssertInitializer(
       int fileOffset, AssertStatement assertStatement) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new AssertInitializer(assertStatement)..fileOffset = fileOffset;
   }
 
   /// Return a representation of an assert that appears as a statement.
-  Statement createAssertStatement(int fileOffset, Expression condition,
-      Expression message, int conditionStartOffset, int conditionEndOffset) {
+  AssertStatement createAssertStatement(int fileOffset, Expression condition,
+      Expression? message, int conditionStartOffset, int conditionEndOffset) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new AssertStatement(condition,
         conditionStartOffset: conditionStartOffset,
@@ -317,6 +351,7 @@
   }
 
   Expression createAwaitExpression(int fileOffset, Expression operand) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new AwaitExpression(operand)..fileOffset = fileOffset;
   }
@@ -325,8 +360,9 @@
   /// [fileOffset].
   Statement createBlock(
       int fileOffset, int fileEndOffset, List<Statement> statements) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
-    List<Statement> copy;
+    List<Statement>? copy;
     for (int i = 0; i < statements.length; i++) {
       Statement statement = statements[i];
       if (statement is _VariablesDeclaration) {
@@ -342,7 +378,8 @@
   }
 
   /// Return a representation of a break statement.
-  Statement createBreakStatement(int fileOffset, Object label) {
+  Statement createBreakStatement(int fileOffset, Object? label) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     // TODO(johnniwinther): Use [label]?
     return new BreakStatementImpl(isContinue: false)..fileOffset = fileOffset;
@@ -352,10 +389,11 @@
   Catch createCatch(
       int fileOffset,
       DartType exceptionType,
-      VariableDeclaration exceptionParameter,
-      VariableDeclaration stackTraceParameter,
+      VariableDeclaration? exceptionParameter,
+      VariableDeclaration? stackTraceParameter,
       DartType stackTraceType,
       Statement body) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new Catch(exceptionParameter, body,
         guard: exceptionType, stackTrace: stackTraceParameter)
@@ -369,12 +407,13 @@
   Expression createConditionalExpression(int fileOffset, Expression condition,
       Expression thenExpression, Expression elseExpression) {
     return new ConditionalExpression(
-        condition, thenExpression, elseExpression, null)
+        condition, thenExpression, elseExpression, const UnknownType())
       ..fileOffset = fileOffset;
   }
 
   /// Return a representation of a continue statement.
-  Statement createContinueStatement(int fileOffset, Object label) {
+  Statement createContinueStatement(int fileOffset, Object? label) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     // TODO(johnniwinther): Use [label]?
     return new BreakStatementImpl(isContinue: true)..fileOffset = fileOffset;
@@ -383,6 +422,7 @@
   /// Return a representation of a do statement.
   Statement createDoStatement(
       int fileOffset, Statement body, Expression condition) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new DoStatement(body, condition)..fileOffset = fileOffset;
   }
@@ -390,12 +430,14 @@
   /// Return a representation of an expression statement at the given
   /// [fileOffset] containing the [expression].
   Statement createExpressionStatement(int fileOffset, Expression expression) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new ExpressionStatement(expression)..fileOffset = fileOffset;
   }
 
   /// Return a representation of an empty statement  at the given [fileOffset].
   Statement createEmptyStatement(int fileOffset) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new EmptyStatement()..fileOffset = fileOffset;
   }
@@ -403,10 +445,11 @@
   /// Return a representation of a for statement.
   Statement createForStatement(
       int fileOffset,
-      List<VariableDeclaration> variables,
-      Expression condition,
+      List<VariableDeclaration>? variables,
+      Expression? condition,
       List<Expression> updaters,
       Statement body) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new ForStatement(variables ?? [], condition, updaters, body)
       ..fileOffset = fileOffset;
@@ -414,7 +457,8 @@
 
   /// Return a representation of an `if` statement.
   Statement createIfStatement(int fileOffset, Expression condition,
-      Statement thenStatement, Statement elseStatement) {
+      Statement thenStatement, Statement? elseStatement) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new IfStatement(condition, thenStatement, elseStatement)
       ..fileOffset = fileOffset;
@@ -426,8 +470,10 @@
   /// is non-null the test is negated the that file offset.
   Expression createIsExpression(
       int fileOffset, Expression operand, DartType type,
-      {bool forNonNullableByDefault, int notFileOffset}) {
+      {required bool forNonNullableByDefault, int? notFileOffset}) {
+    // ignore: unnecessary_null_comparison
     assert(forNonNullableByDefault != null);
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     Expression result = new IsExpression(operand, type)
       ..fileOffset = fileOffset
@@ -443,6 +489,7 @@
   /// (either `&&` or `||`).
   Expression createLogicalExpression(int fileOffset, Expression leftOperand,
       String operatorString, Expression rightOperand) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     LogicalExpressionOperator operator;
     if (operatorString == '&&') {
@@ -459,6 +506,7 @@
   }
 
   Expression createNot(int fileOffset, Expression operand) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new Not(operand)..fileOffset = fileOffset;
   }
@@ -467,7 +515,9 @@
   /// rethrow at [rethrowFileOffset] and the statement at [statementFileOffset].
   Statement createRethrowStatement(
       int rethrowFileOffset, int statementFileOffset) {
+    // ignore: unnecessary_null_comparison
     assert(rethrowFileOffset != null);
+    // ignore: unnecessary_null_comparison
     assert(statementFileOffset != null);
     return new ExpressionStatement(
         new Rethrow()..fileOffset = rethrowFileOffset)
@@ -475,15 +525,17 @@
   }
 
   /// Return a representation of a return statement.
-  Statement createReturnStatement(int fileOffset, Expression expression,
+  Statement createReturnStatement(int fileOffset, Expression? expression,
       {bool isArrow: true}) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new ReturnStatementImpl(isArrow, expression)
-      ..fileOffset = fileOffset ?? TreeNode.noOffset;
+      ..fileOffset = fileOffset;
   }
 
   Expression createStringConcatenation(
       int fileOffset, List<Expression> expressions) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     assert(fileOffset != TreeNode.noOffset);
     return new StringConcatenation(expressions)..fileOffset = fileOffset;
@@ -492,25 +544,28 @@
   /// The given [statement] is being used as the target of either a break or
   /// continue statement. Return the statement that should be used as the actual
   /// target.
-  Statement createLabeledStatement(Statement statement) {
+  LabeledStatement createLabeledStatement(Statement statement) {
     return new LabeledStatement(statement)..fileOffset = statement.fileOffset;
   }
 
   Expression createThisExpression(int fileOffset) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new ThisExpression()..fileOffset = fileOffset;
   }
 
   /// Return a representation of a throw expression at the given [fileOffset].
   Expression createThrow(int fileOffset, Expression expression) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new Throw(expression)..fileOffset = fileOffset;
   }
 
-  bool isThrow(Object o) => o is Throw;
+  bool isThrow(Object? o) => o is Throw;
 
   Statement createTryStatement(int fileOffset, Statement tryBlock,
-      List<Catch> catchBlocks, Statement finallyBlock) {
+      List<Catch>? catchBlocks, Statement? finallyBlock) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new TryStatement(tryBlock, catchBlocks ?? <Catch>[], finallyBlock)
       ..fileOffset = fileOffset;
@@ -522,8 +577,8 @@
   }
 
   List<VariableDeclaration> variablesDeclarationExtractDeclarations(
-      _VariablesDeclaration variablesDeclaration) {
-    return variablesDeclaration.declarations;
+      Object? variablesDeclaration) {
+    return (variablesDeclaration as _VariablesDeclaration).declarations;
   }
 
   Statement wrapVariables(Statement statement) {
@@ -543,6 +598,7 @@
   /// consisting of the given [condition] and [body].
   Statement createWhileStatement(
       int fileOffset, Expression condition, Statement body) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new WhileStatement(condition, body)..fileOffset = fileOffset;
   }
@@ -551,16 +607,16 @@
   /// of the given [expression]. If [isYieldStar] is `true` the created
   /// statement is a yield* statement.
   Statement createYieldStatement(int fileOffset, Expression expression,
-      {bool isYieldStar}) {
+      {required bool isYieldStar}) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
+    // ignore: unnecessary_null_comparison
     assert(isYieldStar != null);
     return new YieldStatement(expression, isYieldStar: isYieldStar)
       ..fileOffset = fileOffset;
   }
 
-  bool isBlock(Object node) => node is Block;
-
-  bool isErroneousNode(Object node) {
+  bool isErroneousNode(Object? node) {
     if (node is ExpressionStatement) {
       ExpressionStatement statement = node;
       node = statement.expression;
@@ -578,19 +634,20 @@
 
   bool isThisExpression(Object node) => node is ThisExpression;
 
-  bool isVariablesDeclaration(Object node) => node is _VariablesDeclaration;
+  bool isVariablesDeclaration(Object? node) => node is _VariablesDeclaration;
 
   /// Creates [VariableDeclaration] for a variable named [name] at the given
   /// [functionNestingLevel].
   VariableDeclaration createVariableDeclaration(
-      int fileOffset, String name, int functionNestingLevel,
-      {Expression initializer,
-      DartType type,
+      int fileOffset, String? name, int functionNestingLevel,
+      {Expression? initializer,
+      DartType? type,
       bool isFinal: false,
       bool isConst: false,
       bool isFieldFormal: false,
       bool isCovariant: false,
       bool isLocalFunction: false}) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new VariableDeclarationImpl(name, functionNestingLevel,
         type: type,
@@ -603,7 +660,8 @@
         hasDeclaredInitializer: initializer != null);
   }
 
-  VariableDeclaration createVariableDeclarationForValue(Expression initializer,
+  VariableDeclarationImpl createVariableDeclarationForValue(
+      Expression initializer,
       {DartType type = const DynamicType()}) {
     return new VariableDeclarationImpl.forValue(initializer)
       ..type = type
@@ -615,13 +673,14 @@
   }
 
   FunctionNode createFunctionNode(int fileOffset, Statement body,
-      {List<TypeParameter> typeParameters,
-      List<VariableDeclaration> positionalParameters,
-      List<VariableDeclaration> namedParameters,
-      int requiredParameterCount,
+      {List<TypeParameter>? typeParameters,
+      List<VariableDeclaration>? positionalParameters,
+      List<VariableDeclaration>? namedParameters,
+      int? requiredParameterCount,
       DartType returnType: const DynamicType(),
       AsyncMarker asyncMarker: AsyncMarker.Sync,
-      AsyncMarker dartAsyncMarker}) {
+      AsyncMarker? dartAsyncMarker}) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new FunctionNode(body,
         typeParameters: typeParameters,
@@ -650,12 +709,14 @@
 
   FunctionExpression createFunctionExpression(
       int fileOffset, FunctionNode function) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new FunctionExpression(function)..fileOffset = fileOffset;
   }
 
   Expression createExpressionInvocation(
       int fileOffset, Expression expression, Arguments arguments) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new ExpressionInvocation(expression, arguments)
       ..fileOffset = fileOffset;
@@ -663,6 +724,7 @@
 
   MethodInvocation createMethodInvocation(
       int fileOffset, Expression expression, Name name, Arguments arguments) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new MethodInvocation(expression, name, arguments)
       ..fileOffset = fileOffset;
@@ -670,56 +732,62 @@
 
   NamedExpression createNamedExpression(
       int fileOffset, String name, Expression expression) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new NamedExpression(name, expression)..fileOffset = fileOffset;
   }
 
   StaticInvocation createStaticInvocation(
       int fileOffset, Procedure procedure, Arguments arguments) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new StaticInvocation(procedure, arguments)..fileOffset = fileOffset;
   }
 
   SuperMethodInvocation createSuperMethodInvocation(
-      int fileOffset, Name name, Procedure procedure, Arguments arguments) {
+      int fileOffset, Name name, Procedure? procedure, Arguments arguments) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new SuperMethodInvocation(name, arguments, procedure)
       ..fileOffset = fileOffset;
   }
 
   NullCheck createNullCheck(int fileOffset, Expression expression) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new NullCheck(expression)..fileOffset = fileOffset;
   }
 
-  PropertyGet createPropertyGet(int fileOffset, Expression receiver, Name name,
-      {Member interfaceTarget}) {
+  PropertyGet createPropertyGet(
+      int fileOffset, Expression receiver, Name name) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
-    return new PropertyGet(receiver, name, interfaceTarget)
-      ..fileOffset = fileOffset;
+    return new PropertyGet(receiver, name)..fileOffset = fileOffset;
   }
 
   PropertySet createPropertySet(
       int fileOffset, Expression receiver, Name name, Expression value,
-      {Member interfaceTarget, bool forEffect, bool readOnlyReceiver: false}) {
+      {required bool forEffect, bool readOnlyReceiver: false}) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new PropertySetImpl(receiver, name, value,
-        interfaceTarget: interfaceTarget,
-        forEffect: forEffect,
-        readOnlyReceiver: readOnlyReceiver)
+        forEffect: forEffect, readOnlyReceiver: readOnlyReceiver)
       ..fileOffset = fileOffset;
   }
 
   IndexGet createIndexGet(
       int fileOffset, Expression receiver, Expression index) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new IndexGet(receiver, index)..fileOffset = fileOffset;
   }
 
   IndexSet createIndexSet(
       int fileOffset, Expression receiver, Expression index, Expression value,
-      {bool forEffect}) {
+      {required bool forEffect}) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
+    // ignore: unnecessary_null_comparison
     assert(forEffect != null);
     return new IndexSet(receiver, index, value, forEffect: forEffect)
       ..fileOffset = fileOffset;
@@ -727,8 +795,10 @@
 
   EqualsExpression createEquals(
       int fileOffset, Expression left, Expression right,
-      {bool isNot}) {
+      {required bool isNot}) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
+    // ignore: unnecessary_null_comparison
     assert(isNot != null);
     return new EqualsExpression(left, right, isNot: isNot)
       ..fileOffset = fileOffset;
@@ -736,6 +806,7 @@
 
   BinaryExpression createBinary(
       int fileOffset, Expression left, Name binaryName, Expression right) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new BinaryExpression(left, binaryName, right)
       ..fileOffset = fileOffset;
@@ -743,18 +814,21 @@
 
   UnaryExpression createUnary(
       int fileOffset, Name unaryName, Expression expression) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new UnaryExpression(unaryName, expression)..fileOffset = fileOffset;
   }
 
   ParenthesizedExpression createParenthesized(
       int fileOffset, Expression expression) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new ParenthesizedExpression(expression)..fileOffset = fileOffset;
   }
 
   ConstructorTearOff createConstructorTearOff(
       int fileOffset, Constructor constructor) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     return new ConstructorTearOff(constructor)..fileOffset = fileOffset;
   }
diff --git a/pkg/front_end/lib/src/fasta/kernel/forwarding_node.dart b/pkg/front_end/lib/src/fasta/kernel/forwarding_node.dart
index 590534c..43f0293 100644
--- a/pkg/front_end/lib/src/fasta/kernel/forwarding_node.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/forwarding_node.dart
@@ -2,8 +2,6 @@
 // for 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 "package:kernel/ast.dart"
     show
         Arguments,
@@ -38,9 +36,9 @@
 
   final ProcedureKind kind;
 
-  final ClassMember _superClassMember;
+  final ClassMember? _superClassMember;
 
-  final ClassMember _mixedInMember;
+  final ClassMember? _mixedInMember;
 
   ForwardingNode(this._combinedMemberSignature, this.kind,
       this._superClassMember, this._mixedInMember);
@@ -49,7 +47,7 @@
   /// forwarding stubs if necessary.
   ///
   /// If a stub is created, this is returned. Otherwise `null` is returned.
-  Procedure finalize() => _computeCovarianceFixes();
+  Procedure? finalize() => _computeCovarianceFixes();
 
   /// Tag the parameters of [interfaceMember] that need type checks
   ///
@@ -63,9 +61,9 @@
   /// stub is introduced as a place to put the checks.
   ///
   /// If a stub is created, this is returned. Otherwise `null` is returned.
-  Procedure _computeCovarianceFixes() {
+  Procedure? _computeCovarianceFixes() {
     SourceClassBuilder classBuilder = _combinedMemberSignature.classBuilder;
-    ClassMember canonicalMember = _combinedMemberSignature.canonicalMember;
+    ClassMember canonicalMember = _combinedMemberSignature.canonicalMember!;
     Member interfaceMember =
         canonicalMember.getMember(_combinedMemberSignature.hierarchy);
 
@@ -101,11 +99,11 @@
             needsTypeOrCovarianceUpdate) ||
         needMixinStub;
     bool needsSuperImpl = _superClassMember != null &&
-        _superClassMember.getCovariance(_combinedMemberSignature.hierarchy) !=
+        _superClassMember!.getCovariance(_combinedMemberSignature.hierarchy) !=
             _combinedMemberSignature.combinedMemberSignatureCovariance;
     if (stubNeeded) {
       Procedure stub = _combinedMemberSignature.createMemberFromSignature(
-          copyLocation: false);
+          copyLocation: false)!;
       bool needsForwardingStub =
           _combinedMemberSignature.needsCovarianceMerging || needsSuperImpl;
       if (needsForwardingStub || needMixinStub) {
@@ -124,7 +122,7 @@
               case ProcedureStubKind.MemberSignature:
               case ProcedureStubKind.AbstractMixinStub:
               case ProcedureStubKind.ConcreteMixinStub:
-                finalTarget = interfaceMember.stubTarget;
+                finalTarget = interfaceMember.stubTarget!;
                 break;
             }
           } else {
@@ -133,7 +131,7 @@
         } else {
           stubKind = ProcedureStubKind.AbstractMixinStub;
           finalTarget =
-              _mixedInMember.getMember(_combinedMemberSignature.hierarchy);
+              _mixedInMember!.getMember(_combinedMemberSignature.hierarchy);
         }
 
         stub.stubKind = stubKind;
@@ -149,12 +147,12 @@
       return stub;
     } else {
       if (_combinedMemberSignature.needsCovarianceMerging) {
-        _combinedMemberSignature.combinedMemberSignatureCovariance
+        _combinedMemberSignature.combinedMemberSignatureCovariance!
             .applyCovariance(interfaceMember);
       }
       if (needsSuperImpl) {
         _createForwardingImplIfNeeded(
-            interfaceMember.function, interfaceMember.name, classBuilder.cls,
+            interfaceMember.function!, interfaceMember.name, classBuilder.cls,
             isForwardingStub: true);
       }
       return null;
@@ -163,7 +161,8 @@
 
   void _createForwardingImplIfNeeded(
       FunctionNode function, Name name, Class enclosingClass,
-      {bool isForwardingStub}) {
+      {required bool isForwardingStub}) {
+    // ignore: unnecessary_null_comparison
     assert(isForwardingStub != null);
     if (function.body != null) {
       // There is already an implementation; nothing further needs to be done.
@@ -174,12 +173,12 @@
     if (_superClassMember == null) {
       return;
     }
-    Procedure procedure = function.parent;
+    Procedure procedure = function.parent as Procedure;
     Member superTarget =
-        _superClassMember.getMember(_combinedMemberSignature.hierarchy);
+        _superClassMember!.getMember(_combinedMemberSignature.hierarchy);
     if (superTarget is Procedure && superTarget.isForwardingStub) {
       Procedure superProcedure = superTarget;
-      superTarget = superProcedure.concreteForwardingStubTarget;
+      superTarget = superProcedure.concreteForwardingStubTarget!;
     } else {
       superTarget = superTarget.memberSignatureOrigin ?? superTarget;
     }
@@ -189,7 +188,7 @@
         .toList();
     List<NamedExpression> namedArguments = function.namedParameters
         .map((parameter) =>
-            new NamedExpression(parameter.name, new VariableGet(parameter)))
+            new NamedExpression(parameter.name!, new VariableGet(parameter)))
         .toList();
     List<DartType> typeArguments = function.typeParameters
         .map<DartType>((typeParameter) =>
@@ -199,6 +198,7 @@
     Arguments arguments = new Arguments(positionalArguments,
         types: typeArguments, named: namedArguments);
     Expression superCall;
+    // ignore: unnecessary_null_comparison
     assert(superTarget != null,
         "No super target found for '${name}' in ${enclosingClass}.");
     assert(
@@ -208,7 +208,8 @@
     switch (kind) {
       case ProcedureKind.Method:
       case ProcedureKind.Operator:
-        superCall = new SuperMethodInvocation(name, arguments, superTarget);
+        superCall = new SuperMethodInvocation(
+            name, arguments, superTarget as Procedure);
         break;
       case ProcedureKind.Getter:
         superCall = new SuperPropertyGet(name, superTarget);
@@ -219,7 +220,6 @@
         break;
       default:
         unhandled('$kind', '_createForwardingImplIfNeeded', -1, null);
-        break;
     }
     function.body = new ReturnStatement(superCall)..parent = function;
     procedure.transformerFlags |= TransformerFlag.superCalls;
diff --git a/pkg/front_end/lib/src/fasta/kernel/implicit_field_type.dart b/pkg/front_end/lib/src/fasta/kernel/implicit_field_type.dart
index f9c2d18..af85f4c 100644
--- a/pkg/front_end/lib/src/fasta/kernel/implicit_field_type.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/implicit_field_type.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.implicit_type;
 
 import 'package:_fe_analyzer_shared/src/scanner/token.dart' show Token;
@@ -28,7 +26,7 @@
   ImplicitFieldType._();
 
   factory ImplicitFieldType(
-          SourceFieldBuilder fieldBuilder, Token initializerToken) =
+          SourceFieldBuilder fieldBuilder, Token? initializerToken) =
       _ImplicitFieldTypeRoot;
 
   @override
@@ -50,7 +48,7 @@
   }
 
   @override
-  visitChildren(Visitor<Object> v) {
+  visitChildren(Visitor<dynamic> v) {
     unsupported("visitChildren", fieldBuilder.charOffset, fieldBuilder.fileUri);
   }
 
@@ -79,7 +77,7 @@
   bool operator ==(Object other) => equals(other, null);
 
   @override
-  bool equals(Object other, Assumptions assumptions) {
+  bool equals(Object other, Assumptions? assumptions) {
     if (identical(this, other)) return true;
     return other is ImplicitFieldType && fieldBuilder == other.fieldBuilder;
   }
@@ -94,8 +92,8 @@
 
 class _ImplicitFieldTypeRoot extends ImplicitFieldType {
   final SourceFieldBuilder fieldBuilder;
-  List<ImplicitFieldType> _overriddenFields;
-  Token initializerToken;
+  List<ImplicitFieldType>? _overriddenFields;
+  Token? initializerToken;
   bool isStarted = false;
 
   _ImplicitFieldTypeRoot(this.fieldBuilder, this.initializerToken) : super._();
@@ -115,9 +113,9 @@
       return fieldBuilder.fieldType = const InvalidType();
     }
     isStarted = true;
-    DartType inferredType;
+    DartType? inferredType;
     if (_overriddenFields != null) {
-      for (ImplicitFieldType overridden in _overriddenFields) {
+      for (ImplicitFieldType overridden in _overriddenFields!) {
         DartType overriddenType = overridden.inferType();
         if (!fieldBuilder.library.isNonNullableByDefault) {
           overriddenType = legacyErasure(overriddenType);
@@ -128,14 +126,14 @@
           inferredType = const InvalidType();
         }
       }
-      return inferredType;
+      return inferredType!;
     } else if (initializerToken != null) {
-      InterfaceType enclosingClassThisType = fieldBuilder.classBuilder == null
+      InterfaceType? enclosingClassThisType = fieldBuilder.classBuilder == null
           ? null
           : fieldBuilder.library.loader.typeInferenceEngine.coreTypes
-              .thisInterfaceType(fieldBuilder.classBuilder.cls,
+              .thisInterfaceType(fieldBuilder.classBuilder!.cls,
                   fieldBuilder.library.library.nonNullable);
-      TypeInferrerImpl typeInferrer = fieldBuilder
+      TypeInferrer typeInferrer = fieldBuilder
           .library.loader.typeInferenceEngine
           .createTopLevelTypeInferrer(
               fieldBuilder.fileUri,
@@ -150,7 +148,7 @@
       bodyBuilder.inFieldInitializer = true;
       bodyBuilder.inLateFieldInitializer = fieldBuilder.isLate;
       Expression initializer =
-          bodyBuilder.parseFieldInitializer(initializerToken);
+          bodyBuilder.parseFieldInitializer(initializerToken!);
       initializerToken = null;
 
       ExpressionInferenceResult result = typeInferrer.inferExpression(
@@ -164,20 +162,19 @@
   }
 
   void addOverride(ImplicitFieldType other) {
-    _overriddenFields ??= [];
-    _overriddenFields.add(other);
+    (_overriddenFields ??= []).add(other);
   }
 
   DartType checkInferred(DartType type) {
     if (_overriddenFields != null) {
-      for (ImplicitFieldType overridden in _overriddenFields) {
+      for (ImplicitFieldType overridden in _overriddenFields!) {
         DartType overriddenType = overridden.inferType();
         if (!fieldBuilder.library.isNonNullableByDefault) {
           overriddenType = legacyErasure(overriddenType);
         }
         if (type != overriddenType) {
           String name = fieldBuilder.fullNameForErrors;
-          fieldBuilder.classBuilder.addProblem(
+          fieldBuilder.classBuilder!.addProblem(
               templateCantInferTypeDueToNoCombinedSignature.withArguments(name),
               fieldBuilder.charOffset,
               name.length,
diff --git a/pkg/front_end/lib/src/fasta/kernel/inference_visitor.dart b/pkg/front_end/lib/src/fasta/kernel/inference_visitor.dart
index fb20d2f..ccd5c3b 100644
--- a/pkg/front_end/lib/src/fasta/kernel/inference_visitor.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/inference_visitor.dart
@@ -2,8 +2,6 @@
 // for 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 'package:_fe_analyzer_shared/src/flow_analysis/flow_analysis.dart';
 import 'package:_fe_analyzer_shared/src/util/link.dart';
 import 'package:front_end/src/api_prototype/lowering_predicates.dart';
@@ -47,19 +45,19 @@
         InitializerVisitor<void> {
   final TypeInferrerImpl inferrer;
 
-  Class mapEntryClass;
+  Class? mapEntryClass;
 
   // Stores the offset of the map entry found by inferMapEntry.
-  int mapEntryOffset = null;
+  int? mapEntryOffset = null;
 
   // Stores the offset of the map spread found by inferMapEntry.
-  int mapSpreadOffset = null;
+  int? mapSpreadOffset = null;
 
   // Stores the offset of the iterable spread found by inferMapEntry.
-  int iterableSpreadOffset = null;
+  int? iterableSpreadOffset = null;
 
   // Stores the type of the iterable spread found by inferMapEntry.
-  DartType iterableSpreadType = null;
+  DartType? iterableSpreadType = null;
 
   InferenceVisitor(this.inferrer);
 
@@ -70,10 +68,10 @@
     int fileOffset;
     if (!inferrer.isTopLevel) {
       // In local inference we have access to the current file uri.
-      uri = inferrer.helper.uri;
+      uri = inferrer.helper!.uri;
       fileOffset = node.fileOffset;
     } else {
-      Location location = node.location;
+      Location? location = node.location;
       if (location != null) {
         // Use the location file uri, if available.
         uri = location.file;
@@ -274,7 +272,7 @@
 
   void _unhandledInitializer(Initializer node) {
     unhandled("${node.runtimeType}", "InferenceVisitor", node.fileOffset,
-        node.location.file);
+        node.location!.file);
   }
 
   @override
@@ -321,14 +319,14 @@
       } else {
         if (!inferrer.isTopLevel) {
           if (operandType.typeParameters.isEmpty) {
-            result = inferrer.helper.buildProblem(
+            result = inferrer.helper!.buildProblem(
                 templateInstantiationNonGenericFunctionType.withArguments(
                     operandType, inferrer.isNonNullableByDefault),
                 node.fileOffset,
                 noLength);
           } else if (operandType.typeParameters.length >
               node.typeArguments.length) {
-            result = inferrer.helper.buildProblem(
+            result = inferrer.helper!.buildProblem(
                 templateInstantiationTooFewArguments.withArguments(
                     operandType.typeParameters.length,
                     node.typeArguments.length),
@@ -336,7 +334,7 @@
                 noLength);
           } else if (operandType.typeParameters.length <
               node.typeArguments.length) {
-            result = inferrer.helper.buildProblem(
+            result = inferrer.helper!.buildProblem(
                 templateInstantiationTooManyArguments.withArguments(
                     operandType.typeParameters.length,
                     node.typeArguments.length),
@@ -347,7 +345,7 @@
       }
     } else {
       if (!inferrer.isTopLevel) {
-        result = inferrer.helper.buildProblem(
+        result = inferrer.helper!.buildProblem(
             templateInstantiationNonGenericFunctionType.withArguments(
                 operandType, inferrer.isNonNullableByDefault),
             node.fileOffset,
@@ -379,7 +377,7 @@
   void visitAssertInitializer(AssertInitializer node) {
     StatementInferenceResult result = inferrer.inferStatement(node.statement);
     if (result.hasChanged) {
-      node.statement = result.statement..parent = node;
+      node.statement = (result.statement as AssertStatement)..parent = node;
     }
   }
 
@@ -398,7 +396,7 @@
     inferrer.flowAnalysis.assert_afterCondition(node.condition);
     if (node.message != null) {
       ExpressionInferenceResult messageResult = inferrer.inferExpression(
-          node.message, const UnknownType(), !inferrer.isTopLevel,
+          node.message!, const UnknownType(), !inferrer.isTopLevel,
           isVoidAllowed: true);
       node.message = messageResult.expression..parent = node;
     }
@@ -421,8 +419,8 @@
     return new ExpressionInferenceResult(inferredType, node);
   }
 
-  List<Statement> _visitStatements<T extends Statement>(List<T> statements) {
-    List<Statement> result;
+  List<Statement>? _visitStatements<T extends Statement>(List<T> statements) {
+    List<Statement>? result;
     for (int index = 0; index < statements.length; index++) {
       T statement = statements[index];
       StatementInferenceResult statementResult =
@@ -447,7 +445,7 @@
   @override
   StatementInferenceResult visitBlock(Block node) {
     inferrer.registerIfUnreachableForTesting(node);
-    List<Statement> result = _visitStatements<Statement>(node.statements);
+    List<Statement>? result = _visitStatements<Statement>(node.statements);
     if (result != null) {
       Block block = new Block(result)..fileOffset = node.fileOffset;
       inferrer.library.loader.dataForTesting?.registerAlias(node, block);
@@ -471,16 +469,16 @@
     // TODO(johnniwinther): Refactor break/continue encoding.
     assert(node.targetStatement != null);
     if (node.isContinue) {
-      inferrer.flowAnalysis.handleContinue(node.targetStatement);
+      inferrer.flowAnalysis.handleContinue(node.targetStatement!);
     } else {
-      inferrer.flowAnalysis.handleBreak(node.targetStatement);
+      inferrer.flowAnalysis.handleBreak(node.targetStatement!);
     }
     return const StatementInferenceResult();
   }
 
   ExpressionInferenceResult visitCascade(Cascade node, DartType typeContext) {
     ExpressionInferenceResult result = inferrer.inferExpression(
-        node.variable.initializer, typeContext, true,
+        node.variable.initializer!, typeContext, true,
         isVoidAllowed: false);
     if (node.isNullAware) {
       reportNonNullableInNullAwareWarningIfNeeded(
@@ -489,7 +487,7 @@
 
     node.variable.initializer = result.expression..parent = node.variable;
     node.variable.type = result.inferredType;
-    NullAwareGuard nullAwareGuard;
+    NullAwareGuard? nullAwareGuard;
     if (node.isNullAware) {
       nullAwareGuard = inferrer.createNullAwareGuard(node.variable);
     }
@@ -511,7 +509,7 @@
 
     if (node.isNullAware) {
       replacement =
-          nullAwareGuard.createExpression(result.inferredType, replacement);
+          nullAwareGuard!.createExpression(result.inferredType, replacement);
     } else {
       replacement = new Let(node.variable, replacement)
         ..fileOffset = node.fileOffset;
@@ -525,12 +523,15 @@
 
   BlockExpression _createBlockExpression(
       int fileOffset, Block body, Expression value) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != TreeNode.noOffset);
     return new BlockExpression(body, value)..fileOffset = fileOffset;
   }
 
   ExpressionStatement _createExpressionStatement(Expression expression) {
+    // ignore: unnecessary_null_comparison
     assert(expression != null);
     assert(expression.fileOffset != TreeNode.noOffset);
     return new ExpressionStatement(expression)
@@ -586,7 +587,7 @@
       SourceLibraryBuilder library = inferrer.library;
       if (!hadExplicitTypeArguments) {
         library.checkBoundsInConstructorInvocation(
-            node, inferrer.typeSchemaEnvironment, inferrer.helper.uri,
+            node, inferrer.typeSchemaEnvironment, inferrer.helper!.uri,
             inferred: true);
       }
     }
@@ -603,6 +604,7 @@
 
   ExpressionInferenceResult visitExtensionTearOff(
       ExtensionTearOff node, DartType typeContext) {
+    // ignore: unnecessary_null_comparison
     FunctionType calleeType = node.target != null
         ? node.target.function.computeFunctionType(inferrer.library.nonNullable)
         : new FunctionType(
@@ -611,12 +613,14 @@
     InvocationInferenceResult result = inferrer.inferInvocation(
         typeContext, node.fileOffset, calleeType, node.arguments,
         staticTarget: node.target);
-    Expression replacement = new StaticInvocation(node.target, node.arguments);
+    StaticInvocation replacement =
+        new StaticInvocation(node.target, node.arguments);
+    // ignore: unnecessary_null_comparison
     if (!inferrer.isTopLevel && node.target != null) {
       inferrer.library.checkBoundsInStaticInvocation(
           replacement,
           inferrer.typeSchemaEnvironment,
-          inferrer.helper.uri,
+          inferrer.helper!.uri,
           typeArgumentsInfo);
     }
     return inferrer.instantiateTearOff(
@@ -650,7 +654,7 @@
         isVoidAllowed: false);
     Expression value = inferrer.ensureAssignableResult(valueType, valueResult);
 
-    VariableDeclaration valueVariable;
+    VariableDeclaration? valueVariable;
     if (node.forEffect) {
       // No need for value variable.
     } else {
@@ -658,7 +662,7 @@
       value = createVariableGet(valueVariable);
     }
 
-    VariableDeclaration receiverVariable;
+    VariableDeclaration? receiverVariable;
     if (node.forEffect || isPureExpression(receiver)) {
       // No need for receiver variable.
     } else {
@@ -681,7 +685,7 @@
       assert(valueVariable != null);
       VariableDeclaration assignmentVariable =
           createVariable(assignment, const VoidType());
-      replacement = createLet(valueVariable,
+      replacement = createLet(valueVariable!,
           createLet(assignmentVariable, createVariableGet(valueVariable)));
       if (receiverVariable != null) {
         replacement = createLet(receiverVariable, replacement);
@@ -707,7 +711,7 @@
     Expression receiver =
         inferrer.ensureAssignableResult(receiverType, receiverResult);
 
-    VariableDeclaration receiverVariable;
+    VariableDeclaration? receiverVariable;
     Expression readReceiver;
     Expression writeReceiver;
     if (isPureExpression(receiver)) {
@@ -722,7 +726,7 @@
     ObjectAccessTarget readTarget = node.getter == null
         ? const ObjectAccessTarget.missing()
         : new ExtensionAccessTarget(
-            node.getter, null, ProcedureKind.Getter, extensionTypeArguments);
+            node.getter!, null, ProcedureKind.Getter, extensionTypeArguments);
 
     DartType readType = inferrer.getGetterType(readTarget, receiverType);
 
@@ -733,7 +737,7 @@
     } else {
       assert(readTarget.isExtensionMember);
       read = new StaticInvocation(
-          readTarget.member,
+          readTarget.member as Procedure,
           new Arguments(<Expression>[
             readReceiver,
           ], types: readTarget.inferredExtensionTypeArguments)
@@ -744,7 +748,7 @@
     ObjectAccessTarget writeTarget = node.setter == null
         ? const ObjectAccessTarget.missing()
         : new ExtensionAccessTarget(
-            node.setter, null, ProcedureKind.Setter, extensionTypeArguments);
+            node.setter!, null, ProcedureKind.Setter, extensionTypeArguments);
 
     DartType valueType = inferrer.getSetterType(writeTarget, receiverType);
 
@@ -763,7 +767,7 @@
     Expression value = inferrer.ensureAssignable(valueType, binaryType, binary,
         isVoidAllowed: true);
 
-    VariableDeclaration valueVariable;
+    VariableDeclaration? valueVariable;
     if (node.forEffect) {
       // No need for value variable.
     } else {
@@ -779,7 +783,7 @@
     } else {
       assert(writeTarget.isExtensionMember);
       write = new StaticInvocation(
-          writeTarget.member,
+          writeTarget.member as Procedure,
           new Arguments(<Expression>[
             writeReceiver,
             value,
@@ -796,7 +800,7 @@
       assert(valueVariable != null);
       VariableDeclaration writeVariable =
           createVariable(write, const VoidType());
-      replacement = createLet(valueVariable,
+      replacement = createLet(valueVariable!,
           createLet(writeVariable, createVariableGet(valueVariable)));
     }
     if (receiverVariable != null) {
@@ -876,12 +880,12 @@
       SourceLibraryBuilder library = inferrer.library;
       if (!hadExplicitTypeArguments) {
         library.checkBoundsInFactoryInvocation(
-            node, inferrer.typeSchemaEnvironment, inferrer.helper.uri,
+            node, inferrer.typeSchemaEnvironment, inferrer.helper!.uri,
             inferred: true);
       }
       if (inferrer.isNonNullableByDefault) {
         if (node.target == inferrer.coreTypes.listDefaultConstructor) {
-          resultNode = inferrer.helper.wrapInProblem(node,
+          resultNode = inferrer.helper!.wrapInProblem(node,
               messageDefaultListConstructorError, node.fileOffset, noLength);
         }
       }
@@ -906,7 +910,7 @@
     if (!inferrer.isTopLevel) {
       if (inferrer.isNonNullableByDefault) {
         if (node.target == inferrer.coreTypes.listDefaultConstructor) {
-          resultNode = inferrer.helper.wrapInProblem(node,
+          resultNode = inferrer.helper!.wrapInProblem(node,
               messageDefaultListConstructorError, node.fileOffset, noLength);
         }
       }
@@ -930,7 +934,7 @@
     if (!inferrer.isTopLevel) {
       if (inferrer.isNonNullableByDefault) {
         if (node.target == inferrer.coreTypes.listDefaultConstructor) {
-          resultNode = inferrer.helper.wrapInProblem(node,
+          resultNode = inferrer.helper!.wrapInProblem(node,
               messageDefaultListConstructorError, node.fileOffset, noLength);
         }
       }
@@ -953,7 +957,7 @@
       TreeNode node,
       VariableDeclaration variable,
       Expression iterable,
-      Statement expressionEffects,
+      Statement? expressionEffects,
       {bool isAsync: false}) {
     DartType elementType;
     bool typeNeeded = false;
@@ -987,7 +991,7 @@
         new VariableDeclaration(null, type: inferredType, isFinal: true);
     VariableGet variableGet = new VariableGet(tempVariable)
       ..fileOffset = variable.fileOffset;
-    TreeNode parent = variable.parent;
+    TreeNode parent = variable.parent!;
     Expression implicitDowncast = inferrer.ensureAssignable(
         variable.type, inferredType, variableGet,
         fileOffset: parent.fileOffset,
@@ -996,7 +1000,7 @@
             templateForInLoopElementTypeNotAssignableNullability,
         nullabilityPartErrorTemplate:
             templateForInLoopElementTypeNotAssignablePartNullability);
-    Statement expressionEffect;
+    Statement? expressionEffect;
     if (!identical(implicitDowncast, variableGet)) {
       variable.initializer = implicitDowncast..parent = variable;
       expressionEffect = variable;
@@ -1048,19 +1052,21 @@
       if (inferredExpressionType is InterfaceType) {
         // TODO(johnniwinther): Should we use the type of
         //  `iterable.iterator.current` instead?
-        List<DartType> supertypeArguments = inferrer.classHierarchy
+        List<DartType>? supertypeArguments = inferrer.classHierarchy
             .getTypeArgumentsAsInstanceOf(
                 inferredExpressionType, iterableClass);
         if (supertypeArguments != null) {
           inferredType = supertypeArguments[0];
         }
       }
+    } else {
+      inferredType = noInferredType;
     }
     return new ExpressionInferenceResult(inferredType, iterable);
   }
 
   ForInVariable computeForInVariable(
-      Expression syntheticAssignment, bool hasProblem) {
+      Expression? syntheticAssignment, bool hasProblem) {
     if (syntheticAssignment is VariableSet) {
       return new LocalForInVariable(syntheticAssignment);
     } else if (syntheticAssignment is PropertySet) {
@@ -1072,7 +1078,7 @@
     } else if (syntheticAssignment is InvalidExpression || hasProblem) {
       return new InvalidForInVariable(syntheticAssignment);
     } else {
-      _UriOffset uriOffset = _computeUriOffset(syntheticAssignment);
+      _UriOffset uriOffset = _computeUriOffset(syntheticAssignment!);
       return unhandled(
           "${syntheticAssignment.runtimeType}",
           "handleForInStatementWithoutVariable",
@@ -1085,10 +1091,11 @@
       TreeNode node,
       VariableDeclaration variable,
       Expression iterable,
-      Expression syntheticAssignment,
-      Statement expressionEffects,
+      Expression? syntheticAssignment,
+      Statement? expressionEffects,
       {bool isAsync: false,
-      bool hasProblem}) {
+      required bool hasProblem}) {
+    // ignore: unnecessary_null_comparison
     assert(hasProblem != null);
     bool typeChecksNeeded = !inferrer.isTopLevel;
     ForInVariable forInVariable =
@@ -1133,11 +1140,11 @@
 
     Statement body = bodyResult.hasChanged ? bodyResult.statement : node.body;
     if (result.expressionSideEffects != null) {
-      body = combineStatements(result.expressionSideEffects, body);
+      body = combineStatements(result.expressionSideEffects!, body);
     }
     if (result.syntheticAssignment != null) {
       body = combineStatements(
-          createExpressionStatement(result.syntheticAssignment), body);
+          createExpressionStatement(result.syntheticAssignment!), body);
     }
     node.variable = result.variable..parent = node;
     node.iterable = result.iterable..parent = node;
@@ -1147,8 +1154,8 @@
 
   StatementInferenceResult visitForInStatementWithSynthesizedVariable(
       ForInStatementWithSynthesizedVariable node) {
-    assert(node.variable.name == null);
-    ForInResult result = handleForInWithoutVariable(node, node.variable,
+    assert(node.variable!.name == null);
+    ForInResult result = handleForInWithoutVariable(node, node.variable!,
         node.iterable, node.syntheticAssignment, node.expressionEffects,
         isAsync: node.isAsync, hasProblem: node.hasProblem);
 
@@ -1160,11 +1167,11 @@
 
     Statement body = bodyResult.hasChanged ? bodyResult.statement : node.body;
     if (result.expressionSideEffects != null) {
-      body = combineStatements(result.expressionSideEffects, body);
+      body = combineStatements(result.expressionSideEffects!, body);
     }
     if (result.syntheticAssignment != null) {
       body = combineStatements(
-          createExpressionStatement(result.syntheticAssignment), body);
+          createExpressionStatement(result.syntheticAssignment!), body);
     }
     Statement replacement = new ForInStatement(
         result.variable, result.iterable, body,
@@ -1177,13 +1184,13 @@
 
   @override
   StatementInferenceResult visitForStatement(ForStatement node) {
-    List<VariableDeclaration> variables;
+    List<VariableDeclaration>? variables;
     for (int index = 0; index < node.variables.length; index++) {
       VariableDeclaration variable = node.variables[index];
       if (variable.name == null) {
         if (variable.initializer != null) {
           ExpressionInferenceResult result = inferrer.inferExpression(
-              variable.initializer, const UnknownType(), true,
+              variable.initializer!, const UnknownType(), true,
               isVoidAllowed: true);
           variable.initializer = result.expression..parent = variable;
           variable.type = result.inferredType;
@@ -1197,10 +1204,10 @@
             variables.addAll(node.variables.sublist(0, index));
           }
           if (variableResult.statementCount == 1) {
-            variables.add(variableResult.statement);
+            variables.add(variableResult.statement as VariableDeclaration);
           } else {
-            for (VariableDeclaration variable in variableResult.statements) {
-              variables.add(variable);
+            for (Statement variable in variableResult.statements) {
+              variables.add(variable as VariableDeclaration);
             }
           }
         } else if (variables != null) {
@@ -1218,7 +1225,7 @@
       InterfaceType expectedType =
           inferrer.coreTypes.boolRawType(inferrer.library.nonNullable);
       ExpressionInferenceResult conditionResult = inferrer.inferExpression(
-          node.condition, expectedType, !inferrer.isTopLevel,
+          node.condition!, expectedType, !inferrer.isTopLevel,
           isVoidAllowed: true);
       Expression condition =
           inferrer.ensureAssignableResult(expectedType, conditionResult);
@@ -1241,8 +1248,8 @@
     return const StatementInferenceResult();
   }
 
-  FunctionType visitFunctionNode(FunctionNode node, DartType typeContext,
-      DartType returnContext, int returnTypeInstrumentationOffset) {
+  FunctionType visitFunctionNode(FunctionNode node, DartType? typeContext,
+      DartType? returnContext, int returnTypeInstrumentationOffset) {
     return inferrer.inferLocalFunction(
         node, typeContext, returnTypeInstrumentationOffset, returnContext);
   }
@@ -1254,12 +1261,12 @@
     inferrer.flowAnalysis.functionExpression_begin(node);
     inferrer.inferMetadataKeepingHelper(
         node.variable, node.variable.annotations);
-    DartType returnContext =
+    DartType? returnContext =
         node.hasImplicitReturnType ? null : node.function.returnType;
     FunctionType inferredType =
         visitFunctionNode(node.function, null, returnContext, node.fileOffset);
     if (inferrer.dataForTesting != null && node.hasImplicitReturnType) {
-      inferrer.dataForTesting.typeInferenceResult.inferredVariableTypes[node] =
+      inferrer.dataForTesting!.typeInferenceResult.inferredVariableTypes[node] =
           inferredType.returnType;
     }
     inferrer.library.checkBoundsInFunctionNode(node.function,
@@ -1276,7 +1283,7 @@
     FunctionType inferredType =
         visitFunctionNode(node.function, typeContext, null, node.fileOffset);
     if (inferrer.dataForTesting != null) {
-      inferrer.dataForTesting.typeInferenceResult.inferredVariableTypes[node] =
+      inferrer.dataForTesting!.typeInferenceResult.inferredVariableTypes[node] =
           inferredType.returnType;
     }
     // In anonymous functions the return type isn't declared, so
@@ -1292,14 +1299,14 @@
       InvalidSuperInitializerJudgment node) {
     Substitution substitution = Substitution.fromSupertype(
         inferrer.classHierarchy.getClassAsInstanceOf(
-            inferrer.thisType.classNode, node.target.enclosingClass));
+            inferrer.thisType!.classNode, node.target.enclosingClass)!);
     FunctionType functionType = replaceReturnType(
         substitution.substituteType(node.target.function
             .computeThisFunctionType(inferrer.library.nonNullable)
-            .withoutTypeParameters),
-        inferrer.thisType);
-    inferrer.inferInvocation(
-        null, node.fileOffset, functionType, node.argumentsJudgment,
+            .withoutTypeParameters) as FunctionType,
+        inferrer.thisType!);
+    inferrer.inferInvocation(const UnknownType(), node.fileOffset, functionType,
+        node.argumentsJudgment,
         skipTypeArgumentInference: true);
   }
 
@@ -1316,7 +1323,7 @@
     Member equalsMember = inferrer
         .findInterfaceMember(
             lhsResult.inferredType, equalsName, node.fileOffset)
-        .member;
+        .member!;
 
     // This ends any shorting in `node.left`.
     Expression left = lhsResult.expression;
@@ -1388,7 +1395,7 @@
     if (node.otherwise != null) {
       inferrer.flowAnalysis.ifStatement_elseBegin();
       StatementInferenceResult otherwiseResult =
-          inferrer.inferStatement(node.otherwise);
+          inferrer.inferStatement(node.otherwise!);
       if (otherwiseResult.hasChanged) {
         node.otherwise = otherwiseResult.statement..parent = node;
       }
@@ -1400,7 +1407,7 @@
   ExpressionInferenceResult visitIntJudgment(
       IntJudgment node, DartType typeContext) {
     if (inferrer.isDoubleContext(typeContext)) {
-      double doubleValue = node.asDouble();
+      double? doubleValue = node.asDouble();
       if (doubleValue != null) {
         Expression replacement = new DoubleLiteral(doubleValue)
           ..fileOffset = node.fileOffset;
@@ -1409,7 +1416,7 @@
         return new ExpressionInferenceResult(inferredType, replacement);
       }
     }
-    Expression error = checkWebIntLiteralsErrorIfUnexact(
+    Expression? error = checkWebIntLiteralsErrorIfUnexact(
         inferrer, node.value, node.literal, node.fileOffset);
     if (error != null) {
       return new ExpressionInferenceResult(const DynamicType(), error);
@@ -1422,7 +1429,7 @@
   ExpressionInferenceResult visitShadowLargeIntLiteral(
       ShadowLargeIntLiteral node, DartType typeContext) {
     if (inferrer.isDoubleContext(typeContext)) {
-      double doubleValue = node.asDouble();
+      double? doubleValue = node.asDouble();
       if (doubleValue != null) {
         Expression replacement = new DoubleLiteral(doubleValue)
           ..fileOffset = node.fileOffset;
@@ -1432,15 +1439,15 @@
       }
     }
 
-    int intValue = node.asInt64();
+    int? intValue = node.asInt64();
     if (intValue == null) {
-      Expression replacement = inferrer.helper.buildProblem(
+      Expression replacement = inferrer.helper!.buildProblem(
           templateIntegerLiteralIsOutOfRange.withArguments(node.literal),
           node.fileOffset,
           node.literal.length);
       return new ExpressionInferenceResult(const DynamicType(), replacement);
     }
-    Expression error = checkWebIntLiteralsErrorIfUnexact(
+    Expression? error = checkWebIntLiteralsErrorIfUnexact(
         inferrer, intValue, node.literal, node.fileOffset);
     if (error != null) {
       return new ExpressionInferenceResult(const DynamicType(), error);
@@ -1453,7 +1460,7 @@
 
   void visitShadowInvalidInitializer(ShadowInvalidInitializer node) {
     ExpressionInferenceResult initializerResult = inferrer.inferExpression(
-        node.variable.initializer, const UnknownType(), !inferrer.isTopLevel,
+        node.variable.initializer!, const UnknownType(), !inferrer.isTopLevel,
         isVoidAllowed: false);
     node.variable.initializer = initializerResult.expression
       ..parent = node.variable;
@@ -1500,7 +1507,7 @@
     return const StatementInferenceResult();
   }
 
-  DartType getSpreadElementType(
+  DartType? getSpreadElementType(
       DartType spreadType, DartType spreadTypeBound, bool isNullAware) {
     if (inferrer.coreTypes.isNull(spreadTypeBound)) {
       if (inferrer.isNonNullableByDefault) {
@@ -1510,7 +1517,7 @@
       }
     }
     if (spreadTypeBound is InterfaceType) {
-      List<DartType> supertypeArguments = inferrer.typeSchemaEnvironment
+      List<DartType>? supertypeArguments = inferrer.typeSchemaEnvironment
           .getTypeArgumentsAsInstanceOf(
               spreadTypeBound, inferrer.coreTypes.iterableClass);
       if (supertypeArguments == null) {
@@ -1550,13 +1557,13 @@
       inferredSpreadTypes[element.expression] = spreadType;
       Expression replacement = element;
       DartType spreadTypeBound = inferrer.resolveTypeParameter(spreadType);
-      DartType spreadElementType = getSpreadElementType(
+      DartType? spreadElementType = getSpreadElementType(
           spreadType, spreadTypeBound, element.isNullAware);
       if (typeChecksNeeded) {
         if (spreadElementType == null) {
           if (inferrer.coreTypes.isNull(spreadTypeBound) &&
               !element.isNullAware) {
-            replacement = inferrer.helper.buildProblem(
+            replacement = inferrer.helper!.buildProblem(
                 templateNonNullAwareSpreadIsNull.withArguments(
                     spreadType, inferrer.isNonNullableByDefault),
                 element.expression.fileOffset,
@@ -1568,15 +1575,15 @@
                 spreadType is! NullType &&
                 !element.isNullAware) {
               Expression receiver = element.expression;
-              replacement = inferrer.helper.buildProblem(
+              replacement = inferrer.helper!.buildProblem(
                   messageNullableSpreadError, receiver.fileOffset, 1,
                   context: inferrer.getWhyNotPromotedContext(
-                      inferrer.flowAnalysis?.whyNotPromoted(receiver)(),
+                      inferrer.flowAnalysis.whyNotPromoted(receiver)(),
                       element,
                       (type) => !type.isPotentiallyNullable));
             }
 
-            replacement = inferrer.helper.buildProblem(
+            replacement = inferrer.helper!.buildProblem(
                 templateSpreadTypeMismatch.withArguments(
                     spreadType, inferrer.isNonNullableByDefault),
                 element.expression.fileOffset,
@@ -1592,7 +1599,7 @@
               if (subtypeCheckResult.isSubtypeWhenIgnoringNullabilities()) {
                 if (spreadElementType == subtypeCheckResult.subtype &&
                     inferredTypeArgument == subtypeCheckResult.supertype) {
-                  replacement = inferrer.helper.buildProblem(
+                  replacement = inferrer.helper!.buildProblem(
                       templateSpreadElementTypeMismatchNullability
                           .withArguments(
                               spreadElementType,
@@ -1601,19 +1608,19 @@
                       element.expression.fileOffset,
                       1);
                 } else {
-                  replacement = inferrer.helper.buildProblem(
+                  replacement = inferrer.helper!.buildProblem(
                       templateSpreadElementTypeMismatchPartNullability
                           .withArguments(
                               spreadElementType,
                               inferredTypeArgument,
-                              subtypeCheckResult.subtype,
-                              subtypeCheckResult.supertype,
+                              subtypeCheckResult.subtype!,
+                              subtypeCheckResult.supertype!,
                               inferrer.isNonNullableByDefault),
                       element.expression.fileOffset,
                       1);
                 }
               } else {
-                replacement = inferrer.helper.buildProblem(
+                replacement = inferrer.helper!.buildProblem(
                     templateSpreadElementTypeMismatch.withArguments(
                         spreadElementType,
                         inferredTypeArgument,
@@ -1622,7 +1629,7 @@
                     1);
               }
             } else {
-              replacement = inferrer.helper.buildProblem(
+              replacement = inferrer.helper!.buildProblem(
                   templateSpreadElementTypeMismatch.withArguments(
                       spreadElementType,
                       inferredTypeArgument,
@@ -1637,10 +1644,10 @@
               spreadType is! NullType &&
               !element.isNullAware) {
             Expression receiver = element.expression;
-            replacement = inferrer.helper.buildProblem(
+            replacement = inferrer.helper!.buildProblem(
                 messageNullableSpreadError, receiver.fileOffset, 1,
                 context: inferrer.getWhyNotPromotedContext(
-                    inferrer.flowAnalysis?.whyNotPromoted(receiver)(),
+                    inferrer.flowAnalysis.whyNotPromoted(receiver)(),
                     element,
                     (type) => !type.isPotentiallyNullable));
             _copyNonPromotionReasonToReplacement(element, replacement);
@@ -1649,7 +1656,7 @@
       }
       // Use 'dynamic' for error recovery.
       element.elementType = spreadElementType ?? const DynamicType();
-      return new ExpressionInferenceResult(element.elementType, replacement);
+      return new ExpressionInferenceResult(element.elementType!, replacement);
     } else if (element is IfElement) {
       inferrer.flowAnalysis.ifStatement_conditionBegin();
       DartType boolType =
@@ -1669,11 +1676,11 @@
           inferenceNeeded,
           typeChecksNeeded);
       element.then = thenResult.expression..parent = element;
-      ExpressionInferenceResult otherwiseResult;
+      ExpressionInferenceResult? otherwiseResult;
       if (element.otherwise != null) {
         inferrer.flowAnalysis.ifStatement_elseBegin();
         otherwiseResult = inferElement(
-            element.otherwise,
+            element.otherwise!,
             inferredTypeArgument,
             inferredSpreadTypes,
             inferredConditionTypes,
@@ -1692,13 +1699,13 @@
           element);
     } else if (element is ForElement) {
       // TODO(johnniwinther): Use _visitStatements instead.
-      List<VariableDeclaration> variables;
+      List<VariableDeclaration>? variables;
       for (int index = 0; index < element.variables.length; index++) {
         VariableDeclaration variable = element.variables[index];
         if (variable.name == null) {
           if (variable.initializer != null) {
             ExpressionInferenceResult initializerResult =
-                inferrer.inferExpression(variable.initializer, variable.type,
+                inferrer.inferExpression(variable.initializer!, variable.type,
                     inferenceNeeded || typeChecksNeeded,
                     isVoidAllowed: true);
             variable.initializer = initializerResult.expression
@@ -1714,10 +1721,10 @@
               variables.addAll(element.variables.sublist(0, index));
             }
             if (variableResult.statementCount == 1) {
-              variables.add(variableResult.statement);
+              variables.add(variableResult.statement as VariableDeclaration);
             } else {
-              for (VariableDeclaration variable in variableResult.statements) {
-                variables.add(variable);
+              for (Statement variable in variableResult.statements) {
+                variables.add(variable as VariableDeclaration);
               }
             }
           } else if (variables != null) {
@@ -1733,12 +1740,12 @@
       inferrer.flowAnalysis.for_conditionBegin(element);
       if (element.condition != null) {
         ExpressionInferenceResult conditionResult = inferrer.inferExpression(
-            element.condition,
+            element.condition!,
             inferrer.coreTypes.boolRawType(inferrer.library.nonNullable),
             inferenceNeeded || typeChecksNeeded,
             isVoidAllowed: false);
         element.condition = conditionResult.expression..parent = element;
-        inferredConditionTypes[element.condition] =
+        inferredConditionTypes[element.condition!] =
             conditionResult.inferredType;
       }
       inferrer.flowAnalysis.for_bodyBegin(null, element.condition);
@@ -1768,7 +1775,7 @@
             element,
             element.variable,
             element.iterable,
-            element.syntheticAssignment,
+            element.syntheticAssignment!,
             element.expressionEffects,
             isAsync: element.isAsync,
             hasProblem: element.problem != null);
@@ -1788,7 +1795,7 @@
 
       if (element.problem != null) {
         ExpressionInferenceResult problemResult = inferrer.inferExpression(
-            element.problem,
+            element.problem!,
             const UnknownType(),
             inferenceNeeded || typeChecksNeeded,
             isVoidAllowed: true);
@@ -1826,10 +1833,10 @@
       TreeNode oldNode, TreeNode replacement) {
     if (!identical(oldNode, replacement) &&
         inferrer.dataForTesting?.flowAnalysisResult != null) {
-      inferrer.dataForTesting.flowAnalysisResult
+      inferrer.dataForTesting!.flowAnalysisResult
               .nonPromotionReasons[replacement] =
           inferrer
-              .dataForTesting.flowAnalysisResult.nonPromotionReasons[oldNode];
+              .dataForTesting!.flowAnalysisResult.nonPromotionReasons[oldNode]!;
     }
   }
 
@@ -1840,7 +1847,7 @@
       Map<TreeNode, DartType> inferredSpreadTypes,
       Map<Expression, DartType> inferredConditionTypes) {
     if (item is SpreadElement) {
-      DartType spreadType = inferredSpreadTypes[item.expression];
+      DartType? spreadType = inferredSpreadTypes[item.expression];
       if (spreadType is DynamicType) {
         Expression expression = inferrer.ensureAssignable(
             inferrer.coreTypes.iterableRawType(
@@ -1853,16 +1860,16 @@
       checkElement(item.then, item, typeArgument, inferredSpreadTypes,
           inferredConditionTypes);
       if (item.otherwise != null) {
-        checkElement(item.otherwise, item, typeArgument, inferredSpreadTypes,
+        checkElement(item.otherwise!, item, typeArgument, inferredSpreadTypes,
             inferredConditionTypes);
       }
     } else if (item is ForElement) {
       if (item.condition != null) {
-        DartType conditionType = inferredConditionTypes[item.condition];
+        DartType conditionType = inferredConditionTypes[item.condition]!;
         Expression condition = inferrer.ensureAssignable(
             inferrer.coreTypes.boolRawType(inferrer.library.nonNullable),
             conditionType,
-            item.condition);
+            item.condition!);
         item.condition = condition..parent = item;
       }
       checkElement(item.body, item, typeArgument, inferredSpreadTypes,
@@ -1881,14 +1888,14 @@
     Class listClass = inferrer.coreTypes.listClass;
     InterfaceType listType = inferrer.coreTypes
         .thisInterfaceType(listClass, inferrer.library.nonNullable);
-    List<DartType> inferredTypes;
+    List<DartType>? inferredTypes;
     DartType inferredTypeArgument;
-    List<DartType> formalTypes;
-    List<DartType> actualTypes;
+    List<DartType>? formalTypes;
+    List<DartType>? actualTypes;
     bool inferenceNeeded = node.typeArgument is ImplicitTypeArgument;
     bool typeChecksNeeded = !inferrer.isTopLevel;
-    Map<TreeNode, DartType> inferredSpreadTypes;
-    Map<Expression, DartType> inferredConditionTypes;
+    Map<TreeNode, DartType>? inferredSpreadTypes;
+    Map<Expression, DartType>? inferredConditionTypes;
     if (inferenceNeeded || typeChecksNeeded) {
       formalTypes = [];
       actualTypes = [];
@@ -1908,7 +1915,7 @@
           isConst: node.isConst);
       inferredTypeArgument = inferredTypes[0];
       if (inferrer.dataForTesting != null) {
-        inferrer.dataForTesting.typeInferenceResult
+        inferrer.dataForTesting!.typeInferenceResult
             .inferredTypeArguments[node] = inferredTypes;
       }
     } else {
@@ -1919,14 +1926,14 @@
         ExpressionInferenceResult result = inferElement(
             node.expressions[index],
             inferredTypeArgument,
-            inferredSpreadTypes,
-            inferredConditionTypes,
+            inferredSpreadTypes!,
+            inferredConditionTypes!,
             inferenceNeeded,
             typeChecksNeeded);
         node.expressions[index] = result.expression..parent = node;
-        actualTypes.add(result.inferredType);
+        actualTypes!.add(result.inferredType);
         if (inferenceNeeded) {
-          formalTypes.add(listType.typeArguments[0]);
+          formalTypes!.add(listType.typeArguments[0]);
         }
       }
     }
@@ -1937,7 +1944,7 @@
           formalTypes,
           actualTypes,
           typeContext,
-          inferredTypes,
+          inferredTypes!,
           inferrer.library.library);
       inferredTypeArgument = inferredTypes[0];
       inferrer.instrumentation?.record(
@@ -1950,7 +1957,7 @@
     if (typeChecksNeeded) {
       for (int i = 0; i < node.expressions.length; i++) {
         checkElement(node.expressions[i], node, node.typeArgument,
-            inferredSpreadTypes, inferredConditionTypes);
+            inferredSpreadTypes!, inferredConditionTypes!);
       }
     }
     DartType inferredType = new InterfaceType(
@@ -1959,7 +1966,7 @@
       SourceLibraryBuilder library = inferrer.library;
       if (inferenceNeeded) {
         library.checkBoundsInListLiteral(
-            node, inferrer.typeSchemaEnvironment, inferrer.helper.uri,
+            node, inferrer.typeSchemaEnvironment, inferrer.helper!.uri,
             inferred: true);
       }
     }
@@ -1995,7 +2002,7 @@
   // + 1.  If the types can't be calculated, for example, if spreadMapEntryType
   // is a function type, the original values in output are preserved.
   void storeSpreadMapEntryElementTypes(DartType spreadMapEntryType,
-      bool isNullAware, List<DartType> output, int offset) {
+      bool isNullAware, List<DartType?> output, int offset) {
     DartType typeBound = inferrer.resolveTypeParameter(spreadMapEntryType);
     if (inferrer.coreTypes.isNull(typeBound)) {
       if (isNullAware) {
@@ -2006,7 +2013,7 @@
         }
       }
     } else if (typeBound is InterfaceType) {
-      List<DartType> supertypeArguments = inferrer.typeSchemaEnvironment
+      List<DartType>? supertypeArguments = inferrer.typeSchemaEnvironment
           .getTypeArgumentsAsInstanceOf(typeBound, inferrer.coreTypes.mapClass);
       if (supertypeArguments != null) {
         output[offset] = supertypeArguments[0];
@@ -2030,7 +2037,7 @@
       DartType inferredKeyType,
       DartType inferredValueType,
       DartType spreadContext,
-      List<DartType> actualTypes,
+      List<DartType?> actualTypes,
       List<DartType> actualTypesForSet,
       Map<TreeNode, DartType> inferredSpreadTypes,
       Map<Expression, DartType> inferredConditionTypes,
@@ -2052,10 +2059,10 @@
       actualTypes.add(null);
       storeSpreadMapEntryElementTypes(
           spreadType, entry.isNullAware, actualTypes, length);
-      DartType actualKeyType = actualTypes[length];
-      DartType actualValueType = actualTypes[length + 1];
+      DartType? actualKeyType = actualTypes[length];
+      DartType? actualValueType = actualTypes[length + 1];
       DartType spreadTypeBound = inferrer.resolveTypeParameter(spreadType);
-      DartType actualElementType =
+      DartType? actualElementType =
           getSpreadElementType(spreadType, spreadTypeBound, entry.isNullAware);
 
       MapLiteralEntry replacement = entry;
@@ -2064,7 +2071,7 @@
           if (inferrer.coreTypes.isNull(spreadTypeBound) &&
               !entry.isNullAware) {
             replacement = new MapLiteralEntry(
-                inferrer.helper.buildProblem(
+                inferrer.helper!.buildProblem(
                     templateNonNullAwareSpreadIsNull.withArguments(
                         spreadType, inferrer.isNonNullableByDefault),
                     entry.expression.fileOffset,
@@ -2078,10 +2085,10 @@
                 spreadType is! NullType &&
                 !entry.isNullAware) {
               Expression receiver = entry.expression;
-              Expression problem = inferrer.helper.buildProblem(
+              Expression problem = inferrer.helper!.buildProblem(
                   messageNullableSpreadError, receiver.fileOffset, 1,
                   context: inferrer.getWhyNotPromotedContext(
-                      inferrer.flowAnalysis?.whyNotPromoted(receiver)(),
+                      inferrer.flowAnalysis.whyNotPromoted(receiver)(),
                       entry,
                       (type) => !type.isPotentiallyNullable));
               _copyNonPromotionReasonToReplacement(entry, problem);
@@ -2094,13 +2101,13 @@
             iterableSpreadType = spreadType;
           } else {
             Expression receiver = entry.expression;
-            Expression problem = inferrer.helper.buildProblem(
+            Expression problem = inferrer.helper!.buildProblem(
                 templateSpreadMapEntryTypeMismatch.withArguments(
                     spreadType, inferrer.isNonNullableByDefault),
                 receiver.fileOffset,
                 1,
                 context: inferrer.getWhyNotPromotedContext(
-                    inferrer.flowAnalysis?.whyNotPromoted(receiver)(),
+                    inferrer.flowAnalysis.whyNotPromoted(receiver)(),
                     entry,
                     (type) => !type.isPotentiallyNullable));
             _copyNonPromotionReasonToReplacement(entry, problem);
@@ -2108,8 +2115,8 @@
               ..fileOffset = entry.fileOffset;
           }
         } else if (spreadTypeBound is InterfaceType) {
-          Expression keyError;
-          Expression valueError;
+          Expression? keyError;
+          Expression? valueError;
           if (!inferrer.isAssignable(inferredKeyType, actualKeyType)) {
             if (inferrer.isNonNullableByDefault) {
               IsSubtypeOf subtypeCheckResult = inferrer.typeSchemaEnvironment
@@ -2118,27 +2125,27 @@
               if (subtypeCheckResult.isSubtypeWhenIgnoringNullabilities()) {
                 if (actualKeyType == subtypeCheckResult.subtype &&
                     inferredKeyType == subtypeCheckResult.supertype) {
-                  keyError = inferrer.helper.buildProblem(
+                  keyError = inferrer.helper!.buildProblem(
                       templateSpreadMapEntryElementKeyTypeMismatchNullability
                           .withArguments(actualKeyType, inferredKeyType,
                               inferrer.isNonNullableByDefault),
                       entry.expression.fileOffset,
                       1);
                 } else {
-                  keyError = inferrer.helper.buildProblem(
+                  keyError = inferrer.helper!.buildProblem(
                       // ignore: lines_longer_than_80_chars
                       templateSpreadMapEntryElementKeyTypeMismatchPartNullability
                           .withArguments(
                               actualKeyType,
                               inferredKeyType,
-                              subtypeCheckResult.subtype,
-                              subtypeCheckResult.supertype,
+                              subtypeCheckResult.subtype!,
+                              subtypeCheckResult.supertype!,
                               inferrer.isNonNullableByDefault),
                       entry.expression.fileOffset,
                       1);
                 }
               } else {
-                keyError = inferrer.helper.buildProblem(
+                keyError = inferrer.helper!.buildProblem(
                     templateSpreadMapEntryElementKeyTypeMismatch.withArguments(
                         actualKeyType,
                         inferredKeyType,
@@ -2147,7 +2154,7 @@
                     1);
               }
             } else {
-              keyError = inferrer.helper.buildProblem(
+              keyError = inferrer.helper!.buildProblem(
                   templateSpreadMapEntryElementKeyTypeMismatch.withArguments(
                       actualKeyType,
                       inferredKeyType,
@@ -2156,7 +2163,7 @@
                   1);
             }
           }
-          if (!inferrer.isAssignable(inferredValueType, actualValueType)) {
+          if (!inferrer.isAssignable(inferredValueType, actualValueType!)) {
             if (inferrer.isNonNullableByDefault) {
               IsSubtypeOf subtypeCheckResult = inferrer.typeSchemaEnvironment
                   .performNullabilityAwareSubtypeCheck(
@@ -2164,27 +2171,27 @@
               if (subtypeCheckResult.isSubtypeWhenIgnoringNullabilities()) {
                 if (actualValueType == subtypeCheckResult.subtype &&
                     inferredValueType == subtypeCheckResult.supertype) {
-                  valueError = inferrer.helper.buildProblem(
+                  valueError = inferrer.helper!.buildProblem(
                       templateSpreadMapEntryElementValueTypeMismatchNullability
                           .withArguments(actualValueType, inferredValueType,
                               inferrer.isNonNullableByDefault),
                       entry.expression.fileOffset,
                       1);
                 } else {
-                  valueError = inferrer.helper.buildProblem(
+                  valueError = inferrer.helper!.buildProblem(
                       // ignore: lines_longer_than_80_chars
                       templateSpreadMapEntryElementValueTypeMismatchPartNullability
                           .withArguments(
                               actualValueType,
                               inferredValueType,
-                              subtypeCheckResult.subtype,
-                              subtypeCheckResult.supertype,
+                              subtypeCheckResult.subtype!,
+                              subtypeCheckResult.supertype!,
                               inferrer.isNonNullableByDefault),
                       entry.expression.fileOffset,
                       1);
                 }
               } else {
-                valueError = inferrer.helper.buildProblem(
+                valueError = inferrer.helper!.buildProblem(
                     templateSpreadMapEntryElementValueTypeMismatch
                         .withArguments(actualValueType, inferredValueType,
                             inferrer.isNonNullableByDefault),
@@ -2192,7 +2199,7 @@
                     1);
               }
             } else {
-              valueError = inferrer.helper.buildProblem(
+              valueError = inferrer.helper!.buildProblem(
                   templateSpreadMapEntryElementValueTypeMismatch.withArguments(
                       actualValueType,
                       inferredValueType,
@@ -2207,10 +2214,10 @@
               spreadType is! NullType &&
               !entry.isNullAware) {
             Expression receiver = entry.expression;
-            keyError = inferrer.helper.buildProblem(
+            keyError = inferrer.helper!.buildProblem(
                 messageNullableSpreadError, receiver.fileOffset, 1,
                 context: inferrer.getWhyNotPromotedContext(
-                    inferrer.flowAnalysis?.whyNotPromoted(receiver)(),
+                    inferrer.flowAnalysis.whyNotPromoted(receiver)(),
                     entry,
                     (type) => !type.isPotentiallyNullable));
             _copyNonPromotionReasonToReplacement(entry, keyError);
@@ -2237,9 +2244,9 @@
           inferrer.coreTypes.index.getClass('dart:core', 'MapEntry');
       // TODO(dmitryas):  Handle the case of an ambiguous Set.
       entry.entryType = new InterfaceType(
-          mapEntryClass,
+          mapEntryClass!,
           inferrer.library.nonNullable,
-          <DartType>[actualKeyType, actualValueType]);
+          <DartType>[actualKeyType, actualValueType!]);
 
       bool isMap = inferrer.typeSchemaEnvironment.isSubtypeOf(
           spreadType,
@@ -2289,11 +2296,11 @@
         inferrer.flowAnalysis.ifStatement_elseBegin();
         // We need to modify the actual types added in the recursive call to
         // inferMapEntry.
-        DartType actualValueType = actualTypes.removeLast();
-        DartType actualKeyType = actualTypes.removeLast();
+        DartType? actualValueType = actualTypes.removeLast();
+        DartType? actualKeyType = actualTypes.removeLast();
         DartType actualTypeForSet = actualTypesForSet.removeLast();
         otherwise = inferMapEntry(
-            entry.otherwise,
+            entry.otherwise!,
             entry,
             inferredKeyType,
             inferredValueType,
@@ -2306,10 +2313,10 @@
             typeChecksNeeded);
         int length = actualTypes.length;
         actualTypes[length - 2] = inferrer.typeSchemaEnvironment
-            .getStandardUpperBound(actualKeyType, actualTypes[length - 2],
+            .getStandardUpperBound(actualKeyType!, actualTypes[length - 2]!,
                 inferrer.library.library);
         actualTypes[length - 1] = inferrer.typeSchemaEnvironment
-            .getStandardUpperBound(actualValueType, actualTypes[length - 1],
+            .getStandardUpperBound(actualValueType!, actualTypes[length - 1]!,
                 inferrer.library.library);
         int lengthForSet = actualTypesForSet.length;
         actualTypesForSet[lengthForSet - 1] = inferrer.typeSchemaEnvironment
@@ -2321,13 +2328,13 @@
       return entry;
     } else if (entry is ForMapEntry) {
       // TODO(johnniwinther): Use _visitStatements instead.
-      List<VariableDeclaration> variables;
+      List<VariableDeclaration>? variables;
       for (int index = 0; index < entry.variables.length; index++) {
         VariableDeclaration variable = entry.variables[index];
         if (variable.name == null) {
           if (variable.initializer != null) {
             ExpressionInferenceResult result = inferrer.inferExpression(
-                variable.initializer,
+                variable.initializer!,
                 variable.type,
                 inferenceNeeded || typeChecksNeeded,
                 isVoidAllowed: true);
@@ -2343,10 +2350,10 @@
               variables.addAll(entry.variables.sublist(0, index));
             }
             if (variableResult.statementCount == 1) {
-              variables.add(variableResult.statement);
+              variables.add(variableResult.statement as VariableDeclaration);
             } else {
-              for (VariableDeclaration variable in variableResult.statements) {
-                variables.add(variable);
+              for (Statement variable in variableResult.statements) {
+                variables.add(variable as VariableDeclaration);
               }
             }
           } else if (variables != null) {
@@ -2362,13 +2369,13 @@
       inferrer.flowAnalysis.for_conditionBegin(entry);
       if (entry.condition != null) {
         ExpressionInferenceResult conditionResult = inferrer.inferExpression(
-            entry.condition,
+            entry.condition!,
             inferrer.coreTypes.boolRawType(inferrer.library.nonNullable),
             inferenceNeeded || typeChecksNeeded,
             isVoidAllowed: false);
         entry.condition = conditionResult.expression..parent = entry;
         // TODO(johnniwinther): Ensure assignability of condition?
-        inferredConditionTypes[entry.condition] = conditionResult.inferredType;
+        inferredConditionTypes[entry.condition!] = conditionResult.inferredType;
       }
       inferrer.flowAnalysis.for_bodyBegin(null, entry.condition);
       // Actual types are added by the recursive call.
@@ -2400,7 +2407,7 @@
       ForInResult result;
       if (entry.variable.name == null) {
         result = handleForInWithoutVariable(entry, entry.variable,
-            entry.iterable, entry.syntheticAssignment, entry.expressionEffects,
+            entry.iterable, entry.syntheticAssignment!, entry.expressionEffects,
             isAsync: entry.isAsync, hasProblem: entry.problem != null);
       } else {
         result = handleForInDeclaringVariable(
@@ -2417,7 +2424,7 @@
       result.expressionSideEffects?.parent = entry;
       if (entry.problem != null) {
         ExpressionInferenceResult problemResult = inferrer.inferExpression(
-            entry.problem,
+            entry.problem!,
             const UnknownType(),
             inferenceNeeded || typeChecksNeeded,
             isVoidAllowed: true);
@@ -2475,16 +2482,16 @@
     MapLiteralEntry replacement = entry;
     if (iterableSpreadOffset != null) {
       replacement = new MapLiteralEntry(
-          inferrer.helper.buildProblem(
+          inferrer.helper!.buildProblem(
               templateSpreadMapEntryTypeMismatch.withArguments(
-                  iterableSpreadType, inferrer.isNonNullableByDefault),
-              iterableSpreadOffset,
+                  iterableSpreadType!, inferrer.isNonNullableByDefault),
+              iterableSpreadOffset!,
               1),
           new NullLiteral())
-        ..fileOffset = iterableSpreadOffset;
+        ..fileOffset = iterableSpreadOffset!;
     }
     if (entry is SpreadMapEntry) {
-      DartType spreadType = inferredSpreadTypes[entry.expression];
+      DartType? spreadType = inferredSpreadTypes[entry.expression];
       if (spreadType is DynamicType) {
         Expression expression = inferrer.ensureAssignable(
             inferrer.coreTypes
@@ -2498,17 +2505,17 @@
           inferredSpreadTypes, inferredConditionTypes);
       entry.then = then..parent = entry;
       if (entry.otherwise != null) {
-        MapLiteralEntry otherwise = checkMapEntry(entry.otherwise, keyType,
+        MapLiteralEntry otherwise = checkMapEntry(entry.otherwise!, keyType,
             valueType, inferredSpreadTypes, inferredConditionTypes);
         entry.otherwise = otherwise..parent = entry;
       }
     } else if (entry is ForMapEntry) {
       if (entry.condition != null) {
-        DartType conditionType = inferredConditionTypes[entry.condition];
+        DartType conditionType = inferredConditionTypes[entry.condition]!;
         Expression condition = inferrer.ensureAssignable(
             inferrer.coreTypes.boolRawType(inferrer.library.nonNullable),
             conditionType,
-            entry.condition);
+            entry.condition!);
         entry.condition = condition..parent = entry;
       }
       MapLiteralEntry body = checkMapEntry(entry.body, keyType, valueType,
@@ -2530,18 +2537,18 @@
     Class mapClass = inferrer.coreTypes.mapClass;
     InterfaceType mapType = inferrer.coreTypes
         .thisInterfaceType(mapClass, inferrer.library.nonNullable);
-    List<DartType> inferredTypes;
+    List<DartType>? inferredTypes;
     DartType inferredKeyType;
     DartType inferredValueType;
-    List<DartType> formalTypes;
-    List<DartType> actualTypes;
-    List<DartType> actualTypesForSet;
+    List<DartType>? formalTypes;
+    List<DartType>? actualTypes;
+    List<DartType>? actualTypesForSet;
     assert((node.keyType is ImplicitTypeArgument) ==
         (node.valueType is ImplicitTypeArgument));
     bool inferenceNeeded = node.keyType is ImplicitTypeArgument;
     bool typeContextIsMap = node.keyType is! ImplicitTypeArgument;
     bool typeContextIsIterable = false;
-    DartType unfuturedTypeContext =
+    DartType? unfuturedTypeContext =
         inferrer.typeSchemaEnvironment.flatten(typeContext);
     if (!inferrer.isTopLevel && inferenceNeeded) {
       // Ambiguous set/map literal
@@ -2564,8 +2571,8 @@
       }
     }
     bool typeChecksNeeded = !inferrer.isTopLevel;
-    Map<TreeNode, DartType> inferredSpreadTypes;
-    Map<Expression, DartType> inferredConditionTypes;
+    Map<TreeNode, DartType>? inferredSpreadTypes;
+    Map<Expression, DartType>? inferredConditionTypes;
     if (inferenceNeeded || typeChecksNeeded) {
       formalTypes = [];
       actualTypes = [];
@@ -2587,7 +2594,7 @@
       inferredKeyType = inferredTypes[0];
       inferredValueType = inferredTypes[1];
       if (inferrer.dataForTesting != null) {
-        inferrer.dataForTesting.typeInferenceResult
+        inferrer.dataForTesting!.typeInferenceResult
             .inferredTypeArguments[node] = inferredTypes;
       }
     } else {
@@ -2605,10 +2612,10 @@
       DartType spreadTypeContext = const UnknownType();
       if (typeContextIsIterable && !typeContextIsMap) {
         spreadTypeContext = inferrer.typeSchemaEnvironment.getTypeAsInstanceOf(
-            unfuturedTypeContext,
+            unfuturedTypeContext as InterfaceType,
             inferrer.coreTypes.iterableClass,
             inferrer.library.library,
-            inferrer.coreTypes);
+            inferrer.coreTypes)!;
       } else if (!typeContextIsIterable && typeContextIsMap) {
         spreadTypeContext = new InterfaceType(
             inferrer.coreTypes.mapClass,
@@ -2623,15 +2630,15 @@
             inferredKeyType,
             inferredValueType,
             spreadTypeContext,
-            actualTypes,
-            actualTypesForSet,
-            inferredSpreadTypes,
-            inferredConditionTypes,
+            actualTypes!,
+            actualTypesForSet!,
+            inferredSpreadTypes!,
+            inferredConditionTypes!,
             inferenceNeeded,
             typeChecksNeeded);
         node.entries[index] = entry..parent = node;
         if (inferenceNeeded) {
-          formalTypes.add(mapType.typeArguments[0]);
+          formalTypes!.add(mapType.typeArguments[0]);
           formalTypes.add(mapType.typeArguments[1]);
         }
       }
@@ -2688,8 +2695,8 @@
                 setLiteral.expressions[i],
                 setLiteral,
                 setLiteral.typeArgument,
-                inferredSpreadTypes,
-                inferredConditionTypes);
+                inferredSpreadTypes!,
+                inferredConditionTypes!);
           }
         }
 
@@ -2700,7 +2707,7 @@
       if (canBeSet && canBeMap && node.entries.isNotEmpty) {
         Expression replacement = node;
         if (!inferrer.isTopLevel) {
-          replacement = inferrer.helper.buildProblem(
+          replacement = inferrer.helper!.buildProblem(
               messageCantDisambiguateNotEnoughInformation, node.fileOffset, 1);
         }
         return new ExpressionInferenceResult(
@@ -2710,7 +2717,7 @@
       if (!canBeSet && !canBeMap) {
         Expression replacement = node;
         if (!inferrer.isTopLevel) {
-          replacement = inferrer.helper.buildProblem(
+          replacement = inferrer.helper!.buildProblem(
               messageCantDisambiguateAmbiguousInformation, node.fileOffset, 1);
         }
         return new ExpressionInferenceResult(
@@ -2723,7 +2730,7 @@
           formalTypes,
           actualTypes,
           typeContext,
-          inferredTypes,
+          inferredTypes!,
           inferrer.library.library);
       inferredKeyType = inferredTypes[0];
       inferredValueType = inferredTypes[1];
@@ -2739,7 +2746,7 @@
     if (typeChecksNeeded) {
       for (int index = 0; index < node.entries.length; ++index) {
         MapLiteralEntry entry = checkMapEntry(node.entries[index], node.keyType,
-            node.valueType, inferredSpreadTypes, inferredConditionTypes);
+            node.valueType, inferredSpreadTypes!, inferredConditionTypes!);
         node.entries[index] = entry..parent = node;
       }
     }
@@ -2751,7 +2758,7 @@
       // none of them, so we may just check one.
       if (inferenceNeeded) {
         library.checkBoundsInMapLiteral(
-            node, inferrer.typeSchemaEnvironment, inferrer.helper.uri,
+            node, inferrer.typeSchemaEnvironment, inferrer.helper!.uri,
             inferred: true);
       }
     }
@@ -2787,7 +2794,7 @@
   ExpressionInferenceResult visitNamedFunctionExpressionJudgment(
       NamedFunctionExpressionJudgment node, DartType typeContext) {
     ExpressionInferenceResult initializerResult =
-        inferrer.inferExpression(node.variable.initializer, typeContext, true);
+        inferrer.inferExpression(node.variable.initializer!, typeContext, true);
     node.variable.initializer = initializerResult.expression
       ..parent = node.variable;
     node.variable.type = initializerResult.inferredType;
@@ -2929,7 +2936,7 @@
   ExpressionInferenceResult visitPropertyPostIncDec(
       PropertyPostIncDec node, DartType typeContext) {
     if (node.variable != null) {
-      inferrer.inferSyntheticVariable(node.variable);
+      inferrer.inferSyntheticVariable(node.variable!);
     }
     inferrer.inferSyntheticVariable(node.read);
     inferrer.inferSyntheticVariable(node.write);
@@ -2938,7 +2945,7 @@
     Expression replacement;
     if (node.variable != null) {
       replacement = new Let(
-          node.variable,
+          node.variable!,
           createLet(
               node.read, createLet(node.write, createVariableGet(node.read))))
         ..fileOffset = node.fileOffset;
@@ -2960,7 +2967,7 @@
     Expression receiver = receiverResult.nullAwareAction;
     DartType receiverType = receiverResult.nullAwareActionType;
 
-    VariableDeclaration receiverVariable;
+    VariableDeclaration? receiverVariable;
     Expression readReceiver;
     Expression writeReceiver;
     if (isPureExpression(receiver)) {
@@ -3065,7 +3072,7 @@
 
     Member equalsMember = inferrer
         .findInterfaceMember(readType, equalsName, node.fileOffset)
-        .member;
+        .member!;
 
     DartType nonNullableReadType = readType.toNonNull();
     DartType inferredType = inferrer.typeSchemaEnvironment
@@ -3129,7 +3136,7 @@
 
     Member equalsMember = inferrer
         .findInterfaceMember(readType, equalsName, node.fileOffset)
-        .member;
+        .member!;
 
     DartType originalReadType = readType;
     DartType nonNullableReadType = originalReadType.toNonNull();
@@ -3219,7 +3226,7 @@
     Expression receiver = receiverResult.nullAwareAction;
     DartType receiverType = receiverResult.nullAwareActionType;
 
-    VariableDeclaration receiverVariable;
+    VariableDeclaration? receiverVariable;
     if (!node.forEffect && !isPureExpression(receiver)) {
       receiverVariable = createVariable(receiver, receiverType);
       receiver = createVariableGet(receiverVariable);
@@ -3238,7 +3245,7 @@
 
     Expression index = inferrer.ensureAssignableResult(indexType, indexResult);
 
-    VariableDeclaration indexVariable;
+    VariableDeclaration? indexVariable;
     if (!node.forEffect && !isPureExpression(index)) {
       indexVariable = createVariable(index, indexResult.inferredType);
       index = createVariableGet(indexVariable);
@@ -3248,8 +3255,8 @@
         .inferExpression(node.value, valueType, true, isVoidAllowed: true);
     Expression value = inferrer.ensureAssignableResult(valueType, valueResult);
 
-    VariableDeclaration valueVariable;
-    Expression returnedValue;
+    VariableDeclaration? valueVariable;
+    Expression? returnedValue;
     if (node.forEffect) {
     } else if (isPureExpression(value)) {
       returnedValue = clonePureExpression(value);
@@ -3272,7 +3279,7 @@
     } else {
       VariableDeclaration assignmentVariable =
           createVariable(assignment, const VoidType());
-      replacement = createLet(assignmentVariable, returnedValue);
+      replacement = createLet(assignmentVariable, returnedValue!);
       if (valueVariable != null) {
         replacement = createLet(valueVariable, replacement);
       }
@@ -3291,21 +3298,21 @@
   ExpressionInferenceResult visitSuperIndexSet(
       SuperIndexSet node, DartType typeContext) {
     ObjectAccessTarget indexSetTarget = node.setter != null
-        ? new ObjectAccessTarget.interfaceMember(node.setter,
+        ? new ObjectAccessTarget.interfaceMember(node.setter!,
             isPotentiallyNullable: false)
         : const ObjectAccessTarget.missing();
 
     DartType indexType =
-        inferrer.getIndexKeyType(indexSetTarget, inferrer.thisType);
+        inferrer.getIndexKeyType(indexSetTarget, inferrer.thisType!);
     DartType valueType =
-        inferrer.getIndexSetValueType(indexSetTarget, inferrer.thisType);
+        inferrer.getIndexSetValueType(indexSetTarget, inferrer.thisType!);
 
     ExpressionInferenceResult indexResult = inferrer
         .inferExpression(node.index, indexType, true, isVoidAllowed: true);
 
     Expression index = inferrer.ensureAssignableResult(indexType, indexResult);
 
-    VariableDeclaration indexVariable;
+    VariableDeclaration? indexVariable;
     if (!isPureExpression(index)) {
       indexVariable = createVariable(index, indexResult.inferredType);
       index = createVariableGet(indexVariable);
@@ -3315,7 +3322,7 @@
         .inferExpression(node.value, valueType, true, isVoidAllowed: true);
     Expression value = inferrer.ensureAssignableResult(valueType, valueResult);
 
-    VariableDeclaration valueVariable;
+    VariableDeclaration? valueVariable;
     Expression returnedValue;
     if (isPureExpression(value)) {
       returnedValue = clonePureExpression(value);
@@ -3339,12 +3346,12 @@
           inferrer.uriForInstrumentation,
           node.fileOffset,
           'target',
-          new InstrumentationValueForMember(node.setter));
+          new InstrumentationValueForMember(node.setter!));
       assignment = new SuperMethodInvocation(
           indexSetName,
           new Arguments(<Expression>[index, value])
             ..fileOffset = node.fileOffset,
-          indexSetTarget.member)
+          indexSetTarget.member as Procedure)
         ..fileOffset = node.fileOffset;
     }
     VariableDeclaration assignmentVariable =
@@ -3375,7 +3382,7 @@
     Expression receiver =
         inferrer.ensureAssignableResult(receiverType, receiverResult);
 
-    VariableDeclaration receiverVariable;
+    VariableDeclaration? receiverVariable;
     if (!isPureExpression(receiver)) {
       receiverVariable = createVariable(receiver, receiverType);
       receiver = createVariableGet(receiverVariable);
@@ -3396,7 +3403,7 @@
         .inferExpression(node.value, valueType, true, isVoidAllowed: true);
     Expression value = inferrer.ensureAssignableResult(valueType, valueResult);
 
-    VariableDeclaration valueVariable;
+    VariableDeclaration? valueVariable;
     Expression returnedValue;
     if (isPureExpression(value)) {
       returnedValue = clonePureExpression(value);
@@ -3437,7 +3444,7 @@
     Expression receiver = receiverResult.nullAwareAction;
     DartType receiverType = receiverResult.nullAwareActionType;
 
-    VariableDeclaration receiverVariable;
+    VariableDeclaration? receiverVariable;
     Expression readReceiver = receiver;
     Expression writeReceiver;
     if (isPureExpression(readReceiver)) {
@@ -3470,10 +3477,10 @@
     ExpressionInferenceResult indexResult = inferrer
         .inferExpression(node.index, readIndexType, true, isVoidAllowed: true);
 
-    VariableDeclaration indexVariable;
+    VariableDeclaration? indexVariable;
     Expression readIndex = indexResult.expression;
     Map<DartType, NonPromotionReason> Function() whyNotPromotedIndex =
-        inferrer.flowAnalysis?.whyNotPromoted(readIndex);
+        inferrer.flowAnalysis.whyNotPromoted(readIndex);
     Expression writeIndex;
     if (isPureExpression(readIndex)) {
       writeIndex = clonePureExpression(readIndex);
@@ -3503,7 +3510,7 @@
 
     Member equalsMember = inferrer
         .findInterfaceMember(readType, equalsName, node.testOffset)
-        .member;
+        .member!;
 
     writeIndex = inferrer.ensureAssignable(
         writeIndexType, indexResult.inferredType, writeIndex,
@@ -3519,8 +3526,8 @@
         .getStandardUpperBound(nonNullableReadType, valueResult.inferredType,
             inferrer.library.library);
 
-    VariableDeclaration valueVariable;
-    Expression returnedValue;
+    VariableDeclaration? valueVariable;
+    Expression? returnedValue;
     if (node.forEffect) {
       // No need for value variable.
     } else if (isPureExpression(value)) {
@@ -3597,7 +3604,7 @@
           !identical(nonNullableReadType, readType)) {
         variableGet.promotedType = nonNullableReadType;
       }
-      Expression result = createLet(writeVariable, returnedValue);
+      Expression result = createLet(writeVariable, returnedValue!);
       if (valueVariable != null) {
         result = createLet(valueVariable, result);
       }
@@ -3624,34 +3631,34 @@
   ExpressionInferenceResult visitIfNullSuperIndexSet(
       IfNullSuperIndexSet node, DartType typeContext) {
     ObjectAccessTarget readTarget = node.getter != null
-        ? new ObjectAccessTarget.interfaceMember(node.getter,
+        ? new ObjectAccessTarget.interfaceMember(node.getter!,
             isPotentiallyNullable: false)
         : const ObjectAccessTarget.missing();
 
-    DartType readType = inferrer.getReturnType(readTarget, inferrer.thisType);
+    DartType readType = inferrer.getReturnType(readTarget, inferrer.thisType!);
     reportNonNullableInNullAwareWarningIfNeeded(
         readType, "??=", node.readOffset);
     DartType readIndexType =
-        inferrer.getIndexKeyType(readTarget, inferrer.thisType);
+        inferrer.getIndexKeyType(readTarget, inferrer.thisType!);
 
     Member equalsMember = inferrer
         .findInterfaceMember(readType, equalsName, node.testOffset)
-        .member;
+        .member!;
 
     ObjectAccessTarget writeTarget = node.setter != null
-        ? new ObjectAccessTarget.interfaceMember(node.setter,
+        ? new ObjectAccessTarget.interfaceMember(node.setter!,
             isPotentiallyNullable: false)
         : const ObjectAccessTarget.missing();
 
     DartType writeIndexType =
-        inferrer.getIndexKeyType(writeTarget, inferrer.thisType);
+        inferrer.getIndexKeyType(writeTarget, inferrer.thisType!);
     DartType valueType =
-        inferrer.getIndexSetValueType(writeTarget, inferrer.thisType);
+        inferrer.getIndexSetValueType(writeTarget, inferrer.thisType!);
 
     ExpressionInferenceResult indexResult = inferrer
         .inferExpression(node.index, readIndexType, true, isVoidAllowed: true);
 
-    VariableDeclaration indexVariable;
+    VariableDeclaration? indexVariable;
     Expression readIndex = indexResult.expression;
     Expression writeIndex;
     if (isPureExpression(readIndex)) {
@@ -3678,14 +3685,14 @@
           inferrer.uriForInstrumentation,
           node.readOffset,
           'target',
-          new InstrumentationValueForMember(node.getter));
+          new InstrumentationValueForMember(node.getter!));
       read = new SuperMethodInvocation(
           indexGetName,
           new Arguments(<Expression>[
             readIndex,
           ])
             ..fileOffset = node.readOffset,
-          readTarget.member)
+          readTarget.member as Procedure)
         ..fileOffset = node.readOffset;
     }
 
@@ -3700,8 +3707,8 @@
         .getStandardUpperBound(nonNullableReadType, valueResult.inferredType,
             inferrer.library.library);
 
-    VariableDeclaration valueVariable;
-    Expression returnedValue;
+    VariableDeclaration? valueVariable;
+    Expression? returnedValue;
     if (node.forEffect) {
       // No need for a value variable.
     } else if (isPureExpression(value)) {
@@ -3723,12 +3730,12 @@
           inferrer.uriForInstrumentation,
           node.writeOffset,
           'target',
-          new InstrumentationValueForMember(node.setter));
+          new InstrumentationValueForMember(node.setter!));
       write = new SuperMethodInvocation(
           indexSetName,
           new Arguments(<Expression>[writeIndex, value])
             ..fileOffset = node.writeOffset,
-          writeTarget.member)
+          writeTarget.member as Procedure)
         ..fileOffset = node.writeOffset;
     }
 
@@ -3767,7 +3774,7 @@
           !identical(nonNullableReadType, readType)) {
         readVariableGet.promotedType = nonNullableReadType;
       }
-      Expression result = createLet(writeVariable, returnedValue);
+      Expression result = createLet(writeVariable, returnedValue!);
       if (valueVariable != null) {
         result = createLet(valueVariable, result);
       }
@@ -3798,7 +3805,7 @@
     Expression receiver =
         inferrer.ensureAssignableResult(receiverType, receiverResult);
 
-    VariableDeclaration receiverVariable;
+    VariableDeclaration? receiverVariable;
     Expression readReceiver;
     Expression writeReceiver;
     if (isPureExpression(receiver)) {
@@ -3812,14 +3819,14 @@
 
     ObjectAccessTarget readTarget = node.getter != null
         ? new ExtensionAccessTarget(
-            node.getter, null, ProcedureKind.Operator, extensionTypeArguments)
+            node.getter!, null, ProcedureKind.Operator, extensionTypeArguments)
         : const ObjectAccessTarget.missing();
 
     DartType readIndexType = inferrer.getIndexKeyType(readTarget, receiverType);
 
     ObjectAccessTarget writeTarget = node.setter != null
         ? new ExtensionAccessTarget(
-            node.setter, null, ProcedureKind.Operator, extensionTypeArguments)
+            node.setter!, null, ProcedureKind.Operator, extensionTypeArguments)
         : const ObjectAccessTarget.missing();
 
     DartType writeIndexType =
@@ -3830,7 +3837,7 @@
     ExpressionInferenceResult indexResult = inferrer
         .inferExpression(node.index, readIndexType, true, isVoidAllowed: true);
 
-    VariableDeclaration indexVariable;
+    VariableDeclaration? indexVariable;
     Expression readIndex = indexResult.expression;
     Expression writeIndex;
     if (isPureExpression(readIndex)) {
@@ -3860,7 +3867,7 @@
 
     Member equalsMember = inferrer
         .findInterfaceMember(readType, equalsName, node.testOffset)
-        .member;
+        .member!;
 
     writeIndex = inferrer.ensureAssignable(
         writeIndexType, indexResult.inferredType, writeIndex);
@@ -3875,8 +3882,8 @@
         .getStandardUpperBound(nonNullableReadType, valueResult.inferredType,
             inferrer.library.library);
 
-    VariableDeclaration valueVariable;
-    Expression returnedValue;
+    VariableDeclaration? valueVariable;
+    Expression? returnedValue;
     if (node.forEffect) {
       // No need for a value variable.
     } else if (isPureExpression(value)) {
@@ -3935,7 +3942,7 @@
           !identical(nonNullableReadType, readType)) {
         readVariableGet.promotedType = nonNullableReadType;
       }
-      Expression result = createLet(writeVariable, returnedValue);
+      Expression result = createLet(writeVariable, returnedValue!);
       if (valueVariable != null) {
         result = createLet(valueVariable, result);
       }
@@ -3967,12 +3974,13 @@
   /// negated to perform a != operation.
   ExpressionInferenceResult _computeEqualsExpression(
       int fileOffset, Expression left, DartType leftType, Expression right,
-      {bool isNot}) {
+      {required bool isNot}) {
+    // ignore: unnecessary_null_comparison
     assert(isNot != null);
     inferrer.flowAnalysis.equalityOp_rightBegin(left, leftType);
     bool typeNeeded = !inferrer.isTopLevel;
 
-    Expression equals;
+    Expression? equals;
     ExpressionInferenceResult rightResult = inferrer.inferExpression(
         right, const UnknownType(), typeNeeded,
         isVoidAllowed: false);
@@ -4008,11 +4016,11 @@
         "Unexpected equals target $equalsTarget for "
         "$left ($leftType) == $right.");
     if (inferrer.instrumentation != null && leftType == const DynamicType()) {
-      inferrer.instrumentation.record(
+      inferrer.instrumentation!.record(
           inferrer.uriForInstrumentation,
           fileOffset,
           'target',
-          new InstrumentationValueForMember(equalsTarget.member));
+          new InstrumentationValueForMember(equalsTarget.member!));
     }
     DartType rightType =
         inferrer.getPositionalParameterTypeForTarget(equalsTarget, leftType, 0);
@@ -4033,7 +4041,8 @@
         FunctionType functionType =
             inferrer.getFunctionType(equalsTarget, leftType);
         equals = new EqualsCall(left, right,
-            functionType: functionType, interfaceTarget: equalsTarget.member)
+            functionType: functionType,
+            interfaceTarget: equalsTarget.member as Procedure)
           ..fileOffset = fileOffset;
         if (isNot) {
           equals = new Not(equals)..fileOffset = fileOffset;
@@ -4046,9 +4055,9 @@
         Member target = inferrer
             .findInterfaceMember(const DynamicType(), equalsName, -1,
                 instrumented: false)
-            .member;
+            .member!;
         equals = new EqualsCall(left, right,
-            functionType: functionType, interfaceTarget: target)
+            functionType: functionType, interfaceTarget: target as Procedure)
           ..fileOffset = fileOffset;
         if (isNot) {
           equals = new Not(equals)..fileOffset = fileOffset;
@@ -4091,7 +4100,7 @@
       DartType leftType,
       Name binaryName,
       Expression right,
-      Map<DartType, NonPromotionReason> Function() whyNotPromoted) {
+      Map<DartType, NonPromotionReason> Function()? whyNotPromoted) {
     assert(binaryName != equalsName);
 
     ObjectAccessTarget binaryTarget = inferrer.findInterfaceMember(
@@ -4122,7 +4131,7 @@
     ExpressionInferenceResult rightResult = inferrer.inferExpression(
         right, rightContextType, typeNeeded,
         isVoidAllowed: true);
-    if (rightResult.inferredType == null) {
+    if (identical(rightResult.inferredType, noInferredType)) {
       assert(!typeNeeded,
           "Missing right type for overloaded arithmetic operator.");
       return new ExpressionInferenceResult(
@@ -4159,7 +4168,7 @@
       case ObjectAccessTargetKind.nullableExtensionMember:
         assert(binaryTarget.extensionMethodKind != ProcedureKind.Setter);
         binary = new StaticInvocation(
-            binaryTarget.member,
+            binaryTarget.member as Procedure,
             new Arguments(<Expression>[
               left,
               right,
@@ -4244,11 +4253,11 @@
         if ((binaryTarget.isInstanceMember || binaryTarget.isObjectMember) &&
             inferrer.instrumentation != null &&
             leftType == const DynamicType()) {
-          inferrer.instrumentation.record(
+          inferrer.instrumentation!.record(
               inferrer.uriForInstrumentation,
               fileOffset,
               'target',
-              new InstrumentationValueForMember(binaryTarget.member));
+              new InstrumentationValueForMember(binaryTarget.member!));
         }
 
         if (inferrer.useNewMethodInvocationEncoding) {
@@ -4262,7 +4271,7 @@
                 ..fileOffset = fileOffset,
               functionType: new FunctionType(
                   [rightType], binaryType, inferrer.library.nonNullable),
-              interfaceTarget: binaryTarget.member)
+              interfaceTarget: binaryTarget.member as Procedure)
             ..fileOffset = fileOffset;
         } else {
           binary = new MethodInvocation(
@@ -4279,7 +4288,7 @@
         if (binaryCheckKind ==
             MethodContravarianceCheckKind.checkMethodReturn) {
           if (inferrer.instrumentation != null) {
-            inferrer.instrumentation.record(
+            inferrer.instrumentation!.record(
                 inferrer.uriForInstrumentation,
                 fileOffset,
                 'checkReturn',
@@ -4295,13 +4304,13 @@
     }
 
     if (!inferrer.isTopLevel && binaryTarget.isNullable) {
-      List<LocatedMessage> context = inferrer.getWhyNotPromotedContext(
+      List<LocatedMessage>? context = inferrer.getWhyNotPromotedContext(
           whyNotPromoted?.call(),
           binary,
           (type) => !type.isPotentiallyNullable);
       return new ExpressionInferenceResult(
           binaryType,
-          inferrer.helper.wrapInProblem(
+          inferrer.helper!.wrapInProblem(
               binary,
               templateNullableOperatorCallError.withArguments(
                   binaryName.text, leftType, inferrer.isNonNullableByDefault),
@@ -4348,7 +4357,7 @@
       case ObjectAccessTargetKind.nullableExtensionMember:
         assert(unaryTarget.extensionMethodKind != ProcedureKind.Setter);
         unary = new StaticInvocation(
-            unaryTarget.member,
+            unaryTarget.member as Procedure,
             new Arguments(<Expression>[
               expression,
             ], types: unaryTarget.inferredExtensionTypeArguments)
@@ -4405,11 +4414,11 @@
         if ((unaryTarget.isInstanceMember || unaryTarget.isObjectMember) &&
             inferrer.instrumentation != null &&
             expressionType == const DynamicType()) {
-          inferrer.instrumentation.record(
+          inferrer.instrumentation!.record(
               inferrer.uriForInstrumentation,
               fileOffset,
               'target',
-              new InstrumentationValueForMember(unaryTarget.member));
+              new InstrumentationValueForMember(unaryTarget.member!));
         }
 
         if (inferrer.useNewMethodInvocationEncoding) {
@@ -4420,7 +4429,7 @@
               new Arguments(<Expression>[])..fileOffset = fileOffset,
               functionType: new FunctionType(
                   <DartType>[], unaryType, inferrer.library.nonNullable),
-              interfaceTarget: unaryTarget.member)
+              interfaceTarget: unaryTarget.member as Procedure)
             ..fileOffset = fileOffset;
         } else {
           unary = new MethodInvocation(
@@ -4433,7 +4442,7 @@
 
         if (unaryCheckKind == MethodContravarianceCheckKind.checkMethodReturn) {
           if (inferrer.instrumentation != null) {
-            inferrer.instrumentation.record(
+            inferrer.instrumentation!.record(
                 inferrer.uriForInstrumentation,
                 fileOffset,
                 'checkReturn',
@@ -4453,13 +4462,13 @@
     }
 
     if (!inferrer.isTopLevel && unaryTarget.isNullable) {
-      List<LocatedMessage> context = inferrer.getWhyNotPromotedContext(
-          whyNotPromoted?.call(), unary, (type) => !type.isPotentiallyNullable);
+      List<LocatedMessage>? context = inferrer.getWhyNotPromotedContext(
+          whyNotPromoted(), unary, (type) => !type.isPotentiallyNullable);
       // TODO(johnniwinther): Special case 'unary-' in messages. It should
       // probably be referred to as "Unary operator '-' ...".
       return new ExpressionInferenceResult(
           unaryType,
-          inferrer.helper.wrapInProblem(
+          inferrer.helper!.wrapInProblem(
               unary,
               templateNullableOperatorCallError.withArguments(unaryName.text,
                   expressionType, inferrer.isNonNullableByDefault),
@@ -4499,7 +4508,7 @@
       case ObjectAccessTargetKind.extensionMember:
       case ObjectAccessTargetKind.nullableExtensionMember:
         read = new StaticInvocation(
-            readTarget.member,
+            readTarget.member as Procedure,
             new Arguments(<Expression>[
               readReceiver,
               readIndex,
@@ -4606,7 +4615,7 @@
                 ..fileOffset = fileOffset,
               functionType: new FunctionType(
                   [indexType], readType, inferrer.library.nonNullable),
-              interfaceTarget: readTarget.member)
+              interfaceTarget: readTarget.member as Procedure)
             ..fileOffset = fileOffset;
         } else {
           read = new MethodInvocation(
@@ -4621,7 +4630,7 @@
         }
         if (readCheckKind == MethodContravarianceCheckKind.checkMethodReturn) {
           if (inferrer.instrumentation != null) {
-            inferrer.instrumentation.record(
+            inferrer.instrumentation!.record(
                 inferrer.uriForInstrumentation,
                 fileOffset,
                 'checkReturn',
@@ -4643,7 +4652,7 @@
     if (!inferrer.isTopLevel && readTarget.isNullable) {
       return new ExpressionInferenceResult(
           readType,
-          inferrer.helper.wrapInProblem(
+          inferrer.helper!.wrapInProblem(
               read,
               templateNullableOperatorCallError.withArguments(indexGetName.text,
                   receiverType, inferrer.isNonNullableByDefault),
@@ -4684,7 +4693,7 @@
       case ObjectAccessTargetKind.nullableExtensionMember:
         assert(writeTarget.extensionMethodKind != ProcedureKind.Setter);
         write = new StaticInvocation(
-            writeTarget.member,
+            writeTarget.member as Procedure,
             new Arguments(<Expression>[receiver, index, value],
                 types: writeTarget.inferredExtensionTypeArguments)
               ..fileOffset = fileOffset)
@@ -4750,7 +4759,6 @@
             ..fileOffset = fileOffset;
           break;
         }
-        break;
       case ObjectAccessTargetKind.instanceMember:
       case ObjectAccessTargetKind.objectMember:
       case ObjectAccessTargetKind.nullableInstanceMember:
@@ -4777,7 +4785,7 @@
                 ..fileOffset = fileOffset,
               functionType: new FunctionType([indexType, valueType],
                   const VoidType(), inferrer.library.nonNullable),
-              interfaceTarget: writeTarget.member)
+              interfaceTarget: writeTarget.member as Procedure)
             ..fileOffset = fileOffset;
         } else {
           write = new MethodInvocation(
@@ -4791,7 +4799,7 @@
         break;
     }
     if (!inferrer.isTopLevel && writeTarget.isNullable) {
-      return inferrer.helper.wrapInProblem(
+      return inferrer.helper!.wrapInProblem(
           write,
           templateNullableOperatorCallError.withArguments(
               indexSetName.text, receiverType, inferrer.isNonNullableByDefault),
@@ -4815,7 +4823,8 @@
       DartType receiverType,
       Name propertyName,
       DartType typeContext,
-      {bool isThisReceiver}) {
+      {required bool isThisReceiver}) {
+    // ignore: unnecessary_null_comparison
     assert(isThisReceiver != null);
 
     ObjectAccessTarget readTarget = inferrer.findInterfaceMember(
@@ -4825,7 +4834,7 @@
     DartType readType = inferrer.getGetterType(readTarget, receiverType);
 
     Expression read;
-    ExpressionInferenceResult readResult;
+    ExpressionInferenceResult? readResult;
     switch (readTarget.kind) {
       case ObjectAccessTargetKind.missing:
         read = inferrer.createMissingPropertyGet(
@@ -4841,7 +4850,7 @@
         switch (readTarget.extensionMethodKind) {
           case ProcedureKind.Getter:
             read = new StaticInvocation(
-                readTarget.member,
+                readTarget.member as Procedure,
                 new Arguments(<Expression>[
                   receiver,
                 ], types: readTarget.inferredExtensionTypeArguments)
@@ -4850,7 +4859,7 @@
             break;
           case ProcedureKind.Method:
             read = new StaticInvocation(
-                readTarget.tearoffTarget,
+                readTarget.tearoffTarget as Procedure,
                 new Arguments(<Expression>[
                   receiver,
                 ], types: readTarget.inferredExtensionTypeArguments)
@@ -4862,8 +4871,7 @@
           case ProcedureKind.Setter:
           case ProcedureKind.Factory:
           case ProcedureKind.Operator:
-            unhandled('$readTarget', "inferPropertyGet", null, null);
-            break;
+            unhandled('$readTarget', "inferPropertyGet", -1, null);
         }
         break;
       case ObjectAccessTargetKind.never:
@@ -4907,15 +4915,12 @@
       case ObjectAccessTargetKind.instanceMember:
       case ObjectAccessTargetKind.objectMember:
       case ObjectAccessTargetKind.nullableInstanceMember:
-        Member member = readTarget.member;
+        Member member = readTarget.member!;
         if ((readTarget.isInstanceMember || readTarget.isObjectMember) &&
             inferrer.instrumentation != null &&
             receiverType == const DynamicType()) {
-          inferrer.instrumentation.record(
-              inferrer.uriForInstrumentation,
-              fileOffset,
-              'target',
-              new InstrumentationValueForMember(readTarget.member));
+          inferrer.instrumentation!.record(inferrer.uriForInstrumentation,
+              fileOffset, 'target', new InstrumentationValueForMember(member));
         }
         if (inferrer.useNewMethodInvocationEncoding) {
           InstanceAccessKind kind;
@@ -4934,11 +4939,11 @@
           }
           if (member is Procedure && member.kind == ProcedureKind.Method) {
             read = new InstanceTearOff(kind, receiver, propertyName,
-                interfaceTarget: readTarget.member, resultType: readType)
+                interfaceTarget: member, resultType: readType)
               ..fileOffset = fileOffset;
           } else {
             read = new InstanceGet(kind, receiver, propertyName,
-                interfaceTarget: readTarget.member, resultType: readType)
+                interfaceTarget: member, resultType: readType)
               ..fileOffset = fileOffset;
           }
         } else {
@@ -4948,21 +4953,21 @@
         bool checkReturn = false;
         if ((readTarget.isInstanceMember || readTarget.isObjectMember) &&
             !isThisReceiver) {
-          Member interfaceMember = readTarget.member;
+          Member interfaceMember = readTarget.member!;
           if (interfaceMember is Procedure) {
             checkReturn =
                 TypeInferrerImpl.returnedTypeParametersOccurNonCovariantly(
-                    interfaceMember.enclosingClass,
+                    interfaceMember.enclosingClass!,
                     interfaceMember.function.returnType);
           } else if (interfaceMember is Field) {
             checkReturn =
                 TypeInferrerImpl.returnedTypeParametersOccurNonCovariantly(
-                    interfaceMember.enclosingClass, interfaceMember.type);
+                    interfaceMember.enclosingClass!, interfaceMember.type);
           }
         }
         if (checkReturn) {
           if (inferrer.instrumentation != null) {
-            inferrer.instrumentation.record(
+            inferrer.instrumentation!.record(
                 inferrer.uriForInstrumentation,
                 fileOffset,
                 'checkReturn',
@@ -4993,7 +4998,7 @@
           read.fileOffset,
           propertyName.text.length,
           context: inferrer.getWhyNotPromotedContext(
-              inferrer.flowAnalysis?.whyNotPromoted(receiver)(),
+              inferrer.flowAnalysis.whyNotPromoted(receiver)(),
               read,
               (type) => !type.isPotentiallyNullable));
     }
@@ -5018,8 +5023,9 @@
       Name propertyName,
       ObjectAccessTarget writeTarget,
       Expression value,
-      {DartType valueType,
-      bool forEffect}) {
+      {DartType? valueType,
+      required bool forEffect}) {
+    // ignore: unnecessary_null_comparison
     assert(forEffect != null);
     assert(forEffect || valueType != null,
         "No value type provided for property set needed for value.");
@@ -5040,16 +5046,16 @@
       case ObjectAccessTargetKind.nullableExtensionMember:
         if (forEffect) {
           write = new StaticInvocation(
-              writeTarget.member,
+              writeTarget.member as Procedure,
               new Arguments(<Expression>[receiver, value],
                   types: writeTarget.inferredExtensionTypeArguments)
                 ..fileOffset = fileOffset)
             ..fileOffset = fileOffset;
         } else {
-          VariableDeclaration valueVariable = createVariable(value, valueType);
+          VariableDeclaration valueVariable = createVariable(value, valueType!);
           VariableDeclaration assignmentVariable = createVariable(
               new StaticInvocation(
-                  writeTarget.member,
+                  writeTarget.member as Procedure,
                   new Arguments(
                       <Expression>[receiver, createVariableGet(valueVariable)],
                       types: writeTarget.inferredExtensionTypeArguments)
@@ -5115,7 +5121,7 @@
               throw new UnsupportedError('Unexpected target kind $writeTarget');
           }
           write = new InstanceSet(kind, receiver, propertyName, value,
-              interfaceTarget: writeTarget.member)
+              interfaceTarget: writeTarget.member!)
             ..fileOffset = fileOffset;
         } else {
           write =
@@ -5125,7 +5131,7 @@
         break;
     }
     if (!inferrer.isTopLevel && writeTarget.isNullable) {
-      return inferrer.helper.wrapInProblem(
+      return inferrer.helper!.wrapInProblem(
           write,
           templateNullablePropertyAccessError.withArguments(
               propertyName.text, receiverType, inferrer.isNonNullableByDefault),
@@ -5146,7 +5152,7 @@
     Expression receiver = receiverResult.nullAwareAction;
     DartType receiverType = receiverResult.nullAwareActionType;
 
-    VariableDeclaration receiverVariable;
+    VariableDeclaration? receiverVariable;
     Expression readReceiver = receiver;
     Expression writeReceiver;
     if (isPureExpression(readReceiver)) {
@@ -5170,10 +5176,10 @@
     ExpressionInferenceResult indexResult = inferrer
         .inferExpression(node.index, readIndexType, true, isVoidAllowed: true);
 
-    VariableDeclaration indexVariable;
+    VariableDeclaration? indexVariable;
     Expression readIndex = indexResult.expression;
     Map<DartType, NonPromotionReason> Function() whyNotPromotedIndex =
-        inferrer.flowAnalysis?.whyNotPromoted(readIndex);
+        inferrer.flowAnalysis.whyNotPromoted(readIndex);
     Expression writeIndex;
     if (isPureExpression(readIndex)) {
       writeIndex = clonePureExpression(readIndex);
@@ -5198,7 +5204,7 @@
     Expression read = readResult.expression;
     DartType readType = readResult.inferredType;
 
-    VariableDeclaration leftVariable;
+    VariableDeclaration? leftVariable;
     Expression left;
     if (node.forEffect) {
       left = read;
@@ -5237,7 +5243,7 @@
     binary = inferrer.ensureAssignable(valueType, binaryType, binary,
         fileOffset: node.fileOffset);
 
-    VariableDeclaration valueVariable;
+    VariableDeclaration? valueVariable;
     Expression valueExpression;
     if (node.forEffect || node.forPostIncDec) {
       valueExpression = binary;
@@ -5278,7 +5284,7 @@
 
       VariableDeclaration writeVariable =
           createVariable(write, const VoidType());
-      inner = createLet(leftVariable,
+      inner = createLet(leftVariable!,
           createLet(writeVariable, createVariableGet(leftVariable)));
     } else {
       // Encode `o[a] += b` as:
@@ -5293,7 +5299,7 @@
 
       VariableDeclaration writeVariable =
           createVariable(write, const VoidType());
-      inner = createLet(valueVariable,
+      inner = createLet(valueVariable!,
           createLet(writeVariable, createVariableGet(valueVariable)));
     }
     if (indexVariable != null) {
@@ -5325,7 +5331,7 @@
     Expression receiver = receiverResult.nullAwareAction;
     DartType receiverType = receiverResult.nullAwareActionType;
 
-    VariableDeclaration receiverVariable =
+    VariableDeclaration? receiverVariable =
         createVariable(receiver, receiverType);
     NullAwareGuard nullAwareGuard =
         inferrer.createNullAwareGuard(receiverVariable);
@@ -5344,7 +5350,7 @@
     Expression read = readResult.expression;
     DartType readType = readResult.inferredType;
 
-    VariableDeclaration leftVariable;
+    VariableDeclaration? leftVariable;
     Expression left;
     if (node.forEffect) {
       left = read;
@@ -5376,7 +5382,7 @@
     binary = inferrer.ensureAssignable(valueType, binaryType, binary,
         fileOffset: node.fileOffset);
 
-    VariableDeclaration valueVariable;
+    VariableDeclaration? valueVariable;
     Expression valueExpression;
     if (node.forEffect || node.forPostIncDec) {
       valueExpression = binary;
@@ -5421,7 +5427,7 @@
 
       VariableDeclaration writeVariable =
           createVariable(write, const VoidType());
-      action = createLet(leftVariable,
+      action = createLet(leftVariable!,
           createLet(writeVariable, createVariableGet(leftVariable)));
     } else {
       // Encode `receiver?.propertyName binaryName= rhs` as:
@@ -5440,7 +5446,7 @@
 
       VariableDeclaration writeVariable =
           createVariable(write, const VoidType());
-      action = createLet(valueVariable,
+      action = createLet(valueVariable!,
           createLet(writeVariable, createVariableGet(valueVariable)));
     }
 
@@ -5451,18 +5457,18 @@
   ExpressionInferenceResult visitCompoundSuperIndexSet(
       CompoundSuperIndexSet node, DartType typeContext) {
     ObjectAccessTarget readTarget = node.getter != null
-        ? new ObjectAccessTarget.interfaceMember(node.getter,
+        ? new ObjectAccessTarget.interfaceMember(node.getter!,
             isPotentiallyNullable: false)
         : const ObjectAccessTarget.missing();
 
-    DartType readType = inferrer.getReturnType(readTarget, inferrer.thisType);
+    DartType readType = inferrer.getReturnType(readTarget, inferrer.thisType!);
     DartType readIndexType =
-        inferrer.getIndexKeyType(readTarget, inferrer.thisType);
+        inferrer.getIndexKeyType(readTarget, inferrer.thisType!);
 
     ExpressionInferenceResult indexResult = inferrer
         .inferExpression(node.index, readIndexType, true, isVoidAllowed: true);
 
-    VariableDeclaration indexVariable;
+    VariableDeclaration? indexVariable;
     Expression readIndex = indexResult.expression;
     Expression writeIndex;
     if (isPureExpression(readIndex)) {
@@ -5485,18 +5491,18 @@
           inferrer.uriForInstrumentation,
           node.readOffset,
           'target',
-          new InstrumentationValueForMember(node.getter));
+          new InstrumentationValueForMember(node.getter!));
       read = new SuperMethodInvocation(
           indexGetName,
           new Arguments(<Expression>[
             readIndex,
           ])
             ..fileOffset = node.readOffset,
-          readTarget.member)
+          readTarget.member as Procedure)
         ..fileOffset = node.readOffset;
     }
 
-    VariableDeclaration leftVariable;
+    VariableDeclaration? leftVariable;
     Expression left;
     if (node.forEffect) {
       left = read;
@@ -5507,15 +5513,15 @@
       left = read;
     }
     ObjectAccessTarget writeTarget = node.setter != null
-        ? new ObjectAccessTarget.interfaceMember(node.setter,
+        ? new ObjectAccessTarget.interfaceMember(node.setter!,
             isPotentiallyNullable: false)
         : const ObjectAccessTarget.missing();
 
     DartType writeIndexType =
-        inferrer.getIndexKeyType(writeTarget, inferrer.thisType);
+        inferrer.getIndexKeyType(writeTarget, inferrer.thisType!);
 
     DartType valueType =
-        inferrer.getIndexSetValueType(writeTarget, inferrer.thisType);
+        inferrer.getIndexSetValueType(writeTarget, inferrer.thisType!);
 
     ExpressionInferenceResult binaryResult = _computeBinaryExpression(
         node.binaryOffset,
@@ -5534,11 +5540,12 @@
     Expression binaryReplacement = inferrer.ensureAssignable(
         valueType, binaryType, binary,
         fileOffset: node.fileOffset);
+    // ignore: unnecessary_null_comparison
     if (binaryReplacement != null) {
       binary = binaryReplacement;
     }
 
-    VariableDeclaration valueVariable;
+    VariableDeclaration? valueVariable;
     Expression valueExpression;
     if (node.forEffect || node.forPostIncDec) {
       valueExpression = binary;
@@ -5557,12 +5564,12 @@
           inferrer.uriForInstrumentation,
           node.writeOffset,
           'target',
-          new InstrumentationValueForMember(node.setter));
+          new InstrumentationValueForMember(node.setter!));
       write = new SuperMethodInvocation(
           indexSetName,
           new Arguments(<Expression>[writeIndex, valueExpression])
             ..fileOffset = node.writeOffset,
-          writeTarget.member)
+          writeTarget.member as Procedure)
         ..fileOffset = node.writeOffset;
     }
 
@@ -5587,7 +5594,7 @@
 
       VariableDeclaration writeVariable =
           createVariable(write, const VoidType());
-      replacement = createLet(leftVariable,
+      replacement = createLet(leftVariable!,
           createLet(writeVariable, createVariableGet(leftVariable)));
     } else {
       // Encode `super[a] += b` as:
@@ -5602,7 +5609,7 @@
 
       VariableDeclaration writeVariable =
           createVariable(write, const VoidType());
-      replacement = createLet(valueVariable,
+      replacement = createLet(valueVariable!,
           createLet(writeVariable, createVariableGet(valueVariable)));
     }
     if (indexVariable != null) {
@@ -5624,7 +5631,7 @@
 
     ObjectAccessTarget readTarget = node.getter != null
         ? new ExtensionAccessTarget(
-            node.getter, null, ProcedureKind.Operator, extensionTypeArguments)
+            node.getter!, null, ProcedureKind.Operator, extensionTypeArguments)
         : const ObjectAccessTarget.missing();
 
     DartType receiverType = inferrer.getExtensionReceiverType(
@@ -5633,7 +5640,7 @@
     Expression receiver =
         inferrer.ensureAssignableResult(receiverType, receiverResult);
 
-    VariableDeclaration receiverVariable;
+    VariableDeclaration? receiverVariable;
     Expression readReceiver;
     Expression writeReceiver;
     if (isPureExpression(receiver)) {
@@ -5650,7 +5657,7 @@
     ExpressionInferenceResult indexResult = inferrer
         .inferExpression(node.index, readIndexType, true, isVoidAllowed: true);
 
-    VariableDeclaration indexVariable;
+    VariableDeclaration? indexVariable;
     Expression readIndex = indexResult.expression;
     Expression writeIndex;
     if (isPureExpression(readIndex)) {
@@ -5675,7 +5682,7 @@
     Expression read = readResult.expression;
     DartType readType = readResult.inferredType;
 
-    VariableDeclaration leftVariable;
+    VariableDeclaration? leftVariable;
     Expression left;
     if (node.forEffect) {
       left = read;
@@ -5688,7 +5695,7 @@
 
     ObjectAccessTarget writeTarget = node.setter != null
         ? new ExtensionAccessTarget(
-            node.setter, null, ProcedureKind.Operator, extensionTypeArguments)
+            node.setter!, null, ProcedureKind.Operator, extensionTypeArguments)
         : const ObjectAccessTarget.missing();
 
     DartType writeIndexType =
@@ -5714,7 +5721,7 @@
     binary = inferrer.ensureAssignable(valueType, binaryType, binary,
         fileOffset: node.fileOffset);
 
-    VariableDeclaration valueVariable;
+    VariableDeclaration? valueVariable;
     Expression valueExpression;
     if (node.forEffect || node.forPostIncDec) {
       valueExpression = binary;
@@ -5759,7 +5766,7 @@
 
       VariableDeclaration writeVariable =
           createVariable(write, const VoidType());
-      replacement = createLet(leftVariable,
+      replacement = createLet(leftVariable!,
           createLet(writeVariable, createVariableGet(leftVariable)));
     } else {
       // Encode `Extension(o)[a] += b` as:
@@ -5776,7 +5783,7 @@
 
       VariableDeclaration writeVariable =
           createVariable(write, const VoidType());
-      replacement = createLet(valueVariable,
+      replacement = createLet(valueVariable!,
           createLet(writeVariable, createVariableGet(valueVariable)));
     }
     if (indexVariable != null) {
@@ -5801,7 +5808,7 @@
   ExpressionInferenceResult visitLet(Let node, DartType typeContext) {
     DartType variableType = node.variable.type;
     ExpressionInferenceResult initializerResult = inferrer.inferExpression(
-        node.variable.initializer, variableType, true,
+        node.variable.initializer!, variableType, true,
         isVoidAllowed: true);
     node.variable.initializer = initializerResult.expression
       ..parent = node.variable;
@@ -5829,18 +5836,17 @@
     if (target.isInstanceMember || target.isObjectMember) {
       if (inferrer.instrumentation != null &&
           receiverType == const DynamicType()) {
-        inferrer.instrumentation.record(
+        inferrer.instrumentation!.record(
             inferrer.uriForInstrumentation,
             node.fileOffset,
             'target',
-            new InstrumentationValueForMember(target.member));
+            new InstrumentationValueForMember(target.member!));
       }
       node.interfaceTarget = target.member;
     }
     DartType writeContext = inferrer.getSetterType(target, receiverType);
-    ExpressionInferenceResult rhsResult = inferrer.inferExpression(
-        node.value, writeContext ?? const UnknownType(), true,
-        isVoidAllowed: true);
+    ExpressionInferenceResult rhsResult = inferrer
+        .inferExpression(node.value, writeContext, true, isVoidAllowed: true);
     DartType rhsType = rhsResult.inferredType;
     Expression rhs = inferrer.ensureAssignableResult(writeContext, rhsResult,
         fileOffset: node.fileOffset, isVoidAllowed: writeContext is VoidType);
@@ -5883,9 +5889,9 @@
 
     Member readEqualsMember = inferrer
         .findInterfaceMember(readType, equalsName, node.testOffset)
-        .member;
+        .member!;
 
-    VariableDeclaration readVariable;
+    VariableDeclaration? readVariable;
     if (!node.forEffect) {
       readVariable = createVariable(read, readType);
       read = createVariableGet(readVariable);
@@ -5942,7 +5948,7 @@
 
       Expression readEqualsNull = inferrer.createEqualsNull(
           receiverVariable.fileOffset, read, readEqualsMember);
-      VariableGet variableGet = createVariableGet(readVariable);
+      VariableGet variableGet = createVariableGet(readVariable!);
       if (inferrer.library.isNonNullableByDefault &&
           !identical(nonNullableReadType, readType)) {
         variableGet.promotedType = nonNullableReadType;
@@ -5988,22 +5994,23 @@
     inferrer.inferConstructorParameterTypes(node.target);
     List<TypeParameter> classTypeParameters =
         node.target.enclosingClass.typeParameters;
-    List<DartType> typeArguments =
-        new List<DartType>.filled(classTypeParameters.length, null);
-    for (int i = 0; i < typeArguments.length; i++) {
-      typeArguments[i] = new TypeParameterType.withDefaultNullabilityForLibrary(
-          classTypeParameters[i], inferrer.library.library);
-    }
-    ArgumentsImpl.setNonInferrableArgumentTypes(node.arguments, typeArguments);
+    List<DartType> typeArguments = new List<DartType>.generate(
+        classTypeParameters.length,
+        (int i) => new TypeParameterType.withDefaultNullabilityForLibrary(
+            classTypeParameters[i], inferrer.library.library),
+        growable: false);
+    ArgumentsImpl.setNonInferrableArgumentTypes(
+        node.arguments as ArgumentsImpl, typeArguments);
     FunctionType functionType = replaceReturnType(
         node.target.function
             .computeThisFunctionType(inferrer.library.nonNullable),
         inferrer.coreTypes.thisInterfaceType(
             node.target.enclosingClass, inferrer.library.nonNullable));
     inferrer.inferInvocation(
-        null, node.fileOffset, functionType, node.arguments,
+        const UnknownType(), node.fileOffset, functionType, node.arguments,
         skipTypeArgumentInference: true, staticTarget: node.target);
-    ArgumentsImpl.removeNonInferrableArgumentTypes(node.arguments);
+    ArgumentsImpl.removeNonInferrableArgumentTypes(
+        node.arguments as ArgumentsImpl);
   }
 
   @override
@@ -6019,12 +6026,12 @@
   @override
   StatementInferenceResult visitReturnStatement(
       covariant ReturnStatementImpl node) {
-    ClosureContext closureContext = inferrer.closureContext;
+    ClosureContext closureContext = inferrer.closureContext!;
     DartType typeContext = closureContext.returnContext;
     DartType inferredType;
     if (node.expression != null) {
       ExpressionInferenceResult expressionResult = inferrer.inferExpression(
-          node.expression, typeContext, true,
+          node.expression!, typeContext, true,
           isVoidAllowed: true);
       node.expression = expressionResult.expression..parent = node;
       inferredType = expressionResult.inferredType;
@@ -6042,14 +6049,14 @@
     Class setClass = inferrer.coreTypes.setClass;
     InterfaceType setType = inferrer.coreTypes
         .thisInterfaceType(setClass, inferrer.library.nonNullable);
-    List<DartType> inferredTypes;
+    List<DartType>? inferredTypes;
     DartType inferredTypeArgument;
-    List<DartType> formalTypes;
-    List<DartType> actualTypes;
+    List<DartType>? formalTypes;
+    List<DartType>? actualTypes;
     bool inferenceNeeded = node.typeArgument is ImplicitTypeArgument;
     bool typeChecksNeeded = !inferrer.isTopLevel;
-    Map<TreeNode, DartType> inferredSpreadTypes;
-    Map<Expression, DartType> inferredConditionTypes;
+    Map<TreeNode, DartType>? inferredSpreadTypes;
+    Map<Expression, DartType>? inferredConditionTypes;
     if (inferenceNeeded || typeChecksNeeded) {
       formalTypes = [];
       actualTypes = [];
@@ -6069,7 +6076,7 @@
           isConst: node.isConst);
       inferredTypeArgument = inferredTypes[0];
       if (inferrer.dataForTesting != null) {
-        inferrer.dataForTesting.typeInferenceResult
+        inferrer.dataForTesting!.typeInferenceResult
             .inferredTypeArguments[node] = inferredTypes;
       }
     } else {
@@ -6080,14 +6087,14 @@
         ExpressionInferenceResult result = inferElement(
             node.expressions[index],
             inferredTypeArgument,
-            inferredSpreadTypes,
-            inferredConditionTypes,
+            inferredSpreadTypes!,
+            inferredConditionTypes!,
             inferenceNeeded,
             typeChecksNeeded);
         node.expressions[index] = result.expression..parent = node;
-        actualTypes.add(result.inferredType);
+        actualTypes!.add(result.inferredType);
         if (inferenceNeeded) {
-          formalTypes.add(setType.typeArguments[0]);
+          formalTypes!.add(setType.typeArguments[0]);
         }
       }
     }
@@ -6098,7 +6105,7 @@
           formalTypes,
           actualTypes,
           typeContext,
-          inferredTypes,
+          inferredTypes!,
           inferrer.library.library);
       inferredTypeArgument = inferredTypes[0];
       inferrer.instrumentation?.record(
@@ -6111,7 +6118,7 @@
     if (typeChecksNeeded) {
       for (int i = 0; i < node.expressions.length; i++) {
         checkElement(node.expressions[i], node, node.typeArgument,
-            inferredSpreadTypes, inferredConditionTypes);
+            inferredSpreadTypes!, inferredConditionTypes!);
       }
     }
     DartType inferredType = new InterfaceType(
@@ -6120,12 +6127,12 @@
       SourceLibraryBuilder library = inferrer.library;
       if (inferenceNeeded) {
         library.checkBoundsInSetLiteral(
-            node, inferrer.typeSchemaEnvironment, inferrer.helper.uri,
+            node, inferrer.typeSchemaEnvironment, inferrer.helper!.uri,
             inferred: true);
       }
 
       if (!library.loader.target.backendTarget.supportsSetLiterals) {
-        inferrer.helper.transformSetLiterals = true;
+        inferrer.helper!.transformSetLiterals = true;
       }
     }
     return new ExpressionInferenceResult(inferredType, node);
@@ -6137,9 +6144,8 @@
     Member writeMember = node.target;
     DartType writeContext = writeMember.setterType;
     TypeInferenceEngine.resolveInferenceNode(writeMember);
-    ExpressionInferenceResult rhsResult = inferrer.inferExpression(
-        node.value, writeContext ?? const UnknownType(), true,
-        isVoidAllowed: true);
+    ExpressionInferenceResult rhsResult = inferrer
+        .inferExpression(node.value, writeContext, true, isVoidAllowed: true);
     Expression rhs = inferrer.ensureAssignableResult(writeContext, rhsResult,
         fileOffset: node.fileOffset, isVoidAllowed: writeContext is VoidType);
     node.value = rhs..parent = node;
@@ -6161,7 +6167,8 @@
     if (target is Procedure && target.kind == ProcedureKind.Method) {
       Expression tearOff = node;
       if (inferrer.useNewMethodInvocationEncoding) {
-        tearOff = new StaticTearOff(node.target)..fileOffset = node.fileOffset;
+        tearOff = new StaticTearOff(node.target as Procedure)
+          ..fileOffset = node.fileOffset;
       }
       return inferrer.instantiateTearOff(type, typeContext, tearOff);
     } else {
@@ -6172,6 +6179,7 @@
   @override
   ExpressionInferenceResult visitStaticInvocation(
       StaticInvocation node, DartType typeContext) {
+    // ignore: unnecessary_null_comparison
     FunctionType calleeType = node.target != null
         ? node.target.function.computeFunctionType(inferrer.library.nonNullable)
         : new FunctionType(
@@ -6180,11 +6188,12 @@
     InvocationInferenceResult result = inferrer.inferInvocation(
         typeContext, node.fileOffset, calleeType, node.arguments,
         staticTarget: node.target);
+    // ignore: unnecessary_null_comparison
     if (!inferrer.isTopLevel && node.target != null) {
       inferrer.library.checkBoundsInStaticInvocation(
           node,
           inferrer.typeSchemaEnvironment,
-          inferrer.helper.uri,
+          inferrer.helper!.uri,
           typeArgumentsInfo);
     }
     return new ExpressionInferenceResult(
@@ -6218,14 +6227,14 @@
     inferrer.inferConstructorParameterTypes(node.target);
     Substitution substitution = Substitution.fromSupertype(
         inferrer.classHierarchy.getClassAsInstanceOf(
-            inferrer.thisType.classNode, node.target.enclosingClass));
+            inferrer.thisType!.classNode, node.target.enclosingClass)!);
     FunctionType functionType = replaceReturnType(
         substitution.substituteType(node.target.function
             .computeThisFunctionType(inferrer.library.nonNullable)
-            .withoutTypeParameters),
-        inferrer.thisType);
+            .withoutTypeParameters) as FunctionType,
+        inferrer.thisType!);
     inferrer.inferInvocation(
-        null, node.fileOffset, functionType, node.arguments,
+        const UnknownType(), node.fileOffset, functionType, node.arguments,
         skipTypeArgumentInference: true, staticTarget: node.target);
   }
 
@@ -6237,7 +6246,7 @@
           inferrer.uriForInstrumentation,
           node.fileOffset,
           'target',
-          new InstrumentationValueForMember(node.interfaceTarget));
+          new InstrumentationValueForMember(node.interfaceTarget!));
     }
     assert(node.interfaceTarget == null || node.interfaceTarget is Procedure);
     return inferrer.inferSuperMethodInvocation(
@@ -6252,7 +6261,7 @@
           inferrer.uriForInstrumentation,
           node.fileOffset,
           'target',
-          new InstrumentationValueForMember(node.interfaceTarget));
+          new InstrumentationValueForMember(node.interfaceTarget!));
     }
     return inferrer.inferSuperPropertyGet(
         node, typeContext, node.interfaceTarget);
@@ -6262,22 +6271,21 @@
   ExpressionInferenceResult visitSuperPropertySet(
       SuperPropertySet node, DartType typeContext) {
     DartType receiverType = inferrer.classHierarchy.getTypeAsInstanceOf(
-        inferrer.thisType,
-        inferrer.thisType.classNode.supertype.classNode,
-        inferrer.library.library);
+        inferrer.thisType!,
+        inferrer.thisType!.classNode.supertype!.classNode,
+        inferrer.library.library)!;
 
     ObjectAccessTarget writeTarget = node.interfaceTarget != null
-        ? new ObjectAccessTarget.interfaceMember(node.interfaceTarget,
+        ? new ObjectAccessTarget.interfaceMember(node.interfaceTarget!,
             isPotentiallyNullable: false)
         : const ObjectAccessTarget.missing();
     DartType writeContext = inferrer.getSetterType(writeTarget, receiverType);
     if (node.interfaceTarget != null) {
       writeContext = inferrer.computeTypeFromSuperClass(
-          node.interfaceTarget.enclosingClass, writeContext);
+          node.interfaceTarget!.enclosingClass!, writeContext);
     }
-    ExpressionInferenceResult rhsResult = inferrer.inferExpression(
-        node.value, writeContext ?? const UnknownType(), true,
-        isVoidAllowed: true);
+    ExpressionInferenceResult rhsResult = inferrer
+        .inferExpression(node.value, writeContext, true, isVoidAllowed: true);
     Expression rhs = inferrer.ensureAssignableResult(writeContext, rhsResult,
         fileOffset: node.fileOffset, isVoidAllowed: writeContext is VoidType);
     node.value = rhs..parent = node;
@@ -6292,7 +6300,7 @@
     node.expression = expressionResult.expression..parent = node;
     DartType expressionType = expressionResult.inferredType;
 
-    Set<Field> enumFields;
+    Set<Field?>? enumFields;
     if (expressionType is InterfaceType && expressionType.classNode.isEnum) {
       enumFields = expressionType.classNode.fields
           .where((Field field) => field.isConst && field.type == expressionType)
@@ -6307,7 +6315,7 @@
     bool hasDefault = false;
     bool lastCaseTerminates = true;
     for (int caseIndex = 0; caseIndex < node.cases.length; ++caseIndex) {
-      SwitchCaseImpl switchCase = node.cases[caseIndex];
+      SwitchCaseImpl switchCase = node.cases[caseIndex] as SwitchCaseImpl;
       hasDefault = hasDefault || switchCase.isDefault;
       inferrer.flowAnalysis
           .switchStatement_beginCase(switchCase.hasLabel, node);
@@ -6331,7 +6339,7 @@
           if (inferrer.library.isNonNullableByDefault) {
             if (!inferrer.typeSchemaEnvironment.isSubtypeOf(caseExpressionType,
                 expressionType, SubtypeCheckMode.withNullabilities)) {
-              inferrer.helper.addProblem(
+              inferrer.helper!.addProblem(
                   templateSwitchExpressionNotSubtype.withArguments(
                       caseExpressionType,
                       expressionType,
@@ -6349,7 +6357,7 @@
             // Check whether the expression type is assignable to the case
             // expression type.
             if (!inferrer.isAssignable(expressionType, caseExpressionType)) {
-              inferrer.helper.addProblem(
+              inferrer.helper!.addProblem(
                   templateSwitchExpressionNotAssignable.withArguments(
                       expressionType,
                       caseExpressionType,
@@ -6379,7 +6387,7 @@
           if (caseIndex < node.cases.length - 1 &&
               inferrer.flowAnalysis.isReachable) {
             inferrer.library.addProblem(messageSwitchCaseFallThrough,
-                switchCase.fileOffset, noLength, inferrer.helper.uri);
+                switchCase.fileOffset, noLength, inferrer.helper!.uri);
           }
         }
       }
@@ -6387,14 +6395,14 @@
     bool isExhaustive =
         hasDefault || (enumFields != null && enumFields.isEmpty);
     inferrer.flowAnalysis.switchStatement_end(isExhaustive);
-    Statement replacement;
+    Statement? replacement;
     if (isExhaustive &&
         !hasDefault &&
         inferrer.shouldThrowUnsoundnessException) {
       if (!lastCaseTerminates) {
         LabeledStatement breakTarget;
         if (node.parent is LabeledStatement) {
-          breakTarget = node.parent;
+          breakTarget = node.parent as LabeledStatement;
         } else {
           replacement = breakTarget = new LabeledStatement(node);
         }
@@ -6434,8 +6442,8 @@
 
   ExpressionInferenceResult visitThisExpression(
       ThisExpression node, DartType typeContext) {
-    inferrer.flowAnalysis.thisOrSuper(node, inferrer.thisType);
-    return new ExpressionInferenceResult(inferrer.thisType, node);
+    inferrer.flowAnalysis.thisOrSuper(node, inferrer.thisType!);
+    return new ExpressionInferenceResult(inferrer.thisType!, node);
   }
 
   @override
@@ -6451,7 +6459,7 @@
           expressionResult.inferredType)) {
         return new ExpressionInferenceResult(
             const DynamicType(),
-            inferrer.helper.buildProblem(
+            inferrer.helper!.buildProblem(
                 templateThrowingNotAssignableToObjectError.withArguments(
                     expressionResult.inferredType, true),
                 node.expression.fileOffset,
@@ -6496,14 +6504,14 @@
       inferrer.flowAnalysis.tryCatchStatement_end();
     }
 
-    StatementInferenceResult finalizerResult;
+    StatementInferenceResult? finalizerResult;
     if (node.finallyBlock != null) {
       // If a try statement has no catch blocks, the finally block uses the
       // assigned variables from the try block in [tryBodyWithAssignedInfo],
       // otherwise it uses the assigned variables for the
       inferrer.flowAnalysis.tryFinallyStatement_finallyBegin(
           node.catchBlocks.isNotEmpty ? node : tryBodyWithAssignedInfo);
-      finalizerResult = inferrer.inferStatement(node.finallyBlock);
+      finalizerResult = inferrer.inferStatement(node.finallyBlock!);
       inferrer.flowAnalysis.tryFinallyStatement_end();
     }
     Statement result =
@@ -6515,9 +6523,9 @@
     if (node.finallyBlock != null) {
       result = new TryFinally(
           result,
-          finalizerResult.hasChanged
+          finalizerResult!.hasChanged
               ? finalizerResult.statement
-              : node.finallyBlock)
+              : node.finallyBlock!)
         ..fileOffset = node.fileOffset;
     }
     inferrer.library.loader.dataForTesting?.registerAlias(node, result);
@@ -6535,7 +6543,7 @@
   @override
   ExpressionInferenceResult visitVariableSet(
       VariableSet node, DartType typeContext) {
-    VariableDeclarationImpl variable = node.variable;
+    VariableDeclarationImpl variable = node.variable as VariableDeclarationImpl;
     bool isDefinitelyAssigned = false;
     bool isDefinitelyUnassigned = false;
     if (inferrer.isNonNullableByDefault) {
@@ -6543,12 +6551,12 @@
       isDefinitelyUnassigned = inferrer.flowAnalysis.isUnassigned(variable);
     }
     DartType declaredOrInferredType = variable.lateType ?? variable.type;
-    DartType promotedType;
+    DartType? promotedType;
     if (inferrer.isNonNullableByDefault) {
       promotedType = inferrer.flowAnalysis.promotedType(variable);
     }
-    ExpressionInferenceResult rhsResult = inferrer.inferExpression(node.value,
-        promotedType ?? declaredOrInferredType ?? const UnknownType(), true,
+    ExpressionInferenceResult rhsResult = inferrer.inferExpression(
+        node.value, promotedType ?? declaredOrInferredType, true,
         isVoidAllowed: true);
     Expression rhs = inferrer.ensureAssignableResult(
         declaredOrInferredType, rhsResult,
@@ -6560,13 +6568,13 @@
     Expression resultExpression;
     if (variable.lateSetter != null) {
       if (inferrer.useNewMethodInvocationEncoding) {
-        resultExpression = new LocalFunctionInvocation(variable.lateSetter,
+        resultExpression = new LocalFunctionInvocation(variable.lateSetter!,
             new Arguments(<Expression>[rhs])..fileOffset = node.fileOffset,
-            functionType: variable.lateSetter.type)
+            functionType: variable.lateSetter!.type as FunctionType)
           ..fileOffset = node.fileOffset;
       } else {
         resultExpression = new MethodInvocation(
-            new VariableGet(variable.lateSetter)..fileOffset = node.fileOffset,
+            new VariableGet(variable.lateSetter!)..fileOffset = node.fileOffset,
             callName,
             new Arguments(<Expression>[rhs])..fileOffset = node.fileOffset)
           ..fileOffset = node.fileOffset;
@@ -6590,23 +6598,23 @@
           if (isDefinitelyAssigned) {
             return new ExpressionInferenceResult(
                 resultType,
-                inferrer.helper.wrapInProblem(
+                inferrer.helper!.wrapInProblem(
                     resultExpression,
                     templateLateDefinitelyAssignedError
-                        .withArguments(node.variable.name),
+                        .withArguments(node.variable.name!),
                     node.fileOffset,
-                    node.variable.name.length));
+                    node.variable.name!.length));
           }
         } else if (variable.isStaticLate) {
           if (!isDefinitelyUnassigned) {
             return new ExpressionInferenceResult(
                 resultType,
-                inferrer.helper.wrapInProblem(
+                inferrer.helper!.wrapInProblem(
                     resultExpression,
                     templateFinalPossiblyAssignedError
-                        .withArguments(node.variable.name),
+                        .withArguments(node.variable.name!),
                     node.fileOffset,
-                    node.variable.name.length));
+                    node.variable.name!.length));
           }
         }
       }
@@ -6620,13 +6628,13 @@
     DartType declaredType =
         node.isImplicitlyTyped ? const UnknownType() : node.type;
     DartType inferredType;
-    ExpressionInferenceResult initializerResult;
+    ExpressionInferenceResult? initializerResult;
     inferrer.flowAnalysis.declare(node, node.hasDeclaredInitializer);
     if (node.initializer != null) {
       if (node.isLate && node.hasDeclaredInitializer) {
         inferrer.flowAnalysis.lateInitializer_begin(node);
       }
-      initializerResult = inferrer.inferExpression(node.initializer,
+      initializerResult = inferrer.inferExpression(node.initializer!,
           declaredType, !inferrer.isTopLevel || node.isImplicitlyTyped,
           isVoidAllowed: true);
       if (node.isLate && node.hasDeclaredInitializer) {
@@ -6645,7 +6653,7 @@
           'type',
           new InstrumentationValueForType(inferredType));
       if (inferrer.dataForTesting != null) {
-        inferrer.dataForTesting.typeInferenceResult
+        inferrer.dataForTesting!.typeInferenceResult
             .inferredVariableTypes[node] = inferredType;
       }
       node.type = inferredType;
@@ -6660,6 +6668,7 @@
       } else {
         // TODO(paulberry): `initializerType` is sometimes `null` during top
         // level inference.  Figure out how to prevent this.
+        // ignore: unnecessary_null_comparison
         if (initializerType != null) {
           inferrer.flowAnalysis.initialize(
               node, initializerType, initializerResult.expression,
@@ -6675,7 +6684,7 @@
       SourceLibraryBuilder library = inferrer.library;
       if (node.isImplicitlyTyped) {
         library.checkBoundsInVariableDeclaration(
-            node, inferrer.typeSchemaEnvironment, inferrer.helper.uri,
+            node, inferrer.typeSchemaEnvironment, inferrer.helper!.uri,
             inferred: true);
       }
     }
@@ -6692,10 +6701,10 @@
       late_lowering.IsSetEncoding isSetEncoding =
           late_lowering.computeIsSetEncoding(
               node.type, late_lowering.computeIsSetStrategy(inferrer.library));
-      VariableDeclaration isSetVariable;
+      VariableDeclaration? isSetVariable;
       if (isSetEncoding == late_lowering.IsSetEncoding.useIsSetField) {
         isSetVariable = new VariableDeclaration(
-            late_lowering.computeLateLocalIsSetName(node.name),
+            late_lowering.computeLateLocalIsSetName(node.name!),
             initializer: new BoolLiteral(false)..fileOffset = fileOffset,
             type: inferrer.coreTypes.boolRawType(inferrer.library.nonNullable),
             isLowered: true)
@@ -6713,14 +6722,14 @@
       }
 
       Expression createIsSetRead() =>
-          new VariableGet(isSetVariable)..fileOffset = fileOffset;
+          new VariableGet(isSetVariable!)..fileOffset = fileOffset;
       Expression createVariableWrite(Expression value) =>
           new VariableSet(node, value);
       Expression createIsSetWrite(Expression value) =>
-          new VariableSet(isSetVariable, value);
+          new VariableSet(isSetVariable!, value);
 
       VariableDeclaration getVariable = new VariableDeclaration(
-          late_lowering.computeLateLocalGetterName(node.name),
+          late_lowering.computeLateLocalGetterName(node.name!),
           isLowered: true)
         ..fileOffset = fileOffset;
       FunctionDeclaration getter = new FunctionDeclaration(
@@ -6730,7 +6739,7 @@
                   ? late_lowering.createGetterBodyWithoutInitializer(
                       inferrer.coreTypes,
                       fileOffset,
-                      node.name,
+                      node.name!,
                       node.type,
                       inferrer.useNewMethodInvocationEncoding,
                       createVariableRead: createVariableRead,
@@ -6741,9 +6750,9 @@
                       ? late_lowering.createGetterWithInitializerWithRecheck(
                           inferrer.coreTypes,
                           fileOffset,
-                          node.name,
+                          node.name!,
                           node.type,
-                          node.initializer,
+                          node.initializer!,
                           inferrer.useNewMethodInvocationEncoding,
                           createVariableRead: createVariableRead,
                           createVariableWrite: createVariableWrite,
@@ -6754,9 +6763,9 @@
                       : late_lowering.createGetterWithInitializer(
                           inferrer.coreTypes,
                           fileOffset,
-                          node.name,
+                          node.name!,
                           node.type,
-                          node.initializer,
+                          node.initializer!,
                           inferrer.useNewMethodInvocationEncoding,
                           createVariableRead: createVariableRead,
                           createVariableWrite: createVariableWrite,
@@ -6774,7 +6783,7 @@
         node.isLateFinalWithoutInitializer =
             node.isFinal && node.initializer == null;
         VariableDeclaration setVariable = new VariableDeclaration(
-            late_lowering.computeLateLocalSetterName(node.name),
+            late_lowering.computeLateLocalSetterName(node.name!),
             isLowered: true)
           ..fileOffset = fileOffset;
         VariableDeclaration setterParameter =
@@ -6787,7 +6796,7 @@
                         ? late_lowering.createSetterBodyFinal(
                             inferrer.coreTypes,
                             fileOffset,
-                            node.name,
+                            node.name!,
                             setterParameter,
                             node.type,
                             inferrer.useNewMethodInvocationEncoding,
@@ -6799,7 +6808,7 @@
                             isSetEncoding: isSetEncoding,
                             forField: false)
                         : late_lowering.createSetterBody(inferrer.coreTypes,
-                            fileOffset, node.name, setterParameter, node.type,
+                            fileOffset, node.name!, setterParameter, node.type,
                             shouldReturnValue: true,
                             createVariableWrite: createVariableWrite,
                             createIsSetWrite: createIsSetWrite,
@@ -6830,7 +6839,7 @@
       node.type = inferrer.computeNullable(node.type);
       node.lateName = node.name;
       node.isLowered = true;
-      node.name = late_lowering.computeLateLocalName(node.name);
+      node.name = late_lowering.computeLateLocalName(node.name!);
 
       return new StatementInferenceResult.multiple(node.fileOffset, result);
     }
@@ -6840,8 +6849,8 @@
   @override
   ExpressionInferenceResult visitVariableGet(
       covariant VariableGetImpl node, DartType typeContext) {
-    VariableDeclarationImpl variable = node.variable;
-    DartType promotedType;
+    VariableDeclarationImpl variable = node.variable as VariableDeclarationImpl;
+    DartType? promotedType;
     DartType declaredOrInferredType = variable.lateType ?? variable.type;
     if (isExtensionThis(variable)) {
       inferrer.flowAnalysis.thisOrSuper(node, variable.type);
@@ -6868,13 +6877,13 @@
       return inferrer.instantiateTearOff(resultType, typeContext, node);
     } else if (variable.lateGetter != null) {
       if (inferrer.useNewMethodInvocationEncoding) {
-        resultExpression = new LocalFunctionInvocation(variable.lateGetter,
+        resultExpression = new LocalFunctionInvocation(variable.lateGetter!,
             new Arguments(<Expression>[])..fileOffset = node.fileOffset,
-            functionType: variable.lateGetter.type)
+            functionType: variable.lateGetter!.type as FunctionType)
           ..fileOffset = node.fileOffset;
       } else {
         resultExpression = new MethodInvocation(
-            new VariableGet(variable.lateGetter)..fileOffset = node.fileOffset,
+            new VariableGet(variable.lateGetter!)..fileOffset = node.fileOffset,
             callName,
             new Arguments(<Expression>[])..fileOffset = node.fileOffset)
           ..fileOffset = node.fileOffset;
@@ -6889,14 +6898,14 @@
     if (!inferrer.isTopLevel) {
       bool isUnassigned = !inferrer.flowAnalysis.isAssigned(variable);
       if (isUnassigned) {
-        inferrer.dataForTesting?.flowAnalysisResult?.potentiallyUnassignedNodes
-            ?.add(node);
+        inferrer.dataForTesting?.flowAnalysisResult.potentiallyUnassignedNodes
+            .add(node);
       }
       bool isDefinitelyUnassigned =
           inferrer.flowAnalysis.isUnassigned(variable);
       if (isDefinitelyUnassigned) {
-        inferrer.dataForTesting?.flowAnalysisResult?.definitelyUnassignedNodes
-            ?.add(node);
+        inferrer.dataForTesting?.flowAnalysisResult.definitelyUnassignedNodes
+            .add(node);
       }
       if (inferrer.isNonNullableByDefault) {
         // Synthetic variables, local functions, and variables with
@@ -6906,10 +6915,10 @@
             declaredOrInferredType is! InvalidType) {
           if (variable.isLate || variable.lateGetter != null) {
             if (isDefinitelyUnassigned) {
-              String name = variable.lateName ?? variable.name;
+              String name = variable.lateName ?? variable.name!;
               return new ExpressionInferenceResult(
                   resultType,
-                  inferrer.helper.wrapInProblem(
+                  inferrer.helper!.wrapInProblem(
                       resultExpression,
                       templateLateDefinitelyUnassignedError.withArguments(name),
                       node.fileOffset,
@@ -6920,21 +6929,21 @@
               if (variable.isFinal) {
                 return new ExpressionInferenceResult(
                     resultType,
-                    inferrer.helper.wrapInProblem(
+                    inferrer.helper!.wrapInProblem(
                         resultExpression,
                         templateFinalNotAssignedError
-                            .withArguments(node.variable.name),
+                            .withArguments(node.variable.name!),
                         node.fileOffset,
-                        node.variable.name.length));
+                        node.variable.name!.length));
               } else if (declaredOrInferredType.isPotentiallyNonNullable) {
                 return new ExpressionInferenceResult(
                     resultType,
-                    inferrer.helper.wrapInProblem(
+                    inferrer.helper!.wrapInProblem(
                         resultExpression,
                         templateNonNullableNotAssignedError
-                            .withArguments(node.variable.name),
+                            .withArguments(node.variable.name!),
                         node.fileOffset,
-                        node.variable.name.length));
+                        node.variable.name!.length));
               }
             }
           }
@@ -6966,7 +6975,7 @@
 
   @override
   StatementInferenceResult visitYieldStatement(YieldStatement node) {
-    ClosureContext closureContext = inferrer.closureContext;
+    ClosureContext closureContext = inferrer.closureContext!;
     ExpressionInferenceResult expressionResult;
     DartType typeContext = closureContext.yieldContext;
     if (node.isYieldStar && typeContext is! UnknownType) {
@@ -6993,7 +7002,7 @@
       FunctionType calleeType =
           new FunctionType([], inferredType, inferrer.library.nonNullable);
       inferrer.inferInvocation(
-          typeContext, node.fileOffset, calleeType, node.arguments);
+          typeContext, node.fileOffset, calleeType, node.arguments!);
     }
     return new ExpressionInferenceResult(inferredType, node);
   }
@@ -7032,7 +7041,7 @@
     ExpressionInferenceResult leftResult =
         inferrer.inferExpression(node.left, const UnknownType(), true);
     Map<DartType, NonPromotionReason> Function() whyNotPromoted =
-        inferrer.flowAnalysis?.whyNotPromoted(leftResult.expression);
+        inferrer.flowAnalysis.whyNotPromoted(leftResult.expression);
     return _computeBinaryExpression(
         node.fileOffset,
         typeContext,
@@ -7045,7 +7054,7 @@
 
   ExpressionInferenceResult visitUnary(
       UnaryExpression node, DartType typeContext) {
-    ExpressionInferenceResult expressionResult;
+    ExpressionInferenceResult? expressionResult;
     if (node.unaryName == unaryMinusName) {
       // Replace integer literals in a double context with the corresponding
       // double literal if it's exact.  For double literals, the negation is
@@ -7057,9 +7066,9 @@
       // and negated 9223372036854775808 represented as
       // -9223372036854775808.unary-() which should be a negative number.
       if (node.expression is IntJudgment) {
-        IntJudgment receiver = node.expression;
+        IntJudgment receiver = node.expression as IntJudgment;
         if (inferrer.isDoubleContext(typeContext)) {
-          double doubleValue = receiver.asDouble(negated: true);
+          double? doubleValue = receiver.asDouble(negated: true);
           if (doubleValue != null) {
             Expression replacement = new DoubleLiteral(doubleValue)
               ..fileOffset = node.fileOffset;
@@ -7068,16 +7077,17 @@
             return new ExpressionInferenceResult(inferredType, replacement);
           }
         }
-        Expression error = checkWebIntLiteralsErrorIfUnexact(
+        Expression? error = checkWebIntLiteralsErrorIfUnexact(
             inferrer, receiver.value, receiver.literal, receiver.fileOffset);
         if (error != null) {
           return new ExpressionInferenceResult(const DynamicType(), error);
         }
       } else if (node.expression is ShadowLargeIntLiteral) {
-        ShadowLargeIntLiteral receiver = node.expression;
+        ShadowLargeIntLiteral receiver =
+            node.expression as ShadowLargeIntLiteral;
         if (!receiver.isParenthesized) {
           if (inferrer.isDoubleContext(typeContext)) {
-            double doubleValue = receiver.asDouble(negated: true);
+            double? doubleValue = receiver.asDouble(negated: true);
             if (doubleValue != null) {
               Expression replacement = new DoubleLiteral(doubleValue)
                 ..fileOffset = node.fileOffset;
@@ -7086,17 +7096,18 @@
               return new ExpressionInferenceResult(inferredType, replacement);
             }
           }
-          int intValue = receiver.asInt64(negated: true);
+          int? intValue = receiver.asInt64(negated: true);
           if (intValue == null) {
-            Expression error = inferrer.helper.buildProblem(
+            Expression error = inferrer.helper!.buildProblem(
                 templateIntegerLiteralIsOutOfRange
                     .withArguments(receiver.literal),
                 receiver.fileOffset,
                 receiver.literal.length);
             return new ExpressionInferenceResult(const DynamicType(), error);
           }
+          // ignore: unnecessary_null_comparison
           if (intValue != null) {
-            Expression error = checkWebIntLiteralsErrorIfUnexact(
+            Expression? error = checkWebIntLiteralsErrorIfUnexact(
                 inferrer, intValue, receiver.literal, receiver.fileOffset);
             if (error != null) {
               return new ExpressionInferenceResult(const DynamicType(), error);
@@ -7114,7 +7125,7 @@
           inferrer.inferExpression(node.expression, const UnknownType(), true);
     }
     Map<DartType, NonPromotionReason> Function() whyNotPromoted =
-        inferrer.flowAnalysis?.whyNotPromoted(expressionResult.expression);
+        inferrer.flowAnalysis.whyNotPromoted(expressionResult.expression);
     return _computeUnaryExpression(node.fileOffset, expressionResult.expression,
         expressionResult.inferredType, node.unaryName, whyNotPromoted);
   }
@@ -7138,7 +7149,7 @@
                 operationName, operandType, inferrer.isNonNullableByDefault),
             offset,
             noLength,
-            inferrer.helper.uri);
+            inferrer.helper!.uri);
       }
     }
   }
@@ -7147,8 +7158,8 @@
 class ForInResult {
   final VariableDeclaration variable;
   final Expression iterable;
-  final Expression syntheticAssignment;
-  final Statement expressionSideEffects;
+  final Expression? syntheticAssignment;
+  final Statement? expressionSideEffects;
 
   ForInResult(this.variable, this.iterable, this.syntheticAssignment,
       this.expressionSideEffects);
@@ -7163,7 +7174,7 @@
 
   /// Infers the assignment to this for-in variable with a value of type
   /// [rhsType]. The resulting expression is returned.
-  Expression inferAssignment(TypeInferrerImpl inferrer, DartType rhsType);
+  Expression? inferAssignment(TypeInferrerImpl inferrer, DartType rhsType);
 }
 
 class LocalForInVariable implements ForInVariable {
@@ -7173,7 +7184,7 @@
 
   DartType computeElementType(TypeInferrerImpl inferrer) {
     VariableDeclaration variable = variableSet.variable;
-    DartType promotedType;
+    DartType? promotedType;
     if (inferrer.isNonNullableByDefault) {
       promotedType = inferrer.flowAnalysis.promotedType(variable);
     }
@@ -7202,9 +7213,9 @@
 class PropertyForInVariable implements ForInVariable {
   final PropertySet propertySet;
 
-  DartType _writeType;
+  DartType? _writeType;
 
-  Expression _rhs;
+  Expression? _rhs;
 
   PropertyForInVariable(this.propertySet);
 
@@ -7219,7 +7230,7 @@
         setter: true, instrumented: true, includeExtensionMethods: true);
     DartType elementType =
         _writeType = inferrer.getSetterType(writeTarget, receiverType);
-    Expression error = inferrer.reportMissingInterfaceMember(
+    Expression? error = inferrer.reportMissingInterfaceMember(
         writeTarget,
         receiverType,
         propertySet.name,
@@ -7231,11 +7242,11 @@
       if (writeTarget.isInstanceMember || writeTarget.isObjectMember) {
         if (inferrer.instrumentation != null &&
             receiverType == const DynamicType()) {
-          inferrer.instrumentation.record(
+          inferrer.instrumentation!.record(
               inferrer.uriForInstrumentation,
               propertySet.fileOffset,
               'target',
-              new InstrumentationValueForMember(writeTarget.member));
+              new InstrumentationValueForMember(writeTarget.member!));
         }
         propertySet.interfaceTarget = writeTarget.member;
       }
@@ -7247,7 +7258,7 @@
   @override
   Expression inferAssignment(TypeInferrerImpl inferrer, DartType rhsType) {
     Expression rhs = inferrer.ensureAssignable(
-        inferrer.computeGreatestClosure(_writeType), rhsType, _rhs,
+        inferrer.computeGreatestClosure(_writeType!), rhsType, _rhs!,
         errorTemplate: templateForInLoopElementTypeNotAssignable,
         nullabilityErrorTemplate:
             templateForInLoopElementTypeNotAssignableNullability,
@@ -7266,13 +7277,13 @@
 class SuperPropertyForInVariable implements ForInVariable {
   final SuperPropertySet superPropertySet;
 
-  DartType _writeType;
+  DartType? _writeType;
 
   SuperPropertyForInVariable(this.superPropertySet);
 
   @override
   DartType computeElementType(TypeInferrerImpl inferrer) {
-    DartType receiverType = inferrer.thisType;
+    DartType receiverType = inferrer.thisType!;
     ObjectAccessTarget writeTarget = inferrer.findInterfaceMember(
         receiverType, superPropertySet.name, superPropertySet.fileOffset,
         setter: true, instrumented: true);
@@ -7285,7 +7296,7 @@
   @override
   Expression inferAssignment(TypeInferrerImpl inferrer, DartType rhsType) {
     Expression rhs = inferrer.ensureAssignable(
-        inferrer.computeGreatestClosure(_writeType),
+        inferrer.computeGreatestClosure(_writeType!),
         rhsType,
         superPropertySet.value,
         errorTemplate: templateForInLoopElementTypeNotAssignable,
@@ -7333,7 +7344,7 @@
 }
 
 class InvalidForInVariable implements ForInVariable {
-  final Expression expression;
+  final Expression? expression;
 
   InvalidForInVariable(this.expression);
 
@@ -7341,7 +7352,7 @@
   DartType computeElementType(TypeInferrerImpl inferrer) => const UnknownType();
 
   @override
-  Expression inferAssignment(TypeInferrerImpl inferrer, DartType rhsType) =>
+  Expression? inferAssignment(TypeInferrerImpl inferrer, DartType rhsType) =>
       expression;
 }
 
diff --git a/pkg/front_end/lib/src/fasta/kernel/internal_ast.dart b/pkg/front_end/lib/src/fasta/kernel/internal_ast.dart
index 55b2d8d..749419c 100644
--- a/pkg/front_end/lib/src/fasta/kernel/internal_ast.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/internal_ast.dart
@@ -2,8 +2,6 @@
 // for 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
-
 /// This file declares a "shadow hierarchy" of concrete classes which extend
 /// the kernel class hierarchy, adding methods and fields needed by the
 /// BodyBuilder.
@@ -34,9 +32,6 @@
 
 import '../problems.dart' show unsupported;
 
-import '../source/source_class_builder.dart' show SourceClassBuilder;
-
-import '../type_inference/type_inference_engine.dart';
 import '../type_inference/type_inferrer.dart';
 
 import '../type_inference/type_schema.dart' show UnknownType;
@@ -61,7 +56,7 @@
   }
 }
 
-List<DartType> getExplicitExtensionTypeArguments(Arguments arguments) {
+List<DartType>? getExplicitExtensionTypeArguments(Arguments arguments) {
   if (arguments is ArgumentsImpl) {
     if (arguments._explicitExtensionTypeArgumentCount == 0) {
       return null;
@@ -144,7 +139,7 @@
   }
 }
 
-List<DartType> getExplicitTypeArguments(Arguments arguments) {
+List<DartType>? getExplicitTypeArguments(Arguments arguments) {
   if (arguments is ArgumentsImpl) {
     if (arguments._explicitTypeArgumentCount == 0) {
       return null;
@@ -167,24 +162,6 @@
   return getExplicitTypeArguments(arguments) != null;
 }
 
-/// Information associated with a class during type inference.
-class ClassInferenceInfo {
-  /// The builder associated with this class.
-  final SourceClassBuilder builder;
-
-  /// The visitor for determining if a given type makes covariant use of one of
-  /// the class's generic parameters, and therefore requires covariant checks.
-  IncludesTypeParametersNonCovariantly needsCheckVisitor;
-
-  /// Getters and methods in the class's API.  May include forwarding nodes.
-  final gettersAndMethods = <Member>[];
-
-  /// Setters in the class's API.  May include forwarding nodes.
-  final setters = <Member>[];
-
-  ClassInferenceInfo(this.builder);
-}
-
 /// Common base class for internal statements.
 abstract class InternalStatement extends Statement {
   @override
@@ -204,25 +181,27 @@
 }
 
 class ForInStatementWithSynthesizedVariable extends InternalStatement {
-  VariableDeclaration variable;
+  VariableDeclaration? variable;
   Expression iterable;
-  Expression syntheticAssignment;
-  Statement expressionEffects;
+  Expression? syntheticAssignment;
+  Statement? expressionEffects;
   Statement body;
   final bool isAsync;
   final bool hasProblem;
-  int bodyOffset;
+  int bodyOffset = TreeNode.noOffset;
 
   ForInStatementWithSynthesizedVariable(this.variable, this.iterable,
       this.syntheticAssignment, this.expressionEffects, this.body,
-      {this.isAsync, this.hasProblem})
+      {required this.isAsync, required this.hasProblem})
+      // ignore: unnecessary_null_comparison
       : assert(isAsync != null),
+        // ignore: unnecessary_null_comparison
         assert(hasProblem != null) {
     variable?.parent = this;
-    iterable?.parent = this;
+    iterable.parent = this;
     syntheticAssignment?.parent = this;
     expressionEffects?.parent = this;
-    body?.parent = this;
+    body.parent = this;
   }
 
   @override
@@ -233,57 +212,61 @@
   @override
   void visitChildren(Visitor<dynamic> v) {
     variable?.accept(v);
-    iterable?.accept(v);
+    iterable.accept(v);
     syntheticAssignment?.accept(v);
     expressionEffects?.accept(v);
-    body?.accept(v);
+    body.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
     if (variable != null) {
-      variable = v.transform(variable);
+      variable = v.transform(variable!);
       variable?.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (iterable != null) {
       iterable = v.transform(iterable);
-      iterable?.parent = this;
+      iterable.parent = this;
     }
     if (syntheticAssignment != null) {
-      syntheticAssignment = v.transform(syntheticAssignment);
+      syntheticAssignment = v.transform(syntheticAssignment!);
       syntheticAssignment?.parent = this;
     }
     if (expressionEffects != null) {
-      expressionEffects = v.transform(expressionEffects);
+      expressionEffects = v.transform(expressionEffects!);
       expressionEffects?.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (body != null) {
       body = v.transform(body);
-      body?.parent = this;
+      body.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
     if (variable != null) {
-      variable = v.transform(variable);
+      variable = v.transform(variable!);
       variable?.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (iterable != null) {
       iterable = v.transform(iterable);
-      iterable?.parent = this;
+      iterable.parent = this;
     }
     if (syntheticAssignment != null) {
-      syntheticAssignment = v.transform(syntheticAssignment);
+      syntheticAssignment = v.transform(syntheticAssignment!);
       syntheticAssignment?.parent = this;
     }
     if (expressionEffects != null) {
-      expressionEffects = v.transform(expressionEffects);
+      expressionEffects = v.transform(expressionEffects!);
       expressionEffects?.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (body != null) {
       body = v.transform(body);
-      body?.parent = this;
+      body.parent = this;
     }
   }
 
@@ -301,10 +284,14 @@
 class TryStatement extends InternalStatement {
   Statement tryBlock;
   List<Catch> catchBlocks;
-  Statement finallyBlock;
+  Statement? finallyBlock;
 
-  TryStatement(this.tryBlock, this.catchBlocks, this.finallyBlock) {
-    tryBlock?.parent = this;
+  TryStatement(this.tryBlock, this.catchBlocks, this.finallyBlock)
+      // ignore: unnecessary_null_comparison
+      : assert(tryBlock != null),
+        // ignore: unnecessary_null_comparison
+        assert(catchBlocks != null) {
+    tryBlock.parent = this;
     setParents(catchBlocks, this);
     finallyBlock?.parent = this;
   }
@@ -316,33 +303,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    tryBlock?.accept(v);
+    tryBlock.accept(v);
     visitList(catchBlocks, v);
     finallyBlock?.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (tryBlock != null) {
       tryBlock = v.transform(tryBlock);
-      tryBlock?.parent = this;
+      tryBlock.parent = this;
     }
     v.transformList(catchBlocks, this);
     if (finallyBlock != null) {
-      finallyBlock = v.transform(finallyBlock);
+      finallyBlock = v.transform(finallyBlock!);
       finallyBlock?.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (tryBlock != null) {
-      tryBlock = v.transformOrRemoveStatement(tryBlock);
-      tryBlock?.parent = this;
+      tryBlock = v.transform(tryBlock);
+      tryBlock.parent = this;
     }
     v.transformCatchList(catchBlocks, this);
     if (finallyBlock != null) {
-      finallyBlock = v.transformOrRemoveStatement(finallyBlock);
+      finallyBlock = v.transformOrRemoveStatement(finallyBlock!);
       finallyBlock?.parent = this;
     }
   }
@@ -362,7 +351,7 @@
     }
     if (finallyBlock != null) {
       printer.write(' finally ');
-      printer.writeStatement(finallyBlock);
+      printer.writeStatement(finallyBlock!);
     }
   }
 }
@@ -372,7 +361,8 @@
 
   SwitchCaseImpl(
       List<Expression> expressions, List<int> expressionOffsets, Statement body,
-      {bool isDefault: false, this.hasLabel})
+      {bool isDefault: false, required this.hasLabel})
+      // ignore: unnecessary_null_comparison
       : assert(hasLabel != null),
         super(expressions, expressionOffsets, body, isDefault: isDefault);
 
@@ -383,12 +373,13 @@
 }
 
 class BreakStatementImpl extends BreakStatement {
-  Statement targetStatement;
+  Statement? targetStatement;
   final bool isContinue;
 
-  BreakStatementImpl({this.isContinue})
+  BreakStatementImpl({required this.isContinue})
+      // ignore: unnecessary_null_comparison
       : assert(isContinue != null),
-        super(null);
+        super(dummyLabeledStatement);
 
   @override
   String toString() {
@@ -486,12 +477,12 @@
 
   final int _explicitExtensionTypeArgumentCount;
 
-  final int _extensionTypeArgumentOffset;
+  final int? _extensionTypeArgumentOffset;
 
   int _explicitTypeArgumentCount;
 
   ArgumentsImpl(List<Expression> positional,
-      {List<DartType> types, List<NamedExpression> named})
+      {List<DartType>? types, List<NamedExpression>? named})
       : _explicitTypeArgumentCount = types?.length ?? 0,
         _extensionTypeParameterCount = 0,
         _explicitExtensionTypeArgumentCount = 0,
@@ -502,7 +493,7 @@
   ArgumentsImpl.forExtensionMethod(int extensionTypeParameterCount,
       int typeParameterCount, Expression receiver,
       {List<DartType> extensionTypeArguments = const <DartType>[],
-      int extensionTypeArgumentOffset,
+      int? extensionTypeArgumentOffset,
       List<DartType> typeArguments = const <DartType>[],
       List<Expression> positionalArguments = const <Expression>[],
       List<NamedExpression> namedArguments = const <NamedExpression>[]})
@@ -575,8 +566,12 @@
   /// variable.  Caller is responsible for ensuring that [variable]'s
   /// initializer is the expression preceding the first `..` of the cascade
   /// expression.
-  Cascade(this.variable, {this.isNullAware}) : assert(isNullAware != null) {
-    variable?.parent = this;
+  Cascade(this.variable, {required this.isNullAware})
+      // ignore: unnecessary_null_comparison
+      : assert(variable != null),
+        // ignore: unnecessary_null_comparison
+        assert(isNullAware != null) {
+    variable.parent = this;
   }
 
   @override
@@ -596,24 +591,26 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    variable?.accept(v);
+    variable.accept(v);
     visitList(expressions, v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (variable != null) {
       variable = v.transform(variable);
-      variable?.parent = this;
+      variable.parent = this;
     }
     v.transformList(expressions, this);
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (variable != null) {
-      variable = v.transformOrRemoveVariableDeclaration(variable);
-      variable?.parent = this;
+      variable = v.transform(variable);
+      variable.parent = this;
     }
     v.transformExpressionList(expressions, this);
   }
@@ -650,9 +647,13 @@
   VariableDeclaration variable;
   Expression expression;
 
-  DeferredCheck(this.variable, this.expression) {
-    variable?.parent = this;
-    expression?.parent = this;
+  DeferredCheck(this.variable, this.expression)
+      // ignore: unnecessary_null_comparison
+      : assert(variable != null),
+        // ignore: unnecessary_null_comparison
+        assert(expression != null) {
+    variable.parent = this;
+    expression.parent = this;
   }
 
   @override
@@ -665,31 +666,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    variable?.accept(v);
-    expression?.accept(v);
+    variable.accept(v);
+    expression.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (variable != null) {
       variable = v.transform(variable);
-      variable?.parent = this;
+      variable.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (expression != null) {
       expression = v.transform(expression);
-      expression?.parent = this;
+      expression.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (variable != null) {
-      variable = v.transformOrRemoveVariableDeclaration(variable);
-      variable?.parent = this;
+      variable = v.transform(variable);
+      variable.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (expression != null) {
-      expression = v.transformOrRemoveExpression(expression);
-      expression?.parent = this;
+      expression = v.transform(expression);
+      expression.parent = this;
     }
   }
 
@@ -722,8 +727,7 @@
     implements ExpressionJudgment {
   bool hasBeenInferred = false;
 
-  FactoryConstructorInvocationJudgment(
-      Procedure target, ArgumentsImpl arguments,
+  FactoryConstructorInvocationJudgment(Procedure target, Arguments arguments,
       {bool isConst: false})
       : super(target, arguments, isConst: isConst);
 
@@ -745,7 +749,7 @@
     } else {
       printer.write('new ');
     }
-    printer.writeClassName(target.enclosingClass.reference);
+    printer.writeClassName(target.enclosingClass!.reference);
     printer.writeTypeArguments(arguments.types);
     if (target.name.text.isNotEmpty) {
       printer.write('.');
@@ -763,7 +767,7 @@
   final TypeAliasBuilder typeAliasBuilder;
 
   TypeAliasedConstructorInvocationJudgment(
-      this.typeAliasBuilder, Constructor target, ArgumentsImpl arguments,
+      this.typeAliasBuilder, Constructor target, Arguments arguments,
       {bool isConst: false})
       : super(target, arguments, isConst: isConst);
 
@@ -793,7 +797,7 @@
   final TypeAliasBuilder typeAliasBuilder;
 
   TypeAliasedFactoryInvocationJudgment(
-      this.typeAliasBuilder, Procedure target, ArgumentsImpl arguments,
+      this.typeAliasBuilder, Procedure target, Arguments arguments,
       {bool isConst: false})
       : super(target, arguments, isConst: isConst);
 
@@ -818,8 +822,7 @@
 class FunctionDeclarationImpl extends FunctionDeclaration {
   bool hasImplicitReturnType = false;
 
-  FunctionDeclarationImpl(
-      VariableDeclarationImpl variable, FunctionNode function)
+  FunctionDeclarationImpl(VariableDeclaration variable, FunctionNode function)
       : super(variable, function);
 
   static void setHasImplicitReturnType(
@@ -864,9 +867,13 @@
   Expression left;
   Expression right;
 
-  IfNullExpression(this.left, this.right) {
-    left?.parent = this;
-    right?.parent = this;
+  IfNullExpression(this.left, this.right)
+      // ignore: unnecessary_null_comparison
+      : assert(left != null),
+        // ignore: unnecessary_null_comparison
+        assert(right != null) {
+    left.parent = this;
+    right.parent = this;
   }
 
   @override
@@ -880,31 +887,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    left?.accept(v);
-    right?.accept(v);
+    left.accept(v);
+    right.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (left != null) {
       left = v.transform(left);
-      left?.parent = this;
+      left.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (right != null) {
       right = v.transform(right);
-      right?.parent = this;
+      right.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (left != null) {
-      left = v.transformOrRemoveExpression(left);
-      left?.parent = this;
+      left = v.transform(left);
+      left.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (right != null) {
-      right = v.transformOrRemoveExpression(right);
-      right?.parent = this;
+      right = v.transform(right);
+      right.parent = this;
     }
   }
 
@@ -930,8 +941,8 @@
   void acceptInference(InferenceVisitor visitor);
 }
 
-Expression checkWebIntLiteralsErrorIfUnexact(
-    TypeInferrerImpl inferrer, int value, String literal, int charOffset) {
+Expression? checkWebIntLiteralsErrorIfUnexact(
+    TypeInferrerImpl inferrer, int value, String? literal, int charOffset) {
   if (value >= 0 && value <= (1 << 53)) return null;
   if (inferrer.isTopLevel) return null;
   if (!inferrer.library.loader.target.backendTarget
@@ -944,7 +955,7 @@
       ? '0x${asDouble.toRadixString(16)}'
       : asDouble.toString();
   int length = literal?.length ?? noLength;
-  return inferrer.helper.buildProblem(
+  return inferrer.helper!.buildProblem(
       templateWebLiteralCannotBeRepresentedExactly.withArguments(text, nearest),
       charOffset,
       length);
@@ -952,12 +963,14 @@
 
 /// Concrete shadow object representing an integer literal in kernel form.
 class IntJudgment extends IntLiteral implements ExpressionJudgment {
-  final String literal;
+  final String? literal;
 
   IntJudgment(int value, this.literal) : super(value);
 
-  double asDouble({bool negated: false}) {
-    if (value == 0 && negated) return -0.0;
+  double? asDouble({bool negated: false}) {
+    if (value == 0 && negated) {
+      return -0.0;
+    }
     BigInt intValue = new BigInt.from(negated ? -value : value);
     double doubleValue = intValue.toDouble();
     return intValue == new BigInt.from(doubleValue) ? doubleValue : null;
@@ -979,7 +992,7 @@
     if (literal == null) {
       printer.write('$value');
     } else {
-      printer.write(literal);
+      printer.write(literal!);
     }
   }
 }
@@ -991,9 +1004,11 @@
 
   ShadowLargeIntLiteral(this.literal, this.fileOffset) : super(0);
 
-  double asDouble({bool negated: false}) {
-    BigInt intValue = BigInt.tryParse(negated ? '-${literal}' : literal);
-    if (intValue == null) return null;
+  double? asDouble({bool negated: false}) {
+    BigInt? intValue = BigInt.tryParse(negated ? '-${literal}' : literal);
+    if (intValue == null) {
+      return null;
+    }
     double doubleValue = intValue.toDouble();
     return !doubleValue.isNaN &&
             !doubleValue.isInfinite &&
@@ -1002,7 +1017,7 @@
         : null;
   }
 
-  int asInt64({bool negated: false}) {
+  int? asInt64({bool negated: false}) {
     return int.tryParse(negated ? '-${literal}' : literal);
   }
 
@@ -1047,8 +1062,10 @@
 
   ShadowInvalidFieldInitializer(
       this.field, this.value, VariableDeclaration variable)
-      : super(variable) {
-    value?.parent = this;
+      // ignore: unnecessary_null_comparison
+      : assert(value != null),
+        super(variable) {
+    value.parent = this;
   }
 
   @override
@@ -1066,9 +1083,13 @@
   Expression expression;
   Arguments arguments;
 
-  ExpressionInvocation(this.expression, this.arguments) {
-    expression?.parent = this;
-    arguments?.parent = this;
+  ExpressionInvocation(this.expression, this.arguments)
+      // ignore: unnecessary_null_comparison
+      : assert(expression != null),
+        // ignore: unnecessary_null_comparison
+        assert(arguments != null) {
+    expression.parent = this;
+    arguments.parent = this;
   }
 
   @override
@@ -1083,31 +1104,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    expression?.accept(v);
-    arguments?.accept(v);
+    expression.accept(v);
+    arguments.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (expression != null) {
       expression = v.transform(expression);
-      expression?.parent = this;
+      expression.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (arguments != null) {
       arguments = v.transform(arguments);
-      arguments?.parent = this;
+      arguments.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (expression != null) {
-      expression = v.transformOrRemoveExpression(expression);
-      expression?.parent = this;
+      expression = v.transform(expression);
+      expression.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (arguments != null) {
-      arguments = v.transformOrRemove(arguments, dummyArguments);
-      arguments?.parent = this;
+      arguments = v.transform(arguments);
+      arguments.parent = this;
     }
   }
 
@@ -1134,7 +1159,7 @@
 ///     let f = () { ... } in f
 class NamedFunctionExpressionJudgment extends Let
     implements ExpressionJudgment {
-  NamedFunctionExpressionJudgment(VariableDeclarationImpl variable)
+  NamedFunctionExpressionJudgment(VariableDeclaration variable)
       : super(variable, new VariableGet(variable));
 
   @override
@@ -1157,14 +1182,18 @@
 ///
 class NullAwareMethodInvocation extends InternalExpression {
   /// The synthetic variable whose initializer hold the receiver.
-  VariableDeclaration variable;
+  VariableDeclarationImpl variable;
 
   /// The expression that invokes the method on [variable].
   Expression invocation;
 
-  NullAwareMethodInvocation(this.variable, this.invocation) {
-    variable?.parent = this;
-    invocation?.parent = this;
+  NullAwareMethodInvocation(this.variable, this.invocation)
+      // ignore: unnecessary_null_comparison
+      : assert(variable != null),
+        // ignore: unnecessary_null_comparison
+        assert(invocation != null) {
+    variable.parent = this;
+    invocation.parent = this;
   }
 
   @override
@@ -1179,31 +1208,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    variable?.accept(v);
-    invocation?.accept(v);
+    variable.accept(v);
+    invocation.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (variable != null) {
       variable = v.transform(variable);
-      variable?.parent = this;
+      variable.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (invocation != null) {
       invocation = v.transform(invocation);
-      invocation?.parent = this;
+      invocation.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (variable != null) {
-      variable = v.transformOrRemoveVariableDeclaration(variable);
-      variable?.parent = this;
+      variable = v.transform(variable);
+      variable.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (invocation != null) {
-      invocation = v.transformOrRemoveExpression(invocation);
-      invocation?.parent = this;
+      invocation = v.transform(invocation);
+      invocation.parent = this;
     }
   }
 
@@ -1219,7 +1252,7 @@
       Expression receiver = methodInvocation.receiver;
       if (receiver is VariableGet && receiver.variable == variable) {
         // Special-case the usual use of this node.
-        printer.writeExpression(variable.initializer);
+        printer.writeExpression(variable.initializer!);
         printer.write('?.');
         printer.writeInterfaceMemberName(
             methodInvocation.interfaceTargetReference, methodInvocation.name);
@@ -1242,14 +1275,18 @@
 ///
 class NullAwarePropertyGet extends InternalExpression {
   /// The synthetic variable whose initializer hold the receiver.
-  VariableDeclaration variable;
+  VariableDeclarationImpl variable;
 
   /// The expression that reads the property from [variable].
   Expression read;
 
-  NullAwarePropertyGet(this.variable, this.read) {
-    variable?.parent = this;
-    read?.parent = this;
+  NullAwarePropertyGet(this.variable, this.read)
+      // ignore: unnecessary_null_comparison
+      : assert(variable != null),
+        // ignore: unnecessary_null_comparison
+        assert(read != null) {
+    variable.parent = this;
+    read.parent = this;
   }
 
   @override
@@ -1264,31 +1301,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    variable?.accept(v);
-    read?.accept(v);
+    variable.accept(v);
+    read.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (variable != null) {
       variable = v.transform(variable);
-      variable?.parent = this;
+      variable.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (read != null) {
       read = v.transform(read);
-      read?.parent = this;
+      read.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (variable != null) {
       variable = v.transform(variable);
-      variable?.parent = this;
+      variable.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (read != null) {
       read = v.transform(read);
-      read?.parent = this;
+      read.parent = this;
     }
   }
 
@@ -1304,7 +1345,7 @@
       Expression receiver = propertyGet.receiver;
       if (receiver is VariableGet && receiver.variable == variable) {
         // Special-case the usual use of this node.
-        printer.writeExpression(variable.initializer);
+        printer.writeExpression(variable.initializer!);
         printer.write('?.');
         printer.writeInterfaceMemberName(
             propertyGet.interfaceTargetReference, propertyGet.name);
@@ -1326,14 +1367,18 @@
 ///
 class NullAwarePropertySet extends InternalExpression {
   /// The synthetic variable whose initializer hold the receiver.
-  VariableDeclaration variable;
+  VariableDeclarationImpl variable;
 
   /// The expression that writes the value to the property in [variable].
   Expression write;
 
-  NullAwarePropertySet(this.variable, this.write) {
-    variable?.parent = this;
-    write?.parent = this;
+  NullAwarePropertySet(this.variable, this.write)
+      // ignore: unnecessary_null_comparison
+      : assert(variable != null),
+        // ignore: unnecessary_null_comparison
+        assert(write != null) {
+    variable.parent = this;
+    write.parent = this;
   }
 
   @override
@@ -1348,31 +1393,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    variable?.accept(v);
-    write?.accept(v);
+    variable.accept(v);
+    write.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (variable != null) {
       variable = v.transform(variable);
-      variable?.parent = this;
+      variable.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (write != null) {
       write = v.transform(write);
-      write?.parent = this;
+      write.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (variable != null) {
-      variable = v.transformOrRemoveVariableDeclaration(variable);
-      variable?.parent = this;
+      variable = v.transform(variable);
+      variable.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (write != null) {
-      write = v.transformOrRemoveExpression(write);
-      write?.parent = this;
+      write = v.transform(write);
+      write.parent = this;
     }
   }
 
@@ -1388,7 +1437,7 @@
       Expression receiver = propertySet.receiver;
       if (receiver is VariableGet && receiver.variable == variable) {
         // Special-case the usual use of this node.
-        printer.writeExpression(variable.initializer);
+        printer.writeExpression(variable.initializer!);
         printer.write('?.');
         printer.writeInterfaceMemberName(
             propertySet.interfaceTargetReference, propertySet.name);
@@ -1408,7 +1457,7 @@
 class ReturnStatementImpl extends ReturnStatement {
   final bool isArrow;
 
-  ReturnStatementImpl(this.isArrow, [Expression expression])
+  ReturnStatementImpl(this.isArrow, [Expression? expression])
       : super(expression);
 
   @override
@@ -1425,7 +1474,7 @@
     }
     if (expression != null) {
       printer.write(' ');
-      printer.writeExpression(expression);
+      printer.writeExpression(expression!);
     }
     printer.write(';');
   }
@@ -1476,11 +1525,11 @@
   /// used.
   bool isStaticLate;
 
-  VariableDeclarationImpl(String name, this.functionNestingLevel,
+  VariableDeclarationImpl(String? name, this.functionNestingLevel,
       {this.forSyntheticToken: false,
       this.hasDeclaredInitializer: false,
-      Expression initializer,
-      DartType type,
+      Expression? initializer,
+      DartType? type,
       bool isFinal: false,
       bool isConst: false,
       bool isFieldFormal: false,
@@ -1525,14 +1574,14 @@
   //
   // This is set in `InferenceVisitor.visitVariableDeclaration` when late
   // lowering is enabled.
-  VariableDeclaration lateGetter;
+  VariableDeclaration? lateGetter;
 
   // The synthesized local setter function for an assignable lowered late
   // variable.
   //
   // This is set in `InferenceVisitor.visitVariableDeclaration` when late
   // lowering is enabled.
-  VariableDeclaration lateSetter;
+  VariableDeclaration? lateSetter;
 
   // Is `true` if this a lowered late final variable without an initializer.
   //
@@ -1544,13 +1593,13 @@
   //
   // This is set in `InferenceVisitor.visitVariableDeclaration` when late
   // lowering is enabled.
-  DartType lateType;
+  DartType? lateType;
 
   // The original name of a lowered late variable.
   //
   // This is set in `InferenceVisitor.visitVariableDeclaration` when late
   // lowering is enabled.
-  String lateName;
+  String? lateName;
 
   @override
   bool get isAssignable {
@@ -1577,7 +1626,9 @@
   // expressions explicitly.
   final bool forNullGuardedAccess;
 
-  VariableGetImpl(VariableDeclaration variable, {this.forNullGuardedAccess})
+  VariableGetImpl(VariableDeclaration variable,
+      {required this.forNullGuardedAccess})
+      // ignore: unnecessary_null_comparison
       : assert(forNullGuardedAccess != null),
         super(variable);
 
@@ -1589,7 +1640,7 @@
 
 /// Front end specific implementation of [LoadLibrary].
 class LoadLibraryImpl extends LoadLibrary {
-  final Arguments arguments;
+  final Arguments? arguments;
 
   LoadLibraryImpl(LibraryDependency import, this.arguments) : super(import);
 
@@ -1600,9 +1651,13 @@
 
   @override
   void toTextInternal(AstPrinter printer) {
-    printer.write(import.name);
+    printer.write(import.name!);
     printer.write('.loadLibrary');
-    printer.writeArguments(arguments);
+    if (arguments != null) {
+      printer.writeArguments(arguments!);
+    } else {
+      printer.write('()');
+    }
   }
 }
 
@@ -1640,7 +1695,7 @@
 
   @override
   void toTextInternal(AstPrinter printer) {
-    printer.write(import.name);
+    printer.write(import.name!);
     printer.write('.loadLibrary');
   }
 }
@@ -1676,10 +1731,21 @@
   final int writeOffset;
 
   IfNullPropertySet(this.receiver, this.propertyName, this.rhs,
-      {this.forEffect, this.readOffset, this.writeOffset})
-      : assert(forEffect != null) {
-    receiver?.parent = this;
-    rhs?.parent = this;
+      {required this.forEffect,
+      required this.readOffset,
+      required this.writeOffset})
+      // ignore: unnecessary_null_comparison
+      : assert(receiver != null),
+        // ignore: unnecessary_null_comparison
+        assert(rhs != null),
+        // ignore: unnecessary_null_comparison
+        assert(forEffect != null),
+        // ignore: unnecessary_null_comparison
+        assert(readOffset != null),
+        // ignore: unnecessary_null_comparison
+        assert(writeOffset != null) {
+    receiver.parent = this;
+    rhs.parent = this;
   }
 
   @override
@@ -1693,31 +1759,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    receiver?.accept(v);
-    rhs?.accept(v);
+    receiver.accept(v);
+    rhs.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
       receiver = v.transform(receiver);
-      receiver?.parent = this;
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (rhs != null) {
       rhs = v.transform(rhs);
-      rhs?.parent = this;
+      rhs.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
-      receiver = v.transformOrRemoveExpression(receiver);
-      receiver?.parent = this;
+      receiver = v.transform(receiver);
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (rhs != null) {
-      rhs = v.transformOrRemoveExpression(rhs);
-      rhs?.parent = this;
+      rhs = v.transform(rhs);
+      rhs.parent = this;
     }
   }
 
@@ -1757,10 +1827,15 @@
   /// If `true`, the expression is only need for effect and not for its value.
   final bool forEffect;
 
-  IfNullSet(this.read, this.write, {this.forEffect})
-      : assert(forEffect != null) {
-    read?.parent = this;
-    write?.parent = this;
+  IfNullSet(this.read, this.write, {required this.forEffect})
+      // ignore: unnecessary_null_comparison
+      : assert(read != null),
+        // ignore: unnecessary_null_comparison
+        assert(write != null),
+        // ignore: unnecessary_null_comparison
+        assert(forEffect != null) {
+    read.parent = this;
+    write.parent = this;
   }
 
   @override
@@ -1774,31 +1849,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    read?.accept(v);
-    write?.accept(v);
+    read.accept(v);
+    write.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (read != null) {
       read = v.transform(read);
-      read?.parent = this;
+      read.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (write != null) {
       write = v.transform(write);
-      write?.parent = this;
+      write.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (read != null) {
-      read = v.transformOrRemoveExpression(read);
-      read?.parent = this;
+      read = v.transform(read);
+      read.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (write != null) {
-      write = v.transformOrRemoveExpression(write);
-      write?.parent = this;
+      write = v.transform(write);
+      write.parent = this;
     }
   }
 
@@ -1844,7 +1923,7 @@
 
   /// The explicit type arguments for the type parameters declared in
   /// [extension].
-  final List<DartType> explicitTypeArguments;
+  final List<DartType>? explicitTypeArguments;
 
   /// The receiver used for the read/write operations.
   Expression receiver;
@@ -1853,7 +1932,7 @@
   final Name propertyName;
 
   /// The member used for the read operation.
-  final Member getter;
+  final Member? getter;
 
   /// The binary operation performed on the getter result and [rhs].
   final Name binaryName;
@@ -1862,7 +1941,7 @@
   Expression rhs;
 
   /// The member used for the write operation.
-  final Member setter;
+  final Member? setter;
 
   /// If `true`, the expression is only need for effect and not for its value.
   final bool forEffect;
@@ -1885,16 +1964,24 @@
       this.binaryName,
       this.rhs,
       this.setter,
-      {this.forEffect,
-      this.readOffset,
-      this.binaryOffset,
-      this.writeOffset})
-      : assert(forEffect != null),
+      {required this.forEffect,
+      required this.readOffset,
+      required this.binaryOffset,
+      required this.writeOffset})
+      // ignore: unnecessary_null_comparison
+      : assert(receiver != null),
+        // ignore: unnecessary_null_comparison
+        assert(rhs != null),
+        // ignore: unnecessary_null_comparison
+        assert(forEffect != null),
+        // ignore: unnecessary_null_comparison
         assert(readOffset != null),
+        // ignore: unnecessary_null_comparison
         assert(binaryOffset != null),
+        // ignore: unnecessary_null_comparison
         assert(writeOffset != null) {
-    receiver?.parent = this;
-    rhs?.parent = this;
+    receiver.parent = this;
+    rhs.parent = this;
   }
 
   @override
@@ -1909,31 +1996,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    receiver?.accept(v);
-    rhs?.accept(v);
+    receiver.accept(v);
+    rhs.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
       receiver = v.transform(receiver);
-      receiver?.parent = this;
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (rhs != null) {
       rhs = v.transform(rhs);
-      rhs?.parent = this;
+      rhs.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
-      receiver = v.transformOrRemoveExpression(receiver);
-      receiver?.parent = this;
+      receiver = v.transform(receiver);
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (rhs != null) {
-      rhs = v.transformOrRemoveExpression(rhs);
-      rhs?.parent = this;
+      rhs = v.transform(rhs);
+      rhs.parent = this;
     }
   }
 
@@ -1981,13 +2072,24 @@
 
   CompoundPropertySet(
       this.receiver, this.propertyName, this.binaryName, this.rhs,
-      {this.forEffect, this.readOffset, this.binaryOffset, this.writeOffset})
-      : assert(forEffect != null),
+      {required this.forEffect,
+      required this.readOffset,
+      required this.binaryOffset,
+      required this.writeOffset})
+      // ignore: unnecessary_null_comparison
+      : assert(receiver != null),
+        // ignore: unnecessary_null_comparison
+        assert(rhs != null),
+        // ignore: unnecessary_null_comparison
+        assert(forEffect != null),
+        // ignore: unnecessary_null_comparison
         assert(readOffset != null),
+        // ignore: unnecessary_null_comparison
         assert(binaryOffset != null),
+        // ignore: unnecessary_null_comparison
         assert(writeOffset != null) {
-    receiver?.parent = this;
-    rhs?.parent = this;
+    receiver.parent = this;
+    rhs.parent = this;
   }
 
   @override
@@ -2001,31 +2103,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    receiver?.accept(v);
-    rhs?.accept(v);
+    receiver.accept(v);
+    rhs.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
       receiver = v.transform(receiver);
-      receiver?.parent = this;
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (rhs != null) {
       rhs = v.transform(rhs);
-      rhs?.parent = this;
+      rhs.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
-      receiver = v.transformOrRemoveExpression(receiver);
-      receiver?.parent = this;
+      receiver = v.transform(receiver);
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (rhs != null) {
-      rhs = v.transformOrRemoveExpression(rhs);
-      rhs?.parent = this;
+      rhs = v.transform(rhs);
+      rhs.parent = this;
     }
   }
 
@@ -2058,23 +2164,27 @@
   ///
   /// This is `null` if the receiver is read-only and therefore does not need to
   /// be stored in a temporary variable.
-  VariableDeclaration variable;
+  VariableDeclarationImpl? variable;
 
   /// The expression that reads the property on [variable].
-  VariableDeclaration read;
+  VariableDeclarationImpl read;
 
   /// The expression that writes the result of the binary operation to the
   /// property on [variable].
-  VariableDeclaration write;
+  VariableDeclarationImpl write;
 
-  PropertyPostIncDec(this.variable, this.read, this.write) {
+  PropertyPostIncDec(this.variable, this.read, this.write)
+      // ignore: unnecessary_null_comparison
+      : assert(read != null),
+        // ignore: unnecessary_null_comparison
+        assert(write != null) {
     variable?.parent = this;
-    read?.parent = this;
-    write?.parent = this;
+    read.parent = this;
+    write.parent = this;
   }
 
   PropertyPostIncDec.onReadOnly(
-      VariableDeclaration read, VariableDeclaration write)
+      VariableDeclarationImpl read, VariableDeclarationImpl write)
       : this(null, read, write);
 
   @override
@@ -2089,31 +2199,36 @@
   @override
   void visitChildren(Visitor<dynamic> v) {
     variable?.accept(v);
-    read?.accept(v);
-    write?.accept(v);
+    read.accept(v);
+    write.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (variable != null) {
-      variable = v.transform(variable);
+      variable = v.transform(variable!);
       variable?.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (write != null) {
       write = v.transform(write);
-      write?.parent = this;
+      write.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (variable != null) {
-      variable = v.transformOrRemoveVariableDeclaration(variable);
+      variable = v.transformOrRemoveVariableDeclaration(variable!)
+          as VariableDeclarationImpl?;
       variable?.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (write != null) {
-      write = v.transformOrRemoveVariableDeclaration(write);
-      write?.parent = this;
+      write = v.transform(write);
+      write.parent = this;
     }
   }
 
@@ -2132,15 +2247,19 @@
 ///
 class LocalPostIncDec extends InternalExpression {
   /// The expression that reads the local variable.
-  VariableDeclaration read;
+  VariableDeclarationImpl read;
 
   /// The expression that writes the result of the binary operation to the
   /// local variable.
-  VariableDeclaration write;
+  VariableDeclarationImpl write;
 
-  LocalPostIncDec(this.read, this.write) {
-    read?.parent = this;
-    write?.parent = this;
+  LocalPostIncDec(this.read, this.write)
+      // ignore: unnecessary_null_comparison
+      : assert(read != null),
+        // ignore: unnecessary_null_comparison
+        assert(write != null) {
+    read.parent = this;
+    write.parent = this;
   }
 
   @override
@@ -2154,31 +2273,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    read?.accept(v);
-    write?.accept(v);
+    read.accept(v);
+    write.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (read != null) {
       read = v.transform(read);
-      read?.parent = this;
+      read.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (write != null) {
       write = v.transform(write);
-      write?.parent = this;
+      write.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (read != null) {
-      read = v.transformOrRemoveVariableDeclaration(read);
-      read?.parent = this;
+      read = v.transform(read);
+      read.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (write != null) {
-      write = v.transformOrRemoveVariableDeclaration(write);
-      write?.parent = this;
+      write = v.transform(write);
+      write.parent = this;
     }
   }
 
@@ -2197,15 +2320,19 @@
 ///
 class StaticPostIncDec extends InternalExpression {
   /// The expression that reads the static member.
-  VariableDeclaration read;
+  VariableDeclarationImpl read;
 
   /// The expression that writes the result of the binary operation to the
   /// static member.
-  VariableDeclaration write;
+  VariableDeclarationImpl write;
 
-  StaticPostIncDec(this.read, this.write) {
-    read?.parent = this;
-    write?.parent = this;
+  StaticPostIncDec(this.read, this.write)
+      // ignore: unnecessary_null_comparison
+      : assert(read != null),
+        // ignore: unnecessary_null_comparison
+        assert(write != null) {
+    read.parent = this;
+    write.parent = this;
   }
 
   @override
@@ -2219,31 +2346,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    read?.accept(v);
-    write?.accept(v);
+    read.accept(v);
+    write.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (read != null) {
       read = v.transform(read);
-      read?.parent = this;
+      read.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (write != null) {
       write = v.transform(write);
-      write?.parent = this;
+      write.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (read != null) {
       read = v.transform(read);
-      read?.parent = this;
+      read.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (write != null) {
       write = v.transform(write);
-      write?.parent = this;
+      write.parent = this;
     }
   }
 
@@ -2262,15 +2393,19 @@
 ///
 class SuperPostIncDec extends InternalExpression {
   /// The expression that reads the static member.
-  VariableDeclaration read;
+  VariableDeclarationImpl read;
 
   /// The expression that writes the result of the binary operation to the
   /// static member.
-  VariableDeclaration write;
+  VariableDeclarationImpl write;
 
-  SuperPostIncDec(this.read, this.write) {
-    read?.parent = this;
-    write?.parent = this;
+  SuperPostIncDec(this.read, this.write)
+      // ignore: unnecessary_null_comparison
+      : assert(read != null),
+        // ignore: unnecessary_null_comparison
+        assert(write != null) {
+    read.parent = this;
+    write.parent = this;
   }
 
   @override
@@ -2284,31 +2419,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    read?.accept(v);
-    write?.accept(v);
+    read.accept(v);
+    write.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (read != null) {
       read = v.transform(read);
-      read?.parent = this;
+      read.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (write != null) {
       write = v.transform(write);
-      write?.parent = this;
+      write.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (read != null) {
-      read = v.transformOrRemoveVariableDeclaration(read);
-      read?.parent = this;
+      read = v.transform(read);
+      read.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (write != null) {
-      write = v.transformOrRemoveVariableDeclaration(write);
-      write?.parent = this;
+      write = v.transform(write);
+      write.parent = this;
     }
   }
 
@@ -2326,9 +2465,13 @@
   /// The index expression of the operation.
   Expression index;
 
-  IndexGet(this.receiver, this.index) {
-    receiver?.parent = this;
-    index?.parent = this;
+  IndexGet(this.receiver, this.index)
+      // ignore: unnecessary_null_comparison
+      : assert(receiver != null),
+        // ignore: unnecessary_null_comparison
+        assert(index != null) {
+    receiver.parent = this;
+    index.parent = this;
   }
 
   @override
@@ -2342,31 +2485,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    receiver?.accept(v);
-    index?.accept(v);
+    receiver.accept(v);
+    index.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
       receiver = v.transform(receiver);
-      receiver?.parent = this;
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (index != null) {
       index = v.transform(index);
-      index?.parent = this;
+      index.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
-      receiver = v.transformOrRemoveExpression(receiver);
-      receiver?.parent = this;
+      receiver = v.transform(receiver);
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (index != null) {
-      index = v.transformOrRemoveExpression(index);
-      index?.parent = this;
+      index = v.transform(index);
+      index.parent = this;
     }
   }
 
@@ -2401,11 +2548,18 @@
 
   final bool forEffect;
 
-  IndexSet(this.receiver, this.index, this.value, {this.forEffect})
-      : assert(forEffect != null) {
-    receiver?.parent = this;
-    index?.parent = this;
-    value?.parent = this;
+  IndexSet(this.receiver, this.index, this.value, {required this.forEffect})
+      // ignore: unnecessary_null_comparison
+      : assert(receiver != null),
+        // ignore: unnecessary_null_comparison
+        assert(index != null),
+        // ignore: unnecessary_null_comparison
+        assert(value != null),
+        // ignore: unnecessary_null_comparison
+        assert(forEffect != null) {
+    receiver.parent = this;
+    index.parent = this;
+    value.parent = this;
   }
 
   @override
@@ -2419,40 +2573,46 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    receiver?.accept(v);
-    index?.accept(v);
-    value?.accept(v);
+    receiver.accept(v);
+    index.accept(v);
+    value.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
       receiver = v.transform(receiver);
-      receiver?.parent = this;
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (index != null) {
       index = v.transform(index);
-      index?.parent = this;
+      index.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (value != null) {
       value = v.transform(value);
-      value?.parent = this;
+      value.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
-      receiver = v.transformOrRemoveExpression(receiver);
-      receiver?.parent = this;
+      receiver = v.transform(receiver);
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (index != null) {
-      index = v.transformOrRemoveExpression(index);
-      index?.parent = this;
+      index = v.transform(index);
+      index.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (value != null) {
-      value = v.transformOrRemoveExpression(value);
-      value?.parent = this;
+      value = v.transform(value);
+      value.parent = this;
     }
   }
 
@@ -2477,7 +2637,7 @@
 ///
 class SuperIndexSet extends InternalExpression {
   /// The []= member.
-  Member setter;
+  Member? setter;
 
   /// The index expression of the operation.
   Expression index;
@@ -2485,9 +2645,13 @@
   /// The value expression of the operation.
   Expression value;
 
-  SuperIndexSet(this.setter, this.index, this.value) {
-    index?.parent = this;
-    value?.parent = this;
+  SuperIndexSet(this.setter, this.index, this.value)
+      // ignore: unnecessary_null_comparison
+      : assert(index != null),
+        // ignore: unnecessary_null_comparison
+        assert(value != null) {
+    index.parent = this;
+    value.parent = this;
   }
 
   @override
@@ -2501,31 +2665,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    index?.accept(v);
-    value?.accept(v);
+    index.accept(v);
+    value.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (index != null) {
       index = v.transform(index);
-      index?.parent = this;
+      index.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (value != null) {
       value = v.transform(value);
-      value?.parent = this;
+      value.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (index != null) {
-      index = v.transformOrRemoveExpression(index);
-      index?.parent = this;
+      index = v.transform(index);
+      index.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (value != null) {
-      value = v.transformOrRemoveExpression(value);
-      value?.parent = this;
+      value = v.transform(value);
+      value.parent = this;
     }
   }
 
@@ -2559,7 +2727,7 @@
 
   /// The explicit type arguments for the type parameters declared in
   /// [extension].
-  final List<DartType> explicitTypeArguments;
+  final List<DartType>? explicitTypeArguments;
 
   /// The receiver of the extension access.
   Expression receiver;
@@ -2576,10 +2744,16 @@
   ExtensionIndexSet(this.extension, this.explicitTypeArguments, this.receiver,
       this.setter, this.index, this.value)
       : assert(explicitTypeArguments == null ||
-            explicitTypeArguments.length == extension.typeParameters.length) {
-    receiver?.parent = this;
-    index?.parent = this;
-    value?.parent = this;
+            explicitTypeArguments.length == extension.typeParameters.length),
+        // ignore: unnecessary_null_comparison
+        assert(receiver != null),
+        // ignore: unnecessary_null_comparison
+        assert(index != null),
+        // ignore: unnecessary_null_comparison
+        assert(value != null) {
+    receiver.parent = this;
+    index.parent = this;
+    value.parent = this;
   }
 
   @override
@@ -2593,40 +2767,46 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    receiver?.accept(v);
-    index?.accept(v);
-    value?.accept(v);
+    receiver.accept(v);
+    index.accept(v);
+    value.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
       receiver = v.transform(receiver);
-      receiver?.parent = this;
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (index != null) {
       index = v.transform(index);
-      index?.parent = this;
+      index.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (value != null) {
       value = v.transform(value);
-      value?.parent = this;
+      value.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
-      receiver = v.transformOrRemoveExpression(receiver);
-      receiver?.parent = this;
+      receiver = v.transform(receiver);
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (index != null) {
-      index = v.transformOrRemoveExpression(index);
-      index?.parent = this;
+      index = v.transform(index);
+      index.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (value != null) {
-      value = v.transformOrRemoveExpression(value);
-      value?.parent = this;
+      value = v.transform(value);
+      value.parent = this;
     }
   }
 
@@ -2639,7 +2819,7 @@
   void toTextInternal(AstPrinter printer) {
     printer.write(extension.name);
     if (explicitTypeArguments != null) {
-      printer.writeTypeArguments(explicitTypeArguments);
+      printer.writeTypeArguments(explicitTypeArguments!);
     }
     printer.write('(');
     printer.writeExpression(receiver);
@@ -2696,14 +2876,27 @@
   final bool forEffect;
 
   IfNullIndexSet(this.receiver, this.index, this.value,
-      {this.readOffset, this.testOffset, this.writeOffset, this.forEffect})
-      : assert(readOffset != null),
+      {required this.readOffset,
+      required this.testOffset,
+      required this.writeOffset,
+      required this.forEffect})
+      // ignore: unnecessary_null_comparison
+      : assert(receiver != null),
+        // ignore: unnecessary_null_comparison
+        assert(index != null),
+        // ignore: unnecessary_null_comparison
+        assert(value != null),
+        // ignore: unnecessary_null_comparison
+        assert(readOffset != null),
+        // ignore: unnecessary_null_comparison
         assert(testOffset != null),
+        // ignore: unnecessary_null_comparison
         assert(writeOffset != null),
+        // ignore: unnecessary_null_comparison
         assert(forEffect != null) {
-    receiver?.parent = this;
-    index?.parent = this;
-    value?.parent = this;
+    receiver.parent = this;
+    index.parent = this;
+    value.parent = this;
   }
 
   @override
@@ -2717,40 +2910,46 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    receiver?.accept(v);
-    index?.accept(v);
-    value?.accept(v);
+    receiver.accept(v);
+    index.accept(v);
+    value.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
       receiver = v.transform(receiver);
-      receiver?.parent = this;
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (index != null) {
       index = v.transform(index);
-      index?.parent = this;
+      index.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (value != null) {
       value = v.transform(value);
-      value?.parent = this;
+      value.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
-      receiver = v.transformOrRemoveExpression(receiver);
-      receiver?.parent = this;
+      receiver = v.transform(receiver);
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (index != null) {
-      index = v.transformOrRemoveExpression(index);
-      index?.parent = this;
+      index = v.transform(index);
+      index.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (value != null) {
-      value = v.transformOrRemoveExpression(value);
-      value?.parent = this;
+      value = v.transform(value);
+      value.parent = this;
     }
   }
 
@@ -2781,10 +2980,10 @@
 ///
 class IfNullSuperIndexSet extends InternalExpression {
   /// The [] member;
-  Member getter;
+  Member? getter;
 
   /// The []= member;
-  Member setter;
+  Member? setter;
 
   /// The index expression of the operation.
   Expression index;
@@ -2805,13 +3004,24 @@
   final bool forEffect;
 
   IfNullSuperIndexSet(this.getter, this.setter, this.index, this.value,
-      {this.readOffset, this.testOffset, this.writeOffset, this.forEffect})
-      : assert(readOffset != null),
+      {required this.readOffset,
+      required this.testOffset,
+      required this.writeOffset,
+      required this.forEffect})
+      // ignore: unnecessary_null_comparison
+      : assert(index != null),
+        // ignore: unnecessary_null_comparison
+        assert(value != null),
+        // ignore: unnecessary_null_comparison
+        assert(readOffset != null),
+        // ignore: unnecessary_null_comparison
         assert(testOffset != null),
+        // ignore: unnecessary_null_comparison
         assert(writeOffset != null),
+        // ignore: unnecessary_null_comparison
         assert(forEffect != null) {
-    index?.parent = this;
-    value?.parent = this;
+    index.parent = this;
+    value.parent = this;
   }
 
   @override
@@ -2825,31 +3035,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    index?.accept(v);
-    value?.accept(v);
+    index.accept(v);
+    value.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (index != null) {
       index = v.transform(index);
-      index?.parent = this;
+      index.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (value != null) {
       value = v.transform(value);
-      value?.parent = this;
+      value.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (index != null) {
-      index = v.transformOrRemoveExpression(index);
-      index?.parent = this;
+      index = v.transform(index);
+      index.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (value != null) {
-      value = v.transformOrRemoveExpression(value);
-      value?.parent = this;
+      value = v.transform(value);
+      value.parent = this;
     }
   }
 
@@ -2881,16 +3095,16 @@
 class IfNullExtensionIndexSet extends InternalExpression {
   final Extension extension;
 
-  final List<DartType> explicitTypeArguments;
+  final List<DartType>? explicitTypeArguments;
 
   /// The extension receiver;
   Expression receiver;
 
   /// The [] member;
-  Member getter;
+  Member? getter;
 
   /// The []= member;
-  Member setter;
+  Member? setter;
 
   /// The index expression of the operation.
   Expression index;
@@ -2912,16 +3126,29 @@
 
   IfNullExtensionIndexSet(this.extension, this.explicitTypeArguments,
       this.receiver, this.getter, this.setter, this.index, this.value,
-      {this.readOffset, this.testOffset, this.writeOffset, this.forEffect})
+      {required this.readOffset,
+      required this.testOffset,
+      required this.writeOffset,
+      required this.forEffect})
       : assert(explicitTypeArguments == null ||
             explicitTypeArguments.length == extension.typeParameters.length),
+        // ignore: unnecessary_null_comparison
+        assert(receiver != null),
+        // ignore: unnecessary_null_comparison
+        assert(index != null),
+        // ignore: unnecessary_null_comparison
+        assert(value != null),
+        // ignore: unnecessary_null_comparison
         assert(readOffset != null),
+        // ignore: unnecessary_null_comparison
         assert(testOffset != null),
+        // ignore: unnecessary_null_comparison
         assert(writeOffset != null),
+        // ignore: unnecessary_null_comparison
         assert(forEffect != null) {
-    receiver?.parent = this;
-    index?.parent = this;
-    value?.parent = this;
+    receiver.parent = this;
+    index.parent = this;
+    value.parent = this;
   }
 
   @override
@@ -2936,40 +3163,46 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    receiver?.accept(v);
-    index?.accept(v);
-    value?.accept(v);
+    receiver.accept(v);
+    index.accept(v);
+    value.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
       receiver = v.transform(receiver);
-      receiver?.parent = this;
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (index != null) {
       index = v.transform(index);
-      index?.parent = this;
+      index.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (value != null) {
       value = v.transform(value);
-      value?.parent = this;
+      value.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
-      receiver = v.transformOrRemoveExpression(receiver);
-      receiver?.parent = this;
+      receiver = v.transform(receiver);
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (index != null) {
-      index = v.transformOrRemoveExpression(index);
-      index?.parent = this;
+      index = v.transform(index);
+      index.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (value != null) {
-      value = v.transformOrRemoveExpression(value);
-      value?.parent = this;
+      value = v.transform(value);
+      value.parent = this;
     }
   }
 
@@ -3022,15 +3255,30 @@
   final bool forPostIncDec;
 
   CompoundIndexSet(this.receiver, this.index, this.binaryName, this.rhs,
-      {this.readOffset,
-      this.binaryOffset,
-      this.writeOffset,
-      this.forEffect,
-      this.forPostIncDec})
-      : assert(forEffect != null) {
-    receiver?.parent = this;
-    index?.parent = this;
-    rhs?.parent = this;
+      {required this.readOffset,
+      required this.binaryOffset,
+      required this.writeOffset,
+      required this.forEffect,
+      required this.forPostIncDec})
+      // ignore: unnecessary_null_comparison
+      : assert(receiver != null),
+        // ignore: unnecessary_null_comparison
+        assert(index != null),
+        // ignore: unnecessary_null_comparison
+        assert(rhs != null),
+        // ignore: unnecessary_null_comparison
+        assert(readOffset != null),
+        // ignore: unnecessary_null_comparison
+        assert(binaryOffset != null),
+        // ignore: unnecessary_null_comparison
+        assert(writeOffset != null),
+        // ignore: unnecessary_null_comparison
+        assert(forEffect != null),
+        // ignore: unnecessary_null_comparison
+        assert(forPostIncDec != null) {
+    receiver.parent = this;
+    index.parent = this;
+    rhs.parent = this;
     fileOffset = binaryOffset;
   }
 
@@ -3045,40 +3293,46 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    receiver?.accept(v);
-    index?.accept(v);
-    rhs?.accept(v);
+    receiver.accept(v);
+    index.accept(v);
+    rhs.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
       receiver = v.transform(receiver);
-      receiver?.parent = this;
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (index != null) {
       index = v.transform(index);
-      index?.parent = this;
+      index.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (rhs != null) {
       rhs = v.transform(rhs);
-      rhs?.parent = this;
+      rhs.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
-      receiver = v.transformOrRemoveExpression(receiver);
-      receiver?.parent = this;
+      receiver = v.transform(receiver);
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (index != null) {
-      index = v.transformOrRemoveExpression(index);
-      index?.parent = this;
+      index = v.transform(index);
+      index.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (rhs != null) {
-      rhs = v.transformOrRemoveExpression(rhs);
-      rhs?.parent = this;
+      rhs = v.transform(rhs);
+      rhs.parent = this;
     }
   }
 
@@ -3174,18 +3428,27 @@
 
   NullAwareCompoundSet(
       this.receiver, this.propertyName, this.binaryName, this.rhs,
-      {this.readOffset,
-      this.binaryOffset,
-      this.writeOffset,
-      this.forEffect,
-      this.forPostIncDec})
-      : assert(readOffset != null),
+      {required this.readOffset,
+      required this.binaryOffset,
+      required this.writeOffset,
+      required this.forEffect,
+      required this.forPostIncDec})
+      // ignore: unnecessary_null_comparison
+      : assert(receiver != null),
+        // ignore: unnecessary_null_comparison
+        assert(rhs != null),
+        // ignore: unnecessary_null_comparison
+        assert(readOffset != null),
+        // ignore: unnecessary_null_comparison
         assert(binaryOffset != null),
+        // ignore: unnecessary_null_comparison
         assert(writeOffset != null),
+        // ignore: unnecessary_null_comparison
         assert(forEffect != null),
+        // ignore: unnecessary_null_comparison
         assert(forPostIncDec != null) {
-    receiver?.parent = this;
-    rhs?.parent = this;
+    receiver.parent = this;
+    rhs.parent = this;
     fileOffset = binaryOffset;
   }
 
@@ -3201,31 +3464,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    receiver?.accept(v);
-    rhs?.accept(v);
+    receiver.accept(v);
+    rhs.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
       receiver = v.transform(receiver);
-      receiver?.parent = this;
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (rhs != null) {
       rhs = v.transform(rhs);
-      rhs?.parent = this;
+      rhs.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
-      receiver = v.transformOrRemoveExpression(receiver);
-      receiver?.parent = this;
+      receiver = v.transform(receiver);
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (rhs != null) {
-      rhs = v.transformOrRemoveExpression(rhs);
-      rhs?.parent = this;
+      rhs = v.transform(rhs);
+      rhs.parent = this;
     }
   }
 
@@ -3302,13 +3569,24 @@
   final bool forEffect;
 
   NullAwareIfNullSet(this.receiver, this.name, this.value,
-      {this.readOffset, this.writeOffset, this.testOffset, this.forEffect})
-      : assert(readOffset != null),
+      {required this.readOffset,
+      required this.writeOffset,
+      required this.testOffset,
+      required this.forEffect})
+      // ignore: unnecessary_null_comparison
+      : assert(receiver != null),
+        // ignore: unnecessary_null_comparison
+        assert(value != null),
+        // ignore: unnecessary_null_comparison
+        assert(readOffset != null),
+        // ignore: unnecessary_null_comparison
         assert(writeOffset != null),
+        // ignore: unnecessary_null_comparison
         assert(testOffset != null),
+        // ignore: unnecessary_null_comparison
         assert(forEffect != null) {
-    receiver?.parent = this;
-    value?.parent = this;
+    receiver.parent = this;
+    value.parent = this;
   }
 
   @override
@@ -3322,31 +3600,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    receiver?.accept(v);
-    value?.accept(v);
+    receiver.accept(v);
+    value.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
       receiver = v.transform(receiver);
-      receiver?.parent = this;
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (value != null) {
       value = v.transform(value);
-      value?.parent = this;
+      value.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
-      receiver = v.transformOrRemoveExpression(receiver);
-      receiver?.parent = this;
+      receiver = v.transform(receiver);
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (value != null) {
-      value = v.transformOrRemoveExpression(value);
-      value?.parent = this;
+      value = v.transform(value);
+      value.parent = this;
     }
   }
 
@@ -3380,10 +3662,10 @@
 ///
 class CompoundSuperIndexSet extends InternalExpression {
   /// The [] member.
-  Member getter;
+  Member? getter;
 
   /// The []= member.
-  Member setter;
+  Member? setter;
 
   /// The index expression of the operation.
   Expression index;
@@ -3411,14 +3693,27 @@
 
   CompoundSuperIndexSet(
       this.getter, this.setter, this.index, this.binaryName, this.rhs,
-      {this.readOffset,
-      this.binaryOffset,
-      this.writeOffset,
-      this.forEffect,
-      this.forPostIncDec})
-      : assert(forEffect != null) {
-    index?.parent = this;
-    rhs?.parent = this;
+      {required this.readOffset,
+      required this.binaryOffset,
+      required this.writeOffset,
+      required this.forEffect,
+      required this.forPostIncDec})
+      // ignore: unnecessary_null_comparison
+      : assert(index != null),
+        // ignore: unnecessary_null_comparison
+        assert(rhs != null),
+        // ignore: unnecessary_null_comparison
+        assert(readOffset != null),
+        // ignore: unnecessary_null_comparison
+        assert(binaryOffset != null),
+        // ignore: unnecessary_null_comparison
+        assert(writeOffset != null),
+        // ignore: unnecessary_null_comparison
+        assert(forEffect != null),
+        // ignore: unnecessary_null_comparison
+        assert(forPostIncDec != null) {
+    index.parent = this;
+    rhs.parent = this;
     fileOffset = binaryOffset;
   }
 
@@ -3434,31 +3729,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    index?.accept(v);
-    rhs?.accept(v);
+    index.accept(v);
+    rhs.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (index != null) {
       index = v.transform(index);
-      index?.parent = this;
+      index.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (rhs != null) {
       rhs = v.transform(rhs);
-      rhs?.parent = this;
+      rhs.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (index != null) {
-      index = v.transformOrRemoveExpression(index);
-      index?.parent = this;
+      index = v.transform(index);
+      index.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (rhs != null) {
-      rhs = v.transformOrRemoveExpression(rhs);
-      rhs?.parent = this;
+      rhs = v.transform(rhs);
+      rhs.parent = this;
     }
   }
 
@@ -3490,15 +3789,15 @@
 class CompoundExtensionIndexSet extends InternalExpression {
   final Extension extension;
 
-  final List<DartType> explicitTypeArguments;
+  final List<DartType>? explicitTypeArguments;
 
   Expression receiver;
 
   /// The [] member.
-  Member getter;
+  Member? getter;
 
   /// The []= member.
-  Member setter;
+  Member? setter;
 
   /// The index expression of the operation.
   Expression index;
@@ -3533,21 +3832,32 @@
       this.index,
       this.binaryName,
       this.rhs,
-      {this.readOffset,
-      this.binaryOffset,
-      this.writeOffset,
-      this.forEffect,
-      this.forPostIncDec})
+      {required this.readOffset,
+      required this.binaryOffset,
+      required this.writeOffset,
+      required this.forEffect,
+      required this.forPostIncDec})
       : assert(explicitTypeArguments == null ||
             explicitTypeArguments.length == extension.typeParameters.length),
+        // ignore: unnecessary_null_comparison
+        assert(receiver != null),
+        // ignore: unnecessary_null_comparison
+        assert(index != null),
+        // ignore: unnecessary_null_comparison
+        assert(rhs != null),
+        // ignore: unnecessary_null_comparison
         assert(readOffset != null),
+        // ignore: unnecessary_null_comparison
         assert(binaryOffset != null),
+        // ignore: unnecessary_null_comparison
         assert(writeOffset != null),
+        // ignore: unnecessary_null_comparison
         assert(forEffect != null),
+        // ignore: unnecessary_null_comparison
         assert(forPostIncDec != null) {
-    receiver?.parent = this;
-    index?.parent = this;
-    rhs?.parent = this;
+    receiver.parent = this;
+    index.parent = this;
+    rhs.parent = this;
     fileOffset = binaryOffset;
   }
 
@@ -3563,40 +3873,46 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    receiver?.accept(v);
-    index?.accept(v);
-    rhs?.accept(v);
+    receiver.accept(v);
+    index.accept(v);
+    rhs.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
       receiver = v.transform(receiver);
-      receiver?.parent = this;
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (index != null) {
       index = v.transform(index);
-      index?.parent = this;
+      index.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (rhs != null) {
       rhs = v.transform(rhs);
-      rhs?.parent = this;
+      rhs.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
-      receiver = v.transformOrRemoveExpression(receiver);
-      receiver?.parent = this;
+      receiver = v.transform(receiver);
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (index != null) {
-      index = v.transformOrRemoveExpression(index);
-      index?.parent = this;
+      index = v.transform(index);
+      index.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (rhs != null) {
-      rhs = v.transformOrRemoveExpression(rhs);
-      rhs?.parent = this;
+      rhs = v.transform(rhs);
+      rhs.parent = this;
     }
   }
 
@@ -3630,13 +3946,13 @@
 class ExtensionSet extends InternalExpression {
   final Extension extension;
 
-  final List<DartType> explicitTypeArguments;
+  final List<DartType>? explicitTypeArguments;
 
   /// The receiver for the assignment.
   Expression receiver;
 
   /// The extension member called for the assignment.
-  Member target;
+  Procedure target;
 
   /// The right-hand side value of the assignment.
   Expression value;
@@ -3647,12 +3963,17 @@
 
   ExtensionSet(this.extension, this.explicitTypeArguments, this.receiver,
       this.target, this.value,
-      {this.forEffect})
+      {required this.forEffect})
       : assert(explicitTypeArguments == null ||
             explicitTypeArguments.length == extension.typeParameters.length),
+        // ignore: unnecessary_null_comparison
+        assert(receiver != null),
+        // ignore: unnecessary_null_comparison
+        assert(value != null),
+        // ignore: unnecessary_null_comparison
         assert(forEffect != null) {
-    receiver?.parent = this;
-    value?.parent = this;
+    receiver.parent = this;
+    value.parent = this;
   }
 
   @override
@@ -3666,31 +3987,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    receiver?.accept(v);
-    value?.accept(v);
+    receiver.accept(v);
+    value.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
       receiver = v.transform(receiver);
-      receiver?.parent = this;
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (value != null) {
       value = v.transform(value);
-      value?.parent = this;
+      value.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (receiver != null) {
       receiver = v.transform(receiver);
-      receiver?.parent = this;
+      receiver.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (value != null) {
       value = v.transform(value);
-      value?.parent = this;
+      value.parent = this;
     }
   }
 
@@ -3710,12 +4035,16 @@
 ///
 /// where `expression` is an encoding of `receiverVariable.target`.
 class NullAwareExtension extends InternalExpression {
-  VariableDeclaration variable;
+  VariableDeclarationImpl variable;
   Expression expression;
 
-  NullAwareExtension(this.variable, this.expression) {
-    variable?.parent = this;
-    expression?.parent = this;
+  NullAwareExtension(this.variable, this.expression)
+      // ignore: unnecessary_null_comparison
+      : assert(variable != null),
+        // ignore: unnecessary_null_comparison
+        assert(expression != null) {
+    variable.parent = this;
+    expression.parent = this;
   }
 
   @override
@@ -3729,31 +4058,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    variable?.accept(v);
-    expression?.accept(v);
+    variable.accept(v);
+    expression.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (variable != null) {
       variable = v.transform(variable);
-      variable?.parent = this;
+      variable.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (expression != null) {
       expression = v.transform(expression);
-      expression?.parent = this;
+      expression.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (variable != null) {
-      variable = v.transformOrRemoveVariableDeclaration(variable);
-      variable?.parent = this;
+      variable = v.transform(variable);
+      variable.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (expression != null) {
-      expression = v.transformOrRemoveExpression(expression);
-      expression?.parent = this;
+      expression = v.transform(expression);
+      expression.parent = this;
     }
   }
 
@@ -3773,9 +4106,12 @@
   final bool readOnlyReceiver;
 
   PropertySetImpl(Expression receiver, Name name, Expression value,
-      {Member interfaceTarget, this.forEffect, this.readOnlyReceiver})
+      {required this.forEffect, required this.readOnlyReceiver})
+      // ignore: unnecessary_null_comparison
       : assert(forEffect != null),
-        super(receiver, name, value, interfaceTarget);
+        // ignore: unnecessary_null_comparison
+        assert(readOnlyReceiver != null),
+        super(receiver, name, value);
 
   @override
   String toString() {
@@ -3797,13 +4133,15 @@
 /// extension instance getter being read.
 class ExtensionTearOff extends InternalExpression {
   /// The top-level method that is that target for the read operation.
-  Member target;
+  Procedure target;
 
   /// The arguments provided to the top-level method.
   Arguments arguments;
 
-  ExtensionTearOff(this.target, this.arguments) {
-    arguments?.parent = this;
+  ExtensionTearOff(this.target, this.arguments)
+      // ignore: unnecessary_null_comparison
+      : assert(arguments != null) {
+    arguments.parent = this;
   }
 
   @override
@@ -3817,22 +4155,24 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    arguments?.accept(v);
+    arguments.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (arguments != null) {
       arguments = v.transform(arguments);
-      arguments?.parent = this;
+      arguments.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (arguments != null) {
-      arguments = v.transformOrRemove(arguments, dummyArguments);
-      arguments?.parent = this;
+      arguments = v.transform(arguments);
+      arguments.parent = this;
     }
   }
 
@@ -3848,10 +4188,15 @@
   Expression right;
   bool isNot;
 
-  EqualsExpression(this.left, this.right, {this.isNot})
-      : assert(isNot != null) {
-    left?.parent = this;
-    right?.parent = this;
+  EqualsExpression(this.left, this.right, {required this.isNot})
+      // ignore: unnecessary_null_comparison
+      : assert(left != null),
+        // ignore: unnecessary_null_comparison
+        assert(right != null),
+        // ignore: unnecessary_null_comparison
+        assert(isNot != null) {
+    left.parent = this;
+    right.parent = this;
   }
 
   @override
@@ -3865,31 +4210,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    left?.accept(v);
-    right?.accept(v);
+    left.accept(v);
+    right.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (left != null) {
       left = v.transform(left);
-      left?.parent = this;
+      left.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (right != null) {
       right = v.transform(right);
-      right?.parent = this;
+      right.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (left != null) {
-      left = v.transformOrRemoveExpression(left);
-      left?.parent = this;
+      left = v.transform(left);
+      left.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (right != null) {
-      right = v.transformOrRemoveExpression(right);
-      right?.parent = this;
+      right = v.transform(right);
+      right.parent = this;
     }
   }
 
@@ -3916,9 +4265,13 @@
   Name binaryName;
   Expression right;
 
-  BinaryExpression(this.left, this.binaryName, this.right) {
-    left?.parent = this;
-    right?.parent = this;
+  BinaryExpression(this.left, this.binaryName, this.right)
+      // ignore: unnecessary_null_comparison
+      : assert(left != null),
+        // ignore: unnecessary_null_comparison
+        assert(right != null) {
+    left.parent = this;
+    right.parent = this;
   }
 
   @override
@@ -3932,31 +4285,35 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    left?.accept(v);
-    right?.accept(v);
+    left.accept(v);
+    right.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (left != null) {
       left = v.transform(left);
-      left?.parent = this;
+      left.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (right != null) {
       right = v.transform(right);
-      right?.parent = this;
+      right.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (left != null) {
-      left = v.transformOrRemoveExpression(left);
-      left?.parent = this;
+      left = v.transform(left);
+      left.parent = this;
     }
+    // ignore: unnecessary_null_comparison
     if (right != null) {
-      right = v.transformOrRemoveExpression(right);
-      right?.parent = this;
+      right = v.transform(right);
+      right.parent = this;
     }
   }
 
@@ -3966,7 +4323,7 @@
   }
 
   @override
-  int get precedence => Precedence.binaryPrecedence[binaryName.text];
+  int get precedence => Precedence.binaryPrecedence[binaryName.text]!;
 
   @override
   void toTextInternal(AstPrinter printer) {
@@ -3981,8 +4338,10 @@
   Name unaryName;
   Expression expression;
 
-  UnaryExpression(this.unaryName, this.expression) {
-    expression?.parent = this;
+  UnaryExpression(this.unaryName, this.expression)
+      // ignore: unnecessary_null_comparison
+      : assert(expression != null) {
+    expression.parent = this;
   }
 
   @override
@@ -3996,22 +4355,24 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    expression?.accept(v);
+    expression.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (expression != null) {
       expression = v.transform(expression);
-      expression?.parent = this;
+      expression.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (expression != null) {
-      expression = v.transformOrRemoveExpression(expression);
-      expression?.parent = this;
+      expression = v.transform(expression);
+      expression.parent = this;
     }
   }
 
@@ -4038,8 +4399,10 @@
 class ParenthesizedExpression extends InternalExpression {
   Expression expression;
 
-  ParenthesizedExpression(this.expression) {
-    expression?.parent = this;
+  ParenthesizedExpression(this.expression)
+      // ignore: unnecessary_null_comparison
+      : assert(expression != null) {
+    expression.parent = this;
   }
 
   @override
@@ -4053,22 +4416,24 @@
 
   @override
   void visitChildren(Visitor<dynamic> v) {
-    expression?.accept(v);
+    expression.accept(v);
   }
 
   @override
   void transformChildren(Transformer v) {
+    // ignore: unnecessary_null_comparison
     if (expression != null) {
       expression = v.transform(expression);
-      expression?.parent = this;
+      expression.parent = this;
     }
   }
 
   @override
   void transformOrRemoveChildren(RemovingTransformer v) {
+    // ignore: unnecessary_null_comparison
     if (expression != null) {
-      expression = v.transformOrRemoveExpression(expression);
-      expression?.parent = this;
+      expression = v.transform(expression);
+      expression.parent = this;
     }
   }
 
diff --git a/pkg/front_end/lib/src/fasta/kernel/kernel_ast_api.dart b/pkg/front_end/lib/src/fasta/kernel/kernel_ast_api.dart
index 06d76b7..775003f 100644
--- a/pkg/front_end/lib/src/fasta/kernel/kernel_ast_api.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/kernel_ast_api.dart
@@ -2,8 +2,6 @@
 // for 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
-
 /// This library exports all API from Kernel's ast.dart that can be used
 /// throughout fasta.
 library fasta.kernel_ast_api;
diff --git a/pkg/front_end/lib/src/fasta/kernel/kernel_builder.dart b/pkg/front_end/lib/src/fasta/kernel/kernel_builder.dart
index 93eed48..3b8d62c 100644
--- a/pkg/front_end/lib/src/fasta/kernel/kernel_builder.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/kernel_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.kernel_builder;
 
 import 'package:kernel/ast.dart'
@@ -37,22 +35,19 @@
       initializers.single is RedirectingInitializer;
 }
 
-List<Combinator> toKernelCombinators(List<fasta.Combinator> fastaCombinators) {
+List<Combinator>? toKernelCombinators(
+    List<fasta.Combinator>? fastaCombinators) {
   if (fastaCombinators == null) {
     // Note: it's safe to return null here as Kernel's LibraryDependency will
     // convert null to an empty list.
     return null;
   }
 
-  List<Combinator> result = new List<Combinator>.filled(
-      fastaCombinators.length, null,
-      growable: true);
-  for (int i = 0; i < fastaCombinators.length; i++) {
+  return new List<Combinator>.generate(fastaCombinators.length, (int i) {
     fasta.Combinator combinator = fastaCombinators[i];
     List<String> nameList = combinator.names.toList();
-    result[i] = combinator.isShow
+    return combinator.isShow
         ? new Combinator.show(nameList)
         : new Combinator.hide(nameList);
-  }
-  return result;
+  }, growable: true);
 }
diff --git a/pkg/front_end/lib/src/fasta/kernel/kernel_constants.dart b/pkg/front_end/lib/src/fasta/kernel/kernel_constants.dart
index 55c93c5..6868aa7 100644
--- a/pkg/front_end/lib/src/fasta/kernel/kernel_constants.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/kernel_constants.dart
@@ -2,13 +2,12 @@
 // for 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
-
 library fasta.kernel_constants;
 
-import 'package:front_end/src/fasta/builder/library_builder.dart';
 import 'package:kernel/ast.dart' show InvalidExpression;
 
+import '../builder/library_builder.dart';
+
 import '../fasta_codes.dart' show LocatedMessage;
 
 import '../loader.dart' show Loader;
@@ -21,9 +20,9 @@
   KernelConstantErrorReporter(this.loader);
 
   @override
-  void report(LocatedMessage message, List<LocatedMessage> context) {
+  void report(LocatedMessage message, List<LocatedMessage>? context) {
     // Try to find library.
-    LibraryBuilder builder = loader.builders[message.uri];
+    LibraryBuilder? builder = loader.builders[message.uri];
     if (builder == null) {
       for (LibraryBuilder candidate in loader.builders.values) {
         if (candidate.fileUri == message.uri) {
@@ -36,7 +35,7 @@
     if (builder == null) {
       // TODO(jensj): Probably a part or something.
       loader.addProblem(message.messageObject, message.charOffset,
-          message.length, message.uri,
+          message.length, message.uri!,
           context: context);
     } else {
       builder.addProblem(message.messageObject, message.charOffset,
diff --git a/pkg/front_end/lib/src/fasta/kernel/kernel_target.dart b/pkg/front_end/lib/src/fasta/kernel/kernel_target.dart
index 3fe1f73..956c6a8 100644
--- a/pkg/front_end/lib/src/fasta/kernel/kernel_target.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/kernel_target.dart
@@ -2,13 +2,8 @@
 // for 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
-
 library fasta.kernel_target;
 
-import 'package:front_end/src/api_prototype/experimental_flags.dart';
-import 'package:front_end/src/fasta/dill/dill_library_builder.dart'
-    show DillLibraryBuilder;
 import 'package:kernel/ast.dart';
 import 'package:kernel/class_hierarchy.dart' show ClassHierarchy;
 import 'package:kernel/clone.dart' show CloneVisitorNotMembers;
@@ -23,6 +18,7 @@
 import 'package:package_config/package_config.dart' hide LanguageVersion;
 
 import '../../api_prototype/file_system.dart' show FileSystem;
+import '../../api_prototype/experimental_flags.dart';
 import '../../base/nnbd_mode.dart';
 import '../builder/builder.dart';
 import '../builder/class_builder.dart';
@@ -44,6 +40,7 @@
 import '../compiler_context.dart' show CompilerContext;
 import '../crash.dart' show withCrashReporting;
 import '../dill/dill_member_builder.dart' show DillMemberBuilder;
+import '../dill/dill_library_builder.dart' show DillLibraryBuilder;
 import '../dill/dill_target.dart' show DillTarget;
 import '../fasta_codes.dart' show LocatedMessage, Message;
 import '../loader.dart' show Loader;
@@ -75,6 +72,7 @@
     show LanguageVersion, SourceLibraryBuilder;
 import '../source/source_loader.dart' show SourceLoader;
 import '../target_implementation.dart' show TargetImplementation;
+import '../type_inference/type_schema.dart';
 import '../uri_translator.dart' show UriTranslator;
 import 'constant_evaluator.dart' as constants
     show
@@ -94,9 +92,9 @@
 
   final DillTarget dillTarget;
 
-  SourceLoader loader;
+  late final SourceLoader loader;
 
-  Component component;
+  Component? component;
 
   // 'dynamic' is always nullable.
   // TODO(johnniwinther): Why isn't this using a FixedTypeBuilder?
@@ -134,7 +132,7 @@
 
   final bool excludeSource = !CompilerContext.current.options.embedSourceText;
 
-  final Map<String, String> environmentDefines =
+  final Map<String, String>? environmentDefines =
       CompilerContext.current.options.environmentDefines;
 
   final bool errorOnUnevaluatedConstant =
@@ -183,11 +181,11 @@
       default:
         // Attempt to reverse-lookup [entryPoint] in package config.
         String asString = "$entryPoint";
-        Package package = uriTranslator.packages.packageOf(entryPoint);
+        Package? package = uriTranslator.packages.packageOf(entryPoint);
         if (package != null) {
           String packageName = package.name;
           Uri packageUri = package.packageUriRoot;
-          if (packageUri?.hasFragment == true) {
+          if (packageUri.hasFragment == true) {
             packageUri = packageUri.removeFragment();
           }
           String prefix = "${packageUri}";
@@ -215,13 +213,13 @@
   LibraryBuilder createLibraryBuilder(
       Uri uri,
       Uri fileUri,
-      Uri packageUri,
+      Uri? packageUri,
       LanguageVersion packageLanguageVersion,
-      SourceLibraryBuilder origin,
-      Library referencesFrom,
-      bool referenceIsPartOwner) {
+      SourceLibraryBuilder? origin,
+      Library? referencesFrom,
+      bool? referenceIsPartOwner) {
     if (dillTarget.isLoaded) {
-      LibraryBuilder builder = dillTarget.loader.builders[uri];
+      LibraryBuilder? builder = dillTarget.loader.builders[uri];
       if (builder != null) {
         if (!builder.isNonNullableByDefault &&
             (loader.nnbdMode == NnbdMode.Strong ||
@@ -306,9 +304,9 @@
   }
 
   @override
-  Future<Component> buildOutlines({CanonicalName nameRoot}) async {
+  Future<Component?> buildOutlines({CanonicalName? nameRoot}) async {
     if (loader.first == null) return null;
-    return withCrashReporting<Component>(() async {
+    return withCrashReporting<Component?>(() async {
       await loader.buildOutlines();
       loader.createTypeInferenceEngine();
       loader.coreLibrary.becomeCoreLibrary();
@@ -345,7 +343,7 @@
       installAllComponentProblems(loader.allComponentProblems);
       loader.allComponentProblems.clear();
       return component;
-    }, () => loader?.currentUriForCrashReporting);
+    }, () => loader.currentUriForCrashReporting);
   }
 
   /// Build the kernel representation of the component loaded by this
@@ -357,9 +355,9 @@
   /// If [verify], run the default kernel verification on the resulting
   /// component.
   @override
-  Future<Component> buildComponent({bool verify: false}) async {
+  Future<Component?> buildComponent({bool verify: false}) async {
     if (loader.first == null) return null;
-    return withCrashReporting<Component>(() async {
+    return withCrashReporting<Component?>(() async {
       ticker.logMs("Building component");
       await loader.buildBodies();
       finishClonedParameters();
@@ -374,23 +372,23 @@
       if (verify) this.verify();
       installAllComponentProblems(loader.allComponentProblems);
       return component;
-    }, () => loader?.currentUriForCrashReporting);
+    }, () => loader.currentUriForCrashReporting);
   }
 
   void installAllComponentProblems(
       List<FormattedMessage> allComponentProblems) {
     if (allComponentProblems.isNotEmpty) {
-      component.problemsAsJson ??= <String>[];
+      component!.problemsAsJson ??= <String>[];
     }
     for (int i = 0; i < allComponentProblems.length; i++) {
       FormattedMessage formattedMessage = allComponentProblems[i];
-      component.problemsAsJson.add(formattedMessage.toJsonString());
+      component!.problemsAsJson!.add(formattedMessage.toJsonString());
     }
   }
 
   /// Creates a component by combining [libraries] with the libraries of
   /// `dillTarget.loader.component`.
-  Component link(List<Library> libraries, {CanonicalName nameRoot}) {
+  Component link(List<Library> libraries, {CanonicalName? nameRoot}) {
     libraries.addAll(dillTarget.loader.libraries);
 
     Map<Uri, Source> uriToSource = new Map<Uri, Source>();
@@ -406,7 +404,7 @@
     Component component = backendTarget.configureComponent(new Component(
         nameRoot: nameRoot, libraries: libraries, uriToSource: uriToSource));
 
-    NonNullableByDefaultCompiledMode compiledMode = null;
+    NonNullableByDefaultCompiledMode? compiledMode = null;
     if (isExperimentEnabledGlobally(ExperimentalFlag.nonNullable)) {
       switch (loader.nnbdMode) {
         case NnbdMode.Weak:
@@ -426,20 +424,21 @@
       compiledMode = NonNullableByDefaultCompiledMode.Invalid;
     }
 
-    Reference mainReference;
+    Reference? mainReference;
 
     if (loader.first != null) {
       // TODO(sigmund): do only for full program
-      Builder declaration = loader.first.exportScope.lookup("main", -1, null);
+      Builder? declaration =
+          loader.first!.exportScope.lookup("main", -1, loader.first!.fileUri);
       if (declaration is AmbiguousBuilder) {
         AmbiguousBuilder problem = declaration;
         declaration = problem.getFirstDeclaration();
       }
       if (declaration is ProcedureBuilder) {
-        mainReference = declaration.actualProcedure?.reference;
+        mainReference = declaration.actualProcedure.reference;
       } else if (declaration is DillMemberBuilder) {
         if (declaration.member is Procedure) {
-          mainReference = declaration.member?.reference;
+          mainReference = declaration.member.reference;
         }
       }
     }
@@ -452,7 +451,7 @@
     return component;
   }
 
-  String _getLibraryNnbdModeError(Component component) {
+  String? _getLibraryNnbdModeError(Component component) {
     if (loader.hasInvalidNnbdModeLibrary) {
       // At least 1 library should be invalid or there should be a mix of strong
       // and weak. For libraries we've just compiled it will be marked as
@@ -547,8 +546,9 @@
                 ..bind(objectClassBuilder);
             }
             if (declaration.isMixinApplication) {
-              cls.mixedInType = declaration.mixedInTypeBuilder.buildMixedInType(
-                  library, declaration.charOffset, declaration.fileUri);
+              cls.mixedInType = declaration.mixedInTypeBuilder!
+                  .buildMixedInType(
+                      library, declaration.charOffset, declaration.fileUri);
             }
           }
         }
@@ -587,7 +587,7 @@
     _delayedParameterTypes.clear();
   }
 
-  ClassBuilder get objectClassBuilder => objectType.declaration;
+  ClassBuilder get objectClassBuilder => objectType.declaration as ClassBuilder;
 
   Class get objectClass => objectClassBuilder.cls;
 
@@ -602,10 +602,11 @@
       if (proc.isFactory) return;
     }
 
-    IndexedClass indexedClass = builder.referencesFromIndexed;
-    Constructor referenceFrom;
+    IndexedClass? indexedClass = builder.referencesFromIndexed;
+    Constructor? referenceFrom;
     if (indexedClass != null) {
-      referenceFrom = indexedClass.lookupConstructor(new Name(""));
+      referenceFrom =
+          indexedClass.lookupConstructor(new Name("")) as Constructor?;
     }
 
     /// From [Dart Programming Language Specification, 4th Edition](
@@ -636,8 +637,8 @@
     /// >that is accessible to LM , C has an implicitly declared constructor
     /// >named q'i = [C/S]qi of the form q'i(ai1,...,aiki) :
     /// >super(ai1,...,aiki);.
-    TypeBuilder type = builder.supertypeBuilder;
-    TypeDeclarationBuilder supertype;
+    TypeBuilder? type = builder.supertypeBuilder;
+    TypeDeclarationBuilder? supertype;
     if (type is NamedTypeBuilder) {
       supertype = type.declaration;
     } else {
@@ -656,27 +657,28 @@
       installForwardingConstructors(supertype);
     }
 
-    IndexedClass indexedClass = builder.referencesFromIndexed;
-    Constructor referenceFrom;
+    IndexedClass? indexedClass = builder.referencesFromIndexed;
+    Constructor? referenceFrom;
     if (indexedClass != null) {
-      referenceFrom = indexedClass.lookupConstructor(new Name(""));
+      referenceFrom =
+          indexedClass.lookupConstructor(new Name("")) as Constructor?;
     }
 
     if (supertype is ClassBuilder) {
       ClassBuilder superclassBuilder = supertype;
       bool isConstructorAdded = false;
-      Map<TypeParameter, DartType> substitutionMap;
+      Map<TypeParameter, DartType>? substitutionMap;
 
       void addSyntheticConstructor(String name, MemberBuilder memberBuilder) {
         if (memberBuilder.member is Constructor) {
           substitutionMap ??= builder.getSubstitutionMap(superclassBuilder.cls);
-          Constructor referenceFrom = indexedClass
-              ?.lookupConstructor(new Name(name, indexedClass.library));
+          Constructor? referenceFrom = indexedClass?.lookupConstructor(
+              new Name(name, indexedClass.library)) as Constructor?;
           builder.addSyntheticConstructor(_makeMixinApplicationConstructor(
               builder,
               builder.cls.mixin,
-              memberBuilder,
-              substitutionMap,
+              memberBuilder as MemberBuilderImpl,
+              substitutionMap!,
               referenceFrom));
           isConstructorAdded = true;
         }
@@ -707,11 +709,11 @@
       Class mixin,
       MemberBuilderImpl memberBuilder,
       Map<TypeParameter, DartType> substitutionMap,
-      Constructor referenceFrom) {
+      Constructor? referenceFrom) {
     VariableDeclaration copyFormal(VariableDeclaration formal) {
       VariableDeclaration copy = new VariableDeclaration(formal.name,
           isFinal: formal.isFinal, isConst: formal.isConst);
-      if (formal.type != null) {
+      if (formal.type is! UnknownType) {
         copy.type = substitute(formal.type, substitutionMap);
       } else {
         _delayedParameterTypes
@@ -721,7 +723,7 @@
     }
 
     Class cls = classBuilder.cls;
-    Constructor constructor = memberBuilder.member;
+    Constructor constructor = memberBuilder.member as Constructor;
     bool isConst = constructor.isConst;
     if (isConst && mixin.fields.isNotEmpty) {
       for (Field field in mixin.fields) {
@@ -745,7 +747,7 @@
       VariableDeclaration clone = copyFormal(formal);
       namedParameters.add(clone);
       named.add(new NamedExpression(
-          formal.name, new VariableGet(namedParameters.last)));
+          formal.name!, new VariableGet(namedParameters.last)));
     }
     FunctionNode function = new FunctionNode(new EmptyStatement(),
         positionalParameters: positionalParameters,
@@ -793,7 +795,7 @@
   }
 
   SyntheticConstructorBuilder _makeDefaultConstructor(
-      SourceClassBuilder classBuilder, Constructor referenceFrom) {
+      SourceClassBuilder classBuilder, Constructor? referenceFrom) {
     Class enclosingClass = classBuilder.cls;
     return new SyntheticConstructorBuilder(
         classBuilder,
@@ -821,15 +823,16 @@
   }
 
   void setupTopAndBottomTypes() {
-    objectType
-        .bind(loader.coreLibrary.lookupLocalMember("Object", required: true));
-    dynamicType
-        .bind(loader.coreLibrary.lookupLocalMember("dynamic", required: true));
-    ClassBuilder nullClassBuilder =
-        loader.coreLibrary.lookupLocalMember("Null", required: true);
+    objectType.bind(loader.coreLibrary
+        .lookupLocalMember("Object", required: true) as TypeDeclarationBuilder);
+    dynamicType.bind(
+        loader.coreLibrary.lookupLocalMember("dynamic", required: true)
+            as TypeDeclarationBuilder);
+    ClassBuilder nullClassBuilder = loader.coreLibrary
+        .lookupLocalMember("Null", required: true) as ClassBuilder;
     nullType.bind(nullClassBuilder..isNullClass = true);
-    bottomType
-        .bind(loader.coreLibrary.lookupLocalMember("Never", required: true));
+    bottomType.bind(loader.coreLibrary
+        .lookupLocalMember("Never", required: true) as TypeDeclarationBuilder);
   }
 
   void computeCoreTypes() {
@@ -842,7 +845,7 @@
       ...backendTarget.extraIndexedLibraries
     ]) {
       Uri uri = Uri.parse(platformLibrary);
-      LibraryBuilder libraryBuilder = loader.builders[uri];
+      LibraryBuilder? libraryBuilder = loader.builders[uri];
       if (libraryBuilder == null) {
         // TODO(ahe): This is working around a bug in kernel_driver_test or
         // kernel_driver.
@@ -914,7 +917,7 @@
         FieldBuilder earliest = fieldBuilder;
         Builder current = fieldBuilder;
         while (current.next != null) {
-          current = current.next;
+          current = current.next!;
           if (current is FieldBuilder && !fieldBuilder.hasInitializer) {
             earliest = current;
           }
@@ -923,7 +926,7 @@
       }
     });
 
-    Constructor superTarget;
+    Constructor? superTarget;
     // In the underlying Kernel IR the patches are already applied, so
     // cls.constructors should contain both constructors from the original
     // declaration and the constructors from the patch.  The assert checks that
@@ -974,7 +977,7 @@
             }
             builder.addProblem(
                 templateSuperclassHasNoDefaultConstructor
-                    .withArguments(cls.superclass.name),
+                    .withArguments(cls.superclass!.name),
                 offset,
                 noLength);
             initializer = new InvalidInitializer();
@@ -990,8 +993,8 @@
           /// >If a generative constructor c is not a redirecting constructor
           /// >and no body is provided, then c implicitly has an empty body {}.
           /// We use an empty statement instead.
-          constructor.function.body = new EmptyStatement();
-          constructor.function.body.parent = constructor.function;
+          constructor.function.body = new EmptyStatement()
+            ..parent = constructor.function;
         }
 
         if (constructor.isConst && nonFinalFields.isNotEmpty) {
@@ -999,7 +1002,7 @@
               constructor.fileOffset, noLength,
               context: nonFinalFields
                   .map((field) => messageConstConstructorNonFinalFieldCause
-                      .withLocation(field.fileUri, field.charOffset, noLength))
+                      .withLocation(field.fileUri!, field.charOffset, noLength))
                   .toList());
           nonFinalFields.clear();
         }
@@ -1022,7 +1025,7 @@
 
     Map<ConstructorBuilder, Set<FieldBuilder>> constructorInitializedFields =
         new Map<ConstructorBuilder, Set<FieldBuilder>>.identity();
-    Set<FieldBuilder> initializedFields = null;
+    Set<FieldBuilder>? initializedFields = null;
 
     builder.forEachDeclaredConstructor(
         (String name, ConstructorBuilder constructorBuilder) {
@@ -1033,7 +1036,7 @@
       // iterate until that last element.
       ConstructorBuilder earliest = constructorBuilder;
       while (earliest.next != null) {
-        earliest = earliest.next;
+        earliest = earliest.next as ConstructorBuilder;
       }
 
       bool isRedirecting = false;
@@ -1053,7 +1056,7 @@
     // set their initializer to `null`.
     for (FieldBuilder fieldBuilder in uninitializedFields) {
       if (initializedFields == null ||
-          !initializedFields.contains(fieldBuilder)) {
+          !initializedFields!.contains(fieldBuilder)) {
         bool uninitializedFinalOrNonNullableFieldIsError =
             cls.enclosingLibrary.isNonNullableByDefault ||
                 (cls.constructors.isNotEmpty || cls.isMixinDeclaration);
@@ -1061,7 +1064,7 @@
           if (fieldBuilder.isFinal &&
               uninitializedFinalOrNonNullableFieldIsError) {
             String uri = '${fieldBuilder.library.importUri}';
-            String file = fieldBuilder.fileUri.pathSegments.last;
+            String file = fieldBuilder.fileUri!.pathSegments.last;
             if (uri == 'dart:html' ||
                 uri == 'dart:svg' ||
                 uri == 'dart:_native_typed_data' ||
@@ -1100,7 +1103,7 @@
     constructorInitializedFields.forEach((ConstructorBuilder constructorBuilder,
         Set<FieldBuilder> fieldBuilders) {
       for (FieldBuilder fieldBuilder
-          in initializedFields.difference(fieldBuilders)) {
+          in initializedFields!.difference(fieldBuilders)) {
         if (!fieldBuilder.hasInitializer && !fieldBuilder.isLate) {
           FieldInitializer initializer =
               new FieldInitializer(fieldBuilder.field, new NullLiteral())
@@ -1117,7 +1120,7 @@
                 context: [
                   templateMissingImplementationCause
                       .withArguments(fieldBuilder.name)
-                      .withLocation(fieldBuilder.fileUri,
+                      .withLocation(fieldBuilder.fileUri!,
                           fieldBuilder.charOffset, fieldBuilder.name.length)
                 ]);
           } else if (fieldBuilder.field.type is! InvalidType &&
@@ -1135,7 +1138,7 @@
                   context: [
                     templateMissingImplementationCause
                         .withArguments(fieldBuilder.name)
-                        .withLocation(fieldBuilder.fileUri,
+                        .withLocation(fieldBuilder.fileUri!,
                             fieldBuilder.charOffset, fieldBuilder.name.length)
                   ]);
             }
@@ -1144,9 +1147,9 @@
       }
     });
 
-    Set<Field> initializedFieldsKernel = null;
+    Set<Field>? initializedFieldsKernel = null;
     if (initializedFields != null) {
-      for (FieldBuilder fieldBuilder in initializedFields) {
+      for (FieldBuilder fieldBuilder in initializedFields!) {
         (initializedFieldsKernel ??= new Set<Field>.identity())
             .add(fieldBuilder.field);
       }
@@ -1191,7 +1194,7 @@
   /// libraries for the first time.
   void runBuildTransformations() {
     backendTarget.performPreConstantEvaluationTransformations(
-        component,
+        component!,
         loader.coreTypes,
         loader.libraries,
         new KernelDiagnosticReporter(loader),
@@ -1220,10 +1223,11 @@
     ticker.logMs("Evaluated constants");
 
     coverage.constructorCoverage.forEach((Uri fileUri, Set<Reference> value) {
-      Source source = uriToSource[fileUri];
+      Source? source = uriToSource[fileUri];
+      // ignore: unnecessary_null_comparison
       if (source != null && fileUri != null) {
         source.constantCoverageConstructors ??= new Set<Reference>();
-        source.constantCoverageConstructors.addAll(value);
+        source.constantCoverageConstructors!.addAll(value);
       }
     });
     ticker.logMs("Added constant coverage");
@@ -1231,14 +1235,14 @@
     if (loader.target.context.options
         .isExperimentEnabledGlobally(ExperimentalFlag.valueClass)) {
       valueClass.transformComponent(
-          component, loader.coreTypes, loader.hierarchy, environment,
+          component!, loader.coreTypes, loader.hierarchy, environment,
           useNewMethodInvocationEncoding:
               backendTarget.supportsNewMethodInvocationEncoding);
       ticker.logMs("Lowered value classes");
     }
 
     backendTarget.performModularTransformationsOnLibraries(
-        component,
+        component!,
         loader.coreTypes,
         loader.hierarchy,
         loader.libraries,
@@ -1249,7 +1253,7 @@
         changedStructureNotifier: changedStructureNotifier);
   }
 
-  ChangedStructureNotifier get changedStructureNotifier => null;
+  ChangedStructureNotifier? get changedStructureNotifier => null;
 
   void runProcedureTransformations(Procedure procedure) {
     TypeEnvironment environment =
@@ -1308,15 +1312,15 @@
 
   void verify() {
     // TODO(ahe): How to handle errors.
-    verifyComponent(component, context.options.target,
+    verifyComponent(component!, context.options.target,
         skipPlatform: context.options.skipPlatformVerification);
     ClassHierarchy hierarchy =
-        new ClassHierarchy(component, new CoreTypes(component),
+        new ClassHierarchy(component!, new CoreTypes(component!),
             onAmbiguousSupertypes: (Class cls, Supertype a, Supertype b) {
       // An error has already been reported.
     });
     verifyGetStaticType(
-        new TypeEnvironment(loader.coreTypes, hierarchy), component,
+        new TypeEnvironment(loader.coreTypes, hierarchy), component!,
         skipPlatform: context.options.skipPlatformVerification);
     ticker.logMs("Verified component");
   }
@@ -1332,18 +1336,22 @@
   @override
   void readPatchFiles(SourceLibraryBuilder library) {
     assert(library.importUri.scheme == "dart");
-    List<Uri> patches = uriTranslator.getDartPatches(library.importUri.path);
+    List<Uri>? patches = uriTranslator.getDartPatches(library.importUri.path);
     if (patches != null) {
-      SourceLibraryBuilder first;
+      SourceLibraryBuilder? first;
       for (Uri patch in patches) {
         if (first == null) {
           first = library.loader.read(patch, -1,
-              fileUri: patch, origin: library, accessor: library);
+              fileUri: patch,
+              origin: library,
+              accessor: library) as SourceLibraryBuilder;
         } else {
           // If there's more than one patch file, it's interpreted as a part of
           // the patch library.
           SourceLibraryBuilder part = library.loader.read(patch, -1,
-              origin: library, fileUri: patch, accessor: library);
+              origin: library,
+              fileUri: patch,
+              accessor: library) as SourceLibraryBuilder;
           first.parts.add(part);
           first.partOffsets.add(-1);
           part.partOfUri = first.importUri;
@@ -1360,8 +1368,8 @@
 /// Looks for a constructor call that matches `super()` from a constructor in
 /// [cls]. Such a constructor may have optional arguments, but no required
 /// arguments.
-Constructor defaultSuperConstructor(Class cls) {
-  Class superclass = cls.superclass;
+Constructor? defaultSuperConstructor(Class cls) {
+  Class? superclass = cls.superclass;
   if (superclass != null) {
     for (Constructor constructor in superclass.constructors) {
       if (constructor.name.text.isEmpty) {
@@ -1381,7 +1389,7 @@
   KernelDiagnosticReporter(this.loader);
 
   void report(Message message, int charOffset, int length, Uri fileUri,
-      {List<LocatedMessage> context}) {
+      {List<LocatedMessage>? context}) {
     loader.addProblem(message, charOffset, noLength, fileUri, context: context);
   }
 }
@@ -1399,6 +1407,7 @@
   DelayedParameterType(this.source, this.target, this.substitutionMap);
 
   void updateType() {
+    // ignore: unnecessary_null_comparison
     assert(source.type != null, "No type computed for $source.");
     target.type = substitute(source.type, substitutionMap);
   }
@@ -1416,15 +1425,15 @@
     // default values, but Fasta is currently allowing it, and the VM
     // accepts it. If it isn't legal, the we can speed this up by using a
     // single cloner without substitution.
-    CloneVisitorNotMembers cloner;
+    CloneVisitorNotMembers? cloner;
 
     void cloneInitializer(VariableDeclaration originalParameter,
         VariableDeclaration clonedParameter) {
       if (originalParameter.initializer != null) {
         cloner ??=
             new CloneVisitorNotMembers(typeSubstitution: _typeSubstitution);
-        clonedParameter.initializer = cloner
-            .clone(originalParameter.initializer)
+        clonedParameter.initializer = cloner!
+            .clone(originalParameter.initializer!)
               ..parent = clonedParameter;
       }
     }
diff --git a/pkg/front_end/lib/src/fasta/kernel/late_lowering.dart b/pkg/front_end/lib/src/fasta/kernel/late_lowering.dart
index a7ce45a..8a9c80c 100644
--- a/pkg/front_end/lib/src/fasta/kernel/late_lowering.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/late_lowering.dart
@@ -2,8 +2,6 @@
 // for 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 'package:kernel/ast.dart';
 import 'package:kernel/core_types.dart';
 
@@ -29,12 +27,13 @@
     DartType type,
     Expression initializer,
     bool useNewMethodInvocationEncoding,
-    {Expression createVariableRead(bool useNewMethodInvocationEncoding,
+    {required Expression createVariableRead(bool useNewMethodInvocationEncoding,
         {bool needsPromotion}),
-    Expression createVariableWrite(Expression value),
-    Expression createIsSetRead(),
-    Expression createIsSetWrite(Expression value),
-    IsSetEncoding isSetEncoding}) {
+    required Expression createVariableWrite(Expression value),
+    required Expression createIsSetRead(),
+    required Expression createIsSetWrite(Expression value),
+    required IsSetEncoding isSetEncoding}) {
+  // ignore: unnecessary_null_comparison
   assert(isSetEncoding != null);
   switch (isSetEncoding) {
     case IsSetEncoding.useIsSetField:
@@ -129,7 +128,6 @@
         ..fileOffset = fileOffset)
         ..fileOffset = fileOffset;
   }
-  throw new UnsupportedError("Unexpected IsSetEncoding $isSetEncoding");
 }
 
 /// Creates the body for the synthesized getter used to encode the lowering
@@ -141,13 +139,14 @@
     DartType type,
     Expression initializer,
     bool useNewMethodInvocationEncoding,
-    {Expression createVariableRead(bool useNewMethodInvocationEncoding,
+    {required Expression createVariableRead(bool useNewMethodInvocationEncoding,
         {bool needsPromotion}),
-    Expression createVariableWrite(Expression value),
-    Expression createIsSetRead(),
-    Expression createIsSetWrite(Expression value),
-    IsSetEncoding isSetEncoding,
-    bool forField}) {
+    required Expression createVariableWrite(Expression value),
+    required Expression createIsSetRead(),
+    required Expression createIsSetWrite(Expression value),
+    required IsSetEncoding isSetEncoding,
+    required bool forField}) {
+  // ignore: unnecessary_null_comparison
   assert(forField != null);
   Constructor constructor = forField
       ? coreTypes.lateInitializationFieldAssignedDuringInitializationConstructor
@@ -313,7 +312,6 @@
         ..fileOffset = fileOffset)
         ..fileOffset = fileOffset;
   }
-  throw new UnsupportedError("Unexpected IsSetEncoding $isSetEncoding");
 }
 
 /// Creates the body for the synthesized getter used to encode the lowering
@@ -324,12 +322,14 @@
     String name,
     DartType type,
     bool useNewMethodInvocationEncoding,
-    {Expression createVariableRead(bool useNewMethodInvocationEncoding,
+    {required Expression createVariableRead(bool useNewMethodInvocationEncoding,
         {bool needsPromotion}),
-    Expression createIsSetRead(),
-    IsSetEncoding isSetEncoding,
-    bool forField}) {
+    required Expression createIsSetRead(),
+    required IsSetEncoding isSetEncoding,
+    required bool forField}) {
+  // ignore: unnecessary_null_comparison
   assert(forField != null);
+  // ignore: unnecessary_null_comparison
   assert(isSetEncoding != null);
   Expression exception = new Throw(
       new ConstructorInvocation(
@@ -413,17 +413,17 @@
         ..fileOffset = fileOffset)
         ..fileOffset = fileOffset;
   }
-  throw new UnsupportedError("Unexpected IsSetEncoding $isSetEncoding");
 }
 
 /// Creates the body for the synthesized setter used to encode the lowering
 /// of a non-final late field or local.
 Statement createSetterBody(CoreTypes coreTypes, int fileOffset, String name,
     VariableDeclaration parameter, DartType type,
-    {bool shouldReturnValue,
-    Expression createVariableWrite(Expression value),
-    Expression createIsSetWrite(Expression value),
-    IsSetEncoding isSetEncoding}) {
+    {required bool shouldReturnValue,
+    required Expression createVariableWrite(Expression value),
+    required Expression createIsSetWrite(Expression value),
+    required IsSetEncoding isSetEncoding}) {
+  // ignore: unnecessary_null_comparison
   assert(isSetEncoding != null);
   Statement createReturn(Expression value) {
     if (shouldReturnValue) {
@@ -460,7 +460,6 @@
       //
       return assignment;
   }
-  throw new UnsupportedError("Unexpected IsSetEncoding $isSetEncoding");
 }
 
 /// Creates the body for the synthesized setter used to encode the lowering
@@ -472,14 +471,16 @@
     VariableDeclaration parameter,
     DartType type,
     bool useNewMethodInvocationEncoding,
-    {bool shouldReturnValue,
-    Expression createVariableRead(bool useNewMethodInvocationEncoding),
-    Expression createVariableWrite(Expression value),
-    Expression createIsSetRead(),
-    Expression createIsSetWrite(Expression value),
-    IsSetEncoding isSetEncoding,
-    bool forField}) {
+    {required bool shouldReturnValue,
+    required Expression createVariableRead(bool useNewMethodInvocationEncoding),
+    required Expression createVariableWrite(Expression value),
+    required Expression createIsSetRead(),
+    required Expression createIsSetWrite(Expression value),
+    required IsSetEncoding isSetEncoding,
+    required bool forField}) {
+  // ignore: unnecessary_null_comparison
   assert(forField != null);
+  // ignore: unnecessary_null_comparison
   assert(isSetEncoding != null);
   Expression exception = new Throw(
       new ConstructorInvocation(
@@ -574,7 +575,6 @@
         new ExpressionStatement(exception)..fileOffset = fileOffset,
       )..fileOffset = fileOffset;
   }
-  throw new UnsupportedError("Unexpected IsSetEncoding $isSetEncoding");
 }
 
 /// Strategies for encoding whether a late field/local has been initialized.
@@ -648,7 +648,6 @@
           ? IsSetEncoding.useSentinel
           : IsSetEncoding.useNull;
   }
-  throw new UnsupportedError("Unexpected IsSetStrategy $isSetStrategy");
 }
 
 /// Returns the name used for the variable that holds the value of a late
diff --git a/pkg/front_end/lib/src/fasta/kernel/load_library_builder.dart b/pkg/front_end/lib/src/fasta/kernel/load_library_builder.dart
index 3639f4a..0c76efe 100644
--- a/pkg/front_end/lib/src/fasta/kernel/load_library_builder.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/load_library_builder.dart
@@ -2,8 +2,6 @@
 // for 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 'package:kernel/ast.dart'
     show
         Arguments,
@@ -13,7 +11,6 @@
         InterfaceType,
         LibraryDependency,
         LoadLibrary,
-        Member,
         Name,
         Procedure,
         ProcedureKind,
@@ -37,25 +34,25 @@
 
   /// Synthetic static method to represent the tear-off of 'loadLibrary'.  If
   /// null, no tear-offs were seen in the code and no method is generated.
-  Member tearoff;
+  Procedure? tearoff;
 
   LoadLibraryBuilder(this.parent, this.importDependency, this.charOffset);
 
   Uri get fileUri => parent.fileUri;
 
   LoadLibrary createLoadLibrary(
-      int charOffset, Forest forest, Arguments arguments) {
+      int charOffset, Forest forest, Arguments? arguments) {
     return forest.createLoadLibrary(charOffset, importDependency, arguments);
   }
 
   Procedure createTearoffMethod(Forest forest) {
-    if (tearoff != null) return tearoff;
+    if (tearoff != null) return tearoff!;
     LoadLibrary expression = createLoadLibrary(charOffset, forest, null);
-    String prefix = expression.import.name;
+    String prefix = expression.import.name!;
     Name name = new Name('_#loadLibrary_$prefix', parent.library);
-    Reference reference =
+    Reference? reference =
         parent.referencesFromIndexed?.lookupGetterReference(name);
-    tearoff = new Procedure(
+    return tearoff = new Procedure(
         name,
         ProcedureKind.Method,
         new FunctionNode(new ReturnStatement(expression),
@@ -67,7 +64,6 @@
       ..startFileOffset = charOffset
       ..fileOffset = charOffset
       ..isNonNullableByDefault = parent.isNonNullableByDefault;
-    return tearoff;
   }
 
   @override
diff --git a/pkg/front_end/lib/src/fasta/kernel/redirecting_factory_body.dart b/pkg/front_end/lib/src/fasta/kernel/redirecting_factory_body.dart
index cdbabbe..265cee2 100644
--- a/pkg/front_end/lib/src/fasta/kernel/redirecting_factory_body.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/redirecting_factory_body.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.redirecting_factory_body;
 
 import 'package:kernel/ast.dart';
@@ -35,31 +33,31 @@
 
 class RedirectingFactoryBody extends ExpressionStatement {
   RedirectingFactoryBody.internal(Expression value,
-      [List<DartType> typeArguments])
+      [List<DartType>? typeArguments])
       : super(new Let(new VariableDeclaration(letName, initializer: value),
             encodeTypeArguments(typeArguments)));
 
-  RedirectingFactoryBody(Member target, [List<DartType> typeArguments])
+  RedirectingFactoryBody(Member target, [List<DartType>? typeArguments])
       : this.internal(new StaticGet(target), typeArguments);
 
   RedirectingFactoryBody.unresolved(String name)
       : this.internal(new StringLiteral(name));
 
-  Member get target {
+  Member? get target {
     dynamic value = getValue(expression);
     return value is StaticGet ? value.target : null;
   }
 
-  String get unresolvedName {
+  String? get unresolvedName {
     dynamic value = getValue(expression);
     return value is StringLiteral ? value.value : null;
   }
 
   bool get isUnresolved => unresolvedName != null;
 
-  List<DartType> get typeArguments {
+  List<DartType>? get typeArguments {
     if (expression is Let) {
-      Let bodyExpression = expression;
+      Let bodyExpression = expression as Let;
       if (bodyExpression.variable.name == letName) {
         return decodeTypeArguments(bodyExpression.body);
       }
@@ -82,10 +80,10 @@
     // dill files. See `ClassBuilder.addRedirectingConstructor` in
     // [kernel_class_builder.dart](kernel_class_builder.dart).
     FunctionNode function = factory.function;
-    ExpressionStatement statement = function.body;
-    List<DartType> typeArguments;
+    ExpressionStatement statement = function.body as ExpressionStatement;
+    List<DartType>? typeArguments;
     if (statement.expression is Let) {
-      Let expression = statement.expression;
+      Let expression = statement.expression as Let;
       typeArguments = decodeTypeArguments(expression.body);
     }
     function.body = new RedirectingFactoryBody.internal(
@@ -124,7 +122,7 @@
     }
   }
 
-  static Expression encodeTypeArguments(List<DartType> typeArguments) {
+  static Expression encodeTypeArguments(List<DartType>? typeArguments) {
     Expression result = new InvalidExpression(null);
     if (typeArguments == null) {
       return result;
@@ -138,7 +136,7 @@
     return result;
   }
 
-  static List<DartType> decodeTypeArguments(Expression encoded) {
+  static List<DartType>? decodeTypeArguments(Expression encoded) {
     if (encoded is InvalidExpression) {
       return null;
     }
@@ -162,13 +160,15 @@
   }
 }
 
-bool isRedirectingFactory(Member member, {EnsureLoaded helper}) {
+bool isRedirectingFactory(Member? member, {EnsureLoaded? helper}) {
   assert(helper == null || helper.isLoaded(member));
   return member is Procedure && member.function.body is RedirectingFactoryBody;
 }
 
-RedirectingFactoryBody getRedirectingFactoryBody(Member member) {
-  return isRedirectingFactory(member) ? member.function.body : null;
+RedirectingFactoryBody? getRedirectingFactoryBody(Member? member) {
+  return isRedirectingFactory(member)
+      ? member!.function!.body as RedirectingFactoryBody
+      : null;
 }
 
 class RedirectionTarget {
@@ -178,7 +178,7 @@
   RedirectionTarget(this.target, this.typeArguments);
 }
 
-RedirectionTarget getRedirectionTarget(Procedure member, EnsureLoaded helper) {
+RedirectionTarget? getRedirectionTarget(Procedure member, EnsureLoaded helper) {
   List<DartType> typeArguments = <DartType>[]..length =
       member.function.typeParameters.length;
   for (int i = 0; i < typeArguments.length; i++) {
@@ -190,23 +190,23 @@
   // (https://en.wikipedia.org/wiki/Cycle_detection#Tortoise_and_hare) to
   // handle cycles.
   Member tortoise = member;
-  RedirectingFactoryBody tortoiseBody = getRedirectingFactoryBody(tortoise);
-  Member hare = tortoiseBody?.target;
+  RedirectingFactoryBody? tortoiseBody = getRedirectingFactoryBody(tortoise);
+  Member? hare = tortoiseBody?.target;
   helper.ensureLoaded(hare);
-  RedirectingFactoryBody hareBody = getRedirectingFactoryBody(hare);
+  RedirectingFactoryBody? hareBody = getRedirectingFactoryBody(hare);
   while (tortoise != hare) {
     if (tortoiseBody?.isUnresolved ?? true) {
       return new RedirectionTarget(tortoise, typeArguments);
     }
-    Member nextTortoise = tortoiseBody.target;
+    Member nextTortoise = tortoiseBody!.target!;
     helper.ensureLoaded(nextTortoise);
-    List<DartType> nextTypeArguments = tortoiseBody.typeArguments;
+    List<DartType>? nextTypeArguments = tortoiseBody.typeArguments;
     if (nextTypeArguments == null) {
       nextTypeArguments = <DartType>[];
     }
 
-    Substitution sub =
-        Substitution.fromPairs(tortoise.function.typeParameters, typeArguments);
+    Substitution sub = Substitution.fromPairs(
+        tortoise.function!.typeParameters, typeArguments);
     typeArguments = <DartType>[]..length = nextTypeArguments.length;
     for (int i = 0; i < typeArguments.length; i++) {
       typeArguments[i] = sub.substituteType(nextTypeArguments[i]);
diff --git a/pkg/front_end/lib/src/fasta/kernel/transform_collections.dart b/pkg/front_end/lib/src/fasta/kernel/transform_collections.dart
index a04c1ae..af26d1b 100644
--- a/pkg/front_end/lib/src/fasta/kernel/transform_collections.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/transform_collections.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.transform_collections;
 
 import 'package:kernel/ast.dart';
@@ -38,69 +36,81 @@
   final SourceLoader _loader;
   final TypeEnvironment _typeEnvironment;
   final Procedure _listAdd;
-  FunctionType _listAddFunctionType;
+  late final FunctionType _listAddFunctionType;
   final Procedure _listAddAll;
-  FunctionType _listAddAllFunctionType;
+  late final FunctionType _listAddAllFunctionType;
   final Procedure _listOf;
   final Procedure _setFactory;
   final Procedure _setAdd;
-  FunctionType _setAddFunctionType;
+  late final FunctionType _setAddFunctionType;
   final Procedure _setAddAll;
-  FunctionType _setAddAllFunctionType;
+  late final FunctionType _setAddAllFunctionType;
   final Procedure _setOf;
   final Procedure _objectEquals;
   final Procedure _mapEntries;
   final Procedure _mapPut;
-  FunctionType _mapPutFunctionType;
+  late final FunctionType _mapPutFunctionType;
   final Class _mapEntryClass;
   final Field _mapEntryKey;
   final Field _mapEntryValue;
-  final SourceLoaderDataForTesting _dataForTesting;
+  final SourceLoaderDataForTesting? _dataForTesting;
   final bool useNewMethodInvocationEncoding;
 
   /// Library that contains the transformed nodes.
   ///
   /// The transformation of the nodes is affected by the NNBD opt-in status of
   /// the library.
-  Library _currentLibrary;
+  Library? _currentLibrary;
 
   static Procedure _findSetFactory(CoreTypes coreTypes, String name) {
-    Procedure factory = coreTypes.index.getMember('dart:core', 'Set', name);
-    RedirectingFactoryBody body = factory?.function?.body;
-    return body?.target;
+    Procedure factory = coreTypes.index.getProcedure('dart:core', 'Set', name);
+    RedirectingFactoryBody body =
+        factory.function.body as RedirectingFactoryBody;
+    return body.target as Procedure;
   }
 
   CollectionTransformer(this._loader)
       : _typeEnvironment = _loader.typeInferenceEngine.typeSchemaEnvironment,
         _listAdd =
-            _loader.coreTypes.index.getMember('dart:core', 'List', 'add'),
+            _loader.coreTypes.index.getProcedure('dart:core', 'List', 'add'),
         _listAddAll =
-            _loader.coreTypes.index.getMember('dart:core', 'List', 'addAll'),
-        _listOf = _loader.coreTypes.index.getMember('dart:core', 'List', 'of'),
+            _loader.coreTypes.index.getProcedure('dart:core', 'List', 'addAll'),
+        _listOf =
+            _loader.coreTypes.index.getProcedure('dart:core', 'List', 'of'),
         _setFactory = _findSetFactory(_loader.coreTypes, ''),
-        _setAdd = _loader.coreTypes.index.getMember('dart:core', 'Set', 'add'),
+        _setAdd =
+            _loader.coreTypes.index.getProcedure('dart:core', 'Set', 'add'),
         _setAddAll =
-            _loader.coreTypes.index.getMember('dart:core', 'Set', 'addAll'),
+            _loader.coreTypes.index.getProcedure('dart:core', 'Set', 'addAll'),
         _setOf = _findSetFactory(_loader.coreTypes, 'of'),
         _objectEquals =
-            _loader.coreTypes.index.getMember('dart:core', 'Object', '=='),
+            _loader.coreTypes.index.getProcedure('dart:core', 'Object', '=='),
         _mapEntries = _loader.coreTypes.index
-            .getMember('dart:core', 'Map', 'get:entries'),
-        _mapPut = _loader.coreTypes.index.getMember('dart:core', 'Map', '[]='),
+            .getProcedure('dart:core', 'Map', 'get:entries'),
+        _mapPut =
+            _loader.coreTypes.index.getProcedure('dart:core', 'Map', '[]='),
         _mapEntryClass =
             _loader.coreTypes.index.getClass('dart:core', 'MapEntry'),
         _mapEntryKey =
-            _loader.coreTypes.index.getMember('dart:core', 'MapEntry', 'key'),
+            _loader.coreTypes.index.getField('dart:core', 'MapEntry', 'key'),
         _mapEntryValue =
-            _loader.coreTypes.index.getMember('dart:core', 'MapEntry', 'value'),
+            _loader.coreTypes.index.getField('dart:core', 'MapEntry', 'value'),
         _dataForTesting = _loader.dataForTesting,
         useNewMethodInvocationEncoding =
             _loader.target.backendTarget.supportsNewMethodInvocationEncoding {
-    _listAddFunctionType = _listAdd.getterType;
-    _listAddAllFunctionType = _listAddAll.getterType;
-    _setAddFunctionType = _setAdd.getterType;
-    _setAddAllFunctionType = _setAddAll.getterType;
-    _mapPutFunctionType = _mapPut.getterType;
+    _listAddFunctionType = _listAdd.getterType as FunctionType;
+    _listAddAllFunctionType = _listAddAll.getterType as FunctionType;
+    _setAddFunctionType = _setAdd.getterType as FunctionType;
+    _setAddAllFunctionType = _setAddAll.getterType as FunctionType;
+    _mapPutFunctionType = _mapPut.getterType as FunctionType;
+  }
+
+  T? _transformNullable<T extends TreeNode>(T? node) {
+    if (node == null) {
+      return null;
+    } else {
+      return transform(node);
+    }
   }
 
   TreeNode _translateListOrSet(
@@ -110,24 +120,24 @@
     int index = 0;
     for (; index < elements.length; ++index) {
       if (elements[index] is ControlFlowElement) break;
-      elements[index] = elements[index].accept<TreeNode>(this)..parent = node;
+      elements[index] = transform(elements[index])..parent = node;
     }
 
     // If there were only expressions, we are done.
     if (index == elements.length) return node;
 
     InterfaceType receiverType = isSet
-        ? _typeEnvironment.setType(elementType, _currentLibrary.nonNullable)
-        : _typeEnvironment.listType(elementType, _currentLibrary.nonNullable);
-    VariableDeclaration result;
+        ? _typeEnvironment.setType(elementType, _currentLibrary!.nonNullable)
+        : _typeEnvironment.listType(elementType, _currentLibrary!.nonNullable);
+    VariableDeclaration? result;
     if (index == 0 && elements[index] is SpreadElement) {
-      SpreadElement initialSpread = elements[index];
+      SpreadElement initialSpread = elements[index] as SpreadElement;
       final bool typeMatches = initialSpread.elementType != null &&
-          _typeEnvironment.isSubtypeOf(initialSpread.elementType, elementType,
+          _typeEnvironment.isSubtypeOf(initialSpread.elementType!, elementType,
               SubtypeCheckMode.withNullabilities);
       if (typeMatches && !initialSpread.isNullAware) {
         // Create a list or set of the initial spread element.
-        Expression value = initialSpread.expression.accept<TreeNode>(this);
+        Expression value = transform(initialSpread.expression);
         index++;
         if (isSet) {
           result = _createVariable(
@@ -148,7 +158,7 @@
         }
       }
     }
-    List<Statement> body;
+    List<Statement>? body;
     if (result == null) {
       // Create a list or set with the elements up to the first non-expression.
       if (isSet) {
@@ -174,8 +184,8 @@
           body = [result];
           // Add the elements up to the first non-expression.
           for (int j = 0; j < index; ++j) {
-            _addExpressionElement(
-                elements[j], receiverType, isSet, result, body);
+            _addExpressionElement(elements[j], receiverType, result, body,
+                isSet: isSet);
           }
         }
       } else {
@@ -191,90 +201,84 @@
     // Translate the elements starting with the first non-expression.
     for (; index < elements.length; ++index) {
       _translateElement(
-          elements[index], receiverType, elementType, isSet, result, body);
+          elements[index], receiverType, elementType, result, body,
+          isSet: isSet);
     }
 
     return _createBlockExpression(
         node.fileOffset, _createBlock(body), _createVariableGet(result));
   }
 
-  void _translateElement(
-      Expression element,
-      InterfaceType receiverType,
-      DartType elementType,
-      bool isSet,
-      VariableDeclaration result,
-      List<Statement> body) {
+  void _translateElement(Expression element, InterfaceType receiverType,
+      DartType elementType, VariableDeclaration result, List<Statement> body,
+      {required bool isSet}) {
     if (element is SpreadElement) {
-      _translateSpreadElement(
-          element, receiverType, elementType, isSet, result, body);
+      _translateSpreadElement(element, receiverType, elementType, result, body,
+          isSet: isSet);
     } else if (element is IfElement) {
-      _translateIfElement(
-          element, receiverType, elementType, isSet, result, body);
+      _translateIfElement(element, receiverType, elementType, result, body,
+          isSet: isSet);
     } else if (element is ForElement) {
-      _translateForElement(
-          element, receiverType, elementType, isSet, result, body);
+      _translateForElement(element, receiverType, elementType, result, body,
+          isSet: isSet);
     } else if (element is ForInElement) {
-      _translateForInElement(
-          element, receiverType, elementType, isSet, result, body);
+      _translateForInElement(element, receiverType, elementType, result, body,
+          isSet: isSet);
     } else {
-      _addExpressionElement(
-          element.accept<TreeNode>(this), receiverType, isSet, result, body);
+      _addExpressionElement(transform(element), receiverType, result, body,
+          isSet: isSet);
     }
   }
 
   void _addExpressionElement(Expression element, InterfaceType receiverType,
-      bool isSet, VariableDeclaration result, List<Statement> body) {
-    body.add(_createExpressionStatement(
-        _createAdd(_createVariableGet(result), receiverType, element, isSet)));
+      VariableDeclaration result, List<Statement> body,
+      {required bool isSet}) {
+    body.add(_createExpressionStatement(_createAdd(
+        _createVariableGet(result), receiverType, element,
+        isSet: isSet)));
   }
 
-  void _translateIfElement(
-      IfElement element,
-      InterfaceType receiverType,
-      DartType elementType,
-      bool isSet,
-      VariableDeclaration result,
-      List<Statement> body) {
+  void _translateIfElement(IfElement element, InterfaceType receiverType,
+      DartType elementType, VariableDeclaration result, List<Statement> body,
+      {required bool isSet}) {
     List<Statement> thenStatements = [];
     _translateElement(
-        element.then, receiverType, elementType, isSet, result, thenStatements);
-    List<Statement> elseStatements;
+        element.then, receiverType, elementType, result, thenStatements,
+        isSet: isSet);
+    List<Statement>? elseStatements;
     if (element.otherwise != null) {
-      _translateElement(element.otherwise, receiverType, elementType, isSet,
-          result, elseStatements = <Statement>[]);
+      _translateElement(element.otherwise!, receiverType, elementType, result,
+          elseStatements = <Statement>[],
+          isSet: isSet);
     }
     Statement thenBody = thenStatements.length == 1
         ? thenStatements.first
         : _createBlock(thenStatements);
-    Statement elseBody;
+    Statement? elseBody;
     if (elseStatements != null && elseStatements.isNotEmpty) {
       elseBody = elseStatements.length == 1
           ? elseStatements.first
           : _createBlock(elseStatements);
     }
-    IfStatement ifStatement = _createIf(element.fileOffset,
-        element.condition.accept<TreeNode>(this), thenBody, elseBody);
+    IfStatement ifStatement = _createIf(
+        element.fileOffset, transform(element.condition), thenBody, elseBody);
     _dataForTesting?.registerAlias(element, ifStatement);
     body.add(ifStatement);
   }
 
-  void _translateForElement(
-      ForElement element,
-      InterfaceType receiverType,
-      DartType elementType,
-      bool isSet,
-      VariableDeclaration result,
-      List<Statement> body) {
+  void _translateForElement(ForElement element, InterfaceType receiverType,
+      DartType elementType, VariableDeclaration result, List<Statement> body,
+      {required bool isSet}) {
     List<Statement> statements = <Statement>[];
     _translateElement(
-        element.body, receiverType, elementType, isSet, result, statements);
+        element.body, receiverType, elementType, result, statements,
+        isSet: isSet);
     Statement loopBody =
         statements.length == 1 ? statements.first : _createBlock(statements);
     ForStatement loop = _createForStatement(
         element.fileOffset,
         element.variables,
-        element.condition?.accept<TreeNode>(this),
+        _transformNullable(element.condition),
         element.updates,
         loopBody);
     transformList(loop.variables, loop);
@@ -283,32 +287,28 @@
     body.add(loop);
   }
 
-  void _translateForInElement(
-      ForInElement element,
-      InterfaceType receiverType,
-      DartType elementType,
-      bool isSet,
-      VariableDeclaration result,
-      List<Statement> body) {
+  void _translateForInElement(ForInElement element, InterfaceType receiverType,
+      DartType elementType, VariableDeclaration result, List<Statement> body,
+      {required bool isSet}) {
     List<Statement> statements;
-    Statement prologue = element.prologue;
+    Statement? prologue = element.prologue;
     if (prologue == null) {
       statements = <Statement>[];
     } else {
-      prologue = prologue.accept<TreeNode>(this);
+      prologue = transform(prologue);
       statements =
           prologue is Block ? prologue.statements : <Statement>[prologue];
     }
     _translateElement(
-        element.body, receiverType, elementType, isSet, result, statements);
+        element.body, receiverType, elementType, result, statements,
+        isSet: isSet);
     Statement loopBody =
         statements.length == 1 ? statements.first : _createBlock(statements);
     if (element.problem != null) {
-      body.add(
-          _createExpressionStatement(element.problem.accept<TreeNode>(this)));
+      body.add(_createExpressionStatement(transform(element.problem!)));
     }
     ForInStatement loop = _createForInStatement(element.fileOffset,
-        element.variable, element.iterable.accept<TreeNode>(this), loopBody,
+        element.variable, transform(element.iterable), loopBody,
         isAsync: element.isAsync);
     _dataForTesting?.registerAlias(element, loop);
     body.add(loop);
@@ -318,26 +318,26 @@
       SpreadElement element,
       InterfaceType receiverType,
       DartType elementType,
-      bool isSet,
       VariableDeclaration result,
-      List<Statement> body) {
-    Expression value = element.expression.accept<TreeNode>(this);
+      List<Statement> body,
+      {required bool isSet}) {
+    Expression value = transform(element.expression);
 
     final bool typeMatches = element.elementType != null &&
-        _typeEnvironment.isSubtypeOf(element.elementType, elementType,
+        _typeEnvironment.isSubtypeOf(element.elementType!, elementType,
             SubtypeCheckMode.withNullabilities);
     if (typeMatches) {
       // If the type guarantees that all elements are of the required type, use
       // a single 'addAll' call instead of a for-loop with calls to 'add'.
 
       // Null-aware spreads require testing the subexpression's value.
-      VariableDeclaration temp;
+      VariableDeclaration? temp;
       if (element.isNullAware) {
         temp = _createVariable(
             value,
             _typeEnvironment.iterableType(
                 typeMatches ? elementType : const DynamicType(),
-                _currentLibrary.nullable));
+                _currentLibrary!.nullable));
         body.add(temp);
         value = _createNullCheckedVariableGet(temp);
       }
@@ -347,20 +347,20 @@
 
       if (element.isNullAware) {
         statement = _createIf(
-            temp.fileOffset,
+            temp!.fileOffset,
             _createEqualsNull(_createVariableGet(temp), notEquals: true),
             statement);
       }
       body.add(statement);
     } else {
       // Null-aware spreads require testing the subexpression's value.
-      VariableDeclaration temp;
+      VariableDeclaration? temp;
       if (element.isNullAware) {
         temp = _createVariable(
             value,
             _typeEnvironment.iterableType(
                 typeMatches ? elementType : const DynamicType(),
-                _currentLibrary.nullable));
+                _currentLibrary!.nullable));
         body.add(temp);
         value = _createNullCheckedVariableGet(temp);
       }
@@ -377,7 +377,8 @@
         loopBody = _createBlock(<Statement>[
           castedVar,
           _createExpressionStatement(_createAdd(_createVariableGet(result),
-              receiverType, _createVariableGet(castedVar), isSet))
+              receiverType, _createVariableGet(castedVar),
+              isSet: isSet))
         ]);
       } else {
         variable = _createForInVariable(element.fileOffset, elementType);
@@ -385,14 +386,14 @@
             _createVariableGet(result),
             receiverType,
             _createVariableGet(variable),
-            isSet));
+            isSet: isSet));
       }
       Statement statement =
           _createForInStatement(element.fileOffset, variable, value, loopBody);
 
       if (element.isNullAware) {
         statement = _createIf(
-            temp.fileOffset,
+            temp!.fileOffset,
             _createEqualsNull(_createVariableGet(temp), notEquals: true),
             statement);
       }
@@ -432,7 +433,7 @@
     int i = 0;
     for (; i < node.entries.length; ++i) {
       if (node.entries[i] is ControlFlowMapEntry) break;
-      node.entries[i] = node.entries[i].accept<TreeNode>(this)..parent = node;
+      node.entries[i] = transform(node.entries[i])..parent = node;
     }
 
     // If there were no control-flow entries we are done.
@@ -440,7 +441,7 @@
 
     // Build a block expression and create an empty map.
     InterfaceType receiverType = _typeEnvironment.mapType(
-        node.keyType, node.valueType, _currentLibrary.nonNullable);
+        node.keyType, node.valueType, _currentLibrary!.nonNullable);
     VariableDeclaration result = _createVariable(
         _createMapLiteral(node.fileOffset, node.keyType, node.valueType, []),
         receiverType);
@@ -476,7 +477,7 @@
       _translateForInEntry(
           entry, receiverType, keyType, valueType, result, body);
     } else {
-      _addNormalEntry(entry.accept<TreeNode>(this), receiverType, result, body);
+      _addNormalEntry(transform(entry), receiverType, result, body);
     }
   }
 
@@ -496,20 +497,20 @@
     List<Statement> thenBody = [];
     _translateEntry(
         entry.then, receiverType, keyType, valueType, result, thenBody);
-    List<Statement> elseBody;
+    List<Statement>? elseBody;
     if (entry.otherwise != null) {
-      _translateEntry(entry.otherwise, receiverType, keyType, valueType, result,
-          elseBody = <Statement>[]);
+      _translateEntry(entry.otherwise!, receiverType, keyType, valueType,
+          result, elseBody = <Statement>[]);
     }
     Statement thenStatement =
         thenBody.length == 1 ? thenBody.first : _createBlock(thenBody);
-    Statement elseStatement;
+    Statement? elseStatement;
     if (elseBody != null && elseBody.isNotEmpty) {
       elseStatement =
           elseBody.length == 1 ? elseBody.first : _createBlock(elseBody);
     }
     IfStatement ifStatement = _createIf(entry.fileOffset,
-        entry.condition.accept<TreeNode>(this), thenStatement, elseStatement);
+        transform(entry.condition), thenStatement, elseStatement);
     _dataForTesting?.registerAlias(entry, ifStatement);
     body.add(ifStatement);
   }
@@ -527,7 +528,7 @@
     Statement loopBody =
         statements.length == 1 ? statements.first : _createBlock(statements);
     ForStatement loop = _createForStatement(entry.fileOffset, entry.variables,
-        entry.condition?.accept<TreeNode>(this), entry.updates, loopBody);
+        _transformNullable(entry.condition), entry.updates, loopBody);
     _dataForTesting?.registerAlias(entry, loop);
     transformList(loop.variables, loop);
     transformList(loop.updates, loop);
@@ -542,11 +543,11 @@
       VariableDeclaration result,
       List<Statement> body) {
     List<Statement> statements;
-    Statement prologue = entry.prologue;
+    Statement? prologue = entry.prologue;
     if (prologue == null) {
       statements = <Statement>[];
     } else {
-      prologue = prologue.accept<TreeNode>(this);
+      prologue = transform(prologue);
       statements =
           prologue is Block ? prologue.statements : <Statement>[prologue];
     }
@@ -555,11 +556,10 @@
     Statement loopBody =
         statements.length == 1 ? statements.first : _createBlock(statements);
     if (entry.problem != null) {
-      body.add(
-          _createExpressionStatement(entry.problem.accept<TreeNode>(this)));
+      body.add(_createExpressionStatement(transform(entry.problem!)));
     }
-    ForInStatement loop = _createForInStatement(entry.fileOffset,
-        entry.variable, entry.iterable.accept<TreeNode>(this), loopBody,
+    ForInStatement loop = _createForInStatement(
+        entry.fileOffset, entry.variable, transform(entry.iterable), loopBody,
         isAsync: entry.isAsync);
     _dataForTesting?.registerAlias(entry, loop);
     body.add(loop);
@@ -572,23 +572,23 @@
       DartType valueType,
       VariableDeclaration result,
       List<Statement> body) {
-    Expression value = entry.expression.accept<TreeNode>(this);
+    Expression value = transform(entry.expression);
 
     final InterfaceType entryType = new InterfaceType(_mapEntryClass,
-        _currentLibrary.nonNullable, <DartType>[keyType, valueType]);
+        _currentLibrary!.nonNullable, <DartType>[keyType, valueType]);
     final bool typeMatches = entry.entryType != null &&
         _typeEnvironment.isSubtypeOf(
-            entry.entryType, entryType, SubtypeCheckMode.withNullabilities);
+            entry.entryType!, entryType, SubtypeCheckMode.withNullabilities);
 
     // Null-aware spreads require testing the subexpression's value.
-    VariableDeclaration temp;
+    VariableDeclaration? temp;
     if (entry.isNullAware) {
       temp = _createVariable(
           value,
           _typeEnvironment.mapType(
               typeMatches ? keyType : const DynamicType(),
               typeMatches ? valueType : const DynamicType(),
-              _currentLibrary.nullable));
+              _currentLibrary!.nullable));
       body.add(temp);
       value = _createNullCheckedVariableGet(temp);
     }
@@ -598,7 +598,7 @@
     if (!typeMatches) {
       final InterfaceType variableType = new InterfaceType(
           _mapEntryClass,
-          _currentLibrary.nonNullable,
+          _currentLibrary!.nonNullable,
           <DartType>[const DynamicType(), const DynamicType()]);
       variable = _createForInVariable(entry.fileOffset, variableType);
       VariableDeclaration keyVar = _createVariable(
@@ -641,7 +641,7 @@
 
     if (entry.isNullAware) {
       statement = _createIf(
-          temp.fileOffset,
+          temp!.fileOffset,
           _createEqualsNull(_createVariableGet(temp), notEquals: true),
           statement);
     }
@@ -655,7 +655,7 @@
     int i = 0;
     for (; i < elements.length; ++i) {
       if (elements[i] is ControlFlowElement) break;
-      elements[i] = elements[i].accept<TreeNode>(this)..parent = node;
+      elements[i] = transform(elements[i])..parent = node;
     }
 
     // If there were only expressions, we are done.
@@ -673,10 +673,10 @@
 
     // Build a concatenation node.
     List<Expression> parts = [];
-    List<Expression> currentPart = i > 0 ? elements.sublist(0, i) : null;
+    List<Expression>? currentPart = i > 0 ? elements.sublist(0, i) : null;
 
-    DartType iterableType =
-        _typeEnvironment.iterableType(elementType, _currentLibrary.nonNullable);
+    DartType iterableType = _typeEnvironment.iterableType(
+        elementType, _currentLibrary!.nonNullable);
 
     for (; i < elements.length; ++i) {
       Expression element = elements[i];
@@ -685,12 +685,12 @@
           parts.add(makeLiteral(node.fileOffset, currentPart));
           currentPart = null;
         }
-        Expression spreadExpression = element.expression.accept<TreeNode>(this);
+        Expression spreadExpression = transform(element.expression);
         if (element.isNullAware) {
           VariableDeclaration temp = _createVariable(
               spreadExpression,
               _typeEnvironment.iterableType(
-                  elementType, _currentLibrary.nullable));
+                  elementType, _currentLibrary!.nullable));
           parts.add(_createNullAwareGuard(element.fileOffset, temp,
               makeLiteral(element.fileOffset, []), iterableType));
         } else {
@@ -701,12 +701,12 @@
           parts.add(makeLiteral(node.fileOffset, currentPart));
           currentPart = null;
         }
-        Expression condition = element.condition.accept<TreeNode>(this);
-        Expression then = makeLiteral(element.then.fileOffset, [element.then])
-            .accept<TreeNode>(this);
+        Expression condition = transform(element.condition);
+        Expression then =
+            transform(makeLiteral(element.then.fileOffset, [element.then]));
         Expression otherwise = element.otherwise != null
-            ? makeLiteral(element.otherwise.fileOffset, [element.otherwise])
-                .accept<TreeNode>(this)
+            ? transform(makeLiteral(
+                element.otherwise!.fileOffset, [element.otherwise!]))
             : makeLiteral(element.fileOffset, []);
         parts.add(_createConditionalExpression(
             element.fileOffset, condition, then, otherwise, iterableType));
@@ -716,7 +716,7 @@
             element.fileOffset, getFileUri(element));
       } else {
         currentPart ??= <Expression>[];
-        currentPart.add(element.accept<TreeNode>(this));
+        currentPart.add(transform(element));
       }
     }
     if (currentPart != null) {
@@ -736,7 +736,7 @@
     int i = 0;
     for (; i < node.entries.length; ++i) {
       if (node.entries[i] is ControlFlowMapEntry) break;
-      node.entries[i] = node.entries[i].accept<TreeNode>(this)..parent = node;
+      node.entries[i] = transform(node.entries[i])..parent = node;
     }
 
     // If there were no control-flow entries we are done.
@@ -750,11 +750,11 @@
 
     // Build a concatenation node.
     List<Expression> parts = [];
-    List<MapLiteralEntry> currentPart =
+    List<MapLiteralEntry>? currentPart =
         i > 0 ? node.entries.sublist(0, i) : null;
 
     DartType collectionType = _typeEnvironment.mapType(
-        node.keyType, node.valueType, _currentLibrary.nonNullable);
+        node.keyType, node.valueType, _currentLibrary!.nonNullable);
 
     for (; i < node.entries.length; ++i) {
       MapLiteralEntry entry = node.entries[i];
@@ -763,10 +763,12 @@
           parts.add(makeLiteral(node.fileOffset, currentPart));
           currentPart = null;
         }
-        Expression spreadExpression = entry.expression.accept<TreeNode>(this);
+        Expression spreadExpression = transform(entry.expression);
         if (entry.isNullAware) {
-          VariableDeclaration temp = _createVariable(spreadExpression,
-              collectionType.withDeclaredNullability(_currentLibrary.nullable));
+          VariableDeclaration temp = _createVariable(
+              spreadExpression,
+              collectionType
+                  .withDeclaredNullability(_currentLibrary!.nullable));
           parts.add(_createNullAwareGuard(entry.fileOffset, temp,
               makeLiteral(entry.fileOffset, []), collectionType));
         } else {
@@ -777,12 +779,12 @@
           parts.add(makeLiteral(node.fileOffset, currentPart));
           currentPart = null;
         }
-        Expression condition = entry.condition.accept<TreeNode>(this);
-        Expression then = makeLiteral(entry.then.fileOffset, [entry.then])
-            .accept<TreeNode>(this);
+        Expression condition = transform(entry.condition);
+        Expression then =
+            transform(makeLiteral(entry.then.fileOffset, [entry.then]));
         Expression otherwise = entry.otherwise != null
-            ? makeLiteral(entry.otherwise.fileOffset, [entry.otherwise])
-                .accept<TreeNode>(this)
+            ? transform(
+                makeLiteral(entry.otherwise!.fileOffset, [entry.otherwise!]))
             : makeLiteral(node.fileOffset, []);
         parts.add(_createConditionalExpression(
             entry.fileOffset, condition, then, otherwise, collectionType));
@@ -792,7 +794,7 @@
             entry.fileOffset, getFileUri(entry));
       } else {
         currentPart ??= <MapLiteralEntry>[];
-        currentPart.add(entry.accept<TreeNode>(this));
+        currentPart.add(transform(entry));
       }
     }
     if (currentPart != null) {
@@ -806,7 +808,7 @@
     assert(
         _currentLibrary == null,
         "Attempting to enter library '${library.fileUri}' "
-        "without having exited library '${_currentLibrary.fileUri}'.");
+        "without having exited library '${_currentLibrary!.fileUri}'.");
     _currentLibrary = library;
   }
 
@@ -817,6 +819,7 @@
   }
 
   VariableDeclaration _createVariable(Expression expression, DartType type) {
+    // ignore: unnecessary_null_comparison
     assert(expression != null);
     assert(expression.fileOffset != TreeNode.noOffset);
     return new VariableDeclaration.forValue(expression, type: type)
@@ -830,16 +833,18 @@
   }
 
   VariableGet _createVariableGet(VariableDeclaration variable) {
+    // ignore: unnecessary_null_comparison
     assert(variable != null);
     assert(variable.fileOffset != TreeNode.noOffset);
     return new VariableGet(variable)..fileOffset = variable.fileOffset;
   }
 
   VariableGet _createNullCheckedVariableGet(VariableDeclaration variable) {
+    // ignore: unnecessary_null_comparison
     assert(variable != null);
     assert(variable.fileOffset != TreeNode.noOffset);
     DartType promotedType =
-        variable.type.withDeclaredNullability(_currentLibrary.nonNullable);
+        variable.type.withDeclaredNullability(_currentLibrary!.nonNullable);
     if (promotedType != variable.type) {
       return new VariableGet(variable, promotedType)
         ..fileOffset = variable.fileOffset;
@@ -850,6 +855,7 @@
   MapLiteral _createMapLiteral(int fileOffset, DartType keyType,
       DartType valueType, List<MapLiteralEntry> entries,
       {bool isConst: false}) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     assert(fileOffset != TreeNode.noOffset);
     return new MapLiteral(entries,
@@ -860,6 +866,7 @@
   ListLiteral _createListLiteral(
       int fileOffset, DartType elementType, List<Expression> elements,
       {bool isConst: false}) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     assert(fileOffset != TreeNode.noOffset);
     return new ListLiteral(elements,
@@ -870,6 +877,7 @@
   Expression _createSetLiteral(
       int fileOffset, DartType elementType, List<Expression> elements,
       {bool isConst: false}) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     assert(fileOffset != TreeNode.noOffset);
     if (isConst) {
@@ -884,27 +892,31 @@
   }
 
   ExpressionStatement _createExpressionStatement(Expression expression) {
+    // ignore: unnecessary_null_comparison
     assert(expression != null);
     assert(expression.fileOffset != TreeNode.noOffset);
     return new ExpressionStatement(expression)
       ..fileOffset = expression.fileOffset;
   }
 
-  Expression _createAdd(Expression receiver, InterfaceType receiverType,
-      Expression argument, bool isSet) {
+  Expression _createAdd(
+      Expression receiver, InterfaceType receiverType, Expression argument,
+      {required bool isSet}) {
+    // ignore: unnecessary_null_comparison
     assert(receiver != null);
+    // ignore: unnecessary_null_comparison
     assert(argument != null);
     assert(argument.fileOffset != TreeNode.noOffset,
         "No fileOffset on ${argument}.");
     if (useNewMethodInvocationEncoding) {
-      FunctionType functionType = Substitution.fromInterfaceType(receiverType)
+      DartType functionType = Substitution.fromInterfaceType(receiverType)
           .substituteType(isSet ? _setAddFunctionType : _listAddFunctionType);
-      if (!_currentLibrary.isNonNullableByDefault) {
+      if (!_currentLibrary!.isNonNullableByDefault) {
         functionType = legacyErasure(functionType);
       }
       return new InstanceInvocation(InstanceAccessKind.Instance, receiver,
           new Name('add'), new Arguments([argument]),
-          functionType: functionType,
+          functionType: functionType as FunctionType,
           interfaceTarget: isSet ? _setAdd : _listAdd)
         ..fileOffset = argument.fileOffset
         ..isInvariant = true;
@@ -918,20 +930,22 @@
 
   Expression _createAddAll(Expression receiver, InterfaceType receiverType,
       Expression argument, bool isSet) {
+    // ignore: unnecessary_null_comparison
     assert(receiver != null);
+    // ignore: unnecessary_null_comparison
     assert(argument != null);
     assert(argument.fileOffset != TreeNode.noOffset,
         "No fileOffset on ${argument}.");
     if (useNewMethodInvocationEncoding) {
-      FunctionType functionType = Substitution.fromInterfaceType(receiverType)
+      DartType functionType = Substitution.fromInterfaceType(receiverType)
           .substituteType(
               isSet ? _setAddAllFunctionType : _listAddAllFunctionType);
-      if (!_currentLibrary.isNonNullableByDefault) {
+      if (!_currentLibrary!.isNonNullableByDefault) {
         functionType = legacyErasure(functionType);
       }
       return new InstanceInvocation(InstanceAccessKind.Instance, receiver,
           new Name('addAll'), new Arguments([argument]),
-          functionType: functionType,
+          functionType: functionType as FunctionType,
           interfaceTarget: isSet ? _setAddAll : _listAddAll)
         ..fileOffset = argument.fileOffset
         ..isInvariant = true;
@@ -944,6 +958,7 @@
   }
 
   Expression _createEqualsNull(Expression expression, {bool notEquals: false}) {
+    // ignore: unnecessary_null_comparison
     assert(expression != null);
     assert(expression.fileOffset != TreeNode.noOffset);
     Expression check;
@@ -966,17 +981,18 @@
 
   Expression _createIndexSet(int fileOffset, Expression receiver,
       InterfaceType receiverType, Expression key, Expression value) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     assert(fileOffset != TreeNode.noOffset);
     if (useNewMethodInvocationEncoding) {
-      FunctionType functionType = Substitution.fromInterfaceType(receiverType)
+      DartType functionType = Substitution.fromInterfaceType(receiverType)
           .substituteType(_mapPutFunctionType);
-      if (!_currentLibrary.isNonNullableByDefault) {
+      if (!_currentLibrary!.isNonNullableByDefault) {
         functionType = legacyErasure(functionType);
       }
       return new InstanceInvocation(InstanceAccessKind.Instance, receiver,
           new Name('[]='), new Arguments([key, value]),
-          functionType: functionType, interfaceTarget: _mapPut)
+          functionType: functionType as FunctionType, interfaceTarget: _mapPut)
         ..fileOffset = fileOffset
         ..isInvariant = true;
     } else {
@@ -989,16 +1005,18 @@
 
   AsExpression _createImplicitAs(
       int fileOffset, Expression expression, DartType type) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     assert(fileOffset != TreeNode.noOffset);
     return new AsExpression(expression, type)
       ..isTypeError = true
-      ..isForNonNullableByDefault = _currentLibrary.isNonNullableByDefault
+      ..isForNonNullableByDefault = _currentLibrary!.isNonNullableByDefault
       ..fileOffset = fileOffset;
   }
 
   IfStatement _createIf(int fileOffset, Expression condition, Statement then,
-      [Statement otherwise]) {
+      [Statement? otherwise]) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     assert(fileOffset != TreeNode.noOffset);
     return new IfStatement(condition, then, otherwise)..fileOffset = fileOffset;
@@ -1006,6 +1024,7 @@
 
   Expression _createGetKey(
       int fileOffset, Expression receiver, InterfaceType entryType) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     assert(fileOffset != TreeNode.noOffset);
     if (useNewMethodInvocationEncoding) {
@@ -1023,6 +1042,7 @@
 
   Expression _createGetValue(
       int fileOffset, Expression receiver, InterfaceType entryType) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     assert(fileOffset != TreeNode.noOffset);
     if (useNewMethodInvocationEncoding) {
@@ -1040,6 +1060,7 @@
 
   Expression _createGetEntries(
       int fileOffset, Expression receiver, InterfaceType mapType) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     assert(fileOffset != TreeNode.noOffset);
     if (useNewMethodInvocationEncoding) {
@@ -1058,9 +1079,10 @@
   ForStatement _createForStatement(
       int fileOffset,
       List<VariableDeclaration> variables,
-      Expression condition,
+      Expression? condition,
       List<Expression> updates,
       Statement body) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     assert(fileOffset != TreeNode.noOffset);
     return new ForStatement(variables, condition, updates, body)
@@ -1070,6 +1092,7 @@
   ForInStatement _createForInStatement(int fileOffset,
       VariableDeclaration variable, Expression iterable, Statement body,
       {bool isAsync: false}) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     assert(fileOffset != TreeNode.noOffset);
     return new ForInStatement(variable, iterable, body, isAsync: isAsync)
@@ -1095,6 +1118,7 @@
 
   BlockExpression _createBlockExpression(
       int fileOffset, Block body, Expression value) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     assert(fileOffset != TreeNode.noOffset);
     return new BlockExpression(body, value)..fileOffset = fileOffset;
@@ -1106,6 +1130,7 @@
       Expression then,
       Expression otherwise,
       DartType type) {
+    // ignore: unnecessary_null_comparison
     assert(fileOffset != null);
     assert(fileOffset != TreeNode.noOffset);
     return new ConditionalExpression(condition, then, otherwise, type)
diff --git a/pkg/front_end/lib/src/fasta/kernel/transform_set_literals.dart b/pkg/front_end/lib/src/fasta/kernel/transform_set_literals.dart
index 253d4ce..74246b0 100644
--- a/pkg/front_end/lib/src/fasta/kernel/transform_set_literals.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/transform_set_literals.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.transform_set_literals;
 
 import 'package:kernel/ast.dart';
@@ -23,23 +21,24 @@
   final CoreTypes coreTypes;
   final Procedure setFactory;
   final Procedure addMethod;
-  FunctionType _addMethodFunctionType;
+  late final FunctionType _addMethodFunctionType;
   final bool useNewMethodInvocationEncoding;
 
   /// Library that contains the transformed nodes.
   ///
   /// The transformation of the nodes is affected by the NNBD opt-in status of
   /// the library.
-  Library _currentLibrary;
+  Library? _currentLibrary;
 
   static Procedure _findSetFactory(CoreTypes coreTypes) {
-    Procedure factory = coreTypes.index.getMember('dart:core', 'Set', '');
-    RedirectingFactoryBody body = factory?.function?.body;
-    return body?.target;
+    Procedure factory = coreTypes.index.getProcedure('dart:core', 'Set', '');
+    RedirectingFactoryBody body =
+        factory.function.body as RedirectingFactoryBody;
+    return body.target as Procedure;
   }
 
   static Procedure _findAddMethod(CoreTypes coreTypes) {
-    return coreTypes.index.getMember('dart:core', 'Set', 'add');
+    return coreTypes.index.getProcedure('dart:core', 'Set', 'add');
   }
 
   SetLiteralTransformer(SourceLoader loader)
@@ -48,34 +47,35 @@
         addMethod = _findAddMethod(loader.coreTypes),
         useNewMethodInvocationEncoding =
             loader.target.backendTarget.supportsNewMethodInvocationEncoding {
-    _addMethodFunctionType = addMethod.getterType;
+    _addMethodFunctionType = addMethod.getterType as FunctionType;
   }
 
   TreeNode visitSetLiteral(SetLiteral node) {
     if (node.isConst) return node;
 
     // Create the set: Set<E> setVar = new Set<E>();
-    DartType receiverType;
+    InterfaceType receiverType;
     VariableDeclaration setVar = new VariableDeclaration.forValue(
         new StaticInvocation(
             setFactory, new Arguments([], types: [node.typeArgument])),
         type: receiverType = new InterfaceType(coreTypes.setClass,
-            _currentLibrary.nonNullable, [node.typeArgument]));
+            _currentLibrary!.nonNullable, [node.typeArgument]));
 
     // Now create a list of all statements needed.
     List<Statement> statements = [setVar];
     for (int i = 0; i < node.expressions.length; i++) {
-      Expression entry = node.expressions[i].accept<TreeNode>(this);
+      Expression entry = transform(node.expressions[i]);
       Expression methodInvocation;
       if (useNewMethodInvocationEncoding) {
-        FunctionType functionType = Substitution.fromInterfaceType(receiverType)
+        DartType functionType = Substitution.fromInterfaceType(receiverType)
             .substituteType(_addMethodFunctionType);
-        if (!_currentLibrary.isNonNullableByDefault) {
+        if (!_currentLibrary!.isNonNullableByDefault) {
           functionType = legacyErasure(functionType);
         }
         methodInvocation = new InstanceInvocation(InstanceAccessKind.Instance,
             new VariableGet(setVar), new Name("add"), new Arguments([entry]),
-            functionType: functionType, interfaceTarget: addMethod)
+            functionType: functionType as FunctionType,
+            interfaceTarget: addMethod)
           ..fileOffset = entry.fileOffset
           ..isInvariant = true;
       } else {
@@ -98,7 +98,7 @@
     assert(
         _currentLibrary == null,
         "Attempting to enter library '${library.fileUri}' "
-        "without having exited library '${_currentLibrary.fileUri}'.");
+        "without having exited library '${_currentLibrary!.fileUri}'.");
     _currentLibrary = library;
   }
 
diff --git a/pkg/front_end/lib/src/fasta/kernel/type_algorithms.dart b/pkg/front_end/lib/src/fasta/kernel/type_algorithms.dart
index 2b2c10f..46c52c1 100644
--- a/pkg/front_end/lib/src/fasta/kernel/type_algorithms.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/type_algorithms.dart
@@ -2,8 +2,6 @@
 // for details. All rights reserved. Use of this source code is governed by a
 // BSD-style license that can be found in the LICENSE.md file.
 
-// @dart = 2.9
-
 import 'package:kernel/ast.dart';
 
 import 'package:kernel/type_algebra.dart' show containsTypeVariable;
@@ -37,6 +35,8 @@
         templateNonSimpleBoundViaReference,
         templateNonSimpleBoundViaVariable;
 
+import '../kernel/utils.dart';
+
 export 'package:kernel/ast.dart' show Variance;
 
 /// Initial value for "variance" that is to be computed by the compiler.
@@ -48,10 +48,10 @@
 // name matches that of the variable, it's interpreted as an occurrence of a
 // type variable.
 int computeTypeVariableBuilderVariance(TypeVariableBuilder variable,
-    TypeBuilder type, LibraryBuilder libraryBuilder) {
+    TypeBuilder? type, LibraryBuilder libraryBuilder) {
   if (type is NamedTypeBuilder) {
     assert(type.declaration != null);
-    TypeDeclarationBuilder declaration = type.declaration;
+    TypeDeclarationBuilder? declaration = type.declaration;
     if (declaration is TypeVariableBuilder) {
       if (declaration == variable) {
         return Variance.covariant;
@@ -62,13 +62,13 @@
       if (declaration is ClassBuilder) {
         int result = Variance.unrelated;
         if (type.arguments != null) {
-          for (int i = 0; i < type.arguments.length; ++i) {
+          for (int i = 0; i < type.arguments!.length; ++i) {
             result = Variance.meet(
                 result,
                 Variance.combine(
                     declaration.cls.typeParameters[i].variance,
                     computeTypeVariableBuilderVariance(
-                        variable, type.arguments[i], libraryBuilder)));
+                        variable, type.arguments![i], libraryBuilder)));
           }
         }
         return result;
@@ -76,14 +76,14 @@
         int result = Variance.unrelated;
 
         if (type.arguments != null) {
-          for (int i = 0; i < type.arguments.length; ++i) {
+          for (int i = 0; i < type.arguments!.length; ++i) {
             const int visitMarker = -2;
 
             int declarationTypeVariableVariance = declaration.varianceAt(i);
             if (declarationTypeVariableVariance == pendingVariance) {
               assert(!declaration.fromDill);
               TypeVariableBuilder declarationTypeVariable =
-                  declaration.typeVariables[i];
+                  declaration.typeVariables![i];
               declarationTypeVariable.variance = visitMarker;
               int computedVariance = computeTypeVariableBuilderVariance(
                   declarationTypeVariable, declaration.type, libraryBuilder);
@@ -92,7 +92,7 @@
             } else if (declarationTypeVariableVariance == visitMarker) {
               assert(!declaration.fromDill);
               TypeVariableBuilder declarationTypeVariable =
-                  declaration.typeVariables[i];
+                  declaration.typeVariables![i];
               libraryBuilder.addProblem(
                   templateCyclicTypedef.withArguments(declaration.name),
                   declaration.charOffset,
@@ -109,7 +109,7 @@
                 result,
                 Variance.combine(
                     computeTypeVariableBuilderVariance(
-                        variable, type.arguments[i], libraryBuilder),
+                        variable, type.arguments![i], libraryBuilder),
                     declarationTypeVariableVariance));
           }
         }
@@ -122,24 +122,24 @@
       result = Variance.meet(
           result,
           computeTypeVariableBuilderVariance(
-              variable, type.returnType, libraryBuilder));
+              variable, type.returnType!, libraryBuilder));
     }
     if (type.typeVariables != null) {
-      for (TypeVariableBuilder typeVariable in type.typeVariables) {
+      for (TypeVariableBuilder typeVariable in type.typeVariables!) {
         // If [variable] is referenced in the bound at all, it makes the
         // variance of [variable] in the entire type invariant.  The invocation
         // of [computeVariance] below is made to simply figure out if [variable]
         // occurs in the bound.
         if (typeVariable.bound != null &&
             computeTypeVariableBuilderVariance(
-                    variable, typeVariable.bound, libraryBuilder) !=
+                    variable, typeVariable.bound!, libraryBuilder) !=
                 Variance.unrelated) {
           result = Variance.invariant;
         }
       }
     }
     if (type.formals != null) {
-      for (FormalParameterBuilder formal in type.formals) {
+      for (FormalParameterBuilder formal in type.formals!) {
         result = Variance.meet(
             result,
             Variance.combine(
@@ -176,8 +176,8 @@
   return const NullabilityBuilder.omitted();
 }
 
-TypeBuilder substituteRange(
-    TypeBuilder type,
+TypeBuilder? substituteRange(
+    TypeBuilder? type,
     Map<TypeVariableBuilder, TypeBuilder> upperSubstitution,
     Map<TypeVariableBuilder, TypeBuilder> lowerSubstitution,
     List<TypeBuilder> unboundTypes,
@@ -186,7 +186,7 @@
   if (type is NamedTypeBuilder) {
     if (type.declaration is TypeVariableBuilder) {
       if (variance == Variance.contravariant) {
-        TypeBuilder replacement = lowerSubstitution[type.declaration];
+        TypeBuilder? replacement = lowerSubstitution[type.declaration];
         if (replacement != null) {
           return replacement.withNullabilityBuilder(
               combineNullabilityBuildersForSubstitution(
@@ -194,7 +194,7 @@
         }
         return type;
       }
-      TypeBuilder replacement = upperSubstitution[type.declaration];
+      TypeBuilder? replacement = upperSubstitution[type.declaration];
       if (replacement != null) {
         return replacement.withNullabilityBuilder(
             combineNullabilityBuildersForSubstitution(
@@ -202,15 +202,17 @@
       }
       return type;
     }
-    if (type.arguments == null || type.arguments.length == 0) {
+    if (type.arguments == null || type.arguments!.length == 0) {
       return type;
     }
-    List<TypeBuilder> arguments;
-    TypeDeclarationBuilder declaration = type.declaration;
+    List<TypeBuilder>? arguments;
+    TypeDeclarationBuilder? declaration = type.declaration;
     if (declaration == null) {
+      // ignore: unnecessary_null_comparison
       assert(unboundTypes != null,
           "Can not handle unbound named type builders without `unboundTypes`.");
       assert(
+          // ignore: unnecessary_null_comparison
           unboundTypeVariables != null,
           "Can not handle unbound named type builders without "
           "`unboundTypeVariables`.");
@@ -218,45 +220,45 @@
           identical(upperSubstitution, lowerSubstitution),
           "Can only handle unbound named type builders identical "
           "`upperSubstitution` and `lowerSubstitution`.");
-      for (int i = 0; i < type.arguments.length; ++i) {
+      for (int i = 0; i < type.arguments!.length; ++i) {
         TypeBuilder substitutedArgument = substituteRange(
-            type.arguments[i],
+            type.arguments![i],
             upperSubstitution,
             lowerSubstitution,
             unboundTypes,
             unboundTypeVariables,
-            variance: variance);
-        if (substitutedArgument != type.arguments[i]) {
-          arguments ??= type.arguments.toList();
+            variance: variance)!;
+        if (substitutedArgument != type.arguments![i]) {
+          arguments ??= type.arguments!.toList();
           arguments[i] = substitutedArgument;
         }
       }
     } else if (declaration is ClassBuilder) {
-      for (int i = 0; i < type.arguments.length; ++i) {
+      for (int i = 0; i < type.arguments!.length; ++i) {
         TypeBuilder substitutedArgument = substituteRange(
-            type.arguments[i],
+            type.arguments![i],
             upperSubstitution,
             lowerSubstitution,
             unboundTypes,
             unboundTypeVariables,
-            variance: variance);
-        if (substitutedArgument != type.arguments[i]) {
-          arguments ??= type.arguments.toList();
+            variance: variance)!;
+        if (substitutedArgument != type.arguments![i]) {
+          arguments ??= type.arguments!.toList();
           arguments[i] = substitutedArgument;
         }
       }
     } else if (declaration is TypeAliasBuilder) {
-      for (int i = 0; i < type.arguments.length; ++i) {
-        TypeVariableBuilder variable = declaration.typeVariables[i];
+      for (int i = 0; i < type.arguments!.length; ++i) {
+        TypeVariableBuilder variable = declaration.typeVariables![i];
         TypeBuilder substitutedArgument = substituteRange(
-            type.arguments[i],
+            type.arguments![i],
             upperSubstitution,
             lowerSubstitution,
             unboundTypes,
             unboundTypeVariables,
-            variance: Variance.combine(variance, variable.variance));
-        if (substitutedArgument != type.arguments[i]) {
-          arguments ??= type.arguments.toList();
+            variance: Variance.combine(variance, variable.variance))!;
+        if (substitutedArgument != type.arguments![i]) {
+          arguments ??= type.arguments!.toList();
           arguments[i] = substitutedArgument;
         }
       }
@@ -277,25 +279,25 @@
     }
     return type;
   } else if (type is FunctionTypeBuilder) {
-    List<TypeVariableBuilder> variables;
+    List<TypeVariableBuilder>? variables;
     if (type.typeVariables != null) {
-      variables =
-          new List<TypeVariableBuilder>.filled(type.typeVariables.length, null);
+      variables = new List<TypeVariableBuilder>.filled(
+          type.typeVariables!.length, dummyTypeVariableBuilder);
     }
-    List<FormalParameterBuilder> formals;
+    List<FormalParameterBuilder>? formals;
     if (type.formals != null) {
-      formals =
-          new List<FormalParameterBuilder>.filled(type.formals.length, null);
+      formals = new List<FormalParameterBuilder>.filled(
+          type.formals!.length, dummyFormalParameterBuilder);
     }
-    TypeBuilder returnType;
+    TypeBuilder? returnType;
     bool changed = false;
 
-    Map<TypeVariableBuilder, TypeBuilder> functionTypeUpperSubstitution;
-    Map<TypeVariableBuilder, TypeBuilder> functionTypeLowerSubstitution;
+    Map<TypeVariableBuilder, TypeBuilder>? functionTypeUpperSubstitution;
+    Map<TypeVariableBuilder, TypeBuilder>? functionTypeLowerSubstitution;
     if (type.typeVariables != null) {
-      for (int i = 0; i < variables.length; i++) {
-        TypeVariableBuilder variable = type.typeVariables[i];
-        TypeBuilder bound = substituteRange(variable.bound, upperSubstitution,
+      for (int i = 0; i < variables!.length; i++) {
+        TypeVariableBuilder variable = type.typeVariables![i];
+        TypeBuilder? bound = substituteRange(variable.bound, upperSubstitution,
             lowerSubstitution, unboundTypes, unboundTypeVariables,
             variance: Variance.invariant);
         if (bound != variable.bound) {
@@ -309,7 +311,7 @@
             functionTypeLowerSubstitution = {}..addAll(lowerSubstitution);
           }
           functionTypeUpperSubstitution[variable] =
-              functionTypeLowerSubstitution[variable] =
+              functionTypeLowerSubstitution![variable] =
                   new NamedTypeBuilder.fromTypeDeclarationBuilder(
                       newTypeVariableBuilder,
                       const NullabilityBuilder.omitted());
@@ -320,9 +322,9 @@
       }
     }
     if (type.formals != null) {
-      for (int i = 0; i < formals.length; i++) {
-        FormalParameterBuilder formal = type.formals[i];
-        TypeBuilder parameterType = substituteRange(
+      for (int i = 0; i < formals!.length; i++) {
+        FormalParameterBuilder formal = type.formals![i];
+        TypeBuilder? parameterType = substituteRange(
             formal.type,
             functionTypeUpperSubstitution ?? upperSubstitution,
             functionTypeLowerSubstitution ?? lowerSubstitution,
@@ -335,7 +337,7 @@
               formal.modifiers,
               parameterType,
               formal.name,
-              formal.parent,
+              formal.parent as LibraryBuilder?,
               formal.charOffset,
               fileUri: formal.fileUri,
               isExtensionThis: formal.isExtensionThis);
@@ -363,10 +365,10 @@
   return type;
 }
 
-TypeBuilder substitute(
-    TypeBuilder type, Map<TypeVariableBuilder, TypeBuilder> substitution,
-    {List<TypeBuilder> unboundTypes,
-    List<TypeVariableBuilder> unboundTypeVariables}) {
+TypeBuilder? substitute(
+    TypeBuilder? type, Map<TypeVariableBuilder, TypeBuilder> substitution,
+    {required List<TypeBuilder> unboundTypes,
+    required List<TypeVariableBuilder> unboundTypeVariables}) {
   return substituteRange(
       type, substitution, substitution, unboundTypes, unboundTypeVariables,
       variance: Variance.covariant);
@@ -380,17 +382,16 @@
 /// of the algorithm for details.
 List<TypeBuilder> calculateBounds(List<TypeVariableBuilder> variables,
     TypeBuilder dynamicType, TypeBuilder bottomType, ClassBuilder objectClass,
-    {List<TypeBuilder> unboundTypes,
-    List<TypeVariableBuilder> unboundTypeVariables}) {
+    {required List<TypeBuilder> unboundTypes,
+    required List<TypeVariableBuilder> unboundTypeVariables}) {
+  // ignore: unnecessary_null_comparison
   assert(unboundTypes != null);
+  // ignore: unnecessary_null_comparison
   assert(unboundTypeVariables != null);
 
-  List<TypeBuilder> bounds =
-      new List<TypeBuilder>.filled(variables.length, null);
-
-  for (int i = 0; i < variables.length; i++) {
-    bounds[i] = variables[i].bound ?? dynamicType;
-  }
+  List<TypeBuilder> bounds = new List<TypeBuilder>.generate(
+      variables.length, (int i) => variables[i].bound ?? dynamicType,
+      growable: false);
 
   TypeVariablesGraph graph = new TypeVariablesGraph(variables, bounds);
   List<List<int>> stronglyConnected = computeStrongComponents(graph);
@@ -411,7 +412,7 @@
           nullSubstitution,
           unboundTypes,
           unboundTypeVariables,
-          variance: variable.variance);
+          variance: variable.variance)!;
     }
   }
 
@@ -426,7 +427,7 @@
       TypeVariableBuilder variable = variables[j];
       bounds[j] = substituteRange(bounds[j], substitution, nullSubstitution,
           unboundTypes, unboundTypeVariables,
-          variance: variable.variance);
+          variance: variable.variance)!;
     }
   }
 
@@ -437,46 +438,45 @@
 /// Type variables are represented by their indices in the corresponding
 /// declaration.
 class TypeVariablesGraph implements Graph<int> {
-  List<int> vertices;
+  late List<int> vertices;
   List<TypeVariableBuilder> variables;
   List<TypeBuilder> bounds;
 
   // `edges[i]` is the list of indices of type variables that reference the type
   // variable with the index `i` in their bounds.
-  List<List<int>> edges;
+  late List<List<int>> edges;
 
   TypeVariablesGraph(this.variables, this.bounds) {
     assert(variables.length == bounds.length);
 
-    vertices = new List<int>.filled(variables.length, null);
+    vertices =
+        new List<int>.generate(variables.length, (int i) => i, growable: false);
     Map<TypeVariableBuilder, int> variableIndices =
         <TypeVariableBuilder, int>{};
-    edges = new List<List<int>>.filled(variables.length, null);
-    for (int i = 0; i < vertices.length; i++) {
-      vertices[i] = i;
+    edges = new List<List<int>>.generate(variables.length, (int i) {
       variableIndices[variables[i]] = i;
-      edges[i] = <int>[];
-    }
+      return <int>[];
+    }, growable: false);
 
-    void collectReferencesFrom(int index, TypeBuilder type) {
+    void collectReferencesFrom(int index, TypeBuilder? type) {
       if (type is NamedTypeBuilder) {
         if (type.declaration is TypeVariableBuilder &&
             this.variables.contains(type.declaration)) {
-          edges[variableIndices[type.declaration]].add(index);
+          edges[variableIndices[type.declaration]!].add(index);
         }
         if (type.arguments != null) {
-          for (TypeBuilder argument in type.arguments) {
+          for (TypeBuilder argument in type.arguments!) {
             collectReferencesFrom(index, argument);
           }
         }
       } else if (type is FunctionTypeBuilder) {
         if (type.typeVariables != null) {
-          for (TypeVariableBuilder typeVariable in type.typeVariables) {
+          for (TypeVariableBuilder typeVariable in type.typeVariables!) {
             collectReferencesFrom(index, typeVariable.bound);
           }
         }
         if (type.formals != null) {
-          for (FormalParameterBuilder parameter in type.formals) {
+          for (FormalParameterBuilder parameter in type.formals!) {
             collectReferencesFrom(index, parameter.type);
           }
         }
@@ -501,7 +501,7 @@
 /// Returns list of the found type builders.
 List<NamedTypeBuilder> findVariableUsesInType(
   TypeVariableBuilder variable,
-  TypeBuilder type,
+  TypeBuilder? type,
 ) {
   List<NamedTypeBuilder> uses = <NamedTypeBuilder>[];
   if (type is NamedTypeBuilder) {
@@ -509,7 +509,7 @@
       uses.add(type);
     } else {
       if (type.arguments != null) {
-        for (TypeBuilder argument in type.arguments) {
+        for (TypeBuilder argument in type.arguments!) {
           uses.addAll(findVariableUsesInType(variable, argument));
         }
       }
@@ -517,7 +517,7 @@
   } else if (type is FunctionTypeBuilder) {
     uses.addAll(findVariableUsesInType(variable, type.returnType));
     if (type.typeVariables != null) {
-      for (TypeVariableBuilder dependentVariable in type.typeVariables) {
+      for (TypeVariableBuilder dependentVariable in type.typeVariables!) {
         if (dependentVariable.bound != null) {
           uses.addAll(
               findVariableUsesInType(variable, dependentVariable.bound));
@@ -529,7 +529,7 @@
       }
     }
     if (type.formals != null) {
-      for (FormalParameterBuilder formal in type.formals) {
+      for (FormalParameterBuilder formal in type.formals!) {
         uses.addAll(findVariableUsesInType(variable, formal.type));
       }
     }
@@ -568,11 +568,11 @@
 /// raw generic type.  The second element in the pair is the list of type
 /// variables of that type with inbound references in the format specified in
 /// [findInboundReferences].
-List<Object> findRawTypesWithInboundReferences(TypeBuilder type) {
+List<Object> findRawTypesWithInboundReferences(TypeBuilder? type) {
   List<Object> typesAndDependencies = <Object>[];
   if (type is NamedTypeBuilder) {
     if (type.arguments == null) {
-      TypeDeclarationBuilder declaration = type.declaration;
+      TypeDeclarationBuilder? declaration = type.declaration;
       if (declaration is DillClassBuilder) {
         bool hasInbound = false;
         List<TypeParameter> typeParameters = declaration.cls.typeParameters;
@@ -602,7 +602,7 @@
       } else if (declaration is ClassBuilder &&
           declaration.typeVariables != null) {
         List<Object> dependencies =
-            findInboundReferences(declaration.typeVariables);
+            findInboundReferences(declaration.typeVariables!);
         if (dependencies.length != 0) {
           typesAndDependencies.add(type);
           typesAndDependencies.add(dependencies);
@@ -610,17 +610,17 @@
       } else if (declaration is TypeAliasBuilder) {
         if (declaration.typeVariables != null) {
           List<Object> dependencies =
-              findInboundReferences(declaration.typeVariables);
+              findInboundReferences(declaration.typeVariables!);
           if (dependencies.length != 0) {
             typesAndDependencies.add(type);
             typesAndDependencies.add(dependencies);
           }
         }
         if (declaration.type is FunctionTypeBuilder) {
-          FunctionTypeBuilder type = declaration.type;
+          FunctionTypeBuilder type = declaration.type as FunctionTypeBuilder;
           if (type.typeVariables != null) {
             List<Object> dependencies =
-                findInboundReferences(type.typeVariables);
+                findInboundReferences(type.typeVariables!);
             if (dependencies.length != 0) {
               typesAndDependencies.add(type);
               typesAndDependencies.add(dependencies);
@@ -629,7 +629,7 @@
         }
       }
     } else {
-      for (TypeBuilder argument in type.arguments) {
+      for (TypeBuilder argument in type.arguments!) {
         typesAndDependencies
             .addAll(findRawTypesWithInboundReferences(argument));
       }
@@ -638,7 +638,7 @@
     typesAndDependencies
         .addAll(findRawTypesWithInboundReferences(type.returnType));
     if (type.typeVariables != null) {
-      for (TypeVariableBuilder variable in type.typeVariables) {
+      for (TypeVariableBuilder variable in type.typeVariables!) {
         if (variable.bound != null) {
           typesAndDependencies
               .addAll(findRawTypesWithInboundReferences(variable.bound));
@@ -650,7 +650,7 @@
       }
     }
     if (type.formals != null) {
-      for (FormalParameterBuilder formal in type.formals) {
+      for (FormalParameterBuilder formal in type.formals!) {
         typesAndDependencies
             .addAll(findRawTypesWithInboundReferences(formal.type));
       }
@@ -673,21 +673,24 @@
       List<Object> rawTypesAndMutualDependencies =
           findRawTypesWithInboundReferences(variable.bound);
       for (int i = 0; i < rawTypesAndMutualDependencies.length; i += 2) {
-        NamedTypeBuilder type = rawTypesAndMutualDependencies[i];
+        NamedTypeBuilder type =
+            rawTypesAndMutualDependencies[i] as NamedTypeBuilder;
         List<Object> variablesAndDependencies =
-            rawTypesAndMutualDependencies[i + 1];
+            rawTypesAndMutualDependencies[i + 1] as List<Object>;
         for (int j = 0; j < variablesAndDependencies.length; j += 2) {
-          TypeVariableBuilder dependent = variablesAndDependencies[j];
-          List<NamedTypeBuilder> dependencies = variablesAndDependencies[j + 1];
+          TypeVariableBuilder dependent =
+              variablesAndDependencies[j] as TypeVariableBuilder;
+          List<NamedTypeBuilder> dependencies =
+              variablesAndDependencies[j + 1] as List<NamedTypeBuilder>;
           for (NamedTypeBuilder dependency in dependencies) {
             issues.add(new NonSimplicityIssue(
                 variable,
                 templateBoundIssueViaRawTypeWithNonSimpleBounds
-                    .withArguments(type.declaration.name),
+                    .withArguments(type.declaration!.name),
                 <LocatedMessage>[
                   templateNonSimpleBoundViaVariable
-                      .withArguments(dependency.declaration.name)
-                      .withLocation(dependent.fileUri, dependent.charOffset,
+                      .withArguments(dependency.declaration!.name)
+                      .withLocation(dependent.fileUri!, dependent.charOffset,
                           dependent.name.length)
                 ]));
           }
@@ -697,7 +700,7 @@
           issues.add(new NonSimplicityIssue(
               variable,
               templateBoundIssueViaRawTypeWithNonSimpleBounds
-                  .withArguments(type.declaration.name),
+                  .withArguments(type.declaration!.name),
               const <LocatedMessage>[]));
         }
       }
@@ -713,7 +716,7 @@
 /// generic types with inbound references in its bound.  The second element of
 /// the triplet is the error message.  The third element is the context.
 List<NonSimplicityIssue> getInboundReferenceIssuesInType(
-    TypeBuilder typeBuilder) {
+    TypeBuilder? typeBuilder) {
   List<FunctionTypeBuilder> genericFunctionTypeBuilders =
       <FunctionTypeBuilder>[];
   findUnaliasedGenericFunctionTypes(typeBuilder,
@@ -722,7 +725,7 @@
   for (FunctionTypeBuilder genericFunctionTypeBuilder
       in genericFunctionTypeBuilders) {
     List<TypeVariableBuilder> typeVariables =
-        genericFunctionTypeBuilder.typeVariables;
+        genericFunctionTypeBuilder.typeVariables!;
     issues.addAll(getInboundReferenceIssues(typeVariables));
   }
   return issues;
@@ -737,18 +740,18 @@
 /// using type for [start], and not the corresponding type declaration,
 /// is better error reporting.
 List<List<RawTypeCycleElement>> findRawTypePathsToDeclaration(
-    TypeBuilder start, TypeDeclarationBuilder end,
-    [Set<TypeDeclarationBuilder> visited]) {
+    TypeBuilder? start, TypeDeclarationBuilder end,
+    [Set<TypeDeclarationBuilder>? visited]) {
   visited ??= new Set<TypeDeclarationBuilder>.identity();
   List<List<RawTypeCycleElement>> paths = <List<RawTypeCycleElement>>[];
   if (start is NamedTypeBuilder) {
-    TypeDeclarationBuilder declaration = start.declaration;
+    TypeDeclarationBuilder? declaration = start.declaration;
     if (start.arguments == null) {
       if (start.declaration == end) {
         paths.add(<RawTypeCycleElement>[new RawTypeCycleElement(start, null)]);
-      } else if (visited.add(start.declaration)) {
+      } else if (visited.add(start.declaration!)) {
         if (declaration is ClassBuilder && declaration.typeVariables != null) {
-          for (TypeVariableBuilder variable in declaration.typeVariables) {
+          for (TypeVariableBuilder variable in declaration.typeVariables!) {
             if (variable.bound != null) {
               for (List<RawTypeCycleElement> path
                   in findRawTypePathsToDeclaration(
@@ -763,7 +766,7 @@
           }
         } else if (declaration is TypeAliasBuilder) {
           if (declaration.typeVariables != null) {
-            for (TypeVariableBuilder variable in declaration.typeVariables) {
+            for (TypeVariableBuilder variable in declaration.typeVariables!) {
               if (variable.bound != null) {
                 for (List<RawTypeCycleElement> dependencyPath
                     in findRawTypePathsToDeclaration(
@@ -778,9 +781,9 @@
             }
           }
           if (declaration.type is FunctionTypeBuilder) {
-            FunctionTypeBuilder type = declaration.type;
+            FunctionTypeBuilder type = declaration.type as FunctionTypeBuilder;
             if (type.typeVariables != null) {
-              for (TypeVariableBuilder variable in type.typeVariables) {
+              for (TypeVariableBuilder variable in type.typeVariables!) {
                 if (variable.bound != null) {
                   for (List<RawTypeCycleElement> dependencyPath
                       in findRawTypePathsToDeclaration(
@@ -799,14 +802,14 @@
         visited.remove(start.declaration);
       }
     } else {
-      for (TypeBuilder argument in start.arguments) {
+      for (TypeBuilder argument in start.arguments!) {
         paths.addAll(findRawTypePathsToDeclaration(argument, end, visited));
       }
     }
   } else if (start is FunctionTypeBuilder) {
     paths.addAll(findRawTypePathsToDeclaration(start.returnType, end, visited));
     if (start.typeVariables != null) {
-      for (TypeVariableBuilder variable in start.typeVariables) {
+      for (TypeVariableBuilder variable in start.typeVariables!) {
         if (variable.bound != null) {
           paths.addAll(
               findRawTypePathsToDeclaration(variable.bound, end, visited));
@@ -818,7 +821,7 @@
       }
     }
     if (start.formals != null) {
-      for (FormalParameterBuilder formal in start.formals) {
+      for (FormalParameterBuilder formal in start.formals!) {
         paths.addAll(findRawTypePathsToDeclaration(formal.type, end, visited));
       }
     }
@@ -838,7 +841,7 @@
     TypeDeclarationBuilder declaration) {
   List<List<RawTypeCycleElement>> cycles = <List<RawTypeCycleElement>>[];
   if (declaration is ClassBuilder && declaration.typeVariables != null) {
-    for (TypeVariableBuilder variable in declaration.typeVariables) {
+    for (TypeVariableBuilder variable in declaration.typeVariables!) {
       if (variable.bound != null) {
         for (List<RawTypeCycleElement> path
             in findRawTypePathsToDeclaration(variable.bound, declaration)) {
@@ -851,7 +854,7 @@
     }
   } else if (declaration is TypeAliasBuilder) {
     if (declaration.typeVariables != null) {
-      for (TypeVariableBuilder variable in declaration.typeVariables) {
+      for (TypeVariableBuilder variable in declaration.typeVariables!) {
         if (variable.bound != null) {
           for (List<RawTypeCycleElement> dependencyPath
               in findRawTypePathsToDeclaration(variable.bound, declaration)) {
@@ -864,9 +867,9 @@
       }
     }
     if (declaration.type is FunctionTypeBuilder) {
-      FunctionTypeBuilder type = declaration.type;
+      FunctionTypeBuilder type = declaration.type as FunctionTypeBuilder;
       if (type.typeVariables != null) {
-        for (TypeVariableBuilder variable in type.typeVariables) {
+        for (TypeVariableBuilder variable in type.typeVariables!) {
           if (variable.bound != null) {
             for (List<RawTypeCycleElement> dependencyPath
                 in findRawTypePathsToDeclaration(variable.bound, declaration)) {
@@ -900,26 +903,26 @@
     if (cycle.length == 1) {
       // Loop.
       issues.add(new NonSimplicityIssue(
-          cycle.single.typeVariable,
+          cycle.single.typeVariable!,
           templateBoundIssueViaLoopNonSimplicity
-              .withArguments(cycle.single.type.declaration.name),
+              .withArguments(cycle.single.type.declaration!.name),
           null));
     } else if (cycle.isNotEmpty) {
       assert(cycle.length > 1);
       List<LocatedMessage> context = <LocatedMessage>[];
       for (RawTypeCycleElement cycleElement in cycle) {
         context.add(templateNonSimpleBoundViaReference
-            .withArguments(cycleElement.type.declaration.name)
+            .withArguments(cycleElement.type.declaration!.name)
             .withLocation(
-                cycleElement.typeVariable.fileUri,
-                cycleElement.typeVariable.charOffset,
-                cycleElement.typeVariable.name.length));
+                cycleElement.typeVariable!.fileUri!,
+                cycleElement.typeVariable!.charOffset,
+                cycleElement.typeVariable!.name.length));
       }
 
       issues.add(new NonSimplicityIssue(
           declaration,
           templateBoundIssueViaCycleNonSimplicity.withArguments(
-              declaration.name, cycle.first.type.declaration.name),
+              declaration.name, cycle.first.type.declaration!.name),
           context));
     }
   }
@@ -936,7 +939,7 @@
 /// The second element in the triplet is the error message.  The third element
 /// in the triplet is the context.
 List<NonSimplicityIssue> getNonSimplicityIssuesForTypeVariables(
-    List<TypeVariableBuilder> variables) {
+    List<TypeVariableBuilder>? variables) {
   if (variables == null) return <NonSimplicityIssue>[];
   return getInboundReferenceIssues(variables);
 }
@@ -956,10 +959,10 @@
     {bool performErrorRecovery: true}) {
   List<NonSimplicityIssue> issues = <NonSimplicityIssue>[];
   if (declaration is ClassBuilder && declaration.typeVariables != null) {
-    issues.addAll(getInboundReferenceIssues(declaration.typeVariables));
+    issues.addAll(getInboundReferenceIssues(declaration.typeVariables!));
   } else if (declaration is TypeAliasBuilder &&
       declaration.typeVariables != null) {
-    issues.addAll(getInboundReferenceIssues(declaration.typeVariables));
+    issues.addAll(getInboundReferenceIssues(declaration.typeVariables!));
   }
   List<List<RawTypeCycleElement>> cyclesToReport =
       <List<RawTypeCycleElement>>[];
@@ -972,10 +975,10 @@
     } else {
       String declarationPathAndName =
           "${declaration.fileUri}:${declaration.name}";
-      String lexMinPathAndName = null;
+      String? lexMinPathAndName = null;
       for (RawTypeCycleElement cycleElement in cycle) {
-        String pathAndName = "${cycleElement.type.declaration.fileUri}:"
-            "${cycleElement.type.declaration.name}";
+        String pathAndName = "${cycleElement.type.declaration!.fileUri}:"
+            "${cycleElement.type.declaration!.name}";
         if (lexMinPathAndName == null ||
             lexMinPathAndName.compareTo(pathAndName) > 0) {
           lexMinPathAndName = pathAndName;
@@ -1004,20 +1007,21 @@
 void breakCycles(List<List<RawTypeCycleElement>> cycles) {
   for (List<RawTypeCycleElement> cycle in cycles) {
     if (cycle.isNotEmpty) {
-      cycle.first.typeVariable.bound = null;
+      cycle.first.typeVariable!.bound = null;
     }
   }
 }
 
 /// Finds generic function type sub-terms in [type].
-void findUnaliasedGenericFunctionTypes(TypeBuilder type,
-    {List<FunctionTypeBuilder> result}) {
+void findUnaliasedGenericFunctionTypes(TypeBuilder? type,
+    {required List<FunctionTypeBuilder> result}) {
+  // ignore: unnecessary_null_comparison
   assert(result != null);
   if (type is FunctionTypeBuilder) {
-    if (type.typeVariables != null && type.typeVariables.length > 0) {
+    if (type.typeVariables != null && type.typeVariables!.length > 0) {
       result.add(type);
 
-      for (TypeVariableBuilder typeVariable in type.typeVariables) {
+      for (TypeVariableBuilder typeVariable in type.typeVariables!) {
         findUnaliasedGenericFunctionTypes(typeVariable.bound, result: result);
         findUnaliasedGenericFunctionTypes(typeVariable.defaultType,
             result: result);
@@ -1025,13 +1029,13 @@
     }
     findUnaliasedGenericFunctionTypes(type.returnType, result: result);
     if (type.formals != null) {
-      for (FormalParameterBuilder formal in type.formals) {
+      for (FormalParameterBuilder formal in type.formals!) {
         findUnaliasedGenericFunctionTypes(formal.type, result: result);
       }
     }
   } else if (type is NamedTypeBuilder) {
     if (type.arguments != null) {
-      for (TypeBuilder argument in type.arguments) {
+      for (TypeBuilder argument in type.arguments!) {
         findUnaliasedGenericFunctionTypes(argument, result: result);
       }
     }
@@ -1039,37 +1043,39 @@
 }
 
 /// Finds generic function type sub-terms in [type] including the aliased ones.
-void findGenericFunctionTypes(TypeBuilder type, {List<TypeBuilder> result}) {
+void findGenericFunctionTypes(TypeBuilder? type,
+    {required List<TypeBuilder> result}) {
+  // ignore: unnecessary_null_comparison
   assert(result != null);
   if (type is FunctionTypeBuilder) {
-    if (type.typeVariables != null && type.typeVariables.length > 0) {
+    if (type.typeVariables != null && type.typeVariables!.length > 0) {
       result.add(type);
 
-      for (TypeVariableBuilder typeVariable in type.typeVariables) {
+      for (TypeVariableBuilder typeVariable in type.typeVariables!) {
         findGenericFunctionTypes(typeVariable.bound, result: result);
         findGenericFunctionTypes(typeVariable.defaultType, result: result);
       }
     }
     findGenericFunctionTypes(type.returnType, result: result);
     if (type.formals != null) {
-      for (FormalParameterBuilder formal in type.formals) {
+      for (FormalParameterBuilder formal in type.formals!) {
         findGenericFunctionTypes(formal.type, result: result);
       }
     }
   } else if (type is NamedTypeBuilder) {
     if (type.arguments != null) {
-      for (TypeBuilder argument in type.arguments) {
+      for (TypeBuilder argument in type.arguments!) {
         findGenericFunctionTypes(argument, result: result);
       }
     }
 
-    TypeDeclarationBuilder declaration = type.declaration;
+    TypeDeclarationBuilder? declaration = type.declaration;
     // TODO(dmitryas): Unalias beyond the first layer for the check.
     if (declaration is TypeAliasBuilder) {
-      TypeBuilder rhsType = declaration.type;
+      TypeBuilder? rhsType = declaration.type;
       if (rhsType is FunctionTypeBuilder &&
           rhsType.typeVariables != null &&
-          rhsType.typeVariables.isNotEmpty) {
+          rhsType.typeVariables!.isNotEmpty) {
         result.add(type);
       }
     }
@@ -1176,7 +1182,7 @@
 
   /// The context for the error message, containing the locations of all of the
   /// elements from the cycle.
-  final List<LocatedMessage> context;
+  final List<LocatedMessage>? context;
 
   NonSimplicityIssue(this.declaration, this.message, this.context);
 }
@@ -1201,7 +1207,7 @@
 
   /// The type variable that connects [type] to the next element in the
   /// non-simple raw type cycle.
-  TypeVariableBuilder typeVariable;
+  TypeVariableBuilder? typeVariable;
 
   RawTypeCycleElement(this.type, this.typeVariable);
 }
diff --git a/pkg/front_end/lib/src/fasta/kernel/type_builder_computer.dart b/pkg/front_end/lib/src/fasta/kernel/type_builder_computer.dart
index f0e5030..b5828a4 100644
--- a/pkg/front_end/lib/src/fasta/kernel/type_builder_computer.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/type_builder_computer.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.type_builder_computer;
 
 import 'package:_fe_analyzer_shared/src/parser/parser.dart'
@@ -25,6 +23,8 @@
 import '../builder/type_variable_builder.dart';
 import '../builder/void_type_declaration_builder.dart';
 
+import '../kernel/utils.dart';
+
 import '../loader.dart' show Loader;
 
 class TypeBuilderComputer implements DartTypeVisitor<TypeBuilder> {
@@ -94,13 +94,12 @@
   TypeBuilder visitInterfaceType(InterfaceType node) {
     ClassBuilder cls =
         loader.computeClassBuilderFromTargetClass(node.classNode);
-    List<TypeBuilder> arguments;
+    List<TypeBuilder>? arguments;
     List<DartType> kernelArguments = node.typeArguments;
     if (kernelArguments.isNotEmpty) {
-      arguments = new List<TypeBuilder>.filled(kernelArguments.length, null);
-      for (int i = 0; i < kernelArguments.length; i++) {
-        arguments[i] = kernelArguments[i].accept(this);
-      }
+      arguments = new List<TypeBuilder>.generate(
+          kernelArguments.length, (int i) => kernelArguments[i].accept(this),
+          growable: false);
     }
     return new NamedTypeBuilder(
         cls.name,
@@ -133,12 +132,13 @@
     TypeBuilder returnType = node.returnType.accept(this);
     // We could compute the type variables here. However, the current
     // implementation of [visitTypeParameterType] is sufficient.
-    List<TypeVariableBuilder> typeVariables = null;
+    List<TypeVariableBuilder>? typeVariables = null;
     List<DartType> positionalParameters = node.positionalParameters;
     List<NamedType> namedParameters = node.namedParameters;
     List<FormalParameterBuilder> formals =
         new List<FormalParameterBuilder>.filled(
-            positionalParameters.length + namedParameters.length, null);
+            positionalParameters.length + namedParameters.length,
+            dummyFormalParameterBuilder);
     for (int i = 0; i < positionalParameters.length; i++) {
       TypeBuilder type = positionalParameters[i].accept(this);
       FormalParameterKind kind = FormalParameterKind.mandatory;
@@ -149,7 +149,7 @@
           /* metadata = */ null,
           /* modifiers = */ 0,
           type,
-          /* name = */ null,
+          /* name = */ '',
           /* compilationUnit = */ null,
           /* charOffset = */ TreeNode.noOffset)
         ..kind = kind;
@@ -177,16 +177,16 @@
 
   TypeBuilder visitTypeParameterType(TypeParameterType node) {
     TypeParameter parameter = node.parameter;
-    TreeNode kernelClassOrTypeDef = parameter.parent;
-    Library kernelLibrary;
+    TreeNode? kernelClassOrTypeDef = parameter.parent;
+    Library? kernelLibrary;
     if (kernelClassOrTypeDef is Class) {
       kernelLibrary = kernelClassOrTypeDef.enclosingLibrary;
     } else if (kernelClassOrTypeDef is Typedef) {
       kernelLibrary = kernelClassOrTypeDef.enclosingLibrary;
     }
-    LibraryBuilder library = loader.builders[kernelLibrary.importUri];
+    LibraryBuilder library = loader.builders[kernelLibrary!.importUri]!;
     return new NamedTypeBuilder(
-        parameter.name,
+        parameter.name!,
         new NullabilityBuilder.fromNullability(node.nullability),
         /* arguments = */ null,
         /* fileUri = */ null,
diff --git a/pkg/front_end/lib/src/fasta/kernel/utils.dart b/pkg/front_end/lib/src/fasta/kernel/utils.dart
index 22ca5d8..b24667f 100644
--- a/pkg/front_end/lib/src/fasta/kernel/utils.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/utils.dart
@@ -6,6 +6,10 @@
 
 import 'dart:typed_data' show Uint8List;
 
+import 'package:_fe_analyzer_shared/src/scanner/scanner.dart' show Token;
+import 'package:_fe_analyzer_shared/src/scanner/token.dart'
+    show SyntheticToken, TokenType;
+
 import 'package:kernel/clone.dart' show CloneVisitorWithMembers;
 
 import 'package:kernel/ast.dart'
@@ -18,12 +22,23 @@
         Supertype,
         TreeNode,
         TypeParameter,
-        TypeParameterType;
+        TypeParameterType,
+        dummyDartType,
+        dummyUri;
 
 import 'package:kernel/binary/ast_to_binary.dart' show BinaryPrinter;
 
 import 'package:kernel/text/ast_to_text.dart' show Printer;
 
+import '../builder/fixed_type_builder.dart';
+import '../builder/formal_parameter_builder.dart';
+import '../builder/type_builder.dart';
+import '../builder/type_variable_builder.dart';
+import '../combinator.dart';
+import '../identifiers.dart';
+import '../source/source_library_builder.dart';
+import 'body_builder.dart';
+
 /// Print the given [component].  Do nothing if it is `null`.  If the
 /// [libraryFilter] is provided, then only libraries that satisfy it are
 /// printed.
@@ -140,3 +155,15 @@
 
   void close() {}
 }
+
+final Token dummyToken = new SyntheticToken(TokenType.AT, -1);
+final Identifier dummyIdentifier = new Identifier(dummyToken);
+final Combinator dummyCombinator = new Combinator(false, {}, -1, dummyUri);
+final TypeBuilder dummyTypeBuilder =
+    new FixedTypeBuilder(dummyDartType, dummyUri, -1);
+final FormalParameterBuilder dummyFormalParameterBuilder =
+    new FormalParameterBuilder(null, 0, null, '', null, -1, fileUri: dummyUri);
+final TypeVariableBuilder dummyTypeVariableBuilder =
+    new TypeVariableBuilder(TypeVariableBuilder.noNameSentinel, null, -1, null);
+final Label dummyLabel = new Label('', -1);
+final FieldInfo dummyFieldInfo = new FieldInfo('', -1, null, dummyToken, -1);
diff --git a/pkg/front_end/lib/src/fasta/kernel/verifier.dart b/pkg/front_end/lib/src/fasta/kernel/verifier.dart
index d9b6147..363f618 100644
--- a/pkg/front_end/lib/src/fasta/kernel/verifier.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/verifier.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.verifier;
 
 import 'package:_fe_analyzer_shared/src/messages/severity.dart' show Severity;
@@ -23,6 +21,7 @@
 import '../fasta_codes.dart'
     show
         LocatedMessage,
+        Message,
         messageVerificationErrorOriginContext,
         noLength,
         templateInternalProblemVerificationError;
@@ -36,7 +35,7 @@
         isRedirectingFactory;
 
 List<LocatedMessage> verifyComponent(Component component, Target target,
-    {bool isOutline, bool afterConst, bool skipPlatform: false}) {
+    {bool? isOutline, bool? afterConst, bool skipPlatform: false}) {
   FastaVerifyingVisitor verifier =
       new FastaVerifyingVisitor(target, isOutline, afterConst, skipPlatform);
   component.accept(verifier);
@@ -47,12 +46,12 @@
   final Target target;
   final List<LocatedMessage> errors = <LocatedMessage>[];
 
-  Uri fileUri;
+  Uri? fileUri;
   final List<TreeNode> treeNodeStack = <TreeNode>[];
   final bool skipPlatform;
 
   FastaVerifyingVisitor(
-      this.target, bool isOutline, bool afterConst, this.skipPlatform)
+      this.target, bool? isOutline, bool? afterConst, this.skipPlatform)
       : super(isOutline: isOutline, afterConst: afterConst);
 
   /// Invoked by all visit methods if the visited node is a [TreeNode].
@@ -73,7 +72,7 @@
     treeNodeStack.removeLast();
   }
 
-  TreeNode getLastSeenTreeNode({bool withLocation = false}) {
+  TreeNode? getLastSeenTreeNode({bool withLocation = false}) {
     assert(treeNodeStack.isNotEmpty);
     for (int i = treeNodeStack.length - 1; i >= 0; --i) {
       TreeNode node = treeNodeStack[i];
@@ -83,15 +82,16 @@
     return null;
   }
 
-  TreeNode getSameLibraryLastSeenTreeNode({bool withLocation = false}) {
+  TreeNode? getSameLibraryLastSeenTreeNode({bool withLocation = false}) {
     if (treeNodeStack.isEmpty) return null;
-    if (currentLibrary == null || currentLibrary.fileUri == null) return null;
+    // ignore: unnecessary_null_comparison
+    if (currentLibrary == null || currentLibrary!.fileUri == null) return null;
 
     for (int i = treeNodeStack.length - 1; i >= 0; --i) {
       TreeNode node = treeNodeStack[i];
       if (withLocation && !_hasLocation(node)) continue;
       if (node.location?.file != null &&
-          node.location.file == currentLibrary.fileUri) {
+          node.location!.file == currentLibrary!.fileUri) {
         return node;
       }
     }
@@ -100,39 +100,43 @@
 
   static bool _hasLocation(TreeNode node) {
     return node.location != null &&
-        node.location.file != null &&
+        // ignore: unnecessary_null_comparison
+        node.location!.file != null &&
+        // ignore: unnecessary_null_comparison
         node.fileOffset != null &&
         node.fileOffset != -1;
   }
 
-  static bool _isInSameLibrary(Library library, TreeNode node) {
+  static bool _isInSameLibrary(Library? library, TreeNode node) {
     if (library == null) return false;
+    // ignore: unnecessary_null_comparison
     if (library.fileUri == null) return false;
     if (node.location == null) return false;
-    if (node.location.file == null) return false;
+    // ignore: unnecessary_null_comparison
+    if (node.location!.file == null) return false;
 
-    return library.fileUri == node.location.file;
+    return library.fileUri == node.location!.file;
   }
 
-  TreeNode get localContext {
-    TreeNode result = getSameLibraryLastSeenTreeNode(withLocation: true);
+  TreeNode? get localContext {
+    TreeNode? result = getSameLibraryLastSeenTreeNode(withLocation: true);
     if (result == null &&
         currentClassOrExtensionOrMember != null &&
-        _isInSameLibrary(currentLibrary, currentClassOrExtensionOrMember)) {
+        _isInSameLibrary(currentLibrary, currentClassOrExtensionOrMember!)) {
       result = currentClassOrExtensionOrMember;
     }
     return result;
   }
 
-  TreeNode get remoteContext {
-    TreeNode result = getLastSeenTreeNode(withLocation: true);
+  TreeNode? get remoteContext {
+    TreeNode? result = getLastSeenTreeNode(withLocation: true);
     if (result != null && _isInSameLibrary(currentLibrary, result)) {
       result = null;
     }
     return result;
   }
 
-  Uri checkLocation(TreeNode node, String name, Uri fileUri) {
+  Uri checkLocation(TreeNode node, String? name, Uri fileUri) {
     if (name == null || name.contains("#")) {
       // TODO(ahe): Investigate if these checks can be enabled:
       // if (node.fileUri != null && node is! Library) {
@@ -145,6 +149,7 @@
       // }
       return fileUri;
     } else {
+      // ignore: unnecessary_null_comparison
       if (fileUri == null) {
         problem(node, "'$name' has no fileUri", context: node);
         return fileUri;
@@ -157,7 +162,7 @@
   }
 
   void checkSuperInvocation(TreeNode node) {
-    Member containingMember = getContainingMember(node);
+    Member? containingMember = getContainingMember(node);
     if (containingMember == null) {
       problem(node, 'Super call outside of any member');
     } else {
@@ -168,7 +173,7 @@
     }
   }
 
-  Member getContainingMember(TreeNode node) {
+  Member? getContainingMember(TreeNode? node) {
     while (node != null) {
       if (node is Member) return node;
       node = node.parent;
@@ -177,24 +182,27 @@
   }
 
   @override
-  problem(TreeNode node, String details, {TreeNode context, TreeNode origin}) {
+  problem(TreeNode? node, String details,
+      {TreeNode? context, TreeNode? origin}) {
     node ??= (context ?? currentClassOrExtensionOrMember);
     int offset = node?.fileOffset ?? -1;
-    Uri file = node?.location?.file ?? fileUri;
-    Uri uri = file == null ? null : file;
-    LocatedMessage message = templateInternalProblemVerificationError
-        .withArguments(details)
-        .withLocation(uri, offset, noLength);
-    List<LocatedMessage> contextMessages;
+    Uri? file = node?.location?.file ?? fileUri;
+    Uri? uri = file == null ? null : file;
+    Message message =
+        templateInternalProblemVerificationError.withArguments(details);
+    LocatedMessage locatedMessage = uri != null
+        ? message.withLocation(uri, offset, noLength)
+        : message.withoutLocation();
+    List<LocatedMessage>? contextMessages;
     if (origin != null) {
       contextMessages = [
         messageVerificationErrorOriginContext.withLocation(
-            origin.location.file, origin.fileOffset, noLength)
+            origin.location!.file, origin.fileOffset, noLength)
       ];
     }
     CompilerContext.current
-        .report(message, Severity.error, context: contextMessages);
-    errors.add(message);
+        .report(locatedMessage, Severity.error, context: contextMessages);
+    errors.add(locatedMessage);
   }
 
   @override
@@ -202,7 +210,7 @@
     enterTreeNode(node);
     super.visitAsExpression(node);
     if (node.fileOffset == -1) {
-      TreeNode parent = node.parent;
+      TreeNode? parent = node.parent;
       while (parent != null) {
         if (parent.fileOffset != -1) break;
         parent = parent.parent;
@@ -315,8 +323,8 @@
 
   @override
   void defaultDartType(DartType node) {
-    final TreeNode localContext = this.localContext;
-    final TreeNode remoteContext = this.remoteContext;
+    final TreeNode? localContext = this.localContext;
+    final TreeNode? remoteContext = this.remoteContext;
 
     if (node is UnknownType) {
       problem(localContext, "Unexpected appearance of the unknown type.",
@@ -421,7 +429,7 @@
   void visitStaticInvocation(StaticInvocation node) {
     enterTreeNode(node);
     super.visitStaticInvocation(node);
-    RedirectingFactoryBody body = getRedirectingFactoryBody(node.target);
+    RedirectingFactoryBody? body = getRedirectingFactoryBody(node.target);
     if (body != null) {
       problem(node, "Attempt to invoke redirecting factory.");
     }
diff --git a/pkg/front_end/lib/src/fasta/loader.dart b/pkg/front_end/lib/src/fasta/loader.dart
index 4c0c277..31aea33 100644
--- a/pkg/front_end/lib/src/fasta/loader.dart
+++ b/pkg/front_end/lib/src/fasta/loader.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.loader;
 
 import 'dart:collection' show Queue;
@@ -84,19 +82,25 @@
 
   final Set<String> seenMessages = new Set<String>();
 
-  LibraryBuilder coreLibrary;
-  LibraryBuilder typedDataLibrary;
+  LibraryBuilder? _coreLibrary;
+  LibraryBuilder? typedDataLibrary;
 
   /// The first library that we've been asked to compile. When compiling a
   /// program (aka script), this is the library that should have a main method.
-  LibraryBuilder first;
+  LibraryBuilder? first;
 
   int byteCount = 0;
 
-  Uri currentUriForCrashReporting;
+  Uri? currentUriForCrashReporting;
 
   Loader(this.target);
 
+  LibraryBuilder get coreLibrary => _coreLibrary!;
+
+  void set coreLibrary(LibraryBuilder value) {
+    _coreLibrary = value;
+  }
+
   Ticker get ticker => target.ticker;
 
   Template<SummaryTemplate> get outlineSummaryTemplate;
@@ -115,19 +119,19 @@
   /// directive. If [accessor] isn't allowed to access [uri], it's a
   /// compile-time error.
   LibraryBuilder read(Uri uri, int charOffset,
-      {Uri fileUri,
-      LibraryBuilder accessor,
-      LibraryBuilder origin,
-      Library referencesFrom,
-      bool referenceIsPartOwner}) {
+      {Uri? fileUri,
+      LibraryBuilder? accessor,
+      LibraryBuilder? origin,
+      Library? referencesFrom,
+      bool? referenceIsPartOwner}) {
     LibraryBuilder builder = builders.putIfAbsent(uri, () {
       if (fileUri != null &&
-          (fileUri.scheme == "dart" ||
-              fileUri.scheme == "package" ||
-              fileUri.scheme == "dart-ext")) {
+          (fileUri!.scheme == "dart" ||
+              fileUri!.scheme == "package" ||
+              fileUri!.scheme == "dart-ext")) {
         fileUri = null;
       }
-      Package packageForLanguageVersion;
+      Package? packageForLanguageVersion;
       if (fileUri == null) {
         switch (uri.scheme) {
           case "package":
@@ -140,27 +144,28 @@
               packageForLanguageVersion = target.uriTranslator.getPackage(uri);
             } else {
               packageForLanguageVersion =
-                  target.uriTranslator.packages.packageOf(fileUri);
+                  target.uriTranslator.packages.packageOf(fileUri!);
             }
             break;
 
           default:
             fileUri = uri;
             packageForLanguageVersion =
-                target.uriTranslator.packages.packageOf(fileUri);
+                target.uriTranslator.packages.packageOf(fileUri!);
             break;
         }
       } else {
         packageForLanguageVersion =
-            target.uriTranslator.packages.packageOf(fileUri);
+            target.uriTranslator.packages.packageOf(fileUri!);
       }
-      src.LanguageVersion packageLanguageVersion;
-      Uri packageUri;
-      Message packageLanguageVersionProblem;
+      src.LanguageVersion? packageLanguageVersion;
+      Uri? packageUri;
+      Message? packageLanguageVersionProblem;
       if (packageForLanguageVersion != null) {
         Uri importUri = origin?.importUri ?? uri;
         if (importUri.scheme != 'dart' &&
             importUri.scheme != 'package' &&
+            // ignore: unnecessary_null_comparison
             packageForLanguageVersion.name != null) {
           packageUri =
               new Uri(scheme: 'package', path: packageForLanguageVersion.name);
@@ -171,18 +176,18 @@
             packageLanguageVersionProblem =
                 messageLanguageVersionInvalidInDotPackages;
             packageLanguageVersion = new src.InvalidLanguageVersion(
-                fileUri, 0, noLength, target.currentSdkVersion, false);
+                fileUri!, 0, noLength, target.currentSdkVersion, false);
           } else {
             Version version = new Version(
-                packageForLanguageVersion.languageVersion.major,
-                packageForLanguageVersion.languageVersion.minor);
+                packageForLanguageVersion.languageVersion!.major,
+                packageForLanguageVersion.languageVersion!.minor);
             if (version > target.currentSdkVersion) {
               packageLanguageVersionProblem =
                   templateLanguageVersionTooHigh.withArguments(
                       target.currentSdkVersion.major,
                       target.currentSdkVersion.minor);
               packageLanguageVersion = new src.InvalidLanguageVersion(
-                  fileUri, 0, noLength, target.currentSdkVersion, false);
+                  fileUri!, 0, noLength, target.currentSdkVersion, false);
             } else {
               packageLanguageVersion = new src.ImplicitLanguageVersion(version);
             }
@@ -192,9 +197,9 @@
       packageLanguageVersion ??=
           new src.ImplicitLanguageVersion(target.currentSdkVersion);
 
-      LibraryBuilder library = target.createLibraryBuilder(
+      LibraryBuilder? library = target.createLibraryBuilder(
           uri,
-          fileUri,
+          fileUri!,
           packageUri,
           packageLanguageVersion,
           origin,
@@ -212,13 +217,13 @@
 
       if (uri.scheme == "dart") {
         if (uri.path == "core") {
-          coreLibrary = library;
+          _coreLibrary = library;
         } else if (uri.path == "typed_data") {
           typedDataLibrary = library;
         }
       }
       if (library.loader != this) {
-        if (coreLibrary == library) {
+        if (_coreLibrary == library) {
           target.loadExtraRequiredLibraries(this);
         }
         // This library isn't owned by this loader, so no further processing
@@ -233,7 +238,7 @@
         firstSourceUri ??= uri;
         first ??= library;
       }
-      if (coreLibrary == library) {
+      if (_coreLibrary == library) {
         target.loadExtraRequiredLibraries(this);
       }
       Uri libraryUri = origin?.importUri ?? uri;
@@ -264,18 +269,18 @@
   }
 
   void ensureCoreLibrary() {
-    if (coreLibrary == null) {
+    if (_coreLibrary == null) {
       read(Uri.parse("dart:core"), 0, accessor: first);
       // TODO(askesc): When all backends support set literals, we no longer
       // need to index dart:collection, as it is only needed for desugaring of
       // const sets. We can remove it from this list at that time.
       read(Uri.parse("dart:collection"), 0, accessor: first);
-      assert(coreLibrary != null);
+      assert(_coreLibrary != null);
     }
   }
 
   Future<Null> buildBodies() async {
-    assert(coreLibrary != null);
+    assert(_coreLibrary != null);
     for (LibraryBuilder library in builders.values) {
       if (library.loader == this) {
         currentUriForCrashReporting = library.importUri;
@@ -317,13 +322,13 @@
 
   /// Register [message] as a problem with a severity determined by the
   /// intrinsic severity of the message.
-  FormattedMessage addProblem(
-      Message message, int charOffset, int length, Uri fileUri,
+  FormattedMessage? addProblem(
+      Message message, int charOffset, int length, Uri? fileUri,
       {bool wasHandled: false,
-      List<LocatedMessage> context,
-      Severity severity,
+      List<LocatedMessage>? context,
+      Severity? severity,
       bool problemOnLibrary: false,
-      List<Uri> involvedFiles}) {
+      List<Uri>? involvedFiles}) {
     return addMessage(message, charOffset, length, fileUri, severity,
         wasHandled: wasHandled,
         context: context,
@@ -342,12 +347,12 @@
   /// If [severity] is `Severity.error`, the message is added to
   /// [handledErrors] if [wasHandled] is true or to [unhandledErrors] if
   /// [wasHandled] is false.
-  FormattedMessage addMessage(Message message, int charOffset, int length,
-      Uri fileUri, Severity severity,
+  FormattedMessage? addMessage(Message message, int charOffset, int length,
+      Uri? fileUri, Severity? severity,
       {bool wasHandled: false,
-      List<LocatedMessage> context,
+      List<LocatedMessage>? context,
       bool problemOnLibrary: false,
-      List<Uri> involvedFiles}) {
+      List<Uri>? involvedFiles}) {
     severity ??= message.code.severity;
     if (severity == Severity.ignored) return null;
     String trace = """
@@ -365,11 +370,16 @@
           fileUri);
     }
     target.context.report(
-        message.withLocation(fileUri, charOffset, length), severity,
-        context: context, involvedFiles: involvedFiles);
+        fileUri != null
+            ? message.withLocation(fileUri, charOffset, length)
+            : message.withoutLocation(),
+        severity,
+        context: context,
+        involvedFiles: involvedFiles);
     if (severity == Severity.error) {
-      (wasHandled ? handledErrors : unhandledErrors)
-          .add(message.withLocation(fileUri, charOffset, length));
+      (wasHandled ? handledErrors : unhandledErrors).add(fileUri != null
+          ? message.withLocation(fileUri, charOffset, length)
+          : message.withoutLocation());
     }
     FormattedMessage formattedMessage = target.createFormattedMessage(
         message, charOffset, length, fileUri, context, severity,
@@ -397,8 +407,8 @@
   TypeBuilder computeTypeBuilder(DartType type);
 
   BodyBuilder createBodyBuilderForOutlineExpression(
-      LibraryBuilder library,
-      DeclarationBuilder declarationBuilder,
+      src.SourceLibraryBuilder library,
+      DeclarationBuilder? declarationBuilder,
       ModifierBuilder member,
       Scope scope,
       Uri fileUri) {
diff --git a/pkg/front_end/lib/src/fasta/scope.dart b/pkg/front_end/lib/src/fasta/scope.dart
index 68baf39..76daac6 100644
--- a/pkg/front_end/lib/src/fasta/scope.dart
+++ b/pkg/front_end/lib/src/fasta/scope.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.scope;
 
 import 'package:kernel/ast.dart';
@@ -66,20 +64,21 @@
   ///       Extension.staticMethod2();
   ///     }
   ///
-  Set<ExtensionBuilder> _extensions;
+  Set<ExtensionBuilder>? _extensions;
 
   /// The scope that this scope is nested within, or `null` if this is the top
   /// level scope.
-  Scope _parent;
+  Scope? _parent;
 
   final String classNameOrDebugName;
 
   MutableScope(this._local, this._setters, this._extensions, this._parent,
       this.classNameOrDebugName) {
+    // ignore: unnecessary_null_comparison
     assert(classNameOrDebugName != null);
   }
 
-  Scope get parent => _parent;
+  Scope? get parent => _parent;
 
   String toString() => "Scope($classNameOrDebugName, ${_local.keys})";
 }
@@ -89,18 +88,18 @@
   /// succeed.
   final bool isModifiable;
 
-  Map<String, JumpTarget> labels;
+  Map<String, JumpTarget>? labels;
 
-  Map<String, JumpTarget> forwardDeclaredLabels;
+  Map<String, JumpTarget>? forwardDeclaredLabels;
 
-  Map<String, int> usedNames;
+  Map<String, int>? usedNames;
 
   Scope(
-      {Map<String, Builder> local,
-      Map<String, MemberBuilder> setters,
-      Set<ExtensionBuilder> extensions,
-      Scope parent,
-      String debugName,
+      {required Map<String, Builder> local,
+      Map<String, MemberBuilder>? setters,
+      Set<ExtensionBuilder>? extensions,
+      Scope? parent,
+      required String debugName,
       this.isModifiable: true})
       : super(local, setters = setters ?? const <String, MemberBuilder>{},
             extensions, parent, debugName);
@@ -184,29 +183,31 @@
         // We start be collecting the relation between an existing getter/setter
         // and the getter/setter that will replace it. This information is used
         // below to handle all the different cases that can occur.
-        Builder existingGetter = _local[name];
-        LibraryBuilder replacementLibraryBuilderFromGetter;
-        Builder replacementGetterFromGetter;
-        Builder replacementSetterFromGetter;
+        Builder? existingGetter = _local[name];
+        LibraryBuilder? replacementLibraryBuilderFromGetter;
+        Builder? replacementGetterFromGetter;
+        Builder? replacementSetterFromGetter;
         if (existingGetter != null &&
             replacementMap.containsKey(existingGetter.parent)) {
-          replacementLibraryBuilderFromGetter = existingGetter.parent;
+          replacementLibraryBuilderFromGetter =
+              existingGetter.parent as LibraryBuilder;
           replacementGetterFromGetter =
-              replacementMap[replacementLibraryBuilderFromGetter][name];
+              replacementMap[replacementLibraryBuilderFromGetter]![name];
           replacementSetterFromGetter =
-              replacementMapSetters[replacementLibraryBuilderFromGetter][name];
+              replacementMapSetters[replacementLibraryBuilderFromGetter]![name];
         }
-        Builder existingSetter = _setters[name];
-        LibraryBuilder replacementLibraryBuilderFromSetter;
-        Builder replacementGetterFromSetter;
-        Builder replacementSetterFromSetter;
+        Builder? existingSetter = _setters[name];
+        LibraryBuilder? replacementLibraryBuilderFromSetter;
+        Builder? replacementGetterFromSetter;
+        Builder? replacementSetterFromSetter;
         if (existingSetter != null &&
             replacementMap.containsKey(existingSetter.parent)) {
-          replacementLibraryBuilderFromSetter = existingSetter.parent;
+          replacementLibraryBuilderFromSetter =
+              existingSetter.parent as LibraryBuilder;
           replacementGetterFromSetter =
-              replacementMap[replacementLibraryBuilderFromSetter][name];
+              replacementMap[replacementLibraryBuilderFromSetter]![name];
           replacementSetterFromSetter =
-              replacementMapSetters[replacementLibraryBuilderFromSetter][name];
+              replacementMapSetters[replacementLibraryBuilderFromSetter]![name];
         }
 
         if (existingGetter == null) {
@@ -237,14 +238,14 @@
           if (replacementSetterFromGetter != null) {
             // We might have had one implicitly from the getter. Use it here,
             // if so.
-            _setters[name] = replacementSetterFromGetter;
+            _setters[name] = replacementSetterFromGetter as MemberBuilder;
           }
         } else if (existingSetter.parent ==
             replacementLibraryBuilderFromSetter) {
           // The existing setter should be replaced.
           if (replacementSetterFromSetter != null) {
             // With a new setter.
-            _setters[name] = replacementSetterFromSetter;
+            _setters[name] = replacementSetterFromSetter as MemberBuilder;
           } else {
             // With `null`, i.e. removed. This means that the setter is
             // implicitly available through the getter. This happens when the
@@ -258,7 +259,7 @@
     }
     if (_extensions != null) {
       bool needsPatching = false;
-      for (ExtensionBuilder extensionBuilder in _extensions) {
+      for (ExtensionBuilder extensionBuilder in _extensions!) {
         if (replacementMap.containsKey(extensionBuilder.parent)) {
           needsPatching = true;
           break;
@@ -267,19 +268,20 @@
       if (needsPatching) {
         Set<ExtensionBuilder> extensionsReplacement =
             new Set<ExtensionBuilder>();
-        for (ExtensionBuilder extensionBuilder in _extensions) {
+        for (ExtensionBuilder extensionBuilder in _extensions!) {
           if (replacementMap.containsKey(extensionBuilder.parent)) {
-            assert(replacementMap[extensionBuilder.parent]
-                    [extensionBuilder.name] !=
+            assert(replacementMap[extensionBuilder.parent]![
+                    extensionBuilder.name] !=
                 null);
             extensionsReplacement.add(
-                replacementMap[extensionBuilder.parent][extensionBuilder.name]);
+                replacementMap[extensionBuilder.parent]![extensionBuilder.name]
+                    as ExtensionBuilder);
             break;
           } else {
             extensionsReplacement.add(extensionBuilder);
           }
         }
-        _extensions.clear();
+        _extensions!.clear();
         extensionsReplacement.addAll(extensionsReplacement);
       }
     }
@@ -301,8 +303,8 @@
   /// This scope becomes equivalent to [scope]. This is used for parts to
   /// become part of their library's scope.
   void becomePartOf(Scope scope) {
-    assert(_parent._parent == null);
-    assert(scope._parent._parent == null);
+    assert(_parent!._parent == null);
+    assert(scope._parent!._parent == null);
     super._local = scope._local;
     super._setters = scope._setters;
     super._parent = scope._parent;
@@ -313,7 +315,7 @@
     return new Scope.nested(this, debugName, isModifiable: isModifiable);
   }
 
-  Scope withTypeVariables(List<TypeVariableBuilder> typeVariables) {
+  Scope withTypeVariables(List<TypeVariableBuilder>? typeVariables) {
     if (typeVariables == null) return this;
     Scope newScope =
         new Scope.nested(this, "type variables", isModifiable: false);
@@ -345,13 +347,13 @@
       usedNames ??= <String, int>{};
       // Don't use putIfAbsent to avoid the context allocation needed
       // for the closure.
-      usedNames[name] ??= charOffset;
+      usedNames![name] ??= charOffset;
     }
   }
 
-  Builder lookupIn(String name, int charOffset, Uri fileUri,
+  Builder? lookupIn(String name, int charOffset, Uri fileUri,
       Map<String, Builder> map, bool isInstanceScope) {
-    Builder builder = map[name];
+    Builder? builder = map[name];
     if (builder == null) return null;
     if (builder.next != null) {
       return new AmbiguousBuilder(name.isEmpty ? classNameOrDebugName : name,
@@ -366,10 +368,10 @@
     }
   }
 
-  Builder lookup(String name, int charOffset, Uri fileUri,
+  Builder? lookup(String name, int charOffset, Uri fileUri,
       {bool isInstanceScope: true}) {
     recordUse(name, charOffset, fileUri);
-    Builder builder =
+    Builder? builder =
         lookupIn(name, charOffset, fileUri, _local, isInstanceScope);
     if (builder != null) return builder;
     builder = lookupIn(name, charOffset, fileUri, _setters, isInstanceScope);
@@ -383,10 +385,10 @@
     return builder ?? _parent?.lookup(name, charOffset, fileUri);
   }
 
-  Builder lookupSetter(String name, int charOffset, Uri fileUri,
+  Builder? lookupSetter(String name, int charOffset, Uri fileUri,
       {bool isInstanceScope: true}) {
     recordUse(name, charOffset, fileUri);
-    Builder builder =
+    Builder? builder =
         lookupIn(name, charOffset, fileUri, _setters, isInstanceScope);
     if (builder != null) return builder;
     builder = lookupIn(name, charOffset, fileUri, _local, isInstanceScope);
@@ -400,13 +402,13 @@
     return builder ?? _parent?.lookupSetter(name, charOffset, fileUri);
   }
 
-  Builder lookupLocalMember(String name, {bool setter}) {
+  Builder? lookupLocalMember(String name, {required bool setter}) {
     return setter ? _setters[name] : _local[name];
   }
 
-  void addLocalMember(String name, Builder member, {bool setter}) {
+  void addLocalMember(String name, Builder member, {required bool setter}) {
     if (setter) {
-      _setters[name] = member;
+      _setters[name] = member as MemberBuilder;
     } else {
       _local[name] = member;
     }
@@ -424,12 +426,13 @@
 
   Iterable<MemberBuilder> get localSetters => _setters.values;
 
-  bool hasLocalLabel(String name) => labels != null && labels.containsKey(name);
+  bool hasLocalLabel(String name) =>
+      labels != null && labels!.containsKey(name);
 
   void declareLabel(String name, JumpTarget target) {
     if (isModifiable) {
       labels ??= <String, JumpTarget>{};
-      labels[name] = target;
+      labels![name] = target;
     } else {
       internalProblem(
           messageInternalProblemExtendingUnmodifiableScope, -1, null);
@@ -439,24 +442,26 @@
   void forwardDeclareLabel(String name, JumpTarget target) {
     declareLabel(name, target);
     forwardDeclaredLabels ??= <String, JumpTarget>{};
-    forwardDeclaredLabels[name] = target;
+    forwardDeclaredLabels![name] = target;
   }
 
   bool claimLabel(String name) {
     if (forwardDeclaredLabels == null ||
-        forwardDeclaredLabels.remove(name) == null) return false;
-    if (forwardDeclaredLabels.length == 0) {
+        forwardDeclaredLabels!.remove(name) == null) {
+      return false;
+    }
+    if (forwardDeclaredLabels!.length == 0) {
       forwardDeclaredLabels = null;
     }
     return true;
   }
 
-  Map<String, JumpTarget> get unclaimedForwardDeclarations {
+  Map<String, JumpTarget>? get unclaimedForwardDeclarations {
     return forwardDeclaredLabels;
   }
 
-  Builder lookupLabel(String name) {
-    return (labels == null ? null : labels[name]) ?? _parent?.lookupLabel(name);
+  Builder? lookupLabel(String name) {
+    return labels?[name] ?? _parent?.lookupLabel(name);
   }
 
   /// Declares that the meaning of [name] in this scope is [builder].
@@ -465,12 +470,13 @@
   /// that can be used as context for reporting a compile-time error about
   /// [name] being used before its declared. [fileUri] is used to bind the
   /// location of this message.
-  LocatedMessage declare(String name, Builder builder, Uri fileUri) {
+  LocatedMessage? declare(String name, Builder builder, Uri fileUri) {
     if (isModifiable) {
-      if (usedNames?.containsKey(name) ?? false) {
+      int? offset = usedNames?[name];
+      if (offset != null) {
         return templateDuplicatedNamePreviouslyUsedCause
             .withArguments(name)
-            .withLocation(fileUri, usedNames[name], name.length);
+            .withLocation(fileUri, offset, name.length);
       }
       _local[name] = builder;
     } else {
@@ -483,7 +489,7 @@
   /// Adds [builder] to the extensions in this scope.
   void addExtension(ExtensionBuilder builder) {
     _extensions ??= <ExtensionBuilder>{};
-    _extensions.add(builder);
+    _extensions!.add(builder);
   }
 
   /// Calls [f] for each extension in this scope and parent scopes.
@@ -499,7 +505,7 @@
     Map<String, Builder> map = _local;
 
     void mergeMember(String name, Builder member) {
-      Builder existing = map[name];
+      Builder? existing = map[name];
       if (existing != null) {
         if (existing != member) {
           member = computeAmbiguousDeclaration(name, existing, member);
@@ -541,23 +547,21 @@
   }
 
   Scope computeMixinScope() {
-    List<String> names = this._local.keys.toList();
     Map<String, Builder> local = <String, Builder>{};
     bool needsCopy = false;
-    for (int i = 0; i < names.length; i++) {
-      String name = names[i];
-      Builder declaration = this._local[name];
+    for (MapEntry<String, Builder> entry in _local.entries) {
+      String name = entry.key;
+      Builder declaration = entry.value;
       if (declaration.isStatic) {
         needsCopy = true;
       } else {
         local[name] = declaration;
       }
     }
-    names = this._setters.keys.toList();
     Map<String, MemberBuilder> setters = <String, MemberBuilder>{};
-    for (int i = 0; i < names.length; i++) {
-      String name = names[i];
-      MemberBuilder declaration = this._setters[name];
+    for (MapEntry<String, MemberBuilder> entry in _setters.entries) {
+      String name = entry.key;
+      MemberBuilder declaration = entry.value;
       if (declaration.isStatic) {
         needsCopy = true;
       } else {
@@ -588,8 +592,8 @@
     local.forEach(f);
   }
 
-  Builder lookup(String name, int charOffset, Uri fileUri) {
-    Builder builder = local[name];
+  MemberBuilder? lookup(String name, int charOffset, Uri fileUri) {
+    MemberBuilder? builder = local[name];
     if (builder == null) return null;
     if (builder.next != null) {
       return new AmbiguousMemberBuilder(
@@ -604,7 +608,7 @@
 
 abstract class LazyScope extends Scope {
   LazyScope(Map<String, Builder> local, Map<String, MemberBuilder> setters,
-      Scope parent, String debugName, {bool isModifiable: true})
+      Scope? parent, String debugName, {bool isModifiable: true})
       : super(
             local: local,
             setters: setters,
@@ -628,7 +632,7 @@
   }
 
   @override
-  Set<ExtensionBuilder> get _extensions {
+  Set<ExtensionBuilder>? get _extensions {
     ensureScope();
     return super._extensions;
   }
@@ -643,7 +647,7 @@
     scope._local[name] = builder;
   }
 
-  void addSetter(String name, Builder builder) {
+  void addSetter(String name, MemberBuilder builder) {
     scope._setters[name] = builder;
   }
 
@@ -651,7 +655,7 @@
     scope.addExtension(builder);
   }
 
-  Builder operator [](String name) => scope._local[name];
+  Builder? operator [](String name) => scope._local[name];
 }
 
 class ConstructorScopeBuilder {
@@ -659,11 +663,11 @@
 
   ConstructorScopeBuilder(this.scope);
 
-  void addMember(String name, Builder builder) {
+  void addMember(String name, MemberBuilder builder) {
     scope.local[name] = builder;
   }
 
-  MemberBuilder operator [](String name) => scope.local[name];
+  MemberBuilder? operator [](String name) => scope.local[name];
 }
 
 abstract class ProblemBuilder extends BuilderImpl {
@@ -741,7 +745,7 @@
       : super(name, builder, charOffset, fileUri);
 
   @override
-  Builder get parent => null;
+  Builder? get parent => null;
 
   @override
   Message get message => templateDuplicatedDeclarationUse.withArguments(name);
@@ -751,7 +755,7 @@
   Builder getFirstDeclaration() {
     Builder declaration = builder;
     while (declaration.next != null) {
-      declaration = declaration.next;
+      declaration = declaration.next!;
     }
     return declaration;
   }
@@ -759,16 +763,16 @@
 
 mixin ErroneousMemberBuilderMixin implements MemberBuilder {
   @override
-  Member get member => null;
+  Member get member => throw new UnsupportedError('$runtimeType.member');
 
   @override
-  Member get readTarget => null;
+  Member? get readTarget => null;
 
   @override
-  Member get writeTarget => null;
+  Member? get writeTarget => null;
 
   @override
-  Member get invokeTarget => null;
+  Member? get invokeTarget => null;
 
   @override
   Iterable<Member> get exportedMembers => const [];
@@ -788,7 +792,7 @@
   bool get isConflictingSetter => false;
 
   @override
-  void set parent(Builder value) {
+  void set parent(Builder? value) {
     throw new UnsupportedError('AmbiguousMemberBuilder.parent=');
   }
 
@@ -799,7 +803,7 @@
 
   // TODO(johnniwinther): Remove this and create a [ProcedureBuilder] interface.
   @override
-  ProcedureKind get kind => null;
+  ProcedureKind? get kind => null;
 
   @override
   void buildOutlineExpressions(LibraryBuilder library, CoreTypes coreTypes,
@@ -823,11 +827,10 @@
 }
 
 class ScopeLocalDeclarationIterator implements Iterator<Builder> {
-  Iterator<Builder> local;
+  Iterator<Builder>? local;
   final Iterator<Builder> setters;
 
-  @override
-  Builder current;
+  Builder? _current;
 
   ScopeLocalDeclarationIterator(Scope scope)
       : local = scope._local.values.iterator,
@@ -835,35 +838,39 @@
 
   @override
   bool moveNext() {
-    Builder next = current?.next;
+    Builder? next = _current?.next;
     if (next != null) {
-      current = next;
+      _current = next;
       return true;
     }
     if (local != null) {
-      if (local.moveNext()) {
-        current = local.current;
+      if (local!.moveNext()) {
+        _current = local!.current;
         return true;
       }
       local = null;
     }
     if (setters.moveNext()) {
-      current = setters.current;
+      _current = setters.current;
       return true;
     } else {
-      current = null;
+      _current = null;
       return false;
     }
   }
+
+  @override
+  Builder get current {
+    return _current ?? (throw new StateError('No element'));
+  }
 }
 
 class ScopeLocalDeclarationNameIterator extends ScopeLocalDeclarationIterator
     implements NameIterator {
-  Iterator<String> localNames;
+  Iterator<String>? localNames;
   final Iterator<String> setterNames;
 
-  @override
-  String name;
+  String? _name;
 
   ScopeLocalDeclarationNameIterator(Scope scope)
       : localNames = scope._local.keys.iterator,
@@ -872,28 +879,33 @@
 
   @override
   bool moveNext() {
-    Builder next = current?.next;
+    Builder? next = _current?.next;
     if (next != null) {
-      current = next;
+      _current = next;
       return true;
     }
     if (local != null) {
-      if (local.moveNext()) {
-        localNames.moveNext();
-        current = local.current;
-        name = localNames.current;
+      if (local!.moveNext()) {
+        localNames!.moveNext();
+        _current = local!.current;
+        _name = localNames!.current;
         return true;
       }
       localNames = null;
     }
     if (setters.moveNext()) {
       setterNames.moveNext();
-      current = setters.current;
-      name = setterNames.current;
+      _current = setters.current;
+      _name = setterNames.current;
       return true;
     } else {
-      current = null;
+      _current = null;
       return false;
     }
   }
+
+  @override
+  String get name {
+    return _name ?? (throw new StateError('No element'));
+  }
 }
diff --git a/pkg/front_end/lib/src/fasta/source/diet_listener.dart b/pkg/front_end/lib/src/fasta/source/diet_listener.dart
index fb6af76..88490a6 100644
--- a/pkg/front_end/lib/src/fasta/source/diet_listener.dart
+++ b/pkg/front_end/lib/src/fasta/source/diet_listener.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.diet_listener;
 
 import 'package:_fe_analyzer_shared/src/parser/parser.dart'
@@ -35,7 +33,6 @@
 import '../builder/modifier_builder.dart';
 import '../builder/type_alias_builder.dart';
 import '../builder/type_builder.dart';
-import '../builder/type_declaration_builder.dart';
 
 import '../identifiers.dart' show QualifiedName;
 
@@ -87,8 +84,8 @@
   int importExportDirectiveIndex = 0;
   int partDirectiveIndex = 0;
 
-  DeclarationBuilder _currentDeclaration;
-  ClassBuilder _currentClass;
+  DeclarationBuilder? _currentDeclaration;
+  ClassBuilder? _currentClass;
   bool _inRedirectingFactory = false;
 
   bool currentClassIsParserRecovery = false;
@@ -113,9 +110,9 @@
         stringExpectedAfterNative =
             library.loader.target.backendTarget.nativeExtensionExpectsString;
 
-  DeclarationBuilder get currentDeclaration => _currentDeclaration;
+  DeclarationBuilder? get currentDeclaration => _currentDeclaration;
 
-  void set currentDeclaration(TypeDeclarationBuilder builder) {
+  void set currentDeclaration(DeclarationBuilder? builder) {
     if (builder == null) {
       _currentClass = _currentDeclaration = null;
     } else {
@@ -124,7 +121,7 @@
     }
   }
 
-  ClassBuilder get currentClass => _currentClass;
+  ClassBuilder? get currentClass => _currentClass;
 
   @override
   void endMetadataStar(int count) {
@@ -139,7 +136,7 @@
   }
 
   @override
-  void endMetadata(Token beginToken, Token periodBeforeName, Token endToken) {
+  void endMetadata(Token beginToken, Token? periodBeforeName, Token endToken) {
     debugEvent("Metadata");
     discard(periodBeforeName == null ? 1 : 2);
     push(beginToken);
@@ -180,7 +177,7 @@
   }
 
   @override
-  void handleType(Token beginToken, Token questionMark) {
+  void handleType(Token beginToken, Token? questionMark) {
     debugEvent("Type");
     discard(1);
   }
@@ -255,39 +252,40 @@
   }
 
   @override
-  void endFunctionType(Token functionToken, Token questionMark) {
+  void endFunctionType(Token functionToken, Token? questionMark) {
     debugEvent("FunctionType");
     discard(1);
   }
 
   @override
   void endFunctionTypeAlias(
-      Token typedefKeyword, Token equals, Token endToken) {
+      Token typedefKeyword, Token? equals, Token endToken) {
     debugEvent("FunctionTypeAlias");
 
     if (equals == null) pop(); // endToken
-    Object name = pop();
+    Object? name = pop();
     // Metadata is handled in [SourceTypeAliasBuilder.buildOutlineExpressions].
     pop(); // metadata
     checkEmpty(typedefKeyword.charOffset);
     if (name is ParserRecovery) return;
 
-    TypeAliasBuilder typedefBuilder = lookupBuilder(typedefKeyword, null, name);
+    Builder? typedefBuilder =
+        lookupBuilder(typedefKeyword, null, name as String);
     if (typedefBuilder is TypeAliasBuilder) {
-      TypeBuilder type = typedefBuilder.type;
+      TypeBuilder? type = typedefBuilder.type;
       if (type is FunctionTypeBuilder) {
-        List<FormalParameterBuilder> formals = type.formals;
+        List<FormalParameterBuilder>? formals = type.formals;
         if (formals != null) {
           for (int i = 0; i < formals.length; ++i) {
             FormalParameterBuilder formal = formals[i];
-            List<MetadataBuilder> metadata = formal.metadata;
+            List<MetadataBuilder>? metadata = formal.metadata;
             if (metadata != null && metadata.length > 0) {
               // [parseMetadata] is using [Parser.parseMetadataStar] under the
               // hood, so we only need the offset of the first annotation.
               Token metadataToken = tokenForOffset(
-                  typedefKeyword, endToken, metadata[0].charOffset);
+                  typedefKeyword, endToken, metadata[0].charOffset)!;
               List<Expression> annotations =
-                  parseMetadata(typedefBuilder, metadataToken, null);
+                  parseMetadata(typedefBuilder, metadataToken, null)!;
               if (formal.isPositional) {
                 VariableDeclaration parameter =
                     typedefBuilder.typedef.positionalParameters[i];
@@ -318,12 +316,12 @@
 
   @override
   void endClassFields(
-      Token abstractToken,
-      Token externalToken,
-      Token staticToken,
-      Token covariantToken,
-      Token lateToken,
-      Token varFinalOrConst,
+      Token? abstractToken,
+      Token? externalToken,
+      Token? staticToken,
+      Token? covariantToken,
+      Token? lateToken,
+      Token? varFinalOrConst,
       int count,
       Token beginToken,
       Token endToken) {
@@ -332,21 +330,22 @@
   }
 
   @override
-  void handleAsyncModifier(Token asyncToken, Token startToken) {
+  void handleAsyncModifier(Token? asyncToken, Token? starToken) {
     debugEvent("AsyncModifier");
   }
 
   @override
-  void endTopLevelMethod(Token beginToken, Token getOrSet, Token endToken) {
+  void endTopLevelMethod(Token beginToken, Token? getOrSet, Token endToken) {
     debugEvent("TopLevelMethod");
-    Token bodyToken = pop();
-    Object name = pop();
-    Token metadata = pop();
+    Token bodyToken = pop() as Token;
+    Object? name = pop();
+    Token metadata = pop() as Token;
     checkEmpty(beginToken.charOffset);
     if (name is ParserRecovery) return;
 
-    final StackListenerImpl listener =
-        createFunctionListener(lookupBuilder(beginToken, getOrSet, name));
+    final StackListenerImpl listener = createFunctionListener(
+        lookupBuilder(beginToken, getOrSet, name as String)
+            as FunctionBuilderImpl);
     buildFunctionBody(listener, bodyToken, metadata, MemberKind.TopLevelMethod);
   }
 
@@ -357,11 +356,11 @@
 
   @override
   void endTopLevelFields(
-      Token externalToken,
-      Token staticToken,
-      Token covariantToken,
-      Token lateToken,
-      Token varFinalOrConst,
+      Token? externalToken,
+      Token? staticToken,
+      Token? covariantToken,
+      Token? lateToken,
+      Token? varFinalOrConst,
       int count,
       Token beginToken,
       Token endToken) {
@@ -401,15 +400,15 @@
       ]),
     ]));
     debugEvent("handleQualified");
-    Object suffix = pop();
-    Object prefix = pop();
+    Object? suffix = pop();
+    Object? prefix = pop();
     if (prefix is ParserRecovery) {
       push(prefix);
     } else if (suffix is ParserRecovery) {
       push(suffix);
     } else {
-      assert(identical(suffix, period.next.lexeme));
-      push(new QualifiedName(prefix, period.next));
+      assert(identical(suffix, period.next!.lexeme));
+      push(new QualifiedName(prefix!, period.next!));
     }
   }
 
@@ -457,7 +456,7 @@
   }
 
   @override
-  void endConditionalUri(Token ifKeyword, Token leftParen, Token equalSign) {
+  void endConditionalUri(Token ifKeyword, Token leftParen, Token? equalSign) {
     debugEvent("ConditionalUri");
   }
 
@@ -500,23 +499,23 @@
   }
 
   @override
-  void handleImportPrefix(Token deferredKeyword, Token asKeyword) {
+  void handleImportPrefix(Token? deferredKeyword, Token? asKeyword) {
     debugEvent("ImportPrefix");
     pushIfNull(asKeyword, NullValue.Prefix);
   }
 
   @override
-  void endImport(Token importKeyword, Token semicolon) {
+  void endImport(Token importKeyword, Token? semicolon) {
     debugEvent("Import");
-    Object name = pop(NullValue.Prefix);
+    Object? name = pop(NullValue.Prefix);
 
-    Token metadata = pop();
+    Token metadata = pop() as Token;
     checkEmpty(importKeyword.charOffset);
     if (name is ParserRecovery) return;
 
     // Native imports must be skipped because they aren't assigned corresponding
     // LibraryDependency nodes.
-    Token importUriToken = importKeyword.next;
+    Token importUriToken = importKeyword.next!;
     String importUri =
         unescapeString(importUriToken.lexeme, importUriToken, this);
     if (importUri.startsWith("dart-ext:")) return;
@@ -528,7 +527,7 @@
   }
 
   @override
-  void handleRecoverImport(Token semicolon) {
+  void handleRecoverImport(Token? semicolon) {
     pop(NullValue.Prefix);
   }
 
@@ -536,7 +535,7 @@
   void endExport(Token exportKeyword, Token semicolon) {
     debugEvent("Export");
 
-    Token metadata = pop();
+    Token metadata = pop() as Token;
     Library libraryNode = libraryBuilder.library;
     LibraryDependency dependency =
         libraryNode.dependencies[importExportDirectiveIndex++];
@@ -547,7 +546,7 @@
   void endPart(Token partKeyword, Token semicolon) {
     debugEvent("Part");
 
-    Token metadata = pop();
+    Token metadata = pop() as Token;
     Library libraryNode = libraryBuilder.library;
     if (libraryNode.parts.length > partDirectiveIndex) {
       // If partDirectiveIndex >= libraryNode.parts.length we are in a case of
@@ -567,7 +566,7 @@
 
   @override
   void endTypeVariable(
-      Token token, int index, Token extendsOrSuper, Token variance) {
+      Token token, int index, Token? extendsOrSuper, Token? variance) {
     debugEvent("endTypeVariable");
   }
 
@@ -578,7 +577,7 @@
 
   @override
   void endConstructorReference(
-      Token start, Token periodBeforeName, Token endToken) {
+      Token start, Token? periodBeforeName, Token endToken) {
     debugEvent("ConstructorReference");
     popIfNotNull(periodBeforeName);
   }
@@ -587,13 +586,14 @@
   void endClassFactoryMethod(
       Token beginToken, Token factoryKeyword, Token endToken) {
     debugEvent("ClassFactoryMethod");
-    Token bodyToken = pop();
-    Object name = pop();
-    Token metadata = pop();
+    Token bodyToken = pop() as Token;
+    Object? name = pop();
+    Token metadata = pop() as Token;
     checkEmpty(beginToken.charOffset);
     if (name is ParserRecovery || currentClassIsParserRecovery) return;
 
-    FunctionBuilder builder = lookupConstructor(beginToken, name);
+    FunctionBuilderImpl builder =
+        lookupConstructor(beginToken, name!) as FunctionBuilderImpl;
     if (_inRedirectingFactory) {
       buildRedirectingFactoryMethod(
           bodyToken, builder, MemberKind.Factory, metadata);
@@ -615,8 +615,8 @@
   }
 
   @override
-  void endExtensionConstructor(Token getOrSet, Token beginToken,
-      Token beginParam, Token beginInitializers, Token endToken) {
+  void endExtensionConstructor(Token? getOrSet, Token beginToken,
+      Token beginParam, Token? beginInitializers, Token endToken) {
     debugEvent("ExtensionConstructor");
     pop(); // bodyToken
     pop(); // name
@@ -657,56 +657,57 @@
   }
 
   @override
-  void endClassMethod(Token getOrSet, Token beginToken, Token beginParam,
-      Token beginInitializers, Token endToken) {
+  void endClassMethod(Token? getOrSet, Token beginToken, Token beginParam,
+      Token? beginInitializers, Token endToken) {
     _endClassMethod(
         getOrSet, beginToken, beginParam, beginInitializers, endToken, false);
   }
 
   @override
-  void endClassConstructor(Token getOrSet, Token beginToken, Token beginParam,
-      Token beginInitializers, Token endToken) {
+  void endClassConstructor(Token? getOrSet, Token beginToken, Token beginParam,
+      Token? beginInitializers, Token endToken) {
     _endClassMethod(
         getOrSet, beginToken, beginParam, beginInitializers, endToken, true);
   }
 
   @override
-  void endMixinMethod(Token getOrSet, Token beginToken, Token beginParam,
-      Token beginInitializers, Token endToken) {
+  void endMixinMethod(Token? getOrSet, Token beginToken, Token beginParam,
+      Token? beginInitializers, Token endToken) {
     _endClassMethod(
         getOrSet, beginToken, beginParam, beginInitializers, endToken, false);
   }
 
   @override
-  void endExtensionMethod(Token getOrSet, Token beginToken, Token beginParam,
-      Token beginInitializers, Token endToken) {
+  void endExtensionMethod(Token? getOrSet, Token beginToken, Token beginParam,
+      Token? beginInitializers, Token endToken) {
     _endClassMethod(
         getOrSet, beginToken, beginParam, beginInitializers, endToken, false);
   }
 
   @override
-  void endMixinConstructor(Token getOrSet, Token beginToken, Token beginParam,
-      Token beginInitializers, Token endToken) {
+  void endMixinConstructor(Token? getOrSet, Token beginToken, Token beginParam,
+      Token? beginInitializers, Token endToken) {
     _endClassMethod(
         getOrSet, beginToken, beginParam, beginInitializers, endToken, true);
   }
 
-  void _endClassMethod(Token getOrSet, Token beginToken, Token beginParam,
-      Token beginInitializers, Token endToken, bool isConstructor) {
+  void _endClassMethod(Token? getOrSet, Token beginToken, Token beginParam,
+      Token? beginInitializers, Token endToken, bool isConstructor) {
     debugEvent("Method");
     // TODO(danrubel): Consider removing the beginParam parameter
     // and using bodyToken, but pushing a NullValue on the stack
     // in handleNoFormalParameters rather than the supplied token.
     pop(); // bodyToken
-    Object name = pop();
-    Token metadata = pop();
+    Object? name = pop();
+    Token metadata = pop() as Token;
     checkEmpty(beginToken.charOffset);
     if (name is ParserRecovery || currentClassIsParserRecovery) return;
-    FunctionBuilder builder;
+    FunctionBuilderImpl builder;
     if (isConstructor) {
-      builder = lookupConstructor(beginToken, name);
+      builder = lookupConstructor(beginToken, name!) as FunctionBuilderImpl;
     } else {
-      builder = lookupBuilder(beginToken, getOrSet, name);
+      builder = lookupBuilder(beginToken, getOrSet, name as String)
+          as FunctionBuilderImpl;
     }
     buildFunctionBody(
         createFunctionListener(builder),
@@ -718,18 +719,18 @@
   }
 
   StackListenerImpl createListener(ModifierBuilder builder, Scope memberScope,
-      {bool isDeclarationInstanceMember,
-      VariableDeclaration extensionThis,
-      List<TypeParameter> extensionTypeParameters,
-      Scope formalParameterScope,
-      InferenceDataForTesting inferenceDataForTesting}) {
+      {required bool isDeclarationInstanceMember,
+      VariableDeclaration? extensionThis,
+      List<TypeParameter>? extensionTypeParameters,
+      Scope? formalParameterScope,
+      InferenceDataForTesting? inferenceDataForTesting}) {
     // Note: we set thisType regardless of whether we are building a static
     // member, since that provides better error recovery.
     // TODO(johnniwinther): Provide a dummy this on static extension methods
     // for better error recovery?
-    InterfaceType thisType =
+    InterfaceType? thisType =
         extensionThis == null ? currentDeclaration?.thisType : null;
-    TypeInferrer typeInferrer = typeInferenceEngine?.createLocalTypeInferrer(
+    TypeInferrer typeInferrer = typeInferenceEngine.createLocalTypeInferrer(
         uri, thisType, libraryBuilder, inferenceDataForTesting);
     ConstantContext constantContext = builder.isConstructor && builder.isConst
         ? ConstantContext.inferred
@@ -748,10 +749,10 @@
   StackListenerImpl createListenerInternal(
       ModifierBuilder builder,
       Scope memberScope,
-      Scope formalParameterScope,
+      Scope? formalParameterScope,
       bool isDeclarationInstanceMember,
-      VariableDeclaration extensionThis,
-      List<TypeParameter> extensionTypeParameters,
+      VariableDeclaration? extensionThis,
+      List<TypeParameter>? extensionTypeParameters,
       TypeInferrer typeInferrer,
       ConstantContext constantContext) {
     return new BodyBuilder(
@@ -775,7 +776,9 @@
         builder.computeTypeParameterScope(memberScope);
     final Scope formalParameterScope =
         builder.computeFormalParameterScope(typeParameterScope);
+    // ignore: unnecessary_null_comparison
     assert(typeParameterScope != null);
+    // ignore: unnecessary_null_comparison
     assert(formalParameterScope != null);
     return createListener(builder, typeParameterScope,
         isDeclarationInstanceMember: builder.isDeclarationInstanceMember,
@@ -785,8 +788,8 @@
         inferenceDataForTesting: builder.dataForTesting?.inferenceData);
   }
 
-  void buildRedirectingFactoryMethod(
-      Token token, FunctionBuilder builder, MemberKind kind, Token metadata) {
+  void buildRedirectingFactoryMethod(Token token, FunctionBuilderImpl builder,
+      MemberKind kind, Token? metadata) {
     final StackListenerImpl listener = createFunctionListener(builder);
     try {
       Parser parser = new Parser(listener);
@@ -798,7 +801,7 @@
       token = parser.parseFormalParametersOpt(
           parser.syntheticPreviousToken(token), MemberKind.Factory);
       listener.pop(); // Pops formal parameters.
-      listener.checkEmpty(token.next.charOffset);
+      listener.checkEmpty(token.next!.charOffset);
     } on DebugAbort {
       rethrow;
     } catch (e, s) {
@@ -807,12 +810,13 @@
   }
 
   void buildFields(int count, Token token, bool isTopLevel) {
-    List<String> names = const FixedNullableList<String>().pop(stack, count);
-    Token metadata = pop();
+    List<String?>? names = const FixedNullableList<String>().pop(stack, count);
+    Token? metadata = pop() as Token?;
     checkEmpty(token.charOffset);
     if (names == null || currentClassIsParserRecovery) return;
 
-    SourceFieldBuilder declaration = lookupBuilder(token, null, names.first);
+    SourceFieldBuilder declaration =
+        lookupBuilder(token, null, names.first!) as SourceFieldBuilder;
     // TODO(paulberry): don't re-parse the field if we've already parsed it
     // for type inference.
     parseFields(
@@ -841,7 +845,7 @@
 
   @override
   void endAssert(Token assertKeyword, Assert kind, Token leftParenthesis,
-      Token commaToken, Token semicolonToken) {
+      Token? commaToken, Token semicolonToken) {
     debugEvent("Assert");
     // Do nothing
   }
@@ -854,8 +858,8 @@
       ValueKinds.TokenOrNull
     ]));
     debugEvent("beginClassOrMixinBody");
-    Token beginToken = pop();
-    Object name = pop();
+    Token beginToken = pop() as Token;
+    Object? name = pop();
     pop(); // Annotation begin token.
     assert(currentDeclaration == null);
     assert(memberScope == libraryBuilder.scope);
@@ -863,8 +867,9 @@
       currentClassIsParserRecovery = true;
       return;
     }
-    currentDeclaration = lookupBuilder(beginToken, null, name);
-    memberScope = currentDeclaration.scope;
+    currentDeclaration =
+        lookupBuilder(beginToken, null, name as String) as DeclarationBuilder;
+    memberScope = currentDeclaration!.scope;
   }
 
   @override
@@ -877,7 +882,7 @@
   }
 
   @override
-  void beginClassDeclaration(Token begin, Token abstractToken, Token name) {
+  void beginClassDeclaration(Token begin, Token? abstractToken, Token name) {
     debugEvent("beginClassDeclaration");
     push(begin);
   }
@@ -901,7 +906,7 @@
   }
 
   @override
-  void beginExtensionDeclaration(Token extensionKeyword, Token nameToken) {
+  void beginExtensionDeclaration(Token extensionKeyword, Token? nameToken) {
     debugEvent("beginExtensionDeclaration");
     String name = nameToken?.lexeme ??
         // Synthesized name used internally.
@@ -911,7 +916,7 @@
   }
 
   @override
-  void endExtensionDeclaration(Token extensionKeyword, Token typeKeyword,
+  void endExtensionDeclaration(Token extensionKeyword, Token? typeKeyword,
       Token onKeyword, Token endToken) {
     debugEvent("endExtensionDeclaration");
     checkEmpty(extensionKeyword.charOffset);
@@ -928,7 +933,7 @@
 
   @override
   void endNamedMixinApplication(Token beginToken, Token classKeyword,
-      Token equals, Token implementsKeyword, Token endToken) {
+      Token equals, Token? implementsKeyword, Token endToken) {
     debugEvent("NamedMixinApplication");
 
     pop(); // Name.
@@ -936,7 +941,8 @@
     checkEmpty(beginToken.charOffset);
   }
 
-  AsyncMarker getAsyncMarker(StackListenerImpl listener) => listener.pop();
+  AsyncMarker? getAsyncMarker(StackListenerImpl listener) =>
+      listener.pop() as AsyncMarker?;
 
   /// Invokes the listener's [finishFunction] method.
   ///
@@ -957,12 +963,12 @@
   /// This is a separate method so that it may be overridden by a derived class
   /// if more computation must be done before finishing the function.
   void listenerFinishFields(StackListenerImpl listener, Token startToken,
-      Token metadata, bool isTopLevel) {
+      Token? metadata, bool isTopLevel) {
     listener.finishFields();
   }
 
   void buildFunctionBody(StackListenerImpl listener, Token startToken,
-      Token metadata, MemberKind kind) {
+      Token? metadata, MemberKind kind) {
     Token token = startToken;
     try {
       Parser parser = new Parser(listener);
@@ -972,8 +978,8 @@
       }
       token = parser.parseFormalParametersOpt(
           parser.syntheticPreviousToken(token), kind);
-      Object formals = listener.pop();
-      listener.checkEmpty(token.next.charOffset);
+      Object? formals = listener.pop();
+      listener.checkEmpty(token.next!.charOffset);
       token = parser.parseInitializersOpt(token);
       token = parser.parseAsyncModifierOpt(token);
       AsyncMarker asyncModifier = getAsyncMarker(listener) ?? AsyncMarker.Sync;
@@ -985,7 +991,7 @@
       bool isExpression = false;
       bool allowAbstract = asyncModifier == AsyncMarker.Sync;
       parser.parseFunctionBody(token, isExpression, allowAbstract);
-      Object body = listener.pop();
+      Object? body = listener.pop();
       listener.checkEmpty(token.charOffset);
       listenerFinishFunction(
           listener, startToken, kind, formals, asyncModifier, body);
@@ -996,23 +1002,24 @@
     }
   }
 
-  void parseFields(StackListenerImpl listener, Token startToken, Token metadata,
-      bool isTopLevel) {
+  void parseFields(StackListenerImpl listener, Token startToken,
+      Token? metadata, bool isTopLevel) {
     Token token = startToken;
     Parser parser = new Parser(listener);
     if (isTopLevel) {
       token = parser.parseTopLevelMember(metadata ?? token);
     } else {
       // TODO(danrubel): disambiguate between class/mixin/extension members
-      token = parser.parseClassMember(metadata ?? token, null).next;
+      token = parser.parseClassMember(metadata ?? token, null).next!;
     }
     listenerFinishFields(listener, startToken, metadata, isTopLevel);
     listener.checkEmpty(token.charOffset);
   }
 
-  Builder lookupBuilder(Token token, Token getOrSet, String name) {
+  Builder? lookupBuilder(Token token, Token? getOrSet, String name) {
     // TODO(ahe): Can I move this to Scope or ScopeBuilder?
-    Builder declaration;
+    Builder? declaration;
+    DeclarationBuilder? currentDeclaration = this.currentDeclaration;
     if (currentDeclaration != null) {
       if (uri != currentDeclaration.fileUri) {
         unexpected("$uri", "${currentDeclaration.fileUri}",
@@ -1036,31 +1043,33 @@
     return declaration;
   }
 
-  Builder lookupConstructor(Token token, Object nameOrQualified) {
+  Builder? lookupConstructor(Token token, Object nameOrQualified) {
     assert(currentClass != null);
-    Builder declaration;
+    Builder? declaration;
     String suffix;
     if (nameOrQualified is QualifiedName) {
       suffix = nameOrQualified.name;
     } else {
-      suffix = nameOrQualified == currentClass.name ? "" : nameOrQualified;
+      suffix = nameOrQualified == currentClass!.name
+          ? ""
+          : nameOrQualified as String;
     }
-    declaration = currentClass.constructors.local[suffix];
+    declaration = currentClass!.constructors.local[suffix];
     declaration = handleDuplicatedName(declaration, token);
     checkBuilder(token, declaration, nameOrQualified);
     return declaration;
   }
 
-  Builder handleDuplicatedName(Builder declaration, Token token) {
+  Builder? handleDuplicatedName(Builder? declaration, Token token) {
     int offset = token.charOffset;
     if (declaration?.next == null) {
       return declaration;
     } else {
-      Builder nearestDeclaration;
+      Builder? nearestDeclaration;
       int minDistance = -1;
       do {
         // Only look at declarations from this file (part).
-        if (uri == declaration.fileUri) {
+        if (uri == declaration!.fileUri) {
           // [distance] will always be non-negative as we ensure [token] is
           // always at the beginning of the declaration. The minimum distance
           // will often be larger than 0, for example, in a class declaration
@@ -1080,7 +1089,7 @@
     }
   }
 
-  void checkBuilder(Token token, Builder declaration, Object name) {
+  void checkBuilder(Token token, Builder? declaration, Object name) {
     if (declaration == null) {
       internalProblem(templateInternalProblemNotFound.withArguments("$name"),
           token.charOffset, uri);
@@ -1093,7 +1102,7 @@
 
   @override
   void addProblem(Message message, int charOffset, int length,
-      {bool wasHandled: false, List<LocatedMessage> context}) {
+      {bool wasHandled: false, List<LocatedMessage>? context}) {
     libraryBuilder.addProblem(message, charOffset, length, uri,
         wasHandled: wasHandled, context: context);
   }
@@ -1105,8 +1114,8 @@
 
   /// If the [metadata] is not `null`, return the parsed metadata [Expression]s.
   /// Otherwise, return `null`.
-  List<Expression> parseMetadata(
-      ModifierBuilder builder, Token metadata, Annotatable parent) {
+  List<Expression>? parseMetadata(
+      ModifierBuilder builder, Token? metadata, Annotatable? parent) {
     if (metadata != null) {
       StackListenerImpl listener = createListener(builder, memberScope,
           isDeclarationInstanceMember: false);
@@ -1120,7 +1129,7 @@
   /// Returns [Token] found between [start] (inclusive) and [end]
   /// (non-inclusive) that has its [Token.charOffset] equal to [offset].  If
   /// there is no such token, null is returned.
-  Token tokenForOffset(Token start, Token end, int offset) {
+  Token? tokenForOffset(Token start, Token end, int offset) {
     if (offset < start.charOffset || offset >= end.charOffset) {
       return null;
     }
@@ -1128,7 +1137,7 @@
       if (offset == start.charOffset) {
         return start;
       }
-      start = start.next;
+      start = start.next!;
     }
     return null;
   }
@@ -1138,18 +1147,18 @@
   /// [start] and [end] for the given offset, the corresponding item in the
   /// resulting list is set to null.  [offsets] are assumed to be in ascending
   /// order.
-  List<Token> tokensForOffsets(Token start, Token end, List<int> offsets) {
-    List<Token> result =
-        new List<Token>.filled(offsets.length, null, growable: false);
+  List<Token?> tokensForOffsets(Token start, Token end, List<int> offsets) {
+    List<Token?> result =
+        new List<Token?>.filled(offsets.length, null, growable: false);
     for (int i = 0; start != end && i < offsets.length;) {
       int offset = offsets[i];
       if (offset < start.charOffset) {
         ++i;
       } else if (offset == start.charOffset) {
         result[i] = start;
-        start = start.next;
+        start = start.next!;
       } else {
-        start = start.next;
+        start = start.next!;
       }
     }
     return result;
diff --git a/pkg/front_end/lib/src/fasta/source/outline_builder.dart b/pkg/front_end/lib/src/fasta/source/outline_builder.dart
index 1b40d03..ec8bc6f 100644
--- a/pkg/front_end/lib/src/fasta/source/outline_builder.dart
+++ b/pkg/front_end/lib/src/fasta/source/outline_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.outline_builder;
 
 import 'package:_fe_analyzer_shared/src/parser/parser.dart'
@@ -53,6 +51,7 @@
 import '../ignored_parser_errors.dart' show isIgnoredParserError;
 
 import '../kernel/type_algorithms.dart';
+import '../kernel/utils.dart';
 
 import '../modifier.dart'
     show
@@ -110,7 +109,7 @@
   bool inConstructorName = false;
   int importIndex = 0;
 
-  String nativeMethodName;
+  String? nativeMethodName;
 
   /// Counter used for naming unnamed extension declarations.
   int unnamedExtensionCounter = 0;
@@ -125,26 +124,28 @@
   @override
   Uri get uri => libraryBuilder.fileUri;
 
-  int popCharOffset() => pop();
+  int popCharOffset() => pop() as int;
 
-  List<String> popIdentifierList(int count) {
+  List<String>? popIdentifierList(int count) {
     if (count == 0) return null;
-    List<String> list = new List<String>.filled(count, null);
+    List<String> list = new List<String>.filled(
+        count,
+        /* dummyValue = */ '');
     bool isParserRecovery = false;
     for (int i = count - 1; i >= 0; i--) {
       popCharOffset();
-      Object identifier = pop();
+      Object? identifier = pop();
       if (identifier is ParserRecovery) {
         isParserRecovery = true;
       } else {
-        list[i] = identifier;
+        list[i] = identifier as String;
       }
     }
     return isParserRecovery ? null : list;
   }
 
   @override
-  void endMetadata(Token beginToken, Token periodBeforeName, Token endToken) {
+  void endMetadata(Token beginToken, Token? periodBeforeName, Token endToken) {
     debugEvent("Metadata");
     pop(); // arguments
     if (periodBeforeName != null) {
@@ -153,7 +154,7 @@
     }
     pop(); // type arguments
     pop(); // offset
-    Object sentinel = pop(); // prefix or constructor
+    Object? sentinel = pop(); // prefix or constructor
     push(sentinel is ParserRecovery
         ? sentinel
         : new MetadataBuilder(beginToken));
@@ -175,49 +176,50 @@
   @override
   void endHide(Token hideKeyword) {
     debugEvent("Hide");
-    Object names = pop();
+    Object? names = pop();
     if (names is ParserRecovery) {
       push(names);
     } else {
-      push(new Combinator.hide(
-          names, hideKeyword.charOffset, libraryBuilder.fileUri));
+      push(new Combinator.hide(names as Iterable<String>,
+          hideKeyword.charOffset, libraryBuilder.fileUri));
     }
   }
 
   @override
   void endShow(Token showKeyword) {
     debugEvent("Show");
-    Object names = pop();
+    Object? names = pop();
     if (names is ParserRecovery) {
       push(names);
     } else {
-      push(new Combinator.show(
-          names, showKeyword.charOffset, libraryBuilder.fileUri));
+      push(new Combinator.show(names as Iterable<String>,
+          showKeyword.charOffset, libraryBuilder.fileUri));
     }
   }
 
   @override
   void endCombinators(int count) {
     debugEvent("Combinators");
-    push(const FixedNullableList<Combinator>().pop(stack, count) ??
+    push(const FixedNullableList<Combinator>()
+            .popNonNullable(stack, count, dummyCombinator) ??
         NullValue.Combinators);
   }
 
   @override
   void endExport(Token exportKeyword, Token semicolon) {
     debugEvent("Export");
-    List<Combinator> combinators = pop();
-    List<Configuration> configurations = pop();
+    List<Combinator>? combinators = pop() as List<Combinator>?;
+    List<Configuration>? configurations = pop() as List<Configuration>?;
     int uriOffset = popCharOffset();
-    String uri = pop();
-    List<MetadataBuilder> metadata = pop();
+    String uri = pop() as String;
+    List<MetadataBuilder>? metadata = pop() as List<MetadataBuilder>?;
     libraryBuilder.addExport(metadata, uri, configurations, combinators,
         exportKeyword.charOffset, uriOffset);
     checkEmpty(exportKeyword.charOffset);
   }
 
   @override
-  void handleImportPrefix(Token deferredKeyword, Token asKeyword) {
+  void handleImportPrefix(Token? deferredKeyword, Token? asKeyword) {
     debugEvent("ImportPrefix");
     if (asKeyword == null) {
       // If asKeyword is null, then no prefix has been pushed on the stack.
@@ -229,23 +231,24 @@
   }
 
   @override
-  void endImport(Token importKeyword, Token semicolon) {
+  void endImport(Token importKeyword, Token? semicolon) {
     debugEvent("EndImport");
-    List<Combinator> combinators = pop();
-    bool isDeferred = pop();
-    int prefixOffset = pop();
-    Object prefix = pop(NullValue.Prefix);
-    List<Configuration> configurations = pop();
+    List<Combinator>? combinators = pop() as List<Combinator>?;
+    bool isDeferred = pop() as bool;
+    int prefixOffset = popCharOffset();
+    Object? prefix = pop(NullValue.Prefix);
+    List<Configuration>? configurations = pop() as List<Configuration>?;
     int uriOffset = popCharOffset();
-    String uri = pop(); // For a conditional import, this is the default URI.
-    List<MetadataBuilder> metadata = pop();
+    String uri =
+        pop() as String; // For a conditional import, this is the default URI.
+    List<MetadataBuilder>? metadata = pop() as List<MetadataBuilder>?;
     checkEmpty(importKeyword.charOffset);
     if (prefix is ParserRecovery) return;
     libraryBuilder.addImport(
         metadata,
         uri,
         configurations,
-        prefix,
+        prefix as String?,
         combinators,
         isDeferred,
         importKeyword.charOffset,
@@ -262,24 +265,24 @@
   }
 
   @override
-  void endConditionalUri(Token ifKeyword, Token leftParen, Token equalSign) {
+  void endConditionalUri(Token ifKeyword, Token leftParen, Token? equalSign) {
     debugEvent("EndConditionalUri");
     int charOffset = popCharOffset();
-    String uri = pop();
+    String uri = pop() as String;
     if (equalSign != null) popCharOffset();
-    String condition = popIfNotNull(equalSign) ?? "true";
-    Object dottedName = pop();
+    String condition = popIfNotNull(equalSign) as String? ?? "true";
+    Object? dottedName = pop();
     if (dottedName is ParserRecovery) {
       push(dottedName);
     } else {
-      push(new Configuration(charOffset, dottedName, condition, uri));
+      push(new Configuration(charOffset, dottedName as String, condition, uri));
     }
   }
 
   @override
   void handleDottedName(int count, Token firstIdentifier) {
     debugEvent("DottedName");
-    List<String> names = popIdentifierList(count);
+    List<String>? names = popIdentifierList(count);
     if (names == null) {
       push(new ParserRecovery(firstIdentifier.charOffset));
     } else {
@@ -288,7 +291,7 @@
   }
 
   @override
-  void handleRecoverImport(Token semicolon) {
+  void handleRecoverImport(Token? semicolon) {
     debugEvent("RecoverImport");
     pop(); // combinators
     pop(NullValue.Deferred); // deferredKeyword
@@ -301,8 +304,8 @@
   void endPart(Token partKeyword, Token semicolon) {
     debugEvent("Part");
     int charOffset = popCharOffset();
-    String uri = pop();
-    List<MetadataBuilder> metadata = pop();
+    String uri = pop() as String;
+    List<MetadataBuilder>? metadata = pop() as List<MetadataBuilder>?;
     libraryBuilder.addPart(metadata, uri, charOffset);
     checkEmpty(partKeyword.charOffset);
   }
@@ -310,7 +313,7 @@
   @override
   void handleOperatorName(Token operatorKeyword, Token token) {
     debugEvent("OperatorName");
-    push(operatorFromString(token.stringValue));
+    push(operatorFromString(token.stringValue!));
     push(token.charOffset);
   }
 
@@ -325,7 +328,7 @@
   void handleIdentifier(Token token, IdentifierContext context) {
     if (context == IdentifierContext.enumValueDeclaration) {
       debugEvent("handleIdentifier");
-      List<MetadataBuilder> metadata = pop();
+      List<MetadataBuilder>? metadata = pop() as List<MetadataBuilder>?;
       if (token.isSynthetic) {
         push(new ParserRecovery(token.charOffset));
       } else {
@@ -356,11 +359,11 @@
   void endLiteralString(int interpolationCount, Token endToken) {
     debugEvent("endLiteralString");
     if (interpolationCount == 0) {
-      Token token = pop();
+      Token token = pop() as Token;
       push(unescapeString(token.lexeme, token, this));
       push(token.charOffset);
     } else {
-      Token beginToken = pop();
+      Token beginToken = pop() as Token;
       int charOffset = beginToken.charOffset;
       push("${SourceLibraryBuilder.MALFORMED_URI_SCHEME}:bad${charOffset}");
       push(charOffset);
@@ -376,11 +379,11 @@
     if (hasName) {
       // Pop the native clause which in this case is a StringLiteral.
       pop(); // Char offset.
-      Object name = pop();
+      Object? name = pop();
       if (name is ParserRecovery) {
         nativeMethodName = '';
       } else {
-        nativeMethodName = name; // String.
+        nativeMethodName = name as String; // String.
       }
     } else {
       nativeMethodName = '';
@@ -390,11 +393,12 @@
   @override
   void handleStringJuxtaposition(Token startToken, int literalCount) {
     debugEvent("StringJuxtaposition");
-    List<String> list = new List<String>.filled(literalCount, null);
+    List<String> list =
+        new List<String>.filled(literalCount, /* dummyValue = */ '');
     int charOffset = -1;
     for (int i = literalCount - 1; i >= 0; i--) {
-      charOffset = pop();
-      list[i] = pop();
+      charOffset = popCharOffset();
+      list[i] = pop() as String;
     }
     push(list.join(""));
     push(charOffset);
@@ -420,18 +424,18 @@
       ]),
     ]));
     debugEvent("handleQualified");
-    int suffixOffset = pop();
-    Object suffix = pop();
-    int offset = pop();
-    Object prefix = pop();
+    int suffixOffset = popCharOffset();
+    Object? suffix = pop();
+    int offset = popCharOffset();
+    Object prefix = pop()!;
     if (prefix is ParserRecovery) {
       push(prefix);
     } else if (suffix is ParserRecovery) {
       push(suffix);
     } else {
-      assert(identical(suffix, period.next.lexeme));
-      assert(suffixOffset == period.next.charOffset);
-      push(new QualifiedName(prefix, period.next));
+      assert(identical(suffix, period.next!.lexeme));
+      assert(suffixOffset == period.next!.charOffset);
+      push(new QualifiedName(prefix, period.next!));
     }
     push(offset);
   }
@@ -440,11 +444,11 @@
   void endLibraryName(Token libraryKeyword, Token semicolon) {
     debugEvent("endLibraryName");
     popCharOffset();
-    Object name = pop();
-    List<MetadataBuilder> metadata = pop();
+    Object? name = pop();
+    List<MetadataBuilder>? metadata = pop() as List<MetadataBuilder>?;
     if (name is! ParserRecovery) {
       libraryBuilder.name =
-          flattenName(name, offsetForToken(libraryKeyword), uri);
+          flattenName(name!, offsetForToken(libraryKeyword), uri);
     }
     libraryBuilder.metadata = metadata;
   }
@@ -458,9 +462,10 @@
   }
 
   @override
-  void beginClassDeclaration(Token begin, Token abstractToken, Token name) {
+  void beginClassDeclaration(Token begin, Token? abstractToken, Token name) {
     debugEvent("beginClassDeclaration");
-    List<TypeVariableBuilder> typeVariables = pop();
+    List<TypeVariableBuilder>? typeVariables =
+        pop() as List<TypeVariableBuilder>?;
     push(typeVariables ?? NullValue.TypeVariables);
     libraryBuilder.currentTypeParameterScopeBuilder
         .markAsClassDeclaration(name.lexeme, name.charOffset, typeVariables);
@@ -471,7 +476,8 @@
   @override
   void beginMixinDeclaration(Token mixinKeyword, Token name) {
     debugEvent("beginMixinDeclaration");
-    List<TypeVariableBuilder> typeVariables = pop();
+    List<TypeVariableBuilder>? typeVariables =
+        pop() as List<TypeVariableBuilder>?;
     push(typeVariables ?? NullValue.TypeVariables);
     libraryBuilder.currentTypeParameterScopeBuilder
         .markAsMixinDeclaration(name.lexeme, name.charOffset, typeVariables);
@@ -484,7 +490,7 @@
       assert(checkState(token, [
         unionOfKinds([ValueKinds.ParserRecovery, ValueKinds.TypeBuilder])
       ]));
-      Object extensionThisType = peek();
+      Object? extensionThisType = peek();
       if (extensionThisType is TypeBuilder) {
         libraryBuilder.currentTypeParameterScopeBuilder
             .registerExtensionThisType(extensionThisType);
@@ -503,9 +509,10 @@
 
   @override
   void beginNamedMixinApplication(
-      Token begin, Token abstractToken, Token name) {
+      Token begin, Token? abstractToken, Token name) {
     debugEvent("beginNamedMixinApplication");
-    List<TypeVariableBuilder> typeVariables = pop();
+    List<TypeVariableBuilder>? typeVariables =
+        pop() as List<TypeVariableBuilder>?;
     push(typeVariables ?? NullValue.TypeVariables);
     libraryBuilder.currentTypeParameterScopeBuilder.markAsNamedMixinApplication(
         name.lexeme, name.charOffset, typeVariables);
@@ -514,9 +521,10 @@
 
   @override
   void handleClassOrMixinImplements(
-      Token implementsKeyword, int interfacesCount) {
+      Token? implementsKeyword, int interfacesCount) {
     debugEvent("ClassOrMixinImplements");
-    push(const FixedNullableList<TypeBuilder>().pop(stack, interfacesCount) ??
+    push(const FixedNullableList<TypeBuilder>()
+            .popNonNullable(stack, interfacesCount, dummyTypeBuilder) ??
         NullValue.TypeBuilderList);
   }
 
@@ -543,7 +551,7 @@
   }
 
   @override
-  void handleClassExtends(Token extendsKeyword, int typeCount) {
+  void handleClassExtends(Token? extendsKeyword, int typeCount) {
     debugEvent("handleClassExtends");
     while (typeCount > 1) {
       pop();
@@ -553,26 +561,29 @@
   }
 
   @override
-  void handleMixinOn(Token onKeyword, int typeCount) {
+  void handleMixinOn(Token? onKeyword, int typeCount) {
     debugEvent("handleMixinOn");
-    push(const FixedNullableList<TypeBuilder>().pop(stack, typeCount) ??
+    push(const FixedNullableList<TypeBuilder>()
+            .popNonNullable(stack, typeCount, dummyTypeBuilder) ??
         new ParserRecovery(offsetForToken(onKeyword)));
   }
 
   @override
   void endClassDeclaration(Token beginToken, Token endToken) {
     debugEvent("endClassDeclaration");
-    List<TypeBuilder> interfaces = pop(NullValue.TypeBuilderList);
-    int supertypeOffset = pop();
-    TypeBuilder supertype = nullIfParserRecovery(pop());
-    int modifiers = pop();
-    List<TypeVariableBuilder> typeVariables = pop();
-    int nameOffset = pop();
-    Object name = pop();
+    List<TypeBuilder>? interfaces =
+        pop(NullValue.TypeBuilderList) as List<TypeBuilder>?;
+    int supertypeOffset = popCharOffset();
+    TypeBuilder? supertype = nullIfParserRecovery(pop()) as TypeBuilder?;
+    int modifiers = pop() as int;
+    List<TypeVariableBuilder>? typeVariables =
+        pop() as List<TypeVariableBuilder>?;
+    int nameOffset = popCharOffset();
+    Object? name = pop();
     if (typeVariables != null && supertype is MixinApplicationBuilder) {
       supertype.typeVariables = typeVariables;
     }
-    List<MetadataBuilder> metadata = pop();
+    List<MetadataBuilder>? metadata = pop() as List<MetadataBuilder>?;
     checkEmpty(beginToken.charOffset);
     if (name is ParserRecovery) {
       libraryBuilder
@@ -587,10 +598,10 @@
 
     if (libraryBuilder.isNonNullableByDefault) {
       String classNameForErrors = "${name}";
-      TypeBuilder supertypeForErrors = supertype is MixinApplicationBuilder
+      TypeBuilder? supertypeForErrors = supertype is MixinApplicationBuilder
           ? supertype.supertype
           : supertype;
-      List<TypeBuilder> mixins =
+      List<TypeBuilder>? mixins =
           supertype is MixinApplicationBuilder ? supertype.mixins : null;
       if (supertypeForErrors != null) {
         if (supertypeForErrors.nullabilityBuilder.build(libraryBuilder) ==
@@ -634,7 +645,7 @@
     libraryBuilder.addClass(
         metadata,
         modifiers,
-        name,
+        name as String,
         typeVariables,
         supertype,
         interfaces,
@@ -646,19 +657,23 @@
     libraryBuilder.setCurrentClassName(null);
   }
 
-  Object nullIfParserRecovery(Object node) {
+  Object? nullIfParserRecovery(Object? node) {
     return node is ParserRecovery ? null : node;
   }
 
   @override
   void endMixinDeclaration(Token mixinToken, Token endToken) {
     debugEvent("endMixinDeclaration");
-    List<TypeBuilder> interfaces = pop(NullValue.TypeBuilderList);
-    List<TypeBuilder> supertypeConstraints = nullIfParserRecovery(pop());
-    List<TypeVariableBuilder> typeVariables = pop(NullValue.TypeVariables);
-    int nameOffset = pop();
-    Object name = pop();
-    List<MetadataBuilder> metadata = pop(NullValue.Metadata);
+    List<TypeBuilder>? interfaces =
+        pop(NullValue.TypeBuilderList) as List<TypeBuilder>?;
+    List<TypeBuilder>? supertypeConstraints =
+        nullIfParserRecovery(pop()) as List<TypeBuilder>?;
+    List<TypeVariableBuilder>? typeVariables =
+        pop(NullValue.TypeVariables) as List<TypeVariableBuilder>?;
+    int nameOffset = popCharOffset();
+    Object? name = pop();
+    List<MetadataBuilder>? metadata =
+        pop(NullValue.Metadata) as List<MetadataBuilder>?;
     checkEmpty(mixinToken.charOffset);
     if (name is ParserRecovery) {
       libraryBuilder
@@ -669,7 +684,7 @@
     }
     int startOffset =
         metadata == null ? mixinToken.charOffset : metadata.first.charOffset;
-    TypeBuilder supertype;
+    TypeBuilder? supertype;
     if (supertypeConstraints != null && supertypeConstraints.isNotEmpty) {
       if (supertypeConstraints.length == 1) {
         supertype = supertypeConstraints.first;
@@ -677,8 +692,8 @@
         supertype = new MixinApplicationBuilder(
             supertypeConstraints.first,
             supertypeConstraints.skip(1).toList(),
-            supertypeConstraints.first.fileUri,
-            supertypeConstraints.first.charOffset);
+            supertypeConstraints.first.fileUri!,
+            supertypeConstraints.first.charOffset!);
       }
     }
 
@@ -715,7 +730,7 @@
     libraryBuilder.addMixinDeclaration(
         metadata,
         mixinDeclarationMask,
-        name,
+        name as String,
         typeVariables,
         supertype,
         interfaces,
@@ -735,11 +750,12 @@
   }
 
   @override
-  void beginExtensionDeclaration(Token extensionKeyword, Token nameToken) {
+  void beginExtensionDeclaration(Token extensionKeyword, Token? nameToken) {
     assert(checkState(extensionKeyword,
         [ValueKinds.TypeVariableListOrNull, ValueKinds.MetadataListOrNull]));
     debugEvent("beginExtensionDeclaration");
-    List<TypeVariableBuilder> typeVariables = pop();
+    List<TypeVariableBuilder>? typeVariables =
+        pop() as List<TypeVariableBuilder>?;
     int offset = nameToken?.charOffset ?? extensionKeyword.charOffset;
     String name = nameToken?.lexeme ??
         // Synthesized name used internally.
@@ -752,7 +768,7 @@
   }
 
   @override
-  void endExtensionDeclaration(Token extensionKeyword, Token typeKeyword,
+  void endExtensionDeclaration(Token extensionKeyword, Token? typeKeyword,
       Token onKeyword, Token endToken) {
     assert(checkState(extensionKeyword, [
       unionOfKinds([ValueKinds.ParserRecovery, ValueKinds.TypeBuilder]),
@@ -762,20 +778,22 @@
       ValueKinds.MetadataListOrNull
     ]));
     debugEvent("endExtensionDeclaration");
-    Object onType = pop();
+    Object? onType = pop();
     if (onType is ParserRecovery) {
       ParserRecovery parserRecovery = onType;
       onType = new FixedTypeBuilder(
           const InvalidType(), uri, parserRecovery.charOffset);
     }
-    List<TypeVariableBuilder> typeVariables = pop(NullValue.TypeVariables);
-    int nameOffset = pop();
-    String name = pop(NullValue.Name);
+    List<TypeVariableBuilder>? typeVariables =
+        pop(NullValue.TypeVariables) as List<TypeVariableBuilder>?;
+    int nameOffset = popCharOffset();
+    String? name = pop(NullValue.Name) as String?;
     if (name == null) {
       nameOffset = extensionKeyword.charOffset;
       name = '$nameOffset';
     }
-    List<MetadataBuilder> metadata = pop(NullValue.Metadata);
+    List<MetadataBuilder>? metadata =
+        pop(NullValue.Metadata) as List<MetadataBuilder>?;
     checkEmpty(extensionKeyword.charOffset);
     int startOffset = metadata == null
         ? extensionKeyword.charOffset
@@ -786,8 +804,8 @@
       addProblem(
           templateExperimentNotEnabled.withArguments('extension-types',
               libraryBuilder.enableExtensionTypesVersionInLibrary.toText()),
-          extensionKeyword.next.charOffset,
-          extensionKeyword.next.length);
+          extensionKeyword.next!.charOffset,
+          extensionKeyword.next!.length);
     }
     libraryBuilder.addExtensionDeclaration(
         metadata,
@@ -795,14 +813,14 @@
         0,
         name,
         typeVariables,
-        onType,
+        onType as TypeBuilder,
         isExtensionTypeDeclaration,
         startOffset,
         nameOffset,
         endToken.charOffset);
   }
 
-  ProcedureKind computeProcedureKind(Token token) {
+  ProcedureKind computeProcedureKind(Token? token) {
     if (token == null) return ProcedureKind.Method;
     if (optional("get", token)) return ProcedureKind.Getter;
     if (optional("set", token)) return ProcedureKind.Setter;
@@ -811,7 +829,7 @@
   }
 
   @override
-  void beginTopLevelMethod(Token lastConsumed, Token externalToken) {
+  void beginTopLevelMethod(Token lastConsumed, Token? externalToken) {
     libraryBuilder.beginNestedDeclaration(
         TypeParameterScopeKind.topLevelMethod, "#method",
         hasMembers: false);
@@ -819,16 +837,18 @@
   }
 
   @override
-  void endTopLevelMethod(Token beginToken, Token getOrSet, Token endToken) {
+  void endTopLevelMethod(Token beginToken, Token? getOrSet, Token endToken) {
     debugEvent("endTopLevelMethod");
-    MethodBody kind = pop();
-    AsyncMarker asyncModifier = pop();
-    List<FormalParameterBuilder> formals = pop();
-    int formalsOffset = pop();
-    List<TypeVariableBuilder> typeVariables = pop();
-    int charOffset = pop();
-    Object name = pop();
-    TypeBuilder returnType = pop();
+    MethodBody kind = pop() as MethodBody;
+    AsyncMarker asyncModifier = pop() as AsyncMarker;
+    List<FormalParameterBuilder>? formals =
+        pop() as List<FormalParameterBuilder>?;
+    int formalsOffset = popCharOffset();
+    List<TypeVariableBuilder>? typeVariables =
+        pop() as List<TypeVariableBuilder>?;
+    int charOffset = popCharOffset();
+    Object? name = pop();
+    TypeBuilder? returnType = pop() as TypeBuilder?;
     bool isAbstract = kind == MethodBody.Abstract;
     if (getOrSet != null && optional("set", getOrSet)) {
       if (formals == null || formals.length != 1) {
@@ -842,12 +862,12 @@
         returnType = null;
       }
     }
-    int modifiers = pop();
+    int modifiers = pop() as int;
     modifiers = Modifier.addAbstractMask(modifiers, isAbstract: isAbstract);
     if (nativeMethodName != null) {
       modifiers |= externalMask;
     }
-    List<MetadataBuilder> metadata = pop();
+    List<MetadataBuilder>? metadata = pop() as List<MetadataBuilder>?;
     checkEmpty(beginToken.charOffset);
     libraryBuilder
         .endNestedDeclaration(TypeParameterScopeKind.topLevelMethod, "#method")
@@ -859,7 +879,7 @@
         metadata,
         modifiers,
         returnType,
-        name,
+        name as String,
         typeVariables,
         formals,
         computeProcedureKind(getOrSet),
@@ -915,12 +935,17 @@
   }
 
   @override
-  void beginMethod(Token externalToken, Token staticToken, Token covariantToken,
-      Token varFinalOrConst, Token getOrSet, Token name) {
+  void beginMethod(
+      Token? externalToken,
+      Token? staticToken,
+      Token? covariantToken,
+      Token? varFinalOrConst,
+      Token? getOrSet,
+      Token name) {
     inConstructor =
-        name?.lexeme == libraryBuilder.currentTypeParameterScopeBuilder.name &&
+        name.lexeme == libraryBuilder.currentTypeParameterScopeBuilder.name &&
             getOrSet == null;
-    List<Modifier> modifiers;
+    List<Modifier>? modifiers;
     if (externalToken != null) {
       modifiers ??= <Modifier>[];
       modifiers.add(External);
@@ -956,47 +981,47 @@
   }
 
   @override
-  void endClassMethod(Token getOrSet, Token beginToken, Token beginParam,
-      Token beginInitializers, Token endToken) {
+  void endClassMethod(Token? getOrSet, Token beginToken, Token beginParam,
+      Token? beginInitializers, Token endToken) {
     _endClassMethod(getOrSet, beginToken, beginParam, beginInitializers,
         endToken, _MethodKind.classMethod);
   }
 
-  void endClassConstructor(Token getOrSet, Token beginToken, Token beginParam,
-      Token beginInitializers, Token endToken) {
+  void endClassConstructor(Token? getOrSet, Token beginToken, Token beginParam,
+      Token? beginInitializers, Token endToken) {
     _endClassMethod(getOrSet, beginToken, beginParam, beginInitializers,
         endToken, _MethodKind.classConstructor);
   }
 
-  void endMixinMethod(Token getOrSet, Token beginToken, Token beginParam,
-      Token beginInitializers, Token endToken) {
+  void endMixinMethod(Token? getOrSet, Token beginToken, Token beginParam,
+      Token? beginInitializers, Token endToken) {
     _endClassMethod(getOrSet, beginToken, beginParam, beginInitializers,
         endToken, _MethodKind.mixinMethod);
   }
 
-  void endExtensionMethod(Token getOrSet, Token beginToken, Token beginParam,
-      Token beginInitializers, Token endToken) {
+  void endExtensionMethod(Token? getOrSet, Token beginToken, Token beginParam,
+      Token? beginInitializers, Token endToken) {
     _endClassMethod(getOrSet, beginToken, beginParam, beginInitializers,
         endToken, _MethodKind.extensionMethod);
   }
 
-  void endMixinConstructor(Token getOrSet, Token beginToken, Token beginParam,
-      Token beginInitializers, Token endToken) {
+  void endMixinConstructor(Token? getOrSet, Token beginToken, Token beginParam,
+      Token? beginInitializers, Token endToken) {
     _endClassMethod(getOrSet, beginToken, beginParam, beginInitializers,
         endToken, _MethodKind.mixinConstructor);
   }
 
-  void endExtensionConstructor(Token getOrSet, Token beginToken,
-      Token beginParam, Token beginInitializers, Token endToken) {
+  void endExtensionConstructor(Token? getOrSet, Token beginToken,
+      Token beginParam, Token? beginInitializers, Token endToken) {
     _endClassMethod(getOrSet, beginToken, beginParam, beginInitializers,
         endToken, _MethodKind.extensionConstructor);
   }
 
-  void _endClassMethod(Token getOrSet, Token beginToken, Token beginParam,
-      Token beginInitializers, Token endToken, _MethodKind methodKind) {
+  void _endClassMethod(Token? getOrSet, Token beginToken, Token beginParam,
+      Token? beginInitializers, Token endToken, _MethodKind methodKind) {
     assert(checkState(beginToken, [ValueKinds.MethodBody]));
     debugEvent("Method");
-    MethodBody bodyKind = pop();
+    MethodBody bodyKind = pop() as MethodBody;
     if (bodyKind == MethodBody.RedirectingFactoryBody) {
       // This will cause an error later.
       pop();
@@ -1018,16 +1043,18 @@
       ValueKinds.Integer, // var/final/const offset
       ValueKinds.MetadataListOrNull,
     ]));
-    AsyncMarker asyncModifier = pop();
-    List<FormalParameterBuilder> formals = pop();
-    int formalsOffset = pop();
-    List<TypeVariableBuilder> typeVariables = pop();
-    int charOffset = pop();
-    Object nameOrOperator = pop();
+    AsyncMarker asyncModifier = pop() as AsyncMarker;
+    List<FormalParameterBuilder>? formals =
+        pop() as List<FormalParameterBuilder>?;
+    int formalsOffset = popCharOffset();
+    List<TypeVariableBuilder>? typeVariables =
+        pop() as List<TypeVariableBuilder>?;
+    int charOffset = popCharOffset();
+    Object? nameOrOperator = pop();
     if (Operator.subtract == nameOrOperator && formals == null) {
       nameOrOperator = Operator.unaryMinus;
     }
-    Object name;
+    Object? name;
     ProcedureKind kind;
     if (nameOrOperator is Operator) {
       name = operatorToString(nameOrOperator);
@@ -1056,8 +1083,8 @@
             unhandled("$requiredArgumentCount", "operatorRequiredArgumentCount",
                 charOffset, uri);
         }
-        String string = name;
-        addProblem(template.withArguments(name), charOffset, string.length);
+        String string = name as String;
+        addProblem(template.withArguments(string), charOffset, string.length);
       } else {
         if (formals != null) {
           for (FormalParameterBuilder formal in formals) {
@@ -1077,7 +1104,7 @@
       name = nameOrOperator;
       kind = computeProcedureKind(getOrSet);
     }
-    TypeBuilder returnType = pop();
+    TypeBuilder? returnType = pop() as TypeBuilder?;
     bool isAbstract = bodyKind == MethodBody.Abstract;
     if (getOrSet != null && optional("set", getOrSet)) {
       if (formals == null || formals.length != 1) {
@@ -1100,14 +1127,14 @@
       // Use implicit void as recovery.
       returnType = null;
     }
-    int modifiers = Modifier.toMask(pop());
+    int modifiers = Modifier.toMask(pop() as List<Modifier>?);
     modifiers = Modifier.addAbstractMask(modifiers, isAbstract: isAbstract);
     if (nativeMethodName != null) {
       modifiers |= externalMask;
     }
     bool isConst = (modifiers & constMask) != 0;
-    int varFinalOrConstOffset = pop();
-    List<MetadataBuilder> metadata = pop();
+    int varFinalOrConstOffset = popCharOffset();
+    List<MetadataBuilder>? metadata = pop() as List<MetadataBuilder>?;
 
     TypeParameterScopeBuilder declarationBuilder =
         libraryBuilder.endNestedDeclaration(
@@ -1120,14 +1147,14 @@
       return;
     }
 
-    String constructorName;
+    String? constructorName;
     switch (methodKind) {
       case _MethodKind.classConstructor:
       case _MethodKind.mixinConstructor:
       case _MethodKind.extensionConstructor:
         constructorName = libraryBuilder.computeAndValidateConstructorName(
                 name, charOffset) ??
-            name;
+            name as String?;
         break;
       case _MethodKind.classMethod:
       case _MethodKind.mixinMethod:
@@ -1141,17 +1168,17 @@
             TypeParameterScopeKind.extensionDeclaration) {
       TypeParameterScopeBuilder extension =
           libraryBuilder.currentTypeParameterScopeBuilder;
-      Map<TypeVariableBuilder, TypeBuilder> substitution;
+      Map<TypeVariableBuilder, TypeBuilder>? substitution;
       if (extension.typeVariables != null) {
         // We synthesize the names of the generated [TypeParameter]s, i.e.
         // rename 'T' to '#T'. We cannot do it on the builders because their
         // names are used to create the scope.
         List<TypeVariableBuilder> synthesizedTypeVariables = libraryBuilder
-            .copyTypeVariables(extension.typeVariables, declarationBuilder,
+            .copyTypeVariables(extension.typeVariables!, declarationBuilder,
                 isExtensionTypeParameter: true);
         substitution = {};
         for (int i = 0; i < synthesizedTypeVariables.length; i++) {
-          substitution[extension.typeVariables[i]] =
+          substitution[extension.typeVariables![i]] =
               new NamedTypeBuilder.fromTypeDeclarationBuilder(
                   synthesizedTypeVariables[i],
                   const NullabilityBuilder.omitted());
@@ -1169,9 +1196,10 @@
         List<TypeVariableBuilder> unboundTypeVariables = [];
         thisType = substitute(thisType, substitution,
             unboundTypes: unboundTypes,
-            unboundTypeVariables: unboundTypeVariables);
+            unboundTypeVariables: unboundTypeVariables)!;
         for (TypeBuilder unboundType in unboundTypes) {
-          extension.addType(new UnresolvedType(unboundType, -1, null));
+          extension.addType(new UnresolvedType(
+              unboundType, thisType.charOffset!, thisType.fileUri!));
         }
         libraryBuilder.boundlessTypeVariables.addAll(unboundTypeVariables);
       }
@@ -1226,7 +1254,7 @@
           metadata,
           modifiers,
           returnType,
-          name,
+          name as String,
           typeVariables,
           formals,
           kind,
@@ -1246,29 +1274,31 @@
   @override
   void handleNamedMixinApplicationWithClause(Token withKeyword) {
     debugEvent("NamedMixinApplicationWithClause");
-    Object mixins = pop();
-    Object supertype = pop();
+    Object? mixins = pop();
+    Object? supertype = pop();
     if (mixins is ParserRecovery) {
       push(mixins);
     } else if (supertype is ParserRecovery) {
       push(supertype);
     } else {
-      push(libraryBuilder.addMixinApplication(
-          supertype, mixins, withKeyword.charOffset));
+      push(libraryBuilder.addMixinApplication(supertype as TypeBuilder?,
+          mixins as List<TypeBuilder>, withKeyword.charOffset));
     }
   }
 
   @override
   void endNamedMixinApplication(Token beginToken, Token classKeyword,
-      Token equals, Token implementsKeyword, Token endToken) {
+      Token equals, Token? implementsKeyword, Token endToken) {
     debugEvent("endNamedMixinApplication");
-    List<TypeBuilder> interfaces = popIfNotNull(implementsKeyword);
-    Object mixinApplication = pop();
-    int modifiers = pop();
-    List<TypeVariableBuilder> typeVariables = pop();
-    int charOffset = pop();
-    Object name = pop();
-    List<MetadataBuilder> metadata = pop();
+    List<TypeBuilder>? interfaces =
+        popIfNotNull(implementsKeyword) as List<TypeBuilder>?;
+    Object? mixinApplication = pop();
+    int modifiers = pop() as int;
+    List<TypeVariableBuilder>? typeVariables =
+        pop() as List<TypeVariableBuilder>?;
+    int charOffset = popCharOffset();
+    Object? name = pop();
+    List<MetadataBuilder>? metadata = pop() as List<MetadataBuilder>?;
     checkEmpty(beginToken.charOffset);
     if (name is ParserRecovery || mixinApplication is ParserRecovery) {
       libraryBuilder
@@ -1280,8 +1310,9 @@
 
     if (libraryBuilder.isNonNullableByDefault) {
       String classNameForErrors = "${name}";
-      MixinApplicationBuilder mixinApplicationBuilder = mixinApplication;
-      TypeBuilder supertype = mixinApplicationBuilder.supertype;
+      MixinApplicationBuilder mixinApplicationBuilder =
+          mixinApplication as MixinApplicationBuilder;
+      TypeBuilder? supertype = mixinApplicationBuilder.supertype;
       List<TypeBuilder> mixins = mixinApplicationBuilder.mixins;
       if (supertype != null && supertype is! MixinApplicationBuilder) {
         if (supertype.nullabilityBuilder.build(libraryBuilder) ==
@@ -1323,10 +1354,10 @@
     int charEndOffset = endToken.charOffset;
     libraryBuilder.addNamedMixinApplication(
         metadata,
-        name,
+        name as String,
         typeVariables,
         modifiers,
-        mixinApplication,
+        mixinApplication as TypeBuilder?,
         interfaces,
         startCharOffset,
         charOffset,
@@ -1359,15 +1390,15 @@
   }
 
   @override
-  void handleType(Token beginToken, Token questionMark) {
+  void handleType(Token beginToken, Token? questionMark) {
     debugEvent("Type");
     if (!libraryBuilder.isNonNullableByDefault) {
       reportErrorIfNullableType(questionMark);
     }
     bool isMarkedAsNullable = questionMark != null;
-    List<TypeBuilder> arguments = pop();
-    int charOffset = pop();
-    Object name = pop();
+    List<TypeBuilder>? arguments = pop() as List<TypeBuilder>?;
+    int charOffset = popCharOffset();
+    Object name = pop()!;
     if (name is ParserRecovery) {
       push(name);
     } else {
@@ -1382,7 +1413,8 @@
   @override
   void endTypeList(int count) {
     debugEvent("TypeList");
-    push(const FixedNullableList<TypeBuilder>().pop(stack, count) ??
+    push(const FixedNullableList<TypeBuilder>()
+            .popNonNullable(stack, count, dummyTypeBuilder) ??
         new ParserRecovery(-1));
   }
 
@@ -1406,8 +1438,8 @@
   }
 
   @override
-  void beginFormalParameter(Token token, MemberKind kind, Token requiredToken,
-      Token covariantToken, Token varFinalOrConst) {
+  void beginFormalParameter(Token token, MemberKind kind, Token? requiredToken,
+      Token? covariantToken, Token? varFinalOrConst) {
     if (requiredToken != null && !libraryBuilder.isNonNullableByDefault) {
       reportNonNullableModifierError(requiredToken);
     }
@@ -1418,24 +1450,24 @@
 
   @override
   void endFormalParameter(
-      Token thisKeyword,
-      Token periodAfterThis,
+      Token? thisKeyword,
+      Token? periodAfterThis,
       Token nameToken,
-      Token initializerStart,
-      Token initializerEnd,
+      Token? initializerStart,
+      Token? initializerEnd,
       FormalParameterKind kind,
       MemberKind memberKind) {
     debugEvent("FormalParameter");
-    int charOffset = pop();
-    Object name = pop();
-    TypeBuilder type = nullIfParserRecovery(pop());
-    int modifiers = pop();
-    List<MetadataBuilder> metadata = pop();
+    int charOffset = popCharOffset();
+    Object? name = pop();
+    TypeBuilder? type = nullIfParserRecovery(pop()) as TypeBuilder?;
+    int modifiers = pop() as int;
+    List<MetadataBuilder>? metadata = pop() as List<MetadataBuilder>?;
     if (name is ParserRecovery) {
       push(name);
     } else {
-      push(libraryBuilder.addFormalParameter(metadata, modifiers, type, name,
-          thisKeyword != null, charOffset, initializerStart));
+      push(libraryBuilder.addFormalParameter(metadata, modifiers, type,
+          name as String, thisKeyword != null, charOffset, initializerStart));
     }
   }
 
@@ -1473,8 +1505,9 @@
     // 0. It might be simpler if the parser didn't call this method in that
     // case, however, then [beginOptionalFormalParameters] wouldn't always be
     // matched by this method.
-    List<FormalParameterBuilder> parameters =
-        const FixedNullableList<FormalParameterBuilder>().pop(stack, count);
+    List<FormalParameterBuilder>? parameters =
+        const FixedNullableList<FormalParameterBuilder>()
+            .popNonNullable(stack, count, dummyFormalParameterBuilder);
     if (parameters == null) {
       push(new ParserRecovery(offsetForToken(beginToken)));
     } else {
@@ -1489,32 +1522,32 @@
   void endFormalParameters(
       int count, Token beginToken, Token endToken, MemberKind kind) {
     debugEvent("FormalParameters");
-    List<FormalParameterBuilder> formals;
+    List<FormalParameterBuilder>? formals;
     if (count == 1) {
-      Object last = pop();
+      Object? last = pop();
       if (last is List<FormalParameterBuilder>) {
         formals = last;
       } else if (last is! ParserRecovery) {
         assert(last != null);
-        formals = new List<FormalParameterBuilder>.filled(1, null);
-        formals[0] = last;
+        formals = [last as FormalParameterBuilder];
       }
     } else if (count > 1) {
-      Object last = pop();
+      Object? last = pop();
       count--;
       if (last is ParserRecovery) {
         discard(count);
       } else if (last is List<FormalParameterBuilder>) {
         formals = const FixedNullableList<FormalParameterBuilder>()
-            .popPadded(stack, count, last.length);
+            .popPaddedNonNullable(
+                stack, count, last.length, dummyFormalParameterBuilder);
         if (formals != null) {
           formals.setRange(count, formals.length, last);
         }
       } else {
         formals = const FixedNullableList<FormalParameterBuilder>()
-            .popPadded(stack, count, 1);
+            .popPaddedNonNullable(stack, count, 1, dummyFormalParameterBuilder);
         if (formals != null) {
-          formals[count] = last;
+          formals[count] = last as FormalParameterBuilder;
         }
       }
     }
@@ -1522,6 +1555,7 @@
       assert(formals.isNotEmpty);
       if (formals.length == 2) {
         // The name may be null for generalized function types.
+        // ignore: unnecessary_null_comparison
         if (formals[0].name != null && formals[0].name == formals[1].name) {
           addProblem(
               templateDuplicatedParameterName.withArguments(formals[1].name),
@@ -1538,6 +1572,7 @@
         Map<String, FormalParameterBuilder> seenNames =
             <String, FormalParameterBuilder>{};
         for (FormalParameterBuilder formal in formals) {
+          // ignore: unnecessary_null_comparison
           if (formal.name == null) continue;
           if (seenNames.containsKey(formal.name)) {
             addProblem(
@@ -1547,8 +1582,8 @@
                 context: [
                   templateDuplicatedParameterNameCause
                       .withArguments(formal.name)
-                      .withLocation(uri, seenNames[formal.name].charOffset,
-                          seenNames[formal.name].name.length)
+                      .withLocation(uri, seenNames[formal.name]!.charOffset,
+                          seenNames[formal.name]!.name.length)
                 ]);
           } else {
             seenNames[formal.name] = formal;
@@ -1568,7 +1603,7 @@
 
   @override
   void endAssert(Token assertKeyword, Assert kind, Token leftParenthesis,
-      Token commaToken, Token semicolonToken) {
+      Token? commaToken, Token semicolonToken) {
     debugEvent("Assert");
     // Do nothing
   }
@@ -1576,16 +1611,16 @@
   @override
   void endEnum(Token enumKeyword, Token leftBrace, int count) {
     debugEvent("Enum");
-    List<EnumConstantInfo> enumConstantInfos =
+    List<EnumConstantInfo?>? enumConstantInfos =
         const FixedNullableList<EnumConstantInfo>().pop(stack, count);
-    int charOffset = pop(); // identifier char offset.
+    int charOffset = popCharOffset(); // identifier char offset.
     int startCharOffset = enumKeyword.charOffset;
-    Object name = pop();
-    List<MetadataBuilder> metadata = pop();
+    Object? name = pop();
+    List<MetadataBuilder>? metadata = pop() as List<MetadataBuilder>?;
     checkEmpty(enumKeyword.charOffset);
     if (name is ParserRecovery) return;
-    libraryBuilder.addEnum(metadata, name, enumConstantInfos, startCharOffset,
-        charOffset, leftBrace?.endGroup?.charOffset);
+    libraryBuilder.addEnum(metadata, name as String, enumConstantInfos,
+        startCharOffset, charOffset, leftBrace.endGroup!.charOffset);
   }
 
   @override
@@ -1612,15 +1647,17 @@
   }
 
   @override
-  void endFunctionType(Token functionToken, Token questionMark) {
+  void endFunctionType(Token functionToken, Token? questionMark) {
     debugEvent("FunctionType");
     if (!libraryBuilder.isNonNullableByDefault) {
       reportErrorIfNullableType(questionMark);
     }
-    List<FormalParameterBuilder> formals = pop();
+    List<FormalParameterBuilder>? formals =
+        pop() as List<FormalParameterBuilder>?;
     pop(); // formals offset
-    TypeBuilder returnType = pop();
-    List<TypeVariableBuilder> typeVariables = pop();
+    TypeBuilder? returnType = pop() as TypeBuilder?;
+    List<TypeVariableBuilder>? typeVariables =
+        pop() as List<TypeVariableBuilder>?;
     push(libraryBuilder.addFunctionType(
         returnType,
         typeVariables,
@@ -1631,12 +1668,14 @@
   }
 
   @override
-  void endFunctionTypedFormalParameter(Token nameToken, Token question) {
+  void endFunctionTypedFormalParameter(Token nameToken, Token? question) {
     debugEvent("FunctionTypedFormalParameter");
-    List<FormalParameterBuilder> formals = pop();
-    int formalsOffset = pop();
-    TypeBuilder returnType = pop();
-    List<TypeVariableBuilder> typeVariables = pop();
+    List<FormalParameterBuilder>? formals =
+        pop() as List<FormalParameterBuilder>?;
+    int formalsOffset = popCharOffset();
+    TypeBuilder? returnType = pop() as TypeBuilder?;
+    List<TypeVariableBuilder>? typeVariables =
+        pop() as List<TypeVariableBuilder>?;
     if (!libraryBuilder.isNonNullableByDefault) {
       reportErrorIfNullableType(question);
     }
@@ -1651,19 +1690,20 @@
 
   @override
   void endFunctionTypeAlias(
-      Token typedefKeyword, Token equals, Token endToken) {
+      Token typedefKeyword, Token? equals, Token endToken) {
     debugEvent("endFunctionTypeAlias");
-    List<TypeVariableBuilder> typeVariables;
-    Object name;
+    List<TypeVariableBuilder>? typeVariables;
+    Object? name;
     int charOffset;
-    TypeBuilder aliasedType;
+    TypeBuilder? aliasedType;
     if (equals == null) {
-      List<FormalParameterBuilder> formals = pop();
+      List<FormalParameterBuilder>? formals =
+          pop() as List<FormalParameterBuilder>?;
       pop(); // formals offset
-      typeVariables = pop();
-      charOffset = pop();
+      typeVariables = pop() as List<TypeVariableBuilder>?;
+      charOffset = popCharOffset();
       name = pop();
-      TypeBuilder returnType = pop();
+      TypeBuilder? returnType = pop() as TypeBuilder?;
       // Create a nested declaration that is ended below by
       // `library.addFunctionType`.
       if (name is ParserRecovery) {
@@ -1681,9 +1721,9 @@
       aliasedType = libraryBuilder.addFunctionType(returnType, null, formals,
           const NullabilityBuilder.omitted(), uri, charOffset);
     } else {
-      Object type = pop();
-      typeVariables = pop();
-      charOffset = pop();
+      Object? type = pop();
+      typeVariables = pop() as List<TypeVariableBuilder>?;
+      charOffset = popCharOffset();
       name = pop();
       if (name is ParserRecovery) {
         pop(); // Metadata.
@@ -1722,19 +1762,19 @@
         addProblem(messageTypedefNotFunction, equals.charOffset, equals.length);
       }
     }
-    List<MetadataBuilder> metadata = pop();
+    List<MetadataBuilder>? metadata = pop() as List<MetadataBuilder>?;
     checkEmpty(typedefKeyword.charOffset);
     libraryBuilder.addFunctionTypeAlias(
-        metadata, name, typeVariables, aliasedType, charOffset);
+        metadata, name as String, typeVariables, aliasedType, charOffset);
   }
 
   @override
   void endTopLevelFields(
-      Token externalToken,
-      Token staticToken,
-      Token covariantToken,
-      Token lateToken,
-      Token varFinalOrConst,
+      Token? externalToken,
+      Token? staticToken,
+      Token? covariantToken,
+      Token? lateToken,
+      Token? varFinalOrConst,
       int count,
       Token beginToken,
       Token endToken) {
@@ -1753,14 +1793,14 @@
         externalToken = null;
       }
     }
-    List<FieldInfo> fieldInfos = popFieldInfos(count);
-    TypeBuilder type = nullIfParserRecovery(pop());
+    List<FieldInfo>? fieldInfos = popFieldInfos(count);
+    TypeBuilder? type = nullIfParserRecovery(pop()) as TypeBuilder?;
     int modifiers = (externalToken != null ? externalMask : 0) |
         (staticToken != null ? staticMask : 0) |
         (covariantToken != null ? covariantMask : 0) |
         (lateToken != null ? lateMask : 0) |
         Modifier.validateVarFinalOrConst(varFinalOrConst?.lexeme);
-    List<MetadataBuilder> metadata = pop();
+    List<MetadataBuilder>? metadata = pop() as List<MetadataBuilder>?;
     checkEmpty(beginToken.charOffset);
     if (fieldInfos == null) return;
     libraryBuilder.addFields(
@@ -1773,12 +1813,12 @@
 
   @override
   void endClassFields(
-      Token abstractToken,
-      Token externalToken,
-      Token staticToken,
-      Token covariantToken,
-      Token lateToken,
-      Token varFinalOrConst,
+      Token? abstractToken,
+      Token? externalToken,
+      Token? staticToken,
+      Token? covariantToken,
+      Token? lateToken,
+      Token? varFinalOrConst,
       int count,
       Token beginToken,
       Token endToken) {
@@ -1811,8 +1851,8 @@
         externalToken = null;
       }
     }
-    List<FieldInfo> fieldInfos = popFieldInfos(count);
-    TypeBuilder type = pop();
+    List<FieldInfo>? fieldInfos = popFieldInfos(count);
+    TypeBuilder? type = pop() as TypeBuilder?;
     int modifiers = (abstractToken != null ? abstractMask : 0) |
         (externalToken != null ? externalMask : 0) |
         (staticToken != null ? staticMask : 0) |
@@ -1822,11 +1862,11 @@
     if (staticToken == null && modifiers & constMask != 0) {
       // It is a compile-time error if an instance variable is declared to be
       // constant.
-      addProblem(messageConstInstanceField, varFinalOrConst.charOffset,
+      addProblem(messageConstInstanceField, varFinalOrConst!.charOffset,
           varFinalOrConst.length);
       modifiers &= ~constMask;
     }
-    List<MetadataBuilder> metadata = pop();
+    List<MetadataBuilder>? metadata = pop() as List<MetadataBuilder>?;
     if (fieldInfos == null) return;
     libraryBuilder.addFields(
         metadata,
@@ -1836,20 +1876,21 @@
         fieldInfos);
   }
 
-  List<FieldInfo> popFieldInfos(int count) {
+  List<FieldInfo>? popFieldInfos(int count) {
     if (count == 0) return null;
-    List<FieldInfo> fieldInfos = new List<FieldInfo>.filled(count, null);
+    List<FieldInfo> fieldInfos =
+        new List<FieldInfo>.filled(count, dummyFieldInfo);
     bool isParserRecovery = false;
     for (int i = count - 1; i != -1; i--) {
-      int charEndOffset = pop();
-      Token beforeLast = pop();
-      Token initializerTokenForInference = pop();
-      int charOffset = pop();
-      Object name = pop(NullValue.Identifier);
+      int charEndOffset = popCharOffset();
+      Token beforeLast = pop() as Token;
+      Token? initializerTokenForInference = pop() as Token?;
+      int charOffset = popCharOffset();
+      Object? name = pop(NullValue.Identifier);
       if (name is ParserRecovery) {
         isParserRecovery = true;
       } else {
-        fieldInfos[i] = new FieldInfo(name, charOffset,
+        fieldInfos[i] = new FieldInfo(name as String, charOffset,
             initializerTokenForInference, beforeLast, charEndOffset);
       }
     }
@@ -1859,14 +1900,14 @@
   @override
   void beginTypeVariable(Token token) {
     debugEvent("beginTypeVariable");
-    int charOffset = pop();
-    Object name = pop();
-    List<MetadataBuilder> metadata = pop();
+    int charOffset = popCharOffset();
+    Object? name = pop();
+    List<MetadataBuilder>? metadata = pop() as List<MetadataBuilder>?;
     if (name is ParserRecovery) {
       push(name);
     } else {
       push(libraryBuilder.addTypeVariable(
-          metadata, name, null, charOffset, uri));
+          metadata, name as String, null, charOffset, uri));
     }
   }
 
@@ -1880,11 +1921,12 @@
 
   @override
   void endTypeVariable(
-      Token token, int index, Token extendsOrSuper, Token variance) {
+      Token token, int index, Token? extendsOrSuper, Token? variance) {
     debugEvent("endTypeVariable");
-    TypeBuilder bound = nullIfParserRecovery(pop());
+    TypeBuilder? bound = nullIfParserRecovery(pop()) as TypeBuilder?;
     // Peek to leave type parameters on top of stack.
-    List<TypeVariableBuilder> typeParameters = peek();
+    List<TypeVariableBuilder>? typeParameters =
+        peek() as List<TypeVariableBuilder>?;
     if (typeParameters != null) {
       typeParameters[index].bound = bound;
       if (variance != null) {
@@ -1901,9 +1943,10 @@
     debugEvent("endTypeVariables");
 
     // Peek to leave type parameters on top of stack.
-    List<TypeVariableBuilder> typeParameters = peek();
+    List<TypeVariableBuilder>? typeParameters =
+        peek() as List<TypeVariableBuilder>?;
 
-    Map<String, TypeVariableBuilder> typeVariablesByName;
+    Map<String, TypeVariableBuilder>? typeVariablesByName;
     if (typeParameters != null) {
       for (TypeVariableBuilder builder in typeParameters) {
         if (builder.bound != null) {
@@ -1923,20 +1966,20 @@
           // it for now. It will be reported when processing one of the
           // `builder`s that is in fact `inside` the cycle. This matches the
           // cyclic class hierarchy error.
-          TypeVariableBuilder bound = builder;
+          TypeVariableBuilder? bound = builder;
           for (int steps = 0;
-              bound.bound != null && steps < typeParameters.length;
+              bound!.bound != null && steps < typeParameters.length;
               ++steps) {
-            bound = typeVariablesByName[bound.bound.name];
+            bound = typeVariablesByName[bound.bound!.name];
             if (bound == null || bound == builder) break;
           }
-          if (bound == builder && bound.bound != null) {
+          if (bound == builder && bound!.bound != null) {
             // Write out cycle.
             List<String> via = <String>[];
-            bound = typeVariablesByName[builder.bound.name];
+            bound = typeVariablesByName[builder.bound!.name];
             while (bound != builder) {
-              via.add(bound.name);
-              bound = typeVariablesByName[bound.bound.name];
+              via.add(bound!.name);
+              bound = typeVariablesByName[bound.bound!.name];
             }
             Message message = via.isEmpty
                 ? templateDirectCycleInTypeVariables.withArguments(builder.name)
@@ -1970,25 +2013,26 @@
       Token partKeyword, Token ofKeyword, Token semicolon, bool hasName) {
     debugEvent("endPartOf");
     int charOffset = popCharOffset();
-    Object containingLibrary = pop();
-    List<MetadataBuilder> metadata = pop();
+    Object? containingLibrary = pop();
+    List<MetadataBuilder>? metadata = pop() as List<MetadataBuilder>?;
     if (hasName) {
       libraryBuilder.addPartOf(metadata,
-          flattenName(containingLibrary, charOffset, uri), null, charOffset);
+          flattenName(containingLibrary!, charOffset, uri), null, charOffset);
     } else {
-      libraryBuilder.addPartOf(metadata, null, containingLibrary, charOffset);
+      libraryBuilder.addPartOf(
+          metadata, null, containingLibrary as String?, charOffset);
     }
   }
 
   @override
   void endConstructorReference(
-      Token start, Token periodBeforeName, Token endToken) {
+      Token start, Token? periodBeforeName, Token endToken) {
     debugEvent("ConstructorReference");
     popIfNotNull(periodBeforeName); // charOffset.
-    String suffix = popIfNotNull(periodBeforeName);
-    List<TypeBuilder> typeArguments = pop();
-    int charOffset = pop();
-    Object name = pop();
+    String? suffix = popIfNotNull(periodBeforeName) as String?;
+    List<TypeBuilder>? typeArguments = pop() as List<TypeBuilder>?;
+    int charOffset = popCharOffset();
+    Object name = pop()!;
     if (name is ParserRecovery) {
       push(name);
     } else {
@@ -1999,7 +2043,7 @@
 
   @override
   void beginFactoryMethod(
-      Token lastConsumed, Token externalToken, Token constToken) {
+      Token lastConsumed, Token? externalToken, Token? constToken) {
     inConstructor = true;
     libraryBuilder.beginNestedDeclaration(
         TypeParameterScopeKind.factoryMethod, "#factory_method",
@@ -2012,22 +2056,24 @@
   void endClassFactoryMethod(
       Token beginToken, Token factoryKeyword, Token endToken) {
     debugEvent("ClassFactoryMethod");
-    MethodBody kind = pop();
-    ConstructorReferenceBuilder redirectionTarget;
+    MethodBody kind = pop() as MethodBody;
+    ConstructorReferenceBuilder? redirectionTarget;
     if (kind == MethodBody.RedirectingFactoryBody) {
-      redirectionTarget = nullIfParserRecovery(pop());
+      redirectionTarget =
+          nullIfParserRecovery(pop()) as ConstructorReferenceBuilder?;
     }
-    AsyncMarker asyncModifier = pop();
-    List<FormalParameterBuilder> formals = pop();
-    int formalsOffset = pop();
+    AsyncMarker asyncModifier = pop() as AsyncMarker;
+    List<FormalParameterBuilder>? formals =
+        pop() as List<FormalParameterBuilder>?;
+    int formalsOffset = popCharOffset();
     pop(); // type variables
-    int charOffset = pop();
-    Object name = pop();
-    int modifiers = pop();
+    int charOffset = popCharOffset();
+    Object name = pop()!;
+    int modifiers = pop() as int;
     if (nativeMethodName != null) {
       modifiers |= externalMask;
     }
-    List<MetadataBuilder> metadata = pop();
+    List<MetadataBuilder>? metadata = pop() as List<MetadataBuilder>?;
     if (name is ParserRecovery) {
       libraryBuilder.endNestedDeclaration(
           TypeParameterScopeKind.factoryMethod, "<syntax-error>");
@@ -2067,8 +2113,8 @@
   @override
   void endFieldInitializer(Token assignmentOperator, Token token) {
     debugEvent("FieldInitializer");
-    Token beforeLast = assignmentOperator.next;
-    Token next = beforeLast.next;
+    Token beforeLast = assignmentOperator.next!;
+    Token next = beforeLast.next!;
     while (next != token && !next.isEof) {
       // To avoid storing the rest of the token stream, we need to identify the
       // token before [token]. That token will be the last token of the
@@ -2079,7 +2125,7 @@
       // TODO(ahe): I don't even think this is necessary. [token] points to ;
       // or , and we don't otherwise store tokens.
       beforeLast = next;
-      next = next.next;
+      next = next.next!;
     }
     push(assignmentOperator.next);
     push(beforeLast);
@@ -2122,14 +2168,14 @@
   void handleClassWithClause(Token withKeyword) {
     debugEvent("ClassWithClause");
 
-    Object mixins = pop();
-    int extendsOffset = pop();
-    Object supertype = pop();
+    Object? mixins = pop();
+    int extendsOffset = popCharOffset();
+    Object? supertype = pop();
     if (supertype is ParserRecovery || mixins is ParserRecovery) {
       push(new ParserRecovery(withKeyword.charOffset));
     } else {
-      push(libraryBuilder.addMixinApplication(
-          supertype, mixins, withKeyword.charOffset));
+      push(libraryBuilder.addMixinApplication(supertype as TypeBuilder?,
+          mixins as List<TypeBuilder>, withKeyword.charOffset));
     }
     push(extendsOffset);
   }
@@ -2140,7 +2186,7 @@
   }
 
   @override
-  void handleClassHeader(Token begin, Token classKeyword, Token nativeToken) {
+  void handleClassHeader(Token begin, Token classKeyword, Token? nativeToken) {
     debugEvent("ClassHeader");
     nativeMethodName = null;
   }
@@ -2158,13 +2204,13 @@
   }
 
   @override
-  void handleAsyncModifier(Token asyncToken, Token starToken) {
+  void handleAsyncModifier(Token? asyncToken, Token? starToken) {
     debugEvent("AsyncModifier");
     push(asyncMarkerFromTokens(asyncToken, starToken));
   }
 
   void addProblem(Message message, int charOffset, int length,
-      {bool wasHandled: false, List<LocatedMessage> context}) {
+      {bool wasHandled: false, List<LocatedMessage>? context}) {
     libraryBuilder.addProblem(message, charOffset, length, uri,
         wasHandled: wasHandled, context: context);
   }
diff --git a/pkg/front_end/lib/src/fasta/source/scope_listener.dart b/pkg/front_end/lib/src/fasta/source/scope_listener.dart
index c445403..ee9b746 100644
--- a/pkg/front_end/lib/src/fasta/source/scope_listener.dart
+++ b/pkg/front_end/lib/src/fasta/source/scope_listener.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.scope_listener;
 
 import 'package:_fe_analyzer_shared/src/parser/block_kind.dart' show BlockKind;
@@ -28,11 +26,11 @@
 abstract class ScopeListener<J> extends StackListenerImpl {
   Scope scope;
 
-  J breakTarget;
+  J? breakTarget;
 
-  J continueTarget;
+  J? continueTarget;
 
-  ScopeListener(Scope scope) : scope = scope ?? new Scope.immutable();
+  ScopeListener(Scope? scope) : scope = scope ?? new Scope.immutable();
 
   J createJumpTarget(JumpTargetKind kind, int charOffset);
 
@@ -48,36 +46,37 @@
     return createJumpTarget(JumpTargetKind.Goto, charOffset);
   }
 
-  void enterLocalScope(String debugName, [Scope newScope]) {
+  void enterLocalScope(String debugName, [Scope? newScope]) {
     push(scope);
     scope = newScope ?? scope.createNestedScope(debugName);
   }
 
   @override
   void exitLocalScope() {
-    scope = pop();
+    scope = pop() as Scope;
+    // ignore: unnecessary_null_comparison
     assert(scope != null);
   }
 
-  void enterBreakTarget(int charOffset, [J target]) {
+  void enterBreakTarget(int charOffset, [J? target]) {
     push(breakTarget ?? NullValue.BreakTarget);
     breakTarget = target ?? createBreakTarget(charOffset);
   }
 
-  void enterContinueTarget(int charOffset, [J target]) {
+  void enterContinueTarget(int charOffset, [J? target]) {
     push(continueTarget ?? NullValue.ContinueTarget);
     continueTarget = target ?? createContinueTarget(charOffset);
   }
 
-  J exitBreakTarget() {
-    J current = breakTarget;
-    breakTarget = pop();
+  J? exitBreakTarget() {
+    J? current = breakTarget;
+    breakTarget = pop() as J?;
     return current;
   }
 
-  J exitContinueTarget() {
-    J current = continueTarget;
-    continueTarget = pop();
+  J? exitContinueTarget() {
+    J? current = continueTarget;
+    continueTarget = pop() as J?;
     return current;
   }
 
@@ -100,7 +99,7 @@
   }
 
   @override
-  void beginForControlFlow(Token awaitToken, Token forToken) {
+  void beginForControlFlow(Token? awaitToken, Token forToken) {
     debugEvent("beginForControlFlow");
     enterLocalScope("for in a collection");
   }
@@ -139,7 +138,7 @@
   @override
   void endDoWhileStatementBody(Token token) {
     debugEvent("endDoWhileStatementBody");
-    Object body = pop();
+    Object? body = pop();
     exitLocalScope();
     push(body);
   }
@@ -153,7 +152,7 @@
   @override
   void endWhileStatementBody(Token token) {
     debugEvent("endWhileStatementBody");
-    Object body = pop();
+    Object? body = pop();
     exitLocalScope();
     push(body);
   }
@@ -167,7 +166,7 @@
   @override
   void endForStatementBody(Token token) {
     debugEvent("endForStatementBody");
-    Object body = pop();
+    Object? body = pop();
     exitLocalScope();
     push(body);
   }
@@ -181,7 +180,7 @@
   @override
   void endForInBody(Token token) {
     debugEvent("endForInBody");
-    Object body = pop();
+    Object? body = pop();
     exitLocalScope();
     push(body);
   }
@@ -195,7 +194,7 @@
   @override
   void endThenStatement(Token token) {
     debugEvent("endThenStatement");
-    Object body = pop();
+    Object? body = pop();
     exitLocalScope();
     push(body);
   }
@@ -209,7 +208,7 @@
   @override
   void endElseStatement(Token token) {
     debugEvent("endElseStatement");
-    Object body = pop();
+    Object? body = pop();
     exitLocalScope();
     push(body);
   }
diff --git a/pkg/front_end/lib/src/fasta/source/source_class_builder.dart b/pkg/front_end/lib/src/fasta/source/source_class_builder.dart
index 7e453ba..0bb1220 100644
--- a/pkg/front_end/lib/src/fasta/source/source_class_builder.dart
+++ b/pkg/front_end/lib/src/fasta/source/source_class_builder.dart
@@ -2,11 +2,8 @@
 // for 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
-
 library fasta.source_class_builder;
 
-import 'package:front_end/src/fasta/kernel/combined_member_signature.dart';
 import 'package:kernel/ast.dart';
 import 'package:kernel/class_hierarchy.dart' show ClassHierarchy;
 import 'package:kernel/reference_from_index.dart' show IndexedClass;
@@ -38,6 +35,7 @@
 
 import '../fasta_codes.dart';
 
+import '../kernel/combined_member_signature.dart';
 import '../kernel/kernel_builder.dart' show compareProcedures;
 import '../kernel/kernel_target.dart' show KernelTarget;
 import '../kernel/redirecting_factory_body.dart' show RedirectingFactoryBody;
@@ -56,21 +54,20 @@
 import 'source_library_builder.dart' show SourceLibraryBuilder;
 
 Class initializeClass(
-    Class cls,
-    List<TypeVariableBuilder> typeVariables,
+    Class? cls,
+    List<TypeVariableBuilder>? typeVariables,
     String name,
     SourceLibraryBuilder parent,
     int startCharOffset,
     int charOffset,
     int charEndOffset,
-    Class referencesFrom) {
+    IndexedClass? referencesFrom) {
   cls ??= new Class(
       name: name,
       typeParameters:
           TypeVariableBuilder.typeParametersFromBuilders(typeVariables),
-      reference: referencesFrom?.reference,
+      reference: referencesFrom?.cls.reference,
       fileUri: parent.fileUri);
-  cls.fileUri ??= parent.fileUri;
   if (cls.startFileOffset == TreeNode.noOffset) {
     cls.startFileOffset = startCharOffset;
   }
@@ -89,39 +86,35 @@
   @override
   final Class actualCls;
 
-  final List<ConstructorReferenceBuilder> constructorReferences;
+  final List<ConstructorReferenceBuilder>? constructorReferences;
 
-  TypeBuilder mixedInTypeBuilder;
+  TypeBuilder? mixedInTypeBuilder;
 
   bool isMixinDeclaration;
 
-  final Class referencesFrom;
-  final IndexedClass referencesFromIndexed;
+  final IndexedClass? referencesFromIndexed;
 
   SourceClassBuilder(
-    List<MetadataBuilder> metadata,
+    List<MetadataBuilder>? metadata,
     int modifiers,
     String name,
-    List<TypeVariableBuilder> typeVariables,
-    TypeBuilder supertype,
-    List<TypeBuilder> interfaces,
-    List<TypeBuilder> onTypes,
+    List<TypeVariableBuilder>? typeVariables,
+    TypeBuilder? supertype,
+    List<TypeBuilder>? interfaces,
+    List<TypeBuilder>? onTypes,
     Scope scope,
     ConstructorScope constructors,
-    LibraryBuilder parent,
+    SourceLibraryBuilder parent,
     this.constructorReferences,
     int startCharOffset,
     int nameOffset,
     int charEndOffset,
-    Class referencesFrom,
-    IndexedClass referencesFromIndexed, {
-    Class cls,
+    this.referencesFromIndexed, {
+    Class? cls,
     this.mixedInTypeBuilder,
     this.isMixinDeclaration = false,
   })  : actualCls = initializeClass(cls, typeVariables, name, parent,
-            startCharOffset, nameOffset, charEndOffset, referencesFrom),
-        referencesFrom = referencesFrom,
-        referencesFromIndexed = referencesFromIndexed,
+            startCharOffset, nameOffset, charEndOffset, referencesFromIndexed),
         super(metadata, modifiers, name, typeVariables, supertype, interfaces,
             onTypes, scope, constructors, parent, nameOffset) {
     actualCls.hasConstConstructor = declaresConstConstructor;
@@ -131,7 +124,7 @@
   Class get cls => origin.actualCls;
 
   @override
-  SourceLibraryBuilder get library => super.library;
+  SourceLibraryBuilder get library => super.library as SourceLibraryBuilder;
 
   Class build(SourceLibraryBuilder library, LibraryBuilder coreLibrary) {
     SourceLibraryBuilder.checkMemberConflicts(library, scope,
@@ -140,15 +133,18 @@
         checkForInstanceVsStaticConflict: false,
         checkForMethodVsSetterConflict: false);
 
-    void buildBuilders(String name, Builder declaration) {
-      do {
+    void buildBuilders(String name, Builder? declaration) {
+      while (declaration != null) {
         if (declaration.parent != this) {
-          if (fileUri != declaration.parent.fileUri) {
-            unexpected("$fileUri", "${declaration.parent.fileUri}", charOffset,
+          if (fileUri != declaration.parent?.fileUri) {
+            unexpected("$fileUri", "${declaration.parent?.fileUri}", charOffset,
                 fileUri);
           } else {
-            unexpected(fullNameForErrors, declaration.parent?.fullNameForErrors,
-                charOffset, fileUri);
+            unexpected(
+                fullNameForErrors,
+                declaration.parent?.fullNameForErrors ?? '',
+                charOffset,
+                fileUri);
           }
         } else if (declaration is MemberBuilderImpl) {
           MemberBuilderImpl memberBuilder = declaration;
@@ -177,13 +173,15 @@
               declaration.charOffset, declaration.fileUri);
         }
         declaration = declaration.next;
-      } while (declaration != null);
+      }
     }
 
     scope.forEach(buildBuilders);
     constructors.forEach(buildBuilders);
-    supertypeBuilder = checkSupertype(supertypeBuilder);
-    Supertype supertype =
+    if (supertypeBuilder != null) {
+      supertypeBuilder = checkSupertype(supertypeBuilder!);
+    }
+    Supertype? supertype =
         supertypeBuilder?.buildSupertype(library, charOffset, fileUri);
     if (supertype != null) {
       Class superclass = supertype.classNode;
@@ -197,13 +195,13 @@
     }
     if (!isMixinDeclaration &&
         actualCls.supertype != null &&
-        actualCls.superclass.isMixinDeclaration) {
+        actualCls.superclass!.isMixinDeclaration) {
       // Declared mixins have interfaces that can be implemented, but they
       // cannot be extended.  However, a mixin declaration with a single
       // superclass constraint is encoded with the constraint as the supertype,
       // and that is allowed to be a mixin's interface.
       library.addProblem(
-          templateSupertypeIsIllegal.withArguments(actualCls.superclass.name),
+          templateSupertypeIsIllegal.withArguments(actualCls.superclass!.name),
           charOffset,
           noLength,
           fileUri);
@@ -214,8 +212,10 @@
     }
     actualCls.supertype = supertype;
 
-    mixedInTypeBuilder = checkSupertype(mixedInTypeBuilder);
-    Supertype mixedInType =
+    if (mixedInTypeBuilder != null) {
+      mixedInTypeBuilder = checkSupertype(mixedInTypeBuilder!);
+    }
+    Supertype? mixedInType =
         mixedInTypeBuilder?.buildMixedInType(library, charOffset, fileUri);
     if (mixedInType != null) {
       Class superclass = mixedInType.classNode;
@@ -238,10 +238,10 @@
     // compile-time error.
     cls.isAbstract = isAbstract;
     if (interfaceBuilders != null) {
-      for (int i = 0; i < interfaceBuilders.length; ++i) {
-        interfaceBuilders[i] = checkSupertype(interfaceBuilders[i]);
-        Supertype supertype =
-            interfaceBuilders[i].buildSupertype(library, charOffset, fileUri);
+      for (int i = 0; i < interfaceBuilders!.length; ++i) {
+        interfaceBuilders![i] = checkSupertype(interfaceBuilders![i]);
+        Supertype? supertype =
+            interfaceBuilders![i].buildSupertype(library, charOffset, fileUri);
         if (supertype != null) {
           Class superclass = supertype.classNode;
           if (superclass.name == 'Function' &&
@@ -257,7 +257,7 @@
     }
 
     constructors.forEach((String name, Builder constructor) {
-      Builder member = scopeBuilder[name];
+      Builder? member = scopeBuilder[name];
       if (member == null) return;
       if (!member.isStatic) return;
       // TODO(ahe): Revisit these messages. It seems like the last two should
@@ -279,7 +279,7 @@
     });
 
     scope.forEachLocalSetter((String name, Builder setter) {
-      Builder constructor = constructorScopeBuilder[name];
+      Builder? constructor = constructorScopeBuilder[name];
       if (constructor == null || !setter.isStatic) return;
       addProblem(templateConflictsWithConstructor.withArguments(name),
           setter.charOffset, noLength);
@@ -292,36 +292,37 @@
   }
 
   TypeBuilder checkSupertype(TypeBuilder supertype) {
-    if (typeVariables == null || supertype == null) return supertype;
-    Message message;
-    for (int i = 0; i < typeVariables.length; ++i) {
+    if (typeVariables == null) return supertype;
+    Message? message;
+    for (int i = 0; i < typeVariables!.length; ++i) {
+      TypeVariableBuilder typeVariableBuilder = typeVariables![i];
       int variance = computeTypeVariableBuilderVariance(
-          typeVariables[i], supertype, library);
-      if (!Variance.greaterThanOrEqual(variance, typeVariables[i].variance)) {
-        if (typeVariables[i].parameter.isLegacyCovariant) {
+          typeVariableBuilder, supertype, library);
+      if (!Variance.greaterThanOrEqual(variance, typeVariables![i].variance)) {
+        if (typeVariables![i].parameter.isLegacyCovariant) {
           message = templateInvalidTypeVariableInSupertype.withArguments(
-              typeVariables[i].name,
+              typeVariables![i].name,
               Variance.keywordString(variance),
-              supertype.name);
+              supertype.name as String);
         } else {
           message =
               templateInvalidTypeVariableInSupertypeWithVariance.withArguments(
-                  Variance.keywordString(typeVariables[i].variance),
-                  typeVariables[i].name,
+                  Variance.keywordString(typeVariables![i].variance),
+                  typeVariables![i].name,
                   Variance.keywordString(variance),
-                  supertype.name);
+                  supertype.name as String);
         }
         library.addProblem(message, charOffset, noLength, fileUri);
       }
     }
     if (message != null) {
       return new NamedTypeBuilder(
-          supertype.name,
+          supertype.name as String,
           const NullabilityBuilder.omitted(),
           /* arguments = */ null,
           fileUri,
           charOffset)
-        ..bind(new InvalidTypeDeclarationBuilder(supertype.name,
+        ..bind(new InvalidTypeDeclarationBuilder(supertype.name as String,
             message.withLocation(fileUri, charOffset, noLength)));
     }
     return supertype;
@@ -356,6 +357,7 @@
         procedure.function.namedParameters;
     DartType returnType = procedure.function.returnType;
 
+    // ignore: unnecessary_null_comparison
     if (functionTypeParameters != null) {
       for (TypeParameter functionParameter in functionTypeParameters) {
         for (TypeParameter typeParameter in typeParameters) {
@@ -366,6 +368,7 @@
         }
       }
     }
+    // ignore: unnecessary_null_comparison
     if (positionalParameters != null) {
       for (VariableDeclaration formal in positionalParameters) {
         if (!formal.isCovariant) {
@@ -378,6 +381,7 @@
         }
       }
     }
+    // ignore: unnecessary_null_comparison
     if (namedParameters != null) {
       for (VariableDeclaration named in namedParameters) {
         for (TypeParameter typeParameter in typeParameters) {
@@ -388,6 +392,7 @@
         }
       }
     }
+    // ignore: unnecessary_null_comparison
     if (returnType != null) {
       for (TypeParameter typeParameter in typeParameters) {
         int returnTypeVariance = computeVariance(typeParameter, returnType);
@@ -408,11 +413,11 @@
       if (isReturnType) {
         message = templateInvalidTypeVariableVariancePositionInReturnType
             .withArguments(Variance.keywordString(typeParameter.variance),
-                typeParameter.name, Variance.keywordString(variance));
+                typeParameter.name!, Variance.keywordString(variance));
       } else {
         message = templateInvalidTypeVariableVariancePosition.withArguments(
             Variance.keywordString(typeParameter.variance),
-            typeParameter.name,
+            typeParameter.name!,
             Variance.keywordString(variance));
       }
       library.reportTypeArgumentIssue(message, fileUri, fileOffset,
@@ -475,8 +480,8 @@
               template.withArguments(
                   argument,
                   typeParameter.bound,
-                  typeParameter.name,
-                  getGenericTypeName(issue.enclosingType),
+                  typeParameter.name!,
+                  getGenericTypeName(issue.enclosingType!),
                   supertype.classNode.name,
                   name,
                   library.isNonNullableByDefault),
@@ -502,11 +507,12 @@
 
     // Check in supers.
     if (cls.supertype != null) {
-      checkBoundsInSupertype(cls.supertype, typeEnvironment);
+      checkBoundsInSupertype(cls.supertype!, typeEnvironment);
     }
     if (cls.mixedInType != null) {
-      checkBoundsInSupertype(cls.mixedInType, typeEnvironment);
+      checkBoundsInSupertype(cls.mixedInType!, typeEnvironment);
     }
+    // ignore: unnecessary_null_comparison
     if (cls.implementedTypes != null) {
       for (Supertype supertype in cls.implementedTypes) {
         checkBoundsInSupertype(supertype, typeEnvironment);
@@ -580,16 +586,15 @@
   /// after expansion of type aliases, if any. For each supertype key, the
   /// corresponding value is the type alias which was unaliased in order to
   /// find the supertype, or null if the supertype was not aliased.
-  Map<TypeDeclarationBuilder, TypeAliasBuilder> computeDirectSupertypes(
+  Map<TypeDeclarationBuilder?, TypeAliasBuilder?> computeDirectSupertypes(
       ClassBuilder objectClass) {
-    final Map<TypeDeclarationBuilder, TypeAliasBuilder> result =
-        <TypeDeclarationBuilder, TypeAliasBuilder>{};
-    final TypeBuilder supertype = this.supertypeBuilder;
+    final Map<TypeDeclarationBuilder?, TypeAliasBuilder?> result = {};
+    final TypeBuilder? supertype = this.supertypeBuilder;
     if (supertype != null) {
-      TypeDeclarationBuilder declarationBuilder = supertype.declaration;
+      TypeDeclarationBuilder? declarationBuilder = supertype.declaration;
       if (declarationBuilder is TypeAliasBuilder) {
         TypeAliasBuilder aliasBuilder = declarationBuilder;
-        NamedTypeBuilder namedBuilder = supertype;
+        NamedTypeBuilder namedBuilder = supertype as NamedTypeBuilder;
         declarationBuilder = aliasBuilder.unaliasDeclaration(
             namedBuilder.arguments,
             isUsedAsClass: true,
@@ -602,14 +607,14 @@
     } else if (objectClass != this) {
       result[objectClass] = null;
     }
-    final List<TypeBuilder> interfaces = this.interfaceBuilders;
+    final List<TypeBuilder>? interfaces = this.interfaceBuilders;
     if (interfaces != null) {
       for (int i = 0; i < interfaces.length; i++) {
         TypeBuilder interface = interfaces[i];
-        TypeDeclarationBuilder declarationBuilder = interface.declaration;
+        TypeDeclarationBuilder? declarationBuilder = interface.declaration;
         if (declarationBuilder is TypeAliasBuilder) {
           TypeAliasBuilder aliasBuilder = declarationBuilder;
-          NamedTypeBuilder namedBuilder = interface;
+          NamedTypeBuilder namedBuilder = interface as NamedTypeBuilder;
           declarationBuilder = aliasBuilder.unaliasDeclaration(
               namedBuilder.arguments,
               isUsedAsClass: true,
@@ -621,13 +626,13 @@
         }
       }
     }
-    final TypeBuilder mixedInTypeBuilder = this.mixedInTypeBuilder;
+    final TypeBuilder? mixedInTypeBuilder = this.mixedInTypeBuilder;
     if (mixedInTypeBuilder != null) {
-      TypeDeclarationBuilder declarationBuilder =
+      TypeDeclarationBuilder? declarationBuilder =
           mixedInTypeBuilder.declaration;
       if (declarationBuilder is TypeAliasBuilder) {
         TypeAliasBuilder aliasBuilder = declarationBuilder;
-        NamedTypeBuilder namedBuilder = mixedInTypeBuilder;
+        NamedTypeBuilder namedBuilder = mixedInTypeBuilder as NamedTypeBuilder;
         declarationBuilder = aliasBuilder.unaliasDeclaration(
             namedBuilder.arguments,
             isUsedAsClass: true,
@@ -650,7 +655,8 @@
 
   bool _addMissingNoSuchMethodForwarders(
       KernelTarget target, Set<Member> existingForwarders,
-      {bool forSetters}) {
+      {required bool forSetters}) {
+    // ignore: unnecessary_null_comparison
     assert(forSetters != null);
 
     ClassHierarchy hierarchy = target.loader.hierarchy;
@@ -662,8 +668,8 @@
     List<Member> declaredMembers =
         hierarchy.getDeclaredMembers(cls, setters: forSetters);
 
-    Member noSuchMethod = ClassHierarchy.findMemberByName(
-        hierarchy.getInterfaceMembers(cls), noSuchMethodName);
+    Procedure noSuchMethod = ClassHierarchy.findMemberByName(
+        hierarchy.getInterfaceMembers(cls), noSuchMethodName) as Procedure;
     bool clsHasUserDefinedNoSuchMethod =
         hasUserDefinedNoSuchMethod(cls, hierarchy, target.objectClass);
 
@@ -678,27 +684,27 @@
     for (Member member in allMembers) {
       (sameNameMembers[member.name] ??= []).add(member);
     }
-    for (Name name in sameNameMembers.keys) {
-      List<Member> members = sameNameMembers[name];
+    for (MapEntry<Name, List<Member>> entry in sameNameMembers.entries) {
+      List<Member> members = entry.value;
       assert(members.isNotEmpty);
       CombinedMemberSignatureBuilder combinedMemberSignature =
           new CombinedMemberSignatureBuilder(hierarchy, this, members,
               forSetter: forSetters);
-      Member member = combinedMemberSignature.canonicalMember;
+      Member? member = combinedMemberSignature.canonicalMember;
       if (member != null) {
         if (_isForwarderRequired(
                 clsHasUserDefinedNoSuchMethod, member, cls, concreteMembers,
-                isPatch: member.fileUri != member.enclosingClass.fileUri) &&
+                isPatch: member.fileUri != member.enclosingClass!.fileUri) &&
             !existingForwarders.contains(member)) {
           assert(!combinedMemberSignature.needsCovarianceMerging,
               "Needed covariant merging for ${members}");
           if (ClassHierarchy.findMemberByName(declaredMembers, member.name) !=
               null) {
             _transformProcedureToNoSuchMethodForwarder(
-                noSuchMethod, target, member);
+                noSuchMethod, target, member as Procedure);
           } else {
             Procedure memberSignature =
-                combinedMemberSignature.createMemberFromSignature();
+                combinedMemberSignature.createMemberFromSignature()!;
             _transformProcedureToNoSuchMethodForwarder(
                 noSuchMethod, target, memberSignature);
             cls.procedures.add(memberSignature);
@@ -729,7 +735,7 @@
     Set<Member> existingForwarders = new Set<Member>.identity();
     Set<Member> existingSetterForwarders = new Set<Member>.identity();
     {
-      Class nearestConcreteSuperclass = cls.superclass;
+      Class? nearestConcreteSuperclass = cls.superclass;
       while (nearestConcreteSuperclass != null &&
           nearestConcreteSuperclass.isAbstract) {
         nearestConcreteSuperclass = nearestConcreteSuperclass.superclass;
@@ -744,7 +750,7 @@
               in hierarchy.getInterfaceMembers(nearestConcreteSuperclass)) {
             if (_isForwarderRequired(superHasUserDefinedNoSuchMethod, member,
                 nearestConcreteSuperclass, concrete,
-                isPatch: member.fileUri != member.enclosingClass.fileUri)) {
+                isPatch: member.fileUri != member.enclosingClass!.fileUri)) {
               existingForwarders.add(member);
             }
           }
@@ -801,7 +807,9 @@
   }
 
   void _transformProcedureToNoSuchMethodForwarder(
-      Member noSuchMethodInterface, KernelTarget target, Procedure procedure) {
+      Procedure noSuchMethodInterface,
+      KernelTarget target,
+      Procedure procedure) {
     String prefix = procedure.isGetter
         ? 'get:'
         : procedure.isSetter
@@ -821,7 +829,7 @@
         .loader.target.backendTarget.supportsNewMethodInvocationEncoding) {
       result = new InstanceInvocation(InstanceAccessKind.Instance,
           new ThisExpression(), noSuchMethodName, new Arguments([invocation]),
-          functionType: noSuchMethodInterface.getterType,
+          functionType: noSuchMethodInterface.getterType as FunctionType,
           interfaceTarget: noSuchMethodInterface)
         ..fileOffset = procedure.fileOffset;
     } else {
@@ -837,8 +845,8 @@
         ..fileOffset = procedure.fileOffset;
     }
     procedure.function.body = new ReturnStatement(result)
-      ..fileOffset = procedure.fileOffset;
-    procedure.function.body.parent = procedure.function;
+      ..fileOffset = procedure.fileOffset
+      ..parent = procedure.function;
     procedure.function.asyncMarker = AsyncMarker.Sync;
     procedure.function.dartAsyncMarker = AsyncMarker.Sync;
 
@@ -848,7 +856,7 @@
   }
 
   void _addRedirectingConstructor(ProcedureBuilder constructorBuilder,
-      SourceLibraryBuilder library, Reference getterReference) {
+      SourceLibraryBuilder library, Reference? getterReference) {
     // Add a new synthetic field to this class for representing factory
     // constructors. This is used to support resolving such constructors in
     // source code.
@@ -861,8 +869,8 @@
     // [constructor.target].
     //
     // TODO(ahe): Add a kernel node to represent redirecting factory bodies.
-    DillFieldBuilder constructorsField =
-        origin.scope.lookupLocalMember(redirectingName, setter: false);
+    DillFieldBuilder? constructorsField = origin.scope
+        .lookupLocalMember(redirectingName, setter: false) as DillFieldBuilder?;
     if (constructorsField == null) {
       ListLiteral literal = new ListLiteral(<Expression>[]);
       Name name = new Name(redirectingName, library.library);
@@ -878,44 +886,44 @@
       origin.scope
           .addLocalMember(redirectingName, constructorsField, setter: false);
     }
-    Field field = constructorsField.member;
-    ListLiteral literal = field.initializer;
+    Field field = constructorsField.field;
+    ListLiteral literal = field.initializer as ListLiteral;
     literal.expressions
         .add(new StaticGet(constructorBuilder.procedure)..parent = literal);
   }
 
   @override
-  int resolveConstructors(LibraryBuilder library) {
+  int resolveConstructors(SourceLibraryBuilder library) {
     if (constructorReferences == null) return 0;
-    for (ConstructorReferenceBuilder ref in constructorReferences) {
+    for (ConstructorReferenceBuilder ref in constructorReferences!) {
       ref.resolveIn(scope, library);
     }
-    int count = constructorReferences.length;
+    int count = constructorReferences!.length;
     if (count != 0) {
       Map<String, MemberBuilder> constructors = this.constructors.local;
       // Copy keys to avoid concurrent modification error.
-      List<String> names = constructors.keys.toList();
-      for (String name in names) {
-        Builder declaration = constructors[name];
-        do {
+      for (MapEntry<String, MemberBuilder> entry in constructors.entries) {
+        Builder? declaration = entry.value;
+        while (declaration != null) {
           if (declaration.parent != this) {
-            unexpected("$fileUri", "${declaration.parent.fileUri}", charOffset,
+            unexpected("$fileUri", "${declaration.parent!.fileUri}", charOffset,
                 fileUri);
           }
           if (declaration is RedirectingFactoryBuilder) {
             // Compute the immediate redirection target, not the effective.
             ConstructorReferenceBuilder redirectionTarget =
                 declaration.redirectionTarget;
+            // ignore: unnecessary_null_comparison
             if (redirectionTarget != null) {
-              Builder targetBuilder = redirectionTarget.target;
+              Builder? targetBuilder = redirectionTarget.target;
               if (declaration.next == null) {
                 // Only the first one (that is, the last on in the linked list)
                 // is actually in the kernel tree. This call creates a StaticGet
                 // to [declaration.target] in a field `_redirecting#` which is
                 // only legal to do to things in the kernel tree.
-                Reference getterReference =
+                Reference? getterReference =
                     referencesFromIndexed?.lookupGetterReference(new Name(
-                        "_redirecting#", referencesFromIndexed.library));
+                        "_redirecting#", referencesFromIndexed!.library));
                 _addRedirectingConstructor(
                     declaration, library, getterReference);
               }
@@ -923,7 +931,7 @@
                 List<DartType> typeArguments = declaration.typeArguments ??
                     new List<DartType>.filled(
                         targetBuilder
-                            .member.enclosingClass.typeParameters.length,
+                            .member.enclosingClass!.typeParameters.length,
                         const UnknownType());
                 declaration.setRedirectingFactoryBody(
                     targetBuilder.member, typeArguments);
@@ -931,7 +939,7 @@
                 List<DartType> typeArguments = declaration.typeArguments ??
                     new List<DartType>.filled(
                         targetBuilder
-                            .member.enclosingClass.typeParameters.length,
+                            .member.enclosingClass!.typeParameters.length,
                         const UnknownType());
                 declaration.setRedirectingFactoryBody(
                     targetBuilder.member, typeArguments);
@@ -959,7 +967,7 @@
             }
           }
           declaration = declaration.next;
-        } while (declaration != null);
+        }
       }
     }
     return count;
@@ -967,8 +975,11 @@
 
   void checkOverride(Types types, Member declaredMember, Member interfaceMember,
       bool isSetter, callback(Member interfaceMember, bool isSetter),
-      {bool isInterfaceCheck, bool declaredNeedsLegacyErasure}) {
+      {required bool isInterfaceCheck,
+      required bool declaredNeedsLegacyErasure}) {
+    // ignore: unnecessary_null_comparison
     assert(isInterfaceCheck != null);
+    // ignore: unnecessary_null_comparison
     assert(declaredNeedsLegacyErasure != null);
     if (declaredMember == interfaceMember) {
       return;
@@ -1067,20 +1078,20 @@
     }
 
     DartType getterType = getter.getterType;
-    if (getter.enclosingClass.typeParameters.isNotEmpty) {
+    if (getter.enclosingClass!.typeParameters.isNotEmpty) {
       getterType = Substitution.fromPairs(
-              getter.enclosingClass.typeParameters,
+              getter.enclosingClass!.typeParameters,
               types.hierarchy.getTypeArgumentsAsInstanceOf(
-                  thisType, getter.enclosingClass))
+                  thisType, getter.enclosingClass!)!)
           .substituteType(getterType);
     }
 
     DartType setterType = setter.setterType;
-    if (setter.enclosingClass.typeParameters.isNotEmpty) {
+    if (setter.enclosingClass!.typeParameters.isNotEmpty) {
       setterType = Substitution.fromPairs(
-              setter.enclosingClass.typeParameters,
+              setter.enclosingClass!.typeParameters,
               types.hierarchy.getTypeArgumentsAsInstanceOf(
-                  thisType, setter.enclosingClass))
+                  thisType, setter.enclosingClass!)!)
           .substituteType(setterType);
     }
 
@@ -1102,9 +1113,9 @@
       if (!isValid) {
         Member getterOrigin = getter.memberSignatureOrigin ?? getter;
         Member setterOrigin = setter.memberSignatureOrigin ?? setter;
-        String getterMemberName = '${getterOrigin.enclosingClass.name}'
+        String getterMemberName = '${getterOrigin.enclosingClass!.name}'
             '.${getterOrigin.name.text}';
-        String setterMemberName = '${setterOrigin.enclosingClass.name}'
+        String setterMemberName = '${setterOrigin.enclosingClass!.name}'
             '.${setterOrigin.name.text}';
         if (getterOrigin.enclosingClass == cls &&
             setterOrigin.enclosingClass == cls) {
@@ -1213,33 +1224,33 @@
     return unhandled('${member.runtimeType}', '_getMemberUri', -1, null);
   }
 
-  Substitution _computeInterfaceSubstitution(
+  Substitution? _computeInterfaceSubstitution(
       Types types,
       Member declaredMember,
       Member interfaceMember,
       Member interfaceMemberOrigin,
-      FunctionNode declaredFunction,
-      FunctionNode interfaceFunction,
+      FunctionNode? declaredFunction,
+      FunctionNode? interfaceFunction,
       bool isInterfaceCheck,
       bool declaredNeedsLegacyErasure) {
-    Substitution interfaceSubstitution = Substitution.empty;
-    if (interfaceMember.enclosingClass.typeParameters.isNotEmpty) {
-      Class enclosingClass = interfaceMember.enclosingClass;
+    Substitution? interfaceSubstitution;
+    if (interfaceMember.enclosingClass!.typeParameters.isNotEmpty) {
+      Class enclosingClass = interfaceMember.enclosingClass!;
       interfaceSubstitution = Substitution.fromPairs(
           enclosingClass.typeParameters,
           types.hierarchy
-              .getTypeArgumentsAsInstanceOf(thisType, enclosingClass));
+              .getTypeArgumentsAsInstanceOf(thisType, enclosingClass)!);
     }
 
-    if (declaredFunction?.typeParameters?.length !=
-        interfaceFunction?.typeParameters?.length) {
+    if (declaredFunction?.typeParameters.length !=
+        interfaceFunction?.typeParameters.length) {
       reportInvalidOverride(
           isInterfaceCheck,
           declaredMember,
           templateOverrideTypeVariablesMismatch.withArguments(
-              "${declaredMember.enclosingClass.name}."
+              "${declaredMember.enclosingClass!.name}."
                   "${declaredMember.name.text}",
-              "${interfaceMemberOrigin.enclosingClass.name}."
+              "${interfaceMemberOrigin.enclosingClass!.name}."
                   "${interfaceMemberOrigin.name.text}"),
           declaredMember.fileOffset,
           noLength,
@@ -1252,8 +1263,8 @@
     } else if (declaredFunction?.typeParameters != null) {
       Map<TypeParameter, DartType> substitutionMap =
           <TypeParameter, DartType>{};
-      for (int i = 0; i < declaredFunction.typeParameters.length; ++i) {
-        substitutionMap[interfaceFunction.typeParameters[i]] =
+      for (int i = 0; i < declaredFunction!.typeParameters.length; ++i) {
+        substitutionMap[interfaceFunction!.typeParameters[i]] =
             new TypeParameterType.forAlphaRenaming(
                 interfaceFunction.typeParameters[i],
                 declaredFunction.typeParameters[i]);
@@ -1261,7 +1272,7 @@
       Substitution substitution = Substitution.fromMap(substitutionMap);
       for (int i = 0; i < declaredFunction.typeParameters.length; ++i) {
         TypeParameter declaredParameter = declaredFunction.typeParameters[i];
-        TypeParameter interfaceParameter = interfaceFunction.typeParameters[i];
+        TypeParameter interfaceParameter = interfaceFunction!.typeParameters[i];
         if (!interfaceParameter.isGenericCovariantImpl) {
           DartType declaredBound = declaredParameter.bound;
           DartType interfaceBound = interfaceParameter.bound;
@@ -1286,11 +1297,11 @@
                 declaredMember,
                 templateOverrideTypeVariablesBoundMismatch.withArguments(
                     declaredBound,
-                    declaredParameter.name,
-                    "${declaredMember.enclosingClass.name}."
+                    declaredParameter.name!,
+                    "${declaredMember.enclosingClass!.name}."
                         "${declaredMember.name.text}",
                     computedBound,
-                    "${interfaceMemberOrigin.enclosingClass.name}."
+                    "${interfaceMemberOrigin.enclosingClass!.name}."
                         "${interfaceMemberOrigin.name.text}",
                     library.isNonNullableByDefault),
                 declaredMember.fileOffset,
@@ -1304,36 +1315,40 @@
           }
         }
       }
-      interfaceSubstitution =
-          Substitution.combine(interfaceSubstitution, substitution);
+      if (interfaceSubstitution != null) {
+        interfaceSubstitution =
+            Substitution.combine(interfaceSubstitution, substitution);
+      } else {
+        interfaceSubstitution = substitution;
+      }
     }
     return interfaceSubstitution;
   }
 
-  Substitution _computeDeclaredSubstitution(
+  Substitution? _computeDeclaredSubstitution(
       Types types, Member declaredMember) {
-    Substitution declaredSubstitution = Substitution.empty;
-    if (declaredMember.enclosingClass.typeParameters.isNotEmpty) {
-      Class enclosingClass = declaredMember.enclosingClass;
+    Substitution? declaredSubstitution;
+    if (declaredMember.enclosingClass!.typeParameters.isNotEmpty) {
+      Class enclosingClass = declaredMember.enclosingClass!;
       declaredSubstitution = Substitution.fromPairs(
           enclosingClass.typeParameters,
           types.hierarchy
-              .getTypeArgumentsAsInstanceOf(thisType, enclosingClass));
+              .getTypeArgumentsAsInstanceOf(thisType, enclosingClass)!);
     }
     return declaredSubstitution;
   }
 
   void _checkTypes(
       Types types,
-      Substitution interfaceSubstitution,
-      Substitution declaredSubstitution,
+      Substitution? interfaceSubstitution,
+      Substitution? declaredSubstitution,
       Member declaredMember,
       Member interfaceMember,
       Member interfaceMemberOrigin,
       DartType declaredType,
       DartType interfaceType,
       bool isCovariant,
-      VariableDeclaration declaredParameter,
+      VariableDeclaration? declaredParameter,
       bool isInterfaceCheck,
       bool declaredNeedsLegacyErasure,
       {bool asIfDeclaredParameter = false}) {
@@ -1375,10 +1390,10 @@
               !types.isSubtypeOf(
                   supertype, subtype, SubtypeCheckMode.ignoringNullabilities));
       if (isErrorInNnbdOptedOutMode || library.isNonNullableByDefault) {
-        String declaredMemberName = '${declaredMember.enclosingClass.name}'
+        String declaredMemberName = '${declaredMember.enclosingClass!.name}'
             '.${declaredMember.name.text}';
         String interfaceMemberName =
-            '${interfaceMemberOrigin.enclosingClass.name}'
+            '${interfaceMemberOrigin.enclosingClass!.name}'
             '.${interfaceMemberOrigin.name.text}';
         Message message;
         int fileOffset;
@@ -1402,7 +1417,7 @@
           fileOffset = declaredMember.fileOffset;
         } else {
           message = templateOverrideTypeMismatchParameter.withArguments(
-              declaredParameter.name,
+              declaredParameter.name!,
               declaredMemberName,
               declaredType,
               interfaceType,
@@ -1444,7 +1459,7 @@
     FunctionNode declaredFunction = declaredMember.function;
     FunctionNode interfaceFunction = interfaceMember.function;
 
-    Substitution interfaceSubstitution = _computeInterfaceSubstitution(
+    Substitution? interfaceSubstitution = _computeInterfaceSubstitution(
         types,
         declaredMember,
         interfaceMember,
@@ -1454,7 +1469,7 @@
         isInterfaceCheck,
         declaredNeedsLegacyErasure);
 
-    Substitution declaredSubstitution =
+    Substitution? declaredSubstitution =
         _computeDeclaredSubstitution(types, declaredMember);
 
     _checkTypes(
@@ -1476,9 +1491,9 @@
           isInterfaceCheck,
           declaredMember,
           templateOverrideFewerPositionalArguments.withArguments(
-              "${declaredMember.enclosingClass.name}."
+              "${declaredMember.enclosingClass!.name}."
                   "${declaredMember.name.text}",
-              "${interfaceMemberOrigin.enclosingClass.name}."
+              "${interfaceMemberOrigin.enclosingClass!.name}."
                   "${interfaceMemberOrigin.name.text}"),
           declaredMember.fileOffset,
           noLength,
@@ -1495,9 +1510,9 @@
           isInterfaceCheck,
           declaredMember,
           templateOverrideMoreRequiredArguments.withArguments(
-              "${declaredMember.enclosingClass.name}."
+              "${declaredMember.enclosingClass!.name}."
                   "${declaredMember.name.text}",
-              "${interfaceMemberOrigin.enclosingClass.name}."
+              "${interfaceMemberOrigin.enclosingClass!.name}."
                   "${interfaceMemberOrigin.name.text}"),
           declaredMember.fileOffset,
           noLength,
@@ -1552,9 +1567,9 @@
           isInterfaceCheck,
           declaredMember,
           templateOverrideFewerNamedArguments.withArguments(
-              "${declaredMember.enclosingClass.name}."
+              "${declaredMember.enclosingClass!.name}."
                   "${declaredMember.name.text}",
-              "${interfaceMemberOrigin.enclosingClass.name}."
+              "${interfaceMemberOrigin.enclosingClass!.name}."
                   "${interfaceMemberOrigin.name.text}"),
           declaredMember.fileOffset,
           noLength,
@@ -1565,8 +1580,9 @@
                     interfaceMemberOrigin.fileOffset, noLength)
           ]);
     }
+
     int compareNamedParameters(VariableDeclaration p0, VariableDeclaration p1) {
-      return p0.name.compareTo(p1.name);
+      return p0.name!.compareTo(p1.name!);
     }
 
     List<VariableDeclaration> sortedFromDeclared =
@@ -1589,10 +1605,10 @@
               isInterfaceCheck,
               declaredMember,
               templateOverrideMismatchNamedParameter.withArguments(
-                  "${declaredMember.enclosingClass.name}."
+                  "${declaredMember.enclosingClass!.name}."
                       "${declaredMember.name.text}",
-                  interfaceNamedParameters.current.name,
-                  "${interfaceMember.enclosingClass.name}."
+                  interfaceNamedParameters.current.name!,
+                  "${interfaceMember.enclosingClass!.name}."
                       "${interfaceMember.name.text}"),
               declaredMember.fileOffset,
               noLength,
@@ -1628,10 +1644,10 @@
             isInterfaceCheck,
             declaredMember,
             templateOverrideMismatchRequiredNamedParameter.withArguments(
-                declaredParameter.name,
-                "${declaredMember.enclosingClass.name}."
+                declaredParameter.name!,
+                "${declaredMember.enclosingClass!.name}."
                     "${declaredMember.name.text}",
-                "${interfaceMember.enclosingClass.name}."
+                "${interfaceMember.enclosingClass!.name}."
                     "${interfaceMember.name.text}"),
             declaredParameter.fileOffset,
             noLength,
@@ -1659,7 +1675,7 @@
       Member interfaceMemberOrigin,
       bool isInterfaceCheck,
       bool declaredNeedsLegacyErasure) {
-    Substitution interfaceSubstitution = _computeInterfaceSubstitution(
+    Substitution? interfaceSubstitution = _computeInterfaceSubstitution(
         types,
         declaredMember,
         interfaceMember,
@@ -1668,7 +1684,7 @@
         /* interfaceFunction = */ null,
         isInterfaceCheck,
         declaredNeedsLegacyErasure);
-    Substitution declaredSubstitution =
+    Substitution? declaredSubstitution =
         _computeDeclaredSubstitution(types, declaredMember);
     DartType declaredType = declaredMember.getterType;
     DartType interfaceType = interfaceMember.getterType;
@@ -1702,7 +1718,7 @@
       Member interfaceMemberOrigin,
       bool isInterfaceCheck,
       bool declaredNeedsLegacyErasure) {
-    Substitution interfaceSubstitution = _computeInterfaceSubstitution(
+    Substitution? interfaceSubstitution = _computeInterfaceSubstitution(
         types,
         declaredMember,
         interfaceMember,
@@ -1711,12 +1727,12 @@
         /* interfaceFunction = */ null,
         isInterfaceCheck,
         declaredNeedsLegacyErasure);
-    Substitution declaredSubstitution =
+    Substitution? declaredSubstitution =
         _computeDeclaredSubstitution(types, declaredMember);
     DartType declaredType = declaredMember.setterType;
     DartType interfaceType = interfaceMember.setterType;
-    VariableDeclaration declaredParameter =
-        declaredMember.function?.positionalParameters?.elementAt(0);
+    VariableDeclaration? declaredParameter =
+        declaredMember.function?.positionalParameters.elementAt(0);
     bool isCovariant = declaredParameter?.isCovariant ?? false;
     if (!isCovariant && declaredMember is Field) {
       isCovariant = declaredMember.isCovariant;
@@ -1745,7 +1761,7 @@
   // the conflict as the main error.
   void reportInvalidOverride(bool isInterfaceCheck, Member declaredMember,
       Message message, int fileOffset, int length,
-      {List<LocatedMessage> context}) {
+      {List<LocatedMessage>? context}) {
     if (shouldOverrideProblemBeOverlooked(this)) {
       return;
     }
@@ -1771,8 +1787,8 @@
       } else {
         if (cls.isAnonymousMixin) {
           // Implicit mixin application class
-          String baseName = cls.superclass.demangledName;
-          String mixinName = cls.mixedInClass.name;
+          String baseName = cls.superclass!.demangledName;
+          String mixinName = cls.mixedInClass!.name;
           int classNameLength = cls.nameAsMixinApplicationSubclass.length;
           library.addProblem(
               templateImplicitMixinOverride.withArguments(
@@ -1813,7 +1829,7 @@
 /// classes that are not valid Dart. For instance `JSInt` in
 /// 'dart:_interceptors' that implements both `int` and `double`, and `JsArray`
 /// in `dart:js` that implement both `ListMixin` and `JsObject`.
-int getOverlookedOverrideProblemChoice(ClassBuilder classBuilder) {
+int? getOverlookedOverrideProblemChoice(ClassBuilder classBuilder) {
   String uri = '${classBuilder.library.importUri}';
   if (uri == 'dart:js' && classBuilder.fileUri.pathSegments.last == 'js.dart') {
     return 0;
diff --git a/pkg/front_end/lib/src/fasta/source/source_extension_builder.dart b/pkg/front_end/lib/src/fasta/source/source_extension_builder.dart
index 96e2b51..9adab49 100644
--- a/pkg/front_end/lib/src/fasta/source/source_extension_builder.dart
+++ b/pkg/front_end/lib/src/fasta/source/source_extension_builder.dart
@@ -2,8 +2,6 @@
 // for 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 'package:kernel/ast.dart';
 import 'package:kernel/core_types.dart';
 import 'package:kernel/type_environment.dart';
@@ -41,22 +39,28 @@
 class SourceExtensionBuilder extends ExtensionBuilderImpl {
   final Extension _extension;
 
-  SourceExtensionBuilder _origin;
-  SourceExtensionBuilder patchForTesting;
+  SourceExtensionBuilder? _origin;
+  SourceExtensionBuilder? patchForTesting;
+
+  @override
+  final List<TypeVariableBuilder>? typeParameters;
+
+  @override
+  final TypeBuilder onType;
 
   SourceExtensionBuilder(
-      List<MetadataBuilder> metadata,
+      List<MetadataBuilder>? metadata,
       int modifiers,
       String name,
-      List<TypeVariableBuilder> typeParameters,
-      TypeBuilder onType,
+      this.typeParameters,
+      this.onType,
       Scope scope,
-      LibraryBuilder parent,
+      SourceLibraryBuilder parent,
       bool isExtensionTypeDeclaration,
       int startOffset,
       int nameOffset,
       int endOffset,
-      Extension referenceFrom)
+      Extension? referenceFrom)
       : _extension = new Extension(
             name: name,
             fileUri: parent.fileUri,
@@ -65,11 +69,10 @@
             reference: referenceFrom?.reference)
           ..isExtensionTypeDeclaration = isExtensionTypeDeclaration
           ..fileOffset = nameOffset,
-        super(metadata, modifiers, name, parent, nameOffset, scope,
-            typeParameters, onType);
+        super(metadata, modifiers, name, parent, nameOffset, scope);
 
   @override
-  SourceLibraryBuilder get library => super.library;
+  SourceLibraryBuilder get library => super.library as SourceLibraryBuilder;
 
   @override
   SourceExtensionBuilder get origin => _origin ?? this;
@@ -86,17 +89,17 @@
   /// library.
   Extension build(
       SourceLibraryBuilder libraryBuilder, LibraryBuilder coreLibrary,
-      {bool addMembersToLibrary}) {
+      {required bool addMembersToLibrary}) {
     SourceLibraryBuilder.checkMemberConflicts(library, scope,
         checkForInstanceVsStaticConflict: true,
         checkForMethodVsSetterConflict: true);
 
     ClassBuilder objectClassBuilder =
-        coreLibrary.lookupLocalMember('Object', required: true);
-    void buildBuilders(String name, Builder declaration) {
-      do {
-        Builder objectGetter = objectClassBuilder.lookupLocalMember(name);
-        Builder objectSetter =
+        coreLibrary.lookupLocalMember('Object', required: true) as ClassBuilder;
+    void buildBuilders(String name, Builder? declaration) {
+      while (declaration != null) {
+        Builder? objectGetter = objectClassBuilder.lookupLocalMember(name);
+        Builder? objectSetter =
             objectClassBuilder.lookupLocalMember(name, setter: true);
         if (objectGetter != null || objectSetter != null) {
           addProblem(
@@ -106,11 +109,11 @@
               name.length);
         }
         if (declaration.parent != this) {
-          if (fileUri != declaration.parent.fileUri) {
-            unexpected("$fileUri", "${declaration.parent.fileUri}", charOffset,
+          if (fileUri != declaration.parent!.fileUri) {
+            unexpected("$fileUri", "${declaration.parent!.fileUri}", charOffset,
                 fileUri);
           } else {
-            unexpected(fullNameForErrors, declaration.parent?.fullNameForErrors,
+            unexpected(fullNameForErrors, declaration.parent!.fullNameForErrors,
                 charOffset, fileUri);
           }
         } else if (declaration is MemberBuilderImpl) {
@@ -131,9 +134,8 @@
                   unhandled(
                       "${member.runtimeType}:${memberKind}",
                       "buildMembers",
-                      declaration.charOffset,
-                      declaration.fileUri);
-                  break;
+                      memberBuilder.charOffset,
+                      memberBuilder.fileUri);
                 case BuiltMemberKind.ExtensionField:
                 case BuiltMemberKind.LateIsSetField:
                   kind = ExtensionMemberKind.Field;
@@ -156,6 +158,7 @@
                   kind = ExtensionMemberKind.TearOff;
                   break;
               }
+              // ignore: unnecessary_null_comparison
               assert(kind != null);
               Reference memberReference;
               if (member is Field) {
@@ -171,7 +174,7 @@
               extension.members.add(new ExtensionMemberDescriptor(
                   name: new Name(name, libraryBuilder.library),
                   member: memberReference,
-                  isStatic: declaration.isStatic,
+                  isStatic: memberBuilder.isStatic,
                   kind: kind));
             }
           });
@@ -180,7 +183,7 @@
               declaration.charOffset, declaration.fileUri);
         }
         declaration = declaration.next;
-      } while (declaration != null);
+      }
     }
 
     scope.forEach(buildBuilders);
@@ -198,14 +201,15 @@
         patchForTesting = patch;
       }
       scope.forEachLocalMember((String name, Builder member) {
-        Builder memberPatch =
+        Builder? memberPatch =
             patch.scope.lookupLocalMember(name, setter: false);
         if (memberPatch != null) {
           member.applyPatch(memberPatch);
         }
       });
       scope.forEachLocalSetter((String name, Builder member) {
-        Builder memberPatch = patch.scope.lookupLocalMember(name, setter: true);
+        Builder? memberPatch =
+            patch.scope.lookupLocalMember(name, setter: true);
         if (memberPatch != null) {
           member.applyPatch(memberPatch);
         }
@@ -238,9 +242,10 @@
         typeEnvironment, extension.typeParameters, fileUri);
 
     // Check on clause.
+    // ignore: unnecessary_null_comparison
     if (_extension.onType != null) {
       library.checkBoundsInType(_extension.onType, typeEnvironment,
-          onType.fileUri, onType.charOffset);
+          onType.fileUri!, onType.charOffset!);
     }
 
     forEach((String name, Builder builder) {
@@ -251,11 +256,11 @@
         // Check procedures
         library.checkTypesInProcedureBuilder(builder, typeEnvironment);
         if (builder.isGetter) {
-          Builder setterDeclaration =
+          Builder? setterDeclaration =
               scope.lookupLocalMember(builder.name, setter: true);
           if (setterDeclaration != null) {
-            library.checkGetterSetterTypes(
-                builder, setterDeclaration, typeEnvironment);
+            library.checkGetterSetterTypes(builder,
+                setterDeclaration as ProcedureBuilder, typeEnvironment);
           }
         }
       } else {
@@ -265,19 +270,21 @@
   }
 
   @override
-  void buildOutlineExpressions(LibraryBuilder library, CoreTypes coreTypes,
+  void buildOutlineExpressions(
+      SourceLibraryBuilder library,
+      CoreTypes coreTypes,
       List<DelayedActionPerformer> delayedActionPerformers) {
     MetadataBuilder.buildAnnotations(isPatch ? origin.extension : extension,
         metadata, library, this, null, fileUri);
     if (typeParameters != null) {
-      for (int i = 0; i < typeParameters.length; i++) {
-        typeParameters[i].buildOutlineExpressions(
+      for (int i = 0; i < typeParameters!.length; i++) {
+        typeParameters![i].buildOutlineExpressions(
             library, this, null, coreTypes, delayedActionPerformers);
       }
     }
 
     void build(String ignore, Builder declaration) {
-      MemberBuilder member = declaration;
+      MemberBuilder member = declaration as MemberBuilder;
       member.buildOutlineExpressions(
           library, coreTypes, delayedActionPerformers);
     }
diff --git a/pkg/front_end/lib/src/fasta/source/source_library_builder.dart b/pkg/front_end/lib/src/fasta/source/source_library_builder.dart
index 00e4320..78cf330 100644
--- a/pkg/front_end/lib/src/fasta/source/source_library_builder.dart
+++ b/pkg/front_end/lib/src/fasta/source/source_library_builder.dart
@@ -2,10 +2,9 @@
 // for 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
-
 library fasta.source_library_builder;
 
+import 'dart:collection';
 import 'dart:convert' show jsonEncode;
 
 import 'package:_fe_analyzer_shared/src/scanner/token.dart' show Token;
@@ -102,8 +101,6 @@
         getNonSimplicityIssuesForTypeVariables,
         pendingVariance;
 
-import '../loader.dart' show Loader;
-
 import '../modifier.dart'
     show
         abstractMask,
@@ -156,19 +153,19 @@
 
   final Uri fileUri;
 
-  final Uri _packageUri;
+  final Uri? _packageUri;
 
-  Uri get packageUriForTesting => _packageUri;
+  Uri? get packageUriForTesting => _packageUri;
 
   final List<Object> accessors = <Object>[];
 
-  String name;
+  String? name;
 
-  String partOfName;
+  String? partOfName;
 
-  Uri partOfUri;
+  Uri? partOfUri;
 
-  List<MetadataBuilder> metadata;
+  List<MetadataBuilder>? metadata;
 
   /// The current declaration that is being built. When we start parsing a
   /// declaration (class, method, and so on), we don't have enough information
@@ -178,12 +175,12 @@
 
   /// Non-null if this library causes an error upon access, that is, there was
   /// an error reading its source.
-  Message accessProblem;
+  Message? accessProblem;
 
   @override
   final Library library;
 
-  final SourceLibraryBuilder actualOrigin;
+  final SourceLibraryBuilder? actualOrigin;
 
   final List<FunctionBuilder> nativeMethods = <FunctionBuilder>[];
 
@@ -215,11 +212,11 @@
   // another, for example during expression compilation (debugging).
   Library get nameOrigin => _nameOrigin?.library ?? library;
   LibraryBuilder get nameOriginBuilder => _nameOrigin ?? this;
-  final LibraryBuilder _nameOrigin;
+  final LibraryBuilder? _nameOrigin;
 
-  final Library referencesFrom;
-  final IndexedLibrary referencesFromIndexed;
-  IndexedClass _currentClassReferencesFromIndexed;
+  final Library? referencesFrom;
+  final IndexedLibrary? referencesFromIndexed;
+  IndexedClass? _currentClassReferencesFromIndexed;
 
   /// Exports that can't be serialized.
   ///
@@ -230,9 +227,9 @@
   ///
   /// Otherwise, this represents an error (an ambiguous export). In this case,
   /// the error message is the corresponding value in the map.
-  Map<String, String> unserializableExports;
+  Map<String, String?>? unserializableExports;
 
-  List<FieldBuilder> _implicitlyTypedFields;
+  List<FieldBuilder>? _implicitlyTypedFields;
 
   /// The language version of this library as defined by the language version
   /// of the package it belongs to, if present, or the current language version
@@ -248,26 +245,26 @@
   LanguageVersion _languageVersion;
 
   bool postponedProblemsIssued = false;
-  List<PostponedProblem> postponedProblems;
+  List<PostponedProblem>? postponedProblems;
 
   /// List of [PrefixBuilder]s for imports with prefixes.
-  List<PrefixBuilder> _prefixBuilders;
+  List<PrefixBuilder>? _prefixBuilders;
 
   /// Set of extension declarations in scope. This is computed lazily in
   /// [forEachExtensionInScope].
-  Set<ExtensionBuilder> _extensionsInScope;
+  Set<ExtensionBuilder>? _extensionsInScope;
 
   SourceLibraryBuilder.internal(
       SourceLoader loader,
       Uri fileUri,
-      Uri packageUri,
+      Uri? packageUri,
       LanguageVersion packageLanguageVersion,
-      Scope scope,
-      SourceLibraryBuilder actualOrigin,
+      Scope? scope,
+      SourceLibraryBuilder? actualOrigin,
       Library library,
-      LibraryBuilder nameOrigin,
-      Library referencesFrom,
-      bool referenceIsPartOwner)
+      LibraryBuilder? nameOrigin,
+      Library? referencesFrom,
+      bool? referenceIsPartOwner)
       : this.fromScopes(
             loader,
             fileUri,
@@ -300,7 +297,7 @@
     assert(
         _packageUri == null ||
             importUri.scheme != 'package' ||
-            importUri.path.startsWith(_packageUri.path),
+            importUri.path.startsWith(_packageUri!.path),
         "Foreign package uri '$_packageUri' set on library with import uri "
         "'${importUri}'.");
     assert(
@@ -309,18 +306,18 @@
         "'${importUri}'.");
   }
 
-  bool _enableConstFunctionsInLibrary;
-  bool _enableVarianceInLibrary;
-  bool _enableNonfunctionTypeAliasesInLibrary;
-  bool _enableNonNullableInLibrary;
-  Version _enableNonNullableVersionInLibrary;
-  Version _enableConstructorTearoffsVersionInLibrary;
-  Version _enableExtensionTypesVersionInLibrary;
-  bool _enableTripleShiftInLibrary;
-  bool _enableExtensionMethodsInLibrary;
-  bool _enableGenericMetadataInLibrary;
-  bool _enableExtensionTypesInLibrary;
-  bool _enableConstructorTearOffsInLibrary;
+  bool? _enableConstFunctionsInLibrary;
+  bool? _enableVarianceInLibrary;
+  bool? _enableNonfunctionTypeAliasesInLibrary;
+  bool? _enableNonNullableInLibrary;
+  Version? _enableNonNullableVersionInLibrary;
+  Version? _enableConstructorTearoffsVersionInLibrary;
+  Version? _enableExtensionTypesVersionInLibrary;
+  bool? _enableTripleShiftInLibrary;
+  bool? _enableExtensionMethodsInLibrary;
+  bool? _enableGenericMetadataInLibrary;
+  bool? _enableExtensionTypesInLibrary;
+  bool? _enableConstructorTearOffsInLibrary;
 
   bool get enableConstFunctionsInLibrary => _enableConstFunctionsInLibrary ??=
       loader.target.isExperimentEnabledInLibraryByVersion(
@@ -417,15 +414,15 @@
   SourceLibraryBuilder(
       Uri uri,
       Uri fileUri,
-      Uri packageUri,
+      Uri? packageUri,
       LanguageVersion packageLanguageVersion,
-      Loader loader,
-      SourceLibraryBuilder actualOrigin,
-      {Scope scope,
-      Library target,
-      LibraryBuilder nameOrigin,
-      Library referencesFrom,
-      bool referenceIsPartOwner})
+      SourceLoader loader,
+      SourceLibraryBuilder? actualOrigin,
+      {Scope? scope,
+      Library? target,
+      LibraryBuilder? nameOrigin,
+      Library? referencesFrom,
+      bool? referenceIsPartOwner})
       : this.internal(
             loader,
             fileUri,
@@ -453,13 +450,13 @@
   @override
   bool get isSynthetic => accessProblem != null;
 
-  TypeBuilder addType(TypeBuilder type, int charOffset) {
+  T addType<T extends TypeBuilder>(T type, int charOffset) {
     currentTypeParameterScopeBuilder
         .addType(new UnresolvedType(type, charOffset, fileUri));
     return type;
   }
 
-  bool _isNonNullableByDefault;
+  bool? _isNonNullableByDefault;
 
   @override
   bool get isNonNullableByDefault {
@@ -477,7 +474,7 @@
       _isNonNullableByDefault = _computeIsNonNullableByDefault();
       _updateLibraryNNBDSettings();
     }
-    return _isNonNullableByDefault;
+    return _isNonNullableByDefault!;
   }
 
   bool _computeIsNonNullableByDefault() =>
@@ -576,7 +573,7 @@
   }
 
   ConstructorReferenceBuilder addConstructorReference(Object name,
-      List<TypeBuilder> typeArguments, String suffix, int charOffset) {
+      List<TypeBuilder>? typeArguments, String? suffix, int charOffset) {
     ConstructorReferenceBuilder ref = new ConstructorReferenceBuilder(
         name, typeArguments, suffix, this, charOffset);
     constructorReferences.add(ref);
@@ -590,7 +587,7 @@
   }
 
   TypeParameterScopeBuilder endNestedDeclaration(
-      TypeParameterScopeKind kind, String name) {
+      TypeParameterScopeKind kind, String? name) {
     assert(
         currentTypeParameterScopeBuilder.kind == kind,
         "Unexpected declaration. "
@@ -602,13 +599,13 @@
             identical(name, "<syntax-error>"),
         "${name} != ${currentTypeParameterScopeBuilder.name}");
     TypeParameterScopeBuilder previous = currentTypeParameterScopeBuilder;
-    currentTypeParameterScopeBuilder = currentTypeParameterScopeBuilder.parent;
+    currentTypeParameterScopeBuilder = currentTypeParameterScopeBuilder.parent!;
     return previous;
   }
 
   bool uriIsValid(Uri uri) => uri.scheme != MALFORMED_URI_SCHEME;
 
-  Uri resolve(Uri baseUri, String uri, int uriOffset, {isPart: false}) {
+  Uri resolve(Uri baseUri, String? uri, int uriOffset, {isPart: false}) {
     if (uri == null) {
       addProblem(messageExpectedUri, uriOffset, noLength, fileUri);
       return new Uri(scheme: MALFORMED_URI_SCHEME);
@@ -633,16 +630,16 @@
     }
   }
 
-  String computeAndValidateConstructorName(Object name, int charOffset,
+  String? computeAndValidateConstructorName(Object? name, int charOffset,
       {isFactory: false}) {
     String className = currentTypeParameterScopeBuilder.name;
     String prefix;
-    String suffix;
+    String? suffix;
     if (name is QualifiedName) {
-      prefix = name.qualifier;
+      prefix = name.qualifier as String;
       suffix = name.name;
     } else {
-      prefix = name;
+      prefix = name as String;
       suffix = null;
     }
     if (prefix == className) {
@@ -668,10 +665,10 @@
   }
 
   void addExport(
-      List<MetadataBuilder> metadata,
+      List<MetadataBuilder>? metadata,
       String uri,
-      List<Configuration> configurations,
-      List<Combinator> combinators,
+      List<Configuration>? configurations,
+      List<Combinator>? combinators,
       int charOffset,
       int uriOffset) {
     if (configurations != null) {
@@ -696,7 +693,7 @@
     dottedName = dottedName.substring(prefix.length);
     if (!loader.target.uriTranslator.isLibrarySupported(dottedName)) return "";
 
-    LibraryBuilder imported =
+    LibraryBuilder? imported =
         loader.builders[new Uri(scheme: "dart", path: dottedName)];
 
     if (imported == null) {
@@ -712,11 +709,11 @@
   }
 
   void addImport(
-      List<MetadataBuilder> metadata,
+      List<MetadataBuilder>? metadata,
       String uri,
-      List<Configuration> configurations,
-      String prefix,
-      List<Combinator> combinators,
+      List<Configuration>? configurations,
+      String? prefix,
+      List<Combinator>? combinators,
       bool deferred,
       int charOffset,
       int prefixCharOffset,
@@ -731,10 +728,9 @@
       }
     }
 
-    LibraryBuilder builder = null;
-
-    Uri resolvedUri;
-    String nativePath;
+    LibraryBuilder? builder = null;
+    Uri? resolvedUri;
+    String? nativePath;
     const String nativeExtensionScheme = "dart-ext:";
     if (uri.startsWith(nativeExtensionScheme)) {
       addProblem(messageDeprecateDartExt, charOffset, noLength, fileUri);
@@ -758,7 +754,7 @@
         nativeImportPath: nativePath));
   }
 
-  void addPart(List<MetadataBuilder> metadata, String uri, int charOffset) {
+  void addPart(List<MetadataBuilder>? metadata, String uri, int charOffset) {
     Uri resolvedUri;
     Uri newFileUri;
     resolvedUri = resolve(this.importUri, uri, charOffset, isPart: true);
@@ -775,13 +771,13 @@
     library.addPart(part);
   }
 
-  void addPartOf(
-      List<MetadataBuilder> metadata, String name, String uri, int uriOffset) {
+  void addPartOf(List<MetadataBuilder>? metadata, String? name, String? uri,
+      int uriOffset) {
     partOfName = name;
     if (uri != null) {
       partOfUri = resolve(this.importUri, uri, uriOffset);
       Uri newFileUri = resolve(fileUri, uri, uriOffset);
-      LibraryBuilder library = loader.read(partOfUri, uriOffset,
+      LibraryBuilder library = loader.read(partOfUri!, uriOffset,
           fileUri: newFileUri, accessor: this);
       if (loader.first == this) {
         // This is a part, and it was the first input. Let the loader know
@@ -791,13 +787,13 @@
     }
   }
 
-  void addFields(List<MetadataBuilder> metadata, int modifiers, bool isTopLevel,
-      TypeBuilder type, List<FieldInfo> fieldInfos) {
+  void addFields(List<MetadataBuilder>? metadata, int modifiers,
+      bool isTopLevel, TypeBuilder? type, List<FieldInfo> fieldInfos) {
     for (FieldInfo info in fieldInfos) {
       bool isConst = modifiers & constMask != 0;
       bool isFinal = modifiers & finalMask != 0;
       bool potentiallyNeedInitializerInOutline = isConst || isFinal;
-      Token startToken;
+      Token? startToken;
       if (potentiallyNeedInitializerInOutline || type == null) {
         startToken = info.initializerToken;
       }
@@ -805,8 +801,8 @@
         // Extract only the tokens for the initializer expression from the
         // token stream.
         Token endToken = info.beforeLast;
-        endToken.setNext(new Token.eof(endToken.next.offset));
-        new Token.eof(startToken.previous.offset).setNext(startToken);
+        endToken.setNext(new Token.eof(endToken.next!.offset));
+        new Token.eof(startToken.previous!.offset).setNext(startToken);
       }
       bool hasInitializer = info.initializerToken != null;
       addField(metadata, modifiers, isTopLevel, type, info.name,
@@ -817,8 +813,8 @@
   }
 
   @override
-  Builder addBuilder(String name, Builder declaration, int charOffset,
-      {Reference getterReference, Reference setterReference}) {
+  Builder? addBuilder(String? name, Builder declaration, int charOffset,
+      {Reference? getterReference, Reference? setterReference}) {
     // TODO(ahe): Set the parent correctly here. Could then change the
     // implementation of MemberBuilder.isTopLevel to test explicitly for a
     // LibraryBuilder.
@@ -852,17 +848,17 @@
           messageMemberWithSameNameAsClass, charOffset, noLength, fileUri);
     }
     Map<String, Builder> members = isConstructor
-        ? currentTypeParameterScopeBuilder.constructors
+        ? currentTypeParameterScopeBuilder.constructors!
         : (declaration.isSetter
-            ? currentTypeParameterScopeBuilder.setters
-            : currentTypeParameterScopeBuilder.members);
-    Builder existing = members[name];
+            ? currentTypeParameterScopeBuilder.setters!
+            : currentTypeParameterScopeBuilder.members!);
+    Builder? existing = members[name];
 
     if (existing == declaration) return existing;
 
     if (declaration.next != null && declaration.next != existing) {
       unexpected(
-          "${declaration.next.fileUri}@${declaration.next.charOffset}",
+          "${declaration.next!.fileUri}@${declaration.next!.charOffset}",
           "${existing?.fileUri}@${existing?.charOffset}",
           declaration.charOffset,
           declaration.fileUri);
@@ -870,8 +866,8 @@
     declaration.next = existing;
     if (declaration is PrefixBuilder && existing is PrefixBuilder) {
       assert(existing.next is! PrefixBuilder);
-      Builder deferred;
-      Builder other;
+      Builder? deferred;
+      Builder? other;
       if (declaration.deferred) {
         deferred = declaration;
         other = existing;
@@ -885,7 +881,7 @@
             context: [
               templateDeferredPrefixDuplicatedCause
                   .withArguments(name)
-                  .withLocation(fileUri, other.charOffset, noLength)
+                  .withLocation(fileUri, other!.charOffset, noLength)
             ]);
       }
       return existing
@@ -904,29 +900,30 @@
         }
       }
       addProblem(templateDuplicatedDeclaration.withArguments(fullName),
-          charOffset, fullName.length, declaration.fileUri,
+          charOffset, fullName.length, declaration.fileUri!,
           context: <LocatedMessage>[
             templateDuplicatedDeclarationCause
                 .withArguments(fullName)
                 .withLocation(
-                    existing.fileUri, existing.charOffset, fullName.length)
+                    existing!.fileUri!, existing.charOffset, fullName.length)
           ]);
     } else if (declaration.isExtension) {
       // We add the extension declaration to the extension scope only if its
       // name is unique. Only the first of duplicate extensions is accessible
       // by name or by resolution and the remaining are dropped for the output.
-      currentTypeParameterScopeBuilder.extensions.add(declaration);
+      currentTypeParameterScopeBuilder.extensions!
+          .add(declaration as ExtensionBuilder);
     }
     if (declaration is PrefixBuilder) {
       _prefixBuilders ??= <PrefixBuilder>[];
-      _prefixBuilders.add(declaration);
+      _prefixBuilders!.add(declaration);
     }
     return members[name] = declaration;
   }
 
-  bool isDuplicatedDeclaration(Builder existing, Builder other) {
+  bool isDuplicatedDeclaration(Builder? existing, Builder other) {
     if (existing == null) return false;
-    Builder next = existing.next;
+    Builder? next = existing.next;
     if (next == null) {
       if (existing.isGetter && other.isSetter) return false;
       if (existing.isSetter && other.isGetter) return false;
@@ -953,13 +950,15 @@
   /// methods and setters of the same name are reported.
   static void checkMemberConflicts(
       SourceLibraryBuilder sourceLibraryBuilder, Scope scope,
-      {bool checkForInstanceVsStaticConflict,
-      bool checkForMethodVsSetterConflict}) {
+      {required bool checkForInstanceVsStaticConflict,
+      required bool checkForMethodVsSetterConflict}) {
+    // ignore: unnecessary_null_comparison
     assert(checkForInstanceVsStaticConflict != null);
+    // ignore: unnecessary_null_comparison
     assert(checkForMethodVsSetterConflict != null);
 
     scope.forEachLocalSetter((String name, MemberBuilder setter) {
-      Builder getable = scope.lookupLocalMember(name, setter: false);
+      Builder? getable = scope.lookupLocalMember(name, setter: false);
       if (getable == null) {
         // Setter without getter.
         return;
@@ -967,7 +966,7 @@
 
       bool isConflictingSetter = false;
       Set<Builder> conflictingGetables = {};
-      for (Builder currentGetable = getable;
+      for (Builder? currentGetable = getable;
           currentGetable != null;
           currentGetable = currentGetable.next) {
         if (currentGetable is FieldBuilder) {
@@ -981,11 +980,11 @@
           conflictingGetables.add(currentGetable);
         }
       }
-      for (MemberBuilderImpl currentSetter = setter;
+      for (MemberBuilderImpl? currentSetter = setter as MemberBuilderImpl?;
           currentSetter != null;
-          currentSetter = currentSetter.next) {
+          currentSetter = currentSetter.next as MemberBuilderImpl?) {
         bool conflict = conflictingGetables.isNotEmpty;
-        for (Builder currentGetable = getable;
+        for (Builder? currentGetable = getable;
             currentGetable != null;
             currentGetable = currentGetable.next) {
           if (checkForInstanceVsStaticConflict &&
@@ -1020,13 +1019,13 @@
             templateConflictsWithSetter.withArguments(name),
             conflictingGetable.charOffset,
             noLength,
-            conflictingGetable.fileUri);
+            conflictingGetable.fileUri!);
       }
     });
   }
 
   /// Builds the core AST structure of this library as needed for the outline.
-  Library build(LibraryBuilder coreLibrary, {bool modifyTarget}) {
+  Library build(LibraryBuilder coreLibrary, {bool modifyTarget: true}) {
     checkMemberConflicts(this, scope,
         checkForInstanceVsStaticConflict: false,
         checkForMethodVsSetterConflict: true);
@@ -1036,7 +1035,7 @@
       buildBuilder(iterator.current, coreLibrary);
     }
 
-    if (modifyTarget == false) return library;
+    if (!modifyTarget) return library;
 
     library.isSynthetic = isSynthetic;
     addDependencies(library, new Set<SourceLibraryBuilder>());
@@ -1046,7 +1045,7 @@
 
     if (unserializableExports != null) {
       Name fieldName = new Name("_exports#", library);
-      Reference getterReference =
+      Reference? getterReference =
           referencesFromIndexed?.lookupGetterReference(fieldName);
       library.addField(new Field.immutable(fieldName,
           initializer: new StringLiteral(jsonEncode(unserializableExports)),
@@ -1059,7 +1058,7 @@
     return library;
   }
 
-  void validatePart(SourceLibraryBuilder library, Set<Uri> usedParts) {
+  void validatePart(SourceLibraryBuilder? library, Set<Uri>? usedParts) {
     if (library != null && parts.isNotEmpty) {
       // If [library] is null, we have already reported a problem that this
       // part is orphaned.
@@ -1070,9 +1069,9 @@
         addProblem(messagePartInPart, offset, noLength, fileUri,
             context: context);
       }
-      for (SourceLibraryBuilder part in parts) {
+      for (LibraryBuilder part in parts) {
         // Mark this part as used so we don't report it as orphaned.
-        usedParts.add(part.importUri);
+        usedParts!.add(part.importUri);
       }
     }
     parts.clear();
@@ -1100,7 +1099,7 @@
           addProblem(messagePartOfTwoLibraries, -1, noLength, part.fileUri,
               context: [
                 messagePartOfTwoLibrariesContext.withLocation(
-                    part.partOfLibrary.fileUri, -1, noLength),
+                    part.partOfLibrary!.fileUri, -1, noLength),
                 messagePartOfTwoLibrariesContext.withLocation(
                     this.fileUri, -1, noLength)
               ]);
@@ -1122,12 +1121,12 @@
   bool includePart(LibraryBuilder part, Set<Uri> usedParts, int partOffset) {
     if (part is SourceLibraryBuilder) {
       if (part.partOfUri != null) {
-        if (uriIsValid(part.partOfUri) && part.partOfUri != importUri) {
+        if (uriIsValid(part.partOfUri!) && part.partOfUri != importUri) {
           // This is an error, but the part is not removed from the list of
           // parts, so that metadata annotations can be associated with it.
           addProblem(
               templatePartOfUriMismatch.withArguments(
-                  part.fileUri, importUri, part.partOfUri),
+                  part.fileUri, importUri, part.partOfUri!),
               partOffset,
               noLength,
               fileUri);
@@ -1140,7 +1139,7 @@
             // parts, so that metadata annotations can be associated with it.
             addProblem(
                 templatePartOfLibraryNameMismatch.withArguments(
-                    part.fileUri, name, part.partOfName),
+                    part.fileUri, name!, part.partOfName!),
                 partOffset,
                 noLength,
                 fileUri);
@@ -1151,7 +1150,7 @@
           // parts, so that metadata annotations can be associated with it.
           addProblem(
               templatePartOfUseUri.withArguments(
-                  part.fileUri, fileUri, part.partOfName),
+                  part.fileUri, fileUri, part.partOfName!),
               partOffset,
               noLength,
               fileUri);
@@ -1178,13 +1177,13 @@
         List<LocatedMessage> context = <LocatedMessage>[];
         if (languageVersion.isExplicit) {
           context.add(messageLanguageVersionLibraryContext.withLocation(
-              languageVersion.fileUri,
+              languageVersion.fileUri!,
               languageVersion.charOffset,
               languageVersion.charCount));
         }
         if (part.languageVersion.isExplicit) {
           context.add(messageLanguageVersionPartContext.withLocation(
-              part.languageVersion.fileUri,
+              part.languageVersion.fileUri!,
               part.languageVersion.charOffset,
               part.languageVersion.charCount));
         }
@@ -1250,16 +1249,16 @@
       // Check that the targets are different. This is not normally a problem
       // but is for patch files.
       if (library != part.library && part.library.problemsAsJson != null) {
-        library.problemsAsJson ??= <String>[];
-        library.problemsAsJson.addAll(part.library.problemsAsJson);
+        (library.problemsAsJson ??= <String>[])
+            .addAll(part.library.problemsAsJson!);
       }
-      List<FieldBuilder> partImplicitlyTypedFields =
+      List<FieldBuilder>? partImplicitlyTypedFields =
           part.takeImplicitlyTypedFields();
       if (partImplicitlyTypedFields != null) {
         if (_implicitlyTypedFields == null) {
           _implicitlyTypedFields = partImplicitlyTypedFields;
         } else {
-          _implicitlyTypedFields.addAll(partImplicitlyTypedFields);
+          _implicitlyTypedFields!.addAll(partImplicitlyTypedFields);
         }
       }
       return true;
@@ -1295,7 +1294,7 @@
       }
       if (import.imported?.isPart ?? false) {
         addProblem(
-            templatePartOfInLibrary.withArguments(import.imported.fileUri),
+            templatePartOfInLibrary.withArguments(import.imported!.fileUri),
             import.charOffset,
             noLength,
             fileUri);
@@ -1314,14 +1313,14 @@
           case "dynamic":
           case "void":
           case "Never":
-            unserializableExports ??= <String, String>{};
-            unserializableExports[name] = null;
+            unserializableExports ??= <String, String?>{};
+            unserializableExports![name] = null;
             break;
 
           default:
             if (member is InvalidTypeDeclarationBuilder) {
               unserializableExports ??= <String, String>{};
-              unserializableExports[name] = member.message.message;
+              unserializableExports![name] = member.message.message;
             } else {
               // Eventually (in #buildBuilder) members aren't added to the
               // library if the have 'next' pointers, so don't add them as
@@ -1329,7 +1328,7 @@
               // will eventually be added to the library).
               Builder memberLast = member;
               while (memberLast.next != null) {
-                memberLast = memberLast.next;
+                memberLast = memberLast.next!;
               }
               if (memberLast is ClassBuilder) {
                 library.additionalExports.add(memberLast.cls.reference);
@@ -1345,7 +1344,7 @@
                     // exports correctly.
                     library.additionalExports.add(member.getterReference);
                     if (member.hasSetter) {
-                      library.additionalExports.add(member.setterReference);
+                      library.additionalExports.add(member.setterReference!);
                     }
                   } else {
                     library.additionalExports.add(member.reference);
@@ -1363,7 +1362,7 @@
 
   @override
   void addToScope(String name, Builder member, int charOffset, bool isImport) {
-    Builder existing =
+    Builder? existing =
         importScope.lookupLocalMember(name, setter: member.isSetter);
     if (existing != null) {
       if (existing != member) {
@@ -1377,7 +1376,7 @@
       importScope.addLocalMember(name, member, setter: member.isSetter);
     }
     if (member.isExtension) {
-      importScope.addExtension(member);
+      importScope.addExtension(member as ExtensionBuilder);
     }
   }
 
@@ -1419,7 +1418,7 @@
     accessors.add(charOffset);
     accessors.add(length);
     if (accessProblem != null) {
-      addProblem(accessProblem, charOffset, length, fileUri);
+      addProblem(accessProblem!, charOffset, length, fileUri);
     }
   }
 
@@ -1431,9 +1430,9 @@
         loader.addProblem(message, -1, 1, null);
       }
       for (int i = 0; i < accessors.length; i += 3) {
-        Uri accessor = accessors[i];
-        int charOffset = accessors[i + 1];
-        int length = accessors[i + 2];
+        Uri accessor = accessors[i] as Uri;
+        int charOffset = accessors[i + 1] as int;
+        int length = accessors[i + 2] as int;
         addProblem(message, charOffset, length, accessor);
       }
       accessProblem = message;
@@ -1465,7 +1464,7 @@
   }
 
   TypeBuilder addNamedType(Object name, NullabilityBuilder nullabilityBuilder,
-      List<TypeBuilder> arguments, int charOffset) {
+      List<TypeBuilder>? arguments, int charOffset) {
     return addType(
         new NamedTypeBuilder(
             name, nullabilityBuilder, arguments, fileUri, charOffset),
@@ -1473,7 +1472,7 @@
   }
 
   TypeBuilder addMixinApplication(
-      TypeBuilder supertype, List<TypeBuilder> mixins, int charOffset) {
+      TypeBuilder? supertype, List<TypeBuilder> mixins, int charOffset) {
     return addType(
         new MixinApplicationBuilder(supertype, mixins, fileUri, charOffset),
         charOffset);
@@ -1487,7 +1486,7 @@
           new VoidTypeDeclarationBuilder(const VoidType(), this, charOffset));
   }
 
-  void _checkBadFunctionParameter(List<TypeVariableBuilder> typeVariables) {
+  void _checkBadFunctionParameter(List<TypeVariableBuilder>? typeVariables) {
     if (typeVariables == null || typeVariables.isEmpty) {
       return;
     }
@@ -1495,14 +1494,14 @@
     for (TypeVariableBuilder type in typeVariables) {
       if (type.name == "Function") {
         addProblem(messageFunctionAsTypeParameter, type.charOffset,
-            type.name.length, type.fileUri);
+            type.name.length, type.fileUri!);
       }
     }
   }
 
   void _checkBadFunctionDeclUse(
       String className, TypeParameterScopeKind kind, int charOffset) {
-    String decType;
+    String? decType;
     switch (kind) {
       case TypeParameterScopeKind.classDeclaration:
         decType = "class";
@@ -1525,7 +1524,7 @@
     }
     if (decType != null) {
       addProblem(templateFunctionUsedAsDec.withArguments(decType), charOffset,
-          className?.length, fileUri);
+          className.length, fileUri);
     }
   }
 
@@ -1540,7 +1539,7 @@
       addProblem(message, charOffset, length, fileUri);
     } else {
       postponedProblems ??= <PostponedProblem>[];
-      postponedProblems
+      postponedProblems!
           .add(new PostponedProblem(message, charOffset, length, fileUri));
     }
   }
@@ -1548,8 +1547,8 @@
   void issuePostponedProblems() {
     postponedProblemsIssued = true;
     if (postponedProblems == null) return;
-    for (int i = 0; i < postponedProblems.length; ++i) {
-      PostponedProblem postponedProblem = postponedProblems[i];
+    for (int i = 0; i < postponedProblems!.length; ++i) {
+      PostponedProblem postponedProblem = postponedProblems![i];
       addProblem(postponedProblem.message, postponedProblem.charOffset,
           postponedProblem.length, postponedProblem.fileUri);
     }
@@ -1557,13 +1556,13 @@
   }
 
   @override
-  FormattedMessage addProblem(
-      Message message, int charOffset, int length, Uri fileUri,
+  FormattedMessage? addProblem(
+      Message message, int charOffset, int length, Uri? fileUri,
       {bool wasHandled: false,
-      List<LocatedMessage> context,
-      Severity severity,
+      List<LocatedMessage>? context,
+      Severity? severity,
       bool problemOnLibrary: false}) {
-    FormattedMessage formattedMessage = super.addProblem(
+    FormattedMessage? formattedMessage = super.addProblem(
         message, charOffset, length, fileUri,
         wasHandled: wasHandled,
         context: context,
@@ -1571,18 +1570,18 @@
         problemOnLibrary: true);
     if (formattedMessage != null) {
       library.problemsAsJson ??= <String>[];
-      library.problemsAsJson.add(formattedMessage.toJsonString());
+      library.problemsAsJson!.add(formattedMessage.toJsonString());
     }
     return formattedMessage;
   }
 
   void addClass(
-      List<MetadataBuilder> metadata,
+      List<MetadataBuilder>? metadata,
       int modifiers,
       String className,
-      List<TypeVariableBuilder> typeVariables,
-      TypeBuilder supertype,
-      List<TypeBuilder> interfaces,
+      List<TypeVariableBuilder>? typeVariables,
+      TypeBuilder? supertype,
+      List<TypeBuilder>? interfaces,
       int startOffset,
       int nameOffset,
       int endOffset,
@@ -1602,12 +1601,12 @@
   }
 
   void addMixinDeclaration(
-      List<MetadataBuilder> metadata,
+      List<MetadataBuilder>? metadata,
       int modifiers,
       String className,
-      List<TypeVariableBuilder> typeVariables,
-      TypeBuilder supertype,
-      List<TypeBuilder> interfaces,
+      List<TypeVariableBuilder>? typeVariables,
+      TypeBuilder? supertype,
+      List<TypeBuilder>? interfaces,
       int startOffset,
       int nameOffset,
       int endOffset,
@@ -1628,12 +1627,12 @@
 
   void _addClass(
       TypeParameterScopeKind kind,
-      List<MetadataBuilder> metadata,
+      List<MetadataBuilder>? metadata,
       int modifiers,
       String className,
-      List<TypeVariableBuilder> typeVariables,
-      TypeBuilder supertype,
-      List<TypeBuilder> interfaces,
+      List<TypeVariableBuilder>? typeVariables,
+      TypeBuilder? supertype,
+      List<TypeBuilder>? interfaces,
       int startOffset,
       int nameOffset,
       int endOffset,
@@ -1645,9 +1644,9 @@
         endNestedDeclaration(kind, className)
           ..resolveTypes(typeVariables, this);
     assert(declaration.parent == libraryDeclaration);
-    Map<String, MemberBuilder> members = declaration.members;
-    Map<String, MemberBuilder> constructors = declaration.constructors;
-    Map<String, MemberBuilder> setters = declaration.setters;
+    Map<String, Builder> members = declaration.members!;
+    Map<String, MemberBuilder> constructors = declaration.constructors!;
+    Map<String, MemberBuilder> setters = declaration.setters!;
 
     Scope classScope = new Scope(
         local: members,
@@ -1668,12 +1667,6 @@
     if (declaration.declaresConstConstructor) {
       modifiers |= declaresConstConstructorMask;
     }
-    Class referencesFromClass;
-    if (referencesFrom != null) {
-      referencesFromClass = referencesFromIndexed.lookupClass(className);
-      assert(referencesFromClass == null ||
-          _currentClassReferencesFromIndexed != null);
-    }
     ClassBuilder classBuilder = new SourceClassBuilder(
         metadata,
         modifiers,
@@ -1693,23 +1686,22 @@
         startOffset,
         nameOffset,
         endOffset,
-        referencesFromClass,
         _currentClassReferencesFromIndexed,
         isMixinDeclaration: isMixinDeclaration);
 
     constructorReferences.clear();
-    Map<String, TypeVariableBuilder> typeVariablesByName =
+    Map<String, TypeVariableBuilder>? typeVariablesByName =
         checkTypeVariables(typeVariables, classBuilder);
-    void setParent(String name, MemberBuilder member) {
+    void setParent(String name, MemberBuilder? member) {
       while (member != null) {
         member.parent = classBuilder;
-        member = member.next;
+        member = member.next as MemberBuilder?;
       }
     }
 
-    void setParentAndCheckConflicts(String name, MemberBuilder member) {
+    void setParentAndCheckConflicts(String name, Builder member) {
       if (typeVariablesByName != null) {
-        TypeVariableBuilder tv = typeVariablesByName[name];
+        TypeVariableBuilder? tv = typeVariablesByName[name];
         if (tv != null) {
           classBuilder.addProblem(
               templateConflictsWithTypeVariable.withArguments(name),
@@ -1717,27 +1709,27 @@
               name.length,
               context: [
                 messageConflictsWithTypeVariableCause.withLocation(
-                    tv.fileUri, tv.charOffset, name.length)
+                    tv.fileUri!, tv.charOffset, name.length)
               ]);
         }
       }
-      setParent(name, member);
+      setParent(name, member as MemberBuilder);
     }
 
     members.forEach(setParentAndCheckConflicts);
     constructors.forEach(setParentAndCheckConflicts);
     setters.forEach(setParentAndCheckConflicts);
     addBuilder(className, classBuilder, nameOffset,
-        getterReference: referencesFromClass?.reference);
+        getterReference: _currentClassReferencesFromIndexed?.cls.reference);
   }
 
-  Map<String, TypeVariableBuilder> checkTypeVariables(
-      List<TypeVariableBuilder> typeVariables, Builder owner) {
-    if (typeVariables?.isEmpty ?? true) return null;
+  Map<String, TypeVariableBuilder>? checkTypeVariables(
+      List<TypeVariableBuilder>? typeVariables, Builder? owner) {
+    if (typeVariables == null || typeVariables.isEmpty) return null;
     Map<String, TypeVariableBuilder> typeVariablesByName =
         <String, TypeVariableBuilder>{};
     for (TypeVariableBuilder tv in typeVariables) {
-      TypeVariableBuilder existing = typeVariablesByName[tv.name];
+      TypeVariableBuilder? existing = typeVariablesByName[tv.name];
       if (existing != null) {
         if (existing.isExtensionTypeParameter) {
           // The type parameter from the extension is shadowed by the type
@@ -1772,7 +1764,7 @@
   void checkGetterSetterTypes(ProcedureBuilder getterBuilder,
       ProcedureBuilder setterBuilder, TypeEnvironment typeEnvironment) {
     DartType getterType;
-    List<TypeParameter> getterExtensionTypeParameters;
+    List<TypeParameter>? getterExtensionTypeParameters;
     if (getterBuilder.isExtensionInstanceMember) {
       // An extension instance getter
       //
@@ -1818,7 +1810,7 @@
                     getterExtensionTypeParameters.length,
                     (int index) => new TypeParameterType.forAlphaRenaming(
                         setterExtensionTypeParameters[index],
-                        getterExtensionTypeParameters[index])))
+                        getterExtensionTypeParameters![index])))
             .substituteType(setterType);
       }
     } else {
@@ -1856,18 +1848,18 @@
             context: [
               templateInvalidGetterSetterTypeSetterContext
                   .withArguments(setterMemberName)
-                  .withLocation(setterBuilder.fileUri, setterBuilder.charOffset,
-                      setterBuilder.name.length)
+                  .withLocation(setterBuilder.fileUri!,
+                      setterBuilder.charOffset, setterBuilder.name.length)
             ]);
       }
     }
   }
 
   void addExtensionDeclaration(
-      List<MetadataBuilder> metadata,
+      List<MetadataBuilder>? metadata,
       int modifiers,
       String extensionName,
-      List<TypeVariableBuilder> typeVariables,
+      List<TypeVariableBuilder>? typeVariables,
       TypeBuilder type,
       bool isExtensionTypeDeclaration,
       int startOffset,
@@ -1881,9 +1873,9 @@
         TypeParameterScopeKind.extensionDeclaration, extensionName)
       ..resolveTypes(typeVariables, this);
     assert(declaration.parent == libraryDeclaration);
-    Map<String, MemberBuilder> members = declaration.members;
-    Map<String, MemberBuilder> constructors = declaration.constructors;
-    Map<String, MemberBuilder> setters = declaration.setters;
+    Map<String, Builder> members = declaration.members!;
+    Map<String, MemberBuilder> constructors = declaration.constructors!;
+    Map<String, MemberBuilder> setters = declaration.setters!;
 
     Scope classScope = new Scope(
         local: members,
@@ -1892,7 +1884,7 @@
         debugName: "extension $extensionName",
         isModifiable: false);
 
-    Extension referenceFrom =
+    Extension? referenceFrom =
         referencesFromIndexed?.lookupExtension(extensionName);
 
     ExtensionBuilder extensionBuilder = new SourceExtensionBuilder(
@@ -1909,18 +1901,18 @@
         endOffset,
         referenceFrom);
     constructorReferences.clear();
-    Map<String, TypeVariableBuilder> typeVariablesByName =
+    Map<String, TypeVariableBuilder>? typeVariablesByName =
         checkTypeVariables(typeVariables, extensionBuilder);
-    void setParent(String name, MemberBuilder member) {
+    void setParent(String name, MemberBuilder? member) {
       while (member != null) {
         member.parent = extensionBuilder;
-        member = member.next;
+        member = member.next as MemberBuilder?;
       }
     }
 
-    void setParentAndCheckConflicts(String name, MemberBuilder member) {
+    void setParentAndCheckConflicts(String name, Builder member) {
       if (typeVariablesByName != null) {
-        TypeVariableBuilder tv = typeVariablesByName[name];
+        TypeVariableBuilder? tv = typeVariablesByName[name];
         if (tv != null) {
           extensionBuilder.addProblem(
               templateConflictsWithTypeVariable.withArguments(name),
@@ -1928,11 +1920,11 @@
               name.length,
               context: [
                 messageConflictsWithTypeVariableCause.withLocation(
-                    tv.fileUri, tv.charOffset, name.length)
+                    tv.fileUri!, tv.charOffset, name.length)
               ]);
         }
       }
-      setParent(name, member);
+      setParent(name, member as MemberBuilder);
     }
 
     members.forEach(setParentAndCheckConflicts);
@@ -1942,13 +1934,18 @@
         getterReference: referenceFrom?.reference);
   }
 
-  TypeBuilder applyMixins(TypeBuilder type, int startCharOffset, int charOffset,
-      int charEndOffset, String subclassName, bool isMixinDeclaration,
-      {List<MetadataBuilder> metadata,
-      String name,
-      List<TypeVariableBuilder> typeVariables,
-      int modifiers,
-      List<TypeBuilder> interfaces}) {
+  TypeBuilder? applyMixins(
+      TypeBuilder? type,
+      int startCharOffset,
+      int charOffset,
+      int charEndOffset,
+      String subclassName,
+      bool isMixinDeclaration,
+      {List<MetadataBuilder>? metadata,
+      String? name,
+      List<TypeVariableBuilder>? typeVariables,
+      int modifiers: 0,
+      List<TypeBuilder>? interfaces}) {
     if (name == null) {
       // The following parameters should only be used when building a named
       // mixin application.
@@ -2009,7 +2006,7 @@
       bool isNamedMixinApplication;
 
       /// The names of the type variables of the subclass.
-      Set<String> typeVariableNames;
+      Set<String>? typeVariableNames;
       if (typeVariables != null) {
         typeVariableNames = new Set<String>();
         for (TypeVariableBuilder typeVariable in typeVariables) {
@@ -2019,13 +2016,13 @@
 
       /// Helper function that returns `true` if a type variable with a name
       /// from [typeVariableNames] is referenced in [type].
-      bool usesTypeVariables(TypeBuilder type) {
+      bool usesTypeVariables(TypeBuilder? type) {
         if (type is NamedTypeBuilder) {
           if (type.declaration is TypeVariableBuilder) {
-            return typeVariableNames.contains(type.declaration.name);
+            return typeVariableNames!.contains(type.declaration!.name);
           }
 
-          List<TypeBuilder> typeArguments = type.arguments;
+          List<TypeBuilder>? typeArguments = type.arguments;
           if (typeArguments != null && typeVariables != null) {
             for (TypeBuilder argument in typeArguments) {
               if (usesTypeVariables(argument)) {
@@ -2035,13 +2032,13 @@
           }
         } else if (type is FunctionTypeBuilder) {
           if (type.formals != null) {
-            for (FormalParameterBuilder formal in type.formals) {
+            for (FormalParameterBuilder formal in type.formals!) {
               if (usesTypeVariables(formal.type)) {
                 return true;
               }
             }
           }
-          List<TypeVariableBuilder> typeVariables = type.typeVariables;
+          List<TypeVariableBuilder>? typeVariables = type.typeVariables;
           if (typeVariables != null) {
             for (TypeVariableBuilder variable in typeVariables) {
               if (usesTypeVariables(variable.bound)) {
@@ -2072,8 +2069,8 @@
         }
         String fullname =
             isNamedMixinApplication ? name : "_$subclassName&$runningName";
-        List<TypeVariableBuilder> applicationTypeVariables;
-        List<TypeBuilder> applicationTypeArguments;
+        List<TypeVariableBuilder>? applicationTypeVariables;
+        List<TypeBuilder>? applicationTypeArguments;
         if (isNamedMixinApplication) {
           // If this is a named mixin application, it must be given all the
           // declarated type variables.
@@ -2087,24 +2084,24 @@
                 "mixin application");
 
             applicationTypeVariables = copyTypeVariables(
-                typeVariables, currentTypeParameterScopeBuilder);
+                typeVariables!, currentTypeParameterScopeBuilder);
 
             List<TypeBuilder> newTypes = <TypeBuilder>[];
             if (supertype is NamedTypeBuilder && supertype.arguments != null) {
-              for (int i = 0; i < supertype.arguments.length; ++i) {
-                supertype.arguments[i] = supertype.arguments[i]
+              for (int i = 0; i < supertype.arguments!.length; ++i) {
+                supertype.arguments![i] = supertype.arguments![i]
                     .clone(newTypes, this, currentTypeParameterScopeBuilder);
               }
             }
             if (mixin is NamedTypeBuilder && mixin.arguments != null) {
-              for (int i = 0; i < mixin.arguments.length; ++i) {
-                mixin.arguments[i] = mixin.arguments[i]
+              for (int i = 0; i < mixin.arguments!.length; ++i) {
+                mixin.arguments![i] = mixin.arguments![i]
                     .clone(newTypes, this, currentTypeParameterScopeBuilder);
               }
             }
             for (TypeBuilder newType in newTypes) {
-              currentTypeParameterScopeBuilder
-                  .addType(new UnresolvedType(newType, -1, null));
+              currentTypeParameterScopeBuilder.addType(new UnresolvedType(
+                  newType, newType.charOffset!, newType.fileUri!));
             }
 
             TypeParameterScopeBuilder mixinDeclaration = this
@@ -2127,16 +2124,14 @@
           }
         }
         final int computedStartCharOffset =
-            (isNamedMixinApplication ? metadata : null) == null
+            !isNamedMixinApplication || metadata == null
                 ? startCharOffset
                 : metadata.first.charOffset;
 
-        Class referencesFromClass;
-        IndexedClass referencesFromIndexedClass;
-        if (referencesFrom != null) {
-          referencesFromClass = referencesFromIndexed.lookupClass(fullname);
+        IndexedClass? referencesFromIndexedClass;
+        if (referencesFromIndexed != null) {
           referencesFromIndexedClass =
-              referencesFromIndexed.lookupIndexedClass(fullname);
+              referencesFromIndexed!.lookupIndexedClass(fullname);
         }
 
         SourceClassBuilder application = new SourceClassBuilder(
@@ -2165,7 +2160,6 @@
           computedStartCharOffset,
           charOffset,
           charEndOffset,
-          referencesFromClass,
           referencesFromIndexedClass,
           mixedInTypeBuilder: isMixinDeclaration ? null : mixin,
         );
@@ -2174,7 +2168,7 @@
         // handle that :(
         application.cls.isAnonymousMixin = !isNamedMixinApplication;
         addBuilder(fullname, application, charOffset,
-            getterReference: referencesFromClass?.reference);
+            getterReference: referencesFromIndexedClass?.cls.reference);
         supertype = addNamedType(fullname, const NullabilityBuilder.omitted(),
             applicationTypeArguments, charOffset);
       }
@@ -2185,39 +2179,39 @@
   }
 
   void addNamedMixinApplication(
-      List<MetadataBuilder> metadata,
+      List<MetadataBuilder>? metadata,
       String name,
-      List<TypeVariableBuilder> typeVariables,
+      List<TypeVariableBuilder>? typeVariables,
       int modifiers,
-      TypeBuilder mixinApplication,
-      List<TypeBuilder> interfaces,
+      TypeBuilder? mixinApplication,
+      List<TypeBuilder>? interfaces,
       int startCharOffset,
       int charOffset,
       int charEndOffset) {
     // Nested declaration began in `OutlineBuilder.beginNamedMixinApplication`.
     endNestedDeclaration(TypeParameterScopeKind.namedMixinApplication, name)
         .resolveTypes(typeVariables, this);
-    NamedTypeBuilder supertype = applyMixins(mixinApplication, startCharOffset,
+    TypeBuilder supertype = applyMixins(mixinApplication, startCharOffset,
         charOffset, charEndOffset, name, false,
         metadata: metadata,
         name: name,
         typeVariables: typeVariables,
         modifiers: modifiers,
-        interfaces: interfaces);
+        interfaces: interfaces)!;
     checkTypeVariables(typeVariables, supertype.declaration);
   }
 
   void addField(
-      List<MetadataBuilder> metadata,
+      List<MetadataBuilder>? metadata,
       int modifiers,
       bool isTopLevel,
-      TypeBuilder type,
+      TypeBuilder? type,
       String name,
       int charOffset,
       int charEndOffset,
-      Token initializerToken,
+      Token? initializerToken,
       bool hasInitializer,
-      {Token constInitializerToken}) {
+      {Token? constInitializerToken}) {
     if (hasInitializer) {
       modifiers |= hasInitializerMask;
     }
@@ -2229,23 +2223,23 @@
     final bool isInstanceMember = currentTypeParameterScopeBuilder.kind !=
             TypeParameterScopeKind.library &&
         (modifiers & staticMask) == 0;
-    String className;
+    String? className;
     if (isInstanceMember) {
       className = currentTypeParameterScopeBuilder.name;
     }
     final bool isExtensionMember = currentTypeParameterScopeBuilder.kind ==
         TypeParameterScopeKind.extensionDeclaration;
-    String extensionName;
+    String? extensionName;
     if (isExtensionMember) {
       extensionName = currentTypeParameterScopeBuilder.name;
     }
 
-    Reference fieldGetterReference;
-    Reference fieldSetterReference;
-    Reference lateIsSetGetterReference;
-    Reference lateIsSetSetterReference;
-    Reference lateGetterReference;
-    Reference lateSetterReference;
+    Reference? fieldGetterReference;
+    Reference? fieldSetterReference;
+    Reference? lateIsSetGetterReference;
+    Reference? lateIsSetSetterReference;
+    Reference? lateGetterReference;
+    Reference? lateSetterReference;
 
     FieldNameScheme fieldNameScheme = new FieldNameScheme(
         isInstanceMember: isInstanceMember,
@@ -2255,7 +2249,7 @@
         libraryReference: referencesFrom?.reference ?? library.reference);
     if (referencesFrom != null) {
       IndexedContainer indexedContainer =
-          _currentClassReferencesFromIndexed ?? referencesFromIndexed;
+          (_currentClassReferencesFromIndexed ?? referencesFromIndexed)!;
       Name nameToLookupName = fieldNameScheme.getName(FieldNameType.Field, name,
           isSynthesized: fieldIsLateWithLowering);
       fieldGetterReference =
@@ -2295,8 +2289,8 @@
         lateIsSetGetterReference: lateIsSetGetterReference,
         lateIsSetSetterReference: lateIsSetSetterReference,
         lateGetterReference: lateGetterReference,
-        lateSetterReference: lateSetterReference);
-    fieldBuilder.constInitializerToken = constInitializerToken;
+        lateSetterReference: lateSetterReference,
+        constInitializerToken: constInitializerToken);
     addBuilder(name, fieldBuilder, charOffset,
         getterReference: fieldGetterReference,
         setterReference: fieldSetterReference);
@@ -2318,24 +2312,24 @@
   }
 
   void addConstructor(
-      List<MetadataBuilder> metadata,
+      List<MetadataBuilder>? metadata,
       int modifiers,
-      TypeBuilder returnType,
-      final Object name,
+      TypeBuilder? returnType,
+      final Object? name,
       String constructorName,
-      List<TypeVariableBuilder> typeVariables,
-      List<FormalParameterBuilder> formals,
+      List<TypeVariableBuilder>? typeVariables,
+      List<FormalParameterBuilder>? formals,
       int startCharOffset,
       int charOffset,
       int charOpenParenOffset,
       int charEndOffset,
-      String nativeMethodName,
-      {Token beginInitializers}) {
-    Member referenceFrom;
+      String? nativeMethodName,
+      {Token? beginInitializers}) {
+    Member? referenceFrom;
     if (_currentClassReferencesFromIndexed != null) {
-      referenceFrom = _currentClassReferencesFromIndexed.lookupConstructor(
+      referenceFrom = _currentClassReferencesFromIndexed!.lookupConstructor(
           new Name(
-              constructorName, _currentClassReferencesFromIndexed.library));
+              constructorName, _currentClassReferencesFromIndexed!.library));
     }
     ConstructorBuilder constructorBuilder = new ConstructorBuilderImpl(
         metadata,
@@ -2358,7 +2352,7 @@
       addNativeMethod(constructorBuilder);
     }
     if (constructorBuilder.isConst) {
-      currentTypeParameterScopeBuilder?.declaresConstConstructor = true;
+      currentTypeParameterScopeBuilder.declaresConstConstructor = true;
       // const constructors will have their initializers compiled and written
       // into the outline.
       constructorBuilder.beginInitializers =
@@ -2367,27 +2361,29 @@
   }
 
   void addProcedure(
-      List<MetadataBuilder> metadata,
+      List<MetadataBuilder>? metadata,
       int modifiers,
-      TypeBuilder returnType,
+      TypeBuilder? returnType,
       String name,
-      List<TypeVariableBuilder> typeVariables,
-      List<FormalParameterBuilder> formals,
+      List<TypeVariableBuilder>? typeVariables,
+      List<FormalParameterBuilder>? formals,
       ProcedureKind kind,
       int startCharOffset,
       int charOffset,
       int charOpenParenOffset,
       int charEndOffset,
-      String nativeMethodName,
+      String? nativeMethodName,
       AsyncMarker asyncModifier,
-      {bool isInstanceMember,
-      bool isExtensionMember}) {
+      {required bool isInstanceMember,
+      required bool isExtensionMember}) {
+    // ignore: unnecessary_null_comparison
     assert(isInstanceMember != null);
+    // ignore: unnecessary_null_comparison
     assert(isExtensionMember != null);
     assert(!isExtensionMember ||
         currentTypeParameterScopeBuilder.kind ==
             TypeParameterScopeKind.extensionDeclaration);
-    String extensionName =
+    String? extensionName =
         isExtensionMember ? currentTypeParameterScopeBuilder.name : null;
     ProcedureNameScheme procedureNameScheme = new ProcedureNameScheme(
         isExtensionMember: isExtensionMember,
@@ -2403,16 +2399,16 @@
         returnType = addVoidType(charOffset);
       }
     }
-    Reference procedureReference;
-    Reference tearOffReference;
+    Reference? procedureReference;
+    Reference? tearOffReference;
     if (referencesFrom != null) {
       Name nameToLookup = procedureNameScheme.getName(kind, name);
       if (_currentClassReferencesFromIndexed != null) {
         if (kind == ProcedureKind.Setter) {
-          procedureReference = _currentClassReferencesFromIndexed
+          procedureReference = _currentClassReferencesFromIndexed!
               .lookupSetterReference(nameToLookup);
         } else {
-          procedureReference = _currentClassReferencesFromIndexed
+          procedureReference = _currentClassReferencesFromIndexed!
               .lookupGetterReference(nameToLookup);
         }
       } else {
@@ -2420,13 +2416,13 @@
             // Extension instance setters are encoded as methods.
             !(isExtensionMember && isInstanceMember)) {
           procedureReference =
-              referencesFromIndexed.lookupSetterReference(nameToLookup);
+              referencesFromIndexed!.lookupSetterReference(nameToLookup);
         } else {
           procedureReference =
-              referencesFromIndexed.lookupGetterReference(nameToLookup);
+              referencesFromIndexed!.lookupGetterReference(nameToLookup);
         }
         if (isExtensionMember && kind == ProcedureKind.Method) {
-          tearOffReference = referencesFromIndexed.lookupGetterReference(
+          tearOffReference = referencesFromIndexed!.lookupGetterReference(
               procedureNameScheme.getName(ProcedureKind.Getter, name));
         }
       }
@@ -2460,19 +2456,19 @@
   }
 
   void addFactoryMethod(
-      List<MetadataBuilder> metadata,
+      List<MetadataBuilder>? metadata,
       int modifiers,
       Object name,
-      List<FormalParameterBuilder> formals,
-      ConstructorReferenceBuilder redirectionTarget,
+      List<FormalParameterBuilder>? formals,
+      ConstructorReferenceBuilder? redirectionTarget,
       int startCharOffset,
       int charOffset,
       int charOpenParenOffset,
       int charEndOffset,
-      String nativeMethodName,
+      String? nativeMethodName,
       AsyncMarker asyncModifier) {
     TypeBuilder returnType = addNamedType(
-        currentTypeParameterScopeBuilder.parent.name,
+        currentTypeParameterScopeBuilder.parent!.name,
         const NullabilityBuilder.omitted(),
         <TypeBuilder>[],
         charOffset);
@@ -2482,12 +2478,12 @@
 
     // Prepare the simple procedure name.
     String procedureName;
-    String constructorName =
+    String? constructorName =
         computeAndValidateConstructorName(name, charOffset, isFactory: true);
     if (constructorName != null) {
       procedureName = constructorName;
     } else {
-      procedureName = name;
+      procedureName = name as String;
     }
 
     ProcedureNameScheme procedureNameScheme = new ProcedureNameScheme(
@@ -2495,14 +2491,14 @@
         extensionName: null,
         isStatic: true,
         libraryReference: referencesFrom != null
-            ? (_currentClassReferencesFromIndexed ?? referencesFromIndexed)
+            ? (_currentClassReferencesFromIndexed ?? referencesFromIndexed)!
                 .library
                 .reference
             : library.reference);
 
-    Reference reference = _currentClassReferencesFromIndexed
-        ?.lookupConstructor(
-            new Name(procedureName, _currentClassReferencesFromIndexed.library))
+    Reference? reference = _currentClassReferencesFromIndexed
+        ?.lookupConstructor(new Name(
+            procedureName, _currentClassReferencesFromIndexed!.library))
         ?.reference;
 
     ProcedureBuilder procedureBuilder;
@@ -2544,7 +2540,7 @@
           charOpenParenOffset,
           charEndOffset,
           reference,
-          null,
+          /* tearOffReference = */ null,
           asyncModifier,
           procedureNameScheme,
           isExtensionMember: false,
@@ -2555,9 +2551,9 @@
     TypeParameterScopeBuilder savedDeclaration =
         currentTypeParameterScopeBuilder;
     currentTypeParameterScopeBuilder = factoryDeclaration;
-    for (TypeVariableBuilder tv in procedureBuilder.typeVariables) {
-      NamedTypeBuilder t = procedureBuilder.returnType;
-      t.arguments.add(addNamedType(tv.name, const NullabilityBuilder.omitted(),
+    for (TypeVariableBuilder tv in procedureBuilder.typeVariables!) {
+      NamedTypeBuilder t = procedureBuilder.returnType as NamedTypeBuilder;
+      t.arguments!.add(addNamedType(tv.name, const NullabilityBuilder.omitted(),
           null, procedureBuilder.charOffset));
     }
     currentTypeParameterScopeBuilder = savedDeclaration;
@@ -2571,18 +2567,16 @@
   }
 
   void addEnum(
-      List<MetadataBuilder> metadata,
+      List<MetadataBuilder>? metadata,
       String name,
-      List<EnumConstantInfo> enumConstantInfos,
+      List<EnumConstantInfo?>? enumConstantInfos,
       int startCharOffset,
       int charOffset,
       int charEndOffset) {
-    Class referencesFromClass;
-    IndexedClass referencesFromIndexedClass;
+    IndexedClass? referencesFromIndexedClass;
     if (referencesFrom != null) {
-      referencesFromClass = referencesFromIndexed.lookupClass(name);
       referencesFromIndexedClass =
-          referencesFromIndexed.lookupIndexedClass(name);
+          referencesFromIndexed!.lookupIndexedClass(name);
     }
     EnumBuilder builder = new EnumBuilder(
         metadata,
@@ -2592,24 +2586,23 @@
         startCharOffset,
         charOffset,
         charEndOffset,
-        referencesFromClass,
         referencesFromIndexedClass);
     addBuilder(name, builder, charOffset,
-        getterReference: referencesFromClass?.reference);
+        getterReference: referencesFromIndexedClass?.cls.reference);
   }
 
   void addFunctionTypeAlias(
-      List<MetadataBuilder> metadata,
+      List<MetadataBuilder>? metadata,
       String name,
-      List<TypeVariableBuilder> typeVariables,
-      TypeBuilder type,
+      List<TypeVariableBuilder>? typeVariables,
+      TypeBuilder? type,
       int charOffset) {
     if (typeVariables != null) {
       for (TypeVariableBuilder typeVariable in typeVariables) {
         typeVariable.variance = pendingVariance;
       }
     }
-    Typedef referenceFrom = referencesFromIndexed?.lookupTypedef(name);
+    Typedef? referenceFrom = referencesFromIndexed?.lookupTypedef(name);
     TypeAliasBuilder typedefBuilder = new SourceTypeAliasBuilder(
         metadata, name, typeVariables, type, this, charOffset,
         referenceFrom: referenceFrom);
@@ -2622,9 +2615,9 @@
   }
 
   FunctionTypeBuilder addFunctionType(
-      TypeBuilder returnType,
-      List<TypeVariableBuilder> typeVariables,
-      List<FormalParameterBuilder> formals,
+      TypeBuilder? returnType,
+      List<TypeVariableBuilder>? typeVariables,
+      List<FormalParameterBuilder>? formals,
       NullabilityBuilder nullabilityBuilder,
       Uri fileUri,
       int charOffset) {
@@ -2649,13 +2642,13 @@
   }
 
   FormalParameterBuilder addFormalParameter(
-      List<MetadataBuilder> metadata,
+      List<MetadataBuilder>? metadata,
       int modifiers,
-      TypeBuilder type,
+      TypeBuilder? type,
       String name,
       bool hasThis,
       int charOffset,
-      Token initializerToken) {
+      Token? initializerToken) {
     if (hasThis) {
       modifiers |= initializingFormalMask;
     }
@@ -2667,8 +2660,8 @@
     return formal;
   }
 
-  TypeVariableBuilder addTypeVariable(List<MetadataBuilder> metadata,
-      String name, TypeBuilder bound, int charOffset, Uri fileUri) {
+  TypeVariableBuilder addTypeVariable(List<MetadataBuilder>? metadata,
+      String name, TypeBuilder? bound, int charOffset, Uri fileUri) {
     TypeVariableBuilder builder = new TypeVariableBuilder(
         name, this, charOffset, fileUri,
         bound: bound, metadata: metadata);
@@ -2687,7 +2680,7 @@
     String findDuplicateSuffix(Builder declaration) {
       if (declaration.next != null) {
         int count = 0;
-        Builder current = declaration.next;
+        Builder? current = declaration.next;
         while (current != null) {
           count++;
           current = current.next;
@@ -2758,11 +2751,13 @@
         new Arguments(<Expression>[new StringLiteral(nativeImportPath)]);
     Expression annotation;
     if (constructor.isConstructor) {
-      annotation = new ConstructorInvocation(constructor.member, arguments)
+      annotation = new ConstructorInvocation(
+          constructor.member as Constructor, arguments)
         ..isConst = true;
     } else {
-      annotation = new StaticInvocation(constructor.member, arguments)
-        ..isConst = true;
+      annotation =
+          new StaticInvocation(constructor.member as Procedure, arguments)
+            ..isConst = true;
     }
     library.addAnnotation(annotation);
   }
@@ -2786,15 +2781,15 @@
 
         // Rather than add a LibraryDependency, we attach an annotation.
         if (import.nativeImportPath != null) {
-          addNativeDependency(import.nativeImportPath);
+          addNativeDependency(import.nativeImportPath!);
           continue;
         }
 
         if (import.deferred && import.prefixBuilder?.dependency != null) {
-          library.addDependency(import.prefixBuilder.dependency);
+          library.addDependency(import.prefixBuilder!.dependency!);
         } else {
           library.addDependency(new LibraryDependency.import(
-              import.imported.library,
+              import.imported!.library,
               name: import.prefix,
               combinators: toKernelCombinators(import.combinators))
             ..fileOffset = import.charOffset);
@@ -2832,9 +2827,9 @@
       AccessErrorBuilder error = other;
       other = error.builder;
     }
-    Builder preferred;
-    Uri uri;
-    Uri otherUri;
+    Builder? preferred;
+    Uri? uri;
+    Uri? otherUri;
     if (scope.lookupLocalMember(name, setter: false) == declaration) {
       preferred = declaration;
     } else {
@@ -2844,9 +2839,9 @@
         preferred = declaration;
       } else if (other is LoadLibraryBuilder) {
         preferred = other;
-      } else if (otherUri?.scheme == "dart" && uri?.scheme != "dart") {
+      } else if (otherUri.scheme == "dart" && uri.scheme != "dart") {
         preferred = declaration;
-      } else if (uri?.scheme == "dart" && otherUri?.scheme != "dart") {
+      } else if (uri.scheme == "dart" && otherUri.scheme != "dart") {
         preferred = other;
       }
     }
@@ -2869,7 +2864,7 @@
     if (isExport) {
       Template<Message Function(String name, Uri uri, Uri uri2)> template =
           templateDuplicatedExport;
-      Message message = template.withArguments(name, uri, otherUri);
+      Message message = template.withArguments(name, uri!, otherUri!);
       addProblem(message, charOffset, noLength, fileUri);
     }
     Template<Message Function(String name, Uri uri, Uri uri2)> builderTemplate =
@@ -2880,8 +2875,8 @@
         name,
         // TODO(ahe): We should probably use a context object here
         // instead of including URIs in this message.
-        uri,
-        otherUri);
+        uri!,
+        otherUri!);
     // We report the error lazily (setting suppressMessage to false) because the
     // spec 18.1 states that 'It is not an error if N is introduced by two or
     // more imports but never referred to.'
@@ -2894,8 +2889,10 @@
     int total = 0;
     for (Import import in imports) {
       if (import.deferred) {
-        Procedure tearoff = import.prefixBuilder.loadLibraryBuilder.tearoff;
-        if (tearoff != null) library.addProcedure(tearoff);
+        Procedure? tearoff = import.prefixBuilder!.loadLibraryBuilder!.tearoff;
+        if (tearoff != null) {
+          library.addProcedure(tearoff);
+        }
         total++;
       }
     }
@@ -2924,26 +2921,26 @@
             origin.function.positionalParameters[j];
         if (originParameter.initializer != null) {
           forwarderParameter.initializer =
-              cloner.clone(originParameter.initializer);
-          forwarderParameter.initializer.parent = forwarderParameter;
+              cloner.clone(originParameter.initializer!);
+          forwarderParameter.initializer!.parent = forwarderParameter;
         }
       }
 
       Map<String, VariableDeclaration> originNamedMap =
           <String, VariableDeclaration>{};
       for (VariableDeclaration originNamed in origin.function.namedParameters) {
-        originNamedMap[originNamed.name] = originNamed;
+        originNamedMap[originNamed.name!] = originNamed;
       }
       for (VariableDeclaration forwarderNamed
           in forwarder.function.namedParameters) {
-        VariableDeclaration originNamed = originNamedMap[forwarderNamed.name];
+        VariableDeclaration? originNamed = originNamedMap[forwarderNamed.name];
         if (originNamed == null) {
           return unhandled(
               "null", forwarder.name.text, origin.fileOffset, origin.fileUri);
         }
         if (originNamed.initializer == null) continue;
-        forwarderNamed.initializer = cloner.clone(originNamed.initializer);
-        forwarderNamed.initializer.parent = forwarderNamed;
+        forwarderNamed.initializer = cloner.clone(originNamed.initializer!);
+        forwarderNamed.initializer!.parent = forwarderNamed;
       }
 
       ++count;
@@ -2987,7 +2984,8 @@
       boundlessTypeVariables.add(newVariable);
     }
     for (TypeBuilder newType in newTypes) {
-      declaration.addType(new UnresolvedType(newType, -1, null));
+      declaration.addType(
+          new UnresolvedType(newType, newType.charOffset!, newType.fileUri!));
     }
     return copy;
   }
@@ -3022,39 +3020,59 @@
     // of a type parameter type can't ever be 'nullable' if computed from the
     // bound. It allows us to use 'nullable' nullability as the marker in the
     // DFS implementation.
+
+    // We cannot set the declared nullability on the pending types to `null` so
+    // we create a map of the pending type parameter type nullabilities.
+    Map<TypeParameterType, Nullability?> nullabilityMap =
+        new LinkedHashMap.identity();
+    Nullability? getDeclaredNullability(TypeParameterType type) {
+      if (nullabilityMap.containsKey(type)) {
+        return nullabilityMap[type];
+      }
+      return type.declaredNullability;
+    }
+
+    void setDeclaredNullability(
+        TypeParameterType type, Nullability nullability) {
+      if (nullabilityMap.containsKey(type)) {
+        nullabilityMap[type] = nullability;
+      }
+      type.declaredNullability = nullability;
+    }
+
     Nullability marker = Nullability.nullable;
-    List<TypeParameterType> stack =
-        new List<TypeParameterType>.filled(_pendingNullabilities.length, null);
+    List<TypeParameterType?> stack =
+        new List<TypeParameterType?>.filled(_pendingNullabilities.length, null);
     int stackTop = 0;
     for (PendingNullability pendingNullability in _pendingNullabilities) {
-      pendingNullability.type.declaredNullability = null;
+      nullabilityMap[pendingNullability.type] = null;
     }
     for (PendingNullability pendingNullability in _pendingNullabilities) {
       TypeParameterType type = pendingNullability.type;
-      if (type.declaredNullability != null) {
+      if (getDeclaredNullability(type) != null) {
         // Nullability for [type] was already computed on one of the branches
         // of the depth-first search.  Continue to the next one.
         continue;
       }
       if (type.parameter.bound is TypeParameterType) {
         TypeParameterType current = type;
-        TypeParameterType next = current.parameter.bound;
-        while (next != null && next.declaredNullability == null) {
+        TypeParameterType? next = current.parameter.bound as TypeParameterType;
+        while (next != null && getDeclaredNullability(next) == null) {
           stack[stackTop++] = current;
-          current.declaredNullability = marker;
+          setDeclaredNullability(current, marker);
 
           current = next;
           if (current.parameter.bound is TypeParameterType) {
-            next = current.parameter.bound;
-            if (next.declaredNullability == marker) {
-              next.declaredNullability = Nullability.undetermined;
+            next = current.parameter.bound as TypeParameterType;
+            if (getDeclaredNullability(next) == marker) {
+              setDeclaredNullability(next, Nullability.undetermined);
               current.parameter.bound = const InvalidType();
               current.parameter.defaultType = const InvalidType();
               addProblem(
                   templateCycleInTypeVariables.withArguments(
-                      next.parameter.name, current.parameter.name),
+                      next.parameter.name!, current.parameter.name!),
                   pendingNullability.charOffset,
-                  next.parameter.name.length,
+                  next.parameter.name!.length,
                   pendingNullability.fileUri);
               next = null;
             }
@@ -3062,17 +3080,17 @@
             next = null;
           }
         }
-        current.declaredNullability =
-            TypeParameterType.computeNullabilityFromBound(current.parameter);
+        setDeclaredNullability(current,
+            TypeParameterType.computeNullabilityFromBound(current.parameter));
         while (stackTop != 0) {
           --stackTop;
-          current = stack[stackTop];
-          current.declaredNullability =
-              TypeParameterType.computeNullabilityFromBound(current.parameter);
+          current = stack[stackTop]!;
+          setDeclaredNullability(current,
+              TypeParameterType.computeNullabilityFromBound(current.parameter));
         }
       } else {
-        type.declaredNullability =
-            TypeParameterType.computeNullabilityFromBound(type.parameter);
+        setDeclaredNullability(type,
+            TypeParameterType.computeNullabilityFromBound(type.parameter));
       }
     }
     _pendingNullabilities.clear();
@@ -3080,11 +3098,12 @@
 
   int computeVariances() {
     int count = 0;
-    for (Builder declaration in libraryDeclaration.members.values) {
+    for (Builder? declaration in libraryDeclaration.members!.values) {
       while (declaration != null) {
         if (declaration is TypeAliasBuilder &&
             declaration.typeVariablesCount > 0) {
-          for (TypeVariableBuilder typeParameter in declaration.typeVariables) {
+          for (TypeVariableBuilder typeParameter
+              in declaration.typeVariables!) {
             typeParameter.variance = computeTypeVariableBuilderVariance(
                 typeParameter, declaration.type, this);
             ++count;
@@ -3124,7 +3143,7 @@
   /// for being generic function types.  Returns `true` if any errors were
   /// reported.
   bool _recursivelyReportGenericFunctionTypesAsBoundsForType(
-      TypeBuilder typeBuilder) {
+      TypeBuilder? typeBuilder) {
     if (enableGenericMetadataInLibrary) return false;
 
     List<FunctionTypeBuilder> genericFunctionTypeBuilders =
@@ -3139,7 +3158,7 @@
           "Function 'findUnaliasedGenericFunctionTypes' "
           "returned a function type without type variables.");
       for (TypeVariableBuilder typeVariable
-          in genericFunctionTypeBuilder.typeVariables) {
+          in genericFunctionTypeBuilder.typeVariables!) {
         hasReportedErrors =
             _reportGenericFunctionTypeAsBoundIfNeeded(typeVariable) ||
                 hasReportedErrors;
@@ -3155,19 +3174,19 @@
       TypeVariableBuilder typeVariable) {
     if (enableGenericMetadataInLibrary) return false;
 
-    TypeBuilder bound = typeVariable.bound;
+    TypeBuilder? bound = typeVariable.bound;
     bool isUnaliasedGenericFunctionType = bound is FunctionTypeBuilder &&
         bound.typeVariables != null &&
-        bound.typeVariables.isNotEmpty;
+        bound.typeVariables!.isNotEmpty;
     bool isAliasedGenericFunctionType = false;
     if (bound is NamedTypeBuilder) {
-      TypeDeclarationBuilder declaration = bound.declaration;
+      TypeDeclarationBuilder? declaration = bound.declaration;
       // TODO(dmitryas): Unalias beyond the first layer for the check.
       if (declaration is TypeAliasBuilder) {
-        TypeBuilder rhsType = declaration.type;
+        TypeBuilder? rhsType = declaration.type;
         if (rhsType is FunctionTypeBuilder &&
             rhsType.typeVariables != null &&
-            rhsType.typeVariables.isNotEmpty) {
+            rhsType.typeVariables!.isNotEmpty) {
           isAliasedGenericFunctionType = true;
         }
       }
@@ -3185,8 +3204,8 @@
       TypeBuilder bottomType, ClassBuilder objectClass) {
     int count = 0;
 
-    int computeDefaultTypesForVariables(List<TypeVariableBuilder> variables,
-        {bool inErrorRecovery}) {
+    int computeDefaultTypesForVariables(List<TypeVariableBuilder>? variables,
+        {required bool inErrorRecovery}) {
       if (variables == null) return 0;
 
       bool haveErroneousBounds = false;
@@ -3211,8 +3230,8 @@
               unboundTypes: unboundTypes,
               unboundTypeVariables: unboundTypeVariables);
           for (TypeBuilder unboundType in unboundTypes) {
-            currentTypeParameterScopeBuilder
-                .addType(new UnresolvedType(unboundType, -1, null));
+            currentTypeParameterScopeBuilder.addType(new UnresolvedType(
+                unboundType, unboundType.charOffset!, unboundType.fileUri!));
           }
           boundlessTypeVariables.addAll(unboundTypeVariables);
           for (int i = 0; i < variables.length; ++i) {
@@ -3239,7 +3258,7 @@
       }
     }
 
-    for (Builder declaration in libraryDeclaration.members.values) {
+    for (Builder declaration in libraryDeclaration.members!.values) {
       if (declaration is ClassBuilder) {
         {
           List<NonSimplicityIssue> issues =
@@ -3250,7 +3269,7 @@
               inErrorRecovery: issues.isNotEmpty);
 
           declaration.constructors.forEach((String name, Builder member) {
-            List<FormalParameterBuilder> formals;
+            List<FormalParameterBuilder>? formals;
             if (member is ProcedureBuilder) {
               assert(member.isFactory,
                   "Unexpected constructor member (${member.runtimeType}).");
@@ -3277,10 +3296,10 @@
         }
         declaration.forEach((String name, Builder member) {
           if (member is ProcedureBuilder) {
-            List<Object> issues =
+            List<NonSimplicityIssue> issues =
                 getNonSimplicityIssuesForTypeVariables(member.typeVariables);
-            if (member.formals != null && member.formals.isNotEmpty) {
-              for (FormalParameterBuilder formal in member.formals) {
+            if (member.formals != null && member.formals!.isNotEmpty) {
+              for (FormalParameterBuilder formal in member.formals!) {
                 issues.addAll(getInboundReferenceIssuesInType(formal.type));
                 _recursivelyReportGenericFunctionTypesAsBoundsForType(
                     formal.type);
@@ -3297,9 +3316,10 @@
           } else {
             assert(member is FieldBuilder,
                 "Unexpected class member $member (${member.runtimeType}).");
-            TypeBuilder fieldType = (member as FieldBuilder).type;
+            TypeBuilder? fieldType = (member as FieldBuilder).type;
             if (fieldType != null) {
-              List<Object> issues = getInboundReferenceIssuesInType(fieldType);
+              List<NonSimplicityIssue> issues =
+                  getInboundReferenceIssuesInType(fieldType);
               reportIssues(issues);
               _recursivelyReportGenericFunctionTypesAsBoundsForType(fieldType);
             }
@@ -3315,10 +3335,10 @@
             inErrorRecovery: issues.isNotEmpty);
         _recursivelyReportGenericFunctionTypesAsBoundsForType(declaration.type);
       } else if (declaration is FunctionBuilder) {
-        List<Object> issues =
+        List<NonSimplicityIssue> issues =
             getNonSimplicityIssuesForTypeVariables(declaration.typeVariables);
-        if (declaration.formals != null && declaration.formals.isNotEmpty) {
-          for (FormalParameterBuilder formal in declaration.formals) {
+        if (declaration.formals != null && declaration.formals!.isNotEmpty) {
+          for (FormalParameterBuilder formal in declaration.formals!) {
             issues.addAll(getInboundReferenceIssuesInType(formal.type));
             _recursivelyReportGenericFunctionTypesAsBoundsForType(formal.type);
           }
@@ -3334,19 +3354,19 @@
             inErrorRecovery: issues.isNotEmpty);
       } else if (declaration is ExtensionBuilder) {
         {
-          List<Object> issues = getNonSimplicityIssuesForDeclaration(
-              declaration,
-              performErrorRecovery: true);
+          List<NonSimplicityIssue> issues =
+              getNonSimplicityIssuesForDeclaration(declaration,
+                  performErrorRecovery: true);
           reportIssues(issues);
           count += computeDefaultTypesForVariables(declaration.typeParameters,
               inErrorRecovery: issues.isNotEmpty);
         }
         declaration.forEach((String name, Builder member) {
           if (member is ProcedureBuilder) {
-            List<Object> issues =
+            List<NonSimplicityIssue> issues =
                 getNonSimplicityIssuesForTypeVariables(member.typeVariables);
-            if (member.formals != null && member.formals.isNotEmpty) {
-              for (FormalParameterBuilder formal in member.formals) {
+            if (member.formals != null && member.formals!.isNotEmpty) {
+              for (FormalParameterBuilder formal in member.formals!) {
                 issues.addAll(getInboundReferenceIssuesInType(formal.type));
                 _recursivelyReportGenericFunctionTypesAsBoundsForType(
                     formal.type);
@@ -3372,7 +3392,7 @@
         });
       } else if (declaration is FieldBuilder) {
         if (declaration.type != null) {
-          List<Object> issues =
+          List<NonSimplicityIssue> issues =
               getInboundReferenceIssuesInType(declaration.type);
           reportIssues(issues);
           _recursivelyReportGenericFunctionTypesAsBoundsForType(
@@ -3387,15 +3407,15 @@
             "(${declaration.runtimeType}).");
       }
     }
-    for (Builder declaration in libraryDeclaration.setters.values) {
+    for (Builder declaration in libraryDeclaration.setters!.values) {
       assert(
           declaration is ProcedureBuilder,
           "Expected setter to be a ProcedureBuilder, "
           "but got '${declaration.runtimeType}'");
       if (declaration is ProcedureBuilder &&
           declaration.formals != null &&
-          declaration.formals.isNotEmpty) {
-        for (FormalParameterBuilder formal in declaration.formals) {
+          declaration.formals!.isNotEmpty) {
+        for (FormalParameterBuilder formal in declaration.formals!) {
           reportIssues(getInboundReferenceIssuesInType(formal.type));
           _recursivelyReportGenericFunctionTypesAsBoundsForType(formal.type);
         }
@@ -3413,7 +3433,7 @@
       List<LocatedMessage> context = <LocatedMessage>[];
       if (origin.languageVersion.isExplicit) {
         context.add(messageLanguageVersionLibraryContext.withLocation(
-            origin.languageVersion.fileUri,
+            origin.languageVersion.fileUri!,
             origin.languageVersion.charOffset,
             origin.languageVersion.charCount));
       }
@@ -3436,7 +3456,7 @@
       String name = originDeclarations.name;
       Builder member = originDeclarations.current;
       bool isSetter = member.isSetter;
-      Builder patch = scope.lookupLocalMember(name, setter: isSetter);
+      Builder? patch = scope.lookupLocalMember(name, setter: isSetter);
       if (patch != null) {
         // [patch] has the same name as a [member] in [origin] library, so it
         // must be a patch to [member].
@@ -3447,7 +3467,7 @@
         // import it into the patch library. This ensures that the origin
         // library is in scope of the patch library.
         if (isSetter) {
-          scopeBuilder.addSetter(name, member);
+          scopeBuilder.addSetter(name, member as MemberBuilder);
         } else {
           scopeBuilder.addMember(name, member);
         }
@@ -3482,7 +3502,7 @@
   void injectMemberFromPatch(String name, Builder member) {
     if (member.isSetter) {
       assert(scope.lookupLocalMember(name, setter: true) == null);
-      scopeBuilder.addSetter(name, member);
+      scopeBuilder.addSetter(name, member as MemberBuilder);
     } else {
       assert(scope.lookupLocalMember(name, setter: false) == null);
       scopeBuilder.addMember(name, member);
@@ -3509,13 +3529,13 @@
 
   void reportTypeArgumentIssues(
       Iterable<TypeArgumentIssue> issues, Uri fileUri, int offset,
-      {bool inferred,
-      TypeArgumentsInfo typeArgumentsInfo,
-      DartType targetReceiver,
-      String targetName}) {
+      {bool? inferred,
+      TypeArgumentsInfo? typeArgumentsInfo,
+      DartType? targetReceiver,
+      String? targetName}) {
     for (TypeArgumentIssue issue in issues) {
       DartType argument = issue.argument;
-      TypeParameter typeParameter = issue.typeParameter;
+      TypeParameter? typeParameter = issue.typeParameter;
 
       Message message;
       bool issueInferred = inferred ??
@@ -3539,7 +3559,7 @@
                   templateIncorrectTypeArgumentQualifiedInferred.withArguments(
                       argument,
                       typeParameter.bound,
-                      typeParameter.name,
+                      typeParameter.name!,
                       targetReceiver,
                       targetName,
                       isNonNullableByDefault);
@@ -3547,7 +3567,7 @@
               message = templateIncorrectTypeArgumentQualified.withArguments(
                   argument,
                   typeParameter.bound,
-                  typeParameter.name,
+                  typeParameter.name!,
                   targetReceiver,
                   targetName,
                   isNonNullableByDefault);
@@ -3558,7 +3578,7 @@
                   .withArguments(
                       argument,
                       typeParameter.bound,
-                      typeParameter.name,
+                      typeParameter.name!,
                       targetReceiver,
                       isNonNullableByDefault);
             } else {
@@ -3566,28 +3586,29 @@
                   templateIncorrectTypeArgumentInstantiation.withArguments(
                       argument,
                       typeParameter.bound,
-                      typeParameter.name,
+                      typeParameter.name!,
                       targetReceiver,
                       isNonNullableByDefault);
             }
           }
         } else {
           String enclosingName = issue.enclosingType == null
-              ? targetName
-              : getGenericTypeName(issue.enclosingType);
+              ? targetName!
+              : getGenericTypeName(issue.enclosingType!);
+          // ignore: unnecessary_null_comparison
           assert(enclosingName != null);
           if (issueInferred) {
             message = templateIncorrectTypeArgumentInferred.withArguments(
                 argument,
                 typeParameter.bound,
-                typeParameter.name,
+                typeParameter.name!,
                 enclosingName,
                 isNonNullableByDefault);
           } else {
             message = templateIncorrectTypeArgument.withArguments(
                 argument,
                 typeParameter.bound,
-                typeParameter.name,
+                typeParameter.name!,
                 enclosingName,
                 isNonNullableByDefault);
           }
@@ -3606,10 +3627,10 @@
   }
 
   void reportTypeArgumentIssue(Message message, Uri fileUri, int fileOffset,
-      {TypeParameter typeParameter,
-      DartType superBoundedAttempt,
-      DartType superBoundedAttemptInverted}) {
-    List<LocatedMessage> context;
+      {TypeParameter? typeParameter,
+      DartType? superBoundedAttempt,
+      DartType? superBoundedAttemptInverted}) {
+    List<LocatedMessage>? context;
     // Skip reporting location for function-type type parameters as it's a
     // limitation of Kernel.
     if (typeParameter != null &&
@@ -3619,7 +3640,9 @@
       // have a reportable location.
       (context ??= <LocatedMessage>[]).add(
           messageIncorrectTypeArgumentVariable.withLocation(
-              typeParameter.location.file, typeParameter.fileOffset, noLength));
+              typeParameter.location!.file,
+              typeParameter.fileOffset,
+              noLength));
     }
     if (superBoundedAttemptInverted != null && superBoundedAttempt != null) {
       (context ??= <LocatedMessage>[]).add(templateSuperBoundedHint
@@ -3634,7 +3657,7 @@
       FieldBuilder fieldBuilder, TypeEnvironment typeEnvironment) {
     // Check the bounds in the field's type.
     checkBoundsInType(fieldBuilder.fieldType, typeEnvironment,
-        fieldBuilder.fileUri, fieldBuilder.charOffset,
+        fieldBuilder.fileUri!, fieldBuilder.charOffset,
         allowSuperBounded: true);
 
     // Check that the field has an initializer if its type is potentially
@@ -3670,11 +3693,11 @@
       bool isOptionalNamed = !formal.isNamedRequired && formal.isNamed;
       bool isOptional = isOptionalPositional || isOptionalNamed;
       if (isOptional &&
-          formal.variable.type.isPotentiallyNonNullable &&
+          formal.variable!.type.isPotentiallyNonNullable &&
           !formal.hasDeclaredInitializer) {
         addProblem(
             templateOptionalNonNullableWithoutInitializerError.withArguments(
-                formal.name, formal.variable.type, isNonNullableByDefault),
+                formal.name, formal.variable!.type, isNonNullableByDefault),
             formal.charOffset,
             formal.name.length,
             formal.fileUri);
@@ -3718,8 +3741,8 @@
               templateIncorrectTypeArgument.withArguments(
                   argument,
                   typeParameter.bound,
-                  typeParameter.name,
-                  getGenericTypeName(issue.enclosingType),
+                  typeParameter.name!,
+                  getGenericTypeName(issue.enclosingType!),
                   library.isNonNullableByDefault),
               fileUri,
               parameter.fileOffset,
@@ -3733,11 +3756,11 @@
 
   void checkBoundsInFunctionNodeParts(
       TypeEnvironment typeEnvironment, Uri fileUri, int fileOffset,
-      {List<TypeParameter> typeParameters,
-      List<VariableDeclaration> positionalParameters,
-      List<VariableDeclaration> namedParameters,
-      DartType returnType,
-      int requiredParameterCount,
+      {List<TypeParameter>? typeParameters,
+      List<VariableDeclaration>? positionalParameters,
+      List<VariableDeclaration>? namedParameters,
+      DartType? returnType,
+      int? requiredParameterCount,
       bool skipReturnType = false}) {
     if (typeParameters != null) {
       for (TypeParameter parameter in typeParameters) {
@@ -3790,8 +3813,8 @@
               templateIncorrectTypeArgumentInReturnType.withArguments(
                   argument,
                   typeParameter.bound,
-                  typeParameter.name,
-                  getGenericTypeName(issue.enclosingType),
+                  typeParameter.name!,
+                  getGenericTypeName(issue.enclosingType!),
                   isNonNullableByDefault),
               fileUri,
               fileOffset,
@@ -3806,10 +3829,10 @@
   void checkTypesInProcedureBuilder(
       ProcedureBuilder procedureBuilder, TypeEnvironment typeEnvironment) {
     checkBoundsInFunctionNode(procedureBuilder.procedure.function,
-        typeEnvironment, procedureBuilder.fileUri);
+        typeEnvironment, procedureBuilder.fileUri!);
     if (procedureBuilder.formals != null &&
         !(procedureBuilder.isAbstract || procedureBuilder.isExternal)) {
-      checkInitializersInFormals(procedureBuilder.formals, typeEnvironment);
+      checkInitializersInFormals(procedureBuilder.formals!, typeEnvironment);
     }
   }
 
@@ -3818,7 +3841,7 @@
     checkBoundsInFunctionNode(
         constructorBuilder.constructor.function, typeEnvironment, fileUri);
     if (!constructorBuilder.isExternal && constructorBuilder.formals != null) {
-      checkInitializersInFormals(constructorBuilder.formals, typeEnvironment);
+      checkInitializersInFormals(constructorBuilder.formals!, typeEnvironment);
     }
   }
 
@@ -3871,7 +3894,7 @@
 
   void checkBoundsInType(
       DartType type, TypeEnvironment typeEnvironment, Uri fileUri, int offset,
-      {bool inferred, bool allowSuperBounded = true}) {
+      {bool? inferred, bool allowSuperBounded = true}) {
     List<TypeArgumentIssue> issues = findTypeArgumentIssues(
         type,
         typeEnvironment,
@@ -3887,6 +3910,7 @@
   void checkBoundsInVariableDeclaration(
       VariableDeclaration node, TypeEnvironment typeEnvironment, Uri fileUri,
       {bool inferred = false}) {
+    // ignore: unnecessary_null_comparison
     if (node.type == null) return;
     checkBoundsInType(node.type, typeEnvironment, fileUri, node.fileOffset,
         inferred: inferred, allowSuperBounded: true);
@@ -3911,7 +3935,7 @@
     if (node.arguments.types.isEmpty) return;
     Procedure factory = node.target;
     assert(factory.isFactory);
-    Class klass = factory.enclosingClass;
+    Class klass = factory.enclosingClass!;
     DartType constructedType = new InterfaceType(
         klass, klass.enclosingLibrary.nonNullable, node.arguments.types);
     checkBoundsInType(
@@ -3928,7 +3952,7 @@
     // extension method calls. Currently all are considered inferred in the
     // error messages.
     if (node.arguments.types.isEmpty) return;
-    Class klass = node.target.enclosingClass;
+    Class? klass = node.target.enclosingClass;
     List<TypeParameter> parameters = node.target.function.typeParameters;
     List<DartType> arguments = node.arguments.types;
     // The following error is to be reported elsewhere.
@@ -3948,7 +3972,7 @@
         isNonNullableByDefault: library.isNonNullableByDefault,
         areGenericArgumentsAllowed: enableGenericMetadataInLibrary);
     if (issues.isNotEmpty) {
-      DartType targetReceiver;
+      DartType? targetReceiver;
       if (klass != null) {
         targetReceiver =
             new InterfaceType(klass, klass.enclosingLibrary.nonNullable);
@@ -3967,7 +3991,7 @@
       ClassHierarchy hierarchy,
       TypeInferrerImpl typeInferrer,
       Name name,
-      Member interfaceTarget,
+      Member? interfaceTarget,
       Arguments arguments,
       Uri fileUri,
       int offset) {
@@ -3981,14 +4005,16 @@
       return;
     }
     // TODO(dmitryas): Find a better way than relying on [interfaceTarget].
-    Member method = hierarchy.getDispatchTarget(klass, name) ?? interfaceTarget;
+    Member? method =
+        hierarchy.getDispatchTarget(klass, name) ?? interfaceTarget;
+    // ignore: unnecessary_null_comparison
     if (method == null || method is! Procedure) {
       return;
     }
     if (klass != method.enclosingClass) {
       Supertype parent =
-          hierarchy.getClassAsInstanceOf(klass, method.enclosingClass);
-      klass = method.enclosingClass;
+          hierarchy.getClassAsInstanceOf(klass, method.enclosingClass!)!;
+      klass = method.enclosingClass!;
       receiverTypeArguments = parent.typeArguments;
     }
     Map<TypeParameter, DartType> substitutionMap = <TypeParameter, DartType>{};
@@ -3999,14 +4025,14 @@
     // The error is to be reported elsewhere.
     if (methodParameters.length != arguments.types.length) return;
     List<TypeParameter> instantiatedMethodParameters =
-        new List<TypeParameter>.filled(methodParameters.length, null);
-    for (int i = 0; i < instantiatedMethodParameters.length; ++i) {
-      instantiatedMethodParameters[i] =
+        new List<TypeParameter>.generate(methodParameters.length, (int i) {
+      TypeParameter instantiatedMethodParameter =
           new TypeParameter(methodParameters[i].name);
       substitutionMap[methodParameters[i]] =
           new TypeParameterType.forAlphaRenaming(
-              methodParameters[i], instantiatedMethodParameters[i]);
-    }
+              methodParameters[i], instantiatedMethodParameter);
+      return instantiatedMethodParameter;
+    }, growable: false);
     for (int i = 0; i < instantiatedMethodParameters.length; ++i) {
       instantiatedMethodParameters[i].bound =
           substitute(methodParameters[i].bound, substitutionMap);
@@ -4036,7 +4062,7 @@
       ClassHierarchy hierarchy,
       TypeInferrerImpl typeInferrer,
       FunctionType functionType,
-      String localName,
+      String? localName,
       Arguments arguments,
       Uri fileUri,
       int offset) {
@@ -4074,7 +4100,8 @@
       List<DartType> typeArguments,
       Uri fileUri,
       int offset,
-      {bool inferred}) {
+      {required bool inferred}) {
+    // ignore: unnecessary_null_comparison
     assert(inferred != null);
     if (typeArguments.isEmpty) return;
 
@@ -4110,11 +4137,11 @@
       } else if (declaration is ProcedureBuilder) {
         checkTypesInProcedureBuilder(declaration, typeEnvironment);
         if (declaration.isGetter) {
-          Builder setterDeclaration =
+          Builder? setterDeclaration =
               scope.lookupLocalMember(declaration.name, setter: true);
           if (setterDeclaration != null) {
-            checkGetterSetterTypes(
-                declaration, setterDeclaration, typeEnvironment);
+            checkGetterSetterTypes(declaration,
+                setterDeclaration as ProcedureBuilder, typeEnvironment);
           }
         }
       } else if (declaration is SourceClassBuilder) {
@@ -4139,8 +4166,8 @@
   }
 
   @override
-  List<FieldBuilder> takeImplicitlyTypedFields() {
-    List<FieldBuilder> result = _implicitlyTypedFields;
+  List<FieldBuilder>? takeImplicitlyTypedFields() {
+    List<FieldBuilder>? result = _implicitlyTypedFields;
     _implicitlyTypedFields = null;
     return result;
   }
@@ -4150,20 +4177,20 @@
       _extensionsInScope = <ExtensionBuilder>{};
       scope.forEachExtension((e) {
         if (!e.extension.isExtensionTypeDeclaration) {
-          _extensionsInScope.add(e);
+          _extensionsInScope!.add(e);
         }
       });
       if (_prefixBuilders != null) {
-        for (PrefixBuilder prefix in _prefixBuilders) {
+        for (PrefixBuilder prefix in _prefixBuilders!) {
           prefix.exportScope.forEachExtension((e) {
             if (!e.extension.isExtensionTypeDeclaration) {
-              _extensionsInScope.add(e);
+              _extensionsInScope!.add(e);
             }
           });
         }
       }
     }
-    _extensionsInScope.forEach(f);
+    _extensionsInScope!.forEach(f);
   }
 
   void clearExtensionsInScopeCache() {
@@ -4177,12 +4204,12 @@
   /// OutlineBuilder.endClassDeclaration,
   /// OutlineBuilder.beginMixinDeclaration,
   /// OutlineBuilder.endMixinDeclaration.
-  void setCurrentClassName(String name) {
+  void setCurrentClassName(String? name) {
     if (name == null) {
       _currentClassReferencesFromIndexed = null;
     } else if (referencesFrom != null) {
       _currentClassReferencesFromIndexed =
-          referencesFromIndexed.lookupIndexedClass(name);
+          referencesFromIndexed!.lookupIndexedClass(name);
     }
   }
 
@@ -4202,7 +4229,7 @@
   void checkUncheckedTypedefTypes(TypeEnvironment typeEnvironment) {
     for (UncheckedTypedefType uncheckedTypedefType in uncheckedTypedefTypes) {
       checkBoundsInType(uncheckedTypedefType.typeToCheck, typeEnvironment,
-          uncheckedTypedefType.fileUri, uncheckedTypedefType.offset);
+          uncheckedTypedefType.fileUri!, uncheckedTypedefType.offset!);
     }
     uncheckedTypedefTypes.clear();
   }
@@ -4233,15 +4260,15 @@
 class TypeParameterScopeBuilder {
   TypeParameterScopeKind _kind;
 
-  final TypeParameterScopeBuilder parent;
+  final TypeParameterScopeBuilder? parent;
 
-  final Map<String, Builder> members;
+  final Map<String, Builder>? members;
 
-  final Map<String, Builder> constructors;
+  final Map<String, MemberBuilder>? constructors;
 
-  final Map<String, MemberBuilder> setters;
+  final Map<String, MemberBuilder>? setters;
 
-  final Set<ExtensionBuilder> extensions;
+  final Set<ExtensionBuilder>? extensions;
 
   final List<UnresolvedType> types = <UnresolvedType>[];
 
@@ -4253,13 +4280,13 @@
   /// with the name as the current declaration changes.
   int _charOffset;
 
-  List<TypeVariableBuilder> _typeVariables;
+  List<TypeVariableBuilder>? _typeVariables;
 
   /// The type of `this` in instance methods declared in extension declarations.
   ///
   /// Instance methods declared in extension declarations methods are extended
   /// with a synthesized parameter of this type.
-  TypeBuilder _extensionThisType;
+  TypeBuilder? _extensionThisType;
 
   bool declaresConstConstructor = false;
 
@@ -4272,6 +4299,7 @@
       this._name,
       this._charOffset,
       this.parent) {
+    // ignore: unnecessary_null_comparison
     assert(_name != null);
   }
 
@@ -4302,7 +4330,7 @@
   /// Registers that this builder is preparing for a class declaration with the
   /// given [name] and [typeVariables] located [charOffset].
   void markAsClassDeclaration(
-      String name, int charOffset, List<TypeVariableBuilder> typeVariables) {
+      String name, int charOffset, List<TypeVariableBuilder>? typeVariables) {
     assert(_kind == TypeParameterScopeKind.classOrNamedMixinApplication,
         "Unexpected declaration kind: $_kind");
     _kind = TypeParameterScopeKind.classDeclaration;
@@ -4314,7 +4342,7 @@
   /// Registers that this builder is preparing for a named mixin application
   /// with the given [name] and [typeVariables] located [charOffset].
   void markAsNamedMixinApplication(
-      String name, int charOffset, List<TypeVariableBuilder> typeVariables) {
+      String name, int charOffset, List<TypeVariableBuilder>? typeVariables) {
     assert(_kind == TypeParameterScopeKind.classOrNamedMixinApplication,
         "Unexpected declaration kind: $_kind");
     _kind = TypeParameterScopeKind.namedMixinApplication;
@@ -4326,7 +4354,7 @@
   /// Registers that this builder is preparing for a mixin declaration with the
   /// given [name] and [typeVariables] located [charOffset].
   void markAsMixinDeclaration(
-      String name, int charOffset, List<TypeVariableBuilder> typeVariables) {
+      String name, int charOffset, List<TypeVariableBuilder>? typeVariables) {
     // TODO(johnniwinther): Avoid using 'classOrNamedMixinApplication' for mixin
     // declaration. These are syntactically distinct so we don't need the
     // transition.
@@ -4341,7 +4369,7 @@
   /// Registers that this builder is preparing for an extension declaration with
   /// the given [name] and [typeVariables] located [charOffset].
   void markAsExtensionDeclaration(
-      String name, int charOffset, List<TypeVariableBuilder> typeVariables) {
+      String name, int charOffset, List<TypeVariableBuilder>? typeVariables) {
     assert(_kind == TypeParameterScopeKind.extensionDeclaration,
         "Unexpected declaration kind: $_kind");
     _name = name;
@@ -4377,7 +4405,7 @@
 
   int get charOffset => _charOffset;
 
-  List<TypeVariableBuilder> get typeVariables => _typeVariables;
+  List<TypeVariableBuilder>? get typeVariables => _typeVariables;
 
   /// Returns the 'extension this type' of the extension declaration prepared
   /// for by this builder.
@@ -4396,7 +4424,7 @@
         "DeclarationBuilder.extensionThisType not supported on $kind.");
     assert(_extensionThisType != null,
         "DeclarationBuilder.extensionThisType has not been set on $this.");
-    return _extensionThisType;
+    return _extensionThisType!;
   }
 
   /// Adds the yet unresolved [type] to this scope builder.
@@ -4410,24 +4438,24 @@
 
   /// Resolves type variables in [types] and propagate other types to [parent].
   void resolveTypes(
-      List<TypeVariableBuilder> typeVariables, SourceLibraryBuilder library) {
-    Map<String, TypeVariableBuilder> map;
+      List<TypeVariableBuilder>? typeVariables, SourceLibraryBuilder library) {
+    Map<String, TypeVariableBuilder>? map;
     if (typeVariables != null) {
       map = <String, TypeVariableBuilder>{};
       for (TypeVariableBuilder builder in typeVariables) {
         map[builder.name] = builder;
       }
     }
-    Scope scope;
+    Scope? scope;
     for (UnresolvedType type in types) {
-      Object nameOrQualified = type.builder.name;
-      String name = nameOrQualified is QualifiedName
-          ? nameOrQualified.qualifier
-          : nameOrQualified;
-      Builder declaration;
+      Object? nameOrQualified = type.builder.name;
+      String? name = nameOrQualified is QualifiedName
+          ? nameOrQualified.qualifier as String
+          : nameOrQualified as String?;
+      Builder? declaration;
       if (name != null) {
         if (members != null) {
-          declaration = members[name];
+          declaration = members![name];
         }
         if (declaration == null && map != null) {
           declaration = map[name];
@@ -4436,9 +4464,9 @@
       if (declaration == null) {
         // Since name didn't resolve in this scope, propagate it to the
         // parent declaration.
-        parent.addType(type);
+        parent!.addType(type);
       } else if (nameOrQualified is QualifiedName) {
-        NamedTypeBuilder builder = type.builder;
+        NamedTypeBuilder builder = type.builder as NamedTypeBuilder;
         // Attempt to use a member or type variable as a prefix.
         Message message = templateNotAPrefixInTypeAnnotation.withArguments(
             flattenName(
@@ -4457,9 +4485,9 @@
     types.clear();
   }
 
-  Scope toScope(Scope parent) {
+  Scope toScope(Scope? parent) {
     return new Scope(
-        local: members,
+        local: members ?? const {},
         setters: setters,
         extensions: extensions,
         parent: parent,
@@ -4474,7 +4502,7 @@
 class FieldInfo {
   final String name;
   final int charOffset;
-  final Token initializerToken;
+  final Token? initializerToken;
   final Token beforeLast;
   final int charEndOffset;
 
@@ -4483,11 +4511,11 @@
 }
 
 Uri computeLibraryUri(Builder declaration) {
-  Builder current = declaration;
-  do {
+  Builder? current = declaration;
+  while (current != null) {
     if (current is LibraryBuilder) return current.importUri;
     current = current.parent;
-  } while (current != null);
+  }
   return unhandled("no library parent", "${declaration.runtimeType}",
       declaration.charOffset, declaration.fileUri);
 }
@@ -4505,7 +4533,7 @@
 
 class LanguageVersion {
   final Version version;
-  final Uri fileUri;
+  final Uri? fileUri;
   final int charOffset;
   final int charCount;
   bool isFinal = false;
@@ -4569,7 +4597,7 @@
   bool get valid => true;
 
   @override
-  Uri get fileUri => null;
+  Uri? get fileUri => null;
 
   @override
   int get charOffset => -1;
@@ -4601,7 +4629,7 @@
     unhandled.remove(rootVariable);
     if (rootVariable.bound != null) {
       _sortTypeVariablesTopologicallyFromRoot(
-          rootVariable.bound, unhandled, result);
+          rootVariable.bound!, unhandled, result);
     }
     result.add(rootVariable);
   }
@@ -4610,39 +4638,40 @@
 
 void _sortTypeVariablesTopologicallyFromRoot(TypeBuilder root,
     Set<TypeVariableBuilder> unhandled, List<TypeVariableBuilder> result) {
+  // ignore: unnecessary_null_comparison
   assert(root != null);
 
-  List<TypeVariableBuilder> typeVariables;
-  List<TypeBuilder> internalDependents;
+  List<TypeVariableBuilder>? typeVariables;
+  List<TypeBuilder>? internalDependents;
 
   if (root is NamedTypeBuilder) {
-    TypeDeclarationBuilder declaration = root.declaration;
+    TypeDeclarationBuilder? declaration = root.declaration;
     if (declaration is ClassBuilder) {
       if (declaration.typeVariables != null &&
-          declaration.typeVariables.isNotEmpty) {
+          declaration.typeVariables!.isNotEmpty) {
         typeVariables = declaration.typeVariables;
       }
     } else if (declaration is TypeAliasBuilder) {
       if (declaration.typeVariables != null &&
-          declaration.typeVariables.isNotEmpty) {
+          declaration.typeVariables!.isNotEmpty) {
         typeVariables = declaration.typeVariables;
       }
-      internalDependents = <TypeBuilder>[declaration.type];
+      internalDependents = <TypeBuilder>[declaration.type!];
     } else if (declaration is TypeVariableBuilder) {
       typeVariables = <TypeVariableBuilder>[declaration];
     }
   } else if (root is FunctionTypeBuilder) {
-    if (root.typeVariables != null && root.typeVariables.isNotEmpty) {
+    if (root.typeVariables != null && root.typeVariables!.isNotEmpty) {
       typeVariables = root.typeVariables;
     }
-    if (root.formals != null && root.formals.isNotEmpty) {
+    if (root.formals != null && root.formals!.isNotEmpty) {
       internalDependents = <TypeBuilder>[];
-      for (FormalParameterBuilder formal in root.formals) {
-        internalDependents.add(formal.type);
+      for (FormalParameterBuilder formal in root.formals!) {
+        internalDependents.add(formal.type!);
       }
     }
     if (root.returnType != null) {
-      (internalDependents ??= <TypeBuilder>[]).add(root.returnType);
+      (internalDependents ??= <TypeBuilder>[]).add(root.returnType!);
     }
   }
 
@@ -4652,7 +4681,7 @@
         unhandled.remove(variable);
         if (variable.bound != null) {
           _sortTypeVariablesTopologicallyFromRoot(
-              variable.bound, unhandled, result);
+              variable.bound!, unhandled, result);
         }
         result.add(variable);
       }
@@ -4676,10 +4705,8 @@
 class UncheckedTypedefType {
   final TypedefType typeToCheck;
 
-  // TODO(dmitryas): Make these fields nullable when the library is opted-in to
-  // NNBD.
-  int offset;
-  Uri fileUri;
+  int? offset;
+  Uri? fileUri;
 
   UncheckedTypedefType(this.typeToCheck);
 }
diff --git a/pkg/front_end/lib/src/fasta/source/source_loader.dart b/pkg/front_end/lib/src/fasta/source/source_loader.dart
index ddf578b..51b2dd8 100644
--- a/pkg/front_end/lib/src/fasta/source/source_loader.dart
+++ b/pkg/front_end/lib/src/fasta/source/source_loader.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.source_loader;
 
 import 'dart:convert' show utf8;
@@ -135,14 +133,14 @@
 
   final Map<Uri, List<int>> sourceBytes = <Uri, List<int>>{};
 
-  ClassHierarchyBuilder builderHierarchy;
+  ClassHierarchyBuilder? _builderHierarchy;
 
-  ReferenceFromIndex referenceFromIndex;
+  ReferenceFromIndex? referenceFromIndex;
 
   /// Used when building directly to kernel.
-  ClassHierarchy _hierarchy;
-  CoreTypes _coreTypes;
-  TypeEnvironment _typeEnvironment;
+  ClassHierarchy? _hierarchy;
+  CoreTypes? _coreTypes;
+  TypeEnvironment? _typeEnvironment;
 
   /// For builders created with a reference, this maps from that reference to
   /// that builder. This is used for looking up source builders when finalizing
@@ -152,27 +150,33 @@
   /// Used when checking whether a return type of an async function is valid.
   ///
   /// The said return type is valid if it's a subtype of [futureOfBottom].
-  DartType futureOfBottom;
+  DartType? _futureOfBottom;
+
+  DartType get futureOfBottom => _futureOfBottom!;
 
   /// Used when checking whether a return type of a sync* function is valid.
   ///
   /// The said return type is valid if it's a subtype of [iterableOfBottom].
-  DartType iterableOfBottom;
+  DartType? _iterableOfBottom;
+
+  DartType get iterableOfBottom => _iterableOfBottom!;
 
   /// Used when checking whether a return type of an async* function is valid.
   ///
   /// The said return type is valid if it's a subtype of [streamOfBottom].
-  DartType streamOfBottom;
+  DartType? _streamOfBottom;
 
-  TypeInferenceEngineImpl typeInferenceEngine;
+  DartType get streamOfBottom => _streamOfBottom!;
 
-  Instrumentation instrumentation;
+  TypeInferenceEngineImpl? _typeInferenceEngine;
 
-  CollectionTransformer collectionTransformer;
+  Instrumentation? instrumentation;
 
-  SetLiteralTransformer setLiteralTransformer;
+  CollectionTransformer? collectionTransformer;
 
-  final SourceLoaderDataForTesting dataForTesting;
+  SetLiteralTransformer? setLiteralTransformer;
+
+  final SourceLoaderDataForTesting? dataForTesting;
 
   SourceLoader(this.fileSystem, this.includeComments, KernelTarget target)
       : dataForTesting =
@@ -183,12 +187,12 @@
 
   CoreTypes get coreTypes {
     assert(_coreTypes != null, "CoreTypes has not been computed.");
-    return _coreTypes;
+    return _coreTypes!;
   }
 
-  ClassHierarchy get hierarchy => _hierarchy;
+  ClassHierarchy get hierarchy => _hierarchy!;
 
-  void set hierarchy(ClassHierarchy value) {
+  void set hierarchy(ClassHierarchy? value) {
     if (_hierarchy != value) {
       _hierarchy = value;
       _typeEnvironment = null;
@@ -199,6 +203,10 @@
     return _typeEnvironment ??= new TypeEnvironment(coreTypes, hierarchy);
   }
 
+  TypeInferenceEngineImpl get typeInferenceEngine => _typeInferenceEngine!;
+
+  ClassHierarchyBuilder get builderHierarchy => _builderHierarchy!;
+
   Template<SummaryTemplate> get outlineSummaryTemplate =>
       templateSourceOutlineSummary;
 
@@ -209,7 +217,7 @@
     Uri fileUri = library.fileUri;
 
     // Lookup the file URI in the cache.
-    List<int> bytes = sourceBytes[fileUri];
+    List<int>? bytes = sourceBytes[fileUri];
 
     if (bytes == null) {
       // Error recovery.
@@ -312,12 +320,12 @@
         library.addProblem(error.assertionMessage, offsetForToken(token),
             lengthForToken(token), fileUri);
       }
-      token = token.next;
+      token = token.next!;
     }
     return token;
   }
 
-  List<int> synthesizeSourceForMissingFile(Uri uri, Message message) {
+  List<int> synthesizeSourceForMissingFile(Uri uri, Message? message) {
     switch ("$uri") {
       case "dart:core":
         return utf8.encode(defaultDartCoreSource);
@@ -339,22 +347,22 @@
     }
   }
 
-  Set<LibraryBuilder> _strongOptOutLibraries;
+  Set<LibraryBuilder>? _strongOptOutLibraries;
 
   void registerStrongOptOutLibrary(LibraryBuilder libraryBuilder) {
     _strongOptOutLibraries ??= {};
-    _strongOptOutLibraries.add(libraryBuilder);
+    _strongOptOutLibraries!.add(libraryBuilder);
     hasInvalidNnbdModeLibrary = true;
   }
 
   bool hasInvalidNnbdModeLibrary = false;
 
-  Map<LibraryBuilder, Message> _nnbdMismatchLibraries;
+  Map<LibraryBuilder, Message>? _nnbdMismatchLibraries;
 
   void registerNnbdMismatchLibrary(
       LibraryBuilder libraryBuilder, Message message) {
     _nnbdMismatchLibraries ??= {};
-    _nnbdMismatchLibraries[libraryBuilder] = message;
+    _nnbdMismatchLibraries![libraryBuilder] = message;
     hasInvalidNnbdModeLibrary = true;
   }
 
@@ -378,26 +386,26 @@
       // config we include each library uri in the message. For non-package
       // libraries with no corresponding package config we generate a message
       // per library.
-      giveCombinedErrorForNonStrongLibraries(_strongOptOutLibraries,
+      giveCombinedErrorForNonStrongLibraries(_strongOptOutLibraries!,
           emitNonPackageErrors: true);
       _strongOptOutLibraries = null;
     }
     if (_nnbdMismatchLibraries != null) {
       for (MapEntry<LibraryBuilder, Message> entry
-          in _nnbdMismatchLibraries.entries) {
+          in _nnbdMismatchLibraries!.entries) {
         addProblem(entry.value, -1, noLength, entry.key.fileUri);
       }
       _nnbdMismatchLibraries = null;
     }
   }
 
-  FormattedMessage giveCombinedErrorForNonStrongLibraries(
+  FormattedMessage? giveCombinedErrorForNonStrongLibraries(
       Set<LibraryBuilder> libraries,
-      {bool emitNonPackageErrors}) {
-    Map<String, List<LibraryBuilder>> libraryByPackage = {};
+      {required bool emitNonPackageErrors}) {
+    Map<String?, List<LibraryBuilder>> libraryByPackage = {};
     Map<Package, Version> enableNonNullableVersionByPackage = {};
     for (LibraryBuilder libraryBuilder in libraries) {
-      final Package package =
+      final Package? package =
           target.uriTranslator.getPackage(libraryBuilder.importUri);
 
       if (package != null &&
@@ -409,7 +417,7 @@
                     ExperimentalFlag.nonNullable,
                     new Uri(scheme: 'package', path: package.name));
         Version version = new Version(
-            package.languageVersion.major, package.languageVersion.minor);
+            package.languageVersion!.major, package.languageVersion!.minor);
         if (version < enableNonNullableVersion) {
           (libraryByPackage[package.name] ??= []).add(libraryBuilder);
           continue;
@@ -428,7 +436,7 @@
     if (libraryByPackage.isNotEmpty) {
       List<Uri> involvedFiles = [];
       List<String> dependencies = [];
-      libraryByPackage.forEach((String name, List<LibraryBuilder> libraries) {
+      libraryByPackage.forEach((String? name, List<LibraryBuilder> libraries) {
         if (name != null) {
           dependencies.add('package:$name');
           for (LibraryBuilder libraryBuilder in libraries) {
@@ -464,6 +472,7 @@
 
   Future<Null> buildOutline(SourceLibraryBuilder library) async {
     Token tokens = await tokenize(library);
+    // ignore: unnecessary_null_comparison
     if (tokens == null) return;
     OutlineBuilder listener = new OutlineBuilder(library);
     new ClassMemberParser(listener).parseUnit(tokens);
@@ -475,6 +484,7 @@
       // second time, and the first time was in [buildOutline] above. So this
       // time we suppress lexical errors.
       Token tokens = await tokenize(library, suppressLexicalErrors: true);
+      // ignore: unnecessary_null_comparison
       if (tokens == null) return;
       DietListener listener = createDietListener(library);
       DietParser parser = new DietParser(listener);
@@ -484,7 +494,9 @@
           // Part was included in multiple libraries. Skip it here.
           continue;
         }
-        Token tokens = await tokenize(part, suppressLexicalErrors: true);
+        Token tokens = await tokenize(part as SourceLibraryBuilder,
+            suppressLexicalErrors: true);
+        // ignore: unnecessary_null_comparison
         if (tokens != null) {
           listener.uri = part.fileUri;
           parser.parseUnit(tokens);
@@ -496,16 +508,16 @@
   // TODO(johnniwinther,jensj): Handle expression in extensions?
   Future<Expression> buildExpression(
       SourceLibraryBuilder libraryBuilder,
-      String enclosingClass,
+      String? enclosingClass,
       bool isClassInstanceMember,
       FunctionNode parameters) async {
     Token token = await tokenize(libraryBuilder, suppressLexicalErrors: false);
-    if (token == null) return null;
     DietListener dietListener = createDietListener(libraryBuilder);
 
     Builder parent = libraryBuilder;
     if (enclosingClass != null) {
-      Builder cls = dietListener.memberScope.lookup(enclosingClass, -1, null);
+      Builder? cls = dietListener.memberScope
+          .lookup(enclosingClass, -1, libraryBuilder.fileUri);
       if (cls is ClassBuilder) {
         parent = cls;
         dietListener
@@ -540,13 +552,13 @@
       ..parent = parent;
     BodyBuilder listener = dietListener.createListener(
         builder, dietListener.memberScope,
-        isDeclarationInstanceMember: isClassInstanceMember);
+        isDeclarationInstanceMember: isClassInstanceMember) as BodyBuilder;
 
     return listener.parseSingleExpression(
         new Parser(listener), token, parameters);
   }
 
-  KernelTarget get target => super.target;
+  KernelTarget get target => super.target as KernelTarget;
 
   DietListener createDietListener(SourceLibraryBuilder library) {
     return new DietListener(library, hierarchy, coreTypes, typeInferenceEngine);
@@ -560,7 +572,7 @@
         if (library.isPart) {
           parts.add(uri);
         } else {
-          libraries.add(library);
+          libraries.add(library as SourceLibraryBuilder);
         }
       }
     });
@@ -572,7 +584,7 @@
       if (usedParts.contains(uri)) {
         builders.remove(uri);
       } else {
-        SourceLibraryBuilder part = builders[uri];
+        SourceLibraryBuilder part = builders[uri] as SourceLibraryBuilder;
         part.addProblem(messagePartOrphan, 0, 1, part.fileUri);
         part.validatePart(null, null);
       }
@@ -592,7 +604,7 @@
     Set<LibraryBuilder> exportees = new Set<LibraryBuilder>();
     for (LibraryBuilder library in builders.values) {
       if (library.loader == this) {
-        SourceLibraryBuilder sourceLibrary = library;
+        SourceLibraryBuilder sourceLibrary = library as SourceLibraryBuilder;
         sourceLibrary.buildInitialScopes();
       }
       if (library.exporters.isNotEmpty) {
@@ -605,7 +617,7 @@
     Set<SourceLibraryBuilder> both = new Set<SourceLibraryBuilder>();
     for (LibraryBuilder exported in exportees) {
       if (exporters.contains(exported)) {
-        both.add(exported);
+        both.add(exported as SourceLibraryBuilder);
       }
       for (Export export in exported.exporters) {
         exported.exportScope.forEach(export.addToExportScope);
@@ -626,7 +638,7 @@
     } while (wasChanged);
     for (LibraryBuilder library in builders.values) {
       if (library.loader == this) {
-        SourceLibraryBuilder sourceLibrary = library;
+        SourceLibraryBuilder sourceLibrary = library as SourceLibraryBuilder;
         sourceLibrary.addImportsToScope();
       }
     }
@@ -651,7 +663,7 @@
         members.add(iterator.current);
       }
       List<String> exports = <String>[];
-      library.exportScope.forEach((String name, Builder member) {
+      library.exportScope.forEach((String name, Builder? member) {
         while (member != null) {
           if (!members.contains(member)) {
             exports.add(name);
@@ -669,7 +681,7 @@
     int typeCount = 0;
     for (LibraryBuilder library in builders.values) {
       if (library.loader == this) {
-        SourceLibraryBuilder sourceLibrary = library;
+        SourceLibraryBuilder sourceLibrary = library as SourceLibraryBuilder;
         typeCount += sourceLibrary.resolveTypes();
       }
     }
@@ -803,15 +815,16 @@
 
     Set<ClassBuilder> denyListedClasses = new Set<ClassBuilder>();
     for (int i = 0; i < denylistedCoreClasses.length; i++) {
-      denyListedClasses.add(coreLibrary
-          .lookupLocalMember(denylistedCoreClasses[i], required: true));
+      denyListedClasses.add(coreLibrary.lookupLocalMember(
+          denylistedCoreClasses[i],
+          required: true) as ClassBuilder);
     }
     if (typedDataLibrary != null) {
       for (int i = 0; i < denylistedTypedDataClasses.length; i++) {
         // Allow the member to not exist. If it doesn't, nobody can extend it.
-        Builder member = typedDataLibrary
+        Builder? member = typedDataLibrary!
             .lookupLocalMember(denylistedTypedDataClasses[i], required: false);
-        if (member != null) denyListedClasses.add(member);
+        if (member != null) denyListedClasses.add(member as ClassBuilder);
       }
     }
 
@@ -824,13 +837,13 @@
       workList = <SourceClassBuilder>[];
       for (int i = 0; i < previousWorkList.length; i++) {
         SourceClassBuilder cls = previousWorkList[i];
-        Map<TypeDeclarationBuilder, TypeAliasBuilder> directSupertypeMap =
+        Map<TypeDeclarationBuilder?, TypeAliasBuilder?> directSupertypeMap =
             cls.computeDirectSupertypes(objectClass);
-        List<TypeDeclarationBuilder> directSupertypes =
+        List<TypeDeclarationBuilder?> directSupertypes =
             directSupertypeMap.keys.toList();
         bool allSupertypesProcessed = true;
         for (int i = 0; i < directSupertypes.length; i++) {
-          Builder supertype = directSupertypes[i];
+          Builder? supertype = directSupertypes[i];
           if (supertype is SourceClassBuilder &&
               supertype.library.loader == this &&
               !topologicallySortedClasses.contains(supertype)) {
@@ -885,7 +898,7 @@
               templateIllegalMixinDueToConstructorsCause
                   .withArguments(builder.fullNameForErrors)
                   .withLocation(
-                      constructor.fileUri, constructor.charOffset, noLength)
+                      constructor.fileUri!, constructor.charOffset, noLength)
             ]);
       }
     }
@@ -893,23 +906,23 @@
 
   void checkClassSupertypes(
       SourceClassBuilder cls,
-      Map<TypeDeclarationBuilder, TypeAliasBuilder> directSupertypeMap,
+      Map<TypeDeclarationBuilder?, TypeAliasBuilder?> directSupertypeMap,
       Set<ClassBuilder> denyListedClasses) {
     // Check that the direct supertypes aren't deny-listed or enums.
-    List<TypeDeclarationBuilder> directSupertypes =
+    List<TypeDeclarationBuilder?> directSupertypes =
         directSupertypeMap.keys.toList();
     for (int i = 0; i < directSupertypes.length; i++) {
-      TypeDeclarationBuilder supertype = directSupertypes[i];
+      TypeDeclarationBuilder? supertype = directSupertypes[i];
       if (supertype is EnumBuilder) {
         cls.addProblem(templateExtendingEnum.withArguments(supertype.name),
             cls.charOffset, noLength);
       } else if (!cls.library.mayImplementRestrictedTypes &&
           denyListedClasses.contains(supertype)) {
-        TypeAliasBuilder aliasBuilder = directSupertypeMap[supertype];
+        TypeAliasBuilder? aliasBuilder = directSupertypeMap[supertype];
         if (aliasBuilder != null) {
           cls.addProblem(
               templateExtendingRestricted
-                  .withArguments(supertype.fullNameForErrors),
+                  .withArguments(supertype!.fullNameForErrors),
               cls.charOffset,
               noLength,
               context: [
@@ -919,7 +932,7 @@
         } else {
           cls.addProblem(
               templateExtendingRestricted
-                  .withArguments(supertype.fullNameForErrors),
+                  .withArguments(supertype!.fullNameForErrors),
               cls.charOffset,
               noLength);
         }
@@ -927,11 +940,11 @@
     }
 
     // Check that the mixed-in type can be used as a mixin.
-    final TypeBuilder mixedInTypeBuilder = cls.mixedInTypeBuilder;
+    final TypeBuilder? mixedInTypeBuilder = cls.mixedInTypeBuilder;
     if (mixedInTypeBuilder != null) {
       bool isClassBuilder = false;
       if (mixedInTypeBuilder is NamedTypeBuilder) {
-        TypeDeclarationBuilder builder = mixedInTypeBuilder.declaration;
+        TypeDeclarationBuilder? builder = mixedInTypeBuilder.declaration;
         if (builder is TypeAliasBuilder) {
           TypeAliasBuilder aliasBuilder = builder;
           NamedTypeBuilder namedBuilder = mixedInTypeBuilder;
@@ -941,7 +954,7 @@
               usedAsClassFileUri: namedBuilder.fileUri);
           if (builder is! ClassBuilder) {
             cls.addProblem(
-                templateIllegalMixin.withArguments(builder.fullNameForErrors),
+                templateIllegalMixin.withArguments(builder!.fullNameForErrors),
                 cls.charOffset,
                 noLength,
                 context: [
@@ -989,13 +1002,13 @@
   void buildComponent() {
     for (LibraryBuilder library in builders.values) {
       if (library.loader == this) {
-        SourceLibraryBuilder sourceLibrary = library;
+        SourceLibraryBuilder sourceLibrary = library as SourceLibraryBuilder;
         Library target = sourceLibrary.build(coreLibrary);
         if (!library.isPatch) {
           if (sourceLibrary.referencesFrom != null) {
             referenceFromIndex ??= new ReferenceFromIndex();
-            referenceFromIndex.addIndexedLibrary(
-                target, sourceLibrary.referencesFromIndexed);
+            referenceFromIndex!.addIndexedLibrary(
+                target, sourceLibrary.referencesFromIndexed!);
           }
           libraries.add(target);
         }
@@ -1029,14 +1042,14 @@
   }
 
   void computeHierarchy() {
-    List<AmbiguousTypesRecord> ambiguousTypesRecords = [];
+    List<AmbiguousTypesRecord>? ambiguousTypesRecords = [];
     HandleAmbiguousSupertypes onAmbiguousSupertypes =
         (Class cls, Supertype a, Supertype b) {
       if (ambiguousTypesRecords != null) {
         ambiguousTypesRecords.add(new AmbiguousTypesRecord(cls, a, b));
       }
     };
-    if (hierarchy == null) {
+    if (_hierarchy == null) {
       hierarchy = new ClassHierarchy(computeFullComponent(), coreTypes,
           onAmbiguousSupertypes: onAmbiguousSupertypes);
     } else {
@@ -1072,11 +1085,11 @@
     // to check if the return types of functions with async, sync*, and async*
     // bodies are correct.  It's valid to use the non-nullable types on the
     // left-hand side in both opt-in and opt-out code.
-    futureOfBottom = new InterfaceType(coreTypes.futureClass,
+    _futureOfBottom = new InterfaceType(coreTypes.futureClass,
         Nullability.nonNullable, <DartType>[const NeverType.nonNullable()]);
-    iterableOfBottom = new InterfaceType(coreTypes.iterableClass,
+    _iterableOfBottom = new InterfaceType(coreTypes.iterableClass,
         Nullability.nonNullable, <DartType>[const NeverType.nonNullable()]);
-    streamOfBottom = new InterfaceType(coreTypes.streamClass,
+    _streamOfBottom = new InterfaceType(coreTypes.streamClass,
         Nullability.nonNullable, <DartType>[const NeverType.nonNullable()]);
 
     ticker.logMs("Computed core types");
@@ -1110,7 +1123,7 @@
     }
     ticker.logMs("Checked ${overrideChecks.length} overrides");
 
-    typeInferenceEngine?.finishTopLevelInitializingFormals();
+    typeInferenceEngine.finishTopLevelInitializingFormals();
     ticker.logMs("Finished initializing formals");
   }
 
@@ -1160,7 +1173,7 @@
   void checkMixins(List<SourceClassBuilder> sourceClasses) {
     for (SourceClassBuilder builder in sourceClasses) {
       if (builder.library.loader == this && !builder.isPatch) {
-        Class mixedInClass = builder.cls.mixedInClass;
+        Class? mixedInClass = builder.cls.mixedInClass;
         if (mixedInClass != null && mixedInClass.isMixinDeclaration) {
           builder.checkMixinApplication(hierarchy, coreTypes);
         }
@@ -1174,7 +1187,7 @@
         <DelayedActionPerformer>[];
     for (LibraryBuilder library in builders.values) {
       if (library.loader == this) {
-        library.buildOutlineExpressions();
+        (library as SourceLibraryBuilder).buildOutlineExpressions();
         Iterator<Builder> iterator = library.iterator;
         while (iterator.moveNext()) {
           Builder declaration = iterator.current;
@@ -1210,14 +1223,14 @@
 
   void buildClassHierarchy(
       List<SourceClassBuilder> sourceClasses, ClassBuilder objectClass) {
-    builderHierarchy = ClassHierarchyBuilder.build(
+    _builderHierarchy = ClassHierarchyBuilder.build(
         objectClass, sourceClasses, this, coreTypes);
-    typeInferenceEngine?.hierarchyBuilder = builderHierarchy;
+    typeInferenceEngine.hierarchyBuilder = builderHierarchy;
     ticker.logMs("Built class hierarchy");
   }
 
   void createTypeInferenceEngine() {
-    typeInferenceEngine = new TypeInferenceEngineImpl(instrumentation);
+    _typeInferenceEngine = new TypeInferenceEngineImpl(instrumentation);
   }
 
   void performTopLevelInference(List<SourceClassBuilder> sourceClasses) {
@@ -1231,7 +1244,7 @@
     List<FieldBuilder> allImplicitlyTypedFields = <FieldBuilder>[];
     for (LibraryBuilder library in builders.values) {
       if (library.loader == this) {
-        List<FieldBuilder> implicitlyTypedFields =
+        List<FieldBuilder>? implicitlyTypedFields =
             library.takeImplicitlyTypedFields();
         if (implicitlyTypedFields != null) {
           allImplicitlyTypedFields.addAll(implicitlyTypedFields);
@@ -1259,15 +1272,15 @@
       bool transformCollections, Library clientLibrary) {
     if (transformCollections) {
       collectionTransformer ??= new CollectionTransformer(this);
-      collectionTransformer.enterLibrary(clientLibrary);
-      node.accept(collectionTransformer);
-      collectionTransformer.exitLibrary();
+      collectionTransformer!.enterLibrary(clientLibrary);
+      node.accept(collectionTransformer!);
+      collectionTransformer!.exitLibrary();
     }
     if (transformSetLiterals) {
       setLiteralTransformer ??= new SetLiteralTransformer(this);
-      setLiteralTransformer.enterLibrary(clientLibrary);
-      node.accept(setLiteralTransformer);
-      setLiteralTransformer.exitLibrary();
+      setLiteralTransformer!.enterLibrary(clientLibrary);
+      node.accept(setLiteralTransformer!);
+      setLiteralTransformer!.exitLibrary();
     }
   }
 
@@ -1323,12 +1336,12 @@
   }
 
   void checkMainMethods() {
-    DartType listOfString;
+    DartType? listOfString;
 
     for (LibraryBuilder libraryBuilder in builders.values) {
       if (libraryBuilder.loader == this &&
           libraryBuilder.isNonNullableByDefault) {
-        Builder mainBuilder =
+        Builder? mainBuilder =
             libraryBuilder.exportScope.lookupLocalMember('main', setter: false);
         mainBuilder ??=
             libraryBuilder.exportScope.lookupLocalMember('main', setter: true);
@@ -1347,7 +1360,7 @@
                   noLength,
                   libraryBuilder.fileUri,
                   context: [
-                    messageExportedMain.withLocation(mainBuilder.fileUri,
+                    messageExportedMain.withLocation(mainBuilder.fileUri!,
                         mainBuilder.charOffset, mainBuilder.name.length)
                   ]);
             } else {
@@ -1358,7 +1371,7 @@
                   mainBuilder.fileUri);
             }
           } else {
-            Procedure procedure = mainBuilder.member;
+            Procedure procedure = mainBuilder.member as Procedure;
             if (procedure.function.requiredParameterCount > 2) {
               if (mainBuilder.parent != libraryBuilder) {
                 libraryBuilder.addProblem(
@@ -1367,7 +1380,7 @@
                     noLength,
                     libraryBuilder.fileUri,
                     context: [
-                      messageExportedMain.withLocation(mainBuilder.fileUri,
+                      messageExportedMain.withLocation(mainBuilder.fileUri!,
                           mainBuilder.charOffset, mainBuilder.name.length)
                     ]);
               } else {
@@ -1386,7 +1399,7 @@
                     noLength,
                     libraryBuilder.fileUri,
                     context: [
-                      messageExportedMain.withLocation(mainBuilder.fileUri,
+                      messageExportedMain.withLocation(mainBuilder.fileUri!,
                           mainBuilder.charOffset, mainBuilder.name.length)
                     ]);
               } else {
@@ -1417,7 +1430,7 @@
                       noLength,
                       libraryBuilder.fileUri,
                       context: [
-                        messageExportedMain.withLocation(mainBuilder.fileUri,
+                        messageExportedMain.withLocation(mainBuilder.fileUri!,
                             mainBuilder.charOffset, mainBuilder.name.length)
                       ]);
                 } else {
@@ -1439,7 +1452,7 @@
                 libraryBuilder.charOffset, noLength, libraryBuilder.fileUri,
                 context: [
                   messageExportedMain.withLocation(
-                      mainBuilder.fileUri, mainBuilder.charOffset, noLength)
+                      mainBuilder.fileUri!, mainBuilder.charOffset, noLength)
                 ]);
           } else {
             libraryBuilder.addProblem(messageMainNotFunctionDeclaration,
@@ -1452,13 +1465,13 @@
 
   void releaseAncillaryResources() {
     hierarchy = null;
-    builderHierarchy = null;
-    typeInferenceEngine = null;
-    builders?.clear();
-    libraries?.clear();
+    _builderHierarchy = null;
+    _typeInferenceEngine = null;
+    builders.clear();
+    libraries.clear();
     first = null;
-    sourceBytes?.clear();
-    target?.releaseAncillaryResources();
+    sourceBytes.clear();
+    target.releaseAncillaryResources();
     _coreTypes = null;
     instrumentation = null;
     collectionTransformer = null;
@@ -1468,11 +1481,11 @@
   @override
   ClassBuilder computeClassBuilderFromTargetClass(Class cls) {
     Library kernelLibrary = cls.enclosingLibrary;
-    LibraryBuilder library = builders[kernelLibrary.importUri];
+    LibraryBuilder? library = builders[kernelLibrary.importUri];
     if (library == null) {
       return target.dillTarget.loader.computeClassBuilderFromTargetClass(cls);
     }
-    return library.lookupLocalMember(cls.name, required: true);
+    return library.lookupLocalMember(cls.name, required: true) as ClassBuilder;
   }
 
   @override
@@ -1586,9 +1599,10 @@
 class Symbol {}
 
 class Set<E> {
-  factory Set() = Set<E>._fake;
-  external factory Set._fake();
-  external factory Set.of();
+  factory Set() = Set<E>._;
+  external factory Set._();
+  factory Set.of(o) = Set<E>._of;
+  external factory Set._of(o);
   bool add(E element) {}
   void addAll(Iterable<E> iterable) {}
 }
diff --git a/pkg/front_end/lib/src/fasta/source/source_type_alias_builder.dart b/pkg/front_end/lib/src/fasta/source/source_type_alias_builder.dart
index 615343c..ae4fbb9 100644
--- a/pkg/front_end/lib/src/fasta/source/source_type_alias_builder.dart
+++ b/pkg/front_end/lib/src/fasta/source/source_type_alias_builder.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.source_type_alias_builder;
 
 import 'package:kernel/ast.dart'
@@ -12,6 +10,7 @@
         DynamicType,
         InvalidType,
         TypeParameter,
+        TypeParameterType,
         Typedef,
         TypedefType,
         VariableDeclaration,
@@ -46,18 +45,24 @@
 import 'source_library_builder.dart' show SourceLibraryBuilder;
 
 class SourceTypeAliasBuilder extends TypeAliasBuilderImpl {
-  final TypeBuilder type;
+  final TypeBuilder? type;
 
-  final List<TypeVariableBuilder> _typeVariables;
+  final List<TypeVariableBuilder>? _typeVariables;
 
   /// The [Typedef] built by this builder.
   final Typedef typedef;
 
-  DartType thisType;
+  DartType? thisType;
 
-  SourceTypeAliasBuilder(List<MetadataBuilder> metadata, String name,
-      this._typeVariables, this.type, LibraryBuilder parent, int charOffset,
-      {Typedef typedef, Typedef referenceFrom})
+  SourceTypeAliasBuilder(
+      List<MetadataBuilder>? metadata,
+      String name,
+      this._typeVariables,
+      this.type,
+      SourceLibraryBuilder parent,
+      int charOffset,
+      {Typedef? typedef,
+      Typedef? referenceFrom})
       : typedef = typedef ??
             (new Typedef(name, null,
                 typeParameters: TypeVariableBuilder.typeParametersFromBuilders(
@@ -68,13 +73,13 @@
         super(metadata, name, parent, charOffset);
 
   @override
-  SourceLibraryBuilder get library => super.library;
+  SourceLibraryBuilder get library => super.library as SourceLibraryBuilder;
 
   @override
-  List<TypeVariableBuilder> get typeVariables => _typeVariables;
+  List<TypeVariableBuilder>? get typeVariables => _typeVariables;
 
   @override
-  int varianceAt(int index) => typeVariables[index].parameter.variance;
+  int varianceAt(int index) => typeVariables![index].parameter.variance;
 
   @override
   bool get fromDill => false;
@@ -84,7 +89,7 @@
 
   @override
   bool get isNullAlias {
-    TypeDeclarationBuilder typeDeclarationBuilder = type.declaration;
+    TypeDeclarationBuilder? typeDeclarationBuilder = type?.declaration;
     return typeDeclarationBuilder is ClassBuilder &&
         typeDeclarationBuilder.isNullClass;
   }
@@ -92,14 +97,12 @@
   Typedef build(SourceLibraryBuilder libraryBuilder) {
     typedef.type ??= buildThisType();
 
-    TypeBuilder type = this.type;
+    TypeBuilder? type = this.type;
     if (type is FunctionTypeBuilder) {
-      List<TypeParameter> typeParameters =
-          new List<TypeParameter>.filled(type.typeVariables?.length ?? 0, null);
-      for (int i = 0; i < typeParameters.length; ++i) {
-        TypeVariableBuilder typeVariable = type.typeVariables[i];
-        typeParameters[i] = typeVariable.parameter;
-      }
+      List<TypeParameter> typeParameters = new List<TypeParameter>.generate(
+          type.typeVariables?.length ?? 0,
+          (int i) => type.typeVariables![i].parameter,
+          growable: false);
       FreshTypeParameters freshTypeParameters =
           getFreshTypeParameters(typeParameters);
       for (int i = 0; i < freshTypeParameters.freshTypeParameters.length; i++) {
@@ -110,7 +113,7 @@
       }
 
       if (type.formals != null) {
-        for (FormalParameterBuilder formal in type.formals) {
+        for (FormalParameterBuilder formal in type.formals!) {
           VariableDeclaration parameter = formal.build(libraryBuilder, 0);
           parameter.type = freshTypeParameters.substitute(parameter.type);
           if (formal.isNamed) {
@@ -123,6 +126,7 @@
       }
     } else if (type is NamedTypeBuilder || type is FixedTypeBuilder) {
       // No error, but also no additional setup work.
+      // ignore: unnecessary_null_comparison
     } else if (type != null) {
       unhandled("${type.fullNameForErrors}", "build", charOffset, fileUri);
     }
@@ -140,19 +144,21 @@
       } else if (identical(thisType, cyclicTypeAliasMarker)) {
         return const InvalidType();
       }
-      return thisType;
+      return thisType!;
     }
     // It is a compile-time error for an alias (typedef) to refer to itself. We
     // detect cycles by detecting recursive calls to this method using an
     // instance of InvalidType that isn't identical to `const InvalidType()`.
     thisType = pendingTypeAliasMarker;
-    TypeBuilder type = this.type;
+    TypeBuilder? type = this.type;
+    // ignore: unnecessary_null_comparison
     if (type != null) {
       DartType builtType =
-          type.build(library, thisTypedefType(typedef, library));
+          type.build(library, origin: thisTypedefType(typedef, library));
+      // ignore: unnecessary_null_comparison
       if (builtType != null) {
         if (typeVariables != null) {
-          for (TypeVariableBuilder tv in typeVariables) {
+          for (TypeVariableBuilder tv in typeVariables!) {
             // Follow bound in order to find all cycles
             tv.bound?.build(library);
           }
@@ -176,13 +182,14 @@
     // for the bound of all boundless variables and add them to the list for
     // being recomputed later, when the bounds are assigned.
     List<DartType> bounds =
-        new List<DartType>.filled(typedef.typeParameters.length, null);
-    for (int i = 0; i < bounds.length; ++i) {
-      bounds[i] = typedef.typeParameters[i].bound;
-      if (identical(bounds[i], TypeParameter.unsetBoundSentinel)) {
+        new List<DartType>.generate(typedef.typeParameters.length, (int i) {
+      DartType bound = typedef.typeParameters[i].bound;
+      if (identical(bound, TypeParameter.unsetBoundSentinel)) {
         typedef.typeParameters[i].bound = const DynamicType();
       }
-    }
+      return bound;
+    }, growable: false);
+    for (int i = 0; i < bounds.length; ++i) {}
     List<DartType> asTypeArguments =
         getAsTypeArguments(typedef.typeParameters, clientLibrary.library);
     TypedefType result =
@@ -194,9 +201,10 @@
         // At this point, [parent] should be a [SourceLibraryBuilder] because
         // otherwise it's a compiled library loaded from a dill file, and the
         // bounds should have been assigned.
-        SourceLibraryBuilder parentLibrary = parent;
-        parentLibrary.registerPendingNullability(_typeVariables[i].fileUri,
-            _typeVariables[i].charOffset, asTypeArguments[i]);
+        library.registerPendingNullability(
+            _typeVariables![i].fileUri!,
+            _typeVariables![i].charOffset,
+            asTypeArguments[i] as TypeParameterType);
       }
     }
     return result;
@@ -204,18 +212,16 @@
 
   @override
   List<DartType> buildTypeArguments(
-      LibraryBuilder library, List<TypeBuilder> arguments,
-      [bool notInstanceContext]) {
+      LibraryBuilder library, List<TypeBuilder>? arguments,
+      {bool? nonInstanceContext}) {
     if (arguments == null && typeVariables == null) {
       return <DartType>[];
     }
 
     if (arguments == null && typeVariables != null) {
-      List<DartType> result =
-          new List<DartType>.filled(typeVariables.length, null, growable: true);
-      for (int i = 0; i < result.length; ++i) {
-        result[i] = typeVariables[i].defaultType.build(library);
-      }
+      List<DartType> result = new List<DartType>.generate(typeVariables!.length,
+          (int i) => typeVariables![i].defaultType!.build(library),
+          growable: true);
       if (library is SourceLibraryBuilder) {
         library.inferredTypes.addAll(result);
       }
@@ -234,30 +240,29 @@
     }
 
     // arguments.length == typeVariables.length
-    List<DartType> result =
-        new List<DartType>.filled(arguments.length, null, growable: true);
-    for (int i = 0; i < result.length; ++i) {
-      result[i] = arguments[i].build(library);
-    }
-    return result;
+    return new List<DartType>.generate(
+        arguments!.length, (int i) => arguments[i].build(library),
+        growable: true);
   }
 
   void checkTypesInOutline(TypeEnvironment typeEnvironment) {
     library.checkBoundsInTypeParameters(
         typeEnvironment, typedef.typeParameters, fileUri);
     library.checkBoundsInType(
-        typedef.type, typeEnvironment, fileUri, type?.charOffset ?? charOffset,
+        typedef.type!, typeEnvironment, fileUri, type?.charOffset ?? charOffset,
         allowSuperBounded: false);
   }
 
   @override
-  void buildOutlineExpressions(LibraryBuilder library, CoreTypes coreTypes,
+  void buildOutlineExpressions(
+      SourceLibraryBuilder library,
+      CoreTypes coreTypes,
       List<DelayedActionPerformer> delayedActionPerformers) {
     MetadataBuilder.buildAnnotations(
         typedef, metadata, library, null, null, fileUri);
     if (typeVariables != null) {
-      for (int i = 0; i < typeVariables.length; i++) {
-        typeVariables[i].buildOutlineExpressions(
+      for (int i = 0; i < typeVariables!.length; i++) {
+        typeVariables![i].buildOutlineExpressions(
             library, null, null, coreTypes, delayedActionPerformers);
       }
     }
diff --git a/pkg/front_end/lib/src/fasta/source/stack_listener_impl.dart b/pkg/front_end/lib/src/fasta/source/stack_listener_impl.dart
index 12c8559..0544f97 100644
--- a/pkg/front_end/lib/src/fasta/source/stack_listener_impl.dart
+++ b/pkg/front_end/lib/src/fasta/source/stack_listener_impl.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.stack_listener_impl;
 
 import 'package:_fe_analyzer_shared/src/parser/parser.dart' show Parser;
@@ -11,10 +9,11 @@
 import 'package:_fe_analyzer_shared/src/parser/stack_listener.dart';
 
 import 'package:_fe_analyzer_shared/src/scanner/scanner.dart' show Token;
-import 'package:front_end/src/api_prototype/experimental_flags.dart';
 
 import 'package:kernel/ast.dart';
 
+import '../../api_prototype/experimental_flags.dart';
+
 import '../fasta_codes.dart';
 
 import '../problems.dart' as problems
@@ -25,7 +24,7 @@
 abstract class StackListenerImpl extends StackListener {
   SourceLibraryBuilder get libraryBuilder;
 
-  AsyncMarker asyncMarkerFromTokens(Token asyncToken, Token starToken) {
+  AsyncMarker asyncMarkerFromTokens(Token? asyncToken, Token? starToken) {
     if (asyncToken == null || identical(asyncToken.stringValue, "sync")) {
       if (starToken == null) {
         return AsyncMarker.Sync;
@@ -50,7 +49,7 @@
   // and ast_builder.dart.
   void finishFunction(
       covariant formals, AsyncMarker asyncModifier, covariant body) {
-    return problems.unsupported("finishFunction", -1, uri);
+    problems.unsupported("finishFunction", -1, uri);
   }
 
   // TODO(ahe): This doesn't belong here. Only implemented by body_builder.dart
@@ -61,7 +60,7 @@
 
   // TODO(ahe): This doesn't belong here. Only implemented by body_builder.dart
   // and ast_builder.dart.
-  List<Expression> finishMetadata(Annotatable parent) {
+  List<Expression> finishMetadata(Annotatable? parent) {
     return problems.unsupported("finishMetadata", -1, uri);
   }
 
@@ -82,12 +81,13 @@
 
   /// Used to report an unexpected situation encountered in the stack
   /// listener.
-  dynamic unhandled(String what, String where, int charOffset, Uri uri) {
+  Never unhandled(String what, String where, int charOffset, Uri? uri) {
     return problems.unhandled(what, where, charOffset, uri);
   }
 
   void reportMissingNonNullableSupport(Token token) {
     assert(!libraryBuilder.isNonNullableByDefault);
+    // ignore: unnecessary_null_comparison
     assert(token != null);
     if (libraryBuilder.enableNonNullableInLibrary) {
       if (libraryBuilder.languageVersion.isExplicit) {
@@ -98,7 +98,7 @@
             token.charCount,
             context: <LocatedMessage>[
               messageNonNullableOptOutComment.withLocation(
-                  libraryBuilder.languageVersion.fileUri,
+                  libraryBuilder.languageVersion.fileUri!,
                   libraryBuilder.languageVersion.charOffset,
                   libraryBuilder.languageVersion.charCount)
             ]);
@@ -144,13 +144,13 @@
     }
   }
 
-  void reportErrorIfNullableType(Token questionMark) {
+  void reportErrorIfNullableType(Token? questionMark) {
     if (questionMark != null) {
       reportMissingNonNullableSupport(questionMark);
     }
   }
 
-  void reportNonNullableModifierError(Token modifierToken) {
+  void reportNonNullableModifierError(Token? modifierToken) {
     assert(!libraryBuilder.isNonNullableByDefault);
     if (modifierToken != null) {
       reportMissingNonNullableSupport(modifierToken);
@@ -164,6 +164,6 @@
 
 /// A null-aware alternative to `token.offset`.  If [token] is `null`, returns
 /// `TreeNode.noOffset`.
-int offsetForToken(Token token) {
+int offsetForToken(Token? token) {
   return token == null ? TreeNode.noOffset : token.offset;
 }
diff --git a/pkg/front_end/lib/src/fasta/source/value_kinds.dart b/pkg/front_end/lib/src/fasta/source/value_kinds.dart
index 03261c1..047d3c6 100644
--- a/pkg/front_end/lib/src/fasta/source/value_kinds.dart
+++ b/pkg/front_end/lib/src/fasta/source/value_kinds.dart
@@ -2,8 +2,6 @@
 // for 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 'package:_fe_analyzer_shared/src/parser/stack_listener.dart'
     show NullValue;
 
diff --git a/pkg/front_end/lib/src/fasta/target.dart b/pkg/front_end/lib/src/fasta/target.dart
index 8d2efd9..4c9944a 100644
--- a/pkg/front_end/lib/src/fasta/target.dart
+++ b/pkg/front_end/lib/src/fasta/target.dart
@@ -19,8 +19,8 @@
   Target(this.ticker);
 
   /// Build and return outlines for all libraries.
-  Future<Component> buildOutlines();
+  Future<Component?> buildOutlines();
 
   /// Build and return the full component for all libraries.
-  Future<Component> buildComponent();
+  Future<Component?> buildComponent();
 }
diff --git a/pkg/front_end/lib/src/fasta/target_implementation.dart b/pkg/front_end/lib/src/fasta/target_implementation.dart
index 2b29da2..d179dbd 100644
--- a/pkg/front_end/lib/src/fasta/target_implementation.dart
+++ b/pkg/front_end/lib/src/fasta/target_implementation.dart
@@ -2,8 +2,6 @@
 // for 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
-
 library fasta.target_implementation;
 
 import 'package:_fe_analyzer_shared/src/messages/severity.dart' show Severity;
@@ -44,16 +42,19 @@
   /// Shared with [CompilerContext].
   final Map<Uri, Source> uriToSource = CompilerContext.current.uriToSource;
 
-  MemberBuilder cachedAbstractClassInstantiationError;
-  MemberBuilder cachedCompileTimeError;
-  MemberBuilder cachedDuplicatedFieldInitializerError;
-  MemberBuilder cachedNativeAnnotation;
+  MemberBuilder? cachedAbstractClassInstantiationError;
+  MemberBuilder? cachedCompileTimeError;
+  MemberBuilder? cachedDuplicatedFieldInitializerError;
+  MemberBuilder? cachedNativeAnnotation;
 
   final ProcessedOptions _options;
 
   TargetImplementation(Ticker ticker, this.uriTranslator, this.backendTarget)
+      // ignore: unnecessary_null_comparison
       : assert(ticker != null),
+        // ignore: unnecessary_null_comparison
         assert(uriTranslator != null),
+        // ignore: unnecessary_null_comparison
         assert(backendTarget != null),
         _options = CompilerContext.current.options,
         super(ticker);
@@ -111,31 +112,28 @@
   /// [packageLanguageVersion] is the language version defined by the package
   /// which the library belongs to, or the current sdk version if the library
   /// doesn't belong to a package.
-  LibraryBuilder createLibraryBuilder(
+  LibraryBuilder? createLibraryBuilder(
       Uri uri,
       Uri fileUri,
-      Uri packageUri,
+      Uri? packageUri,
       LanguageVersion packageLanguageVersion,
-      covariant LibraryBuilder origin,
-      Library referencesFrom,
-      bool referenceIsPartOwner);
+      covariant LibraryBuilder? origin,
+      Library? referencesFrom,
+      bool? referenceIsPartOwner);
 
   /// The class [cls] is involved in a cyclic definition. This method should
   /// ensure that the cycle is broken, for example, by removing superclass and
   /// implemented interfaces.
   void breakCycle(ClassBuilder cls);
 
-  Uri translateUri(Uri uri) => uriTranslator.translate(uri);
+  Uri? translateUri(Uri uri) => uriTranslator.translate(uri);
 
   /// Returns a reference to the constructor of
   /// [AbstractClassInstantiationError] error.  The constructor is expected to
   /// accept a single argument of type String, which is the name of the
   /// abstract class.
   MemberBuilder getAbstractClassInstantiationError(Loader loader) {
-    if (cachedAbstractClassInstantiationError != null) {
-      return cachedAbstractClassInstantiationError;
-    }
-    return cachedAbstractClassInstantiationError =
+    return cachedAbstractClassInstantiationError ??=
         loader.coreLibrary.getConstructor("AbstractClassInstantiationError");
   }
 
@@ -143,8 +141,7 @@
   /// error. The constructor is expected to accept a single argument of type
   /// String, which is the compile-time error message.
   MemberBuilder getCompileTimeError(Loader loader) {
-    if (cachedCompileTimeError != null) return cachedCompileTimeError;
-    return cachedCompileTimeError = loader.coreLibrary
+    return cachedCompileTimeError ??= loader.coreLibrary
         .getConstructor("_CompileTimeError", bypassLibraryPrivacy: true);
   }
 
@@ -152,10 +149,7 @@
   /// when a final field is initialized twice. The constructor is expected to
   /// accept a single argument which is the name of the field.
   MemberBuilder getDuplicatedFieldInitializerError(Loader loader) {
-    if (cachedDuplicatedFieldInitializerError != null) {
-      return cachedDuplicatedFieldInitializerError;
-    }
-    return cachedDuplicatedFieldInitializerError = loader.coreLibrary
+    return cachedDuplicatedFieldInitializerError ??= loader.coreLibrary
         .getConstructor("_DuplicatedFieldInitializerError",
             bypassLibraryPrivacy: true);
   }
@@ -164,7 +158,7 @@
   /// annotations. The constructor is expected to accept a single argument of
   /// type String, which is the name of the native method.
   MemberBuilder getNativeAnnotation(Loader loader) {
-    if (cachedNativeAnnotation != null) return cachedNativeAnnotation;
+    if (cachedNativeAnnotation != null) return cachedNativeAnnotation!;
     LibraryBuilder internal = loader.read(Uri.parse("dart:_internal"), -1,
         accessor: loader.coreLibrary);
     return cachedNativeAnnotation = internal.getConstructor("ExternalName");
@@ -190,13 +184,15 @@
       Message message,
       int charOffset,
       int length,
-      Uri fileUri,
-      List<LocatedMessage> messageContext,
+      Uri? fileUri,
+      List<LocatedMessage>? messageContext,
       Severity severity,
-      {List<Uri> involvedFiles}) {
+      {List<Uri>? involvedFiles}) {
     ProcessedOptions processedOptions = context.options;
     return processedOptions.format(
-        message.withLocation(fileUri, charOffset, length),
+        fileUri != null
+            ? message.withLocation(fileUri, charOffset, length)
+            : message.withoutLocation(),
         severity,
         messageContext,
         involvedFiles: involvedFiles);
@@ -206,20 +202,22 @@
     return CompilerContext.current.options.currentSdkVersion;
   }
 
-  Version _currentSdkVersion;
+  Version? _currentSdkVersion;
   Version get currentSdkVersion {
-    if (_currentSdkVersion != null) return _currentSdkVersion;
-    _parseCurrentSdkVersion();
-    return _currentSdkVersion;
+    if (_currentSdkVersion == null) {
+      _parseCurrentSdkVersion();
+    }
+    return _currentSdkVersion!;
   }
 
   void _parseCurrentSdkVersion() {
     bool good = false;
+    // ignore: unnecessary_null_comparison
     if (currentSdkVersionString != null) {
       List<String> dotSeparatedParts = currentSdkVersionString.split(".");
       if (dotSeparatedParts.length >= 2) {
-        _currentSdkVersion = new Version(int.tryParse(dotSeparatedParts[0]),
-            int.tryParse(dotSeparatedParts[1]));
+        _currentSdkVersion = new Version(int.tryParse(dotSeparatedParts[0])!,
+            int.tryParse(dotSeparatedParts[1])!);
         good = true;
       }
     }
diff --git a/pkg/front_end/lib/src/fasta/type_inference/closure_context.dart b/pkg/front_end/lib/src/fasta/type_inference/closure_context.dart
index 0bad19f..48929d9 100644
--- a/pkg/front_end/lib/src/fasta/type_inference/closure_context.dart
+++ b/pkg/front_end/lib/src/fasta/type_inference/closure_context.dart
@@ -2,8 +2,6 @@
 // for details. All rights reserved. Use of this source code is governed by a
 // BSD-style license that can be found in the LICENSE.md file.
 
-// @dart = 2.9
-
 part of 'type_inferrer.dart';
 
 /// Keeps track of information about the innermost function or closure being
@@ -33,10 +31,11 @@
   /// the unknown type.
   DartType get yieldContext;
 
-  DartType get futureValueType;
+  DartType? get futureValueType;
 
   factory ClosureContext(TypeInferrerImpl inferrer, AsyncMarker asyncMarker,
       DartType returnContext, bool needToInferReturnType) {
+    // ignore: unnecessary_null_comparison
     assert(returnContext != null);
     DartType declaredReturnType =
         inferrer.computeGreatestClosure(returnContext);
@@ -57,7 +56,7 @@
             yieldContext, declaredReturnType, needToInferReturnType);
       }
     } else if (isAsync) {
-      DartType futureValueType;
+      DartType? futureValueType;
       if (inferrer.isNonNullableByDefault) {
         returnContext = inferrer.wrapFutureOrType(
             inferrer.computeFutureValueTypeSchema(returnContext));
@@ -109,7 +108,8 @@
   ///
   /// If the function is a generator function this is based on the explicit
   /// yield statements registered in [handleYield].
-  DartType inferReturnType(TypeInferrerImpl inferrer, {bool hasImplicitReturn});
+  DartType inferReturnType(TypeInferrerImpl inferrer,
+      {required bool hasImplicitReturn});
 }
 
 class _SyncClosureContext implements ClosureContext {
@@ -129,23 +129,23 @@
 
   final bool _needToInferReturnType;
 
-  DartType _inferredReturnType;
+  DartType? _inferredReturnType;
 
   /// Whether the function is an arrow function.
-  bool _isArrow;
+  bool? _isArrow;
 
   /// A list of return statements in functions whose return type is being
   /// inferred.
   ///
   /// The returns are checked for validity after the return type is inferred.
-  List<ReturnStatement> _returnStatements;
+  List<ReturnStatement>? _returnStatements;
 
   /// A list of return expression types in functions whose return type is
   /// being inferred.
-  List<DartType> _returnExpressionTypes;
+  List<DartType>? _returnExpressionTypes;
 
   @override
-  DartType get futureValueType => null;
+  DartType? get futureValueType => null;
 
   _SyncClosureContext(this._returnContext, this._declaredReturnType,
       this._needToInferReturnType) {
@@ -167,7 +167,7 @@
             returnType is NullType) {
           // Valid return;
         } else {
-          statement.expression = inferrer.helper.wrapInProblem(
+          statement.expression = inferrer.helper!.wrapInProblem(
               new NullLiteral()..fileOffset = statement.fileOffset,
               messageReturnWithoutExpressionSync,
               statement.fileOffset,
@@ -175,7 +175,7 @@
             ..parent = statement;
         }
       } else {
-        if (_isArrow && returnType is VoidType) {
+        if (_isArrow! && returnType is VoidType) {
           // For `=> e` it is a compile-time error if T is not void, and it
           // would have been a compile-time error to declare the function with
           // the body `{ return e; }` rather than `=> e`.
@@ -188,29 +188,29 @@
                 expressionType is NullType)) {
           // It is a compile-time error if s is `return e;`, T is void, and S is
           // neither void, dynamic, nor Null.
-          statement.expression = inferrer.helper.wrapInProblem(
-              statement.expression,
+          statement.expression = inferrer.helper!.wrapInProblem(
+              statement.expression!,
               messageReturnFromVoidFunction,
-              statement.expression.fileOffset,
+              statement.expression!.fileOffset,
               noLength)
             ..parent = statement;
         } else if (!(returnType is VoidType || returnType is DynamicType) &&
             expressionType is VoidType) {
           // It is a compile-time error if s is `return e;`, T is neither void
           // nor dynamic, and S is void.
-          statement.expression = inferrer.helper.wrapInProblem(
-              statement.expression,
+          statement.expression = inferrer.helper!.wrapInProblem(
+              statement.expression!,
               templateInvalidReturn.withArguments(expressionType,
                   _declaredReturnType, inferrer.isNonNullableByDefault),
-              statement.expression.fileOffset,
+              statement.expression!.fileOffset,
               noLength)
             ..parent = statement;
         } else if (expressionType is! VoidType) {
           // It is a compile-time error if s is `return e;`, S is not void, and
           // S is not assignable to T.
           Expression expression = inferrer.ensureAssignable(
-              _returnContext, expressionType, statement.expression,
-              fileOffset: statement.expression.fileOffset,
+              _returnContext, expressionType, statement.expression!,
+              fileOffset: statement.expression!.fileOffset,
               isVoidAllowed: true,
               errorTemplate: templateInvalidReturn,
               nullabilityErrorTemplate: templateInvalidReturnNullability,
@@ -233,7 +233,7 @@
             returnType is NullType) {
           // Valid return;
         } else {
-          statement.expression = inferrer.helper.wrapInProblem(
+          statement.expression = inferrer.helper!.wrapInProblem(
               new NullLiteral()..fileOffset = statement.fileOffset,
               messageReturnWithoutExpression,
               statement.fileOffset,
@@ -243,12 +243,12 @@
       } else {
         void ensureAssignability() {
           Expression expression = inferrer.ensureAssignable(
-              _returnContext, expressionType, statement.expression,
+              _returnContext, expressionType, statement.expression!,
               fileOffset: statement.fileOffset, isVoidAllowed: true);
           statement.expression = expression..parent = statement;
         }
 
-        if (_isArrow && returnType is VoidType) {
+        if (_isArrow! && returnType is VoidType) {
           // Arrow functions are valid if: T is void or return exp; is a valid
           // for a block-bodied function.
           ensureAssignability();
@@ -257,10 +257,10 @@
             expressionType is! DynamicType &&
             expressionType is! NullType) {
           // Invalid if T is void and S is not void, dynamic, or Null
-          statement.expression = inferrer.helper.wrapInProblem(
-              statement.expression,
+          statement.expression = inferrer.helper!.wrapInProblem(
+              statement.expression!,
               messageReturnFromVoidFunction,
-              statement.expression.fileOffset,
+              statement.expression!.fileOffset,
               noLength)
             ..parent = statement;
         } else if (expressionType is VoidType &&
@@ -268,10 +268,10 @@
             returnType is! DynamicType &&
             returnType is! NullType) {
           // Invalid if S is void and T is not void, dynamic, or Null.
-          statement.expression = inferrer.helper.wrapInProblem(
-              statement.expression,
+          statement.expression = inferrer.helper!.wrapInProblem(
+              statement.expression!,
               messageVoidExpression,
-              statement.expression.fileOffset,
+              statement.expression!.fileOffset,
               noLength)
             ..parent = statement;
         } else {
@@ -296,8 +296,8 @@
     if (_needToInferReturnType) {
       // Add the return to a list to be checked for validity after we've
       // inferred the return type.
-      _returnStatements.add(statement);
-      _returnExpressionTypes.add(type);
+      _returnStatements!.add(statement);
+      _returnExpressionTypes!.add(type);
     } else if (!inferrer.isTopLevel) {
       _checkValidReturn(inferrer, _declaredReturnType, statement, type);
     }
@@ -311,10 +311,11 @@
 
   @override
   DartType inferReturnType(TypeInferrerImpl inferrer,
-      {bool hasImplicitReturn}) {
+      {required bool hasImplicitReturn}) {
     assert(_needToInferReturnType);
+    // ignore: unnecessary_null_comparison
     assert(hasImplicitReturn != null);
-    DartType actualReturnedType;
+    DartType? actualReturnedType;
     DartType inferredReturnType;
     if (inferrer.isNonNullableByDefault) {
       if (hasImplicitReturn) {
@@ -327,9 +328,9 @@
             NeverType.fromNullability(inferrer.library.nonNullable);
       }
       // Use the types seen from the explicit return statements.
-      for (int i = 0; i < _returnStatements.length; i++) {
-        ReturnStatement statement = _returnStatements[i];
-        DartType type = _returnExpressionTypes[i];
+      for (int i = 0; i < _returnStatements!.length; i++) {
+        ReturnStatement statement = _returnStatements![i];
+        DartType type = _returnExpressionTypes![i];
         // The return expression has to be assignable to the return type
         // expectation from the downwards inference context.
         if (statement.expression != null) {
@@ -355,7 +356,7 @@
         // With null safety: if R is void, or the function literal is marked
         // async and R is FutureOr<void>, let S be void.
         inferredReturnType = const VoidType();
-      } else if (inferrer.typeSchemaEnvironment.isSubtypeOf(actualReturnedType,
+      } else if (inferrer.typeSchemaEnvironment.isSubtypeOf(actualReturnedType!,
           returnContext, SubtypeCheckMode.withNullabilities)) {
         // Otherwise, if T <: R then let S be T.
         inferredReturnType = actualReturnedType;
@@ -364,11 +365,11 @@
         inferredReturnType = returnContext;
       }
     } else {
-      if (_returnStatements.isNotEmpty) {
+      if (_returnStatements!.isNotEmpty) {
         // Use the types seen from the explicit return statements.
-        for (int i = 0; i < _returnStatements.length; i++) {
-          ReturnStatement statement = _returnStatements[i];
-          DartType type = _returnExpressionTypes[i];
+        for (int i = 0; i < _returnStatements!.length; i++) {
+          ReturnStatement statement = _returnStatements![i];
+          DartType type = _returnExpressionTypes![i];
           // The return expression has to be assignable to the return type
           // expectation from the downwards inference context.
           if (statement.expression != null) {
@@ -393,7 +394,7 @@
         actualReturnedType = const NullType();
       }
 
-      if (!inferrer.typeSchemaEnvironment.isSubtypeOf(actualReturnedType,
+      if (!inferrer.typeSchemaEnvironment.isSubtypeOf(actualReturnedType!,
           _returnContext, SubtypeCheckMode.withNullabilities)) {
         // If the inferred return type isn't a subtype of the context, we use
         // the context.
@@ -404,10 +405,10 @@
       }
     }
 
-    for (int i = 0; i < _returnStatements.length; ++i) {
+    for (int i = 0; i < _returnStatements!.length; ++i) {
       if (!inferrer.isTopLevel) {
-        _checkValidReturn(inferrer, inferredReturnType, _returnStatements[i],
-            _returnExpressionTypes[i]);
+        _checkValidReturn(inferrer, inferredReturnType, _returnStatements![i],
+            _returnExpressionTypes![i]);
       }
     }
 
@@ -425,7 +426,7 @@
     if (_needToInferReturnType) {
       assert(_inferredReturnType != null,
           "Return type has not yet been inferred.");
-      returnType = _inferredReturnType;
+      returnType = _inferredReturnType!;
     } else {
       returnType = _declaredReturnType;
     }
@@ -437,7 +438,7 @@
       Statement resultStatement =
           inferenceResult.hasChanged ? inferenceResult.statement : body;
       // Create a synthetic return statement with the error.
-      Statement returnStatement = new ReturnStatement(inferrer.helper
+      Statement returnStatement = new ReturnStatement(inferrer.helper!
           .wrapInProblem(
               new NullLiteral()..fileOffset = fileOffset,
               templateImplicitReturnNull.withArguments(
@@ -480,22 +481,22 @@
 
   final bool _needToInferReturnType;
 
-  DartType _inferredReturnType;
+  DartType? _inferredReturnType;
 
   /// Whether the function is an arrow function.
-  bool _isArrow;
+  bool? _isArrow;
 
   /// A list of return statements in functions whose return type is being
   /// inferred.
   ///
   /// The returns are checked for validity after the return type is inferred.
-  List<ReturnStatement> _returnStatements;
+  List<ReturnStatement>? _returnStatements;
 
   /// A list of return expression types in functions whose return type is
   /// being inferred.
-  List<DartType> _returnExpressionTypes;
+  List<DartType>? _returnExpressionTypes;
 
-  DartType futureValueType;
+  DartType? futureValueType;
 
   _AsyncClosureContext(this._returnContext, this._declaredReturnType,
       this._needToInferReturnType, this.futureValueType) {
@@ -520,7 +521,7 @@
             futureValueType is NullType) {
           // Valid return;
         } else {
-          statement.expression = inferrer.helper.wrapInProblem(
+          statement.expression = inferrer.helper!.wrapInProblem(
               new NullLiteral()..fileOffset = statement.fileOffset,
               messageReturnWithoutExpressionAsync,
               statement.fileOffset,
@@ -528,7 +529,7 @@
             ..parent = statement;
         }
       } else {
-        if (_isArrow &&
+        if (_isArrow! &&
             inferrer.typeSchemaEnvironment.flatten(returnType) is VoidType) {
           // For `async => e` it is a compile-time error if flatten(T) is not
           // void, and it would have been a compile-time error to declare the
@@ -545,11 +546,11 @@
                 flattenedExpressionType is NullType)) {
           // It is a compile-time error if s is `return e;`, T_v is void, and
           // flatten(S) is neither void, dynamic, Null.
-          statement.expression = inferrer.helper.wrapInProblem(
+          statement.expression = inferrer.helper!.wrapInProblem(
               new NullLiteral()..fileOffset = statement.fileOffset,
               templateInvalidReturnAsync.withArguments(
                   expressionType, returnType, inferrer.isNonNullableByDefault),
-              statement.expression.fileOffset,
+              statement.expression!.fileOffset,
               noLength)
             ..parent = statement;
         } else if (!(futureValueType is VoidType ||
@@ -557,24 +558,24 @@
             flattenedExpressionType is VoidType) {
           // It is a compile-time error if s is `return e;`, T_v is neither void
           // nor dynamic, and flatten(S) is void.
-          statement.expression = inferrer.helper.wrapInProblem(
+          statement.expression = inferrer.helper!.wrapInProblem(
               new NullLiteral()..fileOffset = statement.fileOffset,
               templateInvalidReturnAsync.withArguments(
                   expressionType, returnType, inferrer.isNonNullableByDefault),
-              statement.expression.fileOffset,
+              statement.expression!.fileOffset,
               noLength)
             ..parent = statement;
         } else if (flattenedExpressionType is! VoidType &&
             !inferrer.typeSchemaEnvironment
                 .performNullabilityAwareSubtypeCheck(
-                    flattenedExpressionType, futureValueType)
+                    flattenedExpressionType, futureValueType!)
                 .isSubtypeWhenUsingNullabilities()) {
           // It is a compile-time error if s is `return e;`, flatten(S) is not
           // void, S is not assignable to T_v, and flatten(S) is not a subtype
           // of T_v.
           statement.expression = inferrer.ensureAssignable(
-              futureValueType, expressionType, statement.expression,
-              fileOffset: statement.expression.fileOffset,
+              futureValueType!, expressionType, statement.expression!,
+              fileOffset: statement.expression!.fileOffset,
               runtimeCheckedType:
                   inferrer.computeGreatestClosure2(_returnContext),
               declaredContextType: returnType,
@@ -602,7 +603,7 @@
             flattenedReturnType is NullType) {
           // Valid return;
         } else {
-          statement.expression = inferrer.helper.wrapInProblem(
+          statement.expression = inferrer.helper!.wrapInProblem(
               new NullLiteral()..fileOffset = statement.fileOffset,
               messageReturnWithoutExpression,
               statement.fileOffset,
@@ -619,7 +620,7 @@
           Expression expression = inferrer.ensureAssignable(
               computeAssignableType(inferrer, _returnContext, wrappedType),
               wrappedType,
-              statement.expression,
+              statement.expression!,
               fileOffset: statement.fileOffset,
               isVoidAllowed: true,
               runtimeCheckedType:
@@ -627,7 +628,7 @@
           statement.expression = expression..parent = statement;
         }
 
-        if (_isArrow && flattenedReturnType is VoidType) {
+        if (_isArrow! && flattenedReturnType is VoidType) {
           // Arrow functions are valid if: flatten(T) is void or return exp; is
           // valid for a block-bodied function.
           ensureAssignability();
@@ -636,10 +637,10 @@
             flattenedExpressionType is! DynamicType &&
             flattenedExpressionType is! NullType) {
           // Invalid if T is void and flatten(S) is not void, dynamic, or Null.
-          statement.expression = inferrer.helper.wrapInProblem(
-              statement.expression,
+          statement.expression = inferrer.helper!.wrapInProblem(
+              statement.expression!,
               messageReturnFromVoidFunction,
-              statement.expression.fileOffset,
+              statement.expression!.fileOffset,
               noLength)
             ..parent = statement;
         } else if (flattenedExpressionType is VoidType &&
@@ -648,10 +649,10 @@
             flattenedReturnType is! NullType) {
           // Invalid if flatten(S) is void and flatten(T) is not void, dynamic,
           // or Null.
-          statement.expression = inferrer.helper.wrapInProblem(
-              statement.expression,
+          statement.expression = inferrer.helper!.wrapInProblem(
+              statement.expression!,
               messageVoidExpression,
-              statement.expression.fileOffset,
+              statement.expression!.fileOffset,
               noLength)
             ..parent = statement;
         } else {
@@ -678,8 +679,8 @@
     if (_needToInferReturnType) {
       // Add the return to a list to be checked for validity after we've
       // inferred the return type.
-      _returnStatements.add(statement);
-      _returnExpressionTypes.add(type);
+      _returnStatements!.add(statement);
+      _returnExpressionTypes!.add(type);
     } else if (!inferrer.isTopLevel) {
       _checkValidReturn(inferrer, _declaredReturnType, statement, type);
     }
@@ -715,10 +716,11 @@
 
   @override
   DartType inferReturnType(TypeInferrerImpl inferrer,
-      {bool hasImplicitReturn}) {
+      {required bool hasImplicitReturn}) {
     assert(_needToInferReturnType);
+    // ignore: unnecessary_null_comparison
     assert(hasImplicitReturn != null);
-    DartType inferredType;
+    DartType? inferredType;
 
     if (inferrer.isNonNullableByDefault) {
       if (hasImplicitReturn) {
@@ -730,8 +732,8 @@
         inferredType = NeverType.fromNullability(inferrer.library.nonNullable);
       }
       // Use the types seen from the explicit return statements.
-      for (int i = 0; i < _returnStatements.length; i++) {
-        DartType type = _returnExpressionTypes[i];
+      for (int i = 0; i < _returnStatements!.length; i++) {
+        DartType type = _returnExpressionTypes![i];
 
         DartType unwrappedType = inferrer.typeSchemaEnvironment.flatten(type);
         if (inferredType == null) {
@@ -755,7 +757,7 @@
               returnContext.typeArgument is VoidType) {
         inferredType = const VoidType();
       } else if (!inferrer.typeSchemaEnvironment.isSubtypeOf(
-          inferredType, returnContext, SubtypeCheckMode.withNullabilities)) {
+          inferredType!, returnContext, SubtypeCheckMode.withNullabilities)) {
         // If the inferred return type isn't a subtype of the context, we use
         // the context.
         inferredType = returnContext;
@@ -764,11 +766,11 @@
           inferrer.typeSchemaEnvironment.flatten(inferredType),
           inferrer.library.nonNullable);
     } else {
-      if (_returnStatements.isNotEmpty) {
+      if (_returnStatements!.isNotEmpty) {
         // Use the types seen from the explicit return statements.
-        for (int i = 0; i < _returnStatements.length; i++) {
-          ReturnStatement statement = _returnStatements[i];
-          DartType type = _returnExpressionTypes[i];
+        for (int i = 0; i < _returnStatements!.length; i++) {
+          ReturnStatement statement = _returnStatements![i];
+          DartType type = _returnExpressionTypes![i];
 
           // The return expression has to be assignable to the return type
           // expectation from the downwards inference context.
@@ -796,7 +798,7 @@
         inferredType = const NullType();
       }
       inferredType =
-          inferrer.wrapFutureType(inferredType, inferrer.library.nonNullable);
+          inferrer.wrapFutureType(inferredType!, inferrer.library.nonNullable);
 
       if (!inferrer.typeSchemaEnvironment.isSubtypeOf(
           inferredType, _returnContext, SubtypeCheckMode.withNullabilities)) {
@@ -811,9 +813,9 @@
           computeFutureValueType(inferrer.coreTypes, inferredType);
     }
     if (!inferrer.isTopLevel) {
-      for (int i = 0; i < _returnStatements.length; ++i) {
-        _checkValidReturn(inferrer, inferredType, _returnStatements[i],
-            _returnExpressionTypes[i]);
+      for (int i = 0; i < _returnStatements!.length; ++i) {
+        _checkValidReturn(inferrer, inferredType, _returnStatements![i],
+            _returnExpressionTypes![i]);
       }
     }
 
@@ -831,7 +833,7 @@
     if (_needToInferReturnType) {
       assert(_inferredReturnType != null,
           "Return type has not yet been inferred.");
-      returnType = _inferredReturnType;
+      returnType = _inferredReturnType!;
     } else {
       returnType = _declaredReturnType;
     }
@@ -844,7 +846,7 @@
       Statement resultStatement =
           inferenceResult.hasChanged ? inferenceResult.statement : body;
       // Create a synthetic return statement with the error.
-      Statement returnStatement = new ReturnStatement(inferrer.helper
+      Statement returnStatement = new ReturnStatement(inferrer.helper!
           .wrapInProblem(
               new NullLiteral()..fileOffset = fileOffset,
               templateImplicitReturnNull.withArguments(
@@ -894,10 +896,10 @@
 
   /// A list of return expression types in functions whose return type is
   /// being inferred.
-  List<DartType> _yieldElementTypes;
+  List<DartType>? _yieldElementTypes;
 
   @override
-  DartType get futureValueType => null;
+  DartType? get futureValueType => null;
 
   _SyncStarClosureContext(this._yieldElementContext, this._declaredReturnType,
       this._needToInferReturnType) {
@@ -934,20 +936,21 @@
                 type, inferrer.coreTypes.iterableClass) ??
             elementType;
       }
-      _yieldElementTypes.add(elementType);
+      _yieldElementTypes!.add(elementType);
     }
   }
 
   @override
   DartType inferReturnType(TypeInferrerImpl inferrer,
-      {bool hasImplicitReturn}) {
+      {required bool hasImplicitReturn}) {
     assert(_needToInferReturnType);
+    // ignore: unnecessary_null_comparison
     assert(hasImplicitReturn != null);
-    DartType inferredElementType;
-    if (_yieldElementTypes.isNotEmpty) {
+    DartType? inferredElementType;
+    if (_yieldElementTypes!.isNotEmpty) {
       // Use the types seen from the explicit return statements.
-      for (int i = 0; i < _yieldElementTypes.length; i++) {
-        DartType type = _yieldElementTypes[i];
+      for (int i = 0; i < _yieldElementTypes!.length; i++) {
+        DartType type = _yieldElementTypes![i];
         if (inferredElementType == null) {
           inferredElementType = type;
         } else {
@@ -970,7 +973,7 @@
       }
     }
 
-    DartType inferredType = inferrer.wrapType(inferredElementType,
+    DartType inferredType = inferrer.wrapType(inferredElementType!,
         inferrer.coreTypes.iterableClass, inferrer.library.nonNullable);
 
     if (!inferrer.typeSchemaEnvironment.isSubtypeOf(inferredType,
@@ -1023,10 +1026,10 @@
 
   /// A list of return expression types in functions whose return type is
   /// being inferred.
-  List<DartType> _yieldElementTypes;
+  List<DartType>? _yieldElementTypes;
 
   @override
-  DartType get futureValueType => null;
+  DartType? get futureValueType => null;
 
   _AsyncStarClosureContext(this._yieldElementContext, this._declaredReturnType,
       this._needToInferReturnType) {
@@ -1064,19 +1067,20 @@
                 type, inferrer.coreTypes.streamClass) ??
             type;
       }
-      _yieldElementTypes.add(elementType);
+      _yieldElementTypes!.add(elementType);
     }
   }
 
   @override
   DartType inferReturnType(TypeInferrerImpl inferrer,
-      {bool hasImplicitReturn}) {
+      {required bool hasImplicitReturn}) {
     assert(_needToInferReturnType);
+    // ignore: unnecessary_null_comparison
     assert(hasImplicitReturn != null);
-    DartType inferredElementType;
-    if (_yieldElementTypes.isNotEmpty) {
+    DartType? inferredElementType;
+    if (_yieldElementTypes!.isNotEmpty) {
       // Use the types seen from the explicit return statements.
-      for (DartType elementType in _yieldElementTypes) {
+      for (DartType elementType in _yieldElementTypes!) {
         if (inferredElementType == null) {
           inferredElementType = elementType;
         } else {
@@ -1099,7 +1103,7 @@
       }
     }
 
-    DartType inferredType = inferrer.wrapType(inferredElementType,
+    DartType inferredType = inferrer.wrapType(inferredElementType!,
         inferrer.coreTypes.streamClass, inferrer.library.nonNullable);
 
     if (!inferrer.typeSchemaEnvironment.isSubtypeOf(inferredType,
diff --git a/pkg/front_end/lib/src/fasta/type_inference/inference_helper.dart b/pkg/front_end/lib/src/fasta/type_inference/inference_helper.dart
index b6f3f9a..e449a1e 100644
--- a/pkg/front_end/lib/src/fasta/type_inference/inference_helper.dart
+++ b/pkg/front_end/lib/src/fasta/type_inference/inference_helper.dart
@@ -18,7 +18,7 @@
   Expression buildProblem(Message message, int charOffset, int length,
       {List<LocatedMessage>? context, bool suppressMessage = false});
 
-  LocatedMessage checkArgumentsForType(
+  LocatedMessage? checkArgumentsForType(
       FunctionType function, Arguments arguments, int offset,
       {bool isExtensionMemberInvocation = false});
 
diff --git a/pkg/front_end/lib/src/fasta/type_inference/type_inference_engine.dart b/pkg/front_end/lib/src/fasta/type_inference/type_inference_engine.dart
index d410f6e..407fbfb 100644
--- a/pkg/front_end/lib/src/fasta/type_inference/type_inference_engine.dart
+++ b/pkg/front_end/lib/src/fasta/type_inference/type_inference_engine.dart
@@ -2,8 +2,6 @@
 // for details. All rights reserved. Use of this source code is governed by a
 // BSD-style license that can be found in the LICENSE.md file.
 
-// @dart = 2.9
-
 import 'package:_fe_analyzer_shared/src/flow_analysis/flow_analysis.dart';
 import 'package:front_end/src/fasta/kernel/internal_ast.dart';
 
@@ -40,7 +38,7 @@
   final List<TypeParameter> _typeParametersToSearchFor;
 
   IncludesTypeParametersNonCovariantly(this._typeParametersToSearchFor,
-      {int initialVariance})
+      {required int initialVariance})
       : _variance = initialVariance;
 
   @override
@@ -101,11 +99,11 @@
 /// (e.g. DietListener).  Derived classes should derive from
 /// [TypeInferenceEngineImpl].
 abstract class TypeInferenceEngine {
-  ClassHierarchy classHierarchy;
+  late ClassHierarchy classHierarchy;
 
-  ClassHierarchyBuilder hierarchyBuilder;
+  late ClassHierarchyBuilder hierarchyBuilder;
 
-  CoreTypes coreTypes;
+  late CoreTypes coreTypes;
 
   // TODO(johnniwinther): Shared this with the BodyBuilder.
   final Forest forest = const Forest();
@@ -113,7 +111,7 @@
   /// Indicates whether the "prepare" phase of type inference is complete.
   bool isTypeInferencePrepared = false;
 
-  TypeSchemaEnvironment typeSchemaEnvironment;
+  late TypeSchemaEnvironment typeSchemaEnvironment;
 
   /// A map containing constructors with initializing formals whose types
   /// need to be inferred.
@@ -130,19 +128,19 @@
   /// is used to report errors.
   final Map<Constructor, ConstructorBuilder> beingInferred = {};
 
-  final Instrumentation instrumentation;
+  final Instrumentation? instrumentation;
 
   TypeInferenceEngine(this.instrumentation);
 
   /// Creates a type inferrer for use inside of a method body declared in a file
   /// with the given [uri].
-  TypeInferrer createLocalTypeInferrer(Uri uri, InterfaceType thisType,
-      SourceLibraryBuilder library, InferenceDataForTesting dataForTesting);
+  TypeInferrer createLocalTypeInferrer(Uri uri, InterfaceType? thisType,
+      SourceLibraryBuilder library, InferenceDataForTesting? dataForTesting);
 
   /// Creates a [TypeInferrer] object which is ready to perform type inference
   /// on the given [field].
-  TypeInferrer createTopLevelTypeInferrer(Uri uri, InterfaceType thisType,
-      SourceLibraryBuilder library, InferenceDataForTesting dataForTesting);
+  TypeInferrer createTopLevelTypeInferrer(Uri uri, InterfaceType? thisType,
+      SourceLibraryBuilder library, InferenceDataForTesting? dataForTesting);
 
   /// Performs the third phase of top level inference, which is to visit all
   /// constructors still needing inference and infer the types of their
@@ -165,7 +163,7 @@
         new TypeSchemaEnvironment(coreTypes, hierarchy);
   }
 
-  static Member resolveInferenceNode(Member member) {
+  static Member? resolveInferenceNode(Member? member) {
     if (member is Field) {
       DartType type = member.type;
       if (type is ImplicitFieldType) {
@@ -179,12 +177,12 @@
 /// Concrete implementation of [TypeInferenceEngine] specialized to work with
 /// kernel objects.
 class TypeInferenceEngineImpl extends TypeInferenceEngine {
-  TypeInferenceEngineImpl(Instrumentation instrumentation)
+  TypeInferenceEngineImpl(Instrumentation? instrumentation)
       : super(instrumentation);
 
   @override
-  TypeInferrer createLocalTypeInferrer(Uri uri, InterfaceType thisType,
-      SourceLibraryBuilder library, InferenceDataForTesting dataForTesting) {
+  TypeInferrer createLocalTypeInferrer(Uri uri, InterfaceType? thisType,
+      SourceLibraryBuilder library, InferenceDataForTesting? dataForTesting) {
     AssignedVariables<TreeNode, VariableDeclaration> assignedVariables;
     if (dataForTesting != null) {
       assignedVariables = dataForTesting.flowAnalysisResult.assignedVariables =
@@ -198,8 +196,8 @@
   }
 
   @override
-  TypeInferrer createTopLevelTypeInferrer(Uri uri, InterfaceType thisType,
-      SourceLibraryBuilder library, InferenceDataForTesting dataForTesting) {
+  TypeInferrer createTopLevelTypeInferrer(Uri uri, InterfaceType? thisType,
+      SourceLibraryBuilder library, InferenceDataForTesting? dataForTesting) {
     AssignedVariables<TreeNode, VariableDeclaration> assignedVariables;
     if (dataForTesting != null) {
       assignedVariables = dataForTesting.flowAnalysisResult.assignedVariables =
@@ -239,7 +237,7 @@
   final List<TreeNode> definitelyUnassignedNodes = [];
 
   /// The assigned variables information that computed for the member.
-  AssignedVariablesForTesting<TreeNode, VariableDeclaration> assignedVariables;
+  AssignedVariablesForTesting<TreeNode, VariableDeclaration>? assignedVariables;
 
   /// For each expression that led to an error because it was not promoted, a
   /// string describing the reason it was not promoted.
@@ -257,7 +255,7 @@
   TypeOperationsCfe(this.typeEnvironment);
 
   @override
-  TypeClassification classifyType(DartType type) {
+  TypeClassification classifyType(DartType? type) {
     if (type == null) {
       // Note: this can happen during top-level inference.
       return TypeClassification.potentiallyNullable;
diff --git a/pkg/front_end/lib/src/fasta/type_inference/type_inferrer.dart b/pkg/front_end/lib/src/fasta/type_inference/type_inferrer.dart
index 5424d61..fe7c2c6 100644
--- a/pkg/front_end/lib/src/fasta/type_inference/type_inferrer.dart
+++ b/pkg/front_end/lib/src/fasta/type_inference/type_inferrer.dart
@@ -2,8 +2,6 @@
 // for details. All rights reserved. Use of this source code is governed by a
 // BSD-style license that can be found in the LICENSE.md file.
 
-// @dart = 2.9
-
 import 'dart:core';
 
 import 'package:_fe_analyzer_shared/src/flow_analysis/flow_analysis.dart';
@@ -68,7 +66,7 @@
 
 /// Given a [FunctionNode], gets the named parameter identified by [name], or
 /// `null` if there is no parameter with the given name.
-VariableDeclaration getNamedFormal(FunctionNode function, String name) {
+VariableDeclaration? getNamedFormal(FunctionNode function, String name) {
   for (VariableDeclaration formal in function.namedParameters) {
     if (formal.name == name) return formal;
   }
@@ -77,7 +75,7 @@
 
 /// Given a [FunctionNode], gets the [i]th positional formal parameter, or
 /// `null` if there is no parameter with that index.
-VariableDeclaration getPositionalFormal(FunctionNode function, int i) {
+VariableDeclaration? getPositionalFormal(FunctionNode function, int i) {
   if (i < function.positionalParameters.length) {
     return function.positionalParameters[i];
   } else {
@@ -131,6 +129,16 @@
   Expression inferFieldInitializer(
       InferenceHelper helper, DartType declaredType, Expression initializer);
 
+  /// Returns the type used as the inferred type of a variable declaration,
+  /// based on the static type of the initializer expression, given by
+  /// [initializerType].
+  DartType inferDeclarationType(DartType initializerType);
+
+  /// Performs type inference on [expression].
+  ExpressionInferenceResult inferExpression(
+      Expression expression, DartType typeContext, bool typeNeeded,
+      {bool isVoidAllowed: false, bool forEffect: false});
+
   /// Performs type inference on the given function body.
   InferredFunctionBody inferFunctionBody(InferenceHelper helper, int fileOffset,
       DartType returnType, AsyncMarker asyncMarker, Statement body);
@@ -140,7 +148,7 @@
 
   /// Performs type inference on the given metadata annotations.
   void inferMetadata(
-      InferenceHelper helper, TreeNode parent, List<Expression> annotations);
+      InferenceHelper helper, TreeNode? parent, List<Expression>? annotations);
 
   /// Performs type inference on the given metadata annotations keeping the
   /// existing helper if possible.
@@ -175,7 +183,7 @@
 
   final AssignedVariables<TreeNode, VariableDeclaration> assignedVariables;
 
-  final InferenceDataForTesting dataForTesting;
+  final InferenceDataForTesting? dataForTesting;
 
   @override
   final Uri uriForInstrumentation;
@@ -187,23 +195,24 @@
 
   final ClassHierarchy classHierarchy;
 
-  final Instrumentation instrumentation;
+  final Instrumentation? instrumentation;
 
   final TypeSchemaEnvironment typeSchemaEnvironment;
 
-  final InterfaceType thisType;
+  final InterfaceType? thisType;
 
   @override
   final SourceLibraryBuilder library;
 
-  InferenceHelper helper;
+  InferenceHelper? helper;
 
   /// Context information for the current closure, or `null` if we are not
   /// inside a closure.
-  ClosureContext closureContext;
+  ClosureContext? closureContext;
 
   TypeInferrerImpl(this.engine, this.uriForInstrumentation, bool topLevel,
       this.thisType, this.library, this.assignedVariables, this.dataForTesting)
+      // ignore: unnecessary_null_comparison
       : assert(library != null),
         unknownFunction = new FunctionType(
             const [], const DynamicType(), library.nonNullable),
@@ -254,10 +263,12 @@
   Expression createReachabilityError(
       int fileOffset, Message errorMessage, Message warningMessage) {
     if (library.loader.target.context.options.warnOnReachabilityCheck &&
+        // ignore: unnecessary_null_comparison
         warningMessage != null) {
       helper?.addProblem(warningMessage, fileOffset, noLength);
     }
     Arguments arguments;
+    // ignore: unnecessary_null_comparison
     if (errorMessage != null) {
       arguments = new Arguments(
           [new StringLiteral(errorMessage.message)..fileOffset = fileOffset])
@@ -265,6 +276,7 @@
     } else {
       arguments = new Arguments([])..fileOffset = fileOffset;
     }
+    // ignore: unnecessary_null_comparison
     assert(coreTypes.reachabilityErrorConstructor != null);
     return new Throw(
         new ConstructorInvocation(
@@ -276,27 +288,27 @@
   /// Computes a list of context messages explaining why [receiver] was not
   /// promoted, to be used when reporting an error for a larger expression
   /// containing [receiver].  [node] is the containing tree node.
-  List<LocatedMessage> getWhyNotPromotedContext(
-      Map<DartType, NonPromotionReason> whyNotPromoted,
+  List<LocatedMessage>? getWhyNotPromotedContext(
+      Map<DartType, NonPromotionReason>? whyNotPromoted,
       TreeNode node,
       bool Function(DartType) typeFilter) {
-    List<LocatedMessage> context;
+    List<LocatedMessage>? context;
     if (whyNotPromoted != null && whyNotPromoted.isNotEmpty) {
       _WhyNotPromotedVisitor whyNotPromotedVisitor =
           new _WhyNotPromotedVisitor(this);
       for (MapEntry<DartType, NonPromotionReason> entry
           in whyNotPromoted.entries) {
         if (!typeFilter(entry.key)) continue;
-        LocatedMessage message = entry.value.accept(whyNotPromotedVisitor);
+        LocatedMessage? message = entry.value.accept(whyNotPromotedVisitor);
         if (dataForTesting != null) {
           String nonPromotionReasonText = entry.value.shortName;
           List<String> args = <String>[];
           if (whyNotPromotedVisitor.propertyReference != null) {
-            Id id = computeMemberId(whyNotPromotedVisitor.propertyReference);
+            Id id = computeMemberId(whyNotPromotedVisitor.propertyReference!);
             args.add('target: $id');
           }
           if (whyNotPromotedVisitor.propertyType != null) {
-            String typeText = typeToText(whyNotPromotedVisitor.propertyType,
+            String typeText = typeToText(whyNotPromotedVisitor.propertyType!,
                 TypeRepresentation.analyzerNonNullableByDefault);
             args.add('type: $typeText');
           }
@@ -311,9 +323,9 @@
             // Find the original expression.
             // TODO(johnniwinther): add a general solution for getting the
             // original node for testing.
-            origNode = (origNode as VariableGet).variable.initializer;
+            origNode = origNode.variable.initializer!;
           }
-          dataForTesting.flowAnalysisResult.nonPromotionReasons[origNode] =
+          dataForTesting!.flowAnalysisResult.nonPromotionReasons[origNode] =
               nonPromotionReasonText;
         }
         // Note: this will always pick the first viable reason (only).  I
@@ -323,7 +335,9 @@
         // promotions to non-nullable.
         // TODO(paulberry): do more testing and then expand on the comment
         // above.
-        context = [message];
+        if (message != null) {
+          context = [message];
+        }
         break;
       }
     }
@@ -335,17 +349,17 @@
   bool get shouldThrowUnsoundnessException =>
       isNonNullableByDefault && nnbdMode != NnbdMode.Strong;
 
-  void registerIfUnreachableForTesting(TreeNode node, {bool isReachable}) {
+  void registerIfUnreachableForTesting(TreeNode node, {bool? isReachable}) {
     if (dataForTesting == null) return;
     isReachable ??= flowAnalysis.isReachable;
     if (!isReachable) {
-      dataForTesting.flowAnalysisResult.unreachableNodes.add(node);
+      dataForTesting!.flowAnalysisResult.unreachableNodes.add(node);
     }
   }
 
   @override
   void inferConstructorParameterTypes(Constructor target) {
-    ConstructorBuilder constructor = engine.beingInferred[target];
+    ConstructorBuilder? constructor = engine.beingInferred[target];
     if (constructor != null) {
       // There is a cyclic dependency where inferring the types of the
       // initializing formals of a constructor required us to infer the
@@ -362,16 +376,18 @@
           target.fileOffset,
           name.length,
           target.fileUri);
-      for (VariableDeclaration declaration
+      // TODO(johnniwinther): Is this needed? VariableDeclaration.type is
+      // non-nullable so the loops have no effect.
+      /*for (VariableDeclaration declaration
           in target.function.positionalParameters) {
         declaration.type ??= const InvalidType();
       }
       for (VariableDeclaration declaration in target.function.namedParameters) {
         declaration.type ??= const InvalidType();
-      }
+      }*/
     } else if ((constructor = engine.toBeInferred[target]) != null) {
       engine.toBeInferred.remove(target);
-      engine.beingInferred[target] = constructor;
+      engine.beingInferred[target] = constructor!;
       constructor.inferFormalTypes();
       engine.beingInferred.remove(target);
     }
@@ -423,15 +439,15 @@
 
   Expression ensureAssignableResult(
       DartType expectedType, ExpressionInferenceResult result,
-      {int fileOffset,
+      {int? fileOffset,
       bool isVoidAllowed: false,
-      Template<Message Function(DartType, DartType, bool)> errorTemplate,
-      Template<Message Function(DartType, DartType, bool)>
+      Template<Message Function(DartType, DartType, bool)>? errorTemplate,
+      Template<Message Function(DartType, DartType, bool)>?
           nullabilityErrorTemplate,
-      Template<Message Function(DartType, bool)> nullabilityNullErrorTemplate,
-      Template<Message Function(DartType, DartType, bool)>
+      Template<Message Function(DartType, bool)>? nullabilityNullErrorTemplate,
+      Template<Message Function(DartType, DartType, bool)>?
           nullabilityNullTypeErrorTemplate,
-      Template<Message Function(DartType, DartType, DartType, DartType, bool)>
+      Template<Message Function(DartType, DartType, DartType, DartType, bool)>?
           nullabilityPartErrorTemplate}) {
     return ensureAssignable(
         expectedType, result.inferredType, result.expression,
@@ -464,19 +480,20 @@
   /// directly.
   Expression ensureAssignable(
       DartType contextType, DartType expressionType, Expression expression,
-      {int fileOffset,
-      DartType declaredContextType,
-      DartType runtimeCheckedType,
+      {int? fileOffset,
+      DartType? declaredContextType,
+      DartType? runtimeCheckedType,
       bool isVoidAllowed: false,
-      Template<Message Function(DartType, DartType, bool)> errorTemplate,
-      Template<Message Function(DartType, DartType, bool)>
+      Template<Message Function(DartType, DartType, bool)>? errorTemplate,
+      Template<Message Function(DartType, DartType, bool)>?
           nullabilityErrorTemplate,
-      Template<Message Function(DartType, bool)> nullabilityNullErrorTemplate,
-      Template<Message Function(DartType, DartType, bool)>
+      Template<Message Function(DartType, bool)>? nullabilityNullErrorTemplate,
+      Template<Message Function(DartType, DartType, bool)>?
           nullabilityNullTypeErrorTemplate,
-      Template<Message Function(DartType, DartType, DartType, DartType, bool)>
+      Template<Message Function(DartType, DartType, DartType, DartType, bool)>?
           nullabilityPartErrorTemplate,
-      Map<DartType, NonPromotionReason> Function() whyNotPromoted}) {
+      Map<DartType, NonPromotionReason> Function()? whyNotPromoted}) {
+    // ignore: unnecessary_null_comparison
     assert(contextType != null);
 
     // [errorTemplate], [nullabilityErrorTemplate], and
@@ -511,7 +528,7 @@
 
     DartType initialContextType = runtimeCheckedType ?? contextType;
 
-    Template<Message Function(DartType, DartType, bool)>
+    Template<Message Function(DartType, DartType, bool)>?
         preciseTypeErrorTemplate = _getPreciseTypeErrorTemplate(expression);
     AssignabilityResult assignabilityResult = _computeAssignabilityKind(
         contextType, expressionType,
@@ -533,11 +550,15 @@
           ..fileOffset = fileOffset;
         break;
       case AssignabilityKind.assignableTearoff:
-        result = _tearOffCall(expression, expressionType, fileOffset).tearoff;
+        result = _tearOffCall(
+                expression, expressionType as InterfaceType, fileOffset)
+            .tearoff;
         break;
       case AssignabilityKind.assignableTearoffCast:
         result = new AsExpression(
-            _tearOffCall(expression, expressionType, fileOffset).tearoff,
+            _tearOffCall(
+                    expression, expressionType as InterfaceType, fileOffset)
+                .tearoff,
             initialContextType)
           ..isTypeError = true
           ..isForNonNullableByDefault = isNonNullableByDefault
@@ -555,22 +576,22 @@
         break;
       case AssignabilityKind.unassignableVoid:
         // Error: not assignable.  Perform error recovery.
-        result = helper.wrapInProblem(
+        result = helper!.wrapInProblem(
             expression, messageVoidExpression, expression.fileOffset, noLength);
         break;
       case AssignabilityKind.unassignablePrecise:
         // The type of the expression is known precisely, so an implicit
         // downcast is guaranteed to fail.  Insert a compile-time error.
-        result = helper.wrapInProblem(
+        result = helper!.wrapInProblem(
             expression,
-            preciseTypeErrorTemplate.withArguments(
+            preciseTypeErrorTemplate!.withArguments(
                 expressionType, contextType, isNonNullableByDefault),
             expression.fileOffset,
             noLength);
         break;
       case AssignabilityKind.unassignableTearoff:
-        TypedTearoff typedTearoff =
-            _tearOffCall(expression, expressionType, fileOffset);
+        TypedTearoff typedTearoff = _tearOffCall(
+            expression, expressionType as InterfaceType, fileOffset);
         result = _wrapUnassignableExpression(
             typedTearoff.tearoff,
             typedTearoff.tearoffType,
@@ -605,7 +626,7 @@
                     declaredContextType ?? contextType,
                     isNonNullableByDefault));
           } else {
-            whyNotPromoted ??= flowAnalysis?.whyNotPromoted(expression);
+            whyNotPromoted ??= flowAnalysis.whyNotPromoted(expression);
             result = _wrapUnassignableExpression(
                 expression,
                 expressionType,
@@ -613,7 +634,7 @@
                 nullabilityErrorTemplate.withArguments(expressionType,
                     declaredContextType ?? contextType, isNonNullableByDefault),
                 context: getWhyNotPromotedContext(
-                    whyNotPromoted?.call(),
+                    whyNotPromoted.call(),
                     expression,
                     (type) => typeSchemaEnvironment.isSubtypeOf(type,
                         contextType, SubtypeCheckMode.withNullabilities)));
@@ -626,14 +647,14 @@
               nullabilityPartErrorTemplate.withArguments(
                   expressionType,
                   declaredContextType ?? contextType,
-                  assignabilityResult.subtype,
-                  assignabilityResult.supertype,
+                  assignabilityResult.subtype!,
+                  assignabilityResult.supertype!,
                   isNonNullableByDefault));
         }
         break;
       case AssignabilityKind.unassignableNullabilityTearoff:
-        TypedTearoff typedTearoff =
-            _tearOffCall(expression, expressionType, fileOffset);
+        TypedTearoff typedTearoff = _tearOffCall(
+            expression, expressionType as InterfaceType, fileOffset);
         if (expressionType == assignabilityResult.subtype &&
             contextType == assignabilityResult.supertype) {
           result = _wrapUnassignableExpression(
@@ -650,24 +671,25 @@
               nullabilityPartErrorTemplate.withArguments(
                   typedTearoff.tearoffType,
                   declaredContextType ?? contextType,
-                  assignabilityResult.subtype,
-                  assignabilityResult.supertype,
+                  assignabilityResult.subtype!,
+                  assignabilityResult.supertype!,
                   isNonNullableByDefault));
         }
         break;
       default:
         return unhandled("${assignabilityResult}", "ensureAssignable",
-            fileOffset, helper.uri);
+            fileOffset, helper!.uri);
     }
 
     if (!identical(result, expression)) {
-      flowAnalysis?.forwardExpression(result, expression);
+      flowAnalysis.forwardExpression(result, expression);
     }
     return result;
   }
 
   Expression _wrapTearoffErrorExpression(Expression expression,
       DartType contextType, Template<Message Function(String)> template) {
+    // ignore: unnecessary_null_comparison
     assert(template != null);
     Expression errorNode = new AsExpression(
         expression,
@@ -681,7 +703,7 @@
       ..isTypeError = true
       ..fileOffset = expression.fileOffset;
     if (contextType is! InvalidType) {
-      errorNode = helper.wrapInProblem(
+      errorNode = helper!.wrapInProblem(
           errorNode,
           template.withArguments(callName.text),
           errorNode.fileOffset,
@@ -692,7 +714,7 @@
 
   Expression _wrapUnassignableExpression(Expression expression,
       DartType expressionType, DartType contextType, Message message,
-      {List<LocatedMessage> context}) {
+      {List<LocatedMessage>? context}) {
     Expression errorNode = new AsExpression(
         expression,
         // TODO(ahe): The outline phase doesn't correctly remove invalid
@@ -706,7 +728,7 @@
       ..isForNonNullableByDefault = isNonNullableByDefault
       ..fileOffset = expression.fileOffset;
     if (contextType is! InvalidType && expressionType is! InvalidType) {
-      errorNode = helper.wrapInProblem(
+      errorNode = helper!.wrapInProblem(
           errorNode, message, errorNode.fileOffset, noLength,
           context: context);
     }
@@ -716,7 +738,7 @@
   TypedTearoff _tearOffCall(
       Expression expression, InterfaceType expressionType, int fileOffset) {
     Class classNode = expressionType.classNode;
-    Member callMember = classHierarchy.getInterfaceMember(classNode, callName);
+    Member callMember = classHierarchy.getInterfaceMember(classNode, callName)!;
     assert(callMember is Procedure && callMember.kind == ProcedureKind.Method);
 
     // Replace expression with:
@@ -744,7 +766,7 @@
     if (useNewMethodInvocationEncoding) {
       tearOff = new InstanceTearOff(
           InstanceAccessKind.Instance, new VariableGet(t), callName,
-          interfaceTarget: callMember, resultType: tearoffType)
+          interfaceTarget: callMember as Procedure, resultType: tearoffType)
         ..fileOffset = fileOffset;
     } else {
       tearOff = new PropertyGet(new VariableGet(t), callName, callMember)
@@ -761,11 +783,14 @@
   /// The computation is side-effect free.
   AssignabilityResult _computeAssignabilityKind(
       DartType contextType, DartType expressionType,
-      {bool isNonNullableByDefault,
-      bool isVoidAllowed,
-      bool isExpressionTypePrecise}) {
+      {required bool isNonNullableByDefault,
+      required bool isVoidAllowed,
+      required bool isExpressionTypePrecise}) {
+    // ignore: unnecessary_null_comparison
     assert(isNonNullableByDefault != null);
+    // ignore: unnecessary_null_comparison
     assert(isVoidAllowed != null);
+    // ignore: unnecessary_null_comparison
     assert(isExpressionTypePrecise != null);
 
     // If an interface type is being assigned to a function type, see if we
@@ -773,8 +798,8 @@
     // TODO(paulberry): use resolveTypeParameter.  See findInterfaceMember.
     bool needsTearoff = false;
     if (expressionType is InterfaceType) {
-      Class classNode = (expressionType as InterfaceType).classNode;
-      Member callMember =
+      Class classNode = expressionType.classNode;
+      Member? callMember =
           classHierarchy.getInterfaceMember(classNode, callName);
       if (callMember is Procedure && callMember.kind == ProcedureKind.Method) {
         if (_shouldTearOffCall(contextType, expressionType)) {
@@ -848,7 +873,7 @@
   /// are provided, these are returned, otherwise type arguments are inferred
   /// using [receiverType].
   List<DartType> computeExtensionTypeArgument(Extension extension,
-      List<DartType> explicitTypeArguments, DartType receiverType) {
+      List<DartType>? explicitTypeArguments, DartType receiverType) {
     if (explicitTypeArguments != null) {
       assert(explicitTypeArguments.length == extension.typeParameters.length);
       return explicitTypeArguments;
@@ -878,10 +903,10 @@
   /// If none is found, [defaultTarget] is returned.
   ObjectAccessTarget _findDirectExtensionMember(
       ExtensionType receiverType, Name name, int fileOffset,
-      {ObjectAccessTarget defaultTarget}) {
-    Member targetMember;
-    Member targetTearoff;
-    ProcedureKind targetKind;
+      {required ObjectAccessTarget defaultTarget}) {
+    Member? targetMember;
+    Member? targetTearoff;
+    ProcedureKind? targetKind;
     for (ExtensionMemberDescriptor descriptor
         in receiverType.extension.members) {
       if (descriptor.name == name) {
@@ -918,7 +943,7 @@
     if (targetMember != null) {
       assert(targetKind != null);
       return new ObjectAccessTarget.extensionMember(
-          targetMember, targetTearoff, targetKind, receiverType.typeArguments);
+          targetMember, targetTearoff, targetKind!, receiverType.typeArguments);
     } else {
       return defaultTarget;
     }
@@ -938,10 +963,10 @@
   /// is flagged as a nullable extension member access. This access kind results
   /// in a compile-time error, but is used to provide a better message than just
   /// reporting that the receiver does not have a member by the given name.
-  ObjectAccessTarget _findExtensionMember(
+  ObjectAccessTarget? _findExtensionMember(
       DartType receiverType, Class classNode, Name name, int fileOffset,
       {bool setter: false,
-      ObjectAccessTarget defaultTarget,
+      ObjectAccessTarget? defaultTarget,
       bool isPotentiallyNullableAccess: false}) {
     Name otherName = name;
     bool otherIsSetter;
@@ -958,7 +983,7 @@
       otherIsSetter = !setter;
     }
 
-    Member otherMember =
+    Member? otherMember =
         _getInterfaceMember(classNode, otherName, otherIsSetter, fileOffset);
     if (otherMember != null) {
       // If we're looking for `foo` and `foo=` can be found or vice-versa then
@@ -966,13 +991,14 @@
       return defaultTarget;
     }
 
-    ExtensionAccessCandidate bestSoFar;
+    ExtensionAccessCandidate? bestSoFar;
     List<ExtensionAccessCandidate> noneMoreSpecific = [];
     library.forEachExtensionInScope((ExtensionBuilder extensionBuilder) {
-      MemberBuilder thisBuilder =
-          extensionBuilder.lookupLocalMemberByName(name, setter: setter);
-      MemberBuilder otherBuilder = extensionBuilder
-          .lookupLocalMemberByName(otherName, setter: otherIsSetter);
+      MemberBuilder? thisBuilder = extensionBuilder
+          .lookupLocalMemberByName(name, setter: setter) as MemberBuilder?;
+      MemberBuilder? otherBuilder = extensionBuilder.lookupLocalMemberByName(
+          otherName,
+          setter: otherIsSetter) as MemberBuilder?;
       if ((thisBuilder != null && !thisBuilder.isStatic) ||
           (otherBuilder != null && !otherBuilder.isStatic)) {
         DartType onType;
@@ -1013,7 +1039,7 @@
         if (typeSchemaEnvironment.isSubtypeOf(
             receiverType, onType, SubtypeCheckMode.withNullabilities)) {
           ExtensionAccessCandidate candidate = new ExtensionAccessCandidate(
-              thisBuilder ?? otherBuilder,
+              (thisBuilder ?? otherBuilder)!,
               onType,
               onTypeInstantiateToBounds,
               thisBuilder != null &&
@@ -1021,10 +1047,10 @@
                       !thisBuilder.isStatic
                   ? new ObjectAccessTarget.extensionMember(
                       setter
-                          ? thisBuilder.writeTarget
-                          : thisBuilder.invokeTarget,
+                          ? thisBuilder.writeTarget!
+                          : thisBuilder.invokeTarget!,
                       thisBuilder.readTarget,
-                      thisBuilder.kind,
+                      thisBuilder.kind!,
                       inferredTypeArguments,
                       isPotentiallyNullable: isPotentiallyNullableAccess)
                   : const ObjectAccessTarget.missing(),
@@ -1032,7 +1058,7 @@
           if (noneMoreSpecific.isNotEmpty) {
             bool isMostSpecific = true;
             for (ExtensionAccessCandidate other in noneMoreSpecific) {
-              bool isMoreSpecific =
+              bool? isMoreSpecific =
                   candidate.isMoreSpecificThan(typeSchemaEnvironment, other);
               if (isMoreSpecific != true) {
                 isMostSpecific = false;
@@ -1048,12 +1074,12 @@
           } else if (bestSoFar == null) {
             bestSoFar = candidate;
           } else {
-            bool isMoreSpecific =
-                candidate.isMoreSpecificThan(typeSchemaEnvironment, bestSoFar);
+            bool? isMoreSpecific =
+                candidate.isMoreSpecificThan(typeSchemaEnvironment, bestSoFar!);
             if (isMoreSpecific == true) {
               bestSoFar = candidate;
             } else if (isMoreSpecific == null) {
-              noneMoreSpecific.add(bestSoFar);
+              noneMoreSpecific.add(bestSoFar!);
               noneMoreSpecific.add(candidate);
               bestSoFar = null;
             }
@@ -1062,7 +1088,7 @@
       }
     });
     if (bestSoFar != null) {
-      return bestSoFar.target;
+      return bestSoFar!.target;
     } else {
       if (noneMoreSpecific.isNotEmpty) {
         return new AmbiguousExtensionAccessTarget(noneMoreSpecific);
@@ -1087,6 +1113,7 @@
       {bool setter: false,
       bool instrumented: true,
       bool includeExtensionMethods: false}) {
+    // ignore: unnecessary_null_comparison
     assert(receiverType != null && isKnown(receiverType));
 
     DartType receiverBound = resolveTypeParameter(receiverType);
@@ -1101,7 +1128,7 @@
         : coreTypes.objectClass;
 
     if (isReceiverTypePotentiallyNullable) {
-      Member member =
+      Member? member =
           _getInterfaceMember(coreTypes.objectClass, name, setter, fileOffset);
       if (member != null) {
         // Null implements all Object members so this is not considered a
@@ -1109,7 +1136,7 @@
         return new ObjectAccessTarget.objectMember(member);
       }
       if (includeExtensionMethods && receiverBound is! DynamicType) {
-        ObjectAccessTarget target = _findExtensionMember(
+        ObjectAccessTarget? target = _findExtensionMember(
             isNonNullableByDefault ? receiverType : receiverBound,
             coreTypes.objectClass,
             name,
@@ -1144,8 +1171,8 @@
       }
     }
 
-    ObjectAccessTarget target;
-    Member interfaceMember =
+    ObjectAccessTarget? target;
+    Member? interfaceMember =
         _getInterfaceMember(classNode, name, setter, fileOffset);
     if (interfaceMember != null) {
       target = new ObjectAccessTarget.interfaceMember(interfaceMember,
@@ -1171,7 +1198,7 @@
         receiverBound != const DynamicType() &&
         (target.isInstanceMember || target.isObjectMember)) {
       instrumentation?.record(uriForInstrumentation, fileOffset, 'target',
-          new InstrumentationValueForMember(target.member));
+          new InstrumentationValueForMember(target.member!));
     }
 
     if (target.isMissing && includeExtensionMethods) {
@@ -1192,7 +1219,7 @@
             fileOffset,
             setter: setter,
             defaultTarget: target,
-            isPotentiallyNullableAccess: true);
+            isPotentiallyNullableAccess: true)!;
       } else {
         target = _findExtensionMember(
             isNonNullableByDefault ? receiverType : receiverBound,
@@ -1200,7 +1227,7 @@
             name,
             fileOffset,
             setter: setter,
-            defaultTarget: target);
+            defaultTarget: target)!;
       }
     }
     return target;
@@ -1208,20 +1235,22 @@
 
   /// If target is missing on a non-dynamic receiver, an error is reported
   /// using [errorTemplate] and an invalid expression is returned.
-  Expression reportMissingInterfaceMember(
+  Expression? reportMissingInterfaceMember(
       ObjectAccessTarget target,
       DartType receiverType,
       Name name,
       int fileOffset,
       Template<Message Function(String, DartType, bool)> errorTemplate) {
+    // ignore: unnecessary_null_comparison
     assert(receiverType != null && isKnown(receiverType));
+    // ignore: unnecessary_null_comparison
     if (!isTopLevel && target.isMissing && errorTemplate != null) {
       int length = name.text.length;
       if (identical(name.text, callName.text) ||
           identical(name.text, unaryMinusName.text)) {
         length = 1;
       }
-      return helper.buildProblem(
+      return helper!.buildProblem(
           errorTemplate.withArguments(name.text,
               resolveTypeParameter(receiverType), isNonNullableByDefault),
           fileOffset,
@@ -1257,7 +1286,7 @@
   ///    }
   ///
   DartType computeTypeFromSuperClass(Class superClass, DartType type) {
-    if (needsLegacyErasure(thisType.classNode, superClass)) {
+    if (needsLegacyErasure(thisType!.classNode, superClass)) {
       type = legacyErasure(type);
     }
     return type;
@@ -1292,14 +1321,14 @@
       case ObjectAccessTargetKind.instanceMember:
       case ObjectAccessTargetKind.objectMember:
       case ObjectAccessTargetKind.nullableInstanceMember:
-        return getGetterTypeForMemberTarget(target.member, receiverType);
+        return getGetterTypeForMemberTarget(target.member!, receiverType);
       case ObjectAccessTargetKind.extensionMember:
       case ObjectAccessTargetKind.nullableExtensionMember:
         switch (target.extensionMethodKind) {
           case ProcedureKind.Method:
           case ProcedureKind.Operator:
-            FunctionType functionType =
-                target.member.function.computeFunctionType(library.nonNullable);
+            FunctionType functionType = target.member!.function!
+                .computeFunctionType(library.nonNullable);
             List<TypeParameter> extensionTypeParameters = functionType
                 .typeParameters
                 .take(target.inferredExtensionTypeArguments.length)
@@ -1321,8 +1350,8 @@
             }
             return resultType;
           case ProcedureKind.Getter:
-            FunctionType functionType =
-                target.member.function.computeFunctionType(library.nonNullable);
+            FunctionType functionType = target.member!.function!
+                .computeFunctionType(library.nonNullable);
             List<TypeParameter> extensionTypeParameters = functionType
                 .typeParameters
                 .take(target.inferredExtensionTypeArguments.length)
@@ -1340,7 +1369,7 @@
             break;
         }
     }
-    throw unhandled('$target', 'getGetterType', null, null);
+    throw unhandled('$target', 'getGetterType', -1, null);
   }
 
   /// Returns the getter type of [interfaceMember] on a receiver of type
@@ -1359,7 +1388,7 @@
   ///
   DartType getGetterTypeForMemberTarget(
       Member interfaceMember, DartType receiverType) {
-    Class memberClass = interfaceMember.enclosingClass;
+    Class memberClass = interfaceMember.enclosingClass!;
     assert(interfaceMember is Field || interfaceMember is Procedure,
         "Unexpected interface member $interfaceMember.");
     DartType calleeType = interfaceMember.getterType;
@@ -1367,7 +1396,7 @@
       receiverType = resolveTypeParameter(receiverType);
       if (receiverType is InterfaceType) {
         List<DartType> castedTypeArguments = classHierarchy
-            .getTypeArgumentsAsInstanceOf(receiverType, memberClass);
+            .getTypeArgumentsAsInstanceOf(receiverType, memberClass)!;
         calleeType = Substitution.fromPairs(
                 memberClass.typeParameters, castedTypeArguments)
             .substituteType(calleeType);
@@ -1413,27 +1442,27 @@
       case ObjectAccessTargetKind.objectMember:
       case ObjectAccessTargetKind.nullableInstanceMember:
         return _getFunctionType(
-            getGetterTypeForMemberTarget(target.member, receiverType));
+            getGetterTypeForMemberTarget(target.member!, receiverType));
       case ObjectAccessTargetKind.extensionMember:
       case ObjectAccessTargetKind.nullableExtensionMember:
         switch (target.extensionMethodKind) {
           case ProcedureKind.Method:
           case ProcedureKind.Operator:
-            FunctionType functionType =
-                target.member.function.computeFunctionType(library.nonNullable);
+            FunctionType functionType = target.member!.function!
+                .computeFunctionType(library.nonNullable);
             if (!isNonNullableByDefault) {
-              functionType = legacyErasure(functionType);
+              functionType = legacyErasure(functionType) as FunctionType;
             }
             return functionType;
           case ProcedureKind.Getter:
             // TODO(johnniwinther): Handle implicit .call on extension getter.
-            return _getFunctionType(target.member.function.returnType);
+            return _getFunctionType(target.member!.function!.returnType);
           case ProcedureKind.Setter:
           case ProcedureKind.Factory:
             break;
         }
     }
-    throw unhandled('$target', 'getFunctionType', null, null);
+    throw unhandled('$target', 'getFunctionType', -1, null);
   }
 
   /// Returns the type of the receiver argument in an access to an extension
@@ -1458,15 +1487,14 @@
       case ObjectAccessTargetKind.objectMember:
       case ObjectAccessTargetKind.nullableInstanceMember:
         FunctionType functionType = _getFunctionType(
-            getGetterTypeForMemberTarget(target.member, receiverType));
+            getGetterTypeForMemberTarget(target.member!, receiverType));
         return functionType.returnType;
-        break;
       case ObjectAccessTargetKind.extensionMember:
       case ObjectAccessTargetKind.nullableExtensionMember:
         switch (target.extensionMethodKind) {
           case ProcedureKind.Operator:
-            FunctionType functionType =
-                target.member.function.computeFunctionType(library.nonNullable);
+            FunctionType functionType = target.member!.function!
+                .computeFunctionType(library.nonNullable);
             DartType returnType = functionType.returnType;
             if (functionType.typeParameters.isNotEmpty) {
               Substitution substitution = Substitution.fromPairs(
@@ -1479,9 +1507,8 @@
             }
             return returnType;
           default:
-            throw unhandled('$target', 'getFunctionType', null, null);
+            throw unhandled('$target', 'getFunctionType', -1, null);
         }
-        break;
       case ObjectAccessTargetKind.never:
         return const NeverType.nonNullable();
       case ObjectAccessTargetKind.invalid:
@@ -1503,7 +1530,7 @@
       case ObjectAccessTargetKind.objectMember:
       case ObjectAccessTargetKind.nullableInstanceMember:
         FunctionType functionType = _getFunctionType(
-            getGetterTypeForMemberTarget(target.member, receiverType));
+            getGetterTypeForMemberTarget(target.member!, receiverType));
         if (functionType.positionalParameters.length > index) {
           return functionType.positionalParameters[index];
         }
@@ -1511,7 +1538,7 @@
       case ObjectAccessTargetKind.extensionMember:
       case ObjectAccessTargetKind.nullableExtensionMember:
         FunctionType functionType =
-            target.member.function.computeFunctionType(library.nonNullable);
+            target.member!.function!.computeFunctionType(library.nonNullable);
         if (functionType.positionalParameters.length > index + 1) {
           DartType keyType = functionType.positionalParameters[index + 1];
           if (functionType.typeParameters.isNotEmpty) {
@@ -1564,7 +1591,7 @@
       case ObjectAccessTargetKind.objectMember:
       case ObjectAccessTargetKind.nullableInstanceMember:
         FunctionType functionType = _getFunctionType(
-            getGetterTypeForMemberTarget(target.member, receiverType));
+            getGetterTypeForMemberTarget(target.member!, receiverType));
         if (functionType.positionalParameters.length >= 1) {
           return functionType.positionalParameters[0];
         }
@@ -1573,8 +1600,8 @@
       case ObjectAccessTargetKind.nullableExtensionMember:
         switch (target.extensionMethodKind) {
           case ProcedureKind.Operator:
-            FunctionType functionType =
-                target.member.function.computeFunctionType(library.nonNullable);
+            FunctionType functionType = target.member!.function!
+                .computeFunctionType(library.nonNullable);
             if (functionType.positionalParameters.length >= 2) {
               DartType keyType = functionType.positionalParameters[1];
               if (functionType.typeParameters.isNotEmpty) {
@@ -1590,7 +1617,7 @@
             }
             break;
           default:
-            throw unhandled('$target', 'getFunctionType', null, null);
+            throw unhandled('$target', 'getFunctionType', -1, null);
         }
         break;
       case ObjectAccessTargetKind.invalid:
@@ -1622,13 +1649,13 @@
   ///    Extension<int, String>(null)[0] = 'foo'; // The value type is `String`.
   ///
   DartType getIndexSetValueType(
-      ObjectAccessTarget target, DartType receiverType) {
+      ObjectAccessTarget target, DartType? receiverType) {
     switch (target.kind) {
       case ObjectAccessTargetKind.instanceMember:
       case ObjectAccessTargetKind.objectMember:
       case ObjectAccessTargetKind.nullableInstanceMember:
         FunctionType functionType = _getFunctionType(
-            getGetterTypeForMemberTarget(target.member, receiverType));
+            getGetterTypeForMemberTarget(target.member!, receiverType!));
         if (functionType.positionalParameters.length >= 2) {
           return functionType.positionalParameters[1];
         }
@@ -1637,8 +1664,8 @@
       case ObjectAccessTargetKind.nullableExtensionMember:
         switch (target.extensionMethodKind) {
           case ProcedureKind.Operator:
-            FunctionType functionType =
-                target.member.function.computeFunctionType(library.nonNullable);
+            FunctionType functionType = target.member!.function!
+                .computeFunctionType(library.nonNullable);
             if (functionType.positionalParameters.length >= 3) {
               DartType indexType = functionType.positionalParameters[2];
               if (functionType.typeParameters.isNotEmpty) {
@@ -1654,7 +1681,7 @@
             }
             break;
           default:
-            throw unhandled('$target', 'getFunctionType', null, null);
+            throw unhandled('$target', 'getFunctionType', -1, null);
         }
         break;
       case ObjectAccessTargetKind.invalid:
@@ -1676,7 +1703,7 @@
       if (!isNonNullableByDefault) {
         calleeType = legacyErasure(calleeType);
       }
-      return calleeType;
+      return calleeType as FunctionType;
     }
     return unknownFunction;
   }
@@ -1687,9 +1714,9 @@
       if (!isNonNullableByDefault) {
         calleeType = legacyErasure(calleeType);
       }
-      return calleeType;
+      return calleeType as FunctionType;
     } else if (calleeType is InterfaceType) {
-      Member member =
+      Member? member =
           _getInterfaceMember(calleeType.classNode, callName, false, -1);
       if (member != null) {
         DartType callType = getGetterTypeForMemberTarget(member, calleeType);
@@ -1697,16 +1724,16 @@
           if (!isNonNullableByDefault) {
             callType = legacyErasure(callType);
           }
-          return callType;
+          return callType as FunctionType;
         }
       }
     }
     return unknownFunction;
   }
 
-  DartType getDerivedTypeArgumentOf(DartType type, Class class_) {
+  DartType? getDerivedTypeArgumentOf(DartType type, Class class_) {
     if (type is InterfaceType) {
-      List<DartType> typeArgumentsAsInstanceOfClass =
+      List<DartType>? typeArgumentsAsInstanceOfClass =
           classHierarchy.getTypeArgumentsAsInstanceOf(type, class_);
       if (typeArgumentsAsInstanceOfClass != null) {
         return typeArgumentsAsInstanceOfClass[0];
@@ -1719,7 +1746,7 @@
   /// Otherwise return the given [member].
   Member getRealTarget(Member member) {
     if (member is Procedure && member.isForwardingStub) {
-      return member.abstractForwardingStubTarget;
+      return member.abstractForwardingStubTarget!;
     }
     return member;
   }
@@ -1736,8 +1763,8 @@
       case ObjectAccessTargetKind.instanceMember:
       case ObjectAccessTargetKind.objectMember:
       case ObjectAccessTargetKind.nullableInstanceMember:
-        Member interfaceMember = target.member;
-        Class memberClass = interfaceMember.enclosingClass;
+        Member interfaceMember = target.member!;
+        Class memberClass = interfaceMember.enclosingClass!;
         DartType setterType;
         if (interfaceMember is Procedure) {
           assert(interfaceMember.kind == ProcedureKind.Setter);
@@ -1750,7 +1777,7 @@
           setterType = interfaceMember.type;
         } else {
           throw unhandled(interfaceMember.runtimeType.toString(),
-              'getSetterType', null, null);
+              'getSetterType', -1, null);
         }
         if (memberClass.typeParameters.isNotEmpty) {
           receiverType = resolveTypeParameter(receiverType);
@@ -1758,7 +1785,7 @@
             setterType = Substitution.fromPairs(
                     memberClass.typeParameters,
                     classHierarchy.getTypeArgumentsAsInstanceOf(
-                        receiverType, memberClass))
+                        receiverType, memberClass)!)
                 .substituteType(setterType);
           }
         }
@@ -1770,8 +1797,8 @@
       case ObjectAccessTargetKind.nullableExtensionMember:
         switch (target.extensionMethodKind) {
           case ProcedureKind.Setter:
-            FunctionType functionType =
-                target.member.function.computeFunctionType(library.nonNullable);
+            FunctionType functionType = target.member!.function!
+                .computeFunctionType(library.nonNullable);
             List<TypeParameter> extensionTypeParameters = functionType
                 .typeParameters
                 .take(target.inferredExtensionTypeArguments.length)
@@ -1796,7 +1823,7 @@
       case ObjectAccessTargetKind.nullableCallFunction:
         break;
     }
-    throw unhandled(target.runtimeType.toString(), 'getSetterType', null, null);
+    throw unhandled(target.runtimeType.toString(), 'getSetterType', -1, null);
   }
 
   DartType getTypeArgumentOf(DartType type, Class class_) {
@@ -1810,10 +1837,6 @@
   /// Modifies a type as appropriate when inferring a declared variable's type.
   DartType inferDeclarationType(DartType initializerType,
       {bool forSyntheticVariable: false}) {
-    if (initializerType == null) {
-      assert(isTopLevel, "No initializer type provided.");
-      return null;
-    }
     if (initializerType is NullType) {
       // If the initializer type is Null or bottom, the inferred type is
       // dynamic.
@@ -1832,7 +1855,7 @@
     assert(variable.isImplicitlyTyped);
     assert(variable.initializer != null);
     ExpressionInferenceResult result = inferExpression(
-        variable.initializer, const UnknownType(), true,
+        variable.initializer!, const UnknownType(), true,
         isVoidAllowed: true);
     variable.initializer = result.expression..parent = variable;
     DartType inferredType =
@@ -1847,7 +1870,7 @@
     assert(variable.isImplicitlyTyped);
     assert(variable.initializer != null);
     ExpressionInferenceResult result = inferNullAwareExpression(
-        variable.initializer, const UnknownType(), true,
+        variable.initializer!, const UnknownType(), true,
         isVoidAllowed: true);
 
     Link<NullAwareGuard> nullAwareGuards = result.nullAwareGuards;
@@ -1862,13 +1885,13 @@
   }
 
   NullAwareGuard createNullAwareGuard(VariableDeclaration variable) {
-    Member equalsMember =
+    Member? equalsMember =
         findInterfaceMember(variable.type, equalsName, variable.fileOffset)
             .member;
     // Ensure operator == member even for `Never`.
     equalsMember ??= findInterfaceMember(const DynamicType(), equalsName, -1,
             instrumented: false)
-        .member;
+        .member!;
     return new NullAwareGuard(
         variable, variable.fileOffset, equalsMember, this);
   }
@@ -1878,10 +1901,10 @@
       Message message,
       int fileOffset,
       int length,
-      {List<LocatedMessage> context}) {
+      {List<LocatedMessage>? context}) {
     return createNullAwareExpressionInferenceResult(
         result.inferredType,
-        helper.wrapInProblem(
+        helper!.wrapInProblem(
             result.nullAwareAction, message, fileOffset, length,
             context: context),
         result.nullAwareGuards);
@@ -1890,7 +1913,7 @@
   ExpressionInferenceResult createNullAwareExpressionInferenceResult(
       DartType inferredType,
       Expression expression,
-      Link<NullAwareGuard> nullAwareGuards) {
+      Link<NullAwareGuard>? nullAwareGuards) {
     if (nullAwareGuards != null && nullAwareGuards.isNotEmpty) {
       return new NullAwareExpressionInferenceResult(
           computeNullable(inferredType),
@@ -1919,6 +1942,7 @@
 
     // `null` should never be used as the type context.  An instance of
     // `UnknownType` should be used instead.
+    // ignore: unnecessary_null_comparison
     assert(typeContext != null);
 
     // For full (non-top level) inference, we need access to the
@@ -1928,7 +1952,9 @@
     // When doing top level inference, we skip subexpressions whose type isn't
     // needed so that we don't induce bogus dependencies on fields mentioned in
     // those subexpressions.
-    if (!typeNeeded) return new ExpressionInferenceResult(null, expression);
+    if (!typeNeeded) {
+      return new ExpressionInferenceResult(const UnknownType(), expression);
+    }
 
     InferenceVisitor visitor = new InferenceVisitor(this);
     ExpressionInferenceResult result;
@@ -1940,6 +1966,7 @@
       result = expression.accept1(visitor, typeContext);
     }
     DartType inferredType = result.inferredType;
+    // ignore: unnecessary_null_comparison
     assert(inferredType != null,
         "No type inferred for $expression (${expression.runtimeType}).");
     if (inferredType is VoidType && !isVoidAllowed) {
@@ -2009,20 +2036,22 @@
   @override
   InferredFunctionBody inferFunctionBody(InferenceHelper helper, int fileOffset,
       DartType returnType, AsyncMarker asyncMarker, Statement body) {
+    // ignore: unnecessary_null_comparison
     assert(body != null);
+    // ignore: unnecessary_null_comparison
     assert(closureContext == null);
     this.helper = helper;
     closureContext = new ClosureContext(this, asyncMarker, returnType, false);
     StatementInferenceResult result = inferStatement(body);
     if (dataForTesting != null) {
       if (!flowAnalysis.isReachable) {
-        dataForTesting.flowAnalysisResult.functionBodiesThatDontComplete
+        dataForTesting!.flowAnalysisResult.functionBodiesThatDontComplete
             .add(body);
       }
     }
     result =
-        closureContext.handleImplicitReturn(this, body, result, fileOffset);
-    DartType futureValueType = closureContext.futureValueType;
+        closureContext!.handleImplicitReturn(this, body, result, fileOffset);
+    DartType? futureValueType = closureContext!.futureValueType;
     assert(
         !(isNonNullableByDefault &&
             asyncMarker == AsyncMarker.Async &&
@@ -2037,15 +2066,15 @@
 
   InvocationInferenceResult inferInvocation(DartType typeContext, int offset,
       FunctionType calleeType, Arguments arguments,
-      {List<VariableDeclaration> hoistedExpressions,
+      {List<VariableDeclaration>? hoistedExpressions,
       bool isSpecialCasedBinaryOperator: false,
       bool isSpecialCasedTernaryOperator: false,
-      DartType receiverType,
+      DartType? receiverType,
       bool skipTypeArgumentInference: false,
       bool isConst: false,
       bool isImplicitExtensionMember: false,
       bool isImplicitCall: false,
-      Member staticTarget,
+      Member? staticTarget,
       bool isExtensionMemberInvocation = false}) {
     int extensionTypeParameterCount = getExtensionTypeParameterCount(arguments);
     if (extensionTypeParameterCount != 0) {
@@ -2077,15 +2106,15 @@
       int offset,
       FunctionType calleeType,
       Arguments arguments,
-      List<VariableDeclaration> hoistedExpressions,
+      List<VariableDeclaration>? hoistedExpressions,
       {bool isSpecialCasedBinaryOperator: false,
       bool isSpecialCasedTernaryOperator: false,
-      DartType receiverType,
+      DartType? receiverType,
       bool skipTypeArgumentInference: false,
       bool isConst: false,
       bool isImplicitExtensionMember: false,
       bool isImplicitCall: false,
-      Member staticTarget}) {
+      Member? staticTarget}) {
     FunctionType extensionFunctionType = new FunctionType(
         [calleeType.positionalParameters.first],
         const DynamicType(),
@@ -2120,8 +2149,8 @@
         requiredParameterCount: calleeType.requiredParameterCount - 1,
         namedParameters: calleeType.namedParameters,
         typeParameters: targetTypeParameters);
-    targetFunctionType =
-        extensionSubstitution.substituteType(targetFunctionType);
+    targetFunctionType = extensionSubstitution
+        .substituteType(targetFunctionType) as FunctionType;
     Arguments targetArguments = engine.forest.createArguments(
         arguments.fileOffset, arguments.positional.skip(1).toList(),
         named: arguments.named, types: getExplicitTypeArguments(arguments));
@@ -2153,16 +2182,19 @@
       int offset,
       FunctionType calleeType,
       Arguments arguments,
-      List<VariableDeclaration> hoistedExpressions,
+      List<VariableDeclaration>? hoistedExpressions,
       {bool isSpecialCasedBinaryOperator: false,
       bool isSpecialCasedTernaryOperator: false,
-      DartType receiverType,
+      DartType? receiverType,
       bool skipTypeArgumentInference: false,
       bool isConst: false,
       bool isImplicitExtensionMember: false,
-      bool isImplicitCall,
-      Member staticTarget,
+      required bool isImplicitCall,
+      Member? staticTarget,
       bool isExtensionMemberInvocation: false}) {
+    // [receiverType] must be provided for special-cased operators.
+    assert(!isSpecialCasedBinaryOperator && !isSpecialCasedTernaryOperator ||
+        receiverType != null);
     List<TypeParameter> calleeTypeParameters = calleeType.typeParameters;
     if (calleeTypeParameters.isNotEmpty) {
       // It's possible that one of the callee type parameters might match a type
@@ -2178,20 +2210,21 @@
       calleeType = fresh.applyToFunctionType(calleeType);
       calleeTypeParameters = fresh.freshTypeParameters;
     }
-    List<DartType> explicitTypeArguments = getExplicitTypeArguments(arguments);
+    List<DartType>? explicitTypeArguments = getExplicitTypeArguments(arguments);
     bool inferenceNeeded = !skipTypeArgumentInference &&
         explicitTypeArguments == null &&
         calleeTypeParameters.isNotEmpty;
     bool typeChecksNeeded = !isTopLevel;
-    List<DartType> inferredTypes;
-    Substitution substitution;
-    List<DartType> formalTypes;
-    List<DartType> actualTypes;
+    List<DartType>? inferredTypes;
+    Substitution? substitution;
+    List<DartType>? formalTypes;
+    List<DartType>? actualTypes;
     if (inferenceNeeded || typeChecksNeeded) {
       formalTypes = [];
       actualTypes = [];
     }
     if (inferenceNeeded) {
+      // ignore: unnecessary_null_comparison
       if (isConst && typeContext != null) {
         typeContext = new TypeVariableEliminator(
                 bottomType,
@@ -2244,12 +2277,12 @@
         if (isSpecialCasedBinaryOperator) {
           inferredFormalType =
               typeSchemaEnvironment.getContextTypeOfSpecialCasedBinaryOperator(
-                  typeContext, receiverType, inferredFormalType,
+                  typeContext, receiverType!, inferredFormalType,
                   isNonNullableByDefault: isNonNullableByDefault);
         } else if (isSpecialCasedTernaryOperator) {
           inferredFormalType =
               typeSchemaEnvironment.getContextTypeOfSpecialCasedTernaryOperator(
-                  typeContext, receiverType, inferredFormalType,
+                  typeContext, receiverType!, inferredFormalType,
                   isNonNullableByDefault: isNonNullableByDefault);
         }
         ExpressionInferenceResult result = inferExpression(
@@ -2261,37 +2294,38 @@
                 isSpecialCasedBinaryOperator ||
                 isSpecialCasedTernaryOperator ||
                 typeChecksNeeded);
-        inferredType = result.inferredType == null || isNonNullableByDefault
+        inferredType = identical(result.inferredType, noInferredType) ||
+                isNonNullableByDefault
             ? result.inferredType
             : legacyErasure(result.inferredType);
         Expression expression =
             _hoist(result.expression, inferredType, hoistedExpressions);
         if (isIdentical && arguments.positional.length == 2) {
           if (position == 0) {
-            flowAnalysis?.equalityOp_rightBegin(expression, inferredType);
+            flowAnalysis.equalityOp_rightBegin(expression, inferredType);
           } else {
-            flowAnalysis?.equalityOp_end(
-                arguments.parent, expression, inferredType);
+            flowAnalysis.equalityOp_end(
+                arguments.parent as Expression, expression, inferredType);
           }
         }
         arguments.positional[position] = expression..parent = arguments;
       }
       if (inferenceNeeded || typeChecksNeeded) {
-        formalTypes.add(formalType);
-        actualTypes.add(inferredType);
+        formalTypes!.add(formalType);
+        actualTypes!.add(inferredType);
       }
     }
     if (isSpecialCasedBinaryOperator) {
       calleeType = replaceReturnType(
           calleeType,
           typeSchemaEnvironment.getTypeOfSpecialCasedBinaryOperator(
-              receiverType, actualTypes[0],
+              receiverType!, actualTypes![0],
               isNonNullableByDefault: isNonNullableByDefault));
     } else if (isSpecialCasedTernaryOperator) {
       calleeType = replaceReturnType(
           calleeType,
           typeSchemaEnvironment.getTypeOfSpecialCasedTernaryOperator(
-              receiverType, actualTypes[0], actualTypes[1], library.library));
+              receiverType!, actualTypes![0], actualTypes[1], library.library));
     }
     for (NamedExpression namedArgument in arguments.named) {
       DartType formalType =
@@ -2305,16 +2339,16 @@
               ? inferredFormalType
               : legacyErasure(inferredFormalType),
           inferenceNeeded || isSpecialCasedBinaryOperator || typeChecksNeeded);
-      DartType inferredType =
-          result.inferredType == null || isNonNullableByDefault
-              ? result.inferredType
-              : legacyErasure(result.inferredType);
+      DartType inferredType = identical(result.inferredType, noInferredType) ||
+              isNonNullableByDefault
+          ? result.inferredType
+          : legacyErasure(result.inferredType);
       Expression expression =
           _hoist(result.expression, inferredType, hoistedExpressions);
       namedArgument.value = expression..parent = namedArgument;
       if (inferenceNeeded || typeChecksNeeded) {
-        formalTypes.add(formalType);
-        actualTypes.add(inferredType);
+        formalTypes!.add(formalType);
+        actualTypes!.add(inferredType);
       }
     }
 
@@ -2323,13 +2357,13 @@
     if (named.length == 2) {
       if (named[0].name == named[1].name) {
         String name = named[1].name;
-        Expression error = helper.buildProblem(
+        Expression error = helper!.buildProblem(
             templateDuplicatedNamedArgument.withArguments(name),
             named[1].fileOffset,
             name.length);
         arguments.named = [new NamedExpression(named[1].name, error)];
-        formalTypes.removeLast();
-        actualTypes.removeLast();
+        formalTypes!.removeLast();
+        actualTypes!.removeLast();
       }
     } else if (named.length > 2) {
       Map<String, NamedExpression> seenNames = <String, NamedExpression>{};
@@ -2340,14 +2374,14 @@
         String name = expression.name;
         if (seenNames.containsKey(name)) {
           hasProblem = true;
-          NamedExpression prevNamedExpression = seenNames[name];
-          prevNamedExpression.value = helper.buildProblem(
+          NamedExpression prevNamedExpression = seenNames[name]!;
+          prevNamedExpression.value = helper!.buildProblem(
               templateDuplicatedNamedArgument.withArguments(name),
               expression.fileOffset,
               name.length)
             ..parent = prevNamedExpression;
-          formalTypes.removeAt(namedTypeIndex);
-          actualTypes.removeAt(namedTypeIndex);
+          formalTypes!.removeAt(namedTypeIndex);
+          actualTypes!.removeAt(namedTypeIndex);
         } else {
           seenNames[name] = expression;
           uniqueNamed.add(expression);
@@ -2366,7 +2400,7 @@
           formalTypes,
           actualTypes,
           typeContext,
-          inferredTypes,
+          inferredTypes!,
           library.library);
       assert(inferredTypes.every((type) => isKnown(type)),
           "Unknown type(s) in inferred types: $inferredTypes.");
@@ -2380,14 +2414,14 @@
       arguments.types.addAll(inferredTypes);
       if (dataForTesting != null) {
         assert(arguments.fileOffset != TreeNode.noOffset);
-        dataForTesting.typeInferenceResult.inferredTypeArguments[arguments] =
+        dataForTesting!.typeInferenceResult.inferredTypeArguments[arguments] =
             inferredTypes;
       }
     }
     List<DartType> positionalArgumentTypes = [];
     List<NamedType> namedArgumentTypes = [];
     if (typeChecksNeeded && !identical(calleeType, unknownFunction)) {
-      LocatedMessage argMessage = helper.checkArgumentsForType(
+      LocatedMessage? argMessage = helper!.checkArgumentsForType(
           calleeType, arguments, offset,
           isExtensionMemberInvocation: isExtensionMemberInvocation);
       if (argMessage != null) {
@@ -2397,20 +2431,20 @@
             argMessage.messageObject,
             argMessage.charOffset,
             argMessage.length,
-            helper,
+            helper!,
             isInapplicable: true);
       } else {
         // Argument counts and names match. Compare types.
         int positionalShift = isImplicitExtensionMember ? 1 : 0;
         int numPositionalArgs = arguments.positional.length - positionalShift;
-        for (int i = 0; i < formalTypes.length; i++) {
+        for (int i = 0; i < formalTypes!.length; i++) {
           DartType formalType = formalTypes[i];
           DartType expectedType = substitution != null
               ? substitution.substituteType(formalType)
               : formalType;
-          DartType actualType = actualTypes[i];
+          DartType actualType = actualTypes![i];
           Expression expression;
-          NamedExpression namedExpression;
+          NamedExpression? namedExpression;
           if (i < numPositionalArgs) {
             expression = arguments.positional[positionalShift + i];
             positionalArgumentTypes.add(actualType);
@@ -2444,8 +2478,8 @@
     }
     DartType inferredType;
     if (substitution != null) {
-      calleeType =
-          substitution.substituteType(calleeType.withoutTypeParameters);
+      calleeType = substitution.substituteType(calleeType.withoutTypeParameters)
+          as FunctionType;
     }
     inferredType = calleeType.returnType;
     assert(
@@ -2455,14 +2489,14 @@
 
     if (!isNonNullableByDefault) {
       inferredType = legacyErasure(inferredType);
-      calleeType = legacyErasure(calleeType);
+      calleeType = legacyErasure(calleeType) as FunctionType;
     }
 
     return new SuccessfulInferenceResult(inferredType, calleeType);
   }
 
-  FunctionType inferLocalFunction(FunctionNode function, DartType typeContext,
-      int fileOffset, DartType returnContext) {
+  FunctionType inferLocalFunction(FunctionNode function, DartType? typeContext,
+      int fileOffset, DartType? returnContext) {
     bool hasImplicitReturnType = false;
     if (returnContext == null) {
       hasImplicitReturnType = true;
@@ -2477,7 +2511,7 @@
         inferMetadataKeepingHelper(parameter, parameter.annotations);
         if (parameter.initializer != null) {
           ExpressionInferenceResult initializerResult = inferExpression(
-              parameter.initializer, parameter.type, !isTopLevel);
+              parameter.initializer!, parameter.type, !isTopLevel);
           parameter.initializer = initializerResult.expression
             ..parent = parameter;
         }
@@ -2485,8 +2519,8 @@
       for (VariableDeclaration parameter in function.namedParameters) {
         flowAnalysis.declare(parameter, true);
         inferMetadataKeepingHelper(parameter, parameter.annotations);
-        ExpressionInferenceResult initializerResult =
-            inferExpression(parameter.initializer, parameter.type, !isTopLevel);
+        ExpressionInferenceResult initializerResult = inferExpression(
+            parameter.initializer!, parameter.type, !isTopLevel);
         parameter.initializer = initializerResult.expression
           ..parent = parameter;
       }
@@ -2512,8 +2546,8 @@
     // set of matched type parameters and `(Q0, ..., Qm)` be the set of matched
     // formal parameter types, and let `N` be the return type.
     Substitution substitution;
-    List<DartType> formalTypesFromContext =
-        new List<DartType>.filled(formals.length, null);
+    List<DartType?> formalTypesFromContext =
+        new List<DartType?>.filled(formals.length, null);
     if (typeContext is FunctionType &&
         typeContext.typeParameters.length == typeParameters.length) {
       for (int i = 0; i < formals.length; i++) {
@@ -2522,7 +2556,7 @@
               getPositionalParameterType(typeContext, i);
         } else {
           formalTypesFromContext[i] =
-              getNamedParameterType(typeContext, formals[i].name);
+              getNamedParameterType(typeContext, formals[i].name!);
         }
       }
       returnContext = typeContext.returnType;
@@ -2553,12 +2587,12 @@
     // Otherwise, if `Qi` is not `_`, let `Ri` be the greatest closure of
     // `Qi[T/S]` with respect to `?`.  Otherwise, let `Ri` be `dynamic`.
     for (int i = 0; i < formals.length; i++) {
-      VariableDeclarationImpl formal = formals[i];
+      VariableDeclarationImpl formal = formals[i] as VariableDeclarationImpl;
       if (formal.isImplicitlyTyped) {
         DartType inferredType;
         if (formalTypesFromContext[i] != null) {
           inferredType = computeGreatestClosure2(
-              substitution.substituteType(formalTypesFromContext[i]));
+              substitution.substituteType(formalTypesFromContext[i]!));
           if (typeSchemaEnvironment.isSubtypeOf(
               inferredType,
               const NullType(),
@@ -2574,7 +2608,7 @@
             'type', new InstrumentationValueForType(inferredType));
         formal.type = demoteTypeInLibrary(inferredType, library.library);
         if (dataForTesting != null) {
-          dataForTesting.typeInferenceResult.inferredVariableTypes[formal] =
+          dataForTesting!.typeInferenceResult.inferredVariableTypes[formal] =
               formal.type;
         }
       }
@@ -2591,23 +2625,24 @@
             !formal.hasDeclaredInitializer) {
           library.addProblem(
               templateOptionalNonNullableWithoutInitializerError.withArguments(
-                  formal.name, formal.type, isNonNullableByDefault),
+                  formal.name!, formal.type, isNonNullableByDefault),
               formal.fileOffset,
-              formal.name.length,
+              formal.name!.length,
               library.importUri);
         }
       }
     }
 
     if (isNonNullableByDefault) {
-      for (VariableDeclarationImpl formal in function.namedParameters) {
+      for (VariableDeclaration parameter in function.namedParameters) {
+        VariableDeclarationImpl formal = parameter as VariableDeclarationImpl;
         // Required named parameters shouldn't have initializers.
         if (formal.isRequired && formal.hasDeclaredInitializer) {
           library.addProblem(
               templateRequiredNamedParameterHasDefaultValueError
-                  .withArguments(formal.name),
+                  .withArguments(formal.name!),
               formal.fileOffset,
-              formal.name.length,
+              formal.name!.length,
               library.importUri);
         }
       }
@@ -2623,33 +2658,30 @@
     // Apply type inference to `B` in return context `N’`, with any references
     // to `xi` in `B` having type `Pi`.  This produces `B’`.
     bool needToSetReturnType = hasImplicitReturnType;
-    ClosureContext oldClosureContext = this.closureContext;
+    ClosureContext? oldClosureContext = this.closureContext;
     ClosureContext closureContext = new ClosureContext(
         this, function.asyncMarker, returnContext, needToSetReturnType);
     this.closureContext = closureContext;
-    StatementInferenceResult bodyResult = inferStatement(function.body);
+    StatementInferenceResult bodyResult = inferStatement(function.body!);
 
     // If the closure is declared with `async*` or `sync*`, let `M` be the
     // least upper bound of the types of the `yield` expressions in `B’`, or
     // `void` if `B’` contains no `yield` expressions.  Otherwise, let `M` be
     // the least upper bound of the types of the `return` expressions in `B’`,
     // or `void` if `B’` contains no `return` expressions.
-    DartType inferredReturnType;
     if (needToSetReturnType) {
-      inferredReturnType = closureContext.inferReturnType(this,
+      DartType inferredReturnType = closureContext.inferReturnType(this,
           hasImplicitReturn: flowAnalysis.isReachable);
-    }
 
-    // Then the result of inference is `<T0, ..., Tn>(R0 x0, ..., Rn xn) B` with
-    // type `<T0, ..., Tn>(R0, ..., Rn) -> M’` (with some of the `Ri` and `xi`
-    // denoted as optional or named parameters, if appropriate).
-    if (needToSetReturnType) {
+      // Then the result of inference is `<T0, ..., Tn>(R0 x0, ..., Rn xn) B`
+      // with type `<T0, ..., Tn>(R0, ..., Rn) -> M’` (with some of the `Ri` and
+      // `xi` denoted as optional or named parameters, if appropriate).
       instrumentation?.record(uriForInstrumentation, fileOffset, 'returnType',
           new InstrumentationValueForType(inferredReturnType));
       function.returnType = inferredReturnType;
     }
     bodyResult = closureContext.handleImplicitReturn(
-        this, function.body, bodyResult, fileOffset);
+        this, function.body!, bodyResult, fileOffset);
     function.futureValueType = closureContext.futureValueType;
     assert(
         !(isNonNullableByDefault &&
@@ -2666,7 +2698,7 @@
 
   @override
   void inferMetadata(
-      InferenceHelper helper, TreeNode parent, List<Expression> annotations) {
+      InferenceHelper helper, TreeNode? parent, List<Expression>? annotations) {
     if (annotations != null) {
       this.helper = helper;
       inferMetadataKeepingHelper(parent, annotations);
@@ -2676,7 +2708,7 @@
 
   @override
   void inferMetadataKeepingHelper(
-      TreeNode parent, List<Expression> annotations) {
+      TreeNode? parent, List<Expression>? annotations) {
     if (annotations != null) {
       for (int index = 0; index < annotations.length; index++) {
         ExpressionInferenceResult result = inferExpression(
@@ -2689,10 +2721,10 @@
   StaticInvocation transformExtensionMethodInvocation(int fileOffset,
       ObjectAccessTarget target, Expression receiver, Arguments arguments) {
     assert(target.isExtensionMember || target.isNullableExtensionMember);
-    Procedure procedure = target.member;
+    Procedure procedure = target.member as Procedure;
     return engine.forest.createStaticInvocation(
         fileOffset,
-        target.member,
+        procedure,
         engine.forest.createArgumentsForExtensionMethod(
             arguments.fileOffset,
             target.inferredExtensionTypeArguments.length,
@@ -2712,8 +2744,9 @@
       Name name,
       Arguments arguments,
       DartType typeContext,
-      List<VariableDeclaration> hoistedExpressions,
-      {bool isImplicitCall}) {
+      List<VariableDeclaration>? hoistedExpressions,
+      {required bool isImplicitCall}) {
+    // ignore: unnecessary_null_comparison
     assert(isImplicitCall != null);
     InvocationInferenceResult result = inferInvocation(
         typeContext, fileOffset, unknownFunction, arguments,
@@ -2742,8 +2775,9 @@
       Name name,
       Arguments arguments,
       DartType typeContext,
-      List<VariableDeclaration> hoistedExpressions,
-      {bool isImplicitCall}) {
+      List<VariableDeclaration>? hoistedExpressions,
+      {required bool isImplicitCall}) {
+    // ignore: unnecessary_null_comparison
     assert(isImplicitCall != null);
     InvocationInferenceResult result = inferInvocation(
         typeContext, fileOffset, unknownFunction, arguments,
@@ -2775,12 +2809,14 @@
       Name name,
       Arguments arguments,
       DartType typeContext,
-      List<VariableDeclaration> hoistedExpressions,
-      {bool isExpressionInvocation,
-      bool isImplicitCall,
-      Name implicitInvocationPropertyName}) {
+      List<VariableDeclaration>? hoistedExpressions,
+      {required bool isExpressionInvocation,
+      required bool isImplicitCall,
+      Name? implicitInvocationPropertyName}) {
     assert(target.isMissing || target.isAmbiguous);
+    // ignore: unnecessary_null_comparison
     assert(isExpressionInvocation != null);
+    // ignore: unnecessary_null_comparison
     assert(isImplicitCall != null);
     Expression error = createMissingMethodInvocation(
         fileOffset, receiver, receiverType, name, arguments,
@@ -2807,8 +2843,9 @@
       Name name,
       Arguments arguments,
       DartType typeContext,
-      List<VariableDeclaration> hoistedExpressions,
-      {bool isImplicitCall}) {
+      List<VariableDeclaration>? hoistedExpressions,
+      {required bool isImplicitCall}) {
+    // ignore: unnecessary_null_comparison
     assert(isImplicitCall != null);
     assert(target.isExtensionMember || target.isNullableExtensionMember);
     DartType calleeType = getGetterType(target, receiverType);
@@ -2838,8 +2875,8 @@
         //   extension on C {
         //     void Function() get call => () {};
         //   }
-        List<LocatedMessage> context = getWhyNotPromotedContext(
-            flowAnalysis?.whyNotPromoted(receiver)(),
+        List<LocatedMessage>? context = getWhyNotPromotedContext(
+            flowAnalysis.whyNotPromoted(receiver)(),
             staticInvocation,
             (type) => !type.isPotentiallyNullable);
         result = wrapExpressionInferenceResultInProblem(
@@ -2863,14 +2900,17 @@
           isImplicitCall: isImplicitCall,
           isExtensionMemberInvocation: true);
       if (!isTopLevel) {
-        library.checkBoundsInStaticInvocation(staticInvocation,
-            typeSchemaEnvironment, helper.uri, getTypeArgumentsInfo(arguments));
+        library.checkBoundsInStaticInvocation(
+            staticInvocation,
+            typeSchemaEnvironment,
+            helper!.uri,
+            getTypeArgumentsInfo(arguments));
       }
 
       Expression replacement = result.applyResult(staticInvocation);
       if (!isTopLevel && target.isNullable) {
-        List<LocatedMessage> context = getWhyNotPromotedContext(
-            flowAnalysis?.whyNotPromoted(receiver)(),
+        List<LocatedMessage>? context = getWhyNotPromotedContext(
+            flowAnalysis.whyNotPromoted(receiver)(),
             staticInvocation,
             (type) => !type.isPotentiallyNullable);
         if (isImplicitCall) {
@@ -2881,7 +2921,7 @@
           //   extension on int {
           //     void call() {}
           //   }
-          replacement = helper.wrapInProblem(
+          replacement = helper!.wrapInProblem(
               replacement,
               templateNullableExpressionCallError.withArguments(
                   receiverType, isNonNullableByDefault),
@@ -2896,7 +2936,7 @@
           //   extension on int {
           //     void methodOnNonNullInt() {}
           //   }
-          replacement = helper.wrapInProblem(
+          replacement = helper!.wrapInProblem(
               replacement,
               templateNullableMethodCallError.withArguments(
                   name.text, receiverType, isNonNullableByDefault),
@@ -2918,8 +2958,9 @@
       ObjectAccessTarget target,
       Arguments arguments,
       DartType typeContext,
-      List<VariableDeclaration> hoistedExpressions,
-      {bool isImplicitCall}) {
+      List<VariableDeclaration>? hoistedExpressions,
+      {required bool isImplicitCall}) {
+    // ignore: unnecessary_null_comparison
     assert(isImplicitCall != null);
     assert(target.isCallFunction || target.isNullableCallFunction);
     FunctionType declaredFunctionType = getFunctionType(target, receiverType);
@@ -2928,8 +2969,8 @@
         hoistedExpressions: hoistedExpressions,
         receiverType: receiverType,
         isImplicitCall: isImplicitCall);
-    Expression expression;
-    String localName;
+    Expression? expression;
+    String? localName;
     if (useNewMethodInvocationEncoding) {
       DartType inferredFunctionType = result.functionType;
       if (result.isInapplicable) {
@@ -2941,13 +2982,13 @@
           ..fileOffset = fileOffset;
       } else if (receiver is VariableGet) {
         VariableDeclaration variable = receiver.variable;
-        TreeNode parent = variable.parent;
+        TreeNode? parent = variable.parent;
         if (parent is FunctionDeclaration) {
           assert(!identical(inferredFunctionType, unknownFunction),
               "Unknown function type for local function invocation.");
-          localName = variable.name;
+          localName = variable.name!;
           expression = new LocalFunctionInvocation(variable, arguments,
-              functionType: inferredFunctionType)
+              functionType: inferredFunctionType as FunctionType)
             ..fileOffset = receiver.fileOffset;
         }
       }
@@ -2961,16 +3002,16 @@
           arguments,
           functionType: identical(inferredFunctionType, unknownFunction)
               ? null
-              : inferredFunctionType)
+              : inferredFunctionType as FunctionType)
         ..fileOffset = fileOffset;
     } else {
       if (receiver is VariableGet) {
         VariableDeclaration variable = receiver.variable;
-        TreeNode parent = variable.parent;
+        TreeNode? parent = variable.parent;
         if (parent is FunctionDeclaration) {
           // This is a local function invocation. Use the name in bounds
           // checking below.
-          localName = variable.name;
+          localName = variable.name!;
         }
       }
       expression = new MethodInvocation(receiver, callName, arguments)
@@ -2982,15 +3023,15 @@
 
     Expression replacement = result.applyResult(expression);
     if (!isTopLevel && target.isNullableCallFunction) {
-      List<LocatedMessage> context = getWhyNotPromotedContext(
-          flowAnalysis?.whyNotPromoted(receiver)(),
+      List<LocatedMessage>? context = getWhyNotPromotedContext(
+          flowAnalysis.whyNotPromoted(receiver)(),
           expression,
           (type) => !type.isPotentiallyNullable);
       if (isImplicitCall) {
         // Handles cases like:
         //   void Function()? f;
         //   f();
-        replacement = helper.wrapInProblem(
+        replacement = helper!.wrapInProblem(
             replacement,
             templateNullableExpressionCallError.withArguments(
                 receiverType, isNonNullableByDefault),
@@ -3001,7 +3042,7 @@
         // Handles cases like:
         //   void Function()? f;
         //   f.call();
-        replacement = helper.wrapInProblem(
+        replacement = helper!.wrapInProblem(
             replacement,
             templateNullableMethodCallError.withArguments(
                 callName.text, receiverType, isNonNullableByDefault),
@@ -3033,17 +3074,20 @@
       ObjectAccessTarget target,
       Arguments arguments,
       DartType typeContext,
-      List<VariableDeclaration> hoistedExpressions,
-      {bool isImplicitCall,
-      bool isSpecialCasedBinaryOperator,
-      bool isSpecialCasedTernaryOperator}) {
+      List<VariableDeclaration>? hoistedExpressions,
+      {required bool isImplicitCall,
+      required bool isSpecialCasedBinaryOperator,
+      required bool isSpecialCasedTernaryOperator}) {
+    // ignore: unnecessary_null_comparison
     assert(isImplicitCall != null);
+    // ignore: unnecessary_null_comparison
     assert(isSpecialCasedBinaryOperator != null);
+    // ignore: unnecessary_null_comparison
     assert(isSpecialCasedTernaryOperator != null);
     assert(target.isInstanceMember ||
         target.isObjectMember ||
         target.isNullableInstanceMember);
-    Procedure method = target.member;
+    Procedure? method = target.member as Procedure;
     assert(method.kind == ProcedureKind.Method,
         "Unexpected instance method $method");
     Name methodName = method.name;
@@ -3063,7 +3107,7 @@
         }
       }
       if (instrumentation != null && method != null) {
-        instrumentation.record(uriForInstrumentation, fileOffset, 'target',
+        instrumentation!.record(uriForInstrumentation, fileOffset, 'target',
             new InstrumentationValueForMember(method));
       }
     }
@@ -3075,7 +3119,7 @@
     if (receiver is! ThisExpression &&
         method != null &&
         returnedTypeParametersOccurNonCovariantly(
-            method.enclosingClass, method.function.returnType)) {
+            method.enclosingClass!, method.function.returnType)) {
       contravariantCheck = true;
     }
     InvocationInferenceResult result = inferInvocation(
@@ -3102,7 +3146,7 @@
             InstanceAccessKind.Inapplicable, receiver, methodName, arguments,
             functionType: _computeFunctionTypeForArguments(
                 arguments, const InvalidType()),
-            interfaceTarget: method)
+            interfaceTarget: method!)
           ..fileOffset = fileOffset;
       } else {
         assert(
@@ -3126,7 +3170,8 @@
         }
         expression = new InstanceInvocation(
             kind, receiver, methodName, arguments,
-            functionType: inferredFunctionType, interfaceTarget: method)
+            functionType: inferredFunctionType as FunctionType,
+            interfaceTarget: method!)
           ..fileOffset = fileOffset;
       }
     } else {
@@ -3144,7 +3189,7 @@
       if (instrumentation != null) {
         int offset =
             arguments.fileOffset == -1 ? fileOffset : arguments.fileOffset;
-        instrumentation.record(uriForInstrumentation, offset, 'checkReturn',
+        instrumentation!.record(uriForInstrumentation, offset, 'checkReturn',
             new InstrumentationValueForType(result.inferredType));
       }
     } else {
@@ -3156,8 +3201,8 @@
 
     replacement = result.applyResult(replacement);
     if (!isTopLevel && target.isNullable) {
-      List<LocatedMessage> context = getWhyNotPromotedContext(
-          flowAnalysis?.whyNotPromoted(receiver)(),
+      List<LocatedMessage>? context = getWhyNotPromotedContext(
+          flowAnalysis.whyNotPromoted(receiver)(),
           expression,
           (type) => !type.isPotentiallyNullable);
       if (isImplicitCall) {
@@ -3168,7 +3213,7 @@
         //   class C {
         //     void call();
         //   }
-        replacement = helper.wrapInProblem(
+        replacement = helper!.wrapInProblem(
             replacement,
             templateNullableExpressionCallError.withArguments(
                 receiverType, isNonNullableByDefault),
@@ -3179,7 +3224,7 @@
         // Handles cases like:
         //   int? i;
         //   i.abs();
-        replacement = helper.wrapInProblem(
+        replacement = helper!.wrapInProblem(
             replacement,
             templateNullableMethodCallError.withArguments(
                 methodName.text, receiverType, isNonNullableByDefault),
@@ -3201,15 +3246,18 @@
       ObjectAccessTarget target,
       Arguments arguments,
       DartType typeContext,
-      List<VariableDeclaration> hoistedExpressions,
-      {bool isExpressionInvocation}) {
+      List<VariableDeclaration>? hoistedExpressions,
+      {required bool isExpressionInvocation}) {
+    // ignore: unnecessary_null_comparison
     assert(isExpressionInvocation != null);
     assert(target.isInstanceMember ||
         target.isObjectMember ||
         target.isNullableInstanceMember);
-    Procedure getter = target.member;
+    Procedure? getter = target.member as Procedure;
     assert(getter.kind == ProcedureKind.Getter);
 
+    // TODO(johnniwinther): This is inconsistent with the handling below. Remove
+    // this or add handling similar to [_inferMethodInvocation].
     if (receiverType == const DynamicType() && getter is Procedure) {
       FunctionNode signature = getter.function;
       if (arguments.positional.length < signature.requiredParameterCount ||
@@ -3225,7 +3273,7 @@
         }
       }
       if (instrumentation != null && getter != null) {
-        instrumentation.record(uriForInstrumentation, fileOffset, 'target',
+        instrumentation!.record(uriForInstrumentation, fileOffset, 'target',
             new InstrumentationValueForMember(getter));
       }
     }
@@ -3233,7 +3281,7 @@
     DartType calleeType = getGetterType(target, receiverType);
     FunctionType functionType = getFunctionTypeForImplicitCall(calleeType);
 
-    List<VariableDeclaration> locallyHoistedExpressions;
+    List<VariableDeclaration>? locallyHoistedExpressions;
     if (hoistedExpressions == null && !isTopLevel) {
       // We don't hoist in top-level inference.
       hoistedExpressions = locallyHoistedExpressions = <VariableDeclaration>[];
@@ -3242,7 +3290,7 @@
       receiver = _hoist(receiver, receiverType, hoistedExpressions);
     }
 
-    Name originalName = getter.name;
+    Name originalName = getter!.name;
     Expression originalReceiver = receiver;
     Member originalTarget = getter;
     Expression originalPropertyGet;
@@ -3273,7 +3321,7 @@
     if (calleeType is! DynamicType &&
         receiver is! ThisExpression &&
         returnedTypeParametersOccurNonCovariantly(
-            getter.enclosingClass, getter.function.returnType)) {
+            getter.enclosingClass!, getter.function.returnType)) {
       propertyGet = new AsExpression(propertyGet, functionType)
         ..isTypeError = true
         ..isCovarianceCheck = true
@@ -3282,7 +3330,7 @@
       if (instrumentation != null) {
         int offset =
             arguments.fileOffset == -1 ? fileOffset : arguments.fileOffset;
-        instrumentation.record(uriForInstrumentation, offset,
+        instrumentation!.record(uriForInstrumentation, offset,
             'checkGetterReturn', new InstrumentationValueForType(functionType));
       }
     }
@@ -3300,7 +3348,7 @@
         implicitInvocationPropertyName: getter.name);
 
     if (!isTopLevel && isExpressionInvocation) {
-      Expression error = helper.buildProblem(
+      Expression error = helper!.buildProblem(
           templateImplicitCallOfNonMethod.withArguments(
               receiverType, isNonNullableByDefault),
           fileOffset,
@@ -3316,8 +3364,8 @@
       //   class C {
       //     void Function() get foo => () {};
       //   }
-      List<LocatedMessage> context = getWhyNotPromotedContext(
-          flowAnalysis?.whyNotPromoted(receiver)(),
+      List<LocatedMessage>? context = getWhyNotPromotedContext(
+          flowAnalysis.whyNotPromoted(receiver)(),
           invocationResult.expression,
           (type) => !type.isPotentiallyNullable);
       invocationResult = wrapExpressionInferenceResultInProblem(
@@ -3344,7 +3392,7 @@
           nullAwareAction.receiver == originalPropertyGet) {
         // TODO(johnniwinther): Remove this when [MethodInvocation] is no longer
         // used and [originalPropertyGet] can be an [InstanceGet].
-        InstanceGet instanceGet = originalPropertyGet;
+        InstanceGet instanceGet = originalPropertyGet as InstanceGet;
         invocationResult = new ExpressionInferenceResult(
             invocationResult.inferredType,
             new InstanceGetterInvocation(instanceGet.kind, originalReceiver,
@@ -3356,7 +3404,7 @@
           nullAwareAction.receiver == originalPropertyGet) {
         // TODO(johnniwinther): Remove this when [MethodInvocation] is no longer
         // used and [originalPropertyGet] can be an [InstanceGet].
-        InstanceGet instanceGet = originalPropertyGet;
+        InstanceGet instanceGet = originalPropertyGet as InstanceGet;
         invocationResult = new ExpressionInferenceResult(
             invocationResult.inferredType,
             new InstanceGetterInvocation(instanceGet.kind, originalReceiver,
@@ -3367,7 +3415,7 @@
           nullAwareAction.receiver == originalPropertyGet) {
         // TODO(johnniwinther): Remove this when [MethodInvocation] is no longer
         // used and [originalPropertyGet] can be an [InstanceGet].
-        InstanceGet instanceGet = originalPropertyGet;
+        InstanceGet instanceGet = originalPropertyGet as InstanceGet;
         invocationResult = new ExpressionInferenceResult(
             invocationResult.inferredType,
             new InstanceGetterInvocation(instanceGet.kind, originalReceiver,
@@ -3386,7 +3434,7 @@
   }
 
   Expression _hoist(Expression expression, DartType type,
-      List<VariableDeclaration> hoistedExpressions) {
+      List<VariableDeclaration>? hoistedExpressions) {
     if (hoistedExpressions != null && expression is! ThisExpression) {
       VariableDeclaration variable = createVariable(expression, type);
       hoistedExpressions.add(variable);
@@ -3397,7 +3445,7 @@
 
   ExpressionInferenceResult _insertHoistedExpression(
       ExpressionInferenceResult result,
-      List<VariableDeclaration> hoistedExpressions) {
+      List<VariableDeclaration>? hoistedExpressions) {
     if (hoistedExpressions != null && hoistedExpressions.isNotEmpty) {
       Expression expression = result.nullAwareAction;
       for (int index = hoistedExpressions.length - 1; index >= 0; index--) {
@@ -3417,18 +3465,19 @@
       ObjectAccessTarget target,
       Arguments arguments,
       DartType typeContext,
-      List<VariableDeclaration> hoistedExpressions,
-      {bool isExpressionInvocation}) {
+      List<VariableDeclaration>? hoistedExpressions,
+      {required bool isExpressionInvocation}) {
+    // ignore: unnecessary_null_comparison
     assert(isExpressionInvocation != null);
     assert(target.isInstanceMember ||
         target.isObjectMember ||
         target.isNullableInstanceMember);
-    Field field = target.member;
+    Field field = target.member as Field;
 
     DartType calleeType = getGetterType(target, receiverType);
     FunctionType functionType = getFunctionTypeForImplicitCall(calleeType);
 
-    List<VariableDeclaration> locallyHoistedExpressions;
+    List<VariableDeclaration>? locallyHoistedExpressions;
     if (hoistedExpressions == null && !isTopLevel) {
       // We don't hoist in top-level inference.
       hoistedExpressions = locallyHoistedExpressions = <VariableDeclaration>[];
@@ -3437,12 +3486,12 @@
       receiver = _hoist(receiver, receiverType, hoistedExpressions);
     }
 
-    Map<DartType, NonPromotionReason> Function() whyNotPromoted;
+    Map<DartType, NonPromotionReason> Function()? whyNotPromoted;
     if (!isTopLevel && target.isNullable) {
       // We won't report the error until later (after we have an
       // invocationResult), but we need to gather "why not promoted" info now,
       // before we tell flow analysis about the property get.
-      whyNotPromoted = flowAnalysis?.whyNotPromoted(receiver);
+      whyNotPromoted = flowAnalysis.whyNotPromoted(receiver);
     }
 
     Name originalName = field.name;
@@ -3479,7 +3528,7 @@
     if (receiver is! ThisExpression &&
         calleeType is! DynamicType &&
         returnedTypeParametersOccurNonCovariantly(
-            field.enclosingClass, field.type)) {
+            field.enclosingClass!, field.type)) {
       propertyGet = new AsExpression(propertyGet, functionType)
         ..isTypeError = true
         ..isCovarianceCheck = true
@@ -3488,7 +3537,7 @@
       if (instrumentation != null) {
         int offset =
             arguments.fileOffset == -1 ? fileOffset : arguments.fileOffset;
-        instrumentation.record(uriForInstrumentation, offset,
+        instrumentation!.record(uriForInstrumentation, offset,
             'checkGetterReturn', new InstrumentationValueForType(functionType));
       }
     }
@@ -3507,7 +3556,7 @@
         implicitInvocationPropertyName: field.name);
 
     if (!isTopLevel && isExpressionInvocation) {
-      Expression error = helper.buildProblem(
+      Expression error = helper!.buildProblem(
           templateImplicitCallOfNonMethod.withArguments(
               receiverType, isNonNullableByDefault),
           fileOffset,
@@ -3526,8 +3575,10 @@
       //   }
       // TODO(paulberry): would it be better to report NullableMethodCallError
       // in this scenario?
-      List<LocatedMessage> context = getWhyNotPromotedContext(whyNotPromoted(),
-          invocationResult.expression, (type) => !type.isPotentiallyNullable);
+      List<LocatedMessage>? context = getWhyNotPromotedContext(
+          whyNotPromoted!(),
+          invocationResult.expression,
+          (type) => !type.isPotentiallyNullable);
       invocationResult = wrapExpressionInferenceResultInProblem(
           invocationResult,
           templateNullableExpressionCallError.withArguments(
@@ -3552,7 +3603,7 @@
           nullAwareAction.receiver == originalPropertyGet) {
         // TODO(johnniwinther): Remove this when [MethodInvocation] is no longer
         // used and [originalPropertyGet] can be an [InstanceGet].
-        InstanceGet instanceGet = originalPropertyGet;
+        InstanceGet instanceGet = originalPropertyGet as InstanceGet;
         invocationResult = new ExpressionInferenceResult(
             invocationResult.inferredType,
             new InstanceGetterInvocation(instanceGet.kind, originalReceiver,
@@ -3564,7 +3615,7 @@
           nullAwareAction.receiver == originalPropertyGet) {
         // TODO(johnniwinther): Remove this when [MethodInvocation] is no longer
         // used and [originalPropertyGet] can be an [InstanceGet].
-        InstanceGet instanceGet = originalPropertyGet;
+        InstanceGet instanceGet = originalPropertyGet as InstanceGet;
         invocationResult = new ExpressionInferenceResult(
             invocationResult.inferredType,
             new InstanceGetterInvocation(instanceGet.kind, originalReceiver,
@@ -3575,7 +3626,7 @@
           nullAwareAction.receiver == originalPropertyGet) {
         // TODO(johnniwinther): Remove this when [MethodInvocation] is no longer
         // used and [originalPropertyGet] can be an [InstanceGet].
-        InstanceGet instanceGet = originalPropertyGet;
+        InstanceGet instanceGet = originalPropertyGet as InstanceGet;
         invocationResult = new ExpressionInferenceResult(
             invocationResult.inferredType,
             new InstanceGetterInvocation(instanceGet.kind, originalReceiver,
@@ -3602,11 +3653,13 @@
       Name name,
       Arguments arguments,
       DartType typeContext,
-      {bool isExpressionInvocation,
-      bool isImplicitCall,
-      Name implicitInvocationPropertyName,
-      List<VariableDeclaration> hoistedExpressions}) {
+      {required bool isExpressionInvocation,
+      required bool isImplicitCall,
+      Name? implicitInvocationPropertyName,
+      List<VariableDeclaration>? hoistedExpressions}) {
+    // ignore: unnecessary_null_comparison
     assert(isExpressionInvocation != null);
+    // ignore: unnecessary_null_comparison
     assert(isImplicitCall != null);
 
     ObjectAccessTarget target = findInterfaceMember(
@@ -3617,7 +3670,7 @@
       case ObjectAccessTargetKind.instanceMember:
       case ObjectAccessTargetKind.objectMember:
       case ObjectAccessTargetKind.nullableInstanceMember:
-        Member member = target.member;
+        Member member = target.member!;
         if (member is Procedure) {
           if (member.kind == ProcedureKind.Getter) {
             return _inferInstanceGetterInvocation(
@@ -3660,7 +3713,6 @@
               hoistedExpressions,
               isExpressionInvocation: isExpressionInvocation);
         }
-        break;
       case ObjectAccessTargetKind.callFunction:
       case ObjectAccessTargetKind.nullableCallFunction:
         return _inferFunctionInvocation(fileOffset, nullAwareGuards, receiver,
@@ -3700,12 +3752,17 @@
             name, arguments, typeContext, hoistedExpressions,
             isImplicitCall: isExpressionInvocation || isImplicitCall);
       case ObjectAccessTargetKind.never:
-        return _inferNeverInvocation(fileOffset, nullAwareGuards, receiver,
-            receiverType, name, arguments, typeContext, hoistedExpressions,
+        return _inferNeverInvocation(
+            fileOffset,
+            nullAwareGuards,
+            receiver,
+            receiverType as NeverType,
+            name,
+            arguments,
+            typeContext,
+            hoistedExpressions,
             isImplicitCall: isImplicitCall);
     }
-    return unhandled(
-        '$target', 'inferMethodInvocation', fileOffset, uriForInstrumentation);
   }
 
   void _checkBoundsInMethodInvocation(
@@ -3726,7 +3783,7 @@
       //     class C2 { int call<X extends num>(X x) => 42; }
       //     main() { C1 c = new C1(); c.f("foobar"); }
       DartType actualReceiverType;
-      Member interfaceTarget;
+      Member? interfaceTarget;
       Name actualMethodName;
       if (calleeType is InterfaceType) {
         actualReceiverType = calleeType;
@@ -3747,26 +3804,27 @@
           actualMethodName,
           interfaceTarget,
           arguments,
-          helper.uri,
+          helper!.uri,
           fileOffset);
     }
   }
 
   void checkBoundsInInstantiation(
       FunctionType functionType, List<DartType> arguments, int fileOffset,
-      {bool inferred}) {
+      {required bool inferred}) {
+    // ignore: unnecessary_null_comparison
     assert(inferred != null);
     // If [arguments] were inferred, check them.
     if (!isTopLevel) {
       // We only perform checks in full inference.
       library.checkBoundsInInstantiation(typeSchemaEnvironment, classHierarchy,
-          this, functionType, arguments, helper.uri, fileOffset,
+          this, functionType, arguments, helper!.uri, fileOffset,
           inferred: inferred);
     }
   }
 
   void _checkBoundsInFunctionInvocation(FunctionType functionType,
-      String localName, Arguments arguments, int fileOffset) {
+      String? localName, Arguments arguments, int fileOffset) {
     // If [arguments] were inferred, check them.
     if (!isTopLevel) {
       // We only perform checks in full inference.
@@ -3777,7 +3835,7 @@
           functionType,
           localName,
           arguments,
-          helper.uri,
+          helper!.uri,
           fileOffset);
     }
   }
@@ -3789,7 +3847,7 @@
             target.isNullableInstanceMember) &&
         target.member is Procedure &&
         typeSchemaEnvironment.isSpecialCasesBinaryForReceiverType(
-            target.member, receiverType,
+            target.member as Procedure, receiverType,
             isNonNullableByDefault: isNonNullableByDefault);
   }
 
@@ -3798,7 +3856,8 @@
             target.isObjectMember ||
             target.isNullableInstanceMember) &&
         target.member is Procedure &&
-        typeSchemaEnvironment.isSpecialCasedTernaryOperator(target.member,
+        typeSchemaEnvironment.isSpecialCasedTernaryOperator(
+            target.member as Procedure,
             isNonNullableByDefault: isNonNullableByDefault);
   }
 
@@ -3806,7 +3865,7 @@
   ExpressionInferenceResult inferSuperMethodInvocation(
       SuperMethodInvocation expression,
       DartType typeContext,
-      Procedure procedure) {
+      Procedure? procedure) {
     ObjectAccessTarget target = procedure != null
         ? new ObjectAccessTarget.interfaceMember(procedure,
             isPotentiallyNullable: false)
@@ -3814,16 +3873,17 @@
     int fileOffset = expression.fileOffset;
     Name methodName = expression.name;
     Arguments arguments = expression.arguments;
-    DartType receiverType = thisType;
+    DartType receiverType = thisType!;
     bool isSpecialCasedBinaryOperator =
         isSpecialCasedBinaryOperatorForReceiverType(target, receiverType);
     DartType calleeType = getGetterType(target, receiverType);
     FunctionType functionType = getFunctionType(target, receiverType);
     if (procedure != null) {
       calleeType =
-          computeTypeFromSuperClass(procedure.enclosingClass, calleeType);
+          computeTypeFromSuperClass(procedure.enclosingClass!, calleeType);
       functionType =
-          computeTypeFromSuperClass(procedure.enclosingClass, functionType);
+          computeTypeFromSuperClass(procedure.enclosingClass!, functionType)
+              as FunctionType;
     }
     if (isNonNullableByDefault &&
         expression.name == equalsName &&
@@ -3858,6 +3918,7 @@
       bool hasDeclaredInitializer) {
     assert(closureContext == null);
     this.helper = helper;
+    // ignore: unnecessary_null_comparison
     assert(declaredType != null);
     ExpressionInferenceResult result =
         inferExpression(initializer, declaredType, true);
@@ -3870,16 +3931,16 @@
 
   /// Performs the core type inference algorithm for super property get.
   ExpressionInferenceResult inferSuperPropertyGet(
-      SuperPropertyGet expression, DartType typeContext, Member member) {
+      SuperPropertyGet expression, DartType typeContext, Member? member) {
     ObjectAccessTarget readTarget = member != null
         ? new ObjectAccessTarget.interfaceMember(member,
             isPotentiallyNullable: false)
         : const ObjectAccessTarget.missing();
-    DartType receiverType = thisType;
+    DartType receiverType = thisType!;
     DartType inferredType = getGetterType(readTarget, receiverType);
     if (member != null) {
       inferredType =
-          computeTypeFromSuperClass(member.enclosingClass, inferredType);
+          computeTypeFromSuperClass(member.enclosingClass!, inferredType);
     }
     if (member is Procedure && member.kind == ProcedureKind.Method) {
       return instantiateTearOff(inferredType, typeContext, expression);
@@ -3966,10 +4027,11 @@
   /// contravariance.
   MethodContravarianceCheckKind preCheckInvocationContravariance(
       DartType receiverType, ObjectAccessTarget target,
-      {bool isThisReceiver}) {
+      {required bool isThisReceiver}) {
+    // ignore: unnecessary_null_comparison
     assert(isThisReceiver != null);
     if (target.isInstanceMember || target.isObjectMember) {
-      Member interfaceMember = target.member;
+      Member interfaceMember = target.member!;
       if (interfaceMember is Field ||
           interfaceMember is Procedure &&
               interfaceMember.kind == ProcedureKind.Getter) {
@@ -3980,10 +4042,10 @@
         if (!isThisReceiver) {
           if ((interfaceMember is Field &&
                   returnedTypeParametersOccurNonCovariantly(
-                      interfaceMember.enclosingClass, interfaceMember.type)) ||
+                      interfaceMember.enclosingClass!, interfaceMember.type)) ||
               (interfaceMember is Procedure &&
                   returnedTypeParametersOccurNonCovariantly(
-                      interfaceMember.enclosingClass,
+                      interfaceMember.enclosingClass!,
                       interfaceMember.function.returnType))) {
             return MethodContravarianceCheckKind.checkGetterReturn;
           }
@@ -3991,7 +4053,7 @@
       } else if (!isThisReceiver &&
           interfaceMember is Procedure &&
           returnedTypeParametersOccurNonCovariantly(
-              interfaceMember.enclosingClass,
+              interfaceMember.enclosingClass!,
               interfaceMember.function.returnType)) {
         return MethodContravarianceCheckKind.checkMethodReturn;
       }
@@ -4001,7 +4063,7 @@
 
   /// If the given [type] is a [TypeParameterType], resolve it to its bound.
   DartType resolveTypeParameter(DartType type) {
-    DartType resolveOneStep(DartType type) {
+    DartType? resolveOneStep(DartType type) {
       if (type is TypeParameterType) {
         return type.bound;
       } else {
@@ -4009,28 +4071,28 @@
       }
     }
 
-    DartType resolved = resolveOneStep(type);
+    DartType? resolved = resolveOneStep(type);
     if (resolved == null) return type;
 
     // Detect circularities using the tortoise-and-hare algorithm.
-    type = resolved;
-    DartType hare = resolveOneStep(type);
-    if (hare == null) return type;
+    DartType? tortoise = resolved;
+    DartType? hare = resolveOneStep(tortoise);
+    if (hare == null) return tortoise;
     while (true) {
-      if (identical(type, hare)) {
+      if (identical(tortoise, hare)) {
         // We found a circularity.  Give up and return `dynamic`.
         return const DynamicType();
       }
 
       // Hare takes two steps
-      DartType step1 = resolveOneStep(hare);
+      DartType? step1 = resolveOneStep(hare!);
       if (step1 == null) return hare;
-      DartType step2 = resolveOneStep(step1);
+      DartType? step2 = resolveOneStep(step1);
       if (step2 == null) return step1;
       hare = step2;
 
       // Tortoise takes one step
-      type = resolveOneStep(type);
+      tortoise = resolveOneStep(tortoise!);
     }
   }
 
@@ -4040,6 +4102,7 @@
     }
     // TODO(paulberry): If [type] is a subtype of `Future`, should we just
     // return it unmodified?
+    // ignore: unnecessary_null_comparison
     if (type == null) {
       return coreTypes.futureRawType(library.nullable);
     }
@@ -4047,14 +4110,12 @@
   }
 
   DartType wrapFutureType(DartType type, Nullability nullability) {
-    DartType typeWithoutFutureOr = type ?? const DynamicType();
     return new InterfaceType(
-        coreTypes.futureClass, nullability, <DartType>[typeWithoutFutureOr]);
+        coreTypes.futureClass, nullability, <DartType>[type]);
   }
 
   DartType wrapType(DartType type, Class class_, Nullability nullability) {
-    return new InterfaceType(
-        class_, nullability, <DartType>[type ?? const DynamicType()]);
+    return new InterfaceType(class_, nullability, <DartType>[type]);
   }
 
   /// Computes the `futureValueTypeSchema` for the type schema [type].
@@ -4073,9 +4134,9 @@
     }), coreTypes);
   }
 
-  Member _getInterfaceMember(
+  Member? _getInterfaceMember(
       Class class_, Name name, bool setter, int charOffset) {
-    ClassMember classMember = engine.hierarchyBuilder
+    ClassMember? classMember = engine.hierarchyBuilder
         .getInterfaceClassMember(class_, name, setter: setter);
     if (classMember != null) {
       if (classMember.isStatic) {
@@ -4086,12 +4147,12 @@
               templateDuplicatedDeclarationUse.withArguments(name.text),
               charOffset,
               name.text.length,
-              helper.uri);
+              helper!.uri);
         }
         classMember = null;
       }
     }
-    Member member = classMember?.getMember(engine.hierarchyBuilder);
+    Member? member = classMember?.getMember(engine.hierarchyBuilder);
     if (member == null && library.isPatch) {
       // TODO(johnniwinther): Injected members are currently not included
       // in the class hierarchy builder.
@@ -4106,7 +4167,7 @@
   ///
   /// If it is, an error message template is returned, which can be used by the
   /// caller to report an invalid cast.  Otherwise, `null` is returned.
-  Template<Message Function(DartType, DartType, bool)>
+  Template<Message Function(DartType, DartType, bool)>?
       _getPreciseTypeErrorTemplate(Expression expression) {
     if (expression is ListLiteral) {
       return templateInvalidCastLiteralList;
@@ -4153,7 +4214,7 @@
 
   bool _shouldTearOffCall(DartType contextType, DartType expressionType) {
     if (contextType is FutureOrType) {
-      contextType = (contextType as FutureOrType).typeArgument;
+      contextType = contextType.typeArgument;
     }
     if (contextType is FunctionType) return true;
     if (contextType is InterfaceType &&
@@ -4171,7 +4232,7 @@
       return engine.forest.createSuperMethodInvocation(fileOffset, indexGetName,
           null, engine.forest.createArguments(fileOffset, <Expression>[index]));
     } else {
-      return helper.buildProblem(
+      return helper!.buildProblem(
           templateSuperclassHasNoMethod.withArguments(indexGetName.text),
           fileOffset,
           noLength);
@@ -4188,7 +4249,7 @@
           engine.forest
               .createArguments(fileOffset, <Expression>[index, value]));
     } else {
-      return helper.buildProblem(
+      return helper!.buildProblem(
           templateSuperclassHasNoMethod.withArguments(indexSetName.text),
           fileOffset,
           noLength);
@@ -4200,23 +4261,23 @@
       int length,
       DartType receiverType,
       Name name,
-      List<ExtensionAccessCandidate> extensionAccessCandidates,
+      List<ExtensionAccessCandidate>? extensionAccessCandidates,
       Template<Message Function(String, DartType, bool)> missingTemplate,
       Template<Message Function(String, DartType, bool)> ambiguousTemplate) {
-    List<LocatedMessage> context;
+    List<LocatedMessage>? context;
     Template<Message Function(String, DartType, bool)> template =
         missingTemplate;
     if (extensionAccessCandidates != null) {
       context = extensionAccessCandidates
           .map((ExtensionAccessCandidate c) =>
               messageAmbiguousExtensionCause.withLocation(
-                  c.memberBuilder.fileUri,
+                  c.memberBuilder.fileUri!,
                   c.memberBuilder.charOffset,
                   name == unaryMinusName ? 1 : c.memberBuilder.name.length))
           .toList();
       template = ambiguousTemplate;
     }
-    return helper.buildProblem(
+    return helper!.buildProblem(
         template.withArguments(name.text, resolveTypeParameter(receiverType),
             isNonNullableByDefault),
         fileOffset,
@@ -4226,16 +4287,17 @@
 
   Expression createMissingMethodInvocation(int fileOffset, Expression receiver,
       DartType receiverType, Name name, Arguments arguments,
-      {bool isExpressionInvocation,
-      Name implicitInvocationPropertyName,
-      List<ExtensionAccessCandidate> extensionAccessCandidates}) {
+      {required bool isExpressionInvocation,
+      Name? implicitInvocationPropertyName,
+      List<ExtensionAccessCandidate>? extensionAccessCandidates}) {
+    // ignore: unnecessary_null_comparison
     assert(isExpressionInvocation != null);
     if (isTopLevel) {
       return engine.forest
           .createMethodInvocation(fileOffset, receiver, name, arguments);
     } else if (implicitInvocationPropertyName != null) {
       assert(extensionAccessCandidates == null);
-      return helper.buildProblem(
+      return helper!.buildProblem(
           templateInvokeNonFunction
               .withArguments(implicitInvocationPropertyName.text),
           fileOffset,
@@ -4256,7 +4318,7 @@
 
   Expression createMissingPropertyGet(int fileOffset, Expression receiver,
       DartType receiverType, Name propertyName,
-      {List<ExtensionAccessCandidate> extensionAccessCandidates}) {
+      {List<ExtensionAccessCandidate>? extensionAccessCandidates}) {
     if (isTopLevel) {
       return engine.forest
           .createPropertyGet(fileOffset, receiver, propertyName);
@@ -4280,8 +4342,9 @@
 
   Expression createMissingPropertySet(int fileOffset, Expression receiver,
       DartType receiverType, Name propertyName, Expression value,
-      {bool forEffect,
-      List<ExtensionAccessCandidate> extensionAccessCandidates}) {
+      {required bool forEffect,
+      List<ExtensionAccessCandidate>? extensionAccessCandidates}) {
+    // ignore: unnecessary_null_comparison
     assert(forEffect != null);
     if (isTopLevel) {
       return engine.forest.createPropertySet(
@@ -4307,7 +4370,7 @@
 
   Expression createMissingIndexGet(int fileOffset, Expression receiver,
       DartType receiverType, Expression index,
-      {List<ExtensionAccessCandidate> extensionAccessCandidates}) {
+      {List<ExtensionAccessCandidate>? extensionAccessCandidates}) {
     if (isTopLevel) {
       return engine.forest.createIndexGet(fileOffset, receiver, index);
     } else {
@@ -4330,8 +4393,9 @@
 
   Expression createMissingIndexSet(int fileOffset, Expression receiver,
       DartType receiverType, Expression index, Expression value,
-      {bool forEffect,
-      List<ExtensionAccessCandidate> extensionAccessCandidates}) {
+      {required bool forEffect,
+      List<ExtensionAccessCandidate>? extensionAccessCandidates}) {
+    // ignore: unnecessary_null_comparison
     assert(forEffect != null);
     if (isTopLevel) {
       return engine.forest.createIndexSet(fileOffset, receiver, index, value,
@@ -4356,7 +4420,7 @@
 
   Expression createMissingBinary(int fileOffset, Expression left,
       DartType leftType, Name binaryName, Expression right,
-      {List<ExtensionAccessCandidate> extensionAccessCandidates}) {
+      {List<ExtensionAccessCandidate>? extensionAccessCandidates}) {
     assert(binaryName != equalsName);
     if (isTopLevel) {
       return engine.forest.createMethodInvocation(fileOffset, left, binaryName,
@@ -4381,7 +4445,7 @@
 
   Expression createMissingUnary(int fileOffset, Expression expression,
       DartType expressionType, Name unaryName,
-      {List<ExtensionAccessCandidate> extensionAccessCandidates}) {
+      {List<ExtensionAccessCandidate>? extensionAccessCandidates}) {
     if (isTopLevel) {
       return new UnaryExpression(unaryName, expression)
         ..fileOffset = fileOffset;
@@ -4429,7 +4493,7 @@
 
   MixinInferrer(this.coreTypes, this.gatherer);
 
-  Supertype asInstantiationOf(Supertype type, Class superclass);
+  Supertype? asInstantiationOf(Supertype type, Class superclass);
 
   void reportProblem(Message message, Class cls);
 
@@ -4484,11 +4548,11 @@
         s0 = mixinSuperclass.implementedTypes[0];
         s1 = mixinSuperclass.implementedTypes[1];
       } else if (mixinSuperclass.implementedTypes.length == 1) {
-        s0 = mixinSuperclass.supertype;
+        s0 = mixinSuperclass.supertype!;
         s1 = mixinSuperclass.implementedTypes.first;
       } else {
-        s0 = mixinSuperclass.supertype;
-        s1 = mixinSuperclass.mixedInType;
+        s0 = mixinSuperclass.supertype!;
+        s1 = mixinSuperclass.mixedInType!;
       }
       s0 = substitution.substituteSupertype(s0);
       s1 = substitution.substituteSupertype(s1);
@@ -4497,7 +4561,7 @@
     } else {
       // Find the type U0 which is baseType as an instance of mixinSupertype's
       // class.
-      Supertype supertype =
+      Supertype? supertype =
           asInstantiationOf(baseType, mixinSupertype.classNode);
       if (supertype == null) {
         reportProblem(
@@ -4523,14 +4587,14 @@
   }
 
   void infer(Class classNode) {
-    Supertype mixedInType = classNode.mixedInType;
+    Supertype mixedInType = classNode.mixedInType!;
     assert(mixedInType.typeArguments.every((t) => t == const UnknownType()));
     // Note that we have no anonymous mixin applications, they have all
     // been named.  Note also that mixin composition has been translated
     // so that we only have mixin applications of the form `S with M`.
-    Supertype baseType = classNode.supertype;
+    Supertype baseType = classNode.supertype!;
     Class mixinClass = mixedInType.classNode;
-    Supertype mixinSupertype = mixinClass.supertype;
+    Supertype mixinSupertype = mixinClass.supertype!;
     // Generate constraints based on the mixin's supertype.
     generateConstraints(mixinClass, baseType, mixinSupertype);
     // Solve them to get a map from type parameters to upper and lower
@@ -4539,7 +4603,7 @@
         gatherer.computeConstraints(classNode.enclosingLibrary);
     // Generate new type parameters with the solution as bounds.
     List<TypeParameter> parameters = mixinClass.typeParameters.map((p) {
-      TypeConstraint constraint = result[p];
+      TypeConstraint? constraint = result[p];
       // Because we solved for equality, a valid solution has a parameter
       // either unconstrained or else with identical upper and lower bounds.
       if (constraint != null && constraint.upper != constraint.lower) {
@@ -4686,7 +4750,8 @@
 
   WrapInProblemInferenceResult(this.inferredType, this.functionType,
       this.message, this.fileOffset, this.length, this.helper,
-      {this.isInapplicable})
+      {required this.isInapplicable})
+      // ignore: unnecessary_null_comparison
       : assert(isInapplicable != null);
 
   @override
@@ -4701,7 +4766,7 @@
   final ExpressionInferenceResult expressionInferenceResult;
 
   /// The property that was looked up, or `null` if no property was found.
-  final Member member;
+  final Member? member;
 
   PropertyGetInferenceResult(this.expressionInferenceResult, this.member);
 }
@@ -4715,6 +4780,7 @@
   final Expression expression;
 
   ExpressionInferenceResult(this.inferredType, this.expression)
+      // ignore: unnecessary_null_comparison
       : assert(expression != null);
 
   /// The guards used for null-aware access if the expression is part of a
@@ -4748,9 +4814,13 @@
 
   NullAwareGuard(this._nullAwareVariable, this._nullAwareFileOffset,
       this._nullAwareEquals, this._inferrer)
+      // ignore: unnecessary_null_comparison
       : assert(_nullAwareVariable != null),
+        // ignore: unnecessary_null_comparison
         assert(_nullAwareFileOffset != null),
+        // ignore: unnecessary_null_comparison
         assert(_nullAwareEquals != null),
+        // ignore: unnecessary_null_comparison
         assert(_inferrer != null) {
     // Ensure the initializer of [_nullAwareVariable] is promoted to
     // non-nullable.
@@ -4814,6 +4884,7 @@
   NullAwareExpressionInferenceResult(this.inferredType,
       this.nullAwareActionType, this.nullAwareGuards, this.nullAwareAction)
       : assert(nullAwareGuards.isNotEmpty),
+        // ignore: unnecessary_null_comparison
         assert(nullAwareAction != null);
 
   Expression get expression {
@@ -4828,7 +4899,7 @@
     while (nullAwareGuard.isNotEmpty) {
       expression =
           nullAwareGuard.head.createExpression(inferredType, expression);
-      nullAwareGuard = nullAwareGuard.tail;
+      nullAwareGuard = nullAwareGuard.tail!;
     }
     return new ExpressionInferenceResult(inferredType, expression);
   }
@@ -4890,14 +4961,16 @@
 /// `o.foo = ...`.
 class ObjectAccessTarget {
   final ObjectAccessTargetKind kind;
-  final Member member;
+  final Member? member;
 
   const ObjectAccessTarget.internal(this.kind, this.member);
 
   /// Creates an access to the instance [member].
   factory ObjectAccessTarget.interfaceMember(Member member,
-      {bool isPotentiallyNullable}) {
+      {required bool isPotentiallyNullable}) {
+    // ignore: unnecessary_null_comparison
     assert(member != null);
+    // ignore: unnecessary_null_comparison
     assert(isPotentiallyNullable != null);
     return new ObjectAccessTarget.internal(
         isPotentiallyNullable
@@ -4908,6 +4981,7 @@
 
   /// Creates an access to the Object [member].
   factory ObjectAccessTarget.objectMember(Member member) {
+    // ignore: unnecessary_null_comparison
     assert(member != null);
     return new ObjectAccessTarget.internal(
         ObjectAccessTargetKind.objectMember, member);
@@ -4916,7 +4990,7 @@
   /// Creates an access to the extension [member].
   factory ObjectAccessTarget.extensionMember(
       Member member,
-      Member tearoffTarget,
+      Member? tearoffTarget,
       ProcedureKind kind,
       List<DartType> inferredTypeArguments,
       {bool isPotentiallyNullable}) = ExtensionAccessTarget;
@@ -5025,7 +5099,7 @@
   /// This is currently used for extension methods.
   // TODO(johnniwinther): Normalize use by having `readTarget` and
   //  `invokeTarget`?
-  Member get tearoffTarget =>
+  Member? get tearoffTarget =>
       throw new UnsupportedError('ObjectAccessTarget.tearoffTarget');
 
   @override
@@ -5033,7 +5107,7 @@
 }
 
 class ExtensionAccessTarget extends ObjectAccessTarget {
-  final Member tearoffTarget;
+  final Member? tearoffTarget;
   final ProcedureKind extensionMethodKind;
   final List<DartType> inferredExtensionTypeArguments;
 
@@ -5072,10 +5146,11 @@
 
   ExtensionAccessCandidate(this.memberBuilder, this.onType,
       this.onTypeInstantiateToBounds, this.target,
-      {this.isPlatform})
+      {required this.isPlatform})
+      // ignore: unnecessary_null_comparison
       : assert(isPlatform != null);
 
-  bool isMoreSpecificThan(TypeSchemaEnvironment typeSchemaEnvironment,
+  bool? isMoreSpecificThan(TypeSchemaEnvironment typeSchemaEnvironment,
       ExtensionAccessCandidate other) {
     if (this.isPlatform == other.isPlatform) {
       // Both are platform or not platform.
@@ -5157,8 +5232,8 @@
 
 class AssignabilityResult {
   final AssignabilityKind kind;
-  final DartType subtype; // Can be null.
-  final DartType supertype; // Can be null.
+  final DartType? subtype; // Can be null.
+  final DartType? supertype; // Can be null.
 
   const AssignabilityResult(this.kind)
       : subtype = null,
@@ -5185,40 +5260,41 @@
 
 class InferredFunctionBody {
   final Statement body;
-  final DartType futureValueType;
+  final DartType? futureValueType;
 
   InferredFunctionBody(this.body, this.futureValueType);
 }
 
 class _WhyNotPromotedVisitor
     implements
-        NonPromotionReasonVisitor<LocatedMessage, Node, VariableDeclaration,
+        NonPromotionReasonVisitor<LocatedMessage?, Node, VariableDeclaration,
             DartType> {
   final TypeInferrerImpl inferrer;
 
-  Member propertyReference;
+  Member? propertyReference;
 
-  DartType propertyType;
+  DartType? propertyType;
 
   _WhyNotPromotedVisitor(this.inferrer);
 
   @override
-  LocatedMessage visitDemoteViaExplicitWrite(
+  LocatedMessage? visitDemoteViaExplicitWrite(
       DemoteViaExplicitWrite<VariableDeclaration> reason) {
     TreeNode node = reason.node as TreeNode;
     if (inferrer.dataForTesting != null) {
-      inferrer.dataForTesting.flowAnalysisResult
+      inferrer.dataForTesting!.flowAnalysisResult
           .nonPromotionReasonTargets[node] = reason.shortName;
     }
     int offset = node.fileOffset;
     return templateVariableCouldBeNullDueToWrite
-        .withArguments(reason.variable.name, reason.documentationLink)
-        .withLocation(inferrer.helper.uri, offset, noLength);
+        .withArguments(reason.variable.name!, reason.documentationLink)
+        .withLocation(inferrer.helper!.uri, offset, noLength);
   }
 
   @override
-  LocatedMessage visitPropertyNotPromoted(PropertyNotPromoted reason) {
-    Object member = reason.propertyMember;
+  LocatedMessage? visitPropertyNotPromoted(
+      PropertyNotPromoted<DartType> reason) {
+    Object? member = reason.propertyMember;
     if (member is Member) {
       propertyReference = member;
       propertyType = reason.staticType;
@@ -5239,3 +5315,9 @@
         .withoutLocation();
   }
 }
+
+/// Sentinel type used as the result in top level inference when the type is
+/// not needed.
+// TODO(johnniwinther): Should we have a special DartType implementation for
+// this.
+final DartType noInferredType = new UnknownType();
diff --git a/pkg/front_end/lib/src/fasta/type_inference/type_schema_environment.dart b/pkg/front_end/lib/src/fasta/type_inference/type_schema_environment.dart
index f7e463b..ea946df 100644
--- a/pkg/front_end/lib/src/fasta/type_inference/type_schema_environment.dart
+++ b/pkg/front_end/lib/src/fasta/type_inference/type_schema_environment.dart
@@ -243,11 +243,11 @@
   /// If non-null values for [formalTypes] and [actualTypes] are provided, this
   /// is upwards inference.  Otherwise it is downward inference.
   void inferGenericFunctionOrType(
-      DartType declaredReturnType,
+      DartType? declaredReturnType,
       List<TypeParameter> typeParametersToInfer,
       List<DartType>? formalTypes,
       List<DartType>? actualTypes,
-      DartType returnContextType,
+      DartType? returnContextType,
       List<DartType> inferredTypes,
       Library clientLibrary,
       {bool isConst: false}) {
@@ -272,9 +272,9 @@
                 clientLibrary.isNonNullableByDefault
                     ? objectNullableRawType
                     : objectLegacyRawType)
-            .substituteType(returnContextType);
+            .substituteType(returnContextType!);
       }
-      gatherer.tryConstrainUpper(declaredReturnType, returnContextType);
+      gatherer.tryConstrainUpper(declaredReturnType!, returnContextType!);
     }
 
     if (formalTypes != null) {
diff --git a/pkg/front_end/lib/src/kernel_generator_impl.dart b/pkg/front_end/lib/src/kernel_generator_impl.dart
index f7c635b..b8b73a0 100644
--- a/pkg/front_end/lib/src/kernel_generator_impl.dart
+++ b/pkg/front_end/lib/src/kernel_generator_impl.dart
@@ -2,8 +2,6 @@
 // for 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
-
 /// Defines the front-end API for converting source code to Dart Kernel objects.
 library front_end.kernel_generator_impl;
 
@@ -70,7 +68,7 @@
   options.reportNullSafetyCompilationModeInfo();
   FileSystem fs = options.fileSystem;
 
-  Loader sourceLoader;
+  Loader? sourceLoader;
   return withCrashReporting<CompilerResult>(() async {
     UriTranslator uriTranslator = await options.getUriTranslator();
 
@@ -79,7 +77,7 @@
 
     List<Component> loadedComponents = <Component>[];
 
-    Component sdkSummary = await options.loadSdkSummary(null);
+    Component? sdkSummary = await options.loadSdkSummary(null);
     // By using the nameRoot of the the summary, we enable sharing the
     // sdkSummary between multiple invocations.
     CanonicalName nameRoot = sdkSummary?.root ?? new CanonicalName.root();
@@ -100,8 +98,8 @@
     sourceLoader = kernelTarget.loader;
     kernelTarget.setEntryPoints(options.inputs);
     Component summaryComponent =
-        await kernelTarget.buildOutlines(nameRoot: nameRoot);
-    List<int> summary = null;
+        (await kernelTarget.buildOutlines(nameRoot: nameRoot))!;
+    List<int>? summary = null;
     if (buildSummary) {
       if (options.verify) {
         for (LocatedMessage error
@@ -160,7 +158,7 @@
       options.ticker.logMs("Generated outline");
     }
 
-    Component component;
+    Component? component;
     if (buildComponent) {
       component = await kernelTarget.buildComponent(verify: options.verify);
       if (options.debugDump) {
@@ -187,12 +185,12 @@
 /// Result object of [generateKernel].
 class InternalCompilerResult implements CompilerResult {
   /// The generated summary bytes, if it was requested.
-  final List<int> summary;
+  final List<int>? summary;
 
   /// The generated component, if it was requested.
-  final Component component;
+  final Component? component;
 
-  final Component sdkComponent;
+  final Component? sdkComponent;
 
   final List<Component> loadedComponents;
 
@@ -202,21 +200,21 @@
   /// using the compiler itself.
   final List<Uri> deps;
 
-  final ClassHierarchy classHierarchy;
+  final ClassHierarchy? classHierarchy;
 
-  final CoreTypes coreTypes;
+  final CoreTypes? coreTypes;
 
   /// The [KernelTarget] used to generated the component.
   ///
   /// This is only provided for use in testing.
-  final KernelTarget kernelTargetForTesting;
+  final KernelTarget? kernelTargetForTesting;
 
   InternalCompilerResult(
       {this.summary,
       this.component,
       this.sdkComponent,
-      this.loadedComponents,
-      this.deps,
+      required this.loadedComponents,
+      required this.deps,
       this.classHierarchy,
       this.coreTypes,
       this.kernelTargetForTesting});
diff --git a/pkg/front_end/lib/src/testing/id_extractor.dart b/pkg/front_end/lib/src/testing/id_extractor.dart
index eb7832a..50cf52f 100644
--- a/pkg/front_end/lib/src/testing/id_extractor.dart
+++ b/pkg/front_end/lib/src/testing/id_extractor.dart
@@ -2,17 +2,15 @@
 // for 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 'package:_fe_analyzer_shared/src/testing/id.dart';
 import 'package:kernel/ast.dart';
 import '../api_prototype/lowering_predicates.dart';
 
 /// Compute a canonical [Id] for kernel-based nodes.
-Id computeMemberId(Member node) {
-  String className;
+MemberId computeMemberId(Member node) {
+  String? className;
   if (node.enclosingClass != null) {
-    className = node.enclosingClass.name;
+    className = node.enclosingClass!.name;
   }
   String memberName = node.name.text;
   if (node is Procedure && node.kind == ProcedureKind.Setter) {
@@ -21,7 +19,7 @@
   return new MemberId.internal(memberName, className: className);
 }
 
-TreeNode computeTreeNodeWithOffset(TreeNode node) {
+TreeNode? computeTreeNodeWithOffset(TreeNode? node) {
   while (node != null) {
     if (node.fileOffset != TreeNode.noOffset) {
       return node;
@@ -41,70 +39,66 @@
   /// Implement this to compute the data corresponding to [library].
   ///
   /// If `null` is returned, [library] has no associated data.
-  T computeLibraryValue(Id id, Library library) => null;
+  T? computeLibraryValue(Id id, Library library) => null;
 
   /// Implement this to compute the data corresponding to [cls].
   ///
   /// If `null` is returned, [cls] has no associated data.
-  T computeClassValue(Id id, Class cls) => null;
+  T? computeClassValue(Id id, Class cls) => null;
 
   /// Implement this to compute the data corresponding to [extension].
   ///
   /// If `null` is returned, [extension] has no associated data.
-  T computeExtensionValue(Id id, Extension extension) => null;
+  T? computeExtensionValue(Id id, Extension extension) => null;
 
   /// Implement this to compute the data corresponding to [member].
   ///
   /// If `null` is returned, [member] has no associated data.
-  T computeMemberValue(Id id, Member member) => null;
+  T? computeMemberValue(Id id, Member member) => null;
 
   /// Implement this to compute the data corresponding to [node].
   ///
   /// If `null` is returned, [node] has no associated data.
-  T computeNodeValue(Id id, TreeNode node) => null;
+  T? computeNodeValue(Id id, TreeNode node) => null;
 
   DataExtractor(this.actualMap);
 
   void computeForLibrary(Library library) {
     LibraryId id = new LibraryId(library.fileUri);
-    T value = computeLibraryValue(id, library);
-    registerValue(library.fileUri, null, id, value, library);
+    T? value = computeLibraryValue(id, library);
+    registerValue(library.fileUri, -1, id, value, library);
   }
 
   void computeForClass(Class cls) {
     ClassId id = new ClassId(cls.name);
-    T value = computeClassValue(id, cls);
-    TreeNode nodeWithOffset = computeTreeNodeWithOffset(cls);
-    registerValue(nodeWithOffset?.location?.file, nodeWithOffset?.fileOffset,
-        id, value, cls);
+    T? value = computeClassValue(id, cls);
+    registerValue(cls.fileUri, cls.fileOffset, id, value, cls);
   }
 
   void computeForExtension(Extension extension) {
     ClassId id = new ClassId(extension.name);
-    T value = computeExtensionValue(id, extension);
-    TreeNode nodeWithOffset = computeTreeNodeWithOffset(extension);
-    registerValue(nodeWithOffset?.location?.file, nodeWithOffset?.fileOffset,
-        id, value, extension);
+    T? value = computeExtensionValue(id, extension);
+    registerValue(
+        extension.fileUri, extension.fileOffset, id, value, extension);
   }
 
   void computeForMember(Member member) {
     MemberId id = computeMemberId(member);
+    // ignore: unnecessary_null_comparison
     if (id == null) return;
-    T value = computeMemberValue(id, member);
-    TreeNode nodeWithOffset = computeTreeNodeWithOffset(member);
-    registerValue(nodeWithOffset?.location?.file, nodeWithOffset?.fileOffset,
-        id, value, member);
+    T? value = computeMemberValue(id, member);
+    registerValue(member.fileUri, member.fileOffset, id, value, member);
   }
 
-  void computeForNode(TreeNode node, NodeId id) {
+  void computeForNode(TreeNode node, NodeId? id) {
     if (id == null) return;
-    T value = computeNodeValue(id, node);
-    TreeNode nodeWithOffset = computeTreeNodeWithOffset(node);
-    registerValue(nodeWithOffset?.location?.file, nodeWithOffset?.fileOffset,
-        id, value, node);
+    T? value = computeNodeValue(id, node);
+    TreeNode nodeWithOffset = computeTreeNodeWithOffset(node)!;
+    registerValue(nodeWithOffset.location!.file, nodeWithOffset.fileOffset, id,
+        value, node);
   }
 
-  NodeId computeDefaultNodeId(TreeNode node,
+  NodeId? computeDefaultNodeId(TreeNode node,
       {bool skipNodeWithNoOffset: false}) {
     if (skipNodeWithNoOffset && node.fileOffset == TreeNode.noOffset) {
       return null;
@@ -144,7 +138,7 @@
     return new NodeId(node.fileOffset, IdKind.moveNext);
   }
 
-  NodeId createExpressionStatementId(ExpressionStatement node) {
+  NodeId? createExpressionStatementId(ExpressionStatement node) {
     if (node.expression.fileOffset == TreeNode.noOffset) {
       // TODO(johnniwinther): Find out why we something have no offset.
       return null;
@@ -152,15 +146,15 @@
     return new NodeId(node.expression.fileOffset, IdKind.stmt);
   }
 
-  NodeId createLabeledStatementId(LabeledStatement node) =>
+  NodeId? createLabeledStatementId(LabeledStatement node) =>
       computeDefaultNodeId(node.body);
-  NodeId createLoopId(TreeNode node) => computeDefaultNodeId(node);
-  NodeId createGotoId(TreeNode node) => computeDefaultNodeId(node);
-  NodeId createSwitchId(SwitchStatement node) => computeDefaultNodeId(node);
+  NodeId? createLoopId(TreeNode node) => computeDefaultNodeId(node);
+  NodeId? createGotoId(TreeNode node) => computeDefaultNodeId(node);
+  NodeId? createSwitchId(SwitchStatement node) => computeDefaultNodeId(node);
   NodeId createSwitchCaseId(SwitchCase node) =>
       new NodeId(node.expressionOffsets.first, IdKind.node);
 
-  NodeId createImplicitAsId(AsExpression node) {
+  NodeId? createImplicitAsId(AsExpression node) {
     if (node.fileOffset == TreeNode.noOffset) {
       // TODO(johnniwinther): Find out why we something have no offset.
       return null;
@@ -533,7 +527,7 @@
 
   @override
   visitThisExpression(ThisExpression node) {
-    TreeNode parent = node.parent;
+    TreeNode parent = node.parent!;
     if (node.fileOffset == TreeNode.noOffset ||
         (parent is PropertyGet ||
                 parent is InstanceGet ||
diff --git a/pkg/front_end/lib/src/testing/id_testing_utils.dart b/pkg/front_end/lib/src/testing/id_testing_utils.dart
index eaba8c7..fafad3a 100644
--- a/pkg/front_end/lib/src/testing/id_testing_utils.dart
+++ b/pkg/front_end/lib/src/testing/id_testing_utils.dart
@@ -2,8 +2,6 @@
 // for 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 'package:kernel/ast.dart';
 
 import '../fasta/builder/class_builder.dart';
@@ -29,15 +27,15 @@
 /// Returns a canonical qualified name for [member].
 String getQualifiedMemberName(Member member) {
   if (member.enclosingClass != null) {
-    return '${member.enclosingClass.name}.${getMemberName(member)}';
+    return '${member.enclosingClass!.name}.${getMemberName(member)}';
   }
   return getMemberName(member);
 }
 
 /// Returns the enclosing [Member] for [node].
-Member getEnclosingMember(TreeNode node) {
+Member getEnclosingMember(TreeNode? node) {
   while (node is! Member) {
-    node = node.parent;
+    node = node!.parent;
   }
   return node;
 }
@@ -45,78 +43,88 @@
 /// Finds the first [Library] in [component] with the given import [uri].
 ///
 /// If [required] is `true` an error is thrown if no library was found.
-Library lookupLibrary(Component component, Uri uri, {bool required: true}) {
-  return component.libraries
-      .firstWhere((Library library) => library.importUri == uri, orElse: () {
-    if (required) {
-      throw new ArgumentError("Library '$uri' not found.");
+Library? lookupLibrary(Component component, Uri uri, {bool required: true}) {
+  for (Library library in component.libraries) {
+    if (library.importUri == uri) {
+      return library;
     }
-    return null;
-  });
+  }
+  if (required) {
+    throw new ArgumentError("Library '$uri' not found.");
+  }
+  return null;
 }
 
 /// Finds the first [Class] in [library] with the given [className].
 ///
 /// If [required] is `true` an error is thrown if no class was found.
-Class lookupClass(Library library, String className, {bool required: true}) {
-  return library.classes.firstWhere((Class cls) => cls.name == className,
-      orElse: () {
-    if (required) {
-      throw new ArgumentError("Class '$className' not found in '$library'.");
+Class? lookupClass(Library library, String className, {bool required: true}) {
+  for (Class cls in library.classes) {
+    if (cls.name == className) {
+      return cls;
     }
-    return null;
-  });
+  }
+  if (required) {
+    throw new ArgumentError("Class '$className' not found in '$library'.");
+  }
+  return null;
 }
 
 /// Finds the first [Extension] in [library] with the given [className].
 ///
 /// If [required] is `true` an error is thrown if no class was found.
-Extension lookupExtension(Library library, String extensionName,
+Extension? lookupExtension(Library library, String extensionName,
     {bool required: true}) {
-  return library.extensions.firstWhere(
-      (Extension extension) => extension.name == extensionName, orElse: () {
-    if (required) {
-      throw new ArgumentError(
-          "Extension '$extensionName' not found in '${library.importUri}'.");
+  for (Extension extension in library.extensions) {
+    if (extension.name == extensionName) {
+      return extension;
     }
-    return null;
-  });
+  }
+  if (required) {
+    throw new ArgumentError(
+        "Extension '$extensionName' not found in '${library.importUri}'.");
+  }
+  return null;
 }
 
 /// Finds the first [Member] in [library] with the given canonical simple
 /// [memberName] as computed by [getMemberName].
 ///
 /// If [required] is `true` an error is thrown if no member was found.
-Member lookupLibraryMember(Library library, String memberName,
+Member? lookupLibraryMember(Library library, String memberName,
     {bool required: true}) {
-  return library.members.firstWhere(
-      (Member member) => getMemberName(member) == memberName, orElse: () {
-    if (required) {
-      throw new ArgumentError("Member '$memberName' not found in '$library'.");
+  for (Member member in library.members) {
+    if (getMemberName(member) == memberName) {
+      return member;
     }
-    return null;
-  });
+  }
+  if (required) {
+    throw new ArgumentError("Member '$memberName' not found in '$library'.");
+  }
+  return null;
 }
 
 /// Finds the first [Member] in [cls] with the given canonical simple
 /// [memberName] as computed by [getMemberName].
 ///
 /// If [required] is `true` an error is thrown if no member was found.
-Member lookupClassMember(Class cls, String memberName, {bool required: true}) {
-  return cls.members.firstWhere(
-      (Member member) => getMemberName(member) == memberName, orElse: () {
-    if (required) {
-      throw new ArgumentError("Member '$memberName' not found in '$cls'.");
+Member? lookupClassMember(Class cls, String memberName, {bool required: true}) {
+  for (Member member in cls.members) {
+    if (getMemberName(member) == memberName) {
+      return member;
     }
-    return null;
-  });
+  }
+  if (required) {
+    throw new ArgumentError("Member '$memberName' not found in '$cls'.");
+  }
+  return null;
 }
 
-LibraryBuilder lookupLibraryBuilder(
+LibraryBuilder? lookupLibraryBuilder(
     InternalCompilerResult compilerResult, Library library,
     {bool required: true}) {
-  SourceLoader loader = compilerResult.kernelTargetForTesting.loader;
-  SourceLibraryBuilder builder = loader.builders[library.importUri];
+  SourceLoader loader = compilerResult.kernelTargetForTesting!.loader;
+  LibraryBuilder? builder = loader.builders[library.importUri];
   if (builder == null && required) {
     throw new ArgumentError("DeclarationBuilder for $library not found.");
   }
@@ -127,30 +135,32 @@
     InternalCompilerResult compilerResult, Library library,
     {bool required: true}) {
   SourceLibraryBuilder builder =
-      lookupLibraryBuilder(compilerResult, library, required: required);
+      lookupLibraryBuilder(compilerResult, library, required: required)
+          as SourceLibraryBuilder;
   return builder.libraryDeclaration;
 }
 
-ClassBuilder lookupClassBuilder(
+ClassBuilder? lookupClassBuilder(
     InternalCompilerResult compilerResult, Class cls,
     {bool required: true}) {
   TypeParameterScopeBuilder libraryBuilder = lookupLibraryDeclarationBuilder(
       compilerResult, cls.enclosingLibrary,
       required: required);
-  ClassBuilder clsBuilder = libraryBuilder.members[cls.name];
+  ClassBuilder? clsBuilder = libraryBuilder.members![cls.name] as ClassBuilder?;
   if (clsBuilder == null && required) {
     throw new ArgumentError("ClassBuilder for $cls not found.");
   }
   return clsBuilder;
 }
 
-ExtensionBuilder lookupExtensionBuilder(
+ExtensionBuilder? lookupExtensionBuilder(
     InternalCompilerResult compilerResult, Extension extension,
     {bool required: true}) {
   TypeParameterScopeBuilder libraryBuilder = lookupLibraryDeclarationBuilder(
       compilerResult, extension.enclosingLibrary,
       required: required);
-  ExtensionBuilder extensionBuilder = libraryBuilder.members[extension.name];
+  ExtensionBuilder? extensionBuilder =
+      libraryBuilder.members![extension.name] as ExtensionBuilder?;
   if (extensionBuilder == null && required) {
     throw new ArgumentError("ExtensionBuilder for $extension not found.");
   }
@@ -159,18 +169,18 @@
 
 /// Look up the [MemberBuilder] for [member] through the [ClassBuilder] for
 /// [cls] using [memberName] as its name.
-MemberBuilder lookupClassMemberBuilder(InternalCompilerResult compilerResult,
+MemberBuilder? lookupClassMemberBuilder(InternalCompilerResult compilerResult,
     Class cls, Member member, String memberName,
     {bool required: true}) {
-  ClassBuilder classBuilder =
+  ClassBuilder? classBuilder =
       lookupClassBuilder(compilerResult, cls, required: required);
-  MemberBuilder memberBuilder;
+  MemberBuilder? memberBuilder;
   if (classBuilder != null) {
     if (member is Constructor || member is Procedure && member.isFactory) {
       memberBuilder = classBuilder.constructors.local[memberName];
     } else {
       memberBuilder = classBuilder.scope.lookupLocalMember(memberName,
-          setter: member is Procedure && member.isSetter);
+          setter: member is Procedure && member.isSetter) as MemberBuilder?;
     }
   }
   if (memberBuilder == null && required) {
@@ -179,10 +189,10 @@
   return memberBuilder;
 }
 
-MemberBuilder lookupMemberBuilder(
+MemberBuilder? lookupMemberBuilder(
     InternalCompilerResult compilerResult, Member member,
     {bool required: true}) {
-  MemberBuilder memberBuilder;
+  MemberBuilder? memberBuilder;
   if (member.isExtensionMember) {
     String memberName = member.name.text;
     String extensionName = memberName.substring(0, memberName.indexOf('|'));
@@ -194,23 +204,25 @@
     } else if (memberName.startsWith('get#')) {
       memberName = memberName.substring(4);
     }
-    Extension extension =
-        lookupExtension(member.enclosingLibrary, extensionName);
+    Extension extension = lookupExtension(
+        member.enclosingLibrary, extensionName,
+        required: true)!;
     memberBuilder = lookupExtensionMemberBuilder(
         compilerResult, extension, member, memberName,
         isSetter: isSetter, required: required);
   } else if (member.enclosingClass != null) {
     memberBuilder = lookupClassMemberBuilder(
-        compilerResult, member.enclosingClass, member, member.name.text,
+        compilerResult, member.enclosingClass!, member, member.name.text,
         required: required);
   } else {
     TypeParameterScopeBuilder libraryBuilder = lookupLibraryDeclarationBuilder(
         compilerResult, member.enclosingLibrary,
         required: required);
     if (member is Procedure && member.isSetter) {
-      memberBuilder = libraryBuilder.setters[member.name.text];
+      memberBuilder = libraryBuilder.setters![member.name.text];
     } else {
-      memberBuilder = libraryBuilder.members[member.name.text];
+      memberBuilder =
+          libraryBuilder.members![member.name.text] as MemberBuilder?;
     }
   }
   if (memberBuilder == null && required) {
@@ -221,19 +233,19 @@
 
 /// Look up the [MemberBuilder] for [member] through the [ExtensionBuilder] for
 /// [extension] using [memberName] as its name.
-MemberBuilder lookupExtensionMemberBuilder(
+MemberBuilder? lookupExtensionMemberBuilder(
     InternalCompilerResult compilerResult,
     Extension extension,
     Member member,
     String memberName,
     {bool isSetter: false,
     bool required: true}) {
-  ExtensionBuilder extensionBuilder =
+  ExtensionBuilder? extensionBuilder =
       lookupExtensionBuilder(compilerResult, extension, required: required);
-  MemberBuilder memberBuilder;
+  MemberBuilder? memberBuilder;
   if (extensionBuilder != null) {
-    memberBuilder =
-        extensionBuilder.scope.lookupLocalMember(memberName, setter: isSetter);
+    memberBuilder = extensionBuilder.scope
+        .lookupLocalMember(memberName, setter: isSetter) as MemberBuilder?;
   }
   if (memberBuilder == null && required) {
     throw new ArgumentError("MemberBuilder for $member not found.");
@@ -276,10 +288,10 @@
 void _getAllSuperclasses(Class node, Set<Class> set) {
   if (set.add(node)) {
     if (node.supertype != null) {
-      _getAllSuperclasses(node.supertype.classNode, set);
+      _getAllSuperclasses(node.supertype!.classNode, set);
     }
     if (node.mixedInType != null) {
-      _getAllSuperclasses(node.mixedInType.classNode, set);
+      _getAllSuperclasses(node.mixedInType!.classNode, set);
     }
     for (Supertype interface in node.implementedTypes) {
       _getAllSuperclasses(interface.classNode, set);
@@ -389,11 +401,11 @@
     if (node.fieldValues.isNotEmpty) {
       sb.write(',{');
       String comma = '';
-      for (Reference ref in node.fieldValues.keys) {
+      for (MapEntry<Reference, Constant> entry in node.fieldValues.entries) {
         sb.write(comma);
-        sb.write(getMemberName(ref.asField));
+        sb.write(getMemberName(entry.key.asField));
         sb.write(':');
-        visit(node.fieldValues[ref]);
+        visit(entry.value);
         comma = ',';
       }
       sb.write('}');
@@ -591,7 +603,7 @@
     sb.write(nullabilityToText(node.nullability, typeRepresentation));
     if (node.promotedBound != null) {
       sb.write(' & ');
-      visit(node.promotedBound);
+      visit(node.promotedBound!);
     }
   }
 
@@ -629,7 +641,7 @@
 /// Returns a textual representation of the [typeParameter] to be used in
 /// testing.
 String typeParameterToText(TypeParameter typeParameter) {
-  String name = typeParameter.name;
+  String name = typeParameter.name!;
   if (!isObject(typeParameter.bound)) {
     return '$name extends ${typeToText(typeParameter.bound)}';
   }
@@ -646,9 +658,9 @@
 void _typeBuilderToText(TypeBuilder type, StringBuffer sb) {
   if (type is NamedTypeBuilder) {
     sb.write(type.name);
-    if (type.arguments != null && type.arguments.isNotEmpty) {
+    if (type.arguments != null && type.arguments!.isNotEmpty) {
       sb.write('<');
-      _typeBuildersToText(type.arguments, sb);
+      _typeBuildersToText(type.arguments!, sb);
       sb.write('>');
     }
   } else {
@@ -670,7 +682,7 @@
 String typeVariableBuilderToText(TypeVariableBuilder typeVariable) {
   String name = typeVariable.name;
   if (typeVariable.bound != null) {
-    return '$name extends ${typeBuilderToText(typeVariable.bound)}';
+    return '$name extends ${typeBuilderToText(typeVariable.bound!)}';
   }
   return name;
 }
@@ -733,7 +745,6 @@
         case TypeRepresentation.analyzerNonNullableByDefault:
           return '';
       }
-      break;
     case Nullability.nullable:
       return '?';
     case Nullability.undetermined:
@@ -743,7 +754,6 @@
         default:
           return '%';
       }
-      break;
     case Nullability.legacy:
       switch (typeRepresentation) {
         case TypeRepresentation.legacy:
@@ -752,7 +762,5 @@
         case TypeRepresentation.analyzerNonNullableByDefault:
           return '*';
       }
-      break;
   }
-  throw new UnsupportedError('Unexpected nullability: $nullability.');
 }
diff --git a/pkg/front_end/test/explicit_creation_git_test.dart b/pkg/front_end/test/explicit_creation_git_test.dart
index 9229e49..0b6b6e0 100644
--- a/pkg/front_end/test/explicit_creation_git_test.dart
+++ b/pkg/front_end/test/explicit_creation_git_test.dart
@@ -15,7 +15,6 @@
     show computePlatformBinariesLocation;
 import 'package:front_end/src/fasta/builder/declaration_builder.dart';
 import 'package:front_end/src/fasta/builder/field_builder.dart';
-import 'package:front_end/src/fasta/builder/library_builder.dart';
 import 'package:front_end/src/fasta/builder/modifier_builder.dart';
 import 'package:front_end/src/fasta/builder/type_declaration_builder.dart';
 import 'package:front_end/src/fasta/builder/unresolved_type.dart';
@@ -137,7 +136,7 @@
   }
 
   BodyBuilder createBodyBuilderForOutlineExpression(
-      LibraryBuilder library,
+      SourceLibraryBuilder library,
       DeclarationBuilder declarationBuilder,
       ModifierBuilder member,
       Scope scope,
diff --git a/pkg/front_end/test/fasta/generator_to_string_test.dart b/pkg/front_end/test/fasta/generator_to_string_test.dart
index a1c3537..506d663 100644
--- a/pkg/front_end/test/fasta/generator_to_string_test.dart
+++ b/pkg/front_end/test/fasta/generator_to_string_test.dart
@@ -10,12 +10,15 @@
     show Token, scanString;
 
 import 'package:expect/expect.dart' show Expect;
+import 'package:front_end/src/fasta/scope.dart';
+import 'package:front_end/src/fasta/type_inference/type_inference_engine.dart';
 import 'package:front_end/src/fasta/uri_translator.dart';
 
 import 'package:kernel/ast.dart'
     show
         Arguments,
         Class,
+        Component,
         DartType,
         Expression,
         FunctionNode,
@@ -29,6 +32,8 @@
         VariableGet,
         VoidType,
         defaultLanguageVersion;
+import 'package:kernel/class_hierarchy.dart';
+import 'package:kernel/core_types.dart';
 
 import 'package:kernel/target/targets.dart' show NoneTarget, TargetFlags;
 
@@ -65,6 +70,12 @@
     Token token = scanString("    myToken").tokens;
     Uri uri = Uri.parse("org-dartlang-test:my_library.dart");
 
+    /// Create dummy variants of Component, CoreTypes and ClassHierarchy for
+    /// the BodyBuilder. These are not actually used in the test.
+    Component component = new Component();
+    CoreTypes coreTypes = new CoreTypes(component);
+    ClassHierarchy hierarchy = new ClassHierarchy(component, coreTypes);
+
     Arguments arguments = new Arguments(<Expression>[new StringLiteral("arg")]);
     DartType type = const VoidType();
     Expression expression =
@@ -84,6 +95,7 @@
                 uriTranslator)
             .loader,
         null);
+    libraryBuilder.markLanguageVersionFinal();
     LoadLibraryBuilder loadLibraryBuilder =
         new LoadLibraryBuilder(libraryBuilder, null, -1);
     Procedure getter = new Procedure(
@@ -105,10 +117,19 @@
         new TypeParameter("T"), libraryBuilder);
     VariableDeclaration variable = new VariableDeclaration(null);
 
+    TypeInferenceEngineImpl engine = new TypeInferenceEngineImpl(null);
+    engine.prepareTopLevel(coreTypes, hierarchy);
+
     BodyBuilder helper = new BodyBuilder(
         libraryBuilder: libraryBuilder,
         isDeclarationInstanceMember: false,
-        uri: uri);
+        uri: uri,
+        enclosingScope: new Scope.immutable(),
+        member: libraryBuilder,
+        coreTypes: coreTypes,
+        hierarchy: hierarchy,
+        typeInferrer:
+            engine.createTopLevelTypeInferrer(uri, null, libraryBuilder, null));
 
     Generator generator =
         new ThisAccessGenerator(helper, token, false, false, false);
@@ -196,7 +217,7 @@
             ReadOnlyAccessKind.FinalVariable));
     check(
         "ParenthesizedExpressionGenerator(offset: 4, expression: expression,"
-        " plainNameForRead: null, kind:"
+        " plainNameForRead: , kind:"
         " ReadOnlyAccessKind.ParenthesizedExpression)",
         new ParenthesizedExpressionGenerator(helper, token, expression));
     check("TypeUseGenerator(offset: 4, declaration: T, plainNameForRead: foo)",
diff --git a/pkg/front_end/test/lint_test.status b/pkg/front_end/test/lint_test.status
index 14ac1b5..25fc133 100644
--- a/pkg/front_end/test/lint_test.status
+++ b/pkg/front_end/test/lint_test.status
@@ -19,7 +19,6 @@
 front_end/lib/src/fasta/incremental_compiler/ImportsTwice: Fail
 front_end/lib/src/fasta/kernel/body_builder/ImportsTwice: Fail
 front_end/lib/src/fasta/kernel/constant_evaluator/ExplicitType: Pass
-front_end/lib/src/fasta/kernel/expression_generator_helper/ImportsTwice: Fail
 front_end/lib/src/fasta/kernel/kernel_api/Exports: Fail
 front_end/lib/src/fasta/kernel/kernel_ast_api/Exports: Fail
 front_end/lib/src/fasta/kernel/kernel_builder/Exports: Fail
diff --git a/pkg/front_end/test/parser_test_parser.dart b/pkg/front_end/test/parser_test_parser.dart
index 2eb3a9a..1e84578 100644
--- a/pkg/front_end/test/parser_test_parser.dart
+++ b/pkg/front_end/test/parser_test_parser.dart
@@ -975,7 +975,7 @@
     return result;
   }
 
-  Token parseClassMember(Token token, String className) {
+  Token parseClassMember(Token token, String? className) {
     doPrint('parseClassMember(' '$token, ' '$className)');
     indent++;
     var result = super.parseClassMember(token, className);
diff --git a/pkg/front_end/test/spell_checking_list_code.txt b/pkg/front_end/test/spell_checking_list_code.txt
index d5c6a8e..510170a 100644
--- a/pkg/front_end/test/spell_checking_list_code.txt
+++ b/pkg/front_end/test/spell_checking_list_code.txt
@@ -1148,6 +1148,7 @@
 stale
 stand
 starter
+stated
 statics
 stderr
 stdin
diff --git a/pkg/front_end/test/static_types/cfe_allowed.json b/pkg/front_end/test/static_types/cfe_allowed.json
index 13b0b3f..cd3125e 100644
--- a/pkg/front_end/test/static_types/cfe_allowed.json
+++ b/pkg/front_end/test/static_types/cfe_allowed.json
@@ -23,8 +23,5 @@
   },
   "pkg/_fe_analyzer_shared/lib/src/scanner/string_canonicalizer.dart": {
     "Dynamic invocation of '[]'.": 2
-  },
-  "pkg/front_end/lib/src/fasta/kernel/body_builder.dart": {
-    "Dynamic invocation of 'buildForEffect'.": 1
   }
 }
\ No newline at end of file
diff --git a/pkg/front_end/test/text_representation/internal_ast_text_representation_test.dart b/pkg/front_end/test/text_representation/internal_ast_text_representation_test.dart
index b706ee71..e1f4a5b 100644
--- a/pkg/front_end/test/text_representation/internal_ast_text_representation_test.dart
+++ b/pkg/front_end/test/text_representation/internal_ast_text_representation_test.dart
@@ -402,8 +402,8 @@
 }
 
 void _testNullAwareMethodInvocation() {
-  VariableDeclaration variable =
-      new VariableDeclaration.forValue(new IntLiteral(0));
+  VariableDeclarationImpl variable =
+      new VariableDeclarationImpl.forValue(new IntLiteral(0));
 
   // The usual use of this node.
   testExpression(
@@ -423,8 +423,8 @@
 }
 
 void _testNullAwarePropertyGet() {
-  VariableDeclaration variable =
-      new VariableDeclaration.forValue(new IntLiteral(0));
+  VariableDeclarationImpl variable =
+      new VariableDeclarationImpl.forValue(new IntLiteral(0));
 
   // The usual use of this node.
   testExpression(
@@ -444,8 +444,8 @@
 }
 
 void _testNullAwarePropertySet() {
-  VariableDeclaration variable =
-      new VariableDeclaration.forValue(new IntLiteral(0));
+  VariableDeclarationImpl variable =
+      new VariableDeclarationImpl.forValue(new IntLiteral(0));
 
   testExpression(
       new NullAwarePropertySet(
@@ -553,13 +553,13 @@
   testExpression(
       new IfNullPropertySet(
           new IntLiteral(0), new Name('foo'), new IntLiteral(1),
-          forEffect: false),
+          readOffset: -1, writeOffset: -1, forEffect: false),
       '0.foo ??= 1');
 
   testExpression(
       new IfNullPropertySet(
           new IntLiteral(0), new Name('foo'), new IntLiteral(1),
-          forEffect: true),
+          readOffset: -1, writeOffset: -1, forEffect: true),
       '0.foo ??= 1');
 }
 
@@ -643,31 +643,51 @@
   testExpression(
       new CompoundIndexSet(new IntLiteral(0), new IntLiteral(1), new Name('+'),
           new IntLiteral(2),
-          forEffect: false, forPostIncDec: false),
+          readOffset: -1,
+          binaryOffset: -1,
+          writeOffset: -1,
+          forEffect: false,
+          forPostIncDec: false),
       '''
 0[1] += 2''');
   testExpression(
       new CompoundIndexSet(new IntLiteral(0), new IntLiteral(1), new Name('+'),
           new IntLiteral(1),
-          forEffect: false, forPostIncDec: true),
+          readOffset: -1,
+          binaryOffset: -1,
+          writeOffset: -1,
+          forEffect: false,
+          forPostIncDec: true),
       '''
 0[1]++''');
   testExpression(
       new CompoundIndexSet(new IntLiteral(0), new IntLiteral(1), new Name('-'),
           new IntLiteral(1),
-          forEffect: false, forPostIncDec: true),
+          readOffset: -1,
+          binaryOffset: -1,
+          writeOffset: -1,
+          forEffect: false,
+          forPostIncDec: true),
       '''
 0[1]--''');
   testExpression(
       new CompoundIndexSet(new IntLiteral(0), new IntLiteral(1), new Name('*'),
           new IntLiteral(1),
-          forEffect: false, forPostIncDec: true),
+          readOffset: -1,
+          binaryOffset: -1,
+          writeOffset: -1,
+          forEffect: false,
+          forPostIncDec: true),
       '''
 0[1] *= 1''');
   testExpression(
       new CompoundIndexSet(new IntLiteral(0), new IntLiteral(1), new Name('+'),
           new IntLiteral(2),
-          forEffect: false, forPostIncDec: true),
+          readOffset: -1,
+          binaryOffset: -1,
+          writeOffset: -1,
+          forEffect: false,
+          forPostIncDec: true),
       '''
 0[1] += 2''');
 }
diff --git a/pkg/front_end/testcases/general/missing_prefix_name.dart b/pkg/front_end/testcases/general/missing_prefix_name.dart
new file mode 100644
index 0000000..45a162f
--- /dev/null
+++ b/pkg/front_end/testcases/general/missing_prefix_name.dart
@@ -0,0 +1,7 @@
+// 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 "missing_prefix_name.dart" as;
+
+main() {}
\ No newline at end of file
diff --git a/pkg/front_end/testcases/general/missing_prefix_name.dart.textual_outline.expect b/pkg/front_end/testcases/general/missing_prefix_name.dart.textual_outline.expect
new file mode 100644
index 0000000..0c82580
--- /dev/null
+++ b/pkg/front_end/testcases/general/missing_prefix_name.dart.textual_outline.expect
@@ -0,0 +1,2 @@
+import "missing_prefix_name.dart" as;
+main() {}
diff --git a/pkg/front_end/testcases/general/missing_prefix_name.dart.weak.expect b/pkg/front_end/testcases/general/missing_prefix_name.dart.weak.expect
new file mode 100644
index 0000000..fc75ee08
--- /dev/null
+++ b/pkg/front_end/testcases/general/missing_prefix_name.dart.weak.expect
@@ -0,0 +1,12 @@
+library /*isNonNullableByDefault*/;
+//
+// Problems in library:
+//
+// pkg/front_end/testcases/general/missing_prefix_name.dart:5:37: Error: Expected an identifier, but got ';'.
+// Try inserting an identifier before ';'.
+// import "missing_prefix_name.dart" as;
+//                                     ^
+//
+import self as self;
+
+static method main() → dynamic {}
diff --git a/pkg/front_end/testcases/general/missing_prefix_name.dart.weak.outline.expect b/pkg/front_end/testcases/general/missing_prefix_name.dart.weak.outline.expect
new file mode 100644
index 0000000..ef5764a
--- /dev/null
+++ b/pkg/front_end/testcases/general/missing_prefix_name.dart.weak.outline.expect
@@ -0,0 +1,13 @@
+library /*isNonNullableByDefault*/;
+//
+// Problems in library:
+//
+// pkg/front_end/testcases/general/missing_prefix_name.dart:5:37: Error: Expected an identifier, but got ';'.
+// Try inserting an identifier before ';'.
+// import "missing_prefix_name.dart" as;
+//                                     ^
+//
+import self as self;
+
+static method main() → dynamic
+  ;
diff --git a/pkg/front_end/testcases/general/missing_prefix_name.dart.weak.transformed.expect b/pkg/front_end/testcases/general/missing_prefix_name.dart.weak.transformed.expect
new file mode 100644
index 0000000..fc75ee08
--- /dev/null
+++ b/pkg/front_end/testcases/general/missing_prefix_name.dart.weak.transformed.expect
@@ -0,0 +1,12 @@
+library /*isNonNullableByDefault*/;
+//
+// Problems in library:
+//
+// pkg/front_end/testcases/general/missing_prefix_name.dart:5:37: Error: Expected an identifier, but got ';'.
+// Try inserting an identifier before ';'.
+// import "missing_prefix_name.dart" as;
+//                                     ^
+//
+import self as self;
+
+static method main() → dynamic {}
diff --git a/pkg/front_end/testcases/general/top_level_map_literal_error.dart b/pkg/front_end/testcases/general/top_level_map_literal_error.dart
new file mode 100644
index 0000000..90f94c5
--- /dev/null
+++ b/pkg/front_end/testcases/general/top_level_map_literal_error.dart
@@ -0,0 +1,9 @@
+// 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.
+
+var a = {0};
+var b = {0: 1};
+var c = {...a, ...b};
+
+main() {}
diff --git a/pkg/front_end/testcases/general/top_level_map_literal_error.dart.textual_outline.expect b/pkg/front_end/testcases/general/top_level_map_literal_error.dart.textual_outline.expect
new file mode 100644
index 0000000..2430345
--- /dev/null
+++ b/pkg/front_end/testcases/general/top_level_map_literal_error.dart.textual_outline.expect
@@ -0,0 +1,4 @@
+var a = {0};
+var b = {0: 1};
+var c = {...a, ...b};
+main() {}
diff --git a/pkg/front_end/testcases/general/top_level_map_literal_error.dart.textual_outline_modelled.expect b/pkg/front_end/testcases/general/top_level_map_literal_error.dart.textual_outline_modelled.expect
new file mode 100644
index 0000000..3040ec0
--- /dev/null
+++ b/pkg/front_end/testcases/general/top_level_map_literal_error.dart.textual_outline_modelled.expect
@@ -0,0 +1,4 @@
+main() {}
+var a = {0};
+var b = {0: 1};
+var c = {...a, ...b};
diff --git a/pkg/front_end/testcases/general/top_level_map_literal_error.dart.weak.expect b/pkg/front_end/testcases/general/top_level_map_literal_error.dart.weak.expect
new file mode 100644
index 0000000..d52f9e6
--- /dev/null
+++ b/pkg/front_end/testcases/general/top_level_map_literal_error.dart.weak.expect
@@ -0,0 +1,21 @@
+library /*isNonNullableByDefault*/;
+//
+// Problems in library:
+//
+// pkg/front_end/testcases/general/top_level_map_literal_error.dart:7:9: Error: Both Iterable and Map spread elements encountered in ambiguous literal.
+// var c = {...a, ...b};
+//         ^
+//
+import self as self;
+import "dart:core" as core;
+import "dart:collection" as col;
+
+static field core::Set<core::int> a = block {
+  final core::Set<core::int> #t1 = col::LinkedHashSet::•<core::int>();
+  #t1.{core::Set::add}{Invariant}(0){(core::int) → core::bool};
+} =>#t1;
+static field core::Map<core::int, core::int> b = <core::int, core::int>{0: 1};
+static field Never c = invalid-expression "pkg/front_end/testcases/general/top_level_map_literal_error.dart:7:9: Error: Both Iterable and Map spread elements encountered in ambiguous literal.
+var c = {...a, ...b};
+        ^";
+static method main() → dynamic {}
diff --git a/pkg/front_end/testcases/general/top_level_map_literal_error.dart.weak.outline.expect b/pkg/front_end/testcases/general/top_level_map_literal_error.dart.weak.outline.expect
new file mode 100644
index 0000000..151d5fd
--- /dev/null
+++ b/pkg/front_end/testcases/general/top_level_map_literal_error.dart.weak.outline.expect
@@ -0,0 +1,9 @@
+library /*isNonNullableByDefault*/;
+import self as self;
+import "dart:core" as core;
+
+static field core::Set<core::int> a;
+static field core::Map<core::int, core::int> b;
+static field Never c;
+static method main() → dynamic
+  ;
diff --git a/pkg/front_end/testcases/general/top_level_map_literal_error.dart.weak.transformed.expect b/pkg/front_end/testcases/general/top_level_map_literal_error.dart.weak.transformed.expect
new file mode 100644
index 0000000..d5e3691
--- /dev/null
+++ b/pkg/front_end/testcases/general/top_level_map_literal_error.dart.weak.transformed.expect
@@ -0,0 +1,21 @@
+library /*isNonNullableByDefault*/;
+//
+// Problems in library:
+//
+// pkg/front_end/testcases/general/top_level_map_literal_error.dart:7:9: Error: Both Iterable and Map spread elements encountered in ambiguous literal.
+// var c = {...a, ...b};
+//         ^
+//
+import self as self;
+import "dart:core" as core;
+import "dart:collection" as col;
+
+static field core::Set<core::int> a = block {
+  final core::Set<core::int> #t1 = new col::_CompactLinkedHashSet::•<core::int>();
+  #t1.{core::Set::add}{Invariant}(0){(core::int) → core::bool};
+} =>#t1;
+static field core::Map<core::int, core::int> b = <core::int, core::int>{0: 1};
+static field Never c = invalid-expression "pkg/front_end/testcases/general/top_level_map_literal_error.dart:7:9: Error: Both Iterable and Map spread elements encountered in ambiguous literal.
+var c = {...a, ...b};
+        ^";
+static method main() → dynamic {}
diff --git a/pkg/front_end/testcases/general/type_parameter_usage_in_static_method_in_class.dart.weak.expect b/pkg/front_end/testcases/general/type_parameter_usage_in_static_method_in_class.dart.weak.expect
index 07f8284..6b52872 100644
--- a/pkg/front_end/testcases/general/type_parameter_usage_in_static_method_in_class.dart.weak.expect
+++ b/pkg/front_end/testcases/general/type_parameter_usage_in_static_method_in_class.dart.weak.expect
@@ -156,7 +156,7 @@
       return null;
     function foo6Prime() → core::List<invalid-type>*
       return null;
-    (invalid-type) →* invalid-type foo7 = (invalid-type y) → invalid-type => y;
+    invalid-type foo7 = (invalid-type y) → invalid-type => y;
     (core::List<invalid-type>*) →* void foo7Prime = (core::List<invalid-type>* y) → core::List<invalid-type>* => y;
   }
   static method foo8() → () →* invalid-type {
diff --git a/pkg/front_end/testcases/general/type_parameter_usage_in_static_method_in_class.dart.weak.transformed.expect b/pkg/front_end/testcases/general/type_parameter_usage_in_static_method_in_class.dart.weak.transformed.expect
index 07f8284..6b52872 100644
--- a/pkg/front_end/testcases/general/type_parameter_usage_in_static_method_in_class.dart.weak.transformed.expect
+++ b/pkg/front_end/testcases/general/type_parameter_usage_in_static_method_in_class.dart.weak.transformed.expect
@@ -156,7 +156,7 @@
       return null;
     function foo6Prime() → core::List<invalid-type>*
       return null;
-    (invalid-type) →* invalid-type foo7 = (invalid-type y) → invalid-type => y;
+    invalid-type foo7 = (invalid-type y) → invalid-type => y;
     (core::List<invalid-type>*) →* void foo7Prime = (core::List<invalid-type>* y) → core::List<invalid-type>* => y;
   }
   static method foo8() → () →* invalid-type {
diff --git a/pkg/front_end/testcases/general/type_parameter_usage_in_static_method_in_extension.dart.weak.expect b/pkg/front_end/testcases/general/type_parameter_usage_in_static_method_in_extension.dart.weak.expect
index 97ad6b7..e6c02fb 100644
--- a/pkg/front_end/testcases/general/type_parameter_usage_in_static_method_in_extension.dart.weak.expect
+++ b/pkg/front_end/testcases/general/type_parameter_usage_in_static_method_in_extension.dart.weak.expect
@@ -174,7 +174,7 @@
     return null;
   function foo6Prime() → core::List<invalid-type>*
     return null;
-  (invalid-type) →* invalid-type foo7 = (invalid-type y) → invalid-type => y;
+  invalid-type foo7 = (invalid-type y) → invalid-type => y;
   (core::List<invalid-type>*) →* void foo7Prime = (core::List<invalid-type>* y) → core::List<invalid-type>* => y;
 }
 static method Foo|foo8() → () →* invalid-type {
diff --git a/pkg/front_end/testcases/general/type_parameter_usage_in_static_method_in_extension.dart.weak.transformed.expect b/pkg/front_end/testcases/general/type_parameter_usage_in_static_method_in_extension.dart.weak.transformed.expect
index 97ad6b7..e6c02fb 100644
--- a/pkg/front_end/testcases/general/type_parameter_usage_in_static_method_in_extension.dart.weak.transformed.expect
+++ b/pkg/front_end/testcases/general/type_parameter_usage_in_static_method_in_extension.dart.weak.transformed.expect
@@ -174,7 +174,7 @@
     return null;
   function foo6Prime() → core::List<invalid-type>*
     return null;
-  (invalid-type) →* invalid-type foo7 = (invalid-type y) → invalid-type => y;
+  invalid-type foo7 = (invalid-type y) → invalid-type => y;
   (core::List<invalid-type>*) →* void foo7Prime = (core::List<invalid-type>* y) → core::List<invalid-type>* => y;
 }
 static method Foo|foo8() → () →* invalid-type {
diff --git a/pkg/front_end/testcases/textual_outline.status b/pkg/front_end/testcases/textual_outline.status
index 29acb62..e245752 100644
--- a/pkg/front_end/testcases/textual_outline.status
+++ b/pkg/front_end/testcases/textual_outline.status
@@ -82,6 +82,7 @@
 general/issue45490: FormatterCrash
 general/issue45700.crash: FormatterCrash
 general/many_errors: FormatterCrash
+general/missing_prefix_name: FormatterCrash
 general/null_safety_invalid_experiment: FormatterCrash
 general/null_safety_invalid_experiment_and_language_version: FormatterCrash
 general/type_parameters_on_void: FormatterCrash
diff --git a/pkg/front_end/tool/dart_doctest_impl.dart b/pkg/front_end/tool/dart_doctest_impl.dart
index 962bfd5..661c0563 100644
--- a/pkg/front_end/tool/dart_doctest_impl.dart
+++ b/pkg/front_end/tool/dart_doctest_impl.dart
@@ -33,7 +33,6 @@
 import 'package:front_end/src/api_prototype/memory_file_system.dart';
 import 'package:front_end/src/api_prototype/standard_file_system.dart';
 import 'package:front_end/src/base/processed_options.dart';
-// ignore: import_of_legacy_library_into_null_safe
 import 'package:front_end/src/fasta/builder/library_builder.dart';
 import 'package:front_end/src/fasta/combinator.dart';
 
@@ -872,11 +871,11 @@
   LibraryBuilder createLibraryBuilder(
       Uri uri,
       Uri fileUri,
-      Uri packageUri,
+      Uri? packageUri,
       LanguageVersion packageLanguageVersion,
-      covariant LibraryBuilder origin,
-      kernel.Library referencesFrom,
-      bool referenceIsPartOwner) {
+      SourceLibraryBuilder origin,
+      kernel.Library? referencesFrom,
+      bool? referenceIsPartOwner) {
     if (uri == DocTestIncrementalCompiler.dartDocTestUri) {
       HybridFileSystem hfs = compiler.userCode.fileSystem as HybridFileSystem;
       MemoryFileSystem fs = hfs.memory;
@@ -886,13 +885,7 @@
       return compiler
           .createDartDocTestLibrary(compiler._dartDocTestLibraryBuilder!);
     }
-    return super.createLibraryBuilder(
-        uri,
-        fileUri,
-        packageUri,
-        packageLanguageVersion,
-        origin as SourceLibraryBuilder,
-        referencesFrom,
-        referenceIsPartOwner);
+    return super.createLibraryBuilder(uri, fileUri, packageUri,
+        packageLanguageVersion, origin, referencesFrom, referenceIsPartOwner);
   }
 }
diff --git a/pkg/kernel/lib/ast.dart b/pkg/kernel/lib/ast.dart
index a8a2a04..688005a 100644
--- a/pkg/kernel/lib/ast.dart
+++ b/pkg/kernel/lib/ast.dart
@@ -14276,6 +14276,13 @@
 /// constructor.
 final Constant dummyConstant = new NullConstant();
 
+/// Non-nullable [LabeledStatement] dummy value.
+///
+/// This is used as the removal sentinel in [RemovingTransformer] and can be
+/// used for instance as a dummy initial value for the `List.filled`
+/// constructor.
+final LabeledStatement dummyLabeledStatement = new LabeledStatement(null);
+
 /// Of the dummy nodes, some are tree nodes. `TreeNode`s has a parent pointer
 /// and that can be set when the dummy is used. This means that we can leak
 /// through them. This list will (at least as a stopgap) allow us to null-out
@@ -14307,6 +14314,7 @@
   dummyAssertStatement,
   dummySwitchCase,
   dummyCatch,
+  dummyLabeledStatement,
 ];
 
 /// Sentinel value used to signal that a node cannot be removed through the
diff --git a/pkg/kernel/lib/reference_from_index.dart b/pkg/kernel/lib/reference_from_index.dart
index 202c28a..0e83da3 100644
--- a/pkg/kernel/lib/reference_from_index.dart
+++ b/pkg/kernel/lib/reference_from_index.dart
@@ -110,23 +110,24 @@
 }
 
 class IndexedClass extends IndexedContainer {
+  final Class cls;
   final Map<Name, Member> _constructors = new Map<Name, Member>();
   final Library library;
 
-  IndexedClass._(Class c, this.library) {
-    for (int i = 0; i < c.constructors.length; i++) {
-      Constructor constructor = c.constructors[i];
+  IndexedClass._(this.cls, this.library) {
+    for (int i = 0; i < cls.constructors.length; i++) {
+      Constructor constructor = cls.constructors[i];
       _constructors[constructor.name] = constructor;
     }
-    for (int i = 0; i < c.procedures.length; i++) {
-      Procedure procedure = c.procedures[i];
+    for (int i = 0; i < cls.procedures.length; i++) {
+      Procedure procedure = cls.procedures[i];
       if (procedure.isFactory) {
         _constructors[procedure.name] = procedure;
       } else {
         _addProcedure(procedure);
       }
     }
-    _addFields(c.fields);
+    _addFields(cls.fields);
   }
 
   Member? lookupConstructor(Name name) => _constructors[name];
diff --git a/pkg/kernel/lib/target/targets.dart b/pkg/kernel/lib/target/targets.dart
index c84fd53..56ce4b2 100644
--- a/pkg/kernel/lib/target/targets.dart
+++ b/pkg/kernel/lib/target/targets.dart
@@ -250,11 +250,11 @@
       List<Library> libraries,
       // TODO(askesc): Consider how to generally pass compiler options to
       // transformations.
-      Map<String, String> environmentDefines,
+      Map<String, String>? environmentDefines,
       DiagnosticReporter diagnosticReporter,
       ReferenceFromIndex? referenceFromIndex,
       {void logger(String msg),
-      ChangedStructureNotifier changedStructureNotifier});
+      ChangedStructureNotifier? changedStructureNotifier});
 
   /// Perform target-specific modular transformations on the given program.
   ///
@@ -267,7 +267,7 @@
       Procedure procedure,
       // TODO(askesc): Consider how to generally pass compiler options to
       // transformations.
-      Map<String, String> environmentDefines,
+      Map<String, String>? environmentDefines,
       {void Function(String msg)? logger}) {}
 
   /// Whether a platform library may define a restricted type, such as `bool`,
@@ -466,7 +466,7 @@
       CoreTypes coreTypes,
       ClassHierarchy hierarchy,
       List<Library> libraries,
-      Map<String, String> environmentDefines,
+      Map<String, String>? environmentDefines,
       DiagnosticReporter diagnosticReporter,
       ReferenceFromIndex? referenceFromIndex,
       {void Function(String msg)? logger,
diff --git a/runtime/tools/graphexplorer/graphexplorer.css b/runtime/tools/graphexplorer/graphexplorer.css
index bb6c3d8..67c4820 100644
--- a/runtime/tools/graphexplorer/graphexplorer.css
+++ b/runtime/tools/graphexplorer/graphexplorer.css
@@ -14,6 +14,8 @@
 .headerRow {
     font-weight: bold;
     background-color: #BBBBBB;
+    display: flex;
+    flex-direction: row;
 }
 
 .nameCell {
diff --git a/runtime/tools/graphexplorer/graphexplorer.js b/runtime/tools/graphexplorer/graphexplorer.js
index 8df25e8..27b078f 100644
--- a/runtime/tools/graphexplorer/graphexplorer.js
+++ b/runtime/tools/graphexplorer/graphexplorer.js
@@ -47,6 +47,8 @@
   this.dom_ = null;
   this.domHead_ = null;
   this.domNext_ = null;
+  this.mergedDomHead_ = null;
+  this.mergedDomNext_ = null;
 
   // Intermediates.
   this.Nconnected_ = 0;  // Number of nodes reachable from root.
@@ -62,14 +64,8 @@
   this.stack_ = null;
 }
 
-// Load a graph in V8 heap profile format from `data`, then compute the graph's
-// dominator tree and the retained size of each vertex.
-//
-// If `rewriteForOwners` is true, for each vertex that has an "owner" edge,
-// replace all edges to the vertex with an edge from the owner to the vertex.
-// This can be the graph more hierachical and reveal more structure in the
-// dominator tree.
-Graph.prototype.loadV8Profile = function(data, rewriteForOwners) {
+// Load a graph in V8 heap profile format from parsed JSON `data`.
+Graph.prototype.loadV8Profile = function(data) {
   console.log("Building successors...");
 
   const N = data.snapshot.node_count;
@@ -145,10 +141,6 @@
     throw "Incorrect edge_count!";
   }
 
-  // Free memory.
-  data["nodes"] = null;
-  data["edges"] = null;
-
   this.N_ = N;
   this.E_ = E;
   this.strings_ = data.strings;
@@ -159,7 +151,170 @@
   this.class_ = clazz;
   this.shallowSize_ = shallowSize;
   this.shallowSizeSum_ = shallowSizeSum;
+};
 
+// Load a graph in Dart heap snapshot format from ArrayBuffer `data`.
+Graph.prototype.loadDartHeapSnapshot = function(data) {
+  console.log("Building successors...");
+
+  let stream = new Stream(data);
+
+  for (let i = 0; i < 8; i++) {
+    if (stream.byte() != 'dartheap'.charCodeAt(i)) {
+      throw "Wrong format identifier."
+    }
+  }
+
+  stream.uleb128();  // Flags.
+  stream.utf8();     // Name.
+  stream.uleb128();  // Shallow size (used).
+  stream.uleb128();  // Capacity.
+  stream.uleb128();  // External size.
+
+  const strings = new Array();
+  strings.push("???");
+
+  const classCount = stream.uleb128();
+  const classNames = new Uint32Array(classCount + 1);
+  classNames[0] = strings.length;
+  strings.push("Root");
+  const classEdges = new Array(classCount + 1);
+  for (let cid = 1; cid <= classCount; cid++) {
+    stream.uleb128();  // Flags.
+    classNames[cid] = strings.length;
+    strings.push(stream.utf8());  // Class name.
+    stream.utf8();  // Library name.
+    stream.utf8();  // Library name.
+    stream.utf8();  // Reserved.
+    const fieldCount = stream.uleb128();
+    const edgeNames = new Array(fieldCount + 1);
+    classEdges[cid] = edgeNames;
+    for (let j = 0; j < fieldCount; j++) {
+      stream.uleb128();  // Flags.
+      const fieldIndex = stream.uleb128();
+      const fieldName = stream.utf8();
+      stream.utf8();  // Reserved.
+
+      edgeNames[fieldIndex] = strings.length;
+      strings.push(fieldName);
+    }
+  }
+
+  const E = stream.uleb128();  // Reference count.
+  const N = stream.uleb128();  // Object count.
+
+  const firstSuccessor = new Uint32Array(N + 2);
+  const successors = new Uint32Array(E);
+  const successorName = new Uint32Array(E);
+  const name = new Uint32Array(N + 1);
+  const clazz = new Array(N + 1);
+  const shallowSize = new Uint32Array(N + 1);
+
+  name[0] = strings.length;
+  strings.push("<omitted-object>");
+  clazz[0] = "<omitted-object>";
+  const unknownEdge = strings.length;
+  strings.push("<unknown>");
+
+  let shallowSizeSum = 0;
+  let nextSuccessorIndex = 0;
+  for (let i = 1; i <= N; i++) {
+    const cid = stream.uleb128();
+    clazz[i] = strings[classNames[cid]];
+    const objShallowSize = stream.uleb128();
+    shallowSize[i] = objShallowSize;
+    shallowSizeSum += objShallowSize;
+
+    const tag = stream.uleb128();
+    switch (tag) {
+      case 0:  // NoData
+        name[i] = classNames[cid];
+        break;
+      case 1:  // NullData
+        name[i] = strings.length;
+        strings.push("null");
+        break;
+      case 2:  // BoolData
+        name[i] = strings.length;
+        strings.push(stream.uleb128() == 0 ? "false" : "true");
+        break;
+      case 3:  // IntegerData
+        name[i] = stream.sleb128();
+        break;
+      case 4:  // DoubleData
+        name[i] = stream.float64();
+        break;
+      case 5:  // Latin1StringData
+        stream.uleb128();  // Full length.
+        name[i] = strings.length;
+        strings.push(stream.latin1());
+        break;
+      case 6:  // Utf16StringData
+        stream.uleb128();  // Full length.
+        name[i] = strings.length;
+        strings.push(stream.utf16());
+        break;
+      case 7:  // LengthData
+        name[i] = strings.length;
+        strings.push(strings[classNames[cid]] + "(" + stream.uleb128() + ")");
+        break;
+      case 8:  // NameData
+        name[i] = strings.length;
+        strings.push(stream.utf8());
+        break;
+      default:
+        throw "Unknown tag " + tag;
+    }
+
+    firstSuccessor[i] = nextSuccessorIndex;
+    const edge_count = stream.uleb128();
+    for (let j = 0; j < edge_count; j++) {
+      successors[nextSuccessorIndex] = stream.uleb128();
+      successorName[nextSuccessorIndex] = unknownEdge;
+      const edgeNames = classEdges[cid];
+      if (edgeNames !== undefined) {
+        const edgeName = classEdges[cid][j];
+        if (edgeName !== undefined) {
+          successorName[nextSuccessorIndex] = edgeName;
+        }
+      }
+      nextSuccessorIndex++;
+    }
+  }
+  firstSuccessor[N + 1] = nextSuccessorIndex;
+
+  if (nextSuccessorIndex != E) {
+    throw "Incorrect edge_count!";
+  }
+
+  const externalPropertyCount = stream.uleb128();
+  for (let i = 0; i < externalPropertyCount; i++) {
+    let object = stream.uleb128();
+    let externalSize = stream.uleb128();
+    stream.utf8();  // Name.
+    shallowSize[object] += externalSize;
+    shallowSizeSum += externalSize;
+  }
+
+  this.N_ = N;
+  this.E_ = E;
+  this.strings_ = strings;
+  this.firstSuccessor_ = firstSuccessor;
+  this.successorName_ = successorName;
+  this.successors_ = successors;
+  this.name_ = name;
+  this.class_ = clazz;
+  this.shallowSize_ = shallowSize;
+  this.shallowSizeSum_ = shallowSizeSum;
+};
+
+// Compute the graph's dominator tree and the retained size of each vertex.
+//
+// If `rewriteForOwners` is true, for each vertex that has an "owner" edge,
+// replace all edges to the vertex with an edge from the owner to the vertex.
+// This can be the graph more hierachical and reveal more structure in the
+// dominator tree.
+Graph.prototype.compute = function(rewriteForOwners) {
   this.computePredecessors();
   if (rewriteForOwners) {
     this.rewriteEdgesForOwners();
@@ -168,9 +323,11 @@
   this.computeDominators();
   this.computeRetainedSizes();
   this.linkDominatorChildren();
+  this.sortDominatorChildren();
+  this.mergeDominatorSiblings(1);
 
-  this.mark_ = new Uint8Array(N + 1);
-  this.stack_ = new Uint32Array(E);
+  this.mark_ = new Uint8Array(this.N_ + 1);
+  this.stack_ = new Uint32Array(this.E_);
 };
 
 Graph.prototype.computePredecessors = function() {
@@ -193,6 +350,7 @@
        successorIndex < lastSuccessorIndex;
        successorIndex++) {
       let successor = successors[successorIndex];
+      if (successor == 0) continue;  // Omitted object.
       predecessorCount[successor]++;
     }
   }
@@ -203,9 +361,6 @@
     nextPredecessorIndex += predecessorCount[i];
   }
   firstPredecessor[N + 1] = nextPredecessorIndex;
-  if (nextPredecessorIndex != E) {
-    throw "Mismatched edges";
-  }
 
   for (let i = 1; i <= N; i++) {
     let firstSuccessorIndex = firstSuccessor[i];
@@ -214,6 +369,7 @@
        successorIndex < lastSuccessorIndex;
        successorIndex++) {
       let successor = successors[successorIndex];
+      if (successor == 0) continue;  // Omitted object.
       let count = --predecessorCount[successor];
       let predecessorIndex = firstPredecessor[successor] + count;
       predecessors[predecessorIndex] = i;
@@ -250,18 +406,24 @@
     let cls = this.class_[i];
     let ownerEdgeName;
 
-    if (cls == "Class") {
+    if (cls == "Class") {  // Dart VM
       ownerEdgeName = "library_";
-    } else if (cls == "PatchClass") {
+    } else if (cls == "PatchClass") {  // Dart VM
       ownerEdgeName = "patched_class_";
-    } else if (cls == "Function") {
+    } else if (cls == "Function") {  // Dart VM
       ownerEdgeName = "owner_";
-    } else if (cls == "Field") {
+    } else if (cls == "Field") {  // Dart VM
       ownerEdgeName = "owner_";
-    } else if (cls == "Code") {
+    } else if (cls == "Code") {  // Dart VM
       ownerEdgeName = "owner_";
-    } else if (cls == "ICData") {
+    } else if (cls == "ICData") {  // Dart VM
       ownerEdgeName = "owner_";
+    } else if (cls == "Method") {  // Primordial Soup
+      ownerEdgeName = "mixin";
+    } else if (cls.startsWith("InstanceMixin`")) {  // Primordial Soup
+      ownerEdgeName = "_enclosingMixin";
+    } else if (cls.startsWith("ClassMixin`")) {  // Primordial Soup
+      ownerEdgeName = "_instanceMixin";
     } else {
       continue;
     }
@@ -378,7 +540,11 @@
       e++;
       stackEdges[stackTop] = e;
 
-      if (semi[w] == 0) {
+      if (w == 0) {
+        // Omitted object.
+      } else if (semi[w] != 0) {
+        // Already visited.
+      } else {
         parent[w] = v;
 
         preorderNumber++;
@@ -567,6 +733,143 @@
   this.domNext_ = next;
 };
 
+// Merge the given lists according to the given key in ascending order.
+// Returns the head of the merged list.
+function mergeSorted(head1, head2, next, key) {
+  let head = head1;
+  let beforeInsert = 0;
+  let afterInsert = head1;
+  let startInsert = head2;
+
+  while (startInsert != 0) {
+    while ((afterInsert != 0) &&
+           (key[afterInsert] <= key[startInsert])) {
+      beforeInsert = afterInsert;
+      afterInsert = next[beforeInsert];
+    }
+    let endInsert = startInsert;
+    let peek = next[endInsert];
+
+    while ((peek != 0) && (key[peek] < key[afterInsert])) {
+      endInsert = peek;
+      peek = next[endInsert];
+    }
+
+    if (beforeInsert == 0) {
+      head = startInsert;
+    } else {
+      next[beforeInsert] = startInsert;
+    }
+    next[endInsert] = afterInsert;
+
+    startInsert = peek;
+    beforeInsert = endInsert;
+  }
+
+  return head;
+}
+
+Graph.prototype.sortDominatorChildren = function() {
+  console.log("Sorting dominator tree children...");
+
+  const N = this.N_;
+  const Nconnected = this.Nconnected_;
+  const cids = this.class_;
+  const head = this.domHead_;
+  const next = this.domNext_;
+
+  function sort(head) {
+    if (head == 0) return 0;
+    if (next[head] == 0) return head;
+
+    // Find the middle of the list.
+    let head1 = head;
+    let slow = head;
+    let fast = head;
+    while (next[fast] != 0 && next[next[fast]] != 0) {
+      slow = next[slow];
+      fast = next[next[fast]];
+    }
+
+    // Split the list in half.
+    let head2 = next[slow];
+    next[slow] = 0;
+
+    // Recursively sort the sublists and merge.
+    let newHead1 = sort(head1);
+    let newHead2 = sort(head2);
+    return mergeSorted(newHead1, newHead2, next, cids);
+  };
+
+  // Sort all list of dominator tree children by cid.
+  for (let parent = 1; parent <= N; parent++) {
+    head[parent] = sort(head[parent]);
+  }
+};
+
+Graph.prototype.mergeDominatorSiblings = function(root) {
+  console.log("Merging dominator tree siblings...");
+
+  const N = this.N_;
+  const cids = this.class_;
+  const head = new Uint32Array(this.domHead_);
+  const next = new Uint32Array(this.domNext_);
+  const workStack = new Uint32Array(N);
+  let workStackTop = 0;
+
+  function mergeChildrenAndSort(parent1, end) {
+    if (next[parent1] == end) return;
+
+    // Find the middle of the list.
+    let slow = parent1;
+    let fast = parent1;
+    while (next[fast] != end && next[next[fast]] != end) {
+      slow = next[slow];
+      fast = next[next[fast]];
+    }
+
+    let parent2 = next[slow];
+
+    // Recursively sort the sublists.
+    mergeChildrenAndSort(parent1, parent2);
+    mergeChildrenAndSort(parent2, end);
+
+    // Merge sorted sublists.
+    head[parent1] = mergeSorted(head[parent1], head[parent2], next, cids);
+
+    // Children moved to parent1.
+    head[parent2] = 0;
+  }
+
+  // Push root.
+  workStack[workStackTop++] = root;
+
+  while (workStackTop > 0) {
+    let parent = workStack[--workStackTop];
+
+    let child = head[parent];
+    while (child != 0) {
+      // Push child.
+      workStack[workStackTop++] = child;
+
+      // Find next sibling with a different cid.
+      let after = child;
+      while (after != 0 && cids[after] == cids[child]) {
+        after = next[after];
+      }
+
+      // From all the siblings between child and after, take their children,
+      // merge them and given to child.
+      mergeChildrenAndSort(child, after);
+
+      child = after;
+    }
+  }
+
+  this.mergedDomHead_ = head;
+  this.mergedDomNext_ = next;
+};
+
 Graph.prototype.getTotalSize = function() {
   return this.shallowSizeSum_;
 };
@@ -618,6 +921,10 @@
   }
 }
 
+Graph.prototype.parentOf = function(v) {
+  return this.dom_[v];
+};
+
 Graph.prototype.dominatorChildrenOfDo = function(v, action) {
   for (let w = this.domHead_[v]; w != 0; w = this.domNext_[w]) {
     action(w);
@@ -640,6 +947,10 @@
   return this.retainedSize_[v];
 };
 
+Graph.prototype.setFrom = function(v) {
+  return [v];
+};
+
 Graph.prototype.shallowSizeOfSet = function(nodes) {
   let sum = 0;
   for (let i = 0; i < nodes.length; i++) {
@@ -714,6 +1025,198 @@
   return sum;
 };
 
+Graph.prototype.toggleMerge = function() {
+  return new MergedGraph(this);
+};
+
+function MergedGraph(graph) {
+  this.graph_ = graph;
+}
+
+MergedGraph.prototype.nameOf = function(v) {
+  const cids = this.graph_.class_;
+  const next = this.graph_.mergedDomNext_;
+  let count = 0;
+  let sibling = v;
+  while (sibling != 0 && cids[sibling] == cids[v]) {
+    count++;
+    sibling = next[sibling];
+  }
+  return count.toString() + " instances of " + this.graph_.class_[v];
+};
+
+MergedGraph.prototype.classOf = function(v) {
+  return this.graph_.class_[v];
+};
+
+MergedGraph.prototype.shallowSizeOf = function(v) {
+  const cids = this.graph_.class_;
+  const shallowSize = this.graph_.shallowSize_;
+  const next = this.graph_.mergedDomNext_;
+  let size = 0;
+  let sibling = v;
+  while (sibling != 0 && cids[sibling] == cids[v]) {
+    size += shallowSize[sibling];
+    sibling = next[sibling];
+  }
+  return size;
+};
+
+MergedGraph.prototype.retainedSizeOf = function(v) {
+  const cids = this.graph_.class_;
+  const retainedSize = this.graph_.retainedSize_;
+  const next = this.graph_.mergedDomNext_;
+  let size = 0;
+  let sibling = v;
+  while (sibling != 0 && cids[sibling] == cids[v]) {
+    size += retainedSize[sibling];
+    sibling = next[sibling];
+  }
+  return size;
+};
+
+MergedGraph.prototype.setFrom = function(v) {
+  const cids = this.graph_.class_;
+  const next = this.graph_.mergedDomNext_;
+  let set = new Array();
+  let sibling = v;
+  while (sibling != 0 && cids[sibling] == cids[v]) {
+    set.push(sibling);
+    sibling = next[sibling];
+  }
+  return set;
+};
+
+MergedGraph.prototype.parentOf = function(v) {
+  // N.B.: Not dom_[v], which might not be the representative element of the
+  // merged group.
+  const N = this.graph_.N_;
+  const head = this.graph_.mergedDomHead_;
+  const next = this.graph_.mergedDomNext_;
+  for (let parent = 1; parent <= N; parent++) {
+    for (let child = head[parent]; child != 0; child = next[child]) {
+      if (child == v) {
+        return parent;
+      }
+    }
+  }
+  return 0;
+};
+
+MergedGraph.prototype.dominatorChildrenOfDo = function(v, action) {
+  const next = this.graph_.mergedDomNext_;
+  const cids = this.graph_.class_;
+  let prev = 0;
+  let child = this.graph_.mergedDomHead_[v];
+  // Walk the list of children and look for the representative objects, i.e.
+  // the first sibling of each cid.
+  while (child != 0) {
+    if (prev == 0 || cids[prev] != cids[child]) {
+      action(child);
+    }
+    prev = child;
+    child = next[child];
+  }
+};
+
+MergedGraph.prototype.getTotalSize = function() {
+  return this.graph_.shallowSizeSum_;
+};
+
+MergedGraph.prototype.toggleMerge = function() {
+  return this.graph_;
+};
+
+function Stream(bytes) {
+  this.bytes_ = new Uint8Array(bytes);
+  this.position_ = 0;
+}
+
+Stream.prototype.byte = function() {
+  const position = this.position_;
+  const bytes = this.bytes_;
+  if ((position >= 0) && (position < bytes.length)) {
+    const result = bytes[position];
+    this.position_ = position + 1;
+    return result;
+  }
+  throw "Attempt to read past end of stream";
+};
+
+Stream.prototype.uleb128 = function() {
+  let result = 0;
+  let shift = 0;
+  for (;;) {
+    const part = this.byte();
+    result |= (part & 0x7F) << shift;
+    if ((part & 0x80) == 0) {
+      break;
+    }
+    shift += 7;
+  }
+  return result;
+};
+
+Stream.prototype.sleb128 = function() {
+  let result = 0;
+  let shift = 0;
+  for (;;) {
+    const part = this.byte();
+    result |= (part & 0x7F) << shift;
+    shift += 7;
+    if ((part & 0x80) == 0) {
+      if ((part & 0x40) != 0) {
+        result |= (-1 << shift);
+      }
+      break;
+    }
+  }
+  return result;
+};
+
+Stream.prototype.float64 = function() {
+  const buffer = new ArrayBuffer(8);
+  const bytes = new Uint8Array(buffer);
+  for (let i = 0; i < 8; i++) {
+    bytes[i] = this.byte();
+  }
+  return new Float64Array(buffer)[0];
+};
+
+Stream.prototype.utf8 = function() {
+  const length = this.uleb128();
+  let result = '';
+  for (let i = 0; i < length; i++) {
+    // This is incorrect outside of ASCII, but good enough for our purpose
+    // since we're mostly interested in identifiers.
+    result += String.fromCharCode(this.byte());
+  }
+  // Can we force flattening of the rope string?
+  return result.toString();
+};
+
+Stream.prototype.latin1 = function() {
+  const length = this.uleb128();
+  let result = '';
+  for (let i = 0; i < length; i++) {
+    result += String.fromCharCode(this.byte());
+  }
+  // Can we force flattening of the rope string?
+  return result.toString();
+};
+
+Stream.prototype.utf16 = function() {
+  const length = this.uleb128();
+  let result = '';
+  for (let i = 0; i < length; i++) {
+    const lo = this.byte();
+    const hi = this.byte();
+    result += String.fromCharCode((hi << 8) | lo);
+  }
+  // Can we force flattening of the rope string?
+  return result.toString();
+};
+
 function hash(string) {
   // Jenkin's one_at_a_time.
   let h = string.length;
@@ -747,27 +1250,27 @@
   return (fraction * 100).toFixed(1);
 }
 
-function createTreemapTile(v, width, height, depth) {
+function createTreemapTile(graph, v, width, height, depth) {
   let div = document.createElement("div");
   div.className = "treemapTile";
   div.style["background-color"] = color(graph.classOf(v));
   div.ondblclick = function(event) {
     event.stopPropagation();
     if (depth == 0) {
-      let dom = graph.dom_[v];
+      let dom = graph.parentOf(v);
       if (dom == 0) {
         // Already at root.
       } else {
-        showDominatorTree(dom);  // Zoom out.
+        showDominatorTree(graph, dom);  // Zoom out.
       }
     } else {
-      showDominatorTree(v);  // Zoom in.
+      showDominatorTree(graph, v);  // Zoom in.
     }
   };
   div.oncontextmenu = function(event) {
     event.stopPropagation();
     event.preventDefault();
-    showTables([v]);
+    showTables(graph.setFrom(v));
   };
 
   let left = 0;
@@ -877,7 +1380,7 @@
         childWidth = size / childHeight;
       }
 
-      let childDiv = createTreemapTile(child, childWidth, childHeight, depth + 1);
+      let childDiv = createTreemapTile(graph, child, childWidth, childHeight, depth + 1);
       childDiv.style.left = rowLeft + "px";
       childDiv.style.top = rowTop + "px";
       // Oversize the final div by kBorder to make the borders overlap.
@@ -905,17 +1408,35 @@
   return div;
 }
 
-function showDominatorTree(v) {
-  let header = document.createElement("div");
-  header.textContent = "Dominator Tree";
-  header.title =
+function showDominatorTree(graph, v) {
+  let title = document.createElement("span");
+  title.textContent = "Dominator Tree";
+  title.title =
+    "Click title to merge/unmerge by class.\n" +
     "Double click a box to zoom in.\n" +
     "Double click the outermost box to zoom out.\n" +
     "Right click a box to view successor and predecessor tables.";
+  title.className = "nameCell actionCell";
+  title.onclick = function(event) { showDominatorTree(graph.toggleMerge(), v); };
+
+  let filler = document.createElement("span");
+  filler.style["flex-grow"] = 1;
+
+  let totalSize = document.createElement("span");
+  totalSize.className = "sizeCell";
+  totalSize.textContent = graph ? "" + graph.getTotalSize() : "0";
+
+  let totalPercent = document.createElement("span");
+  totalPercent.className = "sizePercentCell";
+  totalPercent.textContent = prettyPercent(1.0);
+
+  let header = document.createElement("div");
   header.className = "headerRow";
-  header.style["flex-grow"] = 0;
-  header.style["padding"] = "5px";
   header.style["border-bottom"] = "solid 1px";
+  header.appendChild(title);
+  header.appendChild(filler);
+  header.appendChild(totalSize);
+  header.appendChild(totalPercent);
 
   let content = document.createElement("div");
   content.style["flex-basis"] = 0;
@@ -937,7 +1458,7 @@
   let w = content.offsetWidth;
   let h = content.offsetHeight;
 
-  let topTile = createTreemapTile(v, w, h, 0);
+  let topTile = createTreemapTile(graph, v, w, h, 0);
   topTile.style.width = w;
   topTile.style.height = h;
   topTile.style.border = "none";
@@ -1048,8 +1569,6 @@
 
   let header = document.createElement("div");
   header.className = "headerRow";
-  header.style["display"] = "flex";
-  header.style["flex-direction"] = "row";
   header.style["border-bottom"] = "solid 1px";
   header.appendChild(this.nom);
   header.appendChild(edge);
@@ -1199,14 +1718,19 @@
   shallowPercent.className = "sizePercentCell";
   shallowPercent.textContent = prettyPercent(graph.shallowSizeOf(v) / graph.getTotalSize());
 
+  function onClickRetained(event) {
+    // For the root, default to the merged view for the sake of web browser layout performance.
+    showDominatorTree(v == 1 ? graph.toggleMerge() : graph, v);
+  }
+
   let retainedSize = document.createElement("span");
-  retainedSize.onclick = function(event) { showDominatorTree(v); };
+  retainedSize.onclick = onClickRetained;
   retainedSize.className = "sizeCell actionCell";
   retainedSize.textContent = graph.retainedSizeOf(v);
   retainedSize.title = "Show dominator tree";
 
   let retainedPercent = document.createElement("span");
-  retainedPercent.onclick = function(event) { showDominatorTree(v); };
+  retainedPercent.onclick = onClickRetained;
   retainedPercent.className = "sizePercentCell actionCell";
   retainedPercent.textContent = prettyPercent(graph.retainedSizeOf(v) / graph.getTotalSize());
   retainedPercent.title = "Show dominator tree";
@@ -1355,14 +1879,27 @@
   input.setAttribute("multiple", false);
   input.onchange = function(event) {
     let file = event.target.files[0];
+    document.title = file.name;
     let reader = new FileReader();
     reader.readAsText(file, 'UTF-8');
     reader.onload = function(event) {
       let data = JSON.parse(event.target.result);
-      document.title = file.name;
-      graph = new Graph();
-      graph.loadV8Profile(data, rewrite.checked);
+      let g = new Graph();
+      g.loadV8Profile(data);
       data = null; // Release memory
+      graph = g;
+      g.compute(rewrite.checked);
+      showTables([graph.getRoot()]);
+    };
+    reader = new FileReader();
+    reader.readAsArrayBuffer(file);
+    reader.onload = function(event) {
+      let data = event.target.result;
+      let g = new Graph();
+      g.loadDartHeapSnapshot(data);
+      data = null; // Release memory
+      graph = g;
+      g.compute(rewrite.checked);
       showTables([graph.getRoot()]);
     };
   };
@@ -1393,8 +1930,6 @@
   let topBar = document.createElement("div");
   topBar.className = "headerRow";
   topBar.style["border"] = "solid 2px";
-  topBar.style["display"] = "flex";
-  topBar.style["flex-direction"] = "row";
   topBar.style["align-items"] = "center";
   topBar.appendChild(rewrite);
   topBar.appendChild(rewriteLabel);
diff --git a/sdk/lib/_internal/js_dev_runtime/private/js_string.dart b/sdk/lib/_internal/js_dev_runtime/private/js_string.dart
index 2987812..985c02d 100644
--- a/sdk/lib/_internal/js_dev_runtime/private/js_string.dart
+++ b/sdk/lib/_internal/js_dev_runtime/private/js_string.dart
@@ -164,13 +164,9 @@
   }
 
   @notNull
-  String substring(@nullCheck int startIndex, [int? _endIndex]) {
-    var length = this.length;
-    final endIndex = _endIndex ?? length;
-    if (startIndex < 0) throw RangeError.value(startIndex);
-    if (startIndex > endIndex) throw RangeError.value(startIndex);
-    if (endIndex > length) throw RangeError.value(endIndex);
-    return JS<String>('!', r'#.substring(#, #)', this, startIndex, endIndex);
+  String substring(@nullCheck int start, [int? end]) {
+    end = RangeError.checkValidRange(start, end, this.length);
+    return JS<String>('!', r'#.substring(#, #)', this, start, end);
   }
 
   @notNull
diff --git a/sdk/lib/_internal/js_runtime/lib/js_string.dart b/sdk/lib/_internal/js_runtime/lib/js_string.dart
index 8ba4c37..6d25e5d 100644
--- a/sdk/lib/_internal/js_runtime/lib/js_string.dart
+++ b/sdk/lib/_internal/js_runtime/lib/js_string.dart
@@ -149,14 +149,11 @@
     return pattern.matchAsPrefix(this, index) != null;
   }
 
-  String substring(int startIndex, [int? endIndex]) {
-    checkInt(startIndex);
-    if (endIndex == null) endIndex = length;
-    checkInt(endIndex);
-    if (startIndex < 0) throw new RangeError.value(startIndex);
-    if (startIndex > endIndex) throw new RangeError.value(startIndex);
-    if (endIndex > length) throw new RangeError.value(endIndex);
-    return JS('String', r'#.substring(#, #)', this, startIndex, endIndex);
+  @pragma('dart2js:noInline')
+  String substring(int start, [int? end]) {
+    checkInt(start);
+    end = RangeError.checkValidRange(start, end, this.length);
+    return JS('String', r'#.substring(#, #)', this, start, end);
   }
 
   String toLowerCase() {
diff --git a/sdk/lib/_internal/vm/lib/string_patch.dart b/sdk/lib/_internal/vm/lib/string_patch.dart
index b02d273..91ac495 100644
--- a/sdk/lib/_internal/vm/lib/string_patch.dart
+++ b/sdk/lib/_internal/vm/lib/string_patch.dart
@@ -390,17 +390,7 @@
   }
 
   String substring(int startIndex, [int? endIndex]) {
-    endIndex ??= this.length;
-
-    if ((startIndex < 0) || (startIndex > this.length)) {
-      throw new RangeError.value(startIndex);
-    }
-    if ((endIndex < 0) || (endIndex > this.length)) {
-      throw new RangeError.value(endIndex);
-    }
-    if (startIndex > endIndex) {
-      throw new RangeError.value(startIndex);
-    }
+    endIndex = RangeError.checkValidRange(startIndex, endIndex, this.length);
     return _substringUnchecked(startIndex, endIndex);
   }
 
diff --git a/tools/VERSION b/tools/VERSION
index ef1b556..e5f179c 100644
--- a/tools/VERSION
+++ b/tools/VERSION
@@ -27,5 +27,5 @@
 MAJOR 2
 MINOR 14
 PATCH 0
-PRERELEASE 286
+PRERELEASE 287
 PRERELEASE_PATCH 0
\ No newline at end of file