Revivable reviveInstance()

in source_gen/lib/src/constants/revive.dart [22:106]


Revivable reviveInstance(DartObject object, [LibraryElement? origin]) {
  final objectType = object.type;
  Element? element = objectType!.alias?.element;
  if (element == null) {
    if (objectType is InterfaceType) {
      element = objectType.element;
    } else {
      element = object.toFunctionValue();
    }
  }
  origin ??= element!.library;
  var url = Uri.parse(urlOfElement(element!));
  if (element is FunctionElement) {
    return Revivable._(
      source: url.removeFragment(),
      accessor: element.name,
    );
  }
  if (element is MethodElement && element.isStatic) {
    return Revivable._(
      source: url.removeFragment(),
      accessor: '${element.enclosingElement.name}.${element.name}',
    );
  }

  if (element is ClassElement) {
    for (final e in element.fields.where(
      (f) => f.isPublic && f.isConst && f.computeConstantValue() == object,
    )) {
      return Revivable._(
        source: url.removeFragment(),
        accessor: '${element.name}.${e.name}',
      );
    }
  }

  // We try and return a public accessor/constructor if available.
  final allResults = <Revivable>[];

  /// Returns whether [result] is an acceptable result to immediately return.
  bool tryResult(Revivable result) {
    allResults.add(result);
    return !result.isPrivate;
  }

  // ignore: deprecated_member_use
  for (final type in origin!.definingCompilationUnit.types) {
    for (final e in type.fields
        .where((f) => f.isConst && f.computeConstantValue() == object)) {
      final result = Revivable._(
        source: url.removeFragment(),
        accessor: '${type.name}.${e.name}',
      );
      if (tryResult(result)) {
        return result;
      }
    }
  }
  final i = (object as DartObjectImpl).getInvocation();
  if (i != null) {
    url = Uri.parse(urlOfElement(i.constructor.enclosingElement));
    final result = Revivable._(
      source: url,
      accessor: i.constructor.name,
      namedArguments: i.namedArguments,
      positionalArguments: i.positionalArguments,
    );
    if (tryResult(result)) {
      return result;
    }
  }
  for (final e in origin.definingCompilationUnit.topLevelVariables.where(
    (f) => f.isConst && f.computeConstantValue() == object,
  )) {
    final result = Revivable._(
      source: Uri.parse(urlOfElement(origin)).replace(fragment: ''),
      accessor: e.name,
    );
    if (tryResult(result)) {
      return result;
    }
  }
  // We could try and return the "best" result more intelligently.
  return allResults.first;
}