Skip to content

Report an invalid psalm-refactor destination instead of crashing - #14097

Merged
orklah merged 7 commits into
vimeo:masterfrom
MohannadElemary:fix/refactor-empty-destination
Nov 21, 2026
Merged

orklah merged 7 commits into
vimeo:masterfrom
MohannadElemary:fix/refactor-empty-destination

Conversation

@MohannadElemary

Copy link
Copy Markdown
Contributor

psalm-refactor scanned the whole project and then crashed with an uncaught RefactorException when the --into or --to value was empty, and also when the destination class didn't exist. A missing value (--into at the end, or followed by another option such as --rename) was not caught either: it ended in "No --move or --rename arguments supplied" or silently dropped the --move and ran only the rename that followed.

Now an empty, whitespace-only or missing --into/--to value is rejected before any scanning with "--into expects a value" (or "--to expects a value") and exit code 1. A RefactorException from the analysis, such as a missing destination class, is printed as a plain error with exit code 1, and no file is changed.

Fixes #13698

@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

✅ Performance: unchanged · Types: unchanged

Project Memory (MB) Wall (s) Issues Weighted (types) Taint
✅ laravel 1 705 95.6 $\color{gray}{\textsf{+1.7\%}}$ 26 008 53 298 574
✅ symfony 3 620 157.9 $\color{gray}{\textsf{-1.1\%}}$ 50 782 99 101 1 254
✅ doctrine-orm 392 20.4 $\color{gray}{\textsf{-0.4\%}}$ 3 527 6 265 0
✅ psl 632 25.4 $\color{gray}{\textsf{+0.4\%}}$ 1 309 5 471 2
✅ phpunit 471 14.1 $\color{gray}{\textsf{-0.7\%}}$ 1 604 2 391 17
✅ php-parser 232 9.4 $\color{gray}{\textsf{-1.3\%}}$ 17 129 21 025 0
✅ tempest 892 24.1 $\color{gray}{\textsf{-0.4\%}}$ 4 930 10 536 97
✅ amphp-amp 61 2.2 29 49 0
✅ webmozarts-assert 284 5.2 $\color{gray}{\textsf{+0.4\%}}$ 577 2 722 0
✅ guzzle-promises 55 2.2 $\color{gray}{\textsf{+1.4\%}}$ 161 438 2
✅ monolog 153 6.0 $\color{gray}{\textsf{+0.2\%}}$ 907 2 422 10
✅ drupal 4 753 162.1 $\color{gray}{\textsf{+0.1\%}}$ 98 268 171 452 595
Total 13 249 524.6 205 231 375 170 2 551
How to read this table
  • Memory: Psalm's own peak figure, threads=1. More than +5 % fails, unless the PR changes composer.json.
  • Wall: base and head run on the same runner; ±10 % is noise. Above +20 % warns, never fails. re-run: a reversed second run was taken and the faster kept.
  • Issues: head count over all categories, then $\color{red}{\textsf{+added}}$ $\color{green}{\textsf{-removed}}$ against base.
  • Weighted (types): type issues weighted by error level (levels 1–8 as is, always-errors 10, strictness checks 1). Taint and dead-code issues are not weighed. The projects' own code is pinned and their dependencies resolve identically for base and head, so a change means Psalm reports more, fewer or differently serious issues. A rise is not necessarily a regression.
  • Taint: head count of Tainted* issues, then $\color{orange}{\textsf{+added}}$ $\color{orange}{\textsf{-removed}}$ against base. Both are orange as either direction needs review: more can be new detection or false positives, fewer can be fixed false positives or lost detection.
  • Dead code: head count of unused-code issues, shown only when a run reported some (findUnusedCode). More is red, fewer is green.
  • Total: sum over the projects compared on both sides. Thresholds apply per project, not to the total.
  • Colors: $\color{red}{\textsf{red}}$ past a fail or warn threshold (or more issues), $\color{green}{\textsf{green}}$ an improvement past noise (or fewer issues), $\color{orange}{\textsf{orange}}$ needs review, $\color{gray}{\textsf{gray}}$ noise.
  • Performance: regressed if a head run crashed or timed out or a memory or wall delta is red, else improved if one is green, else unchanged. Its icon is the check result: ❌ fail · ⚠️ warn · ✅ pass; the icon next to each project is that project's result, 💥 = not comparable: base crashed or timed out (counts as ⚠️).
  • Types (heading): direction of the total weighted change, increased · decreased · unchanged. Taint and Dead code (heading): added and removed counts, present only when non-zero. Informational, never fails the check.

head 86a3fa0 · base 5bcb365 (merge-base) · workflow run

@alies-dev alies-dev left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Fixes #13698 at the right layer: the empty/missing value is rejected in the CLI argument loop before any scanning, and the RefactorException thrown from ProjectAnalyzer (after the scan, since it needs the codebase to know whether the class exists) is turned into a plain error with exit code 1 where check() is called. Not fixed on upstream/master: Refactor.php has no value checks and no catch there.

Overlap with #14070: same file, disjoint hunks (that one only changes LONG_OPTIONS and the help text); no conflict expected.

Findings (blocking)

  1. src/Psalm/Internal/Cli/Refactor.php catches RefactorException only from check(). ProjectAnalyzer::refactorCodeAfterCompletion()/check() also throws it for "Source class X doesn’t exist" and "Destination class X already exists" (ProjectAnalyzer.php, same switch as the missing-destination case), and these are covered by the same catch, but the tests only exercise the missing destination. Add missing source class and destination already exists data-provider entries; otherwise the contract in the description ("A RefactorException from the analysis ... is printed as a plain error") is only half pinned.

Recommendations (non-blocking)

  • Refactor.php:235, :282, :322: ($operation === 'move_into' ? '--into' : '--to') . ' expects a value' . PHP_EOL is repeated three times; a small closure/local $expect_value would keep the message in one place.
  • The new guard at loop start (str_starts_with($arg, '-') while waiting for the destination) also rejects --into -h/--into --no-progress, which is the desired behaviour; one data-provider entry for an unrelated option after --into (not only --rename) would document that.
  • Good that the existing test now asserts exit code 0 before the other assertions.

@MohannadElemary

Copy link
Copy Markdown
Contributor Author

Thanks for the review, good catch on the coverage.

  • Added test cases for a missing source class (Source class Ns\Missing doesn’t exist) and for a destination class that already exists (Destination class Ns\C already exists). Both exit with 1, print only the message and leave the file untouched. On master they end in an uncaught RefactorException.
  • The "expects a value" message now comes from a small closure, so the three call sites share it. The output is the same.
  • Added --into --no-progress as a case too. It now prints "--into expects a value", where master said "No --move or --rename arguments supplied".

All of it is in a new commit on top, so the earlier one is unchanged.

@orklah orklah left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! The empty, whitespace-only and missing --into/--to handling and the RefactorException catch work. I ran each new case's command by hand. On the base it ends in an uncaught exception or a misleading message ("No --move or --rename arguments supplied", "Cannot locate Ns\B"). On 27272bf it prints the expected message.

But other malformed destinations come from the same root cause: the destination is never checked against the source's shape. They still either crash after the scan or, worse, exit 0 and rewrite the code into invalid PHP. Reproduced on 27272bf with

<?php
namespace Ns;
class A {
    public static int $p = 1;
    public const K = 1;
    public static function foo(): void {}
}
class B {}
function f(): void { A::foo(); echo A::$p, A::K; }

Uncaught RuntimeException: PHP Error: Undefined array key 1 (in ProjectAnalyzer::interpretRefactors()):

psalm-refactor --rename 'Ns\A::foo' --to 'Ns\A'      // ProjectAnalyzer.php:666
psalm-refactor --rename 'Ns\A::$p'  --to 'Ns\A'      // ProjectAnalyzer.php:707
psalm-refactor --rename 'Ns\A'      --to 'Ns\C::foo' // ProjectAnalyzer.php:659

Exit code 0, and the file is rewritten into invalid PHP:

psalm-refactor --rename 'Ns\A::foo' --to 'Ns\A::'  // public static function (): void { ... }  and  A::();
psalm-refactor --rename 'Ns\A::$p'  --to 'Ns\A::$' // public static int $ = 1;  and  A::$
psalm-refactor --rename 'Ns\A::K'   --to 'Ns\A::'  // public const  = 1;  and  A::
psalm-refactor --rename 'Ns\A'      --to 'Ns\'     // class  { ... }
psalm-refactor --rename 'Ns\A::foo' --to 'Ns\B::'  // foo() removed from A, a nameless method added to B

Could you validate the destination's shape in the argument loop, before scanning, like the empty value? Rules:

  • a class source needs a class destination in which every \-separated segment is a non-empty identifier;
  • a Cls::member source needs a Cls::member destination with a non-empty identifier member;
  • a Cls::$prop source needs a Cls::$prop destination.

Each rejected shape should exit 1 with a message. Keep the wildcard form (Ns\* → Other\*) accepted. Please add a data-provider case for each command above.

Optional: --into '\Ns\B' (leading backslash) reports "Destination class \Ns\B doesn’t exist". Stripping the leading \ would be friendlier.

A class source needs a class destination, a Cls::member source a
Cls::member destination and a Cls::$prop source a Cls::$prop
destination. A wildcard needs a non-empty prefix on both sides. Each
mapping is checked right before it is stored, so a later valid pair
for the same source can't hide a malformed one. One leading backslash
is stripped from --into, --to and every source.
@MohannadElemary

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough repro, all eight reproduced exactly as you described. I added a commit on top that checks every mapping's shape while the arguments are read, before the config is loaded or anything is scanned.

  • A class source needs a class destination where every \ separated segment is a non-empty identifier. A Cls::member source needs a Cls::member destination with exactly one :: and an identifier member, and a Cls::$prop source needs a Cls::$prop destination. Methods and constants share the Cls::name shape, and ProjectAnalyzer still decides which one it is.
  • Wildcards keep working (Ns\* to Other\*, Ns\A* to Other\B*, --move 'Ns\*' --into Other). A standalone * on either side is now rejected, since interpretRefactors() never expands it, and so is a wildcard on only one side.
  • The check runs on each mapping right before it is stored, including every item of a comma separated --move list, so a malformed pair can't be hidden by a later valid pair with the same source.
  • I took the optional --into suggestion and went a bit further: one leading \ is stripped from --into, --to and every source. --to '\Ns\C' used to exit 0 and write namespace \Ns;. A doubled \\ still fails the shape check.
  • Each rejection exits 1 with a message naming the source and the bad destination, for example "Destination for Ns\A::foo must be of the form Foo\Bar::baz, got Ns\A::".

Tests: your eight commands are data-provider cases, plus a standalone * on each side, a wildcard destination for a class, a malformed pair followed by a valid one for the same source, a malformed source inside a --move list, Ns\\C, Ns\A::bar::baz, Ns\A::1bad, Ns\A::K to Ns\A::$k, the malformed source Ns\A:: and a doubled leading backslash. Each one asserts exit 1, the exact message and an unchanged file. The same shape cases also run once with no psalm.xml present, which shows they fail before the config is loaded. A new provider covers the valid paths end to end (both wildcard forms, --move with a wildcard, Ns\A::foo to Ns\B::baz, and a leading \ on --to, on a source and on --into) and checks the rewritten code and that every file still lints.

This is shape only. Reserved words such as Ns\class still pass, because a keyword list would be hard to keep right across namespace, class and member positions. I left that out of this PR and ProjectAnalyzer is untouched.

…the global namespace

CliUtils::getArguments() drops every argument that realpath() accepts,
so the value of --move, --into, --rename or --to vanished when it named
an existing path, such as a directory called src, and the option then
reported that it expects a value. This also appears to explain the
Windows failure on \\Ns\C, which PHP's realpath() can treat as a UNC
path. Keep the argument right after one of these options.

Renaming a namespaced class to a class without a namespace writes
"namespace ;", and keeping a value such as src made that reachable for
names that used to be dropped. Reject it before scanning until the
namespace rewrite is fixed separately.
@MohannadElemary

Copy link
Copy Markdown
Contributor Author

The Windows job failed on the doubled leading backslash case (\\Ns\C) with --to expects a value instead of the shape error. CliUtils::getArguments() drops any argument that realpath() accepts, and from reading php-src, PHP's Windows UNC path handling looks like what accepts \\Ns\C. I haven't reproduced that realpath() call on Windows directly. The same drop reproduces on Linux whenever a mapping value matches an existing directory, such as --into src or --to src. The value after --move, --into, --rename and --to is now always kept, with regression tests. Since that lets --to src reach the existing namespaced to global class rename, which writes namespace ;, that rename is now rejected with a message, and a proper fix for it can come separately. The Windows CI run on this push should confirm the original case.

@alies-dev alies-dev left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Addressed since the last review: the missing-source / destination-exists tests, the shared expects a value closure, the unrelated-option case, and the destination-shape validation that orklah asked for.

I ran orklah's reproduction (Ns\A with foo(), $p, K, B) against upstream/master (f836e87) merged with 22061839. The eight commands that used to crash or rewrite into invalid PHP (--to 'Ns\A', --to 'Ns\A::', --to 'Ns\', --to 'Ns\B::', --to 'Ns\C::foo', the $p → Ns\A and Ns\A::$ variants) now print a message and leave the file untouched. Valid --rename 'Ns\A' --to 'Ns\C', --rename 'Ns\A::foo' --to 'Ns\A::bar', --move 'Ns\A::foo' --into 'Ns\B' and --rename 'Ns\*' --to 'Other\*' still rewrite as before. So the behaviour side of that review is covered; orklah's CHANGES_REQUESTED needs his re-review or dismissal, which is not something I can do for him.

Findings (blocking)

  1. The full-project self-analysis jobs blow up on this head, and it is caused by this PR:
    • Shepherd build on 22061839: Taint graph resolution took 1015.7 seconds, Checks took 1,106.68 seconds and used 6,867.465MB. A master push run: taint graph 56.7s, total 151s, 4.7GB. Other PR Shepherd runs in the same window take about 105 to 190s in total.
    • macOS Run Psalm was cancelled by its 15 minute timeout-minutes on both 2e71cd6c and 22061839. The same job passed in about 4 to 6 minutes on 94b3087b and 27272bfa, and on every other branch in the same window.
      So the regression arrives with 2e71cd6c (the shape validation: Refactor::getShapeError()/exitOnShapeError()/stripLeadingBackslash(), the CliUtils::getArguments() branch, and the PsalterEndToEndTest additions). I could not reproduce it by analysing only the changed files plus src/Psalm/Internal/Cli and tests/EndToEnd (about 3s), so it only shows up in the whole-project taint graph. [INFERENCE] The likely suspects are the $argv-derived values now flowing through the three new static helpers into the fwrite(STDERR, ...)/exit paths; I have not confirmed which hunk it is.
      Fix: run the CI command locally (./psalm --output-format=github --shepherd equivalent, i.e. full project with taint analysis) with and without 2e71cd6c, bisect the hunks, and restructure the one that explodes (for example keep the shape check as a single function that takes the already-split parts and returns no tainted-string-derived value). The PR should not merge while a CI job times out and Shepherd takes 7 times longer.

Dropped / downgraded

  • Nothing earlier is still outstanding. The data-provider and closure asks are done.

Non-blocking

  • Reserved words (Ns\class) still pass the shape check, as noted in the PR; fine as a follow-up.
  • The CliUtils::getArguments() change (keeping the value after --move/--into/--rename/--to even when it matches an existing path) is reasonable; psalm-refactor is its only caller.

Stripping the --into or --to value inside the mapping loop, and
reassigning the --move list item with its stripped form, made the taint
analysis of Psalm itself several times slower (the Shepherd job went
from about a minute to over 15 minutes of taint graph resolution). The
destination is now stripped while the argument list is built, and the
stripped --move item gets its own variable. A lone backslash as a
destination now reports that the option expects a value.
Also shorten the comment on where --into and --to values are normalized.
@MohannadElemary

Copy link
Copy Markdown
Contributor Author

Thanks for catching the self-analysis regression. I reproduced it with full-project taint analysis on PHP 8.4 (8 threads, no cache). The slowdown came from the leading-backslash normalization in the mapping loop, not from the shape checks.

The base (27272bfa9) took 82s for taint resolution and 135s in total. 22061839 was still resolving the taint graph when it ran out of memory at a 5.6GB limit after 888s. Tested on their own, stripping the destination raised taint resolution to 191s, and reassigning the --move foreach item raised it to 406s. A new variable fixed the foreach case but not the destination strip (208s).

In 3386fadf0 I moved destination normalization into the loop that builds $args and used a separate variable for each --move source. Merged with master, the fixed code took 56.5s for taint resolution, 112s in total and 4.7GB, compared with 59s, 114s and 4.7GB on master (ad083c14). The reported issues were identical.

I compared 30 commands against the previous head. Only three invalid destinations changed their message (--to '\', --to=\ and --to '\-x' now say "--to expects a value"), and all of them still exit 1 before scanning. The full PHPUnit runs on 8.2, 8.4 and 8.6 RC had the same failures as master.

The new head, 32baad63, also adds end-to-end tests for --to=\Ns\C and for a --move source with a leading backslash. On this head the self-analysis took 63s for taint resolution and 114s in total. CI still needs to confirm it.

@orklah orklah left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this now behaves as requested: I re-ran the earlier commands on 32baad6 by hand and each one either prints the expected message with exit 1 or rewrites into valid code, and Shepherd is back to its usual time.

Two small things before merging:

  1. Please drop the comment at Refactor.php:217-218 ("Normalize --into/--to values… Doing it in the mapping loop makes full-project taint analysis much slower"). The code is clear without it, and the slowdown is a Psalm taint-resolver issue rather than something this code should document.
  2. provideInvalidRefactorDestinations() does yield from self::provideMalformedRefactorMappings(), so every shape case also runs with psalm --init and a project, on top of testRefactorRejectsAMalformedMappingBeforeLoadingTheConfig. That doubles ~27 end-to-end processes and the end-to-end shard went from about 4 to about 9-10 minutes. Please remove the yield from (keeping at most one shape case there if you want the "file unchanged" assertion).

Keep one shape case in provideInvalidRefactorDestinations() so the file-unchanged check still covers a shape error. Every shape case still runs once through testRefactorRejectsAMalformedMappingBeforeLoadingTheConfig.
@MohannadElemary

Copy link
Copy Markdown
Contributor Author

Thanks for testing. Both changes are in 86a3fa0d7:

  1. Removed the taint-performance comment. No executable code changed.
  2. Removed the yield from in provideInvalidRefactorDestinations(). I kept only "valid mapping followed by a malformed one" to retain the file-unchanged assertion when a later mapping fails. All malformed-mapping cases remain covered by the pre-config test.

On PHP 8.4, testRefactorReportsAnInvalidDestinationWithoutCrashing dropped from 44 to 19 cases (138s to 59s). The full PsalterEndToEndTest passes with 75 cases.

@orklah orklah added the release:fix The PR will be included in 'Fixes' section of the release notes label Nov 21, 2026

@orklah orklah left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @MohannadElemary, merged.

@orklah
orklah merged commit a0ee964 into vimeo:master Nov 21, 2026
71 of 72 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release:fix The PR will be included in 'Fixes' section of the release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

psalm-refactor crashes with an uncaught RefactorException on an empty --into=

3 participants