Skip to content

Get AST of annotation #527

Closed
Closed
@stargazing-dino

Description

@stargazing-dino

Hi ! I've been using the workaround described here to type my annotation but now I'm having trouble trying to get the ast of my annotation. For example say I have the user define the root of a firebase collection

part 'root.fire.dart';

// UndefinedType is not created until I generate output in my `root.fire.dart` file
const _UsersCollection = Collection<UndefinedType>(name: 'users');

@root
class Database with _$Database {
  // TODO: This should have the option to pass in an app
  @_UsersCollection
  Database._();

  static final instance = Database._();
}

I can get annotations over the named constructor _ but how do I then get the non-synthetic element declaration const _UsersCollection.

I tried this but because I always get back a synthetic element from declaration calling getElementDeclaration by design returns null

@override
FutureOr<String> generateForAnnotatedElement(
  Element element,
  ConstantReader annotation,
  BuildStep buildStep,
) async {
  if (element is! ClassElement) {
    // ...
  }

  final stringBuffer = StringBuffer();
  final constructor = element.constructors.singleWhere(
    (constructor) => constructor.displayName == '_',
    orElse: () {
      // ...
    },
  );

  for (final annotation in constructor.metadata) {
    final annotationElement = annotation.element!.declaration!;

    final elementDecleration = element.library.session
        .getParsedLibraryByElement(element.library)
        .getElementDeclaration(annotationElement);

    // elementDecleration is null i think because annotationElement is synthetic

    final node = element.node; // throws

    final String type = _getUndefinedType(node);

    _createClassWithName(type);
  }
}

I want to get the ast because I need to get the undefined type on Collection<T> so I can use that name to build it. Any help is much appreciated.

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-questionA question about expected behavior or functionality

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions