如何为字段注释生成 Dart 代码?

Mar*_*cel 5 dart build-runner

我正在使用 为 Dart 编写代码生成器build_runner,但是我的构建器没有被调用以在字段中进行注释,尽管它确实适用于类中的注释。

是否也可以在字段(或任何地方)调用生成器进行注释?

例如,为以下文件调用构建器:

import 'package:my_annotation/my_annotation.dart';

part 'example.g.dart';

@MyAnnotation()
class Fruit {
  int number;
}
Run Code Online (Sandbox Code Playgroud)

但不是这个:

import 'package:my_annotation/my_annotation.dart';

part 'example.g.dart';

class Fruit {
  @MyAnnotation()
  int number;
}
Run Code Online (Sandbox Code Playgroud)

这是注释的定义:

class MyAnnotation {
  const MyAnnotation();
}
Run Code Online (Sandbox Code Playgroud)

这就是生成器的定义方式。目前,只要调用它就会中止,从而导致打印错误消息。

library my_annotation_generator;

import 'package:analyzer/dart/element/element.dart';
import 'package:build/build.dart';
import 'package:my_annotation/my_annotation.dart';
import 'package:source_gen/source_gen.dart';

Builder generateAnnotation(BuilderOptions options) =>
    SharedPartBuilder([MyAnnotationGenerator()], 'my_annotation');

class MyAnnotationGenerator extends GeneratorForAnnotation<MyAnnotation> {
  @override
  generateForAnnotatedElement(Element element, ConstantReader annotation, _) {
    throw CodeGenError('Generating code for annotation is not implemented yet.');
}
Run Code Online (Sandbox Code Playgroud)

这是build.yaml配置:

targets:
  $default:
    builders:
      my_annotation_generator|my_annotation:
        enabled: true

builders:
  my_annotation:
    target: ":my_annotation_generator"
    import: "package:my_annotation/my_annotation.dart"
    builder_factories: ["generateAnnotation"]
    build_extensions: { ".dart": [".my_annotation.g.part"] }
    auto_apply: dependents
    build_to: cache
    applies_builders: ["source_gen|combining_builder"]
Run Code Online (Sandbox Code Playgroud)

Dan*_*n R 6

至少根据我的经验,您的文件“example.dart”将需要在类定义之上至少有一个注释才能由 GeneratorForAnnotation 进行解析。

示例.dart:

import 'package:my_annotation/my_annotation.dart';

part 'example.g.dart';

@MyAnnotation()
class Fruit {
 @MyFieldAnnotation()
 int number;
}
Run Code Online (Sandbox Code Playgroud)

要访问类字段或类方法上方的注释,您可以使用访问者“访问”每个子元素并提取源代码信息。例如,要获取有关类字段的信息,您可以重写方法 VisitFieldElement,然后使用 getter:element.metadata 访问任何注释。

生成器.dart:

import 'dart:async';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/visitor.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:build/src/builder/build_step.dart';
import 'package:source_gen/source_gen.dart';
import 'package:my_annotation/my_annotation.dart';

class MyAnnotationGenerator extends 
GeneratorForAnnotation<MyAnnotation> {
  @override
  FutureOr<String> generateForAnnotatedElement(
      Element element, 
      ConstantReader annotation,   
      BuildStep buildStep,){
    return _generateSource(element);
  }

  String _generateSource(Element element) {
    var visitor = ModelVisitor();
    element.visitChildren(visitor);
    return '''
      // ${visitor.className}
      // ${visitor.fields}
      // ${visitor.metaData}
    ''';
  }
}

class ModelVisitor extends SimpleElementVisitor {
  DartType className;
  Map<String, DartType> fields = {};
  Map<String, dynamic> metaData = {};

  @override
  visitConstructorElement(ConstructorElement element) {
    className = element.type.returnType;
  }

  @override
  visitFieldElement(FieldElement element) {
    fields[element.name] = element.type;
    metaData[element.name] = element.metadata;
  }
}
Run Code Online (Sandbox Code Playgroud)

注意:在此示例中,_generateSource 返回注释语句。如果没有注释,您将需要返回格式良好的 dart 源代码,否则构建器将因错误而终止。

有关更多信息,请参阅:源代码生成和编写自己的包(The Boring Flutter Development Show,第 22 集)https://www.youtube.com/watch?v=mYDFOdl-aWM&t=459s


Mar*_*cel 2

内置函数GeneratorForAnnotation使用LibraryElementsannotatedWith(...)方法,该方法仅检查顶级注释。为了还检测字段上的注释,您需要编写一些自定义内容。

这是Generator我为我的项目写的:

abstract class GeneratorForAnnotatedField<AnnotationType> extends Generator {
  /// Returns the annotation of type [AnnotationType] of the given [element],
  /// or [null] if it doesn't have any.
  DartObject getAnnotation(Element element) {
    final annotations =
        TypeChecker.fromRuntime(AnnotationType).annotationsOf(element);
    if (annotations.isEmpty) {
      return null;
    }
    if (annotations.length > 1) {
      throw Exception(
          "You tried to add multiple @$AnnotationType() annotations to the "
          "same element (${element.name}), but that's not possible.");
    }
    return annotations.single;
  }

  @override
  String generate(LibraryReader library, BuildStep buildStep) {
    final values = <String>{};

    for (final element in library.allElements) {
      if (element is ClassElement && !element.isEnum) {
        for (final field in element.fields) {
          final annotation = getAnnotation(field);
          if (annotation != null) {
            values.add(generateForAnnotatedField(
              field,
              ConstantReader(annotation),
            ));
          }
        }
      }
    }

    return values.join('\n\n');
  }

  String generateForAnnotatedField(
      FieldElement field, ConstantReader annotation);
}
Run Code Online (Sandbox Code Playgroud)