parseModelFileSource function

ParsedModelFile parseModelFileSource(
  1. String source
)

Parses the fields of a generated model file source.

Field declarations are matched by their final <type> <name>; form and re-parsed through parseModelField so categories, import paths, and inner types are reconstructed with the same rules used at generation time. The fromJson body is inspected to tell enum fields (which use .values.byName(...)) apart from custom model fields, since both render as a bare PascalCase type in the declaration.

Throws FormatException when the source contains no field declarations or a declaration uses an unsupported type.

Implementation

ParsedModelFile parseModelFileSource(String source) {
  var content = source.startsWith('\uFEFF') ? source.substring(1) : source;
  content = content.replaceAll('\r\n', '\n').replaceAll('\r', '\n');

  final fromJsonExprs = _extractFromJsonExprs(content);

  final fields = <ModelField>[];
  final seen = <String>{};
  for (final line in content.split('\n')) {
    final match = _fieldDeclRegex.firstMatch(line);
    if (match == null) continue;

    final dartType = match.group(1)!.trim();
    final name = match.group(2)!;
    if (!seen.add(name)) {
      throw FormatException('Duplicate field "$name" in model file.');
    }

    fields.add(_reconstructField(name, dartType, fromJsonExprs[name]));
  }

  if (fields.isEmpty) {
    throw const FormatException(
      'No field declarations found in model file. '
      'Expected lines like "final String name;".',
    );
  }

  return ParsedModelFile(fields: fields);
}