phpdoc-parser icon indicating copy to clipboard operation
phpdoc-parser copied to clipboard

(RFC) Implement template default syntax

Open rvanvelzen opened this issue 3 years ago • 5 comments

Proof-of-concept implementation for template default syntax (for phpstan/phpstan#4801)

rvanvelzen avatar Sep 06 '22 12:09 rvanvelzen

/cc @orklah Does Psalm already have this / would you be interested too?

ondrejmirtes avatar Sep 06 '22 12:09 ondrejmirtes

Psalm doesn't have this but it could be interesting (especially because Psalm sometimes struggle to assign values to classes with templates that were never properly created)

I doubt I'll be in position to implement this myself anytime soon though

orklah avatar Sep 06 '22 21:09 orklah

Alright, I'm fine with going ahead with this. But what the syntax should be? The issue proposes a separate @template-default tag. What's the precedent from other languages that have this feature?

How would the syntax proposed here for @template work when the bound is involved?

ondrejmirtes avatar Sep 07 '22 07:09 ondrejmirtes

I've taken the syntax from TypeScript. At least C++ also uses this syntax, but I haven't looked at other languages.

Because the default value is tightly coupled to the type parameter (just like the bound is), I don't think it's a good idea to have a separate tag for it.

rvanvelzen avatar Sep 07 '22 08:09 rvanvelzen

Nice, it makes sense to me. Could you also please submit a proof of concept to phpstan-src to make sure these are not released with a big time gap between them? :) Thank you.

What we need to think about is modifying the rules here https://github.com/phpstan/phpstan-src/tree/1.8.x/src/Rules/Generics for this new feature:

  • We need to allow to omit the optional template type around here https://github.com/phpstan/phpstan-src/blob/fb08fb530f60d3510f2864b9935d2f75b29d7840/src/Rules/Generics/GenericObjectTypeCheck.php#L60-L78
  • We need to check that the default type is a subtype of the bound in this class https://github.com/phpstan/phpstan-src/blob/1.8.x/src/Rules/Generics/TemplateTypeCheck.php
  • We need to check that an optional template type is not followed by a non-optional one, also probably in TemplateTypeCheck

ondrejmirtes avatar Sep 08 '22 13:09 ondrejmirtes

Thank you!

ondrejmirtes avatar Oct 14 '22 13:10 ondrejmirtes

Nice to see this merged. 🎉 🚀

alexander-schranz avatar Oct 14 '22 13:10 alexander-schranz