PHP-Parser icon indicating copy to clipboard operation
PHP-Parser copied to clipboard

New statement node for extra wrapping block?

Open ondrejmirtes opened this issue 6 years ago • 2 comments

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.

ondrejmirtes avatar Mar 14 '19 10:03 ondrejmirtes

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.

nikic avatar Mar 14 '19 16:03 nikic

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.

ondrejmirtes avatar Mar 14 '19 17:03 ondrejmirtes

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.

nikic avatar Sep 24 '23 17:09 nikic

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.

ondrejmirtes avatar Sep 24 '23 18:09 ondrejmirtes

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.

nikic avatar Sep 24 '23 19:09 nikic

Thank you, this is correct and nice to work with! 👍

ondrejmirtes avatar Sep 24 '23 19:09 ondrejmirtes