Re: [RFC] [Discussion] Never parameters

From: Date: Wed, 09 Apr 2025 01:40:31 +0000
Subject: Re: [RFC] [Discussion] Never parameters
References: 1  Groups: php.internals 
Request: Send a blank email to [email protected] to get a copy of this message
On Mon, Mar 10, 2025 at 12:05 PM Daniel Scherzer <
[email protected]> wrote:

> Hi internals,
>
> I'd like to start discussion on a new RFC about allowing never for
> parameter types when declaring a method.
>
> * RFC: https://wiki.php.net/rfc/never-parameters-v2
> * Implementation: https://github.com/php/php-src/pull/18016
>
> -Daniel
>


Since a lot of the discussion seems to be around static analysis and
whether there is a real use case for this, I wanted to share another use
case I just came across: in the thephpleague/commonmark package,
different renderers are added to render different types (subclasses) of
League\CommonMark\Node\Node. You can see the interface for renderers at
[1]. The overall interface supports being called with any Node type, but
each underlying renderer expects to be called with a *narrower* type than
that. To avoid LSP violations, the renderers

* have a Node typehint
* have a documentation comment with the actual subclass of Node that they
support
* manually throw an exception on invalid values

See, e.g., the default renderer for paragraphs[2]. This seems like exactly
the place where you would find it useful to have never parameters. The
current implementation
* uses comments and static analysis tools to document the restriction
* manually throws an exception when violated

Whereas if the base class had a never parameter, it could
* use language typehints to document the restriction
* have the exception enforced automatically

I don't think we should be worried about the fact that, under static
analysis, we don't know what type of value is accepted for a never
parameter, because under actual operation, you can always just manually
throw an exception for a type you don't want, like commonmark does.

-Daniel

[1]
https://github.com/thephpleague/commonmark/blob/2.6/src/Renderer/NodeRendererInterface.php
[2]
https://github.com/thephpleague/commonmark/blob/2.6/src/Renderer/Block/ParagraphRenderer.php


Thread (33 messages)

« previous php.internals (#127082) next »