generateConstructor method

Future<ConstructorDeclaration> generateConstructor(
  1. MethodMirror constructorMirror,
  2. Element? parentElement,
  3. Package package,
  4. String libraryUri,
  5. Uri sourceUri,
  6. String className,
  7. ClassDeclaration parentClass,
)

Generate constructor declaration with analyzer support

Implementation

Future<ConstructorDeclaration> generateConstructor(
  mirrors.MethodMirror constructorMirror,
  Element? parentElement,
  Package package,
  String libraryUri,
  Uri sourceUri,
  String className,
  ClassDeclaration parentClass,
) async {
  final constructorName = mirrors.MirrorSystem.getName(constructorMirror.constructorName);

  // Get analyzer constructor element
  ConstructorElement? constructorElement;
  if (parentElement is InterfaceElement) {
    if (constructorName.isEmpty) {
      constructorElement = parentElement.unnamedConstructor;
    } else {
      constructorElement = parentElement.getNamedConstructor(constructorName);
    }
  }

  final mirrorType = constructorMirror.returnType;
  Type runtimeType = mirrorType.hasReflectedType ? mirrorType.reflectedType : mirrorType.runtimeType;

  // Extract annotations and resolve type
  if(GenericTypeParser.shouldCheckGeneric(runtimeType)) {
    final annotations = await _extractAnnotations(mirrorType.metadata, package);
    final resolvedType = await _resolveTypeFromGenericAnnotation(annotations, constructorName);
    if (resolvedType != null) {
      runtimeType = resolvedType;
    }
  }

  final result = StandardConstructorDeclaration(
    name: constructorName.isEmpty ? '' : constructorName,
    type: runtimeType,
    element: constructorElement,
    dartType: constructorElement?.type,
    libraryDeclaration: _libraryCache[libraryUri]!,
    parentClass: StandardLinkDeclaration(
      name: parentClass.getName(),
      type: parentClass.getType(),
      pointerType: parentClass.getType(),
      qualifiedName: parentClass.getQualifiedName(),
      isPublic: parentClass.getIsPublic(),
      canonicalUri: Uri.parse(parentClass.getPackageUri()),
      referenceUri: Uri.parse(parentClass.getPackageUri()),
      isSynthetic: parentClass.getIsSynthetic(),
    ),
    annotations: await _extractAnnotations(constructorMirror.metadata, package),
    sourceLocation: sourceUri,
    isFactory: constructorMirror.isFactoryConstructor,
    isConst: constructorMirror.isConstConstructor,
    isPublic: !_isInternal(constructorName),
    isSynthetic: _isSynthetic(constructorName),
  );

  result.parameters = await _extractParameters(
    constructorMirror.parameters,
    constructorElement?.typeParameters,
    package,
    libraryUri,
    result
  );

  return result;
}