New statement node for extra wrapping block?
I'm not even sure how this PHP feature is called, but I'm talking about this:
{
$test = 'foo';
$test2 = 'bar';
}
It would be useful in the AST to have a special node for this so we can know user written code like this.
I think this makes sense, but would need some major (backwards incompatible) changes. Especially as properly supporting this would also require changing the structure of lots of other nodes that currently have a stmts array, but in reality on have a single stmt. E.g. if ($x) { ... } is really if ($x) stmt; with the single statement being a block.
OK, thanks. Feel free to close it or target 5.0 - but I'm not encouraging you to start a new major version because the transition period brings a lot of interoperability problems between tools and projects :) I'm happy that PHP-Parser stays in 4.x longer right now.
What was the original motivation for this request?
Above I've been thinking about the "radical" approach, but this could certainly also be introduced in a more minimal way, i.e. keeping if ($x) { ... } etc represented as currently, but e.g. if you write if ($x) { $foo; { $bar; } } then $bar would be part of Stmt\Block instead of merged into the parent array. This would avoid major backwards-compatibilty breakage while still representing the "unusual" cases more accurately.
Yes, sure, traditional if-else structure should still have the same AST, Stmt\Block could be there only if the code is "jailed" in this special way.
The motivation: static analysis could detect that a variable created inside such a block is used outside of this block, and report that as an error. It's opinionated but I think it would match how other languages behave, and some people might prefer that.
I've implemented this variant in https://github.com/nikic/PHP-Parser/commit/a1ccf57727b4e74ea4043561dae968976fd2bec0. Let me know if this is not what you had in mind.
Thank you, this is correct and nice to work with! 👍