Repository navigation
⭐️ Support star projection * syntax in generic type arguments - #13139
Conversation
✅ Performance: unchanged · Types: decreased
How to read this table
✅ laravel: issues +100 −316Memory 1 768 → 1 781 MB (+0.7 %) · Wall 111.8 → 111.4 s (−0.3 %) Weighted 53 513 → 53 049 (−464, −0.87 %): L1 −80 · L2 −78 · L3 +26 · L4 −100 · L5 +6 · L6 +9 · always +1
Added (100)
Removed (316)
head d7438c8 · base 1552477 (merge-base) · workflow run |
* in generic type arguments* in generic type arguments
8ac7bee to
a46594c
Compare
* in generic type arguments* in generic type arguments
a46594c to
eb2b1ef
Compare
…#11931 PHPStan docblocks (Laravel's Relation<TRelated, *, *>, Builder<*>) made Psalm drop the whole tag and collapse templates to never. `*` parses as a TStarProjection type argument of a generic object. Any argument fits it; a `*` argument fits only another `*`, an argument the container leaves out (`Pair $p`), or a covariant argument holding the template's bound, and binds a function template only as that bound. Reading a template bound to `*` gives its bound, as for a use of the class without the argument. `@extends`, `@implements`, `@use` and class-string-map values reject it; the array-like builtins read it as mixed and `class-string<*>` is any class-string.
eb2b1ef to
e3a5443
Compare
e3a5443 to
4ccb4b1
Compare
* in generic type arguments* syntax in generic type arguments
|
Split as requested: this PR now covers parsing |
…tar-projection # Conflicts: # tests/AnnotationTest.php
|
Back to draft until the design of how class members read a |
A `*` accepts any argument, so a bare `instanceof` check passed the containment test without coercion and replaced the star with the template's bound: `Box<*>` became `Box<object>`, `Pair<int, *>` narrowed to `Child` became `Child<object>`.
Its shape is not settled yet, so it stays out of the plugin API.
* syntax in generic type arguments* syntax in generic type arguments
# Conflicts: # src/Psalm/Internal/Analyzer/Statements/Expression/Call/ClassTemplateParamCollector.php # src/Psalm/Internal/Type/AssertionReconciler.php # tests/AnnotationTest.php # tests/TypeParseTest.php
…tar-projection # Conflicts: # src/Psalm/Internal/Analyzer/Statements/Expression/Call/ClassTemplateParamCollector.php # src/Psalm/Internal/Analyzer/Statements/Expression/Call/Method/AtomicMethodCallAnalyzer.php # src/Psalm/Internal/Analyzer/Statements/Expression/YieldFromAnalyzer.php
- `TGenericObject::replaceTemplateTypesWithArgTypes()` no longer resolves a new `*` itself (it is impure); the held type is the receiver's bound, which the expander and the comparator resolve again. - Split `ClassTemplateParamCollector::collect()` into three helpers (ComplexMethod), declare the capabilities of `markStarBindings()` and the test provider, and update the baseline snippet of the changed `getMappedGenericTypeParams()` call.
…ot written vimeo#11931 - Property writes (`$box->prop = $date`, `$box->list[] = $date`) were typed with the star read, so a `Box<DateTime>` was accepted for a `Box<T>` property of a `Box<*>`; only property fetches mark the star now. - A first-class callable (`$box->merge(...)`) takes its arguments as the bound, and a callable's parameter types (`Closure(Box<T>): void`, at any depth) never produce a `*`.
…ery property read vimeo#11931 - `$box->same(...)` marks star bindings like a call, so its closure returns a `Box<*>`; the closure's parameter types are still the bound (the mark flag is carried to the bounds copy in `getFirstClassCallableType()`). - `localizePropertyType()` takes `$star_reads` without a default: `get_object_vars()`, `properties-of` and `@psalm-yield` read, class and assignment checks do not. - Tests: first-class callable return, get_object_vars/properties-of/`@method`/nested property reads, a callable param depth case, and the `@param-out` known gap.
…ad `static<T>` of a covariant class as the bound vimeo#11931 - A template of a class two levels up (`ParentBox::T` is `Middle::U`, which is `Child::V`) is bound to the `*` of a `Child<*>` receiver: method and property reads of `Box<T>` give `Box<*>` again. - `static<T>` takes the variance of the class of the call, so it reads the bound like `Reader<T>` of a covariant template does.
…meo#11931 - Link Kotlin's star projections instead of attributing `*` to PHPStan, and give Java's unbounded wildcard as the other common name.
…TypeParams() vimeo#11931 - Public `TGenericObject::setTypeParams()` no longer keeps the `*` or left-out marker of a slot whose type it changes, so a plugin that rebuilds the pivot argument of a `Relation<User, *>` gets that type back instead of a `*`. - An `@internal` `setHeldTypes()` keeps the markers for the internal callers that only refine what a `*` holds (`StarProjection::resolve()`, the expander). - The plugin test declares `related(): object` so it fails when the provider returns nothing.
…ers the outermost invariant argument vimeo#11931 - A template read from a `Box<*>` into a new `*` slot starts as the `mixed` placeholder, which `resolve()` and the expander turn into the bound of the class the type is read into (`Free<T>` with an unbounded `T` holds `mixed`, not the receiver's `object`); a read property type is expanded for it. Method, `@method`, property and combined reads now print the same `Free<*>` and read the same. - `@return Box<Box<T>>` read from a `Box<*>` is a `Box<*>`: the outermost invariant argument that mentions a star-bound template becomes the `*`. - The star bindings move from a flag on the shared `TemplateBound` objects to a `star_bindings` map on `TemplateResult`, merged by `merge()`.
… of the template mapping vimeo#11931 - The type of `@psalm-assert*` is not expanded, so a `*` in it held `mixed`: `getUntemplatedCopy()` and `getMappedGenericTypeParams()` resolve it, and `[...$value]` of a value narrowed to `Collection<*, *>` by `-if-true` or `-if-false` reads the bounds instead of failing on a `mixed` key.
…keep the self-analysis at the base's issues vimeo#11931 - `Relation<*>` with `@mixin Builder<T>` reads `Builder<*>` and `Box<*>` through the mixin instead of the bound (the mixin patch). - Tests: a mixin read, `offsetGet()`, and the known gaps (wrapped `@implements` argument iterated, callable parameters, composed `@extends` argument); the bare-parameter comments no longer attribute the bare-class change to the write-restriction PR. - `getMappedGenericTypeParams()` and `getObjectMatchingBase()` are `@psalm-impure` now that the mapping resolves its input; the `getUntemplatedCopy()` resolve is dropped, the comparator and the mapping cover its callers.
…y if every member leaves it out vimeo#11931 - `Box<object>|Box` (an explicit and a bare class, both `Box<object>` as keys) took the left-out marker of the bare member, so it accepted a `Box<*>` that `Box<object>` rejects. The combiner counts the members of a key and the ones leaving an offset out, and keeps `Omitted` only when they are equal. - A `*` still outweighs the other members at its offset. The unit test covers `*` with a left-out member, two left-out members and a left-out with an explicit member.
…they are applied, and drop the defensive star resolves vimeo#11931 - The types of `@psalm-assert-if-true` and `-if-false` were not expanded, unlike those of `@psalm-assert`, so a `*` in them held `mixed`. `AssertionFinder` now expands a generic object rule type where it applies the rule, next to the class constants it expanded already. - With that, `StarProjection::resolve()` is no longer called by `GenericTypeComparator`, `getMappedGenericTypeParams()`, `ClassTemplateParamCollector` and `localizePropertyType()`: every `*` they see comes from an expanded type. `getMappedGenericTypeParams()` and `getObjectMatchingBase()` get their capability annotations back. `resolve()` stays for the narrowing, which builds a new `*`. A `*` nested in a non-generic container of an assertion (`list<Reader<*>>`) is still not expanded here. - Tests: the narrowed types are pinned as `Reader<*>`, with invariant `-if-true`/`-if-false` variants that fail if the `*` is lost, and the `Box<object>|Box` case of the previous commit (a union param of an explicit and a bare class rejects a `Box<*>` like `Box<object>`).
…with setTypeParams() vimeo#11931 - `setTypeParams()` dropped the marker of any slot whose Union was another object; it now drops it only when the new type is not `equals()` to the old one, so a plugin that rebuilds equal arguments keeps a `*`. - The plugin test rebuilds every argument of a `Relation<Model, *>` as an equal Union; it fails on the previous commit.
…d the self-referencing bound vimeo#11931 - Docblocks of `withoutStarBindings()` and its use in `CallableTrait` say what the bound in a callable parameter is: the known write gap, not a correct read. - Known-gap test: `($b->setter())(new DateTime())` on a `Box<*>` is accepted until the write-restriction PR. - `starProjectionStaticOfACovariantArgumentIsTheBound` calls a `takeFoo(Reader<Foo>)` with the `same()` and `staticOf()` results and asserts both read `Reader<Foo>` (`staticOf()` is `Reader<Foo>&static`). It fails without the `static<T>` rule (the type prints `Reader<*>&static`); a false ArgumentTypeCoercion could not be reproduced for a covariant parameter. - `@template T of Node<*>`: reading `child()` twice gives `Node<*>` each time, which covers the recursion guard of `StarProjection::boundStars()`.
… the nested write gap vimeo#11931 - Removes the rule that took the variance of the class of the call for `static<T>`. In valid code the only difference is how the type prints (`Reader<object>&static` against `Reader<*>&static`): method and function calls, property and list assignments, template inference and `instanceof` give the same issues with and without it, which I compared on two scratch snippets. - Known-gap test: `$b->nested()->set($box_of_std_class)` on a `Box<*>` with `@return Box<Box<T>>` is accepted until the write-restriction PR.
…its own class vimeo#11931 - `@psalm-assert Box&Countable` on a `Box<*>` gave `Box<*>`: the early return for a `*` narrowed to its own class returned the existing type and dropped the extra types of the asserted one. It adds them to the existing ones now, so the value is a `Box<*>&Countable`.
…n too, and pin the grandchild narrowing vimeo#11931 - `@psalm-assert-if-true list<Reader<*>> $x` left the `*` of the list item unexpanded, so the value did not fit a `list<Reader<Countable>>` parameter although `Reader` is covariant. `expandTypesOfRules()` expands array, keyed array and iterable rule types as well as generic objects, only when it yields a single type. - Tests: that case, its invariant variant (still a coercion, as it should be), and a guard that a `Box<*>` narrowed by `instanceof` to a grandchild is a `Child<*>` reading the child's bound (the flattened `template_extended_params` already covers two `@extends` levels, so `inferTemplateParamsFromParent()` needed no change).
…alue-of or properties-of vimeo#11931 - `value-of<*>`, `key-of<*>`, `int<*, 5>` and the others were rejected, but with messages about `mixed` ("Untemplated value-of param mixed", "Invalid type mixed as int min boundary"). The parser now throws `The * type argument is only for the type arguments of a class, not of <name>` for them, and so is an InvalidDocblock naming the `*`. - The invalid-star provider covers the other positions found (`int<5, *>`, `int-mask<*>`, a callable parameter, a closure return, a parenthesised and an intersected argument), which were already rejected with `Invalid type '*'`.
…nd the use statements vimeo#11931 - `\App\Models\Pair<int, *>`, an imported `Pair<int, *>` and an aliased `Couple<int, *>` all give `\App\Models\Pair<int, *>`, so `TypeTokenizer` leaves the `*` alone and resolves the class name next to it. This passes on the previous commit too.
…meo#11931 - Replaces the paragraph listing the rules by one example whose lines end in their result: a `*` fits a concrete argument, another `*`, a left-out argument and a covariant one, but not an invariant `Box<object>` (ArgumentTypeCoercion); `Dependent<int, *>` reads `list<int>`; `class-string<*>` and `list<*>` read `class-string` and `list<mixed>`; `@extends Box<*>` is an InvalidDocblock. I ran the snippet as written and each line gives the issue or type it says.
…les() vimeo#11931 - Self-analysis reported a possibly undefined offset `0` in the previous commit's `expandTypesOfRules()`; the first expanded type is read with `??` and checked, with the same result.
…-assert does vimeo#11931 - `expandTypesOfRules()` expanded only class constants, generic objects, arrays and iterables, so a `*` inside `class-string<Reader<*>>` or `Closure(Reader<*>): void` stayed unexpanded and held `mixed`: `new $x` gave a false ArgumentTypeCoercion, and a template read from the closure parameter gave `mixed`. - It now expands the atomic of every rule the way CallAnalyzer::applyAssertionsToContext() does for `@psalm-assert`. A union it expands to becomes one IsType per member, as there. - Tests: `class-string` with `-if-true` and `-if-false`, and a closure parameter. Each fails on the previous commit.
…x drops its extends vimeo#11931 - A type built by a plugin (`Type::parseString()`) is not expanded: probes of function and method return type providers show `Foo::BAR`, `key-of<Foo::ARR>`, `Box<self>` and `static` coming out as written. `plugins_type_system.md` now says to pass such a type through `TypeExpander::expandUnion()`, which also gives a `*` the bound of its template (verified: `readOf()` of the expanded `Reader<*>` reads `Countable`). - The star projection example reports `MissingTemplateParam` on `StarBox` as well, as the rejected `@extends Box<*>` is dropped. Re-ran the example as written.
…ncestors, callables, `@method` tags and static calls vimeo#11931 - An ancestor's argument that wraps a template the receiver bound to a `*` (`@implements Getter<Box<T>>`, `@implements IteratorAggregate<int, Box<T>>`) reads as `Box<*>`: `TemplateResult::$star_bindings` records the starred type and only the read side (`getLowerBoundsOfReads()`) uses it, so parameters and callable parameters keep `Box<bound>`. - `Closure::fromCallable()`, callable arrays, first-class callables, `@method` tags (also on interfaces) and static calls through the instance mark the star bindings like a method call. - `Closure::fromCallable([$any, 'set'])` still takes the bound in its parameter: pinned as a known gap.
Psalm rejects PHPStan's star projection
Foo<*>withInvalidDocblockand drops the whole annotation, so templates bound through it resolve tonever.Before
After
Writes through a
*are not restricted yet:$box->set(new stdClass)on aBox<*>is accepted, as it is today with the docblock dropped. A follow-up PR makes themnever, as PHPStan does. Plugins reading thetype_paramsof aBox<*>see the template's bound.Fixes #11931
Fixes #11385