From 651d6e076b8f93559bf1bd63c3b5eba28df33f92 Mon Sep 17 00:00:00 2001 From: "Lasse R.H. Nielsen" Date: Thu, 23 Sep 2021 15:36:23 +0000 Subject: [PATCH] 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 Commit-Queue: Lasse R.H. Nielsen --- sdk/lib/core/print.dart | 2 +- sdk/lib/internal/internal.dart | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/sdk/lib/core/print.dart b/sdk/lib/core/print.dart index d88ea7f3c4d2..460a85204138 100644 --- a/sdk/lib/core/print.dart +++ b/sdk/lib/core/print.dart @@ -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); diff --git a/sdk/lib/internal/internal.dart b/sdk/lib/internal/internal.dart index 71f02d92e477..e7fd45ab3812 100644 --- a/sdk/lib/internal/internal.dart +++ b/sdk/lib/internal/internal.dart @@ -749,8 +749,7 @@ T checkNotNullable(T value, String name) { class NotNullableError 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`