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

EncapsedStringPart shouldn't extend from Expr; or it should be accepted by the printer

Open ondrejmirtes opened this issue 6 years ago • 2 comments

I thought it's safe to pass any Expr into prettyPrintExpr of PrettyPrinterAbstract, but EncapsedStringPart is an exception because of this implementation:

    protected function pScalar_EncapsedStringPart(Scalar\EncapsedStringPart $node) {
        throw new \LogicException('Cannot directly print EncapsedStringPart');
    }

This makes code that puts general Expr into prettyPrintExpr safe from the point of static types, but actually unsafe in runtime.

I'd have to go through all printer usages and check if I'm not passing this object there, probably with my own printer abstraction.

Is there a reason for this limitation? Can I work around it more easily?

ondrejmirtes avatar Jul 20 '19 06:07 ondrejmirtes

This is an error in the node classification, tracked at #500. The reason why it's not possible to pass an encapsed string part directly in the pretty printer is that a correct printing requires knowing the quote type the string is part of.

We could provide a possibly incorrect printing (e.g. assuming no quotes, i.e. heredoc), not sure whether that would be fine for your use-case.

nikic avatar Jul 20 '19 08:07 nikic

correct printing requires knowing the quote type the string is part of

Could this be solved by adding a property to EncapsedStringPart with this information that would get passed from the parser?

Anyway, you've got this covered in #500 so feel free to close this :)

ondrejmirtes avatar Jul 24 '19 03:07 ondrejmirtes

This is now Node\InterpolatedStringPart and no longer an Expr.

nikic avatar Sep 03 '22 13:09 nikic