Skip to content

Negative expression formats as functionally different code #2486

@bayruns

Description

@bayruns

Prettier 3.8.1
PHP Plugin 0.25.0

Options:

--parser php

Input:

<?php

$Y = 1;
$X = -$Y - 1;

Output:

<php

$Y = 1;
$X = -($Y - 1);

Expected behavior:

Prettier should preserve semantics. These two expressions are not equivalent:

-$Y - 1
-($Y - 1)

For example:

<?php

$Y = 1;

$a = -$Y - 1;      // -2
$b = -($Y - 1);    // 0

var_dump($a, $b);

This outputs:

int(-2)
int(0)

So the transformation performed by Prettier changes the behavior of the code.

Additional context:

  • Reproduced with prettier@3.8.1 and @prettier/plugin-php@0.25.0
  • PHP version setting: 8.4
  • Reproduced via CLI with:
npx prettier example.php --parser php --plugin=@prettier/plugin-php

This appears to be an incorrect rewrite involving unary minus and binary subtraction precedence.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions