php-src icon indicating copy to clipboard operation
php-src copied to clipboard

Add nullsafe call and index access

Open Vovan-VE opened this issue 4 years ago • 18 comments

Description

Proposal

// Nullsafe call
$res = $optionalClosure?->(1, 2, 3);
$res = ($obj->optionalClosure)?->(1, 2, 3);
// or even?
$res = $obj->optionalClosure?->(1, 2, 3);

// Nullsafe index access
$res = $optionalArray?->[42];
$res = $obj->optionalArray?->[42];

Backward Incompatible Changes

No.

Motivation

  1. Nullsafe access operator ?-> already exists and whole expression consists of existing tokens only;
  2. Syntax like $fn?() and $arr?[42] is not possible since it's a part of already valid syntax ?: ;
  3. Syntax like $fn?‗() and $arr?‗[42] (where ‗ is anything else) most probably will never be added because ‗ is literally something else and leads to inconsistency with $obj?->member.

Open Issues

  • Must $obj->optionalClosure require parentheses ($obj->optionalClosure)?->() like ($obj->closure)() does?

Future Scope

Probably it may be a small step forward to $array->methods() like [1,2,3]->map(fn ($x) => $x * 10) which itself may be a step to more features like (-42)->abs(), $str->trim()->replace(...)->replace(...).

Vovan-VE avatar Dec 25 '21 05:12 Vovan-VE

OP is probably mimicking syntax from JS/TS. Other languages are using ?[...], but as OP mentioned this would be ambiguous in php. Nullsafe call seems to be unique to javascript (+ TS, Coffee).

As for future scope, this is unrelated. Also see: https://wiki.php.net/rfc/pipe-operator-v2

KapitanOczywisty avatar Dec 25 '21 11:12 KapitanOczywisty

This requires an RFC. @Vovan-VE, are you willing to pursue the RFC process?

cmb69 avatar Dec 27 '21 14:12 cmb69

@cmb69 , I'm not sure.

Vovan-VE avatar Dec 27 '21 15:12 Vovan-VE

Okay, maybe somebody else will. :)

cmb69 avatar Dec 27 '21 15:12 cmb69

Implementation in 5 years seems plausible. Which would be pretty close to what took to implement original proposal: https://wiki.php.net/rfc/nullsafe_calls then https://wiki.php.net/rfc/nullsafe_operator So hopefully there is somebody determinate enough to drag this through whole process 🤞

KapitanOczywisty avatar Dec 27 '21 16:12 KapitanOczywisty

Implementation for nullsafe offset access/calls should be easier as the ZEND_JMP_NULL instruction can be reused. If I'm not mistaken it's a matter of picking the least-sucking syntax and inserting the instruction in the right places. Although there's less of a reason for ?->[] to exist as ?? already works well for this case.

iluuu1994 avatar Dec 27 '21 16:12 iluuu1994

Although there's less of a reason for ?->[] to exist as ?? already works well for this case.

?? could be treated as workaround, but it's probably not desired in longer chains, when only some parts should be nullsafe (may hide warnings).

KapitanOczywisty avatar Dec 27 '21 17:12 KapitanOczywisty

I've been doing some quick experimenting. There are a few things to consider:

  1. How do we handle undefined indexes?

There's similar confusion about $foo?->bar where bar does not exist. Some people expect nullsafe to suppress those errors. I don't think it makes sense there as undefined properties are not something you'd encounter often in correct code. With arrays and undefined indexes it's less clear. I'd imagine many people would think that []?.['foo'] would run without errors.

  1. What about evaluation order of offset expressions?
echo $a[b()][c()];

// is equivalent to
$b = b();
$c = c();
echo $a[$b][$c];

Essentially, all offset expressions are evaluated before evaluating the actual offset access.

echo $a[b()]?.[c()];

// should probably be equivalent to
$b = b();
$tmp = $a[$b];
if ($tmp !== null) {
    $c = c();
    $tmp = $tmp[$c];
}
echo $tmp;

?-> had similar issues that were only fixed later on.

Over all, I'm not super convinced this is worthwhile, since ?? already does the job quite well.

iluuu1994 avatar Apr 15 '22 11:04 iluuu1994

Regarding 1.: a ?[] operation would at least allow for proper inline short-circuitable handling. E.g. ($a["does not exist"] ?? null)?["some index"]. I haven't given it much thought, but there could be in future some unary shortcut operator being semantically equivalent to array_key_exists($a, $key) ? $a[$key] : null. (Maybe a postfix !? Could then look like $a["does not exist"]!?["some index"].)

In that combination this feature probably could be quite useful.

Regarding 2.: yes.

bwoebi avatar Apr 15 '22 11:04 bwoebi

  1. How do we handle undefined indexes?

With $foo?.['bar'] it should only return null if $foo is null, nothing more, nothing less (exactly like ?->). This is the problem with ?? that it silences more than one kind of errors.

  1. What about evaluation order of offset expressions?

Preferably it should short-circuit the same way ?-> does as of 8.1.2 https://3v4l.org/4tgX7

Inconsistency between ?-> and ?[...] would be confusing, so just keep the same way.

Over all, I'm not super convinced this is worthwhile, since ?? already does the job quite well.

It's working, but since silences many errors, it allows for pretty stupid stuff to pass unnoticed. ?[...] would have only one error to silence.

KapitanOczywisty avatar Apr 15 '22 12:04 KapitanOczywisty

For both 1 and 2: As if call $f() would work as $f->__invoke() and $a[$i] would work as $a->__get($i):

operation would work as
$f?->() $f?->__invoke()
$a?->[$i] $a?->__get($i)

Shouldn't it?

Vovan-VE avatar Apr 15 '22 12:04 Vovan-VE

Not really. In general: $f?->() => $f !== null ? $f() : null $a?->[$i] => $a !== null ? $a[$i] : null

KapitanOczywisty avatar Apr 15 '22 12:04 KapitanOczywisty

I mean $object?->method() does already exist and has defined logic. So, $f?->() and $a?->[$i] should work in the same manner, as you said too.

Vovan-VE avatar Apr 15 '22 13:04 Vovan-VE

?->__invoke() works only on objects, ?->() if implemented would work on any callable. Anyway I'm clearly missing a point of your comparison.

KapitanOczywisty avatar Apr 15 '22 14:04 KapitanOczywisty

I mean $f?->() should work by the same existing logic of chaining as $o?->method(), like if $f() does Closure::fromCallable($f)->__invoke() in background. You know better what to do and how. So, I said nothing special here. English is not my first language.

Vovan-VE avatar Apr 16 '22 03:04 Vovan-VE

Would it make sense to make the null-coalesce operator also be a null-safe one when array-access is involved? Aka change the engine to NOT evaluate expr() in null[expr()] ?? etc? This would make sense to me.

nicolas-grekas avatar May 10 '22 09:05 nicolas-grekas

@nicolas-grekas Inconsistency would be bad, unless you want to replace also null->{expr()} ?? etx and then deal with BCs. ?-> already is short circuiting, thus better is to add array counter-part.

KapitanOczywisty avatar May 10 '22 12:05 KapitanOczywisty

There has not been any recent activity in this feature request. It will automatically be closed in 14 days if no further action is taken. Please see https://github.com/probot/stale#is-closing-stale-issues-really-a-good-idea to understand why we auto-close stale feature requests.

github-actions[bot] avatar Aug 09 '22 00:08 github-actions[bot]