[php-src] Issue #9122: `array` type improvements

From: Date: Mon, 25 Jul 2022 07:57:05 +0000
Subject: [php-src] Issue #9122: `array` type improvements
Groups: php.bugs 
Request: Send a blank email to php-bugs+get-242008@lists.php.net to get a copy of this message
Issue: https://github.com/php/php-src/issues/9122 Author: someniatko ### Description I use PHP for some amount of time, and I find arrays as one of its cornerstone features. However, it is also the weak spot of the PHP type system. This hole is filled with docblock-based static analysis tools like Psalm, and they also show the direction of the possible language improvements. Here I suggest five features which can greatly improve typing arrays and throw away the need of most related docblocks. ## Suggested Features: 1. Add list type, which enforces the array_is_list check. 2. Add types which assert that a given array or list contains only items of specific type. Syntactically it may look like array<string> and list<string>. Nesting typed arrays, union and intersection types should also be allowed. Covariance and contravariance rules should probably work the same way as they do without the array<X> wrapper. 3. Add tuple types, e.g. in format [string, int]. 4. Add structure types, e.g. [ 'name' => string, 'age' => int ]. 5. Allow aliasing tuple and structure types for later reuse. These features may be implemented one by one. ## Motivation: - PHP progresses to be more statically typed, meaning more and more types are defined in the source code rather than always determined dynamically, - PHP has a unique and powerful concept of array, which however doesn't play well with the improving type system, and this should be fixed. - Arrays are passed by-value, unlike the classes which are passed by-reference, which makes arrays with structure types a perfect candidate for typed DTOs. - Syntax with angle brackets < may be forward compatible with possible generics introduction. ## Possible Performance Impact: PHP has done lots of internal optimizations to be a fast language, but this feature could somewhat slow it down. To implement the typed array (array<T>) feature in the optimal way, internally an array should probably maintain its inferred type once constructed / mutated to not reevaluate it every time it encounters a typed function parameter or return type. Structure types may be fairly complex, probably a special function should exist which will mark an array as such that conforms to a given structure, without actually checking it. E.g. assert_array_structure($array, $structure_type), where $structure_type could, for example, be obtained via Reflection.

« previous php.bugs (#242008) next »