generateForAnnotatedElement method

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

Implement to return source code to generate for element.

This method is invoked based on finding elements annotated with an instance of T. The annotation is provided as a ConstantReader.

Supported return values include a single String or multiple String instances within an Iterable or Stream. It is also valid to return a Future of String, Iterable, or Stream.

Implementations should return null when no content is generated. Empty or whitespace-only String instances are also ignored.

Implementation

@override
String generateForAnnotatedElement(
  Element element,
  ConstantReader annotation,
  BuildStep buildStep,
) {
  if (element is! ClassElement) {
    throw '@BleObject can only be used on classes';
  }

  final className = element.name;
  print('Generating parser for class: $className');

  // Read default values from @BleObject annotation
  final defaultEndian = _readDefaultEndian(annotation);
  final defaultSigned = _readDefaultSigned(annotation);

  final buffer = StringBuffer();

  // Generate private parsing function: _$ClassNameFromBytes
  buffer.writeln('$className _\$${className}FromBytes(List<int> rawData) {');
  buffer.writeln(
    '  final view = ByteData.sublistView(Uint8List.fromList(rawData));',
  );

  int autoOffset = 0;
  List<String> constructorArgs = [];

  // Iterate through all fields
  for (var field in element.fields) {
    if (field.isStatic) continue;

    // Get @BleField annotation with defaults applied
    final fieldAnn = _getAnnotation(field, defaultEndian, defaultSigned);
    if (fieldAnn == null) continue;

    // 1. Determine offset
    int currentOffset = fieldAnn.offset ?? autoOffset;

    // 2. Generate read expression
    String readExpr = _genReadExpr(fieldAnn, currentOffset);

    // 3. Store constructor arguments
    constructorArgs.add('${field.name}: $readExpr');

    // 4. Update auto offset
    autoOffset = currentOffset + fieldAnn.length;
  }

  // Generate return statement
  buffer.writeln('  return $className(');
  buffer.writeln(constructorArgs.join(',\n'));
  buffer.writeln('  );');
  buffer.writeln('}');

  return buffer.toString();
}