Skip to content

Commit c38bcf7

Browse files
benjaminkincsesDextheking1
andauthored
fix: keep parens when calling the result of an assignment (#2521)
`($fn = function () {})`(...)` lost its parentheses: without them the call binds to the closure instead of the assignment result, producing invalid PHP. Closes #2409 --------- Co-authored-by: Dextheking1 <Dextheking1@users.noreply.github.com>
1 parent 87546de commit c38bcf7

4 files changed

Lines changed: 50 additions & 1 deletion

File tree

‎src/needs-parens.mjs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,10 @@ function needsParens(path, options) {
179179
} else if (parent.kind === "silent") {
180180
return false;
181181
} else if (parent.kind === "call") {
182-
return false;
182+
// `($fn = function () {})()` needs the parentheses: without them
183+
// the call binds to the closure instead of the assignment result.
184+
// https://github.com/prettier/plugin-php/issues/2409
185+
return key === "what";
183186
}
184187

185188
return true;
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
2+
3+
exports[`assign-call.php 1`] = `
4+
====================================options=====================================
5+
parsers: ["php"]
6+
printWidth: 80
7+
| printWidth
8+
=====================================input======================================
9+
<?php
10+
($fib = function () { return 42; })(10);
11+
12+
$result = ($fib = function ($n) use (&$fib) {
13+
return $n <= 1 ? $n : $fib($n - 1) + $fib($n - 2);
14+
})(10);
15+
16+
($fn = fn () => 42)();
17+
18+
call($a = $b);
19+
20+
=====================================output=====================================
21+
<?php
22+
($fib = function () {
23+
return 42;
24+
})(10);
25+
26+
$result = ($fib = function ($n) use (&$fib) {
27+
return $n <= 1 ? $n : $fib($n - 1) + $fib($n - 2);
28+
})(10);
29+
30+
($fn = fn() => 42)();
31+
32+
call($a = $b);
33+
34+
================================================================================
35+
`;

‎tests/assign-call/assign-call.php‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<?php
2+
($fib = function () { return 42; })(10);
3+
4+
$result = ($fib = function ($n) use (&$fib) {
5+
return $n <= 1 ? $n : $fib($n - 1) + $fib($n - 2);
6+
})(10);
7+
8+
($fn = fn () => 42)();
9+
10+
call($a = $b);

‎tests/assign-call/jsfmt.spec.mjs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
run_spec(import.meta, ["php"]);

0 commit comments

Comments
 (0)