More explicit errors for return; vs return null;

Both for "return null" in a void function and "return" in
a nullable return function.
This commit is contained in:
Nikita Popov 2016-06-04 13:25:52 +02:00
parent fe907562ad
commit 73b2f79199
3 changed files with 30 additions and 4 deletions

View File

@ -9,4 +9,4 @@ function foo(): void {
// Note the lack of function call: function validated at compile-time
--EXPECTF--
Fatal error: A void function must not return a value in %s on line %d
Fatal error: A void function must not return a value (did you mean "return;" instead of "return null;"?) in %s on line %d

View File

@ -0,0 +1,14 @@
--TEST--
Nullable typed return without value generates friendlier error message
--FILE--
<?php
function test() : ?int {
return;
}
test();
?>
--EXPECTF--
Fatal error: A function with return type must return a value (did you mean "return null;" instead of "return;"?) in %s on line %d

View File

@ -2270,7 +2270,13 @@ static void zend_emit_return_type_check(
/* `return ...;` is illegal in a void function (but `return;` isn't) */
if (return_info->type_hint == IS_VOID) {
if (expr) {
zend_error_noreturn(E_COMPILE_ERROR, "A void function must not return a value");
if (expr->op_type == IS_CONST && Z_TYPE(expr->u.constant) == IS_NULL) {
zend_error_noreturn(E_COMPILE_ERROR,
"A void function must not return a value "
"(did you mean \"return;\" instead of \"return null;\"?)");
} else {
zend_error_noreturn(E_COMPILE_ERROR, "A void function must not return a value");
}
}
/* we don't need run-time check */
return;
@ -2280,8 +2286,14 @@ static void zend_emit_return_type_check(
zend_op *opline;
if (!expr && !implicit) {
zend_error_noreturn(E_COMPILE_ERROR,
"A function with return type must return a value");
if (return_info->allow_null) {
zend_error_noreturn(E_COMPILE_ERROR,
"A function with return type must return a value "
"(did you mean \"return null;\" instead of \"return;\"?)");
} else {
zend_error_noreturn(E_COMPILE_ERROR,
"A function with return type must return a value");
}
}
if (expr && expr->op_type == IS_CONST) {