Skip to content

Commit 30de584

Browse files
committed
Emit callable expressions as regular function closures for PHP < 7.4
1 parent d33f710 commit 30de584

File tree

4 files changed

+36
-3
lines changed

4 files changed

+36
-3
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<?php namespace lang\ast\emit;
2+
3+
/**
4+
* Rewrites callable expressions to regular closures
5+
*
6+
* @see https://wiki.php.net/rfc/first_class_callable_syntax
7+
*/
8+
trait CallablesAsClosures {
9+
10+
protected function emitCallable($result, $callable) {
11+
12+
// Use variables in the following cases:
13+
//
14+
// $closure(...); => use ($closure)
15+
// $obj->method(...); => use ($obj)
16+
// $obj->$method(...); => use ($obj, $method)
17+
// ($obj->property)(...); => use ($obj)
18+
// $class::$method(...); => use ($class, $method)
19+
// [$obj, 'method'](...); => use ($obj)
20+
// [Foo::class, $method](...); => use ($method)
21+
$use= [];
22+
foreach ($result->codegen->search($callable, 'variable') as $var) {
23+
'this' === $var->name || $use[$var->name]= true;
24+
}
25+
26+
$t= $result->temp();
27+
$result->out->write('function(...'.$t.')');
28+
$use && $result->out->write('use($'.implode(', $', array_keys($use)).')');
29+
$result->out->write('{ return ');
30+
$this->emitOne($result, $callable->expression);
31+
$result->out->write('(... '.$t.'); }');
32+
}
33+
}

src/main/php/lang/ast/emit/PHP70.class.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
* @see https://wiki.php.net/rfc#php_70
99
*/
1010
class PHP70 extends PHP {
11-
use OmitPropertyTypes, OmitConstModifiers;
11+
use OmitPropertyTypes, OmitConstModifiers, CallablesAsClosures;
1212
use RewriteNullCoalesceAssignment, RewriteLambdaExpressions, RewriteMultiCatch, RewriteClassOnObjects, RewriteExplicitOctals;
1313

1414
/** Sets up type => literal mappings */

src/main/php/lang/ast/emit/PHP71.class.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
* @see https://wiki.php.net/rfc#php_71
99
*/
1010
class PHP71 extends PHP {
11-
use OmitPropertyTypes;
11+
use OmitPropertyTypes, CallablesAsClosures;
1212
use RewriteNullCoalesceAssignment, RewriteLambdaExpressions, RewriteClassOnObjects, RewriteExplicitOctals;
1313

1414
/** Sets up type => literal mappings */

src/main/php/lang/ast/emit/PHP72.class.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
* @see https://wiki.php.net/rfc#php_72
99
*/
1010
class PHP72 extends PHP {
11-
use OmitPropertyTypes;
11+
use OmitPropertyTypes, CallablesAsClosures;
1212
use RewriteNullCoalesceAssignment, RewriteLambdaExpressions, RewriteClassOnObjects, RewriteExplicitOctals;
1313

1414
/** Sets up type => literal mappings */

0 commit comments

Comments
 (0)