Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support new T(...) callable syntax #32

Merged
merged 2 commits into from
Oct 6, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/main/php/lang/ast/syntax/PHP.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,31 @@ public function __construct() {
}

$parse->expecting('(', 'new arguments');

// Resolve ambiguity by looking ahead: `new T(...)` which is a first-class
// callable reference vs. `new T(...$it)` - a call with an unpacked argument
if ('...' === $parse->token->value) {
$dots= $parse->token;
$parse->forward();
if (')' === $parse->token->value) {
$parse->forward();

$arguments= [new UnpackExpression(new Variable('__args'), $token->line)];
if (null === $type) {
$class= $this->clazz($parse, null);
$class->annotations= $annotations;
$new= new NewClassExpression($class, $arguments, $token->line);
} else {
$new= new NewExpression($type, $arguments, $token->line);
}

return new CallableExpression($new, $token->line);
thekid marked this conversation as resolved.
Show resolved Hide resolved
}

$parse->queue[]= $parse->token;
$parse->token= $dots;
}

$arguments= $this->arguments($parse);
$parse->expecting(')', 'new arguments');

Expand Down
20 changes: 19 additions & 1 deletion src/test/php/lang/ast/unittest/parse/InvokeTest.class.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
<?php namespace lang\ast\unittest\parse;

use lang\ast\nodes\{CallableExpression, InstanceExpression, InvokeExpression, UnpackExpression, ScopeExpression, Literal, Variable};
use lang\ast\nodes\{
CallableExpression,
NewExpression,
InstanceExpression,
InvokeExpression,
UnpackExpression,
ScopeExpression,
Literal,
Variable
};
use unittest\{Assert, Test};

/**
Expand Down Expand Up @@ -87,4 +96,13 @@ public function first_class_callable_static() {
'self::length(...);'
);
}

#[Test]
public function first_class_callable_object_creation() {
$args= [new UnpackExpression(new Variable('__args'), self::LINE)];
$this->assertParsed(
[new CallableExpression(new NewExpression('\\T', $args, self::LINE), self::LINE)],
'new T(...);'
);
}
}