Add null-unsoundness check to print's object.toString() result.

This makes it an *earlier* error if a `toString` method returns `null`
when passed to `print`, possibly a new error if the underlying platform's
print implementation let `null` through.
Returning `null` is something `toString` was never supposed to do,
and with null safety, it's enforced by the type system,
so only pre-null-safety legacy code can actually return `null`.

Makes the error message from `NotNullableError` not assume a parameter,
so it can be used in more places.

Bug: https://github.com/dart-lang/sdk/issues/47196
Change-Id: I7f10156330994d31e44384fa952dd88385e2628d
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/214043
Reviewed-by: Nate Bosch <nbosch@google.com>
Commit-Queue: Lasse R.H. Nielsen <lrn@google.com>
This commit is contained in:
Lasse R.H. Nielsen 2021-09-23 15:36:23 +00:00 committed by commit-bot@chromium.org
parent 65184a9ff4
commit 651d6e076b
2 changed files with 2 additions and 3 deletions

View file

@ -6,7 +6,7 @@ part of dart.core;
/// Prints a string representation of the object to the console.
void print(Object? object) {
String line = object.toString();
String line = checkNotNullable(object.toString(), "object.toString()");
var toZone = printToZone;
if (toZone == null) {
printToConsole(line);

View file

@ -749,8 +749,7 @@ T checkNotNullable<T extends Object>(T value, String name) {
class NotNullableError<T> extends Error implements TypeError {
final String _name;
NotNullableError(this._name);
String toString() =>
"Null is not a valid value for the parameter '$_name' of type '$T'";
String toString() => "Null is not a valid value for '$_name' of type '$T'";
}
/// A function that returns the value or default value (if invoked with `null`