Skip to content

Function-level @template bound by class-string<T>: typed returns in the analyzer and the compiler #686

Closed

Description

@blacktrs

Problem

The most common generic pattern in Symfony, Laravel and Doctrine code is a function-level template bound by a class name:

/**
 * @template T of object
 * @param class-string<T> $id
 * @return T
 */
public function get(string $id): object

Today neither side uses it:

  • Compiler. A function's own @template T is replaced by its bound, or by mixed (LowerTypes::docTagType). class-string<T> lowers to string. So $c->get(Foo::class) returns cell. Every use after that is boxed and dispatched dynamically.
  • Analyzer / LSP. Hover and completion on $c->get(Foo::class)-> know nothing about Foo.

Proposal

Do it once, on the shared Semantic\SourceType model. It depends on semantic-core P4 step 2c, where lowerTypeHint becomes SourceType → Type.

  1. Analyzer / LSP (no codegen risk).
    • Bind a function's or method's @template T from its arguments: Foo::class → T = Foo, a class-string<Foo> value, or a T-typed argument.
    • Return the substituted @return.
    • @phpstan-* / @psalm-* tags take precedence over the plain tags.
    • Support key-of<> / value-of<>.
    • Diagnostic: a non-class string literal passed to a class-string parameter.
  2. Compiler. The same binding at a call site with a statically known class gives a return of obj<Foo> instead of cell. Vendor docblocks are not enforced by php, and the compiler trusts docblocks. So the call result gets a cheap instanceof check that throws TypeError on a mismatch, never a blind cast.

Out of scope

  • int<..> and positive-int ranges: no value-range analysis exists to use them.
  • non-empty-* beyond what is lowered today.
  • Conditional types (T is null ? A : B).

Done when

  • Hover and completion resolve $c->get(Foo::class)-> to Foo members. Tests are in tests/semantic.
  • AOT cases cover:
    • a container get(Foo::class) returning obj<Foo>;
    • a lying docblock that throws TypeError instead of miscompiling.
  • Request instructions are measured before and after on examples/symfony-demo and examples/laravel-app.

Related: #453, #456.

Activity

  1. added
    enhancement
    on Nov 14, 2026
  2. blacktrs commented on Nov 15, 2026

    @blacktrs
    ContributorAuthor

    Done in #696 (8c817ed): analyzer/LSP binding + compiler obj with instanceof/TypeError guard, interface/abstract/parent inheritance, conditional returns, string|class-string. Symfony container follow-up: #694.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions