google / json_serializable.dart

Generates utilities to aid in serializing to/from JSON.
https://pub.dev/packages/json_serializable
BSD 3-Clause "New" or "Revised" License
1.55k stars 396 forks source link

Invalid generated code when `typedef` refers to unimported file #1124

Open mernen opened 2 years ago

mernen commented 2 years ago

When a field refers to a typedef'd type, the generated code uses the original type name rather than its alias. However, if the original type isn't currently imported, the generated code doesn't compile.

A minimal testcase project is provided at mernen/testcase_serialize_typedef.dart.

Basically, imagine a project with the following structure:

After build_runner runs, comment.g.dart will attempt to use UserImpl.fromJson(...) to instantiate the User, but that name isn't imported!

Since part declarations can't themselves import anything, perhaps the only possible solution here (without the aid of the developer) would be to use the aliased name in this case.

Tested versions

absar commented 2 years ago

@kevmoo is it possible to use typedef aliases instead of original types in generated code, we now face above issue specially after #1136 which creates a generic converter in generated code _$JsonConverterToJson e.g. generates 'id': _$JsonConverterToJson<dynamic, Uuid>(instance.id, const UniqueIdConverter().toJson) instead of 'id': _$JsonConverterToJson<dynamic, UniqueId>(instance.id, const UniqueIdConverter().toJson) which is breaking the code since Uuid is never directly referred or imported, rather it's type def UniqueId is used to not refer external library names directly

kevmoo commented 1 year ago

Ha! This is likely gnarly.

I think the reference to the typedef is erased. The analyzer code I see doesn't know the referenced type is from a typedef.

I'd need to play a bit first to see for sure, though.

kevmoo commented 1 year ago

Yup. The typedef is effectively erased. I can't go back to the typedef when I generate the code. Maybe @scheglov has an idea?

scheglov commented 1 year ago

We have in DartType:

  /// If this type is an instantiation of a type alias, information about
  /// the alias element, and the type arguments.
  /// Otherwise return `null`.
  InstantiatedTypeAliasElement? get alias;

where

/// Information about an instantiated [TypeAliasElement] and the type
/// arguments with which it is instantiated.
abstract class InstantiatedTypeAliasElement {
  /// The alias element that is instantiated to produce a [DartType].
  TypeAliasElement get element;

  /// The type arguments with which the [element] was instantiated.
  /// This list will be empty if the [element] is not generic.
  List<DartType> get typeArguments;
}

So, yes, typedef is transparent, but there are vestiges.