Repository: dart-lang/mockito

Issue:
Support analyzer ^8.0.0
Version 8 of analyzer was released a month ago, so it would be good to eventually allow upgrading to this newer version.

https://pub.dev/packages/analyzer/versions



Fix patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 89df8188..51bfd2a6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,8 @@
 ## 5.5.1
 
-* Allow `source_gen: ">=3.0.0 <5.0.0"`.
+* Require `analyzer: ^8.1.0`.
+* Allow `source_gen: '>=3.0.0 <5.0.0'`.
+* Allow `build: '>=3.0.0 <5.0.0'`.
 
 ## 5.5.0
 
diff --git a/lib/src/builder.dart b/lib/src/builder.dart
index b79c03b3..039e0a61 100644
--- a/lib/src/builder.dart
+++ b/lib/src/builder.dart
@@ -16,7 +16,7 @@ import 'dart:collection';
 
 import 'package:analyzer/dart/ast/ast.dart' as ast;
 import 'package:analyzer/dart/constant/value.dart';
-import 'package:analyzer/dart/element/element2.dart';
+import 'package:analyzer/dart/element/element.dart';
 import 'package:analyzer/dart/element/nullability_suffix.dart';
 import 'package:analyzer/dart/element/type.dart' as analyzer;
 import 'package:analyzer/dart/element/type_provider.dart';
@@ -29,7 +29,8 @@ import 'package:analyzer/src/dart/element/element.dart'
 import 'package:analyzer/src/dart/element/inheritance_manager3.dart'
     show InheritanceManager3, Name;
 // ignore: implementation_imports
-import 'package:analyzer/src/dart/element/member.dart' show ExecutableMember;
+import 'package:analyzer/src/dart/element/member.dart'
+    show SubstitutedExecutableElementImpl;
 // ignore: implementation_imports
 import 'package:analyzer/src/dart/element/type_algebra.dart' show Substitution;
 import 'package:build/build.dart';
@@ -174,39 +175,39 @@ $rawOutput
     await buildStep.writeAsString(mockLibraryAsset, mockLibraryContent);
   }
 
-  Future<Map<Element2, String>> _resolveAssetUris(
+  Future<Map<Element, String>> _resolveAssetUris(
     Resolver resolver,
     List<_MockTarget> mockTargets,
     String entryAssetPath,
-    LibraryElement2 entryLib,
+    LibraryElement entryLib,
   ) async {
     // We pass in the `Future<dynamic>` type so that an asset URI is known for
     // `Future`, which is needed when overriding some methods which return
     // `FutureOr`.
     final typeVisitor = _TypeVisitor(entryLib.typeProvider.futureDynamicType);
     final seenTypes = <analyzer.DartType>{};
-    final librariesWithTypes = <LibraryElement2>{};
+    final librariesWithTypes = <LibraryElement>{};
 
     void addTypesFrom(analyzer.DartType type) {
       // Prevent infinite recursion.
       if (seenTypes.contains(type)) {
         if (type.alias != null) {
           // To check for duplicate typdefs that have different names
-          type.alias!.element2.accept2(typeVisitor);
+          type.alias!.element.accept(typeVisitor);
         }
         return;
       }
       seenTypes.add(type);
 
-      if (type.element3?.library2 case final library?) {
+      if (type.element?.library case final library?) {
         librariesWithTypes.add(library);
       }
-      if (type.alias?.element2.library2 case final library?) {
+      if (type.alias?.element.library case final library?) {
         librariesWithTypes.add(library);
       }
 
-      type.element3?.accept2(typeVisitor);
-      type.alias?.element2.accept2(typeVisitor);
+      type.element?.accept(typeVisitor);
+      type.alias?.element.accept(typeVisitor);
       switch (type) {
         case final analyzer.InterfaceType interface:
           interface.typeArguments.forEach(addTypesFrom);
@@ -224,7 +225,7 @@ $rawOutput
       }
     }
 
-    final typeUris = <Element2, String>{};
+    final typeUris = <Element, String>{};
 
     final elements = [
       // Types which may be referenced.
@@ -235,9 +236,9 @@ $rawOutput
     ];
 
     for (final element in elements) {
-      final elementLibrary = element.library2!;
+      final elementLibrary = element.library!;
       if (elementLibrary.isInSdk &&
-          !elementLibrary.name3!.startsWith('dart._')) {
+          !elementLibrary.name!.startsWith('dart._')) {
         // For public SDK libraries, just use the source URI.
         typeUris[element] = elementLibrary.uri.toString();
         continue;
@@ -269,18 +270,18 @@ $rawOutput
   ///
   /// If [element] is not exported by any libraries in this set, then
   /// [element]'s declaring library is returned.
-  static LibraryElement2 _findExportOf(
-    Iterable<LibraryElement2> inputLibraries,
-    Element2 element,
+  static LibraryElement _findExportOf(
+    Iterable<LibraryElement> inputLibraries,
+    Element element,
   ) {
-    final elementName = element.name3;
+    final elementName = element.name;
     if (elementName == null) {
-      return element.library2!;
+      return element.library!;
     }
 
     final libraries = Queue.of([
       for (final library in inputLibraries)
-        ...library.firstFragment.importedLibraries2,
+        ...library.firstFragment.importedLibraries,
     ]);
 
     for (final library in libraries) {
@@ -288,45 +289,45 @@ $rawOutput
         return library;
       }
     }
-    return element.library2!;
+    return element.library!;
   }
 }
 
-/// An [Element2] visitor which collects the elements of all of the
+/// An [Element] visitor which collects the elements of all of the
 /// [analyzer.InterfaceType]s which it encounters.
 class _TypeVisitor extends RecursiveElementVisitor2<void> {
-  final _elements = <Element2>{};
+  final _elements = <Element>{};
 
   final analyzer.DartType _futureType;
 
   _TypeVisitor(this._futureType);
 
   @override
-  void visitClassElement(ClassElement2 element) {
+  void visitClassElement(ClassElement element) {
     _elements.add(element);
     super.visitClassElement(element);
   }
 
   @override
-  void visitEnumElement(EnumElement2 element) {
+  void visitEnumElement(EnumElement element) {
     _elements.add(element);
     super.visitEnumElement(element);
   }
 
   @override
-  void visitFieldElement(FieldElement2 element) {
+  void visitFieldElement(FieldElement element) {
     _addType(element.type);
     super.visitFieldElement(element);
   }
 
   @override
-  void visitMethodElement(MethodElement2 element) {
+  void visitMethodElement(MethodElement element) {
     _addType(element.returnType);
     super.visitMethodElement(element);
   }
 
   @override
-  void visitMixinElement(MixinElement2 element) {
+  void visitMixinElement(MixinElement element) {
     _elements.add(element);
     super.visitMixinElement(element);
   }
@@ -341,13 +342,13 @@ class _TypeVisitor extends RecursiveElementVisitor2<void> {
   }
 
   @override
-  void visitTypeParameterElement(TypeParameterElement2 element) {
+  void visitTypeParameterElement(TypeParameterElement element) {
     _addType(element.bound);
     super.visitTypeParameterElement(element);
   }
 
   @override
-  void visitTypeAliasElement(TypeAliasElement2 element) {
+  void visitTypeAliasElement(TypeAliasElement element) {
     _addType(element.aliasedType);
     _elements.add(element);
     super.visitTypeAliasElement(element);
@@ -360,15 +361,15 @@ class _TypeVisitor extends RecursiveElementVisitor2<void> {
     type.alias?.typeArguments.forEach(_addType);
 
     if (type is analyzer.InterfaceType) {
-      final alreadyVisitedElement = _elements.contains(type.element3);
-      _elements.add(type.element3);
+      final alreadyVisitedElement = _elements.contains(type.element);
+      _elements.add(type.element);
       type.typeArguments.forEach(_addType);
       if (!alreadyVisitedElement) {
-        type.element3.typeParameters2.forEach(visitTypeParameterElement);
+        type.element.typeParameters.forEach(visitTypeParameterElement);
 
-        final toStringMethod = type.element3.lookUpMethod2(
+        final toStringMethod = type.element.lookUpMethod(
           name: 'toString',
-          library: type.element3.library2,
+          library: type.element.library,
         );
         if (toStringMethod != null &&
             toStringMethod.formalParameters.isNotEmpty) {
@@ -379,7 +380,7 @@ class _TypeVisitor extends RecursiveElementVisitor2<void> {
           for (final parameter in toStringMethod.formalParameters) {
             final parameterType = parameter.type;
             if (parameterType is analyzer.InterfaceType) {
-              parameterType.element3.accept2(this);
+              parameterType.element.accept(this);
             }
           }
         }
@@ -396,12 +397,12 @@ class _TypeVisitor extends RecursiveElementVisitor2<void> {
       // into types, while traversing, so we must explicitly traverse [type]
       // here, in order to visit contained elements.
       for (final typeParameter in type.typeParameters) {
-        typeParameter.accept2(this);
+        typeParameter.accept(this);
       }
       for (final parameter in type.formalParameters) {
-        parameter.accept2(this);
+        parameter.accept(this);
       }
-      final aliasElement = type.alias?.element2;
+      final aliasElement = type.alias?.element;
       if (aliasElement != null) {
         _elements.add(aliasElement);
       }
@@ -438,8 +439,8 @@ class _TypeVisitor extends RecursiveElementVisitor2<void> {
         _addTypesFromConstant(pair.key!);
         _addTypesFromConstant(pair.value!);
       }
-    } else if (object.toFunctionValue2() != null) {
-      _elements.add(object.toFunctionValue2()!);
+    } else if (object.toFunctionValue() != null) {
+      _elements.add(object.toFunctionValue()!);
     } else {
       // If [constant] is not null, a literal, or a type, then it must be an
       // object constructed with `const`. Revive it.
@@ -468,7 +469,7 @@ class _MockTarget {
 
   final Set<String> unsupportedMembers;
 
-  final Map<String, ExecutableElement2> fallbackGenerators;
+  final Map<String, ExecutableElement> fallbackGenerators;
 
   /// Instantiated mock was requested, i.e. `MockSpec<Foo<Bar>>`,
   /// instead of `MockSpec<Foo>`.
@@ -484,15 +485,15 @@ class _MockTarget {
     String? mockName,
   }) : mockName =
            mockName ??
-           'Mock${classType.alias?.element2.name3 ?? classType.element3.name3}';
+           'Mock${classType.alias?.element.name ?? classType.element.name}';
 
-  InterfaceElement2 get interfaceElement => classType.element3;
+  InterfaceElement get interfaceElement => classType.element;
 }
 
 /// This class gathers and verifies mock targets referenced in `GenerateMocks`
 /// annotations.
 class _MockTargetGatherer {
-  final LibraryElement2 _entryLib;
+  final LibraryElement _entryLib;
 
   final List<_MockTarget> _mockTargets;
 
@@ -510,23 +511,23 @@ class _MockTargetGatherer {
   /// annotations and creates a [_MockTargetGatherer] with all of the classes
   /// identified as mocking targets.
   factory _MockTargetGatherer(
-    LibraryElement2 entryLib,
+    LibraryElement entryLib,
     InheritanceManager3 inheritanceManager,
   ) {
     final mockTargets = <_MockTarget>{};
 
-    final possiblyAnnotatedElements = [
-      ...entryLib.firstFragment.libraryExports2,
-      ...entryLib.firstFragment.libraryImports2,
-      ...entryLib.children2.whereType<Annotatable>(),
+    final metadataList = [
+      ...entryLib.firstFragment.libraryExports.map((e) => e.metadata),
+      ...entryLib.firstFragment.libraryImports.map((e) => e.metadata),
+      ...entryLib.children.map((e) => e.metadata),
     ];
 
-    for (final element in possiblyAnnotatedElements) {
+    for (final metadata in metadataList) {
       // TODO(srawlins): Re-think the idea of multiple @GenerateMocks
       // annotations, on one element or even on different elements in a library.
-      for (final annotation in element.metadata2.annotations) {
-        if (annotation.element2 is! ConstructorElement2) continue;
-        final annotationClass = annotation.element2!.enclosingElement2!.name3;
+      for (final annotation in metadata.annotations) {
+        if (annotation.element is! ConstructorElement) continue;
+        final annotationClass = annotation.element!.enclosingElement!.name;
         switch (annotationClass) {
           case 'GenerateMocks':
             mockTargets.addAll(
@@ -571,7 +572,7 @@ class _MockTargetGatherer {
 
   static Iterable<_MockTarget> _mockTargetsFromGenerateMocks(
     ElementAnnotation annotation,
-    LibraryElement2 entryLib,
+    LibraryElement entryLib,
   ) {
     final generateMocksValue = annotation.computeConstantValue();
     final classesField = generateMocksValue?.getField('classes');
@@ -602,7 +603,7 @@ class _MockTargetGatherer {
         // arguments. The type argument(s) on `type` have been instantiated to
         // bounds here. Switch to the declaration, which will be an
         // uninstantiated type.
-        type = (type.element3.baseElement as InterfaceElement2).thisType;
+        type = (type.element.baseElement as InterfaceElement).thisType;
       }
       mockTargets.add(
         _MockTarget(
@@ -635,7 +636,7 @@ class _MockTargetGatherer {
 
   static _MockTarget _mockTargetFromMockSpec(
     DartObject mockSpec,
-    LibraryElement2 entryLib,
+    LibraryElement entryLib,
     int index,
     List<ast.CollectionElement> mockSpecAsts, {
     bool nice = false,
@@ -663,7 +664,7 @@ class _MockTargetGatherer {
     var type = _determineDartType(typeToMock, entryLib.typeProvider);
     final mockTypeArguments = mockType?.typeArguments;
     if (mockTypeArguments != null) {
-      final typeName = type.alias?.element2.displayString2() ?? 'type $type';
+      final typeName = type.alias?.element.displayString() ?? 'type $type';
       final typeArguments = type.alias?.typeArguments ?? type.typeArguments;
       // Check explicit type arguments for unknown types that were
       // turned into `dynamic` by the analyzer.
@@ -695,7 +696,7 @@ class _MockTargetGatherer {
       // the type argument(s) on `type` have been instantiated to bounds if this
       // isn't a type alias. Switch to the declaration, which will be an
       // uninstantiated type.
-      type = (type.element3.baseElement as InterfaceElement2).thisType;
+      type = (type.element.baseElement as InterfaceElement).thisType;
     }
     final mockName = mockSpec.getField('mockName')!.toSymbolValue();
     final mixins = <analyzer.InterfaceType>[];
@@ -748,7 +749,7 @@ class _MockTargetGatherer {
 
   static Iterable<_MockTarget> _mockTargetsFromGenerateNiceMocks(
     ElementAnnotation annotation,
-    LibraryElement2 entryLib,
+    LibraryElement entryLib,
   ) {
     final generateNiceMocksValue = annotation.computeConstantValue()!;
     final mockSpecsField = generateNiceMocksValue.getField('mocks')!;
@@ -769,10 +770,10 @@ class _MockTargetGatherer {
     );
   }
 
-  static Map<String, ExecutableElement2> _extractFallbackGenerators(
+  static Map<String, ExecutableElement> _extractFallbackGenerators(
     Map<DartObject?, DartObject?> objects,
   ) {
-    final fallbackGenerators = <String, ExecutableElement2>{};
+    final fallbackGenerators = <String, ExecutableElement>{};
     objects.forEach((methodName, generator) {
       if (methodName == null) {
         throw InvalidMockitoAnnotationException(
@@ -786,7 +787,7 @@ class _MockTargetGatherer {
         );
       }
       fallbackGenerators[methodName.toSymbolValue()!] =
-          generator.toFunctionValue2()!;
+          generator.toFunctionValue()!;
     });
     return fallbackGenerators;
   }
@@ -802,21 +803,21 @@ class _MockTargetGatherer {
     TypeProvider typeProvider,
   ) {
     if (typeToMock is analyzer.InterfaceType) {
-      final elementToMock = typeToMock.element3;
+      final elementToMock = typeToMock.element;
       final displayName = "'${elementToMock.displayName}'";
-      if (elementToMock is EnumElement2) {
+      if (elementToMock is EnumElement) {
         throw InvalidMockitoAnnotationException(
           'Mockito cannot mock an enum: $displayName',
         );
       }
-      if (typeProvider.isNonSubtypableClass2(elementToMock)) {
+      if (typeProvider.isNonSubtypableClass(elementToMock)) {
         throw InvalidMockitoAnnotationException(
           'Mockito cannot mock a non-subtypable type: '
           '$displayName. It is illegal to subtype this '
           'type.',
         );
       }
-      if (elementToMock is ClassElement2) {
+      if (elementToMock is ClassElement) {
         if (elementToMock.isSealed) {
           throw InvalidMockitoAnnotationException(
             'Mockito cannot mock a sealed class $displayName, '
@@ -840,7 +841,7 @@ class _MockTargetGatherer {
         );
       }
       final typeParameterErrors = _checkTypeParameters(
-        elementToMock.typeParameters2,
+        elementToMock.typeParameters,
         elementToMock,
       );
       if (typeParameterErrors.isNotEmpty) {
@@ -857,7 +858,7 @@ class _MockTargetGatherer {
           typeToMock.nullabilitySuffix == NullabilitySuffix.question) {
         throw InvalidMockitoAnnotationException(
           'Mockito cannot mock a type-aliased nullable type: '
-          '${typeToMock.alias!.element2.name3}',
+          '${typeToMock.alias!.element.name}',
         );
       }
       return typeToMock;
@@ -865,13 +866,12 @@ class _MockTargetGatherer {
 
     throw InvalidMockitoAnnotationException(
       'Mockito cannot mock a non-class: '
-      '${typeToMock.alias?.element2.name3 ?? typeToMock.toString()}',
+      '${typeToMock.alias?.element.name ?? typeToMock.toString()}',
     );
   }
 
   void _checkClassesToMockAreValid() {
-    final classesInEntryLib =
-        _entryLib.children2.whereType<InterfaceElement2>();
+    final classesInEntryLib = _entryLib.children.whereType<InterfaceElement>();
     final classNamesToMock = <String, _MockTarget>{};
     final uniqueNameSuggestion =
         "use the 'customMocks' argument in @GenerateMocks to specify a unique "
@@ -891,8 +891,8 @@ class _MockTargetGatherer {
                 .fullName;
         throw InvalidMockitoAnnotationException(
           'Mockito cannot generate two mocks with the same name: $name (for '
-          '${firstClass.name3} declared in $firstSource, and for '
-          '${mockTarget.interfaceElement.name3} declared in $secondSource); '
+          '${firstClass.name} declared in $firstSource, and for '
+          '${mockTarget.interfaceElement.name} declared in $secondSource); '
           '$uniqueNameSuggestion.',
         );
       }
@@ -901,12 +901,12 @@ class _MockTargetGatherer {
 
     classNamesToMock.forEach((name, mockTarget) {
       final conflictingClass = classesInEntryLib.firstWhereOrNull(
-        (c) => c.name3 == name,
+        (c) => c.name == name,
       );
       if (conflictingClass != null) {
         throw InvalidMockitoAnnotationException(
           'Mockito cannot generate a mock with a name which conflicts with '
-          'another class declared in this library: ${conflictingClass.name3}; '
+          'another class declared in this library: ${conflictingClass.name}; '
           '$uniqueNameSuggestion.',
         );
       }
@@ -914,14 +914,14 @@ class _MockTargetGatherer {
       final preexistingMock = classesInEntryLib.firstWhereOrNull(
         (c) =>
             c.interfaces
-                .map((type) => type.element3)
+                .map((type) => type.element)
                 .contains(mockTarget.interfaceElement) &&
             _isMockClass(c.supertype!),
       );
       if (preexistingMock != null) {
         throw InvalidMockitoAnnotationException(
           'The GenerateMocks annotation contains a class which appears to '
-          'already be mocked inline: ${preexistingMock.name3}; '
+          'already be mocked inline: ${preexistingMock.name}; '
           '$uniqueNameSuggestion.',
         );
       }
@@ -938,18 +938,21 @@ class _MockTargetGatherer {
   ///   such a method.
   void _checkMethodsToStubAreValid(_MockTarget mockTarget) {
     final interfaceElement = mockTarget.interfaceElement;
-    final className = interfaceElement.name3;
+    final className = interfaceElement.name;
     final substitution = Substitution.fromInterfaceType(mockTarget.classType);
     final relevantMembers = _inheritanceManager
-        .getInterface2(interfaceElement)
-        .map2
+        .getInterface(interfaceElement)
+        .map
         .values
         .where((m) => !m.isPrivate && !m.isStatic)
-        .map((member) => ExecutableMember.from(member, substitution));
+        .map(
+          (member) =>
+              SubstitutedExecutableElementImpl.from(member, substitution),
+        );
     final unstubbableErrorMessages =
         relevantMembers.expand((member) {
           final nameWithEquals =
-              member is SetterElement ? '${member.name3}=' : member.name3;
+              member is SetterElement ? '${member.name}=' : member.name;
           if (_entryLib.typeSystem._returnTypeIsNonNullable(member) ||
               _entryLib.typeSystem._hasNonNullableParameter(member) ||
               _needsOverrideForVoidStub(member)) {
@@ -1005,7 +1008,7 @@ class _MockTargetGatherer {
   /// been provided).
   List<String> _checkFunction(
     analyzer.FunctionType function,
-    Element2 enclosingElement, {
+    Element enclosingElement, {
     bool isParameter = false,
     bool allowUnsupportedMember = false,
     bool hasDummyGenerator = false,
@@ -1043,7 +1046,7 @@ class _MockTargetGatherer {
     for (final parameter in function.formalParameters) {
       final parameterType = parameter.type;
       if (parameterType is analyzer.InterfaceType) {
-        final parameterTypeElement = parameterType.element3;
+        final parameterTypeElement = parameterType.element;
         if (parameterTypeElement.isPrivate) {
           // Technically, we can expand the type in the mock to something like
           // `Object?`. However, until there is a decent use case, we will not
@@ -1051,7 +1054,7 @@ class _MockTargetGatherer {
           if (!allowUnsupportedMember) {
             errorMessages.add(
               '${enclosingElement.fullName} features a private parameter '
-              "type, '${parameterTypeElement.name3}', and cannot be stubbed. "
+              "type, '${parameterTypeElement.name}', and cannot be stubbed. "
               '$_tryUnsupportedMembersMessage',
             );
           }
@@ -1092,8 +1095,8 @@ class _MockTargetGatherer {
   /// Checks the bounds of [typeParameters] for properties that would make the
   /// enclosing method un-stubbable.
   static List<String> _checkTypeParameters(
-    List<TypeParameterElement2> typeParameters,
-    Element2 enclosingElement,
+    List<TypeParameterElement> typeParameters,
+    Element enclosingElement,
   ) {
     final errorMessages = <String>[];
     for (final element in typeParameters) {
@@ -1102,7 +1105,7 @@ class _MockTargetGatherer {
       if (typeParameter is analyzer.InterfaceType) {
         // TODO(srawlins): Check for private names in bound; could be
         // `List<_Bar>`.
-        if (typeParameter.element3.isPrivate) {
+        if (typeParameter.element.isPrivate) {
           errorMessages.add(
             '${enclosingElement.fullName} features a private type parameter '
             'bound, and cannot be stubbed.',
@@ -1120,14 +1123,14 @@ class _MockTargetGatherer {
   /// un-stubbable.
   List<String> _checkTypeArguments(
     List<analyzer.DartType> typeArguments,
-    Element2 enclosingElement, {
+    Element enclosingElement, {
     bool isParameter = false,
     bool allowUnsupportedMember = false,
   }) {
     final errorMessages = <String>[];
     for (final typeArgument in typeArguments) {
       if (typeArgument is analyzer.InterfaceType) {
-        if (typeArgument.element3.isPrivate && !allowUnsupportedMember) {
+        if (typeArgument.element.isPrivate && !allowUnsupportedMember) {
           errorMessages.add(
             '${enclosingElement.fullName} features a private type argument, '
             'and cannot be stubbed. $_tryUnsupportedMembersMessage',
@@ -1149,8 +1152,8 @@ class _MockTargetGatherer {
 
   /// Return whether [type] is the Mock class declared by mockito.
   bool _isMockClass(analyzer.InterfaceType type) =>
-      type.element3.name3 == 'Mock' &&
-      type.element3.firstFragment.libraryFragment.source.fullName.endsWith(
+      type.element.name == 'Mock' &&
+      type.element.firstFragment.libraryFragment.source.fullName.endsWith(
         'lib/src/mock.dart',
       );
 }
@@ -1165,18 +1168,18 @@ class _MockLibraryInfo {
   /// values.
   final fakeClasses = <Class>[];
 
-  /// [InterfaceElement2]s which are used in non-nullable return types, for which
+  /// [InterfaceElement]s which are used in non-nullable return types, for which
   /// fake classes are added to the generated library.
-  final fakedInterfaceElements2 = <InterfaceElement2>[];
+  final fakedInterfaceElements2 = <InterfaceElement>[];
 
-  /// A mapping of each necessary [Element2] to a URI from which it can be
+  /// A mapping of each necessary [Element] to a URI from which it can be
   /// imported.
   ///
   /// This mapping is generated eagerly so as to avoid any asynchronous
   /// Asset-resolving while building the mock library.
-  final Map<Element2, String> assetUris;
+  final Map<Element, String> assetUris;
 
-  final LibraryElement2? dartCoreLibrary;
+  final LibraryElement? dartCoreLibrary;
 
   /// Names of overridden members which conflict with elements exported from
   /// 'dart:core'.
@@ -1188,9 +1191,9 @@ class _MockLibraryInfo {
   _MockLibraryInfo(
     Iterable<_MockTarget> mockTargets, {
     required this.assetUris,
-    required LibraryElement2 entryLib,
+    required LibraryElement entryLib,
     required InheritanceManager3 inheritanceManager,
-  }) : dartCoreLibrary = entryLib.firstFragment.importedLibraries2
+  }) : dartCoreLibrary = entryLib.firstFragment.importedLibraries
            .firstWhereOrNull((library) => library.isDartCore) {
     for (final mockTarget in mockTargets) {
       final fallbackGenerators = mockTarget.fallbackGenerators;
@@ -1210,12 +1213,12 @@ class _MockLibraryInfo {
 
   var _fakeNameCounter = 0;
 
-  final _fakeNames2 = <Element2, String>{};
+  final _fakeNames2 = <Element, String>{};
 
   /// Generates a unique name for a fake class representing [element].
-  String _fakeNameFor(Element2 element) => _fakeNames2.putIfAbsent(
+  String _fakeNameFor(Element element) => _fakeNames2.putIfAbsent(
     element,
-    () => '_Fake${element.name3}_${_fakeNameCounter++}',
+    () => '_Fake${element.name}_${_fakeNameCounter++}',
   );
 }
 
@@ -1236,7 +1239,7 @@ class _MockClassInfo {
   ///
   /// Each value is another mapping from method names to the generator
   /// function elements.
-  final Map<String, ExecutableElement2> fallbackGenerators;
+  final Map<String, ExecutableElement> fallbackGenerators;
 
   final InheritanceManager3 inheritanceManager;
 
@@ -1252,14 +1255,14 @@ class _MockClassInfo {
 
   Class _buildMockClass() {
     final instantiatedAlias = mockTarget.classType.alias;
-    final aliasElement = instantiatedAlias?.element2;
+    final aliasElement = instantiatedAlias?.element;
     final aliasedType = aliasElement?.aliasedType as analyzer.InterfaceType?;
     final typeToMock = aliasedType ?? mockTarget.classType;
     final classToMock = mockTarget.interfaceElement;
-    final classIsImmutable = classToMock.metadata2.annotations.any(
+    final classIsImmutable = classToMock.metadata.annotations.any(
       (it) => it.isImmutable,
     );
-    final className = aliasElement?.name3 ?? classToMock.name3;
+    final className = aliasElement?.name ?? classToMock.name;
 
     return Class((cBuilder) {
       cBuilder
@@ -1281,7 +1284,7 @@ class _MockClassInfo {
       // the "implements" clause.
 
       final typeParameters =
-          aliasElement?.typeParameters2 ?? classToMock.typeParameters2;
+          aliasElement?.typeParameters ?? classToMock.typeParameters;
       final typeArguments =
           instantiatedAlias?.typeArguments ?? typeToMock.typeArguments;
 
@@ -1293,8 +1296,8 @@ class _MockClassInfo {
             cBuilder.mixins.add(
               TypeReference((b) {
                 b
-                  ..symbol = mixin.element3.name3
-                  ..url = _typeImport(mixin.element3)
+                  ..symbol = mixin.element.name
+                  ..url = _typeImport(mixin.element)
                   ..types.addAll(mixin.typeArguments.map(_typeReference));
               }),
             );
@@ -1316,14 +1319,17 @@ class _MockClassInfo {
           }
 
           final substitution = Substitution.fromPairs2(
-            [...classToMock.typeParameters2, ...?aliasElement?.typeParameters2],
+            [...classToMock.typeParameters, ...?aliasElement?.typeParameters],
             [...typeToMock.typeArguments, ...?instantiatedAlias?.typeArguments],
           );
           final members = inheritanceManager
-              .getInterface2(classToMock)
-              .map2
+              .getInterface(classToMock)
+              .map
               .values
-              .map((member) => ExecutableMember.from(member, substitution));
+              .map(
+                (member) =>
+                    SubstitutedExecutableElementImpl.from(member, substitution),
+              );
 
           // The test can be pre-null-safety but if the class
           // we want to mock is defined in a null safe library,
@@ -1333,10 +1339,10 @@ class _MockClassInfo {
 
           if (sourceLibIsNonNullable || isNiceMockOfNullSafeClass) {
             cBuilder.methods.addAll(
-              fieldOverrides(members.whereType<PropertyAccessorElement2>()),
+              fieldOverrides(members.whereType<PropertyAccessorElement>()),
             );
             cBuilder.methods.addAll(
-              methodOverrides(members.whereType<MethodElement2>()),
+              methodOverrides(members.whereType<MethodElement>()),
             );
           } else {
             // For a pre-null safe library, we do not need to re-implement any
@@ -1344,8 +1350,8 @@ class _MockClassInfo {
             // we may need to include an implementation of `toString()`, if the
             // class-to-mock has added optional parameters.
             final toStringMethod = members
-                .whereType<MethodElement2>()
-                .firstWhereOrNull((m) => m.name3 == 'toString');
+                .whereType<MethodElement>()
+                .firstWhereOrNull((m) => m.name == 'toString');
             if (toStringMethod != null) {
               cBuilder.methods.addAll(methodOverrides([toStringMethod]));
             }
@@ -1363,17 +1369,17 @@ class _MockClassInfo {
   /// return type (for getters) or a parameter with a potentially non-nullable
   /// type (for setters) are yielded.
   Iterable<Method> fieldOverrides(
-    Iterable<PropertyAccessorElement2> accessors,
+    Iterable<PropertyAccessorElement> accessors,
   ) sync* {
     for (final accessor in accessors) {
       if (accessor.isPrivate) {
         continue;
       }
-      if (accessor.name3 == 'hashCode') {
+      if (accessor.name == 'hashCode') {
         // Never override this getter; user code cannot narrow the return type.
         continue;
       }
-      if (accessor.name3 == 'runtimeType') {
+      if (accessor.name == 'runtimeType') {
         // Never override this getter; user code cannot narrow the return type.
         continue;
       }
@@ -1387,7 +1393,7 @@ class _MockClassInfo {
     }
   }
 
-  bool _methodNeedsOverride(MethodElement2 method) {
+  bool _methodNeedsOverride(MethodElement method) {
     if (!sourceLibIsNonNullable) {
       // If we get here, we are adding overrides only to make
       // nice mocks work. We only care about return types then.
@@ -1405,12 +1411,12 @@ class _MockClassInfo {
   /// Only public instance methods which have either a potentially non-nullable
   /// return type or a parameter with a potentially non-nullable type are
   /// yielded.
-  Iterable<Method> methodOverrides(Iterable<MethodElement2> methods) sync* {
+  Iterable<Method> methodOverrides(Iterable<MethodElement> methods) sync* {
     for (final method in methods) {
       if (method.isPrivate) {
         continue;
       }
-      final methodName = method.name3;
+      final methodName = method.name;
       if (methodName == 'noSuchMethod') {
         continue;
       }
@@ -1425,7 +1431,7 @@ class _MockClassInfo {
         continue;
       }
       if (_methodNeedsOverride(method)) {
-        _checkForConflictWithCore(method.name3!);
+        _checkForConflictWithCore(method.name!);
         yield Method((mBuilder) => _buildOverridingMethod(mBuilder, method));
       }
     }
@@ -1454,12 +1460,12 @@ class _MockClassInfo {
   ///
   /// This new method just calls `super.noSuchMethod`, optionally passing a
   /// return value for methods with a non-nullable return type.
-  void _buildOverridingMethod(MethodBuilder builder, MethodElement2 method) {
+  void _buildOverridingMethod(MethodBuilder builder, MethodElement method) {
     var name = method.displayName;
     if (method.isOperator) name = 'operator$name';
     final returnType = method.returnType;
     _withTypeParameters(
-      method.typeParameters2,
+      method.typeParameters,
       typeFormalsHack: method.type.typeParameters,
       (typeParamsWithBounds, _) {
         builder
@@ -1517,7 +1523,7 @@ class _MockClassInfo {
             );
           } else {
             throw StateError(
-              'Parameter ${parameter.name3} on method ${method.name3} '
+              'Parameter ${parameter.name} on method ${method.name} '
               'is not required-positional, nor optional-positional, nor named',
             );
           }
@@ -1530,7 +1536,7 @@ class _MockClassInfo {
           return;
         }
 
-        final fallbackGenerator = fallbackGenerators[method.name3];
+        final fallbackGenerator = fallbackGenerators[method.name];
         final parametersContainPrivateName = method.formalParameters.any(
           (p) => p.type.containsPrivateName,
         );
@@ -1614,24 +1620,24 @@ class _MockClassInfo {
   }
 
   Expression _fallbackGeneratorCode(
-    ExecutableElement2 method,
-    ExecutableElement2 function,
+    ExecutableElement method,
+    ExecutableElement function,
   ) {
     final positionalArguments = <Expression>[];
     final namedArguments = <String, Expression>{};
     for (final parameter in method.formalParameters) {
       if (parameter.isPositional) {
-        positionalArguments.add(refer(parameter.name3!));
+        positionalArguments.add(refer(parameter.name!));
       } else if (parameter.isNamed) {
-        namedArguments[parameter.name3!] = refer(parameter.name3!);
+        namedArguments[parameter.name!] = refer(parameter.name!);
       }
     }
     final functionReference = referImported(
-      function.name3!,
+      function.name!,
       _typeImport(function),
     );
     return functionReference.call(positionalArguments, namedArguments, [
-      for (final t in method.typeParameters2)
+      for (final t in method.typeParameters)
         _typeParameterReference(t, withBound: false),
     ]);
   }
@@ -1740,7 +1746,7 @@ class _MockClassInfo {
       assert(typeArguments.length == 1);
       final elementType = _typeReference(typeArguments[0]);
       return literalSet({}, elementType);
-    } else if (type.element3.baseElement == typeProvider.streamElement2) {
+    } else if (type.element.baseElement == typeProvider.streamElement) {
       assert(typeArguments.length == 1);
       final elementType = _typeReference(typeArguments[0]);
       return TypeReference((b) {
@@ -1755,7 +1761,7 @@ class _MockClassInfo {
       // have predicatble constructors; each has an unnamed constructor which
       // takes a single int argument.
       return referImported(
-        type.element3.name3!,
+        type.element.name!,
         'dart:typed_data',
       ).call([literalNum(0)]);
       // TODO(srawlins): Do other types from typed_data have a "non-subtypeable"
@@ -1842,7 +1848,7 @@ class _MockClassInfo {
     analyzer.InterfaceType dartType,
     Expression invocation,
   ) {
-    final elementToFake = dartType.element3;
+    final elementToFake = dartType.element;
     final fakeName = mockLibraryInfo._fakeNameFor(elementToFake);
     // Only make one fake class for each class that needs to be faked.
     if (!mockLibraryInfo.fakedInterfaceElements2.contains(elementToFake)) {
@@ -1859,27 +1865,27 @@ class _MockClassInfo {
   Expression _dummyValueImplementing(
     analyzer.InterfaceType dartType,
     Expression invocation,
-  ) => switch (dartType.element3) {
-    EnumElement2(:final fields2) => _typeReference(
+  ) => switch (dartType.element) {
+    EnumElement(:final fields) => _typeReference(
       dartType,
-    ).property(fields2.firstWhere((f) => f.isEnumConstant).name3!),
-    ClassElement2() && final element
+    ).property(fields.firstWhere((f) => f.isEnumConstant).name!),
+    ClassElement() && final element
         when element.isBase || element.isFinal || element.isSealed =>
       // This class can't be faked, so try to call `dummyValue` to get
       // a dummy value at run time.
       // TODO(yanok): Consider checking subtypes, maybe some of them are
       // implementable.
       _dummyValueFallbackToRuntime(dartType, invocation),
-    ClassElement2() => _dummyFakedValue(dartType, invocation),
-    MixinElement2() =>
+    ClassElement() => _dummyFakedValue(dartType, invocation),
+    MixinElement() =>
     // This is a mixin and not a class. This should not happen in Dart 3,
     // since it is not possible to have a value of mixin type. But we
     // have to support this for reverse comptatibility.
     _dummyFakedValue(dartType, invocation),
-    ExtensionTypeElement2(:final typeErasure)
+    ExtensionTypeElement(:final typeErasure)
         when !typeErasure.containsPrivateName =>
       _dummyValue(typeErasure, invocation),
-    ExtensionTypeElement2() => _dummyValueFallbackToRuntime(
+    ExtensionTypeElement() => _dummyValueFallbackToRuntime(
       dartType,
       invocation,
     ),
@@ -1892,7 +1898,7 @@ class _MockClassInfo {
   };
 
   /// Adds a `Fake` implementation of [elementToFake], named [fakeName].
-  void _addFakeClass(String fakeName, InterfaceElement2 elementToFake) {
+  void _addFakeClass(String fakeName, InterfaceElement elementToFake) {
     mockLibraryInfo.fakeClasses.add(
       Class((cBuilder) {
         // For each type parameter on [elementToFake], the Fake class needs a type
@@ -1901,7 +1907,7 @@ class _MockClassInfo {
         cBuilder
           ..name = fakeName
           ..extend = referImported('SmartFake', 'package:mockito/mockito.dart');
-        _withTypeParameters(elementToFake.typeParameters2.map((e) => e), (
+        _withTypeParameters(elementToFake.typeParameters.map((e) => e), (
           typeParamsWithBounds,
           typeParams,
         ) {
@@ -1909,7 +1915,7 @@ class _MockClassInfo {
           cBuilder.implements.add(
             TypeReference((b) {
               b
-                ..symbol = elementToFake.name3
+                ..symbol = elementToFake.name
                 ..url = _typeImport(elementToFake)
                 ..types.addAll(typeParams);
             }),
@@ -1940,9 +1946,9 @@ class _MockClassInfo {
             ),
           );
 
-          final toStringMethod = elementToFake.lookUpMethod2(
+          final toStringMethod = elementToFake.lookUpMethod(
             name: 'toString',
-            library: elementToFake.library2,
+            library: elementToFake.library,
           );
           if (toStringMethod != null &&
               toStringMethod.formalParameters.isNotEmpty) {
@@ -1974,16 +1980,14 @@ class _MockClassInfo {
     bool forceNullable = false,
   }) {
     final parameterHasName =
-        parameter.name3 != null &&
-        parameter.name3 != '' &&
-        parameter.name3 != '_';
+        parameter.name != null && parameter.name != '' && parameter.name != '_';
     assert(
       parameterHasName || defaultName != null,
       'parameter must have a non-empty name, or non-null defaultName must be '
-      'passed, but parameter name is "${parameter.name3}" and defaultName is '
+      'passed, but parameter name is "${parameter.name}" and defaultName is '
       '$defaultName',
     );
-    final name = !parameterHasName ? defaultName! : parameter.name3!;
+    final name = !parameterHasName ? defaultName! : parameter.name!;
     return Parameter((pBuilder) {
       pBuilder.name = name;
       if (!superParameterType.containsPrivateName) {
@@ -2005,7 +2009,7 @@ class _MockClassInfo {
                 parameter,
               ).code;
         } on _ReviveException catch (e) {
-          final method = parameter.enclosingElement2!;
+          final method = parameter.enclosingElement!;
           throw InvalidMockitoAnnotationException(
             'Mockito cannot generate a valid override for method '
             "'${mockTarget.interfaceElement.displayName}.${method.displayName}'; "
@@ -2040,9 +2044,9 @@ class _MockClassInfo {
     if (!parameter.isCovariant) {
       return type;
     }
-    final method = parameter.enclosingElement2 as MethodElement2;
-    final class_ = method.enclosingElement2 as InterfaceElement2;
-    final name = Name(method.library2.uri, method.name3!);
+    final method = parameter.enclosingElement as MethodElement;
+    final class_ = method.enclosingElement as InterfaceElement;
+    final name = Name(method.library.uri, method.name!);
     final overriddenMethods = inheritanceManager.getOverridden(class_, name);
     if (overriddenMethods == null) {
       return type;
@@ -2051,7 +2055,7 @@ class _MockClassInfo {
     while (allOverriddenMethods.isNotEmpty) {
       final overriddenMethod = allOverriddenMethods.removeFirst();
       final secondaryOverrides = inheritanceManager.getOverridden(
-        overriddenMethod.enclosingElement2 as InterfaceElement2,
+        overriddenMethod.enclosingElement as InterfaceElement,
         name,
       );
       if (secondaryOverrides != null) {
@@ -2070,7 +2074,7 @@ class _MockClassInfo {
         type = typeSystem.leastUpperBound(type, overriddenParameter.type);
       } else {
         final overriddenParameter = parameters.firstWhereOrNull(
-          (p) => p.name3 == parameter.name3,
+          (p) => p.name == parameter.name,
         );
         if (overriddenParameter == null) {
           // [parameter] has been _added_ in [method], and has no corresponding
@@ -2145,17 +2149,17 @@ class _MockClassInfo {
           'default value has a private type: $privateReference.',
         );
       }
-      if (object.toFunctionValue2() != null) {
+      if (object.toFunctionValue() != null) {
         // A top-level function, like `void f() {}` must be referenced by its
         // identifier, rather than a revived value.
-        final element = object.toFunctionValue2();
+        final element = object.toFunctionValue();
         return referImported(revivable.accessor, _typeImport(element));
       } else if (revivable.source.fragment.isEmpty) {
         // We can create this invocation by referring to a const field or
         // top-level variable.
         return referImported(
           revivable.accessor,
-          _typeImport(object.type!.element3),
+          _typeImport(object.type!.element),
         );
       }
 
@@ -2169,9 +2173,9 @@ class _MockClassInfo {
           pair.key: _expressionFromDartObject(pair.value),
       };
       final element =
-          parameter != null && name != object.type!.element3!.name3
-              ? parameter.type.element3
-              : object.type!.element3;
+          parameter != null && name != object.type!.element!.name
+              ? parameter.type.element
+              : object.type!.element;
       final type = referImported(name, _typeImport(element));
       if (revivable.accessor.isNotEmpty) {
         return type.constInstanceNamed(
@@ -2201,15 +2205,15 @@ class _MockClassInfo {
     }
 
     final returnType = getter.returnType;
-    final fallbackGenerator = fallbackGenerators[getter.name3];
+    final fallbackGenerator = fallbackGenerators[getter.name];
     final throwsUnsupported =
         fallbackGenerator == null && (getter.returnType.containsPrivateName);
     if (throwsUnsupported) {
-      if (!mockTarget.unsupportedMembers.contains(getter.name3)) {
+      if (!mockTarget.unsupportedMembers.contains(getter.name)) {
         // We shouldn't get here as this is guarded against in
         // [_MockTargetGatherer._checkFunction].
         throw InvalidMockitoAnnotationException(
-          "Mockito cannot generate a valid override for '${getter.name3}', as "
+          "Mockito cannot generate a valid override for '${getter.name}', as "
           'it has a private type.',
         );
       }
@@ -2218,7 +2222,7 @@ class _MockClassInfo {
               .call([
                 // Generate a raw string since getter.name might contain a $.
                 literalString(
-                  '"${getter.name3}" cannot be used without a mockito fallback '
+                  '"${getter.name}" cannot be used without a mockito fallback '
                   'generator.',
                   raw: true,
                 ),
@@ -2260,7 +2264,7 @@ class _MockClassInfo {
   ///
   /// This new setter just calls `super.noSuchMethod`.
   void _buildOverridingSetter(MethodBuilder builder, SetterElement setter) {
-    final nameWithEquals = '${setter.name3}=';
+    final nameWithEquals = '${setter.name}=';
     final name = setter.displayName;
     builder
       ..name = name
@@ -2322,10 +2326,10 @@ class _MockClassInfo {
     builder.body = returnNoSuchMethod.code;
   }
 
-  final List<Map<TypeParameterElement2, String>> _typeVariableScopes = [];
+  final List<Map<TypeParameterElement, String>> _typeVariableScopes = [];
   final Set<String> _usedTypeVariables = {};
 
-  String _lookupTypeParameter(TypeParameterElement2 typeParameter) =>
+  String _lookupTypeParameter(TypeParameterElement typeParameter) =>
       _typeVariableScopes.reversed.firstWhereOrNull(
         (scope) => scope.containsKey(typeParameter),
       )?[typeParameter] ??
@@ -2333,10 +2337,10 @@ class _MockClassInfo {
         '$typeParameter not found, scopes: $_typeVariableScopes',
       ));
 
-  String _newTypeVar(TypeParameterElement2 typeParameter) {
+  String _newTypeVar(TypeParameterElement typeParameter) {
     var idx = 0;
     while (true) {
-      final name = '${typeParameter.name3}${idx == 0 ? '' : '$idx'}';
+      final name = '${typeParameter.name}${idx == 0 ? '' : '$idx'}';
       if (!_usedTypeVariables.contains(name)) {
         _usedTypeVariables.add(name);
         return name;
@@ -2349,19 +2353,19 @@ class _MockClassInfo {
   /// in the extended type parameter scope, passing type references for
   /// [typeParameters] (both with and without bound) as arguments.
   /// If [typeFormalsHack] is not `null`, it will be used to build the
-  /// type references instead of [typeParameters]. This is needed while
-  /// building method overrides, since sometimes
-  /// [ExecutableMember.typeParameters] can contain inconsistency if a type
-  /// parameter refers to itself in its bound. See
-  /// https://github.com/dart-lang/mockito/issues/658. So we have to
-  /// pass `ExecutableMember.type.typeFormals` instead, that seem to be
-  /// always correct. Unfortunately we can't just use the latter everywhere,
-  /// since `type.typeFormals` don't contain default arguments' values
-  /// and we need that for code generation.
+  /// type references instead of [typeParameters].
+  ///
+  /// This is needed while building method overrides, since sometimes
+  /// [typeParameters] can contain inconsistency if a type parameter refers to
+  /// itself in its bound. See https://github.com/dart-lang/mockito/issues/658.
+  /// So we have to pass `ExecutableMember.type.typeFormals` instead, that seem
+  /// to be always correct. Unfortunately we can't just use the latter
+  /// everywhere, since `type.typeFormals` don't contain default arguments'
+  /// values and we need that for code generation.
   T _withTypeParameters<T>(
-    Iterable<TypeParameterElement2> typeParameters,
+    Iterable<TypeParameterElement> typeParameters,
     T Function(Iterable<TypeReference>, Iterable<TypeReference>) body, {
-    Iterable<TypeParameterElement2>? typeFormalsHack,
+    Iterable<TypeParameterElement>? typeFormalsHack,
   }) {
     final typeVars = [for (final t in typeParameters) _newTypeVar(t)];
     final scope = Map.fromIterables(typeParameters, typeVars);
@@ -2391,7 +2395,7 @@ class _MockClassInfo {
   /// Create a reference for [typeParameter], properly referencing all types
   /// in bounds.
   TypeReference _typeParameterReference(
-    TypeParameterElement2 typeParameter, {
+    TypeParameterElement typeParameter, {
     bool withBound = true,
   }) {
     return TypeReference((b) {
@@ -2429,17 +2433,17 @@ class _MockClassInfo {
     if (type is analyzer.InterfaceType) {
       return TypeReference((b) {
         b
-          ..symbol = type.element3.name3
+          ..symbol = type.element.name
           ..isNullable =
               !type.isDartCoreNull &&
               (forceNullable ||
                   type.nullabilitySuffix == NullabilitySuffix.question)
-          ..url = _typeImport(type.element3)
+          ..url = _typeImport(type.element)
           ..types.addAll(type.typeArguments.map(_typeReference));
       });
     } else if (type is analyzer.FunctionType) {
       final alias = type.alias;
-      if (alias == null || alias.element2.isPrivate) {
+      if (alias == null || alias.element.isPrivate) {
         // [type] does not refer to a type alias, or it refers to a private type
         // alias; we must instead write out its signature.
         return FunctionType(
@@ -2458,14 +2462,14 @@ class _MockClassInfo {
             for (final parameter in type.formalParameters.where(
               (p) => p.isOptionalNamed,
             )) {
-              b.namedParameters[parameter.name3!] = _typeReference(
+              b.namedParameters[parameter.name!] = _typeReference(
                 parameter.type,
               );
             }
             for (final parameter in type.formalParameters.where(
               (p) => p.isRequiredNamed,
             )) {
-              b.namedRequiredParameters[parameter.name3!] = _typeReference(
+              b.namedRequiredParameters[parameter.name!] = _typeReference(
                 parameter.type,
               );
             }
@@ -2474,8 +2478,8 @@ class _MockClassInfo {
       }
       return TypeReference((b) {
         b
-          ..symbol = alias.element2.name3
-          ..url = _typeImport(alias.element2)
+          ..symbol = alias.element.name
+          ..url = _typeImport(alias.element)
           ..isNullable = forceNullable || typeSystem.isNullable(type);
         for (final typeArgument in alias.typeArguments) {
           b.types.add(_typeReference(typeArgument));
@@ -2484,7 +2488,7 @@ class _MockClassInfo {
     } else if (type is analyzer.TypeParameterType) {
       return TypeReference((b) {
         b
-          ..symbol = _lookupTypeParameter(type.element3)
+          ..symbol = _lookupTypeParameter(type.element)
           ..isNullable = forceNullable || typeSystem.isNullable(type);
       });
     } else if (type is analyzer.RecordType) {
@@ -2501,19 +2505,19 @@ class _MockClassInfo {
               ..isNullable = forceNullable || typeSystem.isNullable(type),
       );
     } else {
-      return referImported(type.getDisplayString(), _typeImport(type.element3));
+      return referImported(type.getDisplayString(), _typeImport(type.element));
     }
   }
 
   /// Returns the import URL for [element].
   ///
   /// For some types, like `dynamic` and type variables, this may return null.
-  String? _typeImport(Element2? element) {
+  String? _typeImport(Element? element) {
     // For type variables, no import needed.
-    if (element is TypeParameterElement2) return null;
+    if (element is TypeParameterElement) return null;
 
     // For types like `dynamic`, return null; no import needed.
-    if (element?.library2 == null) return null;
+    if (element?.library == null) return null;
 
     assert(
       mockLibraryInfo.assetUris.containsKey(element),
@@ -2635,21 +2639,21 @@ Builder buildMocks(BuilderOptions options) {
   return MockBuilder(buildExtensions: result);
 }
 
-extension on Element2 {
+extension on Element {
   /// Returns the "full name" of a class or method element.
   String get fullName {
-    if (this is ClassElement2) {
-      return "The class '$name3'";
-    } else if (this is EnumElement2) {
-      return "The enum '$name3'";
-    } else if (this is MethodElement2) {
-      final className = enclosingElement2!.name3;
-      return "The method '$className.$name3'";
-    } else if (this is MixinElement2) {
-      return "The mixin '$name3'";
-    } else if (this is PropertyAccessorElement2) {
-      final className = enclosingElement2!.name3;
-      return "The property accessor '$className.$name3'";
+    if (this is ClassElement) {
+      return "The class '$name'";
+    } else if (this is EnumElement) {
+      return "The enum '$name'";
+    } else if (this is MethodElement) {
+      final className = enclosingElement!.name;
+      return "The method '$className.$name'";
+    } else if (this is MixinElement) {
+      return "The mixin '$name'";
+    } else if (this is PropertyAccessorElement) {
+      final className = enclosingElement!.name;
+      return "The property accessor '$className.$name'";
     } else {
       return 'unknown element';
     }
@@ -2666,7 +2670,7 @@ extension on analyzer.DartType {
     } else if (self is analyzer.InvalidType) {
       return false;
     } else if (self is analyzer.InterfaceType) {
-      return self.element3.isPrivate ||
+      return self.element.isPrivate ||
           self.typeArguments.any((t) => t.containsPrivateName);
     } else if (self is analyzer.FunctionType) {
       return self.returnType.containsPrivateName ||
@@ -2694,10 +2698,10 @@ extension on analyzer.DartType {
   /// Returns whether this type is a sealed type from the dart:typed_data
   /// library.
   bool get isDartTypedDataSealed {
-    if (element3!.library2!.name3 != 'dart.typed_data') {
+    if (element!.library!.name != 'dart.typed_data') {
       return false;
     }
-    final name = element3!.name3;
+    final name = element!.name;
     return name == 'Float32List' ||
         name == 'Float64List' ||
         name == 'Int8List' ||
@@ -2713,7 +2717,7 @@ extension on analyzer.DartType {
 }
 
 extension on TypeSystem {
-  bool _returnTypeIsNonNullable(ExecutableElement2 method) =>
+  bool _returnTypeIsNonNullable(ExecutableElement method) =>
       isPotentiallyNonNullable(method.returnType);
 
   // Returns whether [method] has at least one parameter whose type is
@@ -2727,7 +2731,7 @@ extension on TypeSystem {
   //     }
   //     final c1 = C<int?>(); // m's parameter's type is nullable.
   //     final c2 = C<int>(); // m's parameter's type is non-nullable.
-  bool _hasNonNullableParameter(ExecutableElement2 method) =>
+  bool _hasNonNullableParameter(ExecutableElement method) =>
       method.formalParameters.any((p) => isPotentiallyNonNullable(p.type));
 }
 
@@ -2743,7 +2747,7 @@ extension on int {
   }
 }
 
-bool _needsOverrideForVoidStub(ExecutableElement2 method) =>
+bool _needsOverrideForVoidStub(ExecutableElement method) =>
     method.returnType is analyzer.VoidType || method.returnType.isFutureOfVoid;
 
 /// This casts `ElementAnnotation` to the internal `ElementAnnotationImpl`
@@ -2758,8 +2762,8 @@ extension NamedTypeExtension on ast.NamedType {
   String get qualifiedName {
     final importPrefix = this.importPrefix;
     if (importPrefix != null) {
-      return '${importPrefix.name.lexeme}.${name2.lexeme}';
+      return '${importPrefix.name.lexeme}.${name.lexeme}';
     }
-    return name2.lexeme;
+    return name.lexeme;
   }
 }
diff --git a/pubspec.yaml b/pubspec.yaml
index 84ee086d..1dc1711f 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -13,8 +13,8 @@ environment:
   sdk: ^3.7.0
 
 dependencies:
-  analyzer: '>=7.5.5 <8.0.0'
-  build: ^3.0.0
+  analyzer: ^8.1.1
+  build: '>=3.0.0 <5.0.0'
   code_builder: ^4.5.0
   collection: ^1.19.0
   dart_style: '>=2.3.7 <4.0.0'


Test patch:
diff --git a/test/builder/auto_mocks_test.dart b/test/builder/auto_mocks_test.dart
index 3260976e..cca678ae 100644
--- a/test/builder/auto_mocks_test.dart
+++ b/test/builder/auto_mocks_test.dart
@@ -835,7 +835,7 @@ void main() {
       '''),
       _containsAllOf(
         'int get m => (super.noSuchMethod(',
-        'set m(int? _m) => super.noSuchMethod(',
+        'set m(int? value) => super.noSuchMethod(',
       ),
     );
   });
@@ -2401,10 +2401,10 @@ void main() {
             ) as int);
       '''),
         dedent2('''
-        set m(int? _m) => super.noSuchMethod(
+        set m(int? value) => super.noSuchMethod(
               Invocation.setter(
                 #m,
-                _m,
+                value,
               ),
               returnValueForMissingStub: null,
             );
@@ -2429,10 +2429,10 @@ void main() {
             ) as int);
         '''),
         dedent2('''
-        set m(int? _m) => super.noSuchMethod(
+        set m(int? value) => super.noSuchMethod(
               Invocation.setter(
                 #m,
-                _m,
+                value,
               ),
               returnValueForMissingStub: null,
             );