dartObjectToCode function

String dartObjectToCode(
  1. DartObject object,
  2. ArtifactBuilder builder,
  3. List<Uri> importUris, {
  4. _AnnotationSourceArgs? sourceArgs,
  5. String? sourceExpression,
})

Implementation

String dartObjectToCode(
  DartObject object,
  ArtifactBuilder builder,
  List<Uri> importUris, {
  _AnnotationSourceArgs? sourceArgs,
  String? sourceExpression,
}) {
  _AnnotationSourceArgs? activeSourceArgs = sourceArgs;
  if (activeSourceArgs == null && sourceExpression != null) {
    activeSourceArgs = _parseArgsFromExpression(sourceExpression);
  }

  if (object.isNull) {
    return "null";
  }

  DartType type = object.type!;

  if (type.isDartCoreEnum || type.element is EnumElement) {
    String enumName = type.getDisplayString(withNullability: false);
    builder.registerDef(enumName);
    String enumValue =
        object.variable?.toString().split(" ").last.trim() ?? "ERROR";
    importUris.add(type.element!.library!.uri);
    return "${builder.applyDefsF(enumName)}.$enumValue";
  }

  if (type.isDartCoreSet) {
    List<DartObject> elements = object.toSetValue()!.toList();
    String elementType = (type as InterfaceType).typeArguments[0]
        .getDisplayString(withNullability: false);
    List<String>? elementSources =
        sourceExpression == null
            ? null
            : _parseCollectionElementSources(sourceExpression);
    List<String> encoded = <String>[];
    for (int i = 0; i < elements.length; i++) {
      String? elementSource;
      if (elementSources != null && i < elementSources.length) {
        elementSource = elementSources[i];
      }

      encoded.add(
        dartObjectToCode(
          elements[i],
          builder,
          importUris,
          sourceExpression: elementSource,
        ),
      );
    }
    return "<$elementType>{${encoded.join(",")}}";
  }

  if (type.isDartCoreList || type.isDartCoreIterable) {
    List<DartObject> elements = object.toListValue()!;
    String elementType = (type as InterfaceType).typeArguments[0]
        .getDisplayString(withNullability: false);
    List<String>? elementSources =
        sourceExpression == null
            ? null
            : _parseCollectionElementSources(sourceExpression);
    List<String> encoded = <String>[];
    for (int i = 0; i < elements.length; i++) {
      String? elementSource;
      if (elementSources != null && i < elementSources.length) {
        elementSource = elementSources[i];
      }

      encoded.add(
        dartObjectToCode(
          elements[i],
          builder,
          importUris,
          sourceExpression: elementSource,
        ),
      );
    }
    return "<$elementType>[${encoded.join(",")}]";
  }

  if (type.isDartCoreBool) {
    return object.toBoolValue()! ? "_T" : "_F";
  }

  if (type.isDartCoreInt) {
    return object.toIntValue()!.toString();
  }

  if (type.isDartCoreDouble) {
    return object.toDoubleValue()!.toString();
  }

  if (type.isDartCoreString) {
    return "${builder.stringD(object.toStringValue()!.replaceAll("'", "\\'"))}";
  }

  if (type.isDartCoreNum) {
    return object.toDoubleValue()!.toString();
  }

  if (type.isDartCoreMap) {
    Map<DartObject?, DartObject?> map = object.toMapValue()!;
    String keyType = (type as InterfaceType).typeArguments[0].getDisplayString(
      withNullability: false,
    );
    String valueType = type.typeArguments[1].getDisplayString(
      withNullability: false,
    );
    List<MapEntry<String, String>>? sourceEntries =
        sourceExpression == null
            ? null
            : _parseMapEntrySources(sourceExpression);
    List<String> encodedEntries = <String>[];
    int index = 0;
    for (MapEntry<DartObject?, DartObject?> entry in map.entries) {
      if (entry.key == null) {
        continue;
      }

      String? keySource;
      String? valueSource;
      if (sourceEntries != null && index < sourceEntries.length) {
        keySource = sourceEntries[index].key;
        valueSource = sourceEntries[index].value;
      }

      String keyCode = dartObjectToCode(
        entry.key!,
        builder,
        importUris,
        sourceExpression: keySource,
      );
      String valueCode =
          entry.value == null
              ? "null"
              : dartObjectToCode(
                entry.value!,
                builder,
                importUris,
                sourceExpression: valueSource,
              );
      encodedEntries.add("$keyCode: $valueCode");
      index++;
    }

    return "<$keyType, $valueType>{${encodedEntries.join(",")}}";
  }

  if (type.isDartCoreType) {
    DartType? dt = object.toTypeValue();
    return dt != null ? dt.getDisplayString(withNullability: false) : "dynamic";
  }

  String typeName = type.getDisplayString(withNullability: false);
  builder.registerDef(typeName);
  ClassElement ce = type.element as ClassElement;
  importUris.add(ce.library.uri);

  ConstructorElement? ctor = ce.unnamedConstructor;
  if (ctor == null) {
    if ((activeSourceArgs?.positional.isNotEmpty ?? false) ||
        (activeSourceArgs?.named.isNotEmpty ?? false)) {
      List<String> fallbackArgs = <String>[
        ...(activeSourceArgs?.positional ?? const <String>[]),
        ...(activeSourceArgs?.named.entries.map(
              (i) => "${i.key}: ${i.value}",
            ) ??
            const <String>[]),
      ];
      return "${builder.applyDefsF(typeName)}(${fallbackArgs.join(",")})";
    }

    return "${builder.applyDefsF(typeName)}()";
  }

  List<String> positionalArgs = <String>[];
  List<String> namedArgs = <String>[];
  int positionalParamIndex = 0;

  for (FormalParameterElement param in ctor.formalParameters) {
    String? paramName = param.name;
    if (paramName == null) {
      continue;
    }

    DartObject? value = _fieldValueOf(object, paramName);
    String? sourceArg;
    if (param.isNamed) {
      sourceArg = activeSourceArgs?.named[paramName];
    } else if ((activeSourceArgs?.positional.length ?? 0) >
        positionalParamIndex) {
      sourceArg = activeSourceArgs!.positional[positionalParamIndex];
    }
    if (!param.isNamed) {
      positionalParamIndex++;
    }

    if (value == null) {
      if (sourceArg != null) {
        if (param.isNamed) {
          namedArgs.add("$paramName: $sourceArg");
        } else {
          positionalArgs.add(sourceArg);
        }
      }
      continue;
    }

    String code = dartObjectToCode(
      value,
      builder,
      importUris,
      sourceExpression: sourceArg,
    );
    if (param.isNamed) {
      namedArgs.add("$paramName: $code");
    } else {
      positionalArgs.add(code);
    }
  }

  if (positionalArgs.isEmpty &&
      namedArgs.isEmpty &&
      ((activeSourceArgs?.positional.isNotEmpty ?? false) ||
          (activeSourceArgs?.named.isNotEmpty ?? false))) {
    positionalArgs.addAll(activeSourceArgs?.positional ?? const <String>[]);
    namedArgs.addAll(
      activeSourceArgs?.named.entries.map((i) => "${i.key}: ${i.value}") ??
          const <String>[],
    );
  }

  String args = [...positionalArgs, ...namedArgs].join(",");
  return "${builder.applyDefsF(typeName)}($args)";
}