dart-lang / sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
10.1k stars 1.56k forks source link

[Augmentations] Instance of augmented type can't be assigned to parameter of type extended/implemented via augment #56779

Open zajrik opened 1 hour ago

zajrik commented 1 hour ago

I'm working on a little library for fun in which I intend to provide macros for reducing boilerplate and implementing some behind-the-scenes details. For the time being I am prototyping by handwriting augmentations before hashing out the macro implementations to generate them. Unfortunately I'm encountering an error at runtime that is giving me trouble because the analyzer is reporting nothing, leading me to believe the code itself is valid.

I've prepared code samples here to reproduce the error:

// lib/test_augments.dart:

import augment 'augment_foo.dart';

class Foo {}
class Bar {}

void acceptBar(Bar bar) {
  print(bar);
}
// lib/augment_foo.dart:

augment library 'test_augments.dart';

augment class Foo implements Bar {}
// bin/test_augments.dart:

import 'package:test_augments/test_augments.dart' as test_augments;

void main(List<String> arguments) {
  test_augments.acceptBar(test_augments.Foo());
}

I receive no analyzer error but receive the following at runtime:

bin/test_augments.dart:4:41: Error: The argument type 'Foo' can't be assigned to the parameter type 'Bar'.
 - 'Foo' is from 'package:test_augments/test_augments.dart' ('lib/test_augments.dart').
 - 'Bar' is from 'package:test_augments/test_augments.dart' ('lib/test_augments.dart').
  test_augments.acceptBar(test_augments.Foo());
                                        ^

Given that the reported types in the error are from the same library in actuality (and visibly so in the error, even), I'm perplexed why this error is occurring. Of course, removing the augment and directly implementing Bar via class Foo implements Bar {} runs as expected and prints Instance of 'Foo'.

Here's my dart info for both the repro and the actual use-case:

#### General info

- Dart 3.5.3 (stable) (Wed Sep 11 16:22:47 2024 +0000) on "windows_x64"
- on windows / "Windows 10 Pro" 10.0 (Build 22631)
- locale is en-US

#### Project info

- sdk constraint: '^3.5.3'
- dependencies: macros
- dev_dependencies: lints, test
dart-github-bot commented 1 hour ago

Summary: The user is encountering a runtime error when trying to pass an instance of a class augmented to implement an interface to a function expecting that interface. The analyzer does not detect the error, leading to confusion. The user expects the augmented class to behave like a direct implementation, but the runtime error suggests a mismatch between the augmented class and the expected interface.