Skip to content

Fix --generate-stubs signatures for intersections, true/never/static/parent, enums and readonly - #14114

Merged
orklah merged 3 commits into
vimeo:masterfrom
shu-chen-dot-ca:fix-13596-generate-stubs
Nov 23, 2026
Merged

orklah merged 3 commits into
vimeo:masterfrom
shu-chen-dot-ca:fix-13596-generate-stubs

Conversation

@shu-chen-dot-ca

Copy link
Copy Markdown
Contributor

Signature types

--generate-stubs narrows intersection types, widens true/false, drops never, void, mixed, null and callable, and writes static/parent as class names.

Before

<?php
interface I {}
interface J {}
function f(I&J $x): (I&J)|null { return rand(0, 1) ? $x : null; } // function f(\I $x): ?\I

class Base {}
class A extends Base {
    public function yes(): true { return true; }       // yes(): bool
    public function no(): int|false { return false; }  // no(): bool|int
    public function up(): parent { return $this; }     // up(): \parent
    public function same(): static { return $this; }   // same(): \A
    public function stop(): never { throw new Exception(); } // stop()
    public function nothing(): void {}                 // nothing()
    public function call(callable $c): void {}         // call($c)
}

After

function f(I&J $x): (I&J)|null { ... } // function f(\I&\J $x): (\I&\J)|null
    public function yes(): true { ... }       // yes(): true
    public function no(): int|false { ... }   // no(): false|int
    public function up(): parent { ... }      // up(): parent
    public function same(): static { ... }    // same(): static
    public function stop(): never { ... }     // stop(): never
    public function nothing(): void {}        // nothing(): void
    public function call(callable $c): void {} // call(callable $c): void

Enums

An enum is written as a class implementing BackedEnum/UnitEnum, with $name/$value properties and no cases.

Before

<?php
interface L {}
enum Suit: string implements L { // class Suit implements \BackedEnum, \UnitEnum, \L
    case Hearts = "h";
    case Spades = "s";
}

After

enum Suit: string implements L { // enum Suit : string implements \L { case Hearts = 'h'; case Spades = 's'; ... }

new defaults

Before

<?php
final class Dep {}
function f(Dep $dep = new Dep()): void {} // \Dep $dep = 'Psalm could not infer this type'

After

function f(Dep $dep = new Dep()): void {} // \Dep $dep = new \Dep()

Modifiers, typed constants, interfaces, inherited constants and built-in classes

readonly, final and abstract and the type of a typed constant are dropped, a class that extends another loses its interfaces, inherited constants are declared again (a fatal error for a final one), and built-in classes the code uses are copied in (php -l rejects the stub).

Before

<?php
interface K { const string KEY = "k"; }
abstract class Base implements K {      // class Base implements \K
    final public const int MAX = 3;     // public const MAX = 3;
}
readonly class A extends Base implements K { // class A extends \Base
    const string NAME = "a";            // public const NAME = 'a'; public const KEY = 'k'; public const MAX = 3;
}
final class B {                         // class B
    public readonly int $ro;            // public int $ro;
}
class E extends BadMethodCallException {} // also class BadMethodCallException, class LogicException, ...
class MyAO extends ArrayObject {}        // public const STD_PROP_LIST = 1; public const ARRAY_AS_PROPS = 2;

After

abstract class Base implements K {      // abstract class Base implements \K
    final public const int MAX = 3;     // final public const int MAX = 3;
readonly class A extends Base implements K { // readonly class A extends \Base implements \K
    const string NAME = "a";            // public const string NAME = 'a';
final class B {                         // final class B
    public readonly int $ro;            // public readonly int $ro;
class E extends BadMethodCallException {} // class E extends \BadMethodCallException
class MyAO extends ArrayObject {}        // class MyAO extends \ArrayObject {}

The arguments of a new default are not kept: = new Arg(3) is written as = new \Arg().

Before After
before after

Fixes #13596

@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 757 72.7 $\color{gray}{\textsf{-0.6\%}}$ 25 912 53 476 682
✅ symfony 3 600 200.8 $\color{gray}{\textsf{-2.1\%}}$ 50 638 98 502 1 528
✅ doctrine-orm 381 15.7 $\color{gray}{\textsf{+0.4\%}}$ 3 481 6 143 0
✅ psl 617 20.2 $\color{gray}{\textsf{+0.1\%}}$ 1 375 5 615 1
✅ phpunit 455 20.0 1 744 3 459 18
✅ php-parser 226 13.5 $\color{gray}{\textsf{-0.8\%}}$ 17 132 21 025 0
✅ tempest 895 37.0 $\color{gray}{\textsf{-0.5\%}}$ 5 048 10 525 252
✅ amphp-amp 68 1.5 $\color{gray}{\textsf{-6.4\%}}$ 29 49 0
✅ webmozarts-assert 272 3.4 $\color{gray}{\textsf{+0.6\%}}$ 577 2 720 0
✅ guzzle-promises 44 1.2 155 434 2
✅ monolog 135 4.2 $\color{gray}{\textsf{-0.7\%}}$ 913 2 479 10
✅ drupal 4 841 235.0 $\color{gray}{\textsf{+0.5\%}}$ 97 589 169 294 583
Total 13 291 625.2 $\color{gray}{\textsf{-0.6\%}}$ 204 593 373 721 3 076
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 7997be1 · base cd22a51 (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.

🤖 The changes are in the owning layer (StubsGenerator / ClassLikeStubGenerator, plus the one storage field a typed constant needs), and the generated output looks right. I ran --generate-stubs with the PR branch on a small project with enums (backed, with self::CONST and 1 << 1 case values), a readonly promoted property, final/abstract, A&B and (A&B)|null, static/never/true/callable, a new Dep() default, a typed interface constant and a class extending RuntimeException. The result:

  • enums are emitted as enum Suit : string implements \App\L { case Hearts = 'h'; ... } without the synthetic name/value properties and UnitEnum/BackedEnum;
  • implements is kept for classes that also have a parent;
  • inherited interface constants are no longer re-declared, typed constants keep their type;
  • the built-in classes that master dumps into the stub (hundreds of lines for Closure, Countable, mysqli_*, Normalizer, ...) are gone.

No blocking findings.

Recommendations (non-blocking)

  • The PR bundles about eight independent generator fixes. Nothing here is wrong, but splitting by theme (types, enums, modifiers, built-in exclusion) would make a later bisect or revert cheaper.

@shu-chen-dot-ca

Copy link
Copy Markdown
Contributor Author

Thanks for testing it! I kept it as one PR because the parts depend on each other: once final constants are written, the inherited ones have to be left out (a child redeclaring a final constant is a fatal error), and once built-in classes are left out, their constants can't be copied into children (extends \ArrayObject got STD_PROP_LIST and failed php -l). It's one commit, so a revert is one step, and each fix has its own test in StubsGeneratorTest, which should help with a bisect.

@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 type, modifier and enum output looks right. I ran --generate-stubs on a project covering every construct in the title and php -l (PHP 8.5) accepts the result, except for two cases where the new code writes a stub that is a compile error. On master both cases still lint: the first gives an enum without cases, the second a string placeholder.

<?php
namespace App;
final class Dep {}
enum S: string { case A = self::P . "c"; const P = "x"; } // case A;  -> Fatal: Case A of backed enum App\S must have a value
define('App\OBJ', new Dep());
class UsesGlobal { const G = OBJ; }                    // public const G = new \App\Dep();  -> Fatal: New expressions are not supported in this context

(The first input is valid PHP. Psalm reports InvalidEnumCaseValue on it because it doesn't resolve the constant declared after the case, which is a separate bug. An enum case that refers to a constant of an unscanned file gets the same null value.)

Please also add a test that lints the generated stub, or parses it back, over a sample that covers these constructs. Substring assertions can't catch output that is invalid.

$case_name,
$case_value instanceof TLiteralInt
? new VirtualInt($case_value->value)
: ($case_value instanceof TLiteralString ? new VirtualString($case_value->value) : null),

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.

getValue() returns null when the case value can't be resolved, and in a backed enum ($storage->enum_type !== null) case X; is a compile error. This needs a valid fallback for backed enums. A placeholder value has to stay unique, since duplicate case values are also a compile error. Skipping the case is another option.


// a `new` default: its arguments are not kept
if ($atomic_type instanceof TNamedObject) {
return new VirtualNew(new VirtualFullyQualified($atomic_type->value));

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.

getExpressionFromType() is also used for class constants, global constants, property defaults and ArgumentsAnalyzer, not only for parameter defaults. A class constant whose type is a TNamedObject (e.g. const G = SOME_GLOBAL_OBJECT;) now prints public const G = new \App\Dep();, which PHP rejects. Please emit new only where PHP allows it (parameter defaults, global constants), e.g. from getFunctionParamNodes(), and keep the previous fallback elsewhere.

@shu-chen-dot-ca

Copy link
Copy Markdown
Contributor Author

@orklah thanks, both reproduced, fixed in 41c5080:

  • A backed enum case whose value can't be resolved now gets a unique placeholder instead of case A;: 'Psalm could not infer this type: A' for string enums (with _ appended while it collides with another case's value), and the first int from 0 up that no other case uses for int enums, so a case at PHP_INT_MAX can't overflow it. I kept the case rather than skipping it, so code that refers to it still finds it in the stub.
  • getExpressionFromType() takes $allow_new, passed only from getFunctionParamNodes() and the two global-constant sites. Class constants, property defaults and ArgumentsAnalyzer get the old placeholder back. A typed class constant that falls back to the placeholder (const Dep TYPED = OBJ;) is written without its type, since the string wouldn't match it.
  • testTheGeneratedStubIsValidPhp runs php -l on the stub of a sample covering the constructs from the title plus your two cases, int enums with unresolved cases (one next to PHP_INT_MAX), a typed object constant and children of ArrayObject/DateTimeImmutable. It's skipped below PHP 8.3, which typed constants need. testABackedEnumCaseWithoutAResolvedValueGetsAUniquePlaceholder and testAClassConstantIsNeverANewExpression pin the output. All three fail on the previous commit.

@shu-chen-dot-ca
shu-chen-dot-ca force-pushed the fix-13596-generate-stubs branch from 021e803 to 5b3d414 Compare November 20, 2026 01:02

@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, both cases from my last review are fixed and the lint test covers them.

Two things before merging:

  1. Please rebase on master. #14413 (515bfbe) added the same ClassConstantStorage::signature_type field, set the same way in ClassLikeNodeScanner::visitClassConstDeclaration() and copied in Populator::inheritConstantsFromTrait(). The PR's changes to those three files can be dropped; the generator can use master's field as is.

  2. A native final method of a class that is only @final in its docblock loses its final:

/** @final */
class DocFinal {
    final public function f(): void {} // stub: public function f(): void
}

The class is written without final (correctly, since final_from_docblock), but the method's final is skipped because $storage->final is true. The condition in getMethodNodes() should only skip it when the class is written as final, e.g. !($storage->final && !$storage->final_from_docblock). Please add this case to testModifiersAndTypedConstantsAreKept.

…parent, enums and readonly

Keep intersection and DNF types, true, false, never, void, mixed, null,
callable, static and parent in generated signatures. Generate enums with
their backing type and cases, keep new defaults, the readonly, final and
abstract modifiers and the types of typed constants, keep the interfaces of
a class that extends another, and leave out built-in classes and the
constants a class inherits.

Fixes #13596
…nstants

A backed enum case whose value Psalm can't resolve gets a unique placeholder,
and new is only written where PHP allows it: parameter defaults and global
constants.
@shu-chen-dot-ca
shu-chen-dot-ca force-pushed the fix-13596-generate-stubs branch from 5b3d414 to e65253f Compare November 21, 2026 17:03
@shu-chen-dot-ca

Copy link
Copy Markdown
Contributor Author

@orklah thanks, both done:

  1. Rebased on master in e65253f: the PR no longer touches ClassConstantStorage, ClassLikeNodeScanner or Populator, and the generator reads master's signature_type.
  2. Fixed in d60324c. Changing the condition in getMethodNodes() alone wasn't enough: FunctionLikeNodeScanner copied the class's final_from_docblock onto every method, so a method declared final in a @final class also counted as final from the docblock, and the generator then dropped it as well. The scanner now sets the method's final_from_docblock only when the method itself isn't declared final. The generator skips a method's final only when the class is written as final. testModifiersAndTypedConstantsAreKept now has a @final class with one final method and one plain method: only the first is written final, and the class isn't.

The scanner change has one more effect: overriding a method that is declared final in a @final class is a fatal error in PHP, so its MethodSignatureMismatch can no longer be suppressed the way the docblock-only case can (suppressDocblockFinal still passes). testInvalidCode@overrideNativeFinalMethodOfDocblockFinalClass covers it. Both new assertions fail on e65253f.

@orklah orklah added the release:fix The PR will be included in 'Fixes' section of the release notes label Nov 23, 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.

@orklah
orklah merged commit 1be6e36 into vimeo:master Nov 23, 2026
71 of 72 checks passed
@shu-chen-dot-ca
shu-chen-dot-ca deleted the fix-13596-generate-stubs branch November 23, 2026 16:29
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.

--generate-stubs writes wrong signatures for intersections, true/never/static/parent, enums and readonly

3 participants