source_gen icon indicating copy to clipboard operation
source_gen copied to clipboard

throwing an InvalidGenerationSource on an annotation "element"

Open mqus opened this issue 4 years ago • 0 comments

I have seen various different issues(#131, https://github.com/dart-lang/sdk/issues/34062, https://github.com/dart-lang/sdk/issues/32454) about this but never found a proper solution that wouldn't need me to create a utility function on my side. Of course, I could have missed something, if I did, please tell me what to do :)

We're currently working on a code generation library (https://pub.dev/packages/floor) which relies heavily on annotations, some of them expecting a string with e.g. an SQLite query. We're now adding a validator for these queries, which will throw errors if the query inside the annotation has some faults. Until now, we were throwing InvalidSourceGenerationErrors, which reference the method on which the annotation happened:

  InvalidGenerationSourceError fromAnalysisError(AnalysisError error) {
    return InvalidGenerationSourceError(
      'The query contained errors: ${error.message}',
      element: _methodElement,
    );
  }

Now, the output looks something like:

The query contained errors: Unknown column. These columns are available: id in Person, name in Person
package:_resolve_source/_resolve_source.dart:8:22
  ╷
8 │       Future<Person> findPersonByIdAndName(int id);
  │                      ^^^^^^^^^^^^^^^^^^^^^
  ╵

which does not show the annotation at all. But as the annotation is not Element, but ElementAnnotation I can't pass it as the source element. It would also be nice to be able to reference specific parts of the annotation.

Another issue is that the functions for getting the annotation content (firstAnnotationOfExact, annotationsOf, etc) only return DartObjects, which are impossible to use for proper errors referencing the context. I think that a more general API which returns matching ElementAnnotations could be more useful, especially if the associated DartObject is just a getter/computeConstantValue() away.

mqus avatar Jun 21 '20 12:06 mqus