generateForAnnotatedElement method

  1. @override
MapEntry<String, InitializerAggregateResults> generateForAnnotatedElement(
  1. Element element,
  2. ConstantReader annotation,
  3. BuildStep buildStep
)

Implementation

@override
MapEntry<String, InitializerAggregateResults> generateForAnnotatedElement(
  Element element,
  ConstantReader annotation,
  BuildStep buildStep,
) {
  final group = annotation.read('group');
  final groupString = group.isNull ? 'default' : group.stringValue;
  final result = InitializerAggregateResults(
    groupName: groupString,
    path: element.source!.fullName,
  );
  if (element is TopLevelVariableElementImpl) {
    result.addTopLevelVariable(element);
  } else if (element is PropertyAccessorElementImpl && element.isGetter) {
    final variable = element.variable;
    if (variable is TopLevelVariableElementImpl) {
      result.addTopLevelVariable(variable);
    }
  } else if (element is FunctionElementImpl) {
    result.addFunction(element);
  } else if (element is ClassElementImpl) {
    final klass = element;
    final annotatedFields =
        klass.fields.where((element) => typeChecker.hasAnnotationOf(element));
    for (final field in annotatedFields) {
      if (field.isStatic) {
        result.addField(field);
      } else {
        throw InvalidGenerationSourceError(
          '`@Initializer` can only be used on STATIC field.',
          element: element,
        );
      }
    }
    final annotatedMethods = klass.methods
        .where((element) => typeChecker.hasAnnotationOf(element));
    for (final method in annotatedMethods) {
      if (method.isStatic) {
        result.addMethod(method);
      } else {
        throw InvalidGenerationSourceError(
          '`@Initializer` can only be used on STATIC method.',
          element: element,
        );
      }
    }

    final annotatedAccessors = klass.accessors.where((element) =>
        typeChecker.hasAnnotationOf(element) && element.isGetter);

    for (final getter in annotatedAccessors) {
      final variable = getter.variable;
      if (getter.isStatic && variable is FieldElementImpl) {
        result.addField(variable);
      }
    }
  } else {
    const supported = [
      'top-level variable',
      'function without required args',
      'static member of class'
    ];
    throw InvalidGenerationSourceError(
      '`@Initializer` can only be used on $supported.',
      element: element,
    );
  }

  return MapEntry<String, InitializerAggregateResults>(groupString, result);
}