On 16/10/2023 15:08, Olle Härstedt wrote:
Hello internals,

Was there a previous discussion about the pros/cons of adding only the
syntax needed for generics, but not the functionality? So static
analyzers could use it, instead of docblocks. I looked at externals.io
but couldn't find anything specific.


Hi Olle,

Since I haven't seen it expressed quite this way in the previous discussion, I'd like to highlight what I think is a major downside to this approach, at least as commonly proposed:

Using the same syntax for type information that is guaranteed to be true (existing run-time checks) and type information that is "advisory only" (new checks for optional static analysis) means users can no longer have confidence in that type information.

This is one of the interesting things about the compromise over scalar types - if you see a declaration "function foo(int $bar) { ... }", you *know* that $bar will be an int at the start of every invocation of that function, regardless of which mode the calling code uses. I think adding exceptions to that certainty would be a bad direction for the language.

On the other hand, I can see a "third way": if the problem with current static analysis conventions is that they have to be parsed out of a string-based docblock, we can provide *dedicated* syntax, without unifying it with the standard type syntax. For instance, some of the earlier discussions around introducing attributes suggested reflection expose the AST of the attributes arguments, rather than the resolved expressions, allowing them to act a bit like Rust's "hygienic macros". If that was added as an optional mode, you might be able to do something like this:

#[RawAttribute]
class GenericType {
    public function __construct(AST\Node $typeInfo) { ... }
}

function foo(#[GenericType(int|float)] array $foo) {
    // array is the type guaranteed by the language
    // static analysis libraries can get the GenericType attribute from reflection and receive an AST representing the type constraint int|float
}

The actual attributes could either be built-in, making them official parts of the language, or managed in a library that static analysers co-operate on, making them standardised but more agile.


Regards,

--
Rowan Tommins
[IMSoP]

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to