Skip to content

Commit

Permalink
Add null-unsoundness check to print's object.toString() result.
Browse files Browse the repository at this point in the history
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: #47196
Change-Id: I7f10156330994d31e44384fa952dd88385e2628d
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/214043
Reviewed-by: Nate Bosch <[email protected]>
Commit-Queue: Lasse R.H. Nielsen <[email protected]>
  • Loading branch information
lrhn authored and [email protected] committed Sep 23, 2021
1 parent 65184a9 commit 651d6e0
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 3 deletions.
2 changes: 1 addition & 1 deletion sdk/lib/core/print.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
3 changes: 1 addition & 2 deletions sdk/lib/internal/internal.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down

0 comments on commit 651d6e0

Please sign in to comment.