Skip to content

fix(templates): localize the return type of a closure in a used trait - #12810

Merged
orklah merged 5 commits into
vimeo:masterfrom
jirkace:fix/7495-trait-closure-template-types
Nov 21, 2026
Merged

orklah merged 5 commits into
vimeo:masterfrom
jirkace:fix/7495-trait-closure-template-types

Conversation

@jirkace

@jirkace jirkace commented Oct 31, 2026

Copy link
Copy Markdown
Contributor

Psalm reports InvalidReturnType and InvalidReturnStatement for a closure inside a trait method that declares @return T, when the using class binds T with @use.

Before

<?php
interface a {}
class b implements a {}

/** @template T as a */
trait c {
    /** @return T */
    abstract public function get(): a;

    public function getCb(): callable {
        return
            /** @return T */
            function (): a { // InvalidReturnType
                return $this->get(); // InvalidReturnStatement
            };
    }
}

class d {
    /** @use c<b> */
    use c;

    public function get(): b {
        return new b;
    }
}

After

            function (): a { // no issue
                return $this->get(); // no issue

Fixes #7495

…imeo#7495

A closure's `@return T` inside a trait method was compared as the raw template
of the trait, while the method's own return type is localized to what the using
class gives it (`@use c<b>`), so returning a `b` was reported as an invalid
return type and statement. The closure's declared return type is localized the
same way, in both the return type verification and the return statements.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@jirkace

jirkace commented Oct 31, 2026

Copy link
Copy Markdown
Contributor Author

Behaviour change

  • A closure with a @return docblock naming a template of the trait (or parent class) that declares the enclosing method is now checked against what the using class binds that template to (@use c<b> → b), both for the declared return type and for each return. The two false positives above disappear.
  • Unchanged: a closure that returns something that is not the bound type is still an InvalidReturnStatement; closures in functions, in classes without template bindings, and the return types of methods themselves (the method path now goes through the same helper, ClassAnalyzer::localizeReturnType()).
  • psalm-baseline.xml: one RiskyTruthyFalsyComparison entry of ClassAnalyzer.php is removed, as the code it covered moved into the helper with a strict comparison.
  • No existing test expectation was changed. Infection ran only against the 3 new cases (22/22 mutants killed); the full suite is left to CI.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

✅ Performance: unchanged · Types: unchanged

Project Memory (MB) Wall (s) Issues Weighted (types) Taint
✅ laravel 1 765 68.0 $\color{gray}{\textsf{-0.6\%}}$ 25 918 53 210 578
✅ symfony 3 622 199.4 $\color{gray}{\textsf{+0.9\%}}$ 50 660 98 733 1 443
✅ doctrine-orm 393 16.1 $\color{gray}{\textsf{+2.0\%}}$ 3 479 6 160 0
✅ psl 632 19.2 $\color{gray}{\textsf{-2.5\%}}$ 1 305 5 461 1
✅ phpunit 471 14.7 $\color{gray}{\textsf{-0.5\%}}$ 1 742 3 452 17
✅ php-parser 236 9.8 $\color{gray}{\textsf{-0.5\%}}$ 17 133 21 035 0
✅ tempest 899 26.8 $\color{gray}{\textsf{+0.3\%}}$ 5 021 10 514 221
✅ amphp-amp 61 2.0 $\color{gray}{\textsf{-0.5\%}}$ 29 49 0
✅ webmozarts-assert 285 4.8 $\color{gray}{\textsf{-0.8\%}}$ 577 2 722 0
✅ guzzle-promises 55 2.0 $\color{gray}{\textsf{+0.5\%}}$ 158 435 2
✅ monolog 153 5.9 $\color{gray}{\textsf{-0.5\%}}$ 903 2 403 10
✅ drupal 4 821 221.1 $\color{gray}{\textsf{-0.2\%}}$ 97 526 169 331 508
Total 13 395 589.9 $\color{gray}{\textsf{+0.1\%}}$ 204 451 373 505 2 780
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 c7c9195 · base 67cfa84 (merge-base) · workflow run

# Conflicts:
#	tests/Template/TraitTemplateTest.php
@jirkace

jirkace commented Nov 14, 2026

Copy link
Copy Markdown
Contributor Author

Checked the report's findings on the branch (merged with current master, errorLevel 1).

Finding 1 not reproduced: a closure in a trait with @param T $x (and with @return T) where T is the class-level template of the trait and the class has @use c<b> gives no issue on master or on this branch, so the parameter side needs no localize step for what I probed (function (a $x): a and function (a $x): void { echo get_class($x); }); the closure case of #9747 (a template of the trait method nested through callable(T)) is a different path, covered by #13220. The case of this PR, closureReturnTypeNamesTraitTemplate, fails on current master and passes here; the other two cases pass on master (guards).
Not changed: finding 2 (the localisation is computed at two call sites).

Ran: probes on master and on the branch, the PR's cases on master. No code change pushed.

@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 change fixes the reported false positives for a closure in a trait and keeps genuinely wrong returns reported; I found no blocking issue.

Verified

  • Current master reports InvalidReturnType and InvalidReturnStatement for the closure of #7495 (@return T in a trait with @use c<b>); the branch reports nothing.
  • A closure that returns something that is not b (@use W<b2>, closure returns an anonymous a2) is still reported, now against b2 instead of T.
  • The same closure in a class with @extends P<b2> already passes on master, so the change is only needed for traits (the methods of a trait are analysed per using class, so the closure's T has the trait as defining class while the return statement is typed by the using class).

Recommendations (non-blocking)

  • The description says "(or parent class)", but closureReturnTypeNamesInheritedTemplate passes on master; it is a guard, not a regression test for this change. Worth saying so, so that nobody reads it as covering a parent-class bug.
  • localizeClosureReturnType() is called once in FunctionLikeAnalyzer and again for each return in ReturnAnalyzer, and each call runs ClassTemplateParamCollector::collect() + TemplateStandinTypeReplacer::replace(). It is gated on template_extended_params, but computing the localized type once per closure analysis would avoid repeating it for every return.
  • Method templates in a closure's @return are not covered by the new test (only class/trait templates). If that path is intended to work, a case would pin it down.

@jirkace

jirkace commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

From the fresh triage report (head 0e2bd9b), probed on the branch and on current master (errorLevel 1):

  • Finding 1 (a closure @param T $x in a trait method keeps T:c as a and still disagrees with the bound b): not reproduced. A trait @template T with /** @param T $x */ $c = function ($x): void {...}; $c($v); used as @use Tr<b> reports nothing on the branch and on master, so the closure parameter case is either not broken or not reachable through this shape. InvalidArgument for generic closure params in traits #9747 / fix(templates): keep templates of the calling function-like in scope in traits #13220 is where that sibling is handled; I did not merge the two localisations into one place here.
  • Findings 2-5 (per-return recomputation, test coverage of arrow/nested/static closures, the template_extended_params early exit on the using class, a dedicated class instead of ClassAnalyzer): not changed in this round.

Not run: the full suite (CI). Nothing pushed for this comment.

@jirkace

jirkace commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Question for the maintainers (@orklah @alies-dev), from the triage report generated 2026-11-19 05:16 UTC:

Finding 1 of the report asks to localise the parameters and the return of a closure in one place (the storage of the closure when it is analysed for a class) instead of a second hook per consumer; here only the return type is localised (localizeClosureReturnType()), and the closure-parameter sibling is #13220 / #9747.

  • Option A (what the PR does): keep the return-only hook here, fix(templates): keep templates of the calling function-like in scope in traits #13220 handles parameters. I probed a trait @template T with a closure @param T $x used as @use Tr<b> on master and on this branch: no issue on either, so the parameter case is not broken by this PR.
  • Option B: one shared localisation for parameters and return, replacing both hooks; a larger change that touches both PRs.

I would keep A and merge the two PRs separately; which do you want? Nothing else of this PR waits on me.

@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.

🤖 Nothing was pushed since the last review (head 0e2bd9bc81), but a re-check of the branch merged into current master found a regression I missed the first time, so I can't call this mergeable yet.

Blocking

  • ReturnAnalyzer.php:348 / FunctionLikeAnalyzer.php:951: the declared return type of the closure is now localised (T becomes b), but the type of what the closure returns is not. A closure whose @return T returns a value that is itself typed T (a captured @param T variable, or @var T) is reported on this branch and is silent on master:

    interface a {}
    final class b implements a {}
    
    /** @template T of a */
    trait e {
        /** @param T $p */
        public function m($p): Closure {
            return /** @return T */ function () use ($p) { return $p; };
        }
    }
    
    final class f {
        /** @use e<b> */
        use e;
    }
    // master: no issue
    // this PR: MoreSpecificReturnType: The declared return type 'b' for ...:closure is more specific than the inferred return type 'T:e as a'
    //          LessSpecificReturnStatement: The type 'T:e as a' is more general than the declared return type 'b'

    The same happens with /** @var T $t */ $t = ...; return $t; inside the closure. So the PR trades the original false positive (return $this->get() typed b, declared T) for the mirror one in a shape that is just as common in a generic trait (a closure that hands back a templated value it captured). Localising the inferred type with the same helper is not enough on its own (I tried it on ReturnAnalyzer: the statement type becomes b, but LessSpecificReturnStatement still fires, "b is more general than b"), so one option is to report only when the returned type fits neither the localised nor the original declared type. Whatever you pick, please add the snippet above to TraitTemplateTest as a valid case next to closureReturnTypeNamesTraitTemplate.

Dropped / optional now

  • Everything in the first review stays a non-blocking suggestion (the parent-class guard test wording, per-return recomputation, method templates in the closure @return).
  • On your question about one shared localisation for parameters and return: not required for this PR. Keep it return-only and merge #13220 separately, as you proposed.

jirkace and others added 2 commits November 20, 2026 03:06
…in either terms, the trait's or the using class's

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@alies-dev alies-dev added the release:fix The PR will be included in 'Fixes' section of the release notes label Nov 20, 2026
@orklah
orklah merged commit 9bcd6ea into vimeo:master Nov 21, 2026
70 of 71 checks passed
@orklah

orklah commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator

Thanks @jirkace!

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.

Template types aren't resolved in closures inside traits

3 participants