simolus3 / drift

Drift is an easy to use, reactive, typesafe persistence library for Dart & Flutter.
https://drift.simonbinder.eu/
MIT License
2.67k stars 372 forks source link

"type 'Null' is not a subtype of type 'InterfaceElement' in type cast" during code generation #2883

Open btrautmann opened 9 months ago

btrautmann commented 9 months ago

Describe the bug

I'm seeing the following error just about every time I run build_runner locally. It can be cleared up with a flutter clean. I can try and take a peek into drift_dev later to see if it's something I can open a PR for, but wanted to open the issue in the meantime.

type 'Null' is not a subtype of type 'InterfaceElement' in type cast
package:drift_dev/src/analysis/resolver/dart/helper.dart 66:41   new KnownDriftTypes._fromLibrary
package:drift_dev/src/analysis/resolver/dart/helper.dart 104:28  KnownDriftTypes.resolve
package:drift_dev/src/analysis/driver/driver.dart 94:28          DriftAnalysisDriver.loadKnownTypes
package:drift_dev/src/analysis/resolver/discover.dart 77:46      DiscoverStep.discover
package:drift_dev/src/analysis/driver/driver.dart 130:7          DriftAnalysisDriver.discoverIfNecessary
package:drift_dev/src/backends/build/analyzer.dart 97:5          DriftAnalyzer.build

Drift version

  drift:
    dependency: "direct main"
    description:
      name: drift
      sha256: b50a8342c6ddf05be53bda1d246404cbad101b64dc73e8d6d1ac1090d119b4e2
      url: "https://pub.dev"
    source: hosted
    version: "2.15.0"
  drift_dev:
    dependency: "direct dev"
    description:
      name: drift_dev
      sha256: c037d9431b6f8dc633652b1469e5f53aaec6e4eb405ed29dd232fa888ef10d88
      url: "https://pub.dev"
    source: hosted
    version: "2.15.0"

Flutter Version

Flutter 3.16.4 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 2e9cb0aa71 (8 weeks ago) • 2023-12-11 14:35:13 -0700
Engine • revision 54a7145303
Tools • Dart 3.2.3 • DevTools 2.28.4

FWIW, I'm using json_serializable and copy_with_extension builders as well.

simolus3 commented 9 months ago

It's worrying that this happens a lot, but seemingly not all the time? Looking at the stack trace, this happens when the builder is trying to resolve some classes from package:drift to later check whether the classes you've annotated are subtypes of those. These classes all exist, so it shouldn't fail and especially it shouldn't fail inconsistently. It doesn't even fail on the first type, making it look like the analyzer is kind of in a weird state when this happens.

If you're willing to take a look at drift_dev here and run the build with a local checkout, it would be interesting to see what exportNamespace.definedNames.keys contains in _fromLibrary.

drriguz commented 9 months ago

image Same here.

ivanhercaz commented 8 months ago

Same here with the next versions:

I could "solve" it cleaning the cache and the generated files using dart run build_runner clean, then dart run build_runner watch and it asks me:

[INFO] Found 29 declared outputs which already exist on disk. This is likely because the`.dart_tool/build` folder was deleted, or you are submitting generated files to your source repository.
Delete these files?
1 - Delete
2 - Cancel build
3 - List conflicts

I choose 1, then the problem seems it is solved.

btrautmann commented 8 months ago

@ivanhercaz do you have other Builders being used in your codebase? I had this start happening again consistently and it was occurring any time I modified code that impacted json_serializables inputs. I just didn't have the time at the moment to triage further. But if I get a sec I can do what @simolus3 suggested above and run a local version of drift_dev. Just curious if there's a pattern here before I dive into that.

ivanhercaz commented 8 months ago

@ivanhercaz do you have other Builders being used in your codebase?

Yes, I have one for Riverpod (riverpod_generator 2.3.10) and one for Freezed (freezed_annotation 2.4.1).

btrautmann commented 7 months ago

@simolus3 I was able to get to this and checked out drift locally. To reproduce, I did the following:

This printed the following in console:

[WARNING] drift_dev on lib/ynab_api/_category.dart:
BRANDON: 263|Uint8List
[WARNING] drift_dev on lib/ynab_api/_category.dart:
BRANDON: 263|TypeConverter
[WARNING] drift_dev on lib/ynab_api/_category.dart:
BRANDON: 263|JsonTypeConverter2
[WARNING] drift_dev on lib/ynab_api/_category.dart:
BRANDON: 263|DriftAny
[WARNING] drift_dev on lib/ynab_api/_category.dart:
BRANDON: 263|UserDefinedSqlType
[WARNING] drift_dev on lib/ynab_api/_category.dart:
BRANDON: 263|DriftDatabase
[WARNING] drift_dev on lib/ynab_api/_category.dart:
BRANDON: 263|DriftAccessor
[WARNING] drift_dev on lib/ynab_api/_category.dart:
BRANDON: 263|Table
[WARNING] drift_dev on lib/ynab_api/_category.dart:
BRANDON: 263|View
[WARNING] drift_dev on lib/ynab_api/_category.dart:
BRANDON: 263|TableIndex
[SEVERE] drift_dev on lib/ynab_api/_category.dart:

From what I can tell, the missing key is TableInfo. The library being read at the time was drift_dev_helper (determined by printing the Uri being passed to readDart from resolve) which pretty clearly exports TableInfo, so I'm not sure why that wouldn't appear in the exported namespace.

I hope this helps; that may be as far as I can take it without additional breadcrumbs 🙃

btrautmann commented 7 months ago

OK scratch that. I had a hunch that since it was exported, it just wasn't being resolved for some reason, so I swapped out the current implementation of readDart in the AnalysisContextBackend with the following (Essentially just swapping getLibraryByUri for getResolvedLibrary and checking the correct return type):

@override
Future<LibraryElement> readDart(Uri uri) async {
  final result = await context.currentSession.getResolvedLibrary(uri.path);
  if (result is ResolvedLibraryResult) {
    return result.element;
  }

  throw NotALibraryException(uri);
}

With that done, I'm unable to reproduce with the steps indicated above. I'll admit that despite having done some code gen myself, I still struggle with understanding the full implications of the difference between resolving the element model versus the AST, both from a performance perspective but also from an actual functionality perspective, so I can't be confident that there's no downstream impacts of this change, but I at least wanted to point out that it seems to work as intended.

PROGrand commented 7 months ago
final result = await context.currentSession.getResolvedLibrary(uri.path);
  if (result is ResolvedLibraryResult) {
    return result.element;
  }

  throw NotALibraryException(uri);

Actually only works for first time. Second run generates same error. Problem in cache. Only cleaning of .dart_tool and rebuilding resolves this error.

chris-NR commented 1 month ago

I am seeing the same error during code generation. It appears to be raised against every .dart file in my repository - in some cases more than once per file, for example:

type 'Null' is not a subtype of type 'InterfaceElement' in type cast
[SEVERE] drift_dev on lib/src/services/database/database.dart (cached):

I can reproduce at will using these steps:

1. delete .dart_tool directory
2. dart run build_runner build (succeeds)
3. make a change to one of my drift files (see below for details of the change)
4. dart run build_runner build (FAILS)

The only change I am making is to add additional tables to the @DriftAccessor annotation on a DAO class in a separate 'part of' file.

Versions build_runner 2.4.13 drift_dev 2.20.3

Successful run

chris@orac atlas % dart run build_runner build
Resolving dependencies in `/Users/chris/Dev/aaaa/bbbb`... 
Downloading packages... 
Got dependencies in `/Users/chris/Dev/aaaa/bbbb`.
Building package executable... (6.6s)
Built build_runner:build_runner.
[INFO] Generating build script completed, took 505ms
[INFO] Precompiling build script... completed, took 6.8s
[INFO] Building new asset graph completed, took 1.5s
[INFO] Found 4 declared outputs which already exist on disk. This is likely because the`.dart_tool/build` folder was deleted, or you are submitting generated files to your source repository.
Delete these files?
1 - Delete
2 - Cancel build
3 - List conflicts
1
[INFO] Checking for unexpected pre-existing outputs. completed, took 12.0s
[INFO] Generating SDK summary completed, took 7.4s
[WARNING] json_serializable on lib/src/services/database/rows.dart:
The version constraint "any" on json_annotation allows versions before 4.9.0 which is not allowed.
[INFO] Running build completed, took 19.4s
[INFO] Caching finalized dependency graph completed, took 234ms
[INFO] Succeeded after 19.7s with 159 outputs (614 actions)
msxenon commented 1 week ago

any solution for the code-generator?