Repository navigation
Report an invalid psalm-refactor destination instead of crashing - #14097
Conversation
✅ Performance: unchanged · Types: unchanged
How to read this table
head 86a3fa0 · base 5bcb365 (merge-base) · workflow run |
alies-dev
left a comment
There was a problem hiding this comment.
🤖 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)
src/Psalm/Internal/Cli/Refactor.phpcatchesRefactorExceptiononly fromcheck().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. Addmissing source classanddestination already existsdata-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_EOLis repeated three times; a small closure/local$expect_valuewould 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.
|
Thanks for the review, good catch on the coverage.
All of it is in a new commit on top, so the earlier one is unchanged. |
orklah
left a comment
There was a problem hiding this comment.
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::membersource needs aCls::memberdestination with a non-empty identifier member; - a
Cls::$propsource needs aCls::$propdestination.
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.
|
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.
Tests: your eight commands are data-provider cases, plus a standalone This is shape only. Reserved words such as |
…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.
|
The Windows job failed on the doubled leading backslash case ( |
alies-dev
left a comment
There was a problem hiding this comment.
🤖 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)
- The full-project self-analysis jobs blow up on this head, and it is caused by this PR:
- Shepherd
buildon22061839:Taint graph resolution took 1015.7 seconds,Checks took 1,106.68 seconds and used 6,867.465MB. Amasterpush 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 Psalmwas cancelled by its 15 minutetimeout-minuteson both2e71cd6cand22061839. The same job passed in about 4 to 6 minutes on94b3087band27272bfa, and on every other branch in the same window.
So the regression arrives with2e71cd6c(the shape validation:Refactor::getShapeError()/exitOnShapeError()/stripLeadingBackslash(), theCliUtils::getArguments()branch, and thePsalterEndToEndTestadditions). I could not reproduce it by analysing only the changed files plussrc/Psalm/Internal/Cliandtests/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 thefwrite(STDERR, ...)/exitpaths; I have not confirmed which hunk it is.
Fix: run the CI command locally (./psalm --output-format=github --shepherdequivalent, i.e. full project with taint analysis) with and without2e71cd6c, 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.
- Shepherd
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/--toeven when it matches an existing path) is reasonable;psalm-refactoris 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.
|
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 ( In I compared 30 commands against the previous head. Only three invalid destinations changed their message ( The new head, |
orklah
left a comment
There was a problem hiding this comment.
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:
- 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. provideInvalidRefactorDestinations()doesyield from self::provideMalformedRefactorMappings(), so every shape case also runs withpsalm --initand a project, on top oftestRefactorRejectsAMalformedMappingBeforeLoadingTheConfig. That doubles ~27 end-to-end processes and the end-to-end shard went from about 4 to about 9-10 minutes. Please remove theyield 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.
|
Thanks for testing. Both changes are in
On PHP 8.4, |
orklah
left a comment
There was a problem hiding this comment.
Thanks @MohannadElemary, merged.
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 (
--intoat 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