@@ -61,6 +61,22 @@ final class InlineChecker
6161 */
6262 public static array $ nullPropertyCache = [];
6363
64+ /**
65+ * Cache for whether a class property's type references generic templates:
66+ * [$className][$propName] => bool.
67+ *
68+ * @var array<string, array<string, bool>>
69+ */
70+ private static array $ propertyUsesTemplatesCache = [];
71+
72+ /**
73+ * Cache for whether a class has any methods declaring @self-out or @this-out:
74+ * [$className] => bool.
75+ *
76+ * @var array<string, bool>
77+ */
78+ private static array $ classHasSelfOutCache = [];
79+
6480 /**
6581 * Resets internal type node and function caches. Useful for test isolation.
6682 */
@@ -69,6 +85,8 @@ public static function reset(): void
6985 self ::$ parsedTypeNodeCache = [];
7086 self ::$ resolvedClassContextCache = [];
7187 self ::$ nullPropertyCache = [];
88+ self ::$ propertyUsesTemplatesCache = [];
89+ self ::$ classHasSelfOutCache = [];
7290 }
7391
7492 /**
@@ -236,24 +254,39 @@ public static function checkProperty(mixed $value, mixed $objectOrClass, string
236254 return $ value ;
237255 }
238256
239- $ typeNode = DocblockParser ::parseProperty ($ className , $ propName );
240- if ($ typeNode === null ) {
257+ $ rawTypeNode = DocblockParser ::parseProperty ($ className , $ propName );
258+ if ($ rawTypeNode === null ) {
241259 self ::$ nullPropertyCache [$ className ][$ propName ] = true ;
242260
243261 return $ value ;
244262 }
245263
246- if (! self ::shouldValidateType ($ typeNode )) {
264+ if (! self ::shouldValidateType ($ rawTypeNode )) {
247265 return $ value ;
248266 }
249267
268+ $ propertyUsesTemplates = false ;
269+ $ typeNode = $ rawTypeNode ;
270+
250271 if (\is_object ($ objectOrClass )) {
251- $ typeNode = self ::substitutePropertyGenerics ($ typeNode , $ objectOrClass , $ className );
272+ $ propertyUsesTemplates = self ::propertyUsesTemplates ($ rawTypeNode , $ className , $ propName );
273+ if ($ propertyUsesTemplates ) {
274+ $ typeNode = self ::substitutePropertyGenerics ($ rawTypeNode , $ objectOrClass , $ className );
275+ }
252276 }
253277
254278 try {
255279 $ err = $ registry ->validate ($ value , $ typeNode , 'Property ' . $ className . '::$ ' . $ propName );
256280 if ($ err !== null ) {
281+ if (
282+ $ propertyUsesTemplates &&
283+ \is_object ($ objectOrClass ) &&
284+ self ::classHasSelfOut ($ className ) &&
285+ self ::trySelfOutTransition ($ value , $ objectOrClass , $ propName , $ registry )
286+ ) {
287+ return $ value ;
288+ }
289+
257290 return $ err ;
258291 }
259292 } catch (\Throwable $ e ) {
@@ -263,6 +296,138 @@ public static function checkProperty(mixed $value, mixed $objectOrClass, string
263296 return $ value ;
264297 }
265298
299+ /**
300+ * Checks if a property's declared type references class generic templates with memoization.
301+ */
302+ private static function propertyUsesTemplates (TypeNode $ rawTypeNode , string $ className , string $ propName ): bool
303+ {
304+ if (isset (self ::$ propertyUsesTemplatesCache [$ className ][$ propName ])) {
305+ return self ::$ propertyUsesTemplatesCache [$ className ][$ propName ];
306+ }
307+
308+ $ constructorTarget = $ className . '::__construct ' ;
309+ $ contract = DocblockParser ::parse ($ constructorTarget );
310+ $ allTemplates = [...($ contract ['classTemplates ' ] ?? []), ...($ contract ['templates ' ] ?? [])];
311+
312+ if ($ allTemplates === []) {
313+ return self ::$ propertyUsesTemplatesCache [$ className ][$ propName ] = false ;
314+ }
315+
316+ return self ::$ propertyUsesTemplatesCache [$ className ][$ propName ] = DocblockParser ::typeReferencesTemplate ($ rawTypeNode , $ allTemplates );
317+ }
318+
319+ /**
320+ * Checks if a class declares any methods containing @self-out or @this-out annotations with memoization.
321+ */
322+ private static function classHasSelfOut (string $ className ): bool
323+ {
324+ if (isset (self ::$ classHasSelfOutCache [$ className ])) {
325+ return self ::$ classHasSelfOutCache [$ className ];
326+ }
327+
328+ if (! class_exists ($ className ) && ! trait_exists ($ className ) && ! interface_exists ($ className )) {
329+ return self ::$ classHasSelfOutCache [$ className ] = false ;
330+ }
331+
332+ try {
333+ /** @var class-string<object> $className */
334+ $ ref = new \ReflectionClass ($ className );
335+ foreach ($ ref ->getMethods () as $ method ) {
336+ $ doc = $ method ->getDocComment ();
337+ if ($ doc !== false && (str_contains ($ doc , 'self-out ' ) || str_contains ($ doc , 'this-out ' ))) {
338+ return self ::$ classHasSelfOutCache [$ className ] = true ;
339+ }
340+ }
341+ } catch (\Throwable $ e ) {
342+ // Silently ignore reflection errors
343+ }
344+
345+ return self ::$ classHasSelfOutCache [$ className ] = false ;
346+ }
347+
348+ /**
349+ * Attempts a typestate transition when a property assignment to $this fails against current bindings.
350+ */
351+ private static function trySelfOutTransition (mixed $ value , object $ object , string $ propName , TypeValidatorRegistry $ registry ): bool
352+ {
353+ if (! Config ::isSelfOutEnabled ()) {
354+ return false ;
355+ }
356+
357+ $ trace = debug_backtrace (DEBUG_BACKTRACE_PROVIDE_OBJECT , 7 );
358+ $ callerFrame = null ;
359+ $ callerFunction = null ;
360+ $ contract = null ;
361+
362+ foreach ($ trace as $ frame ) {
363+ if (isset ($ frame ['object ' ], $ frame ['class ' ]) && $ frame ['object ' ] === $ object ) {
364+ if ($ frame ['class ' ] === 'TypePHP\Internal\RuntimeTypeChecker ' || str_starts_with ($ frame ['class ' ], 'TypePHP \\Internal \\' )) {
365+ continue ;
366+ }
367+
368+ $ candidateFunction = $ frame ['class ' ] . ':: ' . $ frame ['function ' ];
369+ $ candidateContract = DocblockParser ::parse ($ candidateFunction );
370+
371+ if (($ candidateContract ['hasSelfOutContract ' ] ?? false ) && $ candidateContract ['selfOut ' ] !== null ) {
372+ $ callerFrame = $ frame ;
373+ $ callerFunction = $ candidateFunction ;
374+ $ contract = $ candidateContract ;
375+
376+ break ;
377+ }
378+ }
379+ }
380+
381+ if ($ callerFrame === null || $ callerFunction === null || $ contract === null ) {
382+ return false ;
383+ }
384+
385+ $ selfOutNode = $ contract ['selfOut ' ];
386+ $ allTemplates = [...($ contract ['classTemplates ' ] ?? []), ...($ contract ['templates ' ] ?? [])];
387+ $ boundTemplates = (\count ($ allTemplates ) > 0 )
388+ ? TemplateManager ::getBoundTemplates ($ callerFunction , $ object , $ allTemplates )
389+ : [];
390+
391+ if (\count ($ boundTemplates ) > 0 || \count ($ allTemplates ) > 0 ) {
392+ $ selfOutNode = TemplateSubstitutor ::substitute ($ selfOutNode , $ boundTemplates , $ allTemplates );
393+ $ selfOutNode = SpecialTypeResolver ::resolve ($ selfOutNode , $ callerFunction , $ object );
394+ }
395+
396+ $ vars = $ callerFrame ['args ' ] ?? [];
397+ if (
398+ $ selfOutNode instanceof ConditionalTypeForParameterNode ||
399+ $ selfOutNode instanceof ConditionalTypeNode
400+ ) {
401+ $ selfOutNode = ConditionalChecker ::resolve ($ selfOutNode , $ vars , $ boundTemplates , $ registry , $ callerFunction );
402+ }
403+
404+ if (! ($ selfOutNode instanceof GenericTypeNode)) {
405+ return false ;
406+ }
407+
408+ $ previousBindings = TemplateManager ::getBoundTemplatesForInstance ($ object );
409+
410+ TemplateManager ::bindInstanceFromNode ($ object , $ selfOutNode , forceBind: true );
411+
412+ $ className = $ object ::class;
413+ $ propTypeNode = DocblockParser ::parseProperty ($ className , $ propName );
414+ if ($ propTypeNode !== null ) {
415+ $ propTypeNode = self ::substitutePropertyGenerics ($ propTypeNode , $ object , $ className );
416+ }
417+
418+ $ testErr = $ propTypeNode !== null
419+ ? $ registry ->validate ($ value , $ propTypeNode , 'Property ' . $ className . '::$ ' . $ propName )
420+ : null ;
421+
422+ if ($ testErr === null ) {
423+ return true ;
424+ }
425+
426+ TemplateManager ::restoreInstanceBindings ($ object , $ previousBindings );
427+
428+ return false ;
429+ }
430+
266431 /**
267432 * Resolves caller class or function context and applies templates & type aliases to the AST.
268433 */
0 commit comments