dart-lang / source_gen

Automatic source code generation for Dart
https://pub.dev/packages/source_gen
BSD 3-Clause "New" or "Revised" License
484 stars 105 forks source link

Use type argument for Future of nullable value in test #681

Closed srawlins closed 1 year ago

srawlins commented 1 year ago

This is a weird one, so I'm going to try to carefully explain the situation and my steps. Here is the code in question:

void _testSimpleValue(String testName, Object? value, Object? expected) {
  // ...
  _testFunction('Future<$testName>', Future.value(value), expected);
  // -------------------------------------^ inferred type argument
  // ...
}

void _testFunction(String testName, Object? value, Object? expected) { /* ... */ }

This code works today. It appears that the type of Future.value(...) inferred by CFE is Future<Object?>. A Future<Object?> constructed with the value constructor, and an Object? argument is sound. However, in https://github.com/dart-lang/language/issues/3304, it was decided that CFE infers the wrong type here, and should infer Future<Object>.

If and when CFE will change its behavior remains to be seen, but analyzer will start reporting an issue that an Object? argument was passed to a Future.value constructor for an argument type of Object, and that would be invalid. The situation there is that Future.value's single parameter is optional, so it's type is T?, but at runtime a null value will throw an exception, so we can pretend the parameter is both required and non-nullable when T is non-nullable.

So to prepare for a CFE change, and support analyzer's new warning, we can just put an explicit type argument.


Contribution guidelines:
- See our [contributor guide](https://github.com/dart-lang/.github/blob/main/CONTRIBUTING.md) for general expectations for PRs. - Larger or significant changes should be discussed in an issue before creating a PR. - Contributions to our repos should follow the [Dart style guide](https://dart.dev/guides/language/effective-dart) and use `dart format`. - Most changes should add an entry to the changelog and may need to [rev the pubspec package version](https://github.com/dart-lang/sdk/wiki/External-Package-Maintenance#making-a-change). - Changes to packages require [corresponding tests](https://github.com/dart-lang/.github/blob/main/CONTRIBUTING.md#Testing). Note that many Dart repos have a weekly cadence for reviewing PRs - please allow for some latency before initial review feedback.