Re: [PHP-DEV] Consider removing autogenerated files from tarballs

2024-04-02 Thread Olle Härstedt
internals+unsubscr...@lists.php.net -  550 5.7.1 Looks like spam to me.

Can't unsub...?

Den tis 2 apr. 2024 kl 16:46 skrev Jakub Zelenka :

> On Tue, Apr 2, 2024 at 3:35 PM tag Knife  wrote:
>
>>
>> On Tue, 2 Apr 2024 at 14:53, Jakub Zelenka  wrote:
>>
>>> We will still need RM to sign the build so ideally we should make it
>>> reproducible so RM can verify that CI produced expected build and then sign
>>> it and just upload the signatures (not sure if we actually need signature
>>> uploaded or if they are used just in announcements).
>>>
>>> I think this should then prevent compromise of the RM and CI unless CI
>>> is compromised by RM, of course, but that should be very unlikely.
>>>
>>> Regards
>>>
>>> Jakub
>>>
>>>
>> On the side of the CI being compromised, this does happen, typically with
>> authed
>> private hosted CI, like jenkins. But if its open and accessible to
>> everyone to monitor, such
>> as github actions, everyone can monitor and audit the build logs to
>> verify the commands
>> ran and nothing unexpected happened during build.
>>
>> That is something PHP is missing atm, no one can verify the build process
>> for releases.
>>
>
> Yes that's what I was suggesting. This should be done by RM. In that way,
> the RM becomes more someone that verifies the build and not the actual
> person that provides the build.
>
> Regards
>
> Jakub
>
>
>


Re: [PHP-DEV] Previous discussions about generics syntax only?

2023-10-18 Thread Olle Härstedt
2023-10-17 21:39 GMT+02:00, Rowan Tommins :
> 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
> }

Not sure readability is improved here compared to existing @template
annotations. ;)

Olle

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



[PHP-DEV] Previous discussions about generics syntax only?

2023-10-16 Thread Olle Härstedt
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.

Regards
Olle

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



Re: [PHP-DEV] RFC Proposal: Readonly Structs in PHP

2023-09-08 Thread Olle Härstedt
2023-09-08 15:12 GMT+02:00, Lanre Waju :
> Dear PHP Internals,
>
> I am writing to propose a new feature for PHP that introduces the
> concept of structs. This feature aims to provide a more concise and
> expressive way to define and work with immutable data structures. Below
> is a detailed description of the proposed syntax, usage, and behavior.
>
> Syntax
>
> struct Data
> {
>  string $title;
>  Status $status;
>  ?DateTimeImmutable $publishedAt = null;
> }
> The Data struct is essentially represented as a readonly class with a
> constructor as follows:
>
>
> readonly class Data
> {
>  public function __construct(
>  public string $title,
>  public Status $status,
>  public ?DateTimeImmutable $publishedAt = null,
>  ) {}
> }
> Assertions
> The Data struct will always be readonly.
> It has no methods besides the constructor.
> Constructors
> The Data struct can be constructed in three different ways, each of
> which allows for named or positional arguments, which can be mixed:
>
> 1.1 Class like
> $data = new Data('title', Status::PUBLISHED, new DateTimeImmutable());
>
> 1.2 Class like (Named Syntax)
> $data = new Data(title: 'title', status: Status::PUBLISHED, publishedAt:
> new DateTimeImmutable());
>
> 2.1 Proposed struct initialization syntax (Positional Arguments)
> $data = Data{'title', Status::PUBLISHED, new DateTimeImmutable()};
>
> 2.2 Proposed struct initialization syntax (Named Syntax)
> $data = Data{title: 'title', status: Status::PUBLISHED, publishedAt: new
> DateTimeImmutable()};
>
> 3.1 Anonymous Struct (Named Arguments)
>
> $data = struct {
>  string $title;
>  Status $status;
>  ?DateTimeImmutable $publishedAt = null;
> }('title', Status::PUBLISHED, new DateTimeImmutable());
> 3.2 Anonymous Struct (Named Arguments - Named Syntax)
>
> $data = struct {
>  string $title;
>  Status $status;
>  ?DateTimeImmutable $publishedAt = null;
> }(title: 'title', status: Status::PUBLISHED, publishedAt: new
> DateTimeImmutable());
> Nesting
> The proposed feature also supports nesting of structs. For example:
>
>
> final class HasNestedStruct
> {
>  NestedStruct {
>  string $title;
>  Status $status;
>  ?DateTimeImmutable $publishedAt = null;
>  };
>
>  public function __construct(
>  public string $string,
>  public Data $normalStruct,
>  public NestedStruct $nestedStruct = NestedStruct{'title',
> Status::PUBLISHED, new DateTimeImmutable()},
>  public struct InlineNamed { int $x} $inlineNamed = {x: 1},
>  public { int $x, int $y} $inlineAnonymous = {x: 1, y: 2},
>  ) {}
> }
> This proposal aims to enhance the readability and maintainability of
> code by providing a more concise and expressive way to work with
> immutable data structures in PHP.
> I believe this feature will be a valuable addition to the language as it
> not only opens the door for future enhancements (eg. typed json
> deserialization, etc.), but should also help reduce reliance on arrays
> by providing a more expressive alternative.
>
> Your feedback and suggestions are highly appreciated, and we look
> forward to discussing this proposal further within the PHP internals
> community.
>
> Sincerely
> Lanre
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php

Aren't structs value objects in C#? Might be some semantic confusion
there, in choice of words.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/struct

"Structure types have value semantics".

Java uses the "record" keyword. Worth taking a look at, maybe?

Olle

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



Re: [PHP-DEV] Replace ugly attribute token #[] to other

2023-08-23 Thread Olle Härstedt
2023-08-23 8:35 GMT+02:00, chopins xiao :
> I use @ instead of #[] as attribute token. attribute use whitespace marks
> are closed. Of course you can start with @@ or #, other.
> error control use @@ instead of @, add T_SILENCE token
>
> new syntax:
> one attribute: @attribute{WHITESPACE} @otherAttribute(12){WHITESPACE}
> group attribute: @attribute1(1, 2),attribute2(343,
> 43)@attibute3(33)[WHITESPACE]
>
> current syntax:
> one attribute: #[attribute()] #[otherAttribute()]
> group attribute: #[attribute1(1, 2),attribute2(343,),attibute3(33)]
>
> below is comparison
> new syntax:
>
> @AttrA@AttrB(112, 334),AttrC
> @AttrD
> class A {
>  @AttrE
>  @AttrF @AttrG
>  public $a;
>  @AttrM
>public function m1(@AttrParma(1) $c) {}
> }
>
> $ab = @fn(1) fn()=> 1+2;
> ---
> current syntax:
>
> #[AttrA,AttrB(112, 334),AttrC]
> #[AttrD]
> class A {
>  #[AttrE]
>  #[AttrF]  #[AttrG]
>  public $a;
>  #[AttrM]
>public function m1(#[AttrParma(1)] $c) {}
> }
> $ab  = #[fn(1)] fn()=>1+2;
>
> my implemented:
> https://github.com/chopins/php-src/tree/new-syntax/attribute
>
>
> Other new syntax implemented (Verification of feasibility) :
> https://github.com/chopins/php-src/blob/php-alternative-syntax/alternative-syntax.md
>
>
> Regards
> Chopin Xiao
>

I think this was debated extensively already. :) It's unlikely to change.

Olle

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



Re: [PHP-DEV] pipes, scalar objects and on?

2023-07-19 Thread Olle Härstedt
2023-07-18 18:50 GMT+02:00, Larry Garfield :
> On Tue, Jul 18, 2023, at 4:47 PM, Olle Härstedt wrote:
>
>> Any comment on a pipe (or piped process) as a first-class value? When
>> you use |> the functions are immediately applied, which might not be
>> what you want. You can lazify it by wrapping it in a lambda, but I
>> think that decreases the value of the pipe concept in itself. One
>> strength is the ability to split the decision about what to glue
>> together from the decision on how to execute it. You kinda get some
>> light-weight metaprogramming ability that way.
>>
>> Well i guess such a pipe-concept is pretty far removed from the simple
>> pipe operator. :) And also already possible with existing OOP
>> concepts, callable classes, and now the (...) syntax.
>
> That's the function concat operator I have been mentioning.  Concat can be
> implemented in terms of pipe, and pipe can be implemented in terms of
> concat, but I'd rather have both natively.
>
> For more on my thoughts there, see:
> https://peakd.com/hive-168588/@crell/aoc2021-review

Right, I think I was thinking more of the pipeline design pattern than
the pipe operator. The concat operator will tell you THAT two
functions have been glued together, but you have no way to affect HOW
they are glued together. With the pipeline design pattern, you do: For
example, you could add a logger that logs each input and output in the
Pipe class without much hassle.

The pipeline design pattern could still greatly benefit from some of
these RFCs tho, especially partial function application, I think.

Olle

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



Re: [PHP-DEV] pipes, scalar objects and on?

2023-07-18 Thread Olle Härstedt
2023-07-18 21:44 GMT+02:00, Deleu :
> https://wiki.php.net/rfc/short-functions
>> https://wiki.php.net/rfc/auto-capture-closure
>> https://wiki.php.net/rfc/partial_function_application
>> https://wiki.php.net/rfc/pipe-operator-v2
>
>
> The only thing I can think of is if we gather a team of ~20 ppl and come up
> with a plan on collectively getting Voting Karma so that we can have these
> awesomeness revisited.

Or, we gather the main concern(s) of the no-voters and try to approach
those? :) Put them in a sheet (Google or Excel) and try to make sense
out of it, if there's a way forward.

Olle

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



Re: [PHP-DEV] pipes, scalar objects and on?

2023-07-18 Thread Olle Härstedt
2023-07-18 20:08 GMT+02:00, Larry Garfield :
> On Tue, Jul 18, 2023, at 5:08 PM, Karoly Negyesi wrote:
>> My favorite pipeline is Elixir, where "The pipe operator |> passes the
>> result of an expression as the first parameter of another expression"..
>> But
>> it works there because unlike with PHP, it's almost always the first
>> argument you want. If it's not the first argument you needed to do some
>> tricks which was only cleaned up in 2021 so now they do:
>>
>> 5
>> |> then(&Enum.take(1..10, &1))
>> |> Enum.reverse()
>>
>> but I digress.
>>
>> My problem here is... we actually need something that passes the RFC
>> vote.
>>
>> What flexibility is missing here?
>
> Please don't top post.
>
> The main flexibility for callables is the ability to build a closure on the
> fly.  For example, using $$ (which Hack does, and I insist on calling
> T_BLING) means that for array and string functions you still need to worry
> about parameter order.  With a callable, you can effectively emulate
> Elixir's behavior if you want.
>
> For example, my FP library has a whole bunch of higher order functions that
> just return pipe-ready functions:
>
> https://github.com/Crell/fp/blob/master/src/array.php
>
> Which, with a pipe operator, would allow for:
>
> $result = $arr
>   |> amap(trim(...))
>   |> afilter(is_int(...))
>   |> reduce(0, $fn)
>   |> trim(...) // At this point it's a string and trim() is already unary,
> so we can just use it.
> ;
>
> Which is pretty nice, IMO.  It "flows" nicely, supports both higher order
> functions and direct calls equally well, and allows for all kinds of further
> expansion that I haven't thought of yet.
>
> The Hack style would require thinking about the fact that array_map() and
> array_filter() take their arguments in reverse order from each other, which
> is just silly.  This way, that problem goes away entirely.
>
> It also allows a pipe to be used as a quasi alternative to scalar methods,
> because (if we set aside visibility for the moment) a method is just a
> function with an implicit $this parameter.  Callables and higher order
> functions make that a lot cleaner.
>
> The caveat is that it does add an extra step to use many of the existing
> array or string stdlib functions.  However, that's work that can be done
> once.  The link above is under 500 lines, heavily documented, and covers
> every array use case I've run into so far.
>
> Related improvements:
>
> * Writing a higher order function right now is rather cumbersome.  There
> were two previous RFCs that would have made that vastly nicer
> (short-functions and auto-capture closures), but neither passed.  They would
> have allowed for:
>
> function amap(callable $c) => fn (iterable $it): array {
> if (is_array($it)) {
> return array_map($c, $it);
> }
> $result = [];
> foreach ($it as $k => $v) {
> $result[$k] = $c($v);
> }
> return $result;
> };
>
> Which I think is pretty nice.
>
> * PFA would give us the best of both worlds, as if you wanted you could do:
>
> $result = $arr
>   |> array_map(trim(...), ?)
>   |> array_filter(?, is_int(...))
>   |> array_reduce(?, $fn, 0)
>   |> trim(...)
> ;

Damn, that PFA RFC would _really_ help with removing noise, instead of
wrapping with fn ($x) => ... everywhere. Shame it didn't pass. :/ 29
vs 20 votes.

Olle

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



Re: [PHP-DEV] pipes, scalar objects and on?

2023-07-18 Thread Olle Härstedt
2023-07-18 17:13 GMT+02:00, Larry Garfield :
> On Tue, Jul 18, 2023, at 1:05 PM, Olle Härstedt wrote:
>> 2023-07-18 14:48 GMT+02:00, someniatko :
>>> I am glad this topic arose! I was also planning to write on this topic
>>> to
>>> the internals mailing list, but have abandoned this idea, because I feel
>>> it
>>> might be inconvenient for the real active PHP developers on the list to
>>> receive too many emails from the people which don't actively participate
>>> in
>>> the development itself.
>>>
>>> My interest in the pipe operator might seem a little non-standard -
>>> basically what I'd really want to see is a **nullable** pipe operator!
>>>
>>> There is a popular library github.com/schmittjoh/php-option, which has
>>> 250
>>> MILLION installations. Basically what it provides is a class-wrapper of
>>> a
>>> value of lack thereof: it's either `Some` or `None`.
>>
>> I'd just like to mention that the Option type comes from FP and it's
>> not necessarily needed in PHP-land where we have flow-sensitive type
>> checkers like Psalm (a nullable type `?int` or such is refined to just
>> `int` after a null check). Flow-sensitive type-checking was not
>> invented when the Option type was first created, so adding it to PHP
>> is basically stepping back in time, from my point of view.
>
> As I've written before[1], there's a lot of overlap in different
> error-flow-control options.  PHP at the moment leans heavily on the "null is
> error and build tooling around that" approach, which has its pros (mainly
> simplicity) and cons (lack of information).  That mostly obviates the need
> for a Maybe type, but not entirely.  Right now, there is no "null pipeline"
> option in the language like someniako is describing.
>
> In some sense, that's also trivial to do in user-space[2], which leads
> easily to
>
> $foo
>   |> maybe(bar(...))
>   |> maybe(baz(...))
>   |> maybe(beep(...));
>
> Which isn't terrible, but also isn't ideal.  I don't think I'd oppose a
> nullsafe pipe if there's interest (though again, we need interest in pipes
> in general first).
>
> However, that runs into the related problem that Maybe is... the weaker way
> of handling error context.  In most cases I prefer a Result/Either type,
> which doesn't map cleanly to null handling.  That could be done as a
> user-space monad (as above, with just a class and method or a magic method
> and dedicated operator).  Doing it more natively would require deeper
> language hooks.  For instance, Rust has the ? suffix on any expression,
> which means "if this evaluates to an Error case Result, just return that
> Result."  That wouldn't fit well in PHP, though.
>
> As I noted in [1], one option would be to allow an object to flag itself as
> an error object, and then null-check operators would treat that as null.  So
> given $result = foo($a)->bar(), if foo() returns an error object then
> $result is assigned to that error object and bar() is never called.  I'm
> still not sure if I like that approach myself, but am open to hear what
> others think.
>
> To get back on topic, I do think a pipe operator and concat operator are
> valuable in their own right, and have ample use cases even without mixing in
> monads or nullables or things like that.  We should add them.  We can
> consider adding more robust branching options as well, (be that >>=, ?|>, or
> something else), but be aware that beyond the very trivial case that will
> necessarily involve user-space code for many use cases and we'll need to
> support that.  (Which basically comes down to >>= and making monadic classes
> easier to work with, but also runs into the generics problem, and that's its
> own mess.)
>
> [1] https://peakd.com/hive-168588/@crell/much-ado-about-null
> [2] https://github.com/Crell/fp/blob/master/src/composition.php#L39
>
> --Larry Garfield
>

Any comment on a pipe (or piped process) as a first-class value? When
you use |> the functions are immediately applied, which might not be
what you want. You can lazify it by wrapping it in a lambda, but I
think that decreases the value of the pipe concept in itself. One
strength is the ability to split the decision about what to glue
together from the decision on how to execute it. You kinda get some
light-weight metaprogramming ability that way.

Well i guess such a pipe-concept is pretty far removed from the simple
pipe operator. :) And also already possible with existing OOP
concepts, callable classes, and now the (...) syntax.

Olle

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



Re: [PHP-DEV] pipes, scalar objects and on?

2023-07-18 Thread Olle Härstedt
2023-07-18 14:48 GMT+02:00, someniatko :
> I am glad this topic arose! I was also planning to write on this topic to
> the internals mailing list, but have abandoned this idea, because I feel it
> might be inconvenient for the real active PHP developers on the list to
> receive too many emails from the people which don't actively participate in
> the development itself.
>
> My interest in the pipe operator might seem a little non-standard -
> basically what I'd really want to see is a **nullable** pipe operator!
>
> There is a popular library github.com/schmittjoh/php-option, which has 250
> MILLION installations. Basically what it provides is a class-wrapper of a
> value of lack thereof: it's either `Some` or `None`. I also maintain
> a similar library https://packagist.org/packages/someniatko/result-type
> which fixes some shortcomings of the original one related to the static
> analysis, but this is another story. Basically what the stats tell us is
> that such stuff is popular among the PHP community.
>
> In my eyes, it is actually semantically equivalent to the nullable PHP
> types: `?Type`. And some operations provided by the lib, are actually
> covered by PHP itself, which has multiple null-friendly operators:
> `$option->getOrElse($defaultVal)` --> `$nullable ?? $defaultVal`
> `$option->isEmpty()` --> `$nullable === null`
> `$option->getOrThrow(new \Exception('blah'))` --> `$nullable ?? throw new
> \Exception('blah')`
>
> I'd like to use the arguably "more idiomatic" native PHP nullables, rather
> than a foreign-feeling userspace construct, if they were more convenient.
>
> But there is a very important operation, `map()`, which is unfortunately
> not covered by the native PHP, which is `Option::map()`, and here is a
> real-world example:
> ```
> return $repository->getById($idFromHttpRequest)
> ->map($serializer->serializeToJson(...)) // only executes when the
> Option is Some, not None
> ->map(fn (string $json) => new Response(status: 200, content: $json))
> ->getOrElse(new Response(status: 404));
> ```

Ehm, wouldn't that be the same as a Pipe class that's configured to
stop on null?

public function getThing($id) {
  return new Pipe(
$this->getData(...),
$this->serializeData(...),
$this->mapToResponse(...)
  )
  ->stopOnEmpty()
  ->from($id)
  ->run();
}

Wait, are you using map() for arrays or not? Looks like not.

Olle

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



Re: [PHP-DEV] pipes, scalar objects and on?

2023-07-18 Thread Olle Härstedt
2023-07-18 14:48 GMT+02:00, someniatko :
> I am glad this topic arose! I was also planning to write on this topic to
> the internals mailing list, but have abandoned this idea, because I feel it
> might be inconvenient for the real active PHP developers on the list to
> receive too many emails from the people which don't actively participate in
> the development itself.
>
> My interest in the pipe operator might seem a little non-standard -
> basically what I'd really want to see is a **nullable** pipe operator!
>
> There is a popular library github.com/schmittjoh/php-option, which has 250
> MILLION installations. Basically what it provides is a class-wrapper of a
> value of lack thereof: it's either `Some` or `None`.

I'd just like to mention that the Option type comes from FP and it's
not necessarily needed in PHP-land where we have flow-sensitive type
checkers like Psalm (a nullable type `?int` or such is refined to just
`int` after a null check). Flow-sensitive type-checking was not
invented when the Option type was first created, so adding it to PHP
is basically stepping back in time, from my point of view.

Olle

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



Re: [PHP-DEV] pipes, scalar objects and on?

2023-07-18 Thread Olle Härstedt
2023-07-17 21:57 GMT+02:00, Larry Garfield :
> On Mon, Jul 17, 2023, at 7:07 PM, Olle Härstedt wrote:
>> 2023-07-17 18:58 GMT+02:00, Larry Garfield :
>>> On Mon, Jul 17, 2023, at 2:57 PM, Olle Härstedt wrote:
>>>> 2023-07-17 14:25 GMT+02:00, Karoly Negyesi :
>>>>> Hi,
>>>>>
>>>>> I tried to read on why the pipe RFC failed but by and large I also
>>>>> failed.
>>>>>
>>>>> The discussion on https://github.com/php/php-src/pull/7214 is very
>>>>> short.
>>>>>
>>>>> https://externals.io/message/114770 is not so short but it seems not
>>>>> to
>>>>> cover the latest version which uses first class functions?
>>>>>
>>>>> Could someone please give me a summary why it failed? I really would
>>>>> like
>>>>> to see it succeed :) I am writing code if not daily but certainly
>>>>> weekly
>>>>> that certainly looks like a pipeline.
>>>>
>>>> The pipe RFC was kinda forced in before a deadline, no?
>>>>
>>>> My own two cents:
>>>>
>>>> * It's trivial to implement a pipe() function or a Pipe class
>>>> * A Pipe class is better than both a function and built-in operator,
>>>> since it can be configured with custom behaviour, e.g. stop or throw
>>>> on empty payload, or repeat on a collection, or even with parallelism
>>>> or concurrency
>>>> * If I had voting rights, I'd vote in favor in a pipe operator :)
>>>
>>> From my recollection, there were a couple of things involved.
>>>
>>> 1. It was intended to pair with the PFA RFC, which didn't pass, which
>>> made
>>> it a bit less compelling.
>>> 2. It was close to the RFC deadline, and it seems people get squeamish
>>> around that.
>>> 3. Some folks wanted Hack-style pipes instead of the pipes used by every
>>> other language with pipes. I've written before on why that's a worse
>>> design.
>>> 4. Arguments that it can be done in user space, which is not true, as I
>>> have
>>> a user-space implementation and it's comparatively cumbersome and
>>> definitely
>>> slower than a native operator would be.
>>> 5. General "meh" attitude on FP features in general from some people.
>>>
>>> Side note to Olle: If you want a customizable pipe, you've just described
>>> a
>>> Monad. :-)  It's literally "contextually-sensitive func concatenation."
>>> A
>>> monadic bind operator would be harder to do with PHP's weaker type
>>> system,
>>> but there are ways it could be done.
>>
>> Mm I don't really agree with that, I think monads make sense only in
>> languages which support them syntactically. A Pipe class is a very
>> straight-forward construction, and the blog posts I've read about
>> monads in PHP don't look pretty at all; lots of syntactic noise going
>> on. But that's another discussion... :)
>
> At its most basic:
>
> class Foo {
>   public function __construct(public readonly mixed $val) {}
>
>   public __bind(callable $c) {
> return $c($this->val);
>   }
> }
>
> new Foo('beep') >>= func(...);
>
> Where >>= is the operator that translates to "Call __bind() on the LHS
> object with the callable on the RHS."  Poof, we now have a monad operator.
> This one is effectively the same as |> as it doesn't do anything, but you
> can do whatever you want in the __bind() method.

1. You also want syntactic sugar around this to "flatten" monadic
usage; in OCaml it's `let*`.

2. This way you won't get read-process-write pipelines as first-class
values, which you can do if you just make a Pipe class instead. I
think. Correct me if I'm wrong. :)

Olle

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



Re: [PHP-DEV] pipes, scalar objects and on?

2023-07-17 Thread Olle Härstedt
2023-07-17 18:58 GMT+02:00, Larry Garfield :
> On Mon, Jul 17, 2023, at 2:57 PM, Olle Härstedt wrote:
>> 2023-07-17 14:25 GMT+02:00, Karoly Negyesi :
>>> Hi,
>>>
>>> I tried to read on why the pipe RFC failed but by and large I also
>>> failed.
>>>
>>> The discussion on https://github.com/php/php-src/pull/7214 is very
>>> short.
>>>
>>> https://externals.io/message/114770 is not so short but it seems not to
>>> cover the latest version which uses first class functions?
>>>
>>> Could someone please give me a summary why it failed? I really would
>>> like
>>> to see it succeed :) I am writing code if not daily but certainly weekly
>>> that certainly looks like a pipeline.
>>
>> The pipe RFC was kinda forced in before a deadline, no?
>>
>> My own two cents:
>>
>> * It's trivial to implement a pipe() function or a Pipe class
>> * A Pipe class is better than both a function and built-in operator,
>> since it can be configured with custom behaviour, e.g. stop or throw
>> on empty payload, or repeat on a collection, or even with parallelism
>> or concurrency
>> * If I had voting rights, I'd vote in favor in a pipe operator :)
>
> From my recollection, there were a couple of things involved.
>
> 1. It was intended to pair with the PFA RFC, which didn't pass, which made
> it a bit less compelling.
> 2. It was close to the RFC deadline, and it seems people get squeamish
> around that.
> 3. Some folks wanted Hack-style pipes instead of the pipes used by every
> other language with pipes. I've written before on why that's a worse
> design.
> 4. Arguments that it can be done in user space, which is not true, as I have
> a user-space implementation and it's comparatively cumbersome and definitely
> slower than a native operator would be.
> 5. General "meh" attitude on FP features in general from some people.
>
> Side note to Olle: If you want a customizable pipe, you've just described a
> Monad. :-)  It's literally "contextually-sensitive func concatenation."  A
> monadic bind operator would be harder to do with PHP's weaker type system,
> but there are ways it could be done.

Mm I don't really agree with that, I think monads make sense only in
languages which support them syntactically. A Pipe class is a very
straight-forward construction, and the blog posts I've read about
monads in PHP don't look pretty at all; lots of syntactic noise going
on. But that's another discussion... :)

Olle

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



Re: [PHP-DEV] pipes, scalar objects and on?

2023-07-17 Thread Olle Härstedt
2023-07-17 14:25 GMT+02:00, Karoly Negyesi :
> Hi,
>
> I tried to read on why the pipe RFC failed but by and large I also failed.
>
> The discussion on https://github.com/php/php-src/pull/7214 is very short.
>
> https://externals.io/message/114770 is not so short but it seems not to
> cover the latest version which uses first class functions?
>
> Could someone please give me a summary why it failed? I really would like
> to see it succeed :) I am writing code if not daily but certainly weekly
> that certainly looks like a pipeline.

The pipe RFC was kinda forced in before a deadline, no?

My own two cents:

* It's trivial to implement a pipe() function or a Pipe class
* A Pipe class is better than both a function and built-in operator,
since it can be configured with custom behaviour, e.g. stop or throw
on empty payload, or repeat on a collection, or even with parallelism
or concurrency
* If I had voting rights, I'd vote in favor in a pipe operator :)

Olle

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



Re: [PHP-DEV] Request to create a RFC for const args

2023-06-19 Thread Olle Härstedt
2023-06-19 12:59 GMT+02:00, Sam McDonald :
> He6 Olle,
> Yes more so the former, not the latter in your example.
> If there is already an rfc in place then that is fantastic.
> Regards
> SAM

There's no RFC, just me mailing out the idea when I had it. :) Go wild.

Olle

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



Re: [PHP-DEV] Request to create a RFC for const args

2023-06-19 Thread Olle Härstedt
2023-06-19 9:56 GMT+02:00, Sam McDonald :
> Hello php internals team,
> I would like to put forward an RFC for a new feature. I am a long time user,
> but have never participated as yet to the RFC.
>
> This is my first step to gather reaction/feedback from the team.
>
> I would be happy to implement the feature and post a PR or have someone from
> the team implement this.
>
> The feature I want to put forward is "const function arguments" (same for
> methods)
>
> This feature is available in cpp, and I believe would be a benefit to the
> php community.
>
> My RFC would fully detail and clarify what this is and how it works.
>
> This feature allows the user to specify "const" on a function arg, so that
> the argument while in a function can not be reassigned.
>
> The following example would throw an exception at compile/runtime.
>
> ```
> public function foo(const int $bar)
> {
>$bar =3D "buz";
> }
> ```

Isn't this similar to my own idea of readonly function arguments?
https://externals.io/message/120203#120210

Perhaps more limited in scope?

Olle

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



[PHP-DEV] Re: Limit write access to object function parameters

2023-05-08 Thread Olle Härstedt
2023-05-06 12:55 GMT+02:00, Olle Härstedt :
> Heyo internalitos,
>
> I was thinking of having the possibility to use `readonly` (or any
> other keyword) to make a function argument behave as if it was a
> readonly object.
>
> class Point
> {
>   public int $x;
>   public int $y;
> }
> function doThing(readonly Point $p)
> {
>   $p->x = 10;  // Not allowed
> }
>
> In C# it's called in/out/ref types:
> https://www.pluralsight.com/guides/csharp-in-out-ref-parameters
>
> The main use-case is to not give away more access than you have to,
> and being able to state your intent in the function signature.
>
> Another alternative would be to allow properties in interfaces, and
> then define a readonly-like interface:
>
> interface ReadonlyPoint
> {
>   public readonly int $x;
>   public readonly int $y;
> }
> function doThing(ReadonlyPoint $p)
> {
>   $p->x = 10;  // Not allowed
> }
>
> No idea about practical feasability.
>
> Since arrays are value types, they're not really relevant for this
> suggestion. Same goes for string, int, etc.
>
> Regards
> Olle

Also related is Object.freeze from JS (I was told):
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

Olle

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



[PHP-DEV] Limit write access to object function parameters

2023-05-06 Thread Olle Härstedt
Heyo internalitos,

I was thinking of having the possibility to use `readonly` (or any
other keyword) to make a function argument behave as if it was a
readonly object.

class Point
{
  public int $x;
  public int $y;
}
function doThing(readonly Point $p)
{
  $p->x = 10;  // Not allowed
}

In C# it's called in/out/ref types:
https://www.pluralsight.com/guides/csharp-in-out-ref-parameters

The main use-case is to not give away more access than you have to,
and being able to state your intent in the function signature.

Another alternative would be to allow properties in interfaces, and
then define a readonly-like interface:

interface ReadonlyPoint
{
  public readonly int $x;
  public readonly int $y;
}
function doThing(ReadonlyPoint $p)
{
  $p->x = 10;  // Not allowed
}

No idea about practical feasability.

Since arrays are value types, they're not really relevant for this
suggestion. Same goes for string, int, etc.

Regards
Olle

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



Re: [PHP-DEV] RFC Proposal - Types for Inline Variables

2023-02-07 Thread Olle Härstedt
2023-02-07 17:21 GMT+01:00, Rowan Tommins :
> On 07/02/2023 14:07, Olle Härstedt wrote:
>> It should perhaps be mentioned that analyzers can use type annotations
>> during their process, instead of the more clunky /** @var string */ or
>> similar you have to use today for local variables.
>
> This sounds like you're reaching for Python's approach, where the
> language "supports" the type annotation syntax, but doesn't actually do
> anything with it.

No not really. I'd expect it behave similar to function argument
type-hinting in PHP, that is, runtime checks, but where the notation
can be used by external tools.

Olle

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



Re: [PHP-DEV] Official Preprocessor

2023-02-03 Thread Olle Härstedt
2023-02-03 17:38 GMT+01:00, Flávio Heleno :
> On Fri, Feb 3, 2023 at 6:19 AM Olle Härstedt 
> wrote:
>
>> 2023-02-02 15:19 GMT+01:00, someniatko :
>> > Hi Internals
>> >
>> > The main gist:
>> > --
>> >
>> > I suggest to introduce an official type-checker / static analyser /
>> > preprocessor / transpiler for PHP, somewhat similar to TypeScript in
>> > the JavaScript world, which will allow to introduce the features
>> > otherwise impossible for the PHP world, at the cost of including an
>> > additional transpilation step.
>> >
>> > The reasoning:
>> > --
>> >
>> > You all know there are a lot of problems with the language, especially
>> > large gaps with the current type system, which have large community
>> > demand to overcome, but still cannot be solved due to the paradigm
>> > chosen by PHP. And the paradigm is to be statically typed (to some
>> > extent), but dynamically checked language, which limits the number of
>> > available options due to performance reasons.
>> >
>> > The introduction of static types have gradually eliminated the need of
>> > using external means of communicating the types (phpdoc @param and
>> > @return annotations), replacing them with native language constructs,
>> > making the language more expressive and enterprise-ready. However,
>> > there are a lot of things still missing, like types of arrays,
>> > including lists, hash-maps and structure-like arrays, and of course
>> > generic classes and functions. These are still covered nowadays with
>> > external means like phpdoc annotations and static analysers / type
>> > checkers to validate them. This leaves PHP in the odd mixture of
>> > native types and externally validated annotations via comments.
>> >
>> > Paradigm of a dynamically checked language also leaves out the problem
>> > of type-checking before running the code. Even though the types are
>> > defined statically, you still have to physically run the code, with
>> > all possible execution paths, to catch a type error. To avoid that you
>> > still would have to use an external typechecker / static analyser,
>> > even if PHP could cover 100% of type demand natively.
>> >
>> > Python solves this problem nicely I think. It is dynamically typed,
>> > but it allows a special syntax for static types and also has a
>> > separate static type checker. I think this is really a good approach
>> > and it would be great if PHP followed this path for the beginning, but
>> > we have what we have already.
>> >
>> > There were attempts to create preprocessors for PHP (like PHP++ IIRC),
>> > which allowed features like generics, but they did not gain enough
>> > popularity, weren't baked by large enough companies, didn't make their
>> > way to major IDEs support. I believe the only solution is to make an
>> > official one.
>> >
>> > Therefore, I suggest the following thing:
>> > 1. Introduce a new #declare directive which will mark the file as
>> > requiring pre-processing.
>> > 2. Let PHP introduce special features that only work in such
>> > "pre-processing required" files, such as typed lists and generics.
>> > 3. Implement a static type-checker in PHP that will verify those typed
>> > lists and generics are indeed used in a valid way.
>>
>> No need to waste resources implementing a new one when we already have
>> two very competent already: Psalm and Phpstan? Or why is those not
>> enough for your use-case?
>>
>> "The greatest enemy to a perfect solution is a good enough solution
>> already in place." ;)
>>
>> Olle
>>
>> --
>> PHP Internals - PHP Runtime Development Mailing List
>> To unsubscribe, visit: https://www.php.net/unsub.php
>>
>>
> Why not follow the steps of other projects that have been created
> independently from the core and,
> at some point, gained enough support/traction that were incorporated into
> it?

You'd have to rewrite Psalm or Phpstan in C if you want it to be part
of php-src. Or write a completely new project.

Olle

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



Re: [PHP-DEV] Official Preprocessor

2023-02-03 Thread Olle Härstedt
2023-02-02 15:19 GMT+01:00, someniatko :
> Hi Internals
>
> The main gist:
> --
>
> I suggest to introduce an official type-checker / static analyser /
> preprocessor / transpiler for PHP, somewhat similar to TypeScript in
> the JavaScript world, which will allow to introduce the features
> otherwise impossible for the PHP world, at the cost of including an
> additional transpilation step.
>
> The reasoning:
> --
>
> You all know there are a lot of problems with the language, especially
> large gaps with the current type system, which have large community
> demand to overcome, but still cannot be solved due to the paradigm
> chosen by PHP. And the paradigm is to be statically typed (to some
> extent), but dynamically checked language, which limits the number of
> available options due to performance reasons.
>
> The introduction of static types have gradually eliminated the need of
> using external means of communicating the types (phpdoc @param and
> @return annotations), replacing them with native language constructs,
> making the language more expressive and enterprise-ready. However,
> there are a lot of things still missing, like types of arrays,
> including lists, hash-maps and structure-like arrays, and of course
> generic classes and functions. These are still covered nowadays with
> external means like phpdoc annotations and static analysers / type
> checkers to validate them. This leaves PHP in the odd mixture of
> native types and externally validated annotations via comments.
>
> Paradigm of a dynamically checked language also leaves out the problem
> of type-checking before running the code. Even though the types are
> defined statically, you still have to physically run the code, with
> all possible execution paths, to catch a type error. To avoid that you
> still would have to use an external typechecker / static analyser,
> even if PHP could cover 100% of type demand natively.
>
> Python solves this problem nicely I think. It is dynamically typed,
> but it allows a special syntax for static types and also has a
> separate static type checker. I think this is really a good approach
> and it would be great if PHP followed this path for the beginning, but
> we have what we have already.
>
> There were attempts to create preprocessors for PHP (like PHP++ IIRC),
> which allowed features like generics, but they did not gain enough
> popularity, weren't baked by large enough companies, didn't make their
> way to major IDEs support. I believe the only solution is to make an
> official one.
>
> Therefore, I suggest the following thing:
> 1. Introduce a new #declare directive which will mark the file as
> requiring pre-processing.
> 2. Let PHP introduce special features that only work in such
> "pre-processing required" files, such as typed lists and generics.
> 3. Implement a static type-checker in PHP that will verify those typed
> lists and generics are indeed used in a valid way.

No need to waste resources implementing a new one when we already have
two very competent already: Psalm and Phpstan? Or why is those not
enough for your use-case?

"The greatest enemy to a perfect solution is a good enough solution
already in place." ;)

Olle

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



Re: [PHP-DEV] Re: Alias for `int|float`

2022-10-03 Thread Olle Härstedt
2022-10-03 19:56 GMT+02:00, juan carlos morales :
> Very interesting
>
> But I think that the original suggestion had a slimer scope than the
> rest of the opinions, that is why I also agree that the "scope" should
> be defined clearly, and provide the examples needed to clarify the
> suggestion itself.
>
> Cheers
>

Yep, agree. Got the karma to open an RFC now, will do it "later".

Olle

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



[PHP-DEV] Request for karma

2022-10-01 Thread Olle Härstedt
Heyo,

I'd like to be able to add a new RFC for type alias and possible
extensions of use-statement, to collect discussions that have been
happening in chats/emails/etc in one place.

Username: ollehar

Thank you!

Olle

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



Re: [PHP-DEV] Re: Alias for `int|float`

2022-09-30 Thread Olle Härstedt
2022-09-30 17:16 GMT+02:00, Larry Garfield :
> On Fri, Sep 30, 2022, at 4:04 AM, Olle Härstedt wrote:
>> 2022-09-29 5:08 GMT+02:00, Hamza Ahmad :
>>> Hi Olle,
>>>
>>> I appreciate your idea of introducing a similar concept of typedef.
>>> What if you write an RFC explaining that concept. I can join you
>>> however in co-authoring this request.
>>>
>>> Seriously, I have had issues with writing such type again and again.
>>> If you look at mixed type, it is indeed an alias of some union types.
>>> Adding such an option to userland would lead to introduction of
>>> various type hints. Plus, it will help devs write short hand aliases
>>> for their intersection types.
>>
>> Note that my suggestion here is NOT about a project-global type alias,
>> but an extension of the existing file-only alias, the use-statement.
>> This can also explain the lack of reaction. :) Internal devs might
>> already have consensus on the right way to proceed here, even if
>> there's no RFC yet.
>
> Background:
>
> Type aliases have been discussed several times.

Ya ok, not what I could find in externals.io ^^

> There's definitely
> interest, but like many things it runs into the problems of time and
> figuring out the details.
>
> In particular, I don't get the sense that there's much appetite for
> file-local aliases.  While that would have some benefit, it could lead to
> all kinds of confusion when then using code from another file.  Consider:
>
> A.php:
>
> use int|float as number;
>
> interface A
> {
>   public function a(number $a) {}
> }
>
> B.php:
>
> // Yeah, aliasing this is very helpful.
> use (Request&Linkable)|(ServerRequest&Linkable)|array|null as input;
>
> interface B
> {
>   public function b(input $b) {}
> }
>
> C.php:
>
> class C implements A, B
> {
>   // Which of these to use?
>   public function a(int|float $a) {}
>   public function a(number $a) {}
>   // Or do I need to repeat the definition of "number" in every file?

Yes, you would. That's the limit of my current suggestion. Same
semantics as use-statements.

>   // WTF do I do here? Do I have to repeat the entire definition either
>   // inline or in this file's "use" block?  Both suck.
>   public function b(...)

Neither suck. :) Just "normal" inheritance boilerplate in the absence
of project-global type aliasing.

Do you have similar counter-examples for non-OOP code?

> }
>
>
> This becomes even more of an issue when you start talking about function
> types, which is often mentioned as the primary use case.
>
> type fn(int $a, string $b): Request as mycallback
>
> function do(mycallback $callback) {}
>
> So I have to duplicate the type def in every file now?  This is not an
> improvement.

It's an improvement for readability, especially when repeated in one
file. But my suggestion does not include function-types, because
there's no such thing already in the system. Just to let use-statement
include more of already existing types. If function-types were added
later, they should be supported too, yes.

>
> So we have to go with app-global aliases, but then... how do you handle
> resolution?  Autoloading?  Namespacing?  Conflict resolution?  I dunno,
> that's all hard, and that's where the conversation usually peters out.

Yeah, always better to have a clear limitation, is it not? :D

> The degenerate case you mention of simple type renaming has its own
> interesting implications, which are also a factor for the broader case.
> Specifically, does that create a new type unto itself

No. Keep the same semantics of the current use-statement. But it could
be a future extension, sure. But then you need some kind of "factory"
way to produce those types. In FP they do it with "abstract types",
where the implementation of a type is hidden from outside the module.
In PHP, maybe with Foo::make() functions or such. Different
discussion.

> or does the
> difference get elided at compile time?  For instance:
>
> use int as userId;
> use int as productId;
>
> function a(userId $user) {
>   b($userId);
> }
>
> function b(productId $product) {
>   // ...
> }
>
> a(123);
>
>
> Does this work?  Is it a compile error for mismatched types (as in Go, which
> has this exact feature) or no?  If it is, how do you make it work?  Do you
> need explicit casts?  If it does work, have you gained much since it's no
> more useful than docblocks?  If it does work, how long before SA tools turn
> it into an error anyway and make everything more complicated?  (Because you
> know they will

Re: [PHP-DEV] Re: Alias for `int|float`

2022-09-30 Thread Olle Härstedt
2022-09-30 12:15 GMT+02:00, Lynn :
> On Fri, Sep 30, 2022 at 11:04 AM Olle Härstedt 
> wrote:
>
>> 2022-09-29 5:08 GMT+02:00, Hamza Ahmad :
>> > Hi Olle,
>> >
>> > I appreciate your idea of introducing a similar concept of typedef.
>> > What if you write an RFC explaining that concept. I can join you
>> > however in co-authoring this request.
>> >
>> > Seriously, I have had issues with writing such type again and again.
>> > If you look at mixed type, it is indeed an alias of some union types.
>> > Adding such an option to userland would lead to introduction of
>> > various type hints. Plus, it will help devs write short hand aliases
>> > for their intersection types.
>>
>> Note that my suggestion here is NOT about a project-global type alias,
>> but an extension of the existing file-only alias, the use-statement.
>> This can also explain the lack of reaction. :) Internal devs might
>> already have consensus on the right way to proceed here, even if
>> there's no RFC yet.
>>
>> Olle
>>
>> --
>> PHP Internals - PHP Runtime Development Mailing List
>> To unsubscribe, visit: https://www.php.net/unsub.php
>>
>>
> I don't know if file based type aliases make sense, but just spitballing
> some ideas here.
> ```
> // core php or perhaps some libraries
> typedef number = int|float;
> typedef number = TypeDef::extend('number', static fn (number
> $value, number $min) => $value >= $min);
> typedef number = TypeDef::extend('number',
> static fn (number $value, ?number $min, number $max) => ($min === null ||
> $value >= $min) && $value <= $max);
> typedef even = TypeDef::extend('number', static
> fn (number $value) => $value % 2 === 0);
> typedef positive = number<0>;
> typedef negative = number;
> typedef fraction = float<0, 1>;
> typedef string = TypDef::extend('string', static fn (string
> $value, int $min) => strlen($value) >= $min);
> typedef string = TypeDef::extend('string', static fn
> (string $value, ?int $min, int $max) => length_is_between($value, $min,
> $max));
> typedef regex = TypeDef::extend('string', static fn
> (string $value, string $regex) => preg_match($regex, $value));
>
> namespace  App\Domain;
>
> typedef NonEmptyString = string<1>; // minimum length of 1
> typedef LimitedString = string; // no minimum length, max length
> of 32
> // or typedef LimitedString = string; as alternative notation with
> named parameters
> typedef SomeToken = regex<'/a-z0-9{12}/i'>;
>
> // only allows even numbers ranging from -100 to 100
> function someFunction(even<-100, 100> $number) {}
>
> namespace Elsewhere;
>
> use  App\Domain\NonEmptyString;
> use  App\Domain\LimitedString;
> use  App\Domain\SomeToken;
>
> someFunction(102); // fails `$max` check from `number`
> someFunction(-99); // fails `% 2` check from `even`
>
> ```
>
> I tried to use some consistency for the examples, by no means this is what
> I think it must look like, just making sure the intent of the examples is
> clear. This would be nothing more than syntactic sugar to what I'd
> otherwise write in custom objects to validate types and values and ensure
> type safety. This also doesn't take into account how operators should
> behave or how autoloading could/should behave.

Impressive repertoire of ideas, but probably out of scope from what I
was thinking of. :) Some call this "refinement types":
https://en.wikipedia.org/wiki/Refinement_type

Olle

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



Re: [PHP-DEV] Re: Alias for `int|float`

2022-09-30 Thread Olle Härstedt
2022-09-29 5:08 GMT+02:00, Hamza Ahmad :
> Hi Olle,
>
> I appreciate your idea of introducing a similar concept of typedef.
> What if you write an RFC explaining that concept. I can join you
> however in co-authoring this request.
>
> Seriously, I have had issues with writing such type again and again.
> If you look at mixed type, it is indeed an alias of some union types.
> Adding such an option to userland would lead to introduction of
> various type hints. Plus, it will help devs write short hand aliases
> for their intersection types.

Note that my suggestion here is NOT about a project-global type alias,
but an extension of the existing file-only alias, the use-statement.
This can also explain the lack of reaction. :) Internal devs might
already have consensus on the right way to proceed here, even if
there's no RFC yet.

Olle

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



Re: [PHP-DEV] Re: Alias for `int|float`

2022-09-29 Thread Olle Härstedt
2022-09-29 12:33 GMT+02:00, Ryan Jentzsch :
> `number` type But frankly this seems a bit silly and reminds me too much of
> JavaScript.

That's just an example. You can also consider `use array|ArrayAccess
as arraylike`, or such.

Olle

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



[PHP-DEV] Re: Alias for `int|float`

2022-09-27 Thread Olle Härstedt
>Hello, internals!
>
>What do you think about creating shorthand `number` for `int|float`?

This is also related to allow all types of type-hints in the use-statement, like

use int|float as numeric;

Anyone interested in creating an RFC for this?

Olle

PS. Original thread here: https://externals.io/message/112209#112209
(dunno how to respond to an old thread when I don't have the original
message)

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



[PHP-DEV] Allowing type alias for built-in types

2022-09-26 Thread Olle Härstedt
Has this been discussed before? Some use-cases:



use array as tuple;  // Could interact with Psalm/Phpstan to give more 
intentionality

use array as strings; // Same, together with "@param string[]" docblock

use int as meter;  // To communicate intent

etc



Hard-coded support in the parser could perhaps be added here? 
https://github.com/php/php-src/blob/master/Zend/zend_language_parser.y#L469



Olle Härstedt



Software Developer (Chief Software Architect)



tel:+49 40 22660066



mailto:olle.hearst...@limesurvey.org



https://www.limesurvey.org





LimeSurvey GmbH



Papenreye 63



22453 Hamburg



Sitz der Gesellschaft / trade register: Hamburg, Amtsgericht Hamburg HRB 137625
 Steuernummer / tax id: 49 / 740 / 01441


https://www.limesurvey.org











https://www.facebook.com/LimeSurvey/


https://twitter.com/LimeSurvey


https://www.linkedin.com/company/limesurvey


https://www.xing.com/companies/limesurveygmbh


https://github.com/LimeSurvey/LimeSurvey

Re: [PHP-DEV] One-line heredoc for better syntax highlightning

2022-09-20 Thread Olle Härstedt
2022-09-20 17:00 GMT+02:00, Sara Golemon :
> On 19 September 2022 15:24:26 BST, "Olle Härstedt" <
> olle.haerst...@limesurvey.org> wrote:
>>Some editors can guess the domain-specific language inside heredoc, e.g.
> if you do
>>
>>$query = <<>SELECT * FROM foo
>>MySQL;
>>
>>It would be nice if this feature could be used in single lines as well:
>>
>>$query = <<>
> Good news! This feature exists and was introduced by Rasmus **checks
> notes** about 25 years ago.
>
> To use it, you'll want to hold down your shift key, then press the key just
> to the left of your enter key.  This is called a "quote", and you can see
> it demonstrated here around the word quote.
>
> Hope that helps!
>
> Seriously though, I know you're looking to help your editor find something
> to syntax highlight, but this is an editor problem, not a PHP language
> problem.  If your editor can detect SQL in heredoc, then it should be able
> to improve and find it in interpolated strings.

Nope, because you need to be explicit which type of SQL you're working
with - MySQL, Postgres, SQL Server, etc. Would be hard to write a
regexp to guess that for the editor. :) In the Vim case, it reads your
delimiter name and applies syntax highlight from that (mysql,
javascript, html).

> Making the parser more
> complex for no benefit to the actual language (some detriment, I would
> argue) is not the fix here.
>
> -Sara
>
> P.S. - Yes, I'm assuming a US layout, you know where your quote key is.

I you read my text more carefully, you'd see that I thought the parser
would be simplified by my suggestion, by removing what I thought was
an arbitrary limitation. I was wrong. :(

Olle

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



Re: [PHP-DEV] One-line heredoc for better syntax highlightning

2022-09-20 Thread Olle Härstedt
2022-09-20 11:54 GMT+02:00, Rowan Tommins :
> On 19/09/2022 20:10, Olle Härstedt wrote:
>> More for users to learn? Don't you mean less, haha? This is an
>> arbitrary limitation of heredoc, that we can remove (it might not be
>> arbitrary from a yacc perspective, someone would have to explain that
>> if so).
>
>
> I don't think the rules for heredoc are arbitrary,  but they are quite
> specific: the end delimiter has to appear at the *start* of a line, so
> it can appear anywhere else in the text without prematurely ending the
> string:
>
> $foo = << This is a normal heredoc
> this is not the end FOO
> this is:
> FOO;

Ya ok, this kills my idea. If heredoc was designed from start so that
the delimiter would not be allowed at all in the text, then it would
make sense. Weird that they did it like that, would be easy enough to
come up with a unique delimiter so that it would not cause a
problem... Obviously it can't be changed now without breaking
backwards compatibility.

Our product still supports PHP 7.2 sadly, but that's our own problem. :)

Thank you.

Olle

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



Re: [PHP-DEV] One-line heredoc for better syntax highlightning

2022-09-19 Thread Olle Härstedt
2022-09-19 21:18 GMT+02:00, Tim Düsterhus :
> Hi
>
> On 9/19/22 21:04, Olle Härstedt wrote:
>> That looks good in isolation, but consider the following short snippet:
>>
>> class Foo
>> {
>>  public function bar()
>>  {
>>  $query = <<>  SELECT * FROM baz
>> MySQL;
>>  }
>> }
>>
>> As you can see, the heredoc breaks the reading flow completely. For
>
> The closing marker of the heredoc may be indented as of PHP 7.3, so the
> appropriate comparison would be this:
>
> 
> class Foo
> {
>  public function __construct(
>  private \PDO $dbConnection
>  ) {}
>
>  public function bar()
>  {
>  $query = <<  SELECT  *
>  FROMbaz
>  MySQL;
>  $statement = $this->dbConnection->prepare($query);
>  $statement->execute();
>  }
> }

Pff, that's the second time today 3v4l gives me complete faulty
results in its syntax checker. Guess it's out of date. Thanks for
correcting me here.

Olle

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



Re: [PHP-DEV] One-line heredoc for better syntax highlightning

2022-09-19 Thread Olle Härstedt
> While I can't immediately think of a practical problem with this, I'm hesi
> tant at the idea of adding yet more ways of quoting strings; it means more
> for users to learn, more for third party parsers to implement (including ex
> actly the syntax highlighting tools you're going to help), and in the worst
> case, more edge cases that can lead to security issues

More for users to learn? Don't you mean less, haha? This is an
arbitrary limitation of heredoc, that we can remove (it might not be
arbitrary from a yacc perspective, someone would have to explain that
if so).

>I don't know about other editors, but PhpStorm at least also recognises an
>in-line comment explicitly labelling any string, which if anything seems m
>ore explicit:
>
>$query = /** @lang mysql */"SELECT * FROM foo";

Pja. I wouldn't call it more or less explicit than heredoc notation, personally.

Olle

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



Re: [PHP-DEV] One-line heredoc for better syntax highlightning

2022-09-19 Thread Olle Härstedt
> I don't find that example particularly readable or convincing. It mushes
> together PHP and MySQL keywords too much.
>
> Once you add a WHERE clause that SQL query should be split across
> multiple multiple lines for readability anyway and even for that very
> simple example I personally would add a linebreak in front of the FROM:
>
> $query = << SELECT *
> FROM foo
> MySQL;
>
> Best regards
>Tim Düsterhus

That looks good in isolation, but consider the following short snippet:

class Foo
{
public function bar()
{
$query = <

[PHP-DEV] One-line heredoc for better syntax highlightning

2022-09-19 Thread Olle Härstedt
Hi internals!



Some editors can guess the domain-specific language inside heredoc, e.g. if you 
do



$query = <

Re: [PHP-DEV] RFC: Add `final class Vector` to PHP

2021-09-17 Thread Olle Härstedt
On Thu, Sep 16, 2021 at 8:10 PM tyson andre  
wrote: 
> > Hi internals, 
> 
> I've created a new RFC https://wiki.php.net/rfc/vector proposing to add 
> `final class Vector` to PHP. 
> 
> PHP's native `array` type is rare among programming language in that it is 
> used as an associative map of values, but also needs to support lists of 
> values. 
> In order to support both use cases while also providing a consistent internal 
> array HashTable API to the PHP's internals and PECLs, additional memory is 
> needed to track keys 
> (https://www.npopov.com/2014/12/22/PHPs-new-hashtable-implementation.html - 
> around twice as much as is needed to just store the values due to needing 
> space both for the string pointer and int key in a Bucket, for non-reference 
> counted values)). 
> Additionally, creating non-constant arrays will allocate space for at least 8 
> elements to make the initial resizing more efficient, potentially wasting 
> memory. 
> 
> It would be useful to have an efficient variable-length container in the 
> standard library for the following reasons: 
> 
> 1. To save memory in applications or libraries that may need to store many 
> lists of values and/or run as a CLI or embedded process for long periods of 
> time 
>(in modules identified as using the most memory or potentially exceeding 
> memory limits in the worst case) 
>(both in userland and in native code written in php-src/PECLs) 
> 2. To provide a better alternative to `ArrayObject` and `SplFixedArray` for 
> use cases 
>where objects are easier to use than arrays - e.g. variable sized 
> collections (For lists of values) that can be passed by value to be read and 
> modified. 
> 3. To give users the option of stronger runtime guarantees that property, 
> parameter, or return values really contain a list of values without gaps, 
> that array modifications don't introduce gaps or unexpected indexes, etc. 
> 
> Thoughts on Vector? 
> 
> P.S. The functionality in this proposal can be tested/tried out at 
> https://pecl.php.net/teds (under the class name `\Teds\Vector` instead of 
> `\Vector`). 
> (That is a PECL I created earlier this year for future versions of iterable 
> proposals, common data structures such as Vector/Deque, and less commonly 
> used data structures that may be of use in future work on implementing other 
> data structures) 
> 
> Thanks, 
> Tyson 
> -- 
> PHP Internals - PHP Runtime Development Mailing List 
> To unsubscribe, visit: https://www.php.net/unsub.php 
> 
 
I'm okay with a final Vector class in general. I don't love the 
proposed API but don't hate it either. Feedback on that at the end. 
 
What I would _love_ is a `vec` type from hacklang, which is similar to 
this but pass-by-value, copy-on-write like an array. Of course, this 
would require engine work and I understand it isn't as simple to add. 
 
Feedback on API: 
 
-  `indexOf` returning `false` instead of `null` when it cannot be 
found. If we are keeping this method (which I don't like, because 
there's no comparator), please return `null` instead of false. The 
language has facilities for working with null like `??`, so please 
prefer that when it isn't needed for BC (like this, this is a new 
API). 
- `contains` also doesn't have a comparator. 
-  Similarly but less strongly, I don't like the filter callable 
returning `mixed` -- please just make it `bool`. 
- I don't know what `setSize(int $size)` does. What does it do if the 
current size is less than `$size`? What about if its current size is 
greater? I suspect this is about capacity, not size, but without docs 
I am just guessing. 
 
-- 
PHP Internals - PHP Runtime Development Mailing List 
To unsubscribe, visit: https://www.php.net/unsub.php 
 





use SplFixedArray as vec;



Done. ;)



Olle

Re: [PHP-DEV] Make namespace part of runtime

2021-08-29 Thread Olle Härstedt
2021-08-29 5:12 GMT+02:00, Mike Schinkel :
>
>
>> On Aug 28, 2021, at 5:12 PM, Olle Härstedt 
>> wrote:
>>
>> 2021-08-27 23:07 GMT+02:00, Rowan Tommins > <mailto:rowan.coll...@gmail.com>>:
>>> On 27/08/2021 20:47, Olle Härstedt wrote:
>>>> As a followup for my previous post, I think this could be a good place
>>>> to start to enable attribute writers to create encapsulation mechanics
>>>> for composition, like namespace visibility, "internal" access or
>>>> friend classes.
>>>
>>>
>>> In my experience PHP projects tend to use namespace hierarchies which
>>> are deep rather than broad, and I'm not sure how easily those
>>> hierarchies could be re-purposed as scopes.
>>>
>>> Clicking through the Symfony source at random for an example, I found
>>> "namespace
>>> Symfony\Component\Messenger\Transport\Serialization\Normalizer", which
>>> contains only one class.
>>>
>>> A trivial implementation of namespace visibility which just matched the
>>> exact namespace string would be completely useless for that class (it
>>> would be the same as "private"). A slightly less trivial
>>> implementationmight allow access from "child namespaces", but that
>>> wouldn't help in this case.
>>>
>>> However, it might be really useful to restrict usage of that class, or
>>> some of its members, to classes in the "Symfony\Component\Messenger"
>>> namespace; or maybe to those in the
>>> "Symfony\Component\Messenger\Transport\Serialization" namespace.
>>>
>>> I can see two ways of enabling that:
>>>
>>> - Allowing visibility modifiers to specify exactly what level of prefix
>>> they refer to. This is apparently how Scala approaches things, allowing
>>> you to write the equivalent of "private[Symfony\Component\Messenger]
>>> $foo; protected[Symfony\Component\Messenger\Transport\Serialization]
>>> $bar;"
>>
>> Yes, I assume this is why Psalm introduced a new annotation
>> @psalm-internal , which does take such a parameter. A PHP
>> attribute can do this, _if_ it has access to runtime namespace.
>>
>>> - Introducing a separate concept of "package", either orthogonal to
>>> namespaces or overlapping with them, e.g. "package
>>> Symfony\Component\Messenger; namespace
>>> Transport\Serialization\Normalizer;" would still give a class name
>>> beginning
>>> "Symfony\Component\Messenger\Transport\Serialization\Normalizer", but
>>> would define "internal" to mean accessible within the
>>> "Symfony\Component\Messenger" package.
>>
>> What's the estimated effort for adding package support to PHP? Did
>> anyone outline a possible implementation?
>
> In case you have not seen these, which discuss possibilities but at a higher
> level than actually how to implement:
>
> https://github.com/nikic/php-rfcs/blob/language-evolution/rfcs/-language-evolution.md
> <https://github.com/nikic/php-rfcs/blob/language-evolution/rfcs/-language-evolution.md>
> https://phpinternals.news/45 <https://phpinternals.news/45>
>
> -Mike

Oh cool, thanks! So there's more support in internals for doing
package-visibility instead of namespace-visibility in the end? Or
maybe the topic is not so hot?

Olle

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



Re: [PHP-DEV] Make namespace part of runtime

2021-08-28 Thread Olle Härstedt
2021-08-27 23:07 GMT+02:00, Rowan Tommins :
> On 27/08/2021 20:47, Olle Härstedt wrote:
>> As a followup for my previous post, I think this could be a good place
>> to start to enable attribute writers to create encapsulation mechanics
>> for composition, like namespace visibility, "internal" access or
>> friend classes.
>
>
> In my experience PHP projects tend to use namespace hierarchies which
> are deep rather than broad, and I'm not sure how easily those
> hierarchies could be re-purposed as scopes.
>
> Clicking through the Symfony source at random for an example, I found
> "namespace
> Symfony\Component\Messenger\Transport\Serialization\Normalizer", which
> contains only one class.
>
> A trivial implementation of namespace visibility which just matched the
> exact namespace string would be completely useless for that class (it
> would be the same as "private"). A slightly less trivial
> implementationmight allow access from "child namespaces", but that
> wouldn't help in this case.
>
> However, it might be really useful to restrict usage of that class, or
> some of its members, to classes in the "Symfony\Component\Messenger"
> namespace; or maybe to those in the
> "Symfony\Component\Messenger\Transport\Serialization" namespace.
>
> I can see two ways of enabling that:
>
> - Allowing visibility modifiers to specify exactly what level of prefix
> they refer to. This is apparently how Scala approaches things, allowing
> you to write the equivalent of "private[Symfony\Component\Messenger]
> $foo; protected[Symfony\Component\Messenger\Transport\Serialization] $bar;"

Yes, I assume this is why Psalm introduced a new annotation
@psalm-internal , which does take such a parameter. A PHP
attribute can do this, _if_ it has access to runtime namespace.

> - Introducing a separate concept of "package", either orthogonal to
> namespaces or overlapping with them, e.g. "package
> Symfony\Component\Messenger; namespace
> Transport\Serialization\Normalizer;" would still give a class name
> beginning
> "Symfony\Component\Messenger\Transport\Serialization\Normalizer", but
> would define "internal" to mean accessible within the
> "Symfony\Component\Messenger" package.

What's the estimated effort for adding package support to PHP? Did
anyone outline a possible implementation?

Olle

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



[PHP-DEV] Make namespace part of runtime

2021-08-27 Thread Olle Härstedt
Hi,

As a followup for my previous post, I think this could be a good place
to start to enable attribute writers to create encapsulation mechanics
for composition, like namespace visibility, "internal" access or
friend classes.

There's an outline to an idea by Nikic here:
https://github.com/php/php-src/pull/947#issuecomment-224934615

> In principle this should be relatively simple: Introduce a struct 
> _zend_namespace { zend_string *name, uint32_t start; uint32_t end; } 
> structure (where start/end are opline offsets), and store an array of these 
> in the op array. Usually this array will have only a single element (or be 
> empty). Generating and storing this data should be relatively simple. The 
> most difficult part is probably adding support for this structure in the 
> opcache optimizer (particularly the block pass), but this can later be done 
> by someone else, who is familiar with the component.

The missing part is exposing it to attribute authors using a magic
constant like __NAMESPACE_RUNTIME__, reflection, or something else I
didn't think of. :)

Eventually, idiomatic attributes could be made part of the core
language as new keywords, for performance reasons (instead of
#[Internal] attribute, add an "internal" keyword, and so on).

Good idea or bad?

Olle

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



Re: [PHP-DEV] Alternatives for encapsulation when using composition instead of inheritance

2021-08-26 Thread Olle Härstedt
2021-08-26 22:20 GMT+02:00, Olle Härstedt :
> 2021-08-26 20:30 GMT+02:00, Rowan Tommins :
>> On 26/08/2021 14:47, Olle Härstedt wrote:
>>> Don't know if this already exists, but maybe we could consider
>>> brainstorming or gather alternatives for different types of
>>> encapsulation when using composition?
>>
>>
>> Although not quite equivalent to your suggestions, these threads on
>> making delegation to an encapsulated object might be interesting to you:
>>
>> *  https://externals.io/message/103353
>> * https://github.com/php/php-src/pull/5168
>
> Right, there are indeed a bunch of attempts and suggestions, some
> downvoted, others abandoned.
>
> I'm thinking adding namespaces to runtime might be a logical first
> step. That would allow attributes to add logic like internal
> properties for a certain namespace. Makes me wonder why that never
> happened for this PR: https://github.com/php/php-src/pull/947
>
> Asking anyone on the list, would it be possible to make an opcode out
> of "namespace Foo\Bar" and letting it set a flag in the runtime system
> when run? Then make the flag accessible with a constant like
> __NAMESPACE_RUNTIME__ or whatever.
>
> Ooooh, there's an interesting case with "goto" and namespace
> visibility here:
> https://github.com/php/php-src/pull/947#issuecomment-419821198
>
> That would mean every zval has to carry in which namespace it was
> defined inside. I wonder how that would affect the memory footprint of
> PHP.
>
>> If we had something like that, then perhaps there could be a
>> "delegatable" visibility, which was the equivalent for "protected", but
>> when delegating rather than inheriting, e.g.
>>
>> class Foo {
>>  private int $a = 1;
>>  delegatable int $b = 2;
>> }
>>
>> class Bar {
>>  private delegate Foo $foo;
>>  public function __construct(Foo $foo) {
>>  $this->foo = $foo;
>>  echo $this->a; // Error: can't access private property of a
>> different class
>>  echo $this->b; // allowed: access is to a "delegatable"
>> property, in a "delegated" context
>>  }
>> }
>
> The Foo class has to decide who to give access to, otherwise it's the
> same as public access.
>
> Olle

Whops, Nikic already answered this in 2016:

> The goto here will jump from code in namespace A to code in namespace B 
> without "directly" crossing the boundary. For this reason just inserting 
> opcodes when a namespace starts or ends will quite cut it.

https://github.com/php/php-src/pull/947#issuecomment-224934615

So, deprecate goto when...?

Olle

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



Re: [PHP-DEV] Alternatives for encapsulation when using composition instead of inheritance

2021-08-26 Thread Olle Härstedt
2021-08-26 20:30 GMT+02:00, Rowan Tommins :
> On 26/08/2021 14:47, Olle Härstedt wrote:
>> Don't know if this already exists, but maybe we could consider
>> brainstorming or gather alternatives for different types of
>> encapsulation when using composition?
>
>
> Although not quite equivalent to your suggestions, these threads on
> making delegation to an encapsulated object might be interesting to you:
>
> *  https://externals.io/message/103353
> * https://github.com/php/php-src/pull/5168

Right, there are indeed a bunch of attempts and suggestions, some
downvoted, others abandoned.

I'm thinking adding namespaces to runtime might be a logical first
step. That would allow attributes to add logic like internal
properties for a certain namespace. Makes me wonder why that never
happened for this PR: https://github.com/php/php-src/pull/947

Asking anyone on the list, would it be possible to make an opcode out
of "namespace Foo\Bar" and letting it set a flag in the runtime system
when run? Then make the flag accessible with a constant like
__NAMESPACE_RUNTIME__ or whatever.

Ooooh, there's an interesting case with "goto" and namespace
visibility here:
https://github.com/php/php-src/pull/947#issuecomment-419821198

That would mean every zval has to carry in which namespace it was
defined inside. I wonder how that would affect the memory footprint of
PHP.

> If we had something like that, then perhaps there could be a
> "delegatable" visibility, which was the equivalent for "protected", but
> when delegating rather than inheriting, e.g.
>
> class Foo {
>  private int $a = 1;
>  delegatable int $b = 2;
> }
>
> class Bar {
>  private delegate Foo $foo;
>  public function __construct(Foo $foo) {
>  $this->foo = $foo;
>  echo $this->a; // Error: can't access private property of a
> different class
>  echo $this->b; // allowed: access is to a "delegatable"
> property, in a "delegated" context
>  }
> }

The Foo class has to decide who to give access to, otherwise it's the
same as public access.

Olle

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



[PHP-DEV] Re: Alternatives for encapsulation when using composition instead of inheritance

2021-08-26 Thread Olle Härstedt
2021-08-26 16:20 GMT+02:00, Christoph M. Becker :
> On 26.08.2021 at 15:47, Olle Härstedt wrote:
>
>> * Friend classes, like in C++: Class B is annotated to be a friend of
>> A, so class A can see the content of class B but no other class can.
>
> <https://wiki.php.net/rfc/friend-classes> has been declined.
>
>> * Namespace private: Class A and B are defined in the same namespace,
>> so they can see each other's properties that are defined as "internal"
>
> <https://wiki.php.net/rfc/namespace-visibility> appears to be inactive.
>
> --
> Christoph M. Becker
>

Thanks! I'll check the belonging discussions on externals.io

Olle

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



[PHP-DEV] Alternatives for encapsulation when using composition instead of inheritance

2021-08-26 Thread Olle Härstedt
Hi list!

Don't know if this already exists, but maybe we could consider
brainstorming or gather alternatives for different types of
encapsulation when using composition? Currently, encapsulation like
private and protected is only possible when using inheritance - when
using composition, that is, class A is using (aggregating) class B,
your only alternative is public, so full visibility (or
getters/setters, which also is full visibility, since you can't limit
who's using those methods).

There are four alternatives at least:

* Friend classes, like in C++: Class B is annotated to be a friend of
A, so class A can see the content of class B but no other class can.
* Package private, like in Java: Class A and B are defined in the same
package, so they can see each other's fields that are defined as
"internal"
* Namespace private: Class A and B are defined in the same namespace,
so they can see each other's properties that are defined as "internal"
* Attribute for namespace private: Like above, but not possible right
now since it requires that namespace is added to the PHP runtime

Functionality like this should not be handled by static analysis,
because library authors need to be able to trust it. Psalm supports
already @internal and @psalm-internal, but of course not everyone is
using Psalm/Phpstan/other analyzer.

The problem with package private is that PHP does not have packages.

The problem with namespace private is that it cannot handle namespace
siblings. Another problem is that it can be "hacked" by client code if
the client code decides to use another vendor's namespace (a weird
thing to do, though).

The run-time hit should not be bigger, since we're already checking
each object property for private. Correct me if I'm wrong.

The risk/benefit/effort should be considered for all alternatives. I'd
argue that something is better than nothing, so far as it does not
block future work. :) Maybe adding namespaces to runtime could be a
first step?

Olle

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



Re: [PHP-DEV] RFC Implicit Async (iasync)

2021-08-09 Thread Olle Härstedt
On Mon, 9 Aug 2021, 21:41 the mschop,  wrote:

> Hi all,
>
> This is my first time writing to the internals mailing list, so please
> be patient with me. I would like to get feedback from you on the
> following idea. The idea might seem crazy at the first glance, but the
> longer I thought of it, the cooler I found the idea ;-). I would like
> to share the idea with you and receive feedback. I would currently not
> know how to implement it in the PHP lang. The only way I would be able
> to do this right now with my skill set would be to write a transpiler
> (which is not ideal), which compiles it to e.g. ReactPHP code.
>
> One of the main arguments against PHP is that PHP has a completely
> empty state at the beginning of every request. This implies that on
> every request all of the assets (e.g. configs) needs to be loaded.
> Some applications load it from the database, which makes it even
> worse. This causes slower response times than you can achieve with
> other programming languages.
>
> One way to improve this is by using libraries like ReactPHP for adding
> asynchronicity to PHP. This would enable one to load assets
> concurrently, but migrating existing code bases to asynchronous code
> would be a nightmare, so no one does it. Additionally, asynchronous
> code is harder to read and write.
>
> My suggestion is to add the iasync keyword to PHP. By using the iasync
> keyword, functions or code blocks could be marked as "eventually
> async".
>
> 'eventually async', because it should be possible to disable the
> functionality with an ini setting (especially for debugging purposes).
>
> The keyword could be used on a method level:
>
> public static iasync function doSomething() { ... }
>
> Alternatively it could be used for wrapping a code block:
>
> iasync {
> // contained code
> }
>
> All blocking IO operations in iasync context would then not return the
> actual value, but instead a promise.
> Those promises are automatically awaited in the following cases:
>
> - The variables value is accessed
> - The iasync context is left
> - A non-iasync code block is invoked
>
> Example (variable access):
>
> iasync {
>   $fileContent = file_get_contents('path'); // returns a promise
>   $arr = [$fileContent]; // not awaited, because the actual value is
> not relevant right now
>   echo($fileContent); // now the code would block, because the value is
> needed
> }
>
> Example (context left):
>
> iasync {
>   $fileContent = file_get_contents('path'); // returns a promise
> } // leaving context would block, until value available
> echo $fileContent;
>
> ###
> Promises
> ###
>
> The promises are not like promises of other languages. They are
> implicit and programmers cannot do anything with it.
>
> 
> What is the advantage of this approach?
> 
>
> Many applications could profit by iasync because it's so simple to
> use. Application performance could be greatly improved.
>
> Thank you!
>
> Best regards
> mschop
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.ph
> 


Hi,

Looks kinda similar to what Amphp does with yield and generators? Did you
check that?

Olle


Re: [PHP-DEV] [Vote] Pipe operator v2

2021-07-20 Thread Olle Härstedt
2021-07-20 11:12 GMT+02:00, Marco Pivetta :
> Hey Larry,
>
> On Sat, Jul 17, 2021 at 6:00 PM Larry Garfield 
> wrote:
>
>> Hi Marco.  Thank you for your explanation, even if I naturally disagree.
>>
>> Out of curiosity, what sort of additional
>> power/capability/flexibility/etc. would, in your mind, justify pipe or
>> similar being a native feature?  PHP has a *ton* of native features that
>> *could* be done in user space, or are simply syntax sugar, but still
>> wildly
>> popular and useful as native syntax.  What is your heuristic for that?
>>
>> (The fact that there are 3-4 user space implementations of pipe-like
>> behavior, all incompatible, is one of the reasons why I think
>> standardizing
>> it into a common core syntax *is* a good idea, though I know others
>> disagree.)
>>
>
> I think the pipe operator as a **custom** operator made sense when we had
> the entire discussion around placeholder parameters (`$$`) to be used in
> the pipeline.
>
> As a plain "chain of functions with one input parameter and one output", it
> makes little sense to have it as a custom construct, as it only adds
> complexity to the AST.

That is the idiomatic implementation, though. Hacklang is the odd man
out with $$.

Olle

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



Re: [PHP-DEV] Type casting syntax

2021-07-10 Thread Olle Härstedt
On Sat, 10 Jul 2021, 13:05 Benjamin Morel,  wrote:

> > I've been thinking about extending PHP's cast syntax to user-defined
> types,
> > e.g. not only (int)$foo but also (MyClass)$foo. Currently, a T_STRING in
> > parentheses is always treated as a constant - would it be acceptable to
> > hijack this syntax when used in unary operation context, i.e. "("
> T_STRING
> > ")" expr? If not, any other alternatives?
>
>
> Hi, I proposed something similar a while back, you might want to have a
> look at this discussion:
>
> https://externals.io/message/105332#105367
>
> - Benjamin
>

Maybe start filling the holes for built-in types? Callable...

Olle

>


Re: [PHP-DEV] [RFC] Pipe Operator, take 2

2021-07-04 Thread Olle Härstedt
2021-07-04 4:12 GMT+02:00, Larry Garfield :
> On Mon, Jun 7, 2021, at 2:00 PM, Larry Garfield wrote:
>> Hi folks. Me again.
>>
>> A year ago, I posted an RFC for a pipe operator, |>, aka function
>> concatenation.  At the time, the main thrust of the feedback was "cool,
>> like, but we need partial function application first so that the syntax
>> for callables isn't so crappy."
>>
>> The PFA RFC is winding down now and is looking quite good, so it's time
>> to revisit pipes.
>>
>> https://wiki.php.net/rfc/pipe-operator-v2
>>
>> Nothing radical has changed in the proposal since last year.  I have
>> updated it against the latest master.  I also updated the RFC to use
>> more examples that assume PFA, as the result is legit much nicer.  i
>> also tested it locally with a combined partials-and-pipes branch to
>> make sure they play nicely together, and they do.  (Yay!)  Assuming PFA
>> passes I will include those tests in the pipes branch before this one
>> goes to a vote.
>
> Hi again.
>
> With PFA being declined, I've again reworked the Pipes RFC.
>
> 1) It now does not use PFA in any examples, but it does use Nikita's
> first-class-callables RFC that looks like it's going to pass easily.
>
> 2) With major hand-holding from Levi Morrison and Joe Watkins, the
> implementation has shifted a bit.  It now evaluates left-to-right, always,
> whereas the previous version evaluated right-to-left.  That is, instead of
> $a |> $b |> $c desugaring into $c($b($a)), it now becomes effectively $tmp =
> $a; $tmp = $b($tmp); $tmp = $c($tmp);  That matters if $b or $c are function
> calls that return a callable, as they are then only called when the pipeline
> gets to that part of the expression.

Hi! Can you flesh out an example for this, please? Not sure I get the
use-case where it matters. Couldn't find any example inside the PR
either (the tests) that show-cased this particular implementation
detail. Did I miss it?

Olle

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



Re: [PHP-DEV] Re: [Vote] Partial Function Application

2021-07-01 Thread Olle Härstedt
2021-07-01 17:12 GMT+02:00, Larry Garfield :
> On Wed, Jun 16, 2021, at 11:16 AM, Larry Garfield wrote:
>> Hi folks.  The vote for the Partial Function Application RFC is now
>> open, and will run until 30 June.
>>
>> https://wiki.php.net/rfc/partial_function_application
>>
>> Of particular note, a few people had asked about using ...? instead of
>> ... for the variadic placeholder.  In the end we decided not to explore
>> that, as Nikita explained off-list it was actually more confusing, not
>> less, as it would suggest "placeholder for a variadic" rather than "a
>> placeholder that is variadic."  Otherwise, it's just more typing.  The
>> syntax choices section of the RFC has been updated accordingly.
>
>
> The vote has now closed.  The final result is:
>
> Yes; 29
> No: 20
> Percentage: 59.1%
>
> It has not passed.  Thank you everyone for your involvement.
>
> I'd like to bring this RFC back in the future in some form if either a less
> complex implementation or a stronger use case to justify the implementation
> can be found.  That would be a topic for a different thread at a different
> time.
>
> --Larry Garfield

Hi,

My personal impression is that the feedback loop between RFC authors
and voters seems a bit vague. Should the no-vote be split into "Yes,
but not like this", and "No, never"? Or maybe add a reason for the
no-vote? Like, too complex implementation, or weak use-case. I don't
know. Guessing should be reduced to a minimum, as should be wasted
effort.

I also believe the structure of the RFC itself could be more
disciplined, and collect pros and cons more clearly. Not this
particular RFC, but in general. I assume there's a scaffold being
used?

Olle

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



Re: [PHP-DEV] [Vote] Partial Function Application

2021-06-30 Thread Olle Härstedt
2021-06-30 19:10 GMT+02:00, Larry Garfield :
> On Wed, Jun 30, 2021, at 8:59 AM, Olle Härstedt wrote:
>
>>  > I've been pondering if a completely different approach with a prefix
>>  > symbol would be able to be less complex, and the simple answer is I
>>  > have absolutely no idea.  But we are running low on symbols...
>>
>>  Ah, I found the technical details that Joe gave me (right after I hit
>> send, of course).  Quoting Joe:
>>
>>  "the engine expects certain things to happen, and is designed and then
>> optimized around those assumptions ... for example, a stream of INIT,
>> SEND, DO_FCALL is not meant to be interrupted, the first fundamental
>> change you have to make is making the engine aware that stream of INIT,
>> SEND, + are not always followed by DO_FCALL "
>>
>>  So yes, it sounds like hooking into the function call process is where
>> the complexity comes from.  Which suggests that an approach that works
>> using a different syntax that desugars to a closure would avoid that
>> issue, but then we need a syntax that wouldn't be ambiguous, and that's
>> getting harder and harder to find.  (Nikita's first-class-callables RFC
>> notes some of the issues with available symbols, and they're
>> essentially the same for partials either way.)  And I've been told that
>> creating closures in the AST compiler is Hard(tm)...
>>
>>  --Larry Garfield
>>
>>
>> Wrapping stuff in lambdas is otherwise the obvious solution, no? Make
>> `strlen(?)` evaluate to `fn ($x) => strlen($x)`. Does it depend on the
>> level of look-ahead in the compiler why it's so hard? Didn't work much
>> with scripting language internals.
>>
>> Olle
>
> The tricky part is that conversion has to happen entirely at runtime,
> because we need the type information from the function being partialed, and
> at that point creating an actual closure is, apparently, rather hard.  It
> cannot be done up at the AST level where it would be conceptually much
> easier.
>
> We've been discussing this for the past several days in chat, and the basic
> conclusion is that the PHP engine does not offer any easy way to do this.
> It's one hard-and-messy approach or another hard-and-messy approach.  So far
> no one has figured out a not hard-and-messy way to make it work, regardless
> of performance.
>
> --Larry Garfield

Alright, alright. Guess I have to learn a bit more about the different
passes inside the compiler. :) Thanks.

Olle

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



[PHP-DEV] [Vote] Partial Function Application

2021-06-30 Thread Olle Härstedt
https://github.com/LimeSurvey/LimeSurvey On Wed, 30 Jun 2021 14:22:46 +0200 
Olle Härstedt <mailto:olleharst...@gmail.com> wrote 















-- Forwarded message -
From: Larry Garfield <mailto:la...@garfieldtech.com>
Date: Tue, 29 Jun 2021, 20:05
Subject: Re: [PHP-DEV] [Vote] Partial Function Application
To: php internals <mailto:internals@lists.php.net>



On Tue, Jun 29, 2021, at 1:00 PM, Larry Garfield wrote:
 > On Tue, Jun 29, 2021, at 12:30 PM, Guilliam Xavier wrote:
 > > (Extracted from the "Pipe Operator, take 2" thread)
 > > 
 > > On Tue, Jun 29, 2021 at 12:54 AM Larry Garfield 
 > > <mailto:la...@garfieldtech.com>
 > > wrote:
 > > 
 > > > On Mon, Jun 28, 2021, at 5:30 PM, Olle Härstedt wrote:
 > > >
 > > > > Would a slimmed down version have more support? How about removing the
 > > > > variadic operator, and let the user manually add the lambda for those
 > > > > cases?
 > > >
 > > > I talked with Joe about this, and the answer is no.  Most of the
 > > > complexity comes from the initial "this is a function call, oops no, 
 > > > it's a
 > > > partial call so we switch to doing that instead", which ends up 
 > > > interacting
 > > > with the engine in a lot of different places.
 > > >
 > > 
 > > Are you saying that the implementation complexity is mainly due to chosing
 > > a syntax that looks like a function call?
 > > If yes, is it also the case for the "First-class callable syntax" RFC?
 > > And does it mean that a different syntax (e.g. with a prefix operator)
 > > would result in a simpler implementation?
 > 
 > From what I understand from Joe, most of the complexity comes from 
 > producing something that isn't a closure but shares the same interface 
 > as a closure (at least that's what it would be in PHP terms), which 
 > then requires lots of special handling throughout the engine.  I don't 
 > fully understand it all myself, TBH.
 > 
 > I've been pondering if a completely different approach with a prefix 
 > symbol would be able to be less complex, and the simple answer is I 
 > have absolutely no idea.  But we are running low on symbols...
 
 Ah, I found the technical details that Joe gave me (right after I hit send, of 
course).  Quoting Joe:
 
 "the engine expects certain things to happen, and is designed and then 
optimized around those assumptions ... for example, a stream of INIT, SEND, 
DO_FCALL is not meant to be interrupted, the first fundamental change you have 
to make is making the engine aware that stream of INIT, SEND, + are not always 
followed by DO_FCALL "
 
 So yes, it sounds like hooking into the function call process is where the 
complexity comes from.  Which suggests that an approach that works using a 
different syntax that desugars to a closure would avoid that issue, but then we 
need a syntax that wouldn't be ambiguous, and that's getting harder and harder 
to find.  (Nikita's first-class-callables RFC notes some of the issues with 
available symbols, and they're essentially the same for partials either way.)  
And I've been told that creating closures in the AST compiler is Hard(tm)...
 
 --Larry Garfield






Wrapping stuff in lambdas is otherwise the obvious solution, no? Make 
`strlen(?)` evaluate to `fn ($x) => strlen($x)`. Does it depend on the level of 
look-ahead in the compiler why it's so hard? Didn't work much with scripting 
language internals.



Olle

Re: [PHP-DEV] [RFC] First-class callable syntax

2021-06-29 Thread Olle Härstedt
2021-05-20 14:48 GMT+02:00, Nikita Popov :
> Hi internals,
>
> I'd like to present an RFC for a first-class callable syntax, which is
> intended as a simpler alternative to the partial function application (PFA)
> proposal:
>
> https://wiki.php.net/rfc/first_class_callable_syntax
>
> See the Rationale section for details on how this relates to PFA. Over the
> past week, we've had a lot of discussions on how exactly PFA is supposed to
> work (most of them OTR), and while we seem to have a tentative consensus on
> the correct model to use (which does not match the current RFC), it's clear
> that this feature has turned out more complicated than originally
> anticipated. Joe (who provided the implementation for the PFA RFC) is also
> concerned about the implementation complexity that the final model would
> require.
>
> At least I personally was mainly interested in PFA because it provides a
> first-class callable syntax as a side-effect. This RFC goes back to
> providing *just* that. The syntax is forward-compatible with a future PFA
> proposal though.
>
> Regards,
> Nikita

More bikeshedding, sorry. Was a syntax using `fn` considered? Like

$fn = Closure::fromCallable('strlen');
$fn = fn strlen;

or

$fn = (fn) strlen;

Olle

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



Re: [PHP-DEV] [RFC] Pipe Operator, take 2

2021-06-29 Thread Olle Härstedt
2021-06-29 0:54 GMT+02:00, Larry Garfield :
> On Mon, Jun 28, 2021, at 5:30 PM, Olle Härstedt wrote:
>
>> Mm. Assoc arrays are by now known to be not so good. I hope...
>
> There are millions of PHP sites build on anonymous arrays today.
>
>> OCaml is strictly evaluated, not lazy like Haskell. So the order might
>> matter, dunno, I don't use this operator often. :) My point was mostly
>> that it's very easy to add in OCaml - just one line. And as in
>> Haskell, you can define operators in your modules. Similarly, in PHP
>> it's easy to do super-dynamic stuff like "new $someclass", which is
>> not remotely possible in FP (good or bad, depending on your religion).
>>
>> Adding a new pipe keyword is like the list() keyword, kind of. A bad
>> idea, haha. But I think all stones can be turned, if this RFC now gets
>> a no. :/
>>
>> Would a slimmed down version have more support? How about removing the
>> variadic operator, and let the user manually add the lambda for those
>> cases? Could reduce the complexity while still covering maybe 80% of
>> the use-cases? Same with removing support for named arguments. So '?'
>> would only be a short-cut to get rid of boilerplate like `$strlen =
>> fn($x) => strlen($x)`.
>
> I talked with Joe about this, and the answer is no.  Most of the complexity
> comes from the initial "this is a function call, oops no, it's a partial
> call so we switch to doing that instead", which ends up interacting with the
> engine in a lot of different places.  Once you've done that, supporting one
> placeholder or multiple, variadics or not, etc. is only a small incremental
> increase in complexity.
>
>> > Overall, I really don't like the idea of special-casing pipes to change
>> > what
>> > symbol table gets looked up.
>>
>> Still wondering if this could be a per-file or per-library setting
>> somehow, to opt-in into pipe behaviour when so desired. Or rather, to
>> opt-in into this or that behaviour needed to do more idiomatic pipe.
>>
>> Here's one boilerplaty pipe:
>
> *snip*
>
> We're in the pipe thread here, not PFA. :-)  And really, you're solving the
> wrong problem.  Pipes are trivial.  They're only clunky because of PHP's
> lack of decent callable syntax.  PFA gives us that, but the engine makes the
> implementation more complex than it seems like at first glance.
>
> Trying to come up with complex workarounds to make pipes pretty without
> helping anything else is a fool's errand, especially when we have a working
> PFA RFC that's about to end voting.  (And right now is losing by a very slim
> margin, but could pass if a few people change their minds.)
>
> Aside from something like Nikita's ...-only function reference RFC, which
> only handles half the problem (it doesn't do anything to make multi-arg
> functions work with pipes at all), any other solution is going to end up
> reinventing PFA one way or another, or reinventing existing ugly user-space
> libraries. one way or another
>
> I've not yet decided if I'm going to bring pipes to a vote if PFA doesn't
> pass.  I'm tempted to, but it would require rewriting all the RFC text back
> to the uglier version without PFA, and yeah, it's not going to look as
> pretty.  And the main pushback a year ago when I first brought it up was
> "PFA first, please, so the callable syntax isn't ugly."  And... here we
> are.
>
> --Larry Garfield

Is there no "pre-vote" process for RFCs? For example, letting the
voting members *rate* different alternatives, in a ranking fashion, to
see which one is most and least popular. Feels like a lot of work is
getting wasted if something is voted down on a small margin.

Olle

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



Re: [PHP-DEV] [RFC] Pipe Operator, take 2

2021-06-28 Thread Olle Härstedt
> I talked with Joe about this, and the answer is no.  Most of the complexity
> comes from the initial "this is a function call, oops no, it's a partial
> call so we switch to doing that instead", which ends up interacting with the
> engine in a lot of different places.  Once you've done that, supporting one
> placeholder or multiple, variadics or not, etc. is only a small incremental
> increase in complexity.

Hm, I was thinking more about the conceptual complexity, not the
implementation, but seems like the argument "cover all expected
use-cases" was used too. :) So no half-measures...

Thanks for your feedback.

Olle

>> > Overall, I really don't like the idea of special-casing pipes to change
>> > what
>> > symbol table gets looked up.
>>
>> Still wondering if this could be a per-file or per-library setting
>> somehow, to opt-in into pipe behaviour when so desired. Or rather, to
>> opt-in into this or that behaviour needed to do more idiomatic pipe.
>>
>> Here's one boilerplaty pipe:
>
> *snip*
>
> We're in the pipe thread here, not PFA. :-)  And really, you're solving the
> wrong problem.  Pipes are trivial.  They're only clunky because of PHP's
> lack of decent callable syntax.  PFA gives us that, but the engine makes the
> implementation more complex than it seems like at first glance.
>
> Trying to come up with complex workarounds to make pipes pretty without
> helping anything else is a fool's errand, especially when we have a working
> PFA RFC that's about to end voting.  (And right now is losing by a very slim
> margin, but could pass if a few people change their minds.)
>
> Aside from something like Nikita's ...-only function reference RFC, which
> only handles half the problem (it doesn't do anything to make multi-arg
> functions work with pipes at all), any other solution is going to end up
> reinventing PFA one way or another, or reinventing existing ugly user-space
> libraries. one way or another
>
> I've not yet decided if I'm going to bring pipes to a vote if PFA doesn't
> pass.  I'm tempted to, but it would require rewriting all the RFC text back
> to the uglier version without PFA, and yeah, it's not going to look as
> pretty.  And the main pushback a year ago when I first brought it up was
> "PFA first, please, so the callable syntax isn't ugly."  And... here we
> are.
>
> --Larry Garfield

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



Re: [PHP-DEV] [RFC] Pipe Operator, take 2

2021-06-28 Thread Olle Härstedt
2021-06-29 0:06 GMT+02:00, Rowan Tommins :
> On 28/06/2021 21:28, Olle Härstedt wrote:
>> Sorry for hijacking the thread, but are there no other alternatives,
>> really? Just brainstorming:
>>
>> 1) Setting to silence the warning.
>
>
> Just to reiterate: in PHP 8.0, an undefined constant is not a warning,
> it's an error. My apologies to code golfers: you can no longer save two
> bytes by leaving the quote marks off your strings.
>
> However, that's not really the problem. The problem is when there *is* a
> constant with that name:
>
> const foo='strtoupper';
> function foo($x) { return 'test'; }
> $input = ['hello', 'world'];
> var_dump( array_map(foo, $input) ); // this runs strtoupper(), not foo()
>
> This doesn't work even in old versions of PHP where undefined constants
> fell back to strings.
>
> Even in cases where this trick did work in older versions of PHP, it was
> just a variant of option one, "use our current ugly callable syntax" -
> it saved you those two bytes, but it didn't actually provide you a
> function reference.
>
> Unifying the constant and function name tables would not be to just a
> different way of writing strings, it would let array_map(foo, $input)
> actually check that function foo existed, and represent callables as a
> proper type. Meanwhile, to let array_map($object->foo, $input) do the
> same thing (instead of the current [$object, 'foo'] syntax) you also
> need to unify the method and property tables, which is probably even
> harder.
>
>
>
>> 2) Setting to silence the warning IF and only if argument expects a
>> callable, like in array_map (won't work with a pipe() function,
>> though, since pipe() would take any number of arguments and that can't
>> be typed)
>
>
> In the general case, this is a non-starter: the parameters need to be
> parsed from the source code before function definitions are even known.
> You could special-case a handful of built-in functions, but that would
> be extremely clunky.
>
>
>
>> 3) Silence the warning if you type-case explicitly, like in
>> `pipe($start, (callable) htmlentities);`. Another alternative is
>> `(fn)` as a type-cast. Not much better than `pipe($start,
>> htmlentities(?))`, I guess. Just different style.
>
>
> This falls into my third option: "add a dedicated callable syntax". That
> could be something that looks a bit like PFA but isn't, like Nikita's
> RFC; or something that looks a bit like a type cast; or any number of
> other ideas which have been brainstormed for about as long as I've been
> programming PHP.
>
>
>> 4) Silence the warning ONLY when it's the right-hand argument to pipe
>> operator, like `$start |> str_len`.
>
>
> Re-wording this as "interpret the unquoted word as a function reference
> rather than a constant when...", this one is at least plausible. In
> practice, though, a lot of functions don't take only one parameter, so
> the previous pipe proposal included a placeholder for which argument you
> wanted to "pipe into". At which point you don't need to special case
> keywords, because you can just write this:
>
> $start |> str_len($$)

True. I wish we had numbers for how common the case is when you DON'T
want to pipe into the first argument. If it's rare enough, it might be
worth it to let the rare cases be dealt with by writing manual
lambdas. So allow some boilerplate. Another alternative would be to
add both '?' and parsing unquoted string as function reference
together with pipe operator, but start with the simple one (whichever
that is, I wouldn't know). Or start with the one that has chance of
being accepted by the voters. :)

> Regards,
>
> --
> Rowan Tommins
> [IMSoP]

Thanks for your explanations!

Olle

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



Re: [PHP-DEV] [RFC] Pipe Operator, take 2

2021-06-28 Thread Olle Härstedt
2021-06-28 23:36 GMT+02:00, Larry Garfield :
> On Mon, Jun 28, 2021, at 3:42 PM, Olle Härstedt wrote:
>> 2021-06-28 22:12 GMT+02:00, Larry Garfield :
>> > On Mon, Jun 28, 2021, at 3:04 PM, Rowan Tommins wrote:
>> >> On 28/06/2021 20:25, Olle Härstedt wrote:
>> >> > Usage (ignoring the pesky undefined constant warnings ><):
>> >>
>> >>
>> >> Unfortunately, you can't ignore those warnings; not least because
>> >> they're fatal errors in PHP 8, as they frankly should have been in PHP
>> >> 3.
>> >>
>> >> You can use our current ugly callable syntax (strings and two-element
>> >> arrays); you can tackle the complexity of unifying functions with
>> >> constants, and methods with properties (as Levi explained in the other
>> >> thread); or you can add a dedicated callable syntax, which the PFA
>> >> proposal gets us with bells on.
>> >>
>> >> Regards,
>> >
>> > I think that's a pretty good summary.  There's nothing that pipes or
>> > partials do that you couldn't emulate in user-space today (really, since
>> > 5.3
>> > is you really wanted to).  The emulation is just butt-ugly and slower,
>> > which
>> > is why most people don't do it except in very specific cases or if they
>> > have
>> > a user-space library available that makes it slightly less butt-ugly.
>> >
>> > The purpose of PFA and pipes (and short functions, and auto-capture
>> > closures, and basically everything else I've been talking about all
>> > year) is
>> > to make those things prettier and as fast as reasonable, which makes
>> > using
>> > those techniques more natural.  Once you start down that path, though,
>> > there's really no usable solution before you get down as far as... PFA
>> > and
>> > Pipes in their current form.
>> >
>> > --Larry Garfield
>>
>> The challenge is to write something that's pretty enough to be
>> considered idiomatic. :) The pipe operator in OCaml is defined by one
>> line:
>>
>> let (|>) v f = f v
>>
>> It wasn't always part of core, but eventually it was so common, it got
>> included by default. Same could happen with a pipe() function in PHP,
>> without the pipe operator, or that the function becomes so common, a
>> new keyword is added instead: `pipe`. But it could probably not happen
>> with a Pipe object requiring you to write ->pipe() at every step -
>> it's too much ceremony and boilerplate.
>>
>> By the way, that's alternative 5) New keyword `pipe` to make the
>> warning about constants shut up in a certain scope. Plus some other
>> magic to allow nice chaining. ^^
>>
>> Olle
>
> "Idiomatic PHP" consists primarily of associative arrays, used in ways no
> sane person would ever use a dictionary, but the code is in a method so it
> gets called OOP even though it's barely procedural.
>
> That's not an idiom I have any interest in supporting, and have in fact made
> a career out of training people out of. :-)
>
> There are *already* libraries that let you write ->pipe().  The PHP League
> has one, for instance:
>
> https://github.com/thephpleague/pipeline
>
> I've seen others, but they're no less ugly and offer no better migration
> path into a core syntax.  PHP is just not designed as a user-extensible
> language.  (cf, "Growing a Language" by Guy Steele, one of the best
> presentations ever given: https://www.youtube.com/watch?v=_ahvzDzKdB0)
>
> Also of note, the OCaml definition there is almost exactly the same as the
> current patch; there's a request out I'm working on now to change the
> implementation to ensure that the LHS is fully evaluated before the RHS, but
> it's interesting to see that OCaml's version does have the out-of-order
> challenge.  (Although in a functional language it's semantically a
> meaningless difference, by design.)
>
> Overall, I really don't like the idea of special-casing pipes to change what
> symbol table gets looked up.  That's just asking for edge cases to bite us
> later, especially when the root problem isn't with pipes in the first place;
> it's with PHP lacking either a function-reference syntax or PFA (which gives
> us a function-reference syntax for free).  Fix the real problem, don't hack
> around it in what should be a very simple feature.
>
> --Larry Garfield

Mm. Assoc arrays are by now known to be not so 

Re: [PHP-DEV] [RFC] Pipe Operator, take 2

2021-06-28 Thread Olle Härstedt
2021-06-28 22:12 GMT+02:00, Larry Garfield :
> On Mon, Jun 28, 2021, at 3:04 PM, Rowan Tommins wrote:
>> On 28/06/2021 20:25, Olle Härstedt wrote:
>> > Usage (ignoring the pesky undefined constant warnings ><):
>>
>>
>> Unfortunately, you can't ignore those warnings; not least because
>> they're fatal errors in PHP 8, as they frankly should have been in PHP 3.
>>
>> You can use our current ugly callable syntax (strings and two-element
>> arrays); you can tackle the complexity of unifying functions with
>> constants, and methods with properties (as Levi explained in the other
>> thread); or you can add a dedicated callable syntax, which the PFA
>> proposal gets us with bells on.
>>
>> Regards,
>
> I think that's a pretty good summary.  There's nothing that pipes or
> partials do that you couldn't emulate in user-space today (really, since 5.3
> is you really wanted to).  The emulation is just butt-ugly and slower, which
> is why most people don't do it except in very specific cases or if they have
> a user-space library available that makes it slightly less butt-ugly.
>
> The purpose of PFA and pipes (and short functions, and auto-capture
> closures, and basically everything else I've been talking about all year) is
> to make those things prettier and as fast as reasonable, which makes using
> those techniques more natural.  Once you start down that path, though,
> there's really no usable solution before you get down as far as... PFA and
> Pipes in their current form.
>
> --Larry Garfield

The challenge is to write something that's pretty enough to be
considered idiomatic. :) The pipe operator in OCaml is defined by one
line:

let (|>) v f = f v

It wasn't always part of core, but eventually it was so common, it got
included by default. Same could happen with a pipe() function in PHP,
without the pipe operator, or that the function becomes so common, a
new keyword is added instead: `pipe`. But it could probably not happen
with a Pipe object requiring you to write ->pipe() at every step -
it's too much ceremony and boilerplate.

By the way, that's alternative 5) New keyword `pipe` to make the
warning about constants shut up in a certain scope. Plus some other
magic to allow nice chaining. ^^

Olle

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



Re: [PHP-DEV] [RFC] Pipe Operator, take 2

2021-06-28 Thread Olle Härstedt
2021-06-28 22:04 GMT+02:00, Rowan Tommins :
> On 28/06/2021 20:25, Olle Härstedt wrote:
>> Usage (ignoring the pesky undefined constant warnings ><):
>
>
> Unfortunately, you can't ignore those warnings; not least because
> they're fatal errors in PHP 8, as they frankly should have been in PHP 3.
>
> You can use our current ugly callable syntax (strings and two-element
> arrays); you can tackle the complexity of unifying functions with
> constants, and methods with properties (as Levi explained in the other
> thread); or you can add a dedicated callable syntax, which the PFA
> proposal gets us with bells on.

Sorry for hijacking the thread, but are there no other alternatives,
really? Just brainstorming:

1) Setting to silence the warning. Probably frowned upon, AND requires
that functions/methods are case sensitive, which they are not right
now. BUT, constants are always case sensitive since 7.3, so the risk
of collision is not that high...? Assuming constants are by convention
always UPPER_CASE, and functions either snake_case or camelCase. You
can argue that the setting together with a CI to check cases would be
reasonably safe.

2) Setting to silence the warning IF and only if argument expects a
callable, like in array_map (won't work with a pipe() function,
though, since pipe() would take any number of arguments and that can't
be typed)

3) Silence the warning if you type-case explicitly, like in
`pipe($start, (callable) htmlentities);`. Another alternative is
`(fn)` as a type-cast. Not much better than `pipe($start,
htmlentities(?))`, I guess. Just different style.

4) Silence the warning ONLY when it's the right-hand argument to pipe
operator, like `$start |> str_len`.

All stupid?

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



Re: [PHP-DEV] [RFC] Pipe Operator, take 2

2021-06-28 Thread Olle Härstedt
2021-06-07 21:00 GMT+02:00, Larry Garfield :
> Hi folks. Me again.
>
> A year ago, I posted an RFC for a pipe operator, |>, aka function
> concatenation.  At the time, the main thrust of the feedback was "cool,
> like, but we need partial function application first so that the syntax for
> callables isn't so crappy."
>
> The PFA RFC is winding down now and is looking quite good, so it's time to
> revisit pipes.
>
> https://wiki.php.net/rfc/pipe-operator-v2
>
> Nothing radical has changed in the proposal since last year.  I have updated
> it against the latest master.  I also updated the RFC to use more examples
> that assume PFA, as the result is legit much nicer.  i also tested it
> locally with a combined partials-and-pipes branch to make sure they play
> nicely together, and they do.  (Yay!)  Assuming PFA passes I will include
> those tests in the pipes branch before this one goes to a vote.
>
> --
>   Larry Garfield
>   la...@garfieldtech.com
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php

Hi ho,

Has it been discussed the difference between the pipe operator and a
simple pipe function? Something like

function pipe() {
$args = func_get_args();
$result = $args[0];
$functions = array_slice($args, 1);
foreach ($functions as $function) {
$result = $function($result);
}
return $result;
}

Usage (ignoring the pesky undefined constant warnings ><):

$result = pipe(
"Hello world",
htmlentities,
str_split,
fn ($x) => array_map(strtoupper, $x),
fn ($x) => array_filter($x, fn ($v) => $v !== 'O')
);

There's also pipe operator with object, but that's obviously too
verbose compared to the operator
(https://github.com/sebastiaanluca/php-pipe-operator).

Olle

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



Re: [PHP-DEV] [Vote] Partial Function Application

2021-06-28 Thread Olle Härstedt
On Mon, 28 Jun 2021, 18:49 Levi Morrison, 
wrote:

> On Mon, Jun 28, 2021 at 10:32 AM Olle Härstedt 
> wrote:
> >
> > On Thu, 24 Jun 2021, 18:02 Larry Garfield, 
> wrote:
> >
> > > On Wed, Jun 16, 2021, at 11:16 AM, Larry Garfield wrote:
> > > > Hi folks.  The vote for the Partial Function Application RFC is now
> > > > open, and will run until 30 June.
> > > >
> > > > https://wiki.php.net/rfc/partial_function_application
> > > >
> > > > Of particular note, a few people had asked about using ...? instead
> of
> > > > ... for the variadic placeholder.  In the end we decided not to
> explore
> > > > that, as Nikita explained off-list it was actually more confusing,
> not
> > > > less, as it would suggest "placeholder for a variadic" rather than "a
> > > > placeholder that is variadic."  Otherwise, it's just more typing.
> The
> > > > syntax choices section of the RFC has been updated accordingly.
> > >
> > > Since some people still don't grok the use cases, I've written a blog
> post
> > > to make the case for them better than a detail-oriented RFC can.
> > >
> > >
> https://peakd.com/hive-168588/@crell/the-case-for-partials-and-pipes-in-php
> > >
> > > There has also been some positive Twitter chatter, as well as the
> level of
> > > +1s on that post (which is, I think, the highest of any PHP post I've
> had
> > > on there, ever), so I think the demand for it is definitely there in
> the
> > > ecosystem.  It's just not people who frequent Internals. :-/
> > >
> > > I'd say there are definitely people that want to use partials.
> > >
> > > --Larry Garfield
> > >
> > > --
> > > PHP Internals - PHP Runtime Development Mailing List
> > > To unsubscribe, visit: https://www.php.net/unsub.php
> >
> >
> > Out of curiosity, what would it take to implement function aliasing in
> PHP?
> > To enable a limited form of pipes, like `foo |> bar`.
> >
> > Olle
>
> We probably could special case it for pipes; it's more of a matter if
> we _should_. But, to do it generally so that things like
> `array_map(strlen, $arr)` work is not trivial. The main issue is that
> different symbol types have separate "tables", if you will. The engine
> decides to look in one bucket or another based on the syntax. In this
> case, based on syntax the engine will look in the constant table for
> `strlen`, as `strlen` in `array_map(strlen, $arr)` is a constant
> lookup by syntax.
>
> If we want it to fall-back to looking in other tables, then we'd have
> to deal with various challenges:
>  1. We have to deal with symbol collisions that exist today somehow,
> such as if `strlen` exists both as a function and a constant, or if
> `$this->count` exists as both a property and a method. I would prefer
> to do the simple thing and forbid collisions, but there are other
> strategies.
>  2. How do we handle the fact that different symbol types behave
> differently in namespaces when the symbol doesn't exist?
>  3. Also, how do we handle differences in case sensitivity between symbol
> types?
>
> Personally, I think it's worth it to change all of these things,
> because it could also give us function and constant autoloading. Of
> course, we'd have to get 2/3 of voters to agree on solutions to these
> things, which probably includes some backward-compatibility breaks so
> that might be difficult. But, nobody has tried so maybe not.
>

Right. So you'd have to add a resolve sympol type routine, and if it
returns "this is a function/method", strlen would evaluate to be wrapped in
a lambda? Then the problem would be the overall performance cost of such a
routine, and to deal with collisions, as you said. Hm.

Well, couldn't another alternative be that pipe operator assumes a callable
it can wrap on its right side? This wouldn't allow the array map use case,
but it would allow others. A third alternative would be to type-cast to
callable, perhaps.

array_map((callable) strlen, $arr);

This would be a shorter version of manually writing out the wrapping
lambda. But there's already fn, so. No big benefit.

Olle


Re: [PHP-DEV] [Vote] Partial Function Application

2021-06-28 Thread Olle Härstedt
On Thu, 24 Jun 2021, 18:02 Larry Garfield,  wrote:

> On Wed, Jun 16, 2021, at 11:16 AM, Larry Garfield wrote:
> > Hi folks.  The vote for the Partial Function Application RFC is now
> > open, and will run until 30 June.
> >
> > https://wiki.php.net/rfc/partial_function_application
> >
> > Of particular note, a few people had asked about using ...? instead of
> > ... for the variadic placeholder.  In the end we decided not to explore
> > that, as Nikita explained off-list it was actually more confusing, not
> > less, as it would suggest "placeholder for a variadic" rather than "a
> > placeholder that is variadic."  Otherwise, it's just more typing.  The
> > syntax choices section of the RFC has been updated accordingly.
>
> Since some people still don't grok the use cases, I've written a blog post
> to make the case for them better than a detail-oriented RFC can.
>
> https://peakd.com/hive-168588/@crell/the-case-for-partials-and-pipes-in-php
>
> There has also been some positive Twitter chatter, as well as the level of
> +1s on that post (which is, I think, the highest of any PHP post I've had
> on there, ever), so I think the demand for it is definitely there in the
> ecosystem.  It's just not people who frequent Internals. :-/
>
> I'd say there are definitely people that want to use partials.
>
> --Larry Garfield
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php


Out of curiosity, what would it take to implement function aliasing in PHP?
To enable a limited form of pipes, like `foo |> bar`.

Olle


Re: [PHP-DEV] [RFC] Property accessors

2021-05-04 Thread Olle Härstedt
2021-05-04 12:33 GMT+02:00, Nikita Popov :
> Hi internals,
>
> I'd like to present an RFC for property accessors:
> https://wiki.php.net/rfc/property_accessors
>
> Property accessors are like __get() and __set(), but for a single property.
> They also support read-only properties and properties with asymmetric
> visibility (public read, private write) as a side-effect.
>
> The proposal is modeled after C#-style accessors (also used by Swift), and
> syntactically similar to the previous
> https://wiki.php.net/rfc/propertygetsetsyntax-v1.2 proposal.
>
> While I put a lot of effort into both the proposal and the implementation,
> I've grown increasingly uncertain that this is the right direction for us
> to take. The proposal turned out to be significantly more complex than I
> originally anticipated (despite reducing the scope to only "get" and "set"
> accessors), and I'm sure there are some interactions I still haven't
> accounted for. I'm not convinced the value justifies the complexity.
>
> So, while I'm putting this up for discussion, it may be that I will not
> pursue landing it. I think a lot of the practical value of this accessors
> proposal would be captured by support for read-only (and/or private-write)
> properties. This has been discussed (and declined) in the past, but
> probably should be revisited.
>
> Regards,
> Nikita
>

Is this a typo?

get() {}   // Must not have parameter list

But there are no parameters...?

Olle

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



Re: [PHP-DEV] [RFC] Property accessors

2021-05-04 Thread Olle Härstedt
2021-05-04 15:57 GMT+02:00, Olle Härstedt :
> 2021-05-04 12:33 GMT+02:00, Nikita Popov :
>> Hi internals,
>>
>> I'd like to present an RFC for property accessors:
>> https://wiki.php.net/rfc/property_accessors
>>
>> Property accessors are like __get() and __set(), but for a single
>> property.
>> They also support read-only properties and properties with asymmetric
>> visibility (public read, private write) as a side-effect.
>>
>> The proposal is modeled after C#-style accessors (also used by Swift),
>> and
>> syntactically similar to the previous
>> https://wiki.php.net/rfc/propertygetsetsyntax-v1.2 proposal.
>>
>> While I put a lot of effort into both the proposal and the
>> implementation,
>> I've grown increasingly uncertain that this is the right direction for us
>> to take. The proposal turned out to be significantly more complex than I
>> originally anticipated (despite reducing the scope to only "get" and
>> "set"
>> accessors), and I'm sure there are some interactions I still haven't
>> accounted for. I'm not convinced the value justifies the complexity.
>>
>> So, while I'm putting this up for discussion, it may be that I will not
>> pursue landing it. I think a lot of the practical value of this accessors
>> proposal would be captured by support for read-only (and/or
>> private-write)
>> properties. This has been discussed (and declined) in the past, but
>> probably should be revisited.
>>
>> Regards,
>> Nikita
>>
>
> Hi,
>
> In general I'm no fan of trivial getters and setters at all in OOP. I
> think a better solution is provided by:
>
> * readonly properties (or write-once, in the constructor)
> * namespace- or package-internal accessing; "internal" as an
> alternative to public/private
>
> Especially when getters and setters do not upheld any particular
> invariants or check validation.
>
> Note that namespace-internal access cannot be provided by getters and
> setters (though technically it's a big and hard change to PHP, AFAIK).
>
> Olle

Or maybe I shouldn't be a complete idiot and actually carefully read
the RFC before any knee-jerk reaction. Disregard.

Olle

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



Re: [PHP-DEV] [RFC] Property accessors

2021-05-04 Thread Olle Härstedt
2021-05-04 12:33 GMT+02:00, Nikita Popov :
> Hi internals,
>
> I'd like to present an RFC for property accessors:
> https://wiki.php.net/rfc/property_accessors
>
> Property accessors are like __get() and __set(), but for a single property.
> They also support read-only properties and properties with asymmetric
> visibility (public read, private write) as a side-effect.
>
> The proposal is modeled after C#-style accessors (also used by Swift), and
> syntactically similar to the previous
> https://wiki.php.net/rfc/propertygetsetsyntax-v1.2 proposal.
>
> While I put a lot of effort into both the proposal and the implementation,
> I've grown increasingly uncertain that this is the right direction for us
> to take. The proposal turned out to be significantly more complex than I
> originally anticipated (despite reducing the scope to only "get" and "set"
> accessors), and I'm sure there are some interactions I still haven't
> accounted for. I'm not convinced the value justifies the complexity.
>
> So, while I'm putting this up for discussion, it may be that I will not
> pursue landing it. I think a lot of the practical value of this accessors
> proposal would be captured by support for read-only (and/or private-write)
> properties. This has been discussed (and declined) in the past, but
> probably should be revisited.
>
> Regards,
> Nikita
>

Hi,

In general I'm no fan of trivial getters and setters at all in OOP. I
think a better solution is provided by:

* readonly properties (or write-once, in the constructor)
* namespace- or package-internal accessing; "internal" as an
alternative to public/private

Especially when getters and setters do not upheld any particular
invariants or check validation.

Note that namespace-internal access cannot be provided by getters and
setters (though technically it's a big and hard change to PHP, AFAIK).

Olle

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



Re: [PHP-DEV] [RFC][Draft] Sealed Classes

2021-04-27 Thread Olle Härstedt
2021-04-27 20:17 GMT+02:00, Chase Peeler :
> On Tue, Apr 27, 2021 at 1:56 PM Levi Morrison via internals <
> internals@lists.php.net> wrote:
>
>> I think the conversation on final classes being "bad" has gone on long
>> enough. You don't like final, and you don't want to see more features
>> like it being added, such as sealed. Point taken. Now please stop
>> dominating the discussion, thank you.
>>
>>
> I think the legitimacy of final/sealed classes goes to the heart of this
> RFC. As long as people are going to discuss it and bring up counter points,
> then I think asking someone to stop defending their view is a bit out of
> line.
>
> That being said, David has never said he is against developers being able
> to annotate their classes as being final or sealed. He is just against the
> engine enforcing such requirements. On this I agree. I understand that
> other languages support this concept - and frankly, I don't care. The
> flexibility that PHP offers has always been one of its greatest strengths
> and this just further erodes that.
>
>
>> --
>> PHP Internals - PHP Runtime Development Mailing List
>> To unsubscribe, visit: https://www.php.net/unsub.php
>>
>>
>
> --
> Chase Peeler
> chasepee...@gmail.com
>

Sometimes it's helpful to apply a risk perspective the shed some light
under hidden assumptions of different arguments. For example, what's
the probability and impact of an event that would limit a coder when a
library is using a sealed class? And the other way around, what's the
probability and impact of an event that would decrease code quality
when a sealed class is *not* used (like being able to subclass
Maybe/Option even when it "shouldn't" be possible)?

If the probability of such an event is high, but the impact to overall
code quality is low, the risk is also considered low. (Example: Just
create your own Maybe class. Of course harder with more elaborate
classes, you don't want to copy-paste an entire library. And the other
way, extending Maybe is a very local thing to do and doesn't hurt the
library itself.)

When both probability and impact are uncertain, it will make it harder
to create consensus, and will make arguments more emotional or
heuristic. When risk is low and the benefit high (and clear),
consensus is easy.

Olle

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



Re: [PHP-DEV] [RFC][Draft] Sealed Classes

2021-04-26 Thread Olle Härstedt
2021-04-26 9:37 GMT+02:00, Pierre :
> Le 26/04/2021 à 09:35, Olle Härstedt a écrit :
>> 2021-04-26 9:22 GMT+02:00, Pierre :
>>> Le 25/04/2021 à 21:22, Larry Garfield a écrit :
>>>> Stitching together 2 replies to minimize thread noise...
>>>>
>>>> On Sun, Apr 25, 2021, at 11:58 AM, Michał Marcin Brzuchalski wrote:
>>>>
>>>>> Speaking of Attributes I prefer not to use an Attribute for any
>>>>> particular
>>>>> language feature which expects input arguments to be a valid class or
>>>>> interface name for two reasons: first because there is no effective
>>>>> way
>>>>> to
>>>>> restrict input string to be a valid class or interface name and second
>>>>> that
>>>>> it'd require passing strings which means in most cases passing class
>>>>> or
>>>>> interface name with magic ::class constant read.
>>>>>
>>>>> Cheers,
>>>>> Michał Marcin Brzuchalski
>>>> That's actually a pretty solid argument against attributes here,
>>>> honestly.
>>>>   Consider me convinced, and now in favor of "final class Foo permits
>>>> Bar,
>>>> Baz". :-)
>>>>
>>> Yes, even though I was the first mail suggesting it in the beginning,
>>> this is a solid argument which actually do change my mind.
>>>
>>> In the end, I like the `class Foo permis Bar, Baz` syntax, with a single
>>> keyword added.
>>>
>>> --
>>>
>>> Pierre
>>>
>>> --
>>> PHP Internals - PHP Runtime Development Mailing List
>>> To unsubscribe, visit: https://www.php.net/unsub.php
>>>
>>>
>> Is there actually a bug that this functionality can/could prevent? I
>> get that Maybe and Result types should be closed, but what are the
>> risk of software defects if someone abuses that fact (locally)?
>
> I don't know if you replied to the right mail, I should have specified I
> was talking about using an attribute versus adding a new keyword to the
> language.

Sorry, I was replying to the thread in general, not your reply
specifically. ^^ Maybe I should have replied to the top mail instead,
sorry.

Olle

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



Re: [PHP-DEV] [RFC] Partial function application

2021-04-26 Thread Olle Härstedt
2021-04-26 0:19 GMT+02:00, Larry Garfield :
> On Sun, Apr 25, 2021, at 4:34 PM, Olle Härstedt wrote:
>
>
>> By the way, for pipe operators to be really useful, it should probably
>> be possible to combine with middleware.
>>
>> Olle
>
> Pipes are their own RFC I plan to bring back up after this one gets closer
> to a vote or passes, as they complement each other nicely.  I'm not sure
> what you mean here, though.  Pipes *are* a middleware style, just a
> different approach than the deeply nested call stack that is typical today.
>
> --Larry Garfield

I was thinking of middleware as defined in PSR (since that's what
middleware frameworks are built on). Would be nice with a connection
there.

Olle

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



Re: [PHP-DEV] [RFC][Draft] Sealed Classes

2021-04-26 Thread Olle Härstedt
2021-04-26 9:22 GMT+02:00, Pierre :
> Le 25/04/2021 à 21:22, Larry Garfield a écrit :
>> Stitching together 2 replies to minimize thread noise...
>>
>> On Sun, Apr 25, 2021, at 11:58 AM, Michał Marcin Brzuchalski wrote:
>>
>>> Speaking of Attributes I prefer not to use an Attribute for any
>>> particular
>>> language feature which expects input arguments to be a valid class or
>>> interface name for two reasons: first because there is no effective way
>>> to
>>> restrict input string to be a valid class or interface name and second
>>> that
>>> it'd require passing strings which means in most cases passing class or
>>> interface name with magic ::class constant read.
>>>
>>> Cheers,
>>> Michał Marcin Brzuchalski
>> That's actually a pretty solid argument against attributes here, honestly.
>>  Consider me convinced, and now in favor of "final class Foo permits Bar,
>> Baz". :-)
>>
> Yes, even though I was the first mail suggesting it in the beginning,
> this is a solid argument which actually do change my mind.
>
> In the end, I like the `class Foo permis Bar, Baz` syntax, with a single
> keyword added.
>
> --
>
> Pierre
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>

Is there actually a bug that this functionality can/could prevent? I
get that Maybe and Result types should be closed, but what are the
risk of software defects if someone abuses that fact (locally)?

Olle

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



Re: [PHP-DEV] [RFC] Partial function application

2021-04-25 Thread Olle Härstedt
2021-04-25 21:07 GMT, Max Semenik :
> On Sun, Apr 25, 2021 at 10:26 PM Larry Garfield 
> wrote:
>
>> https://wiki.php.net/rfc/partial_function_application
>
>
>  Amazing, I've wanted this for so long! Have you considered extending this
> syntax to OOP, e.g. $obj->method(?) or SomeClass::staticMethod(?)?
>
> On Sun, Apr 25, 2021 at 10:51 PM Olle Härstedt 
> wrote:
>
>> Nice. :) Are there any other motivating use-cases besides pipe
>> operator (that are relevant for web dev)?
>
>
> One reason I'm personally excited about this proposal is that it would
> allow static analysis in more cases, e.g.
>
> $param = 'fooBar'; // What's this string? A user name? Elon Musk's favorite
> color? Text of US Constitution?
>
> somefunc($param);
>
> function somefunc($cb) {
> $cb(123, 'meh'); // What parameter types does this accept?
> }
>
> Allowing syntax like $param = fooBar(?, ?); would indicate clearly what
> this variable receives. Analysis tools would then be able to check if such
> a function exists and whether it would receive parameters of expected
> types.
>
> --
> Best regards,
> Max Semenik
>

By the way, for pipe operators to be really useful, it should probably
be possible to combine with middleware.

Olle

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



Re: [PHP-DEV] [RFC] Partial function application

2021-04-25 Thread Olle Härstedt
2021-04-25 21:07 GMT, Max Semenik :
> On Sun, Apr 25, 2021 at 10:26 PM Larry Garfield 
> wrote:
>
>> https://wiki.php.net/rfc/partial_function_application
>
>
>  Amazing, I've wanted this for so long! Have you considered extending this
> syntax to OOP, e.g. $obj->method(?) or SomeClass::staticMethod(?)?
>
> On Sun, Apr 25, 2021 at 10:51 PM Olle Härstedt 
> wrote:
>
>> Nice. :) Are there any other motivating use-cases besides pipe
>> operator (that are relevant for web dev)?
>
>
> One reason I'm personally excited about this proposal is that it would
> allow static analysis in more cases, e.g.
>
> $param = 'fooBar'; // What's this string? A user name? Elon Musk's favorite
> color? Text of US Constitution?
>
> somefunc($param);
>
> function somefunc($cb) {
> $cb(123, 'meh'); // What parameter types does this accept?
> }
>
> Allowing syntax like $param = fooBar(?, ?); would indicate clearly what
> this variable receives. Analysis tools would then be able to check if such
> a function exists and whether it would receive parameters of expected
> types.

Like an alternative to value objects (`class Email ... `)? Not sure I
understand how, sorry.

Olle

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



Re: [PHP-DEV] [RFC] Partial function application

2021-04-25 Thread Olle Härstedt
2021-04-25 21:25 GMT+02:00, Larry Garfield :
> Greetings, Internalians!
>
> I would like to offer for your consideration another RFC, specifically
> syntax for partial function application.
>
> https://wiki.php.net/rfc/partial_function_application
>
> It includes an implementation by Joe Watkins that is already about 95%
> complete.  (There's some edge cases he's still sorting out, but all of the
> typical cases should work already.)  Most of the design work comes from Levi
> Morrison and Paul Crovella.  I helped out with the tests, a few edge bits,
> and general instigator/nudge. :-)
>
> Discuss.
>
> --
>   Larry Garfield
>   la...@garfieldtech.com
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>

Nice. :) Are there any other motivating use-cases besides pipe
operator (that are relevant for web dev)?

Olle

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



Re: [PHP-DEV] [RFC][Draft] Sealed Classes

2021-04-25 Thread Olle Härstedt
2021-04-25 18:27 GMT+02:00, Larry Garfield :
> On Sun, Apr 25, 2021, at 2:04 AM, Olle Härstedt wrote:
>> > A total function is a function that is defined over the entire domain of
>> > its
>> > inputs.  For example, addition is a total function over integers,
>> > because
>> > for every possible pair of integers you pass to it there is a logical
>> > return
>> > value.  However, square root is not a total function over integers
>> > because
>> > there are some integers you pass it for which there is not
>> > representable
>> > return value.  (Negative numbers, unless you get into imaginary numbers
>> > which PHP doesn't support.)  In those cases, you have to throw an
>> > exception
>> > or return an error code or similar.
>>
>> Maybe nitpicking, but PHP-land shouldn't make up their own
>> definitions: "A total function is a function that is defined for all
>> possible values of its input. That is, it terminates and returns a
>> value."
>> https://softwareengineering.stackexchange.com/questions/334874/in-the-context-of-functional-programming-what-are-total-functions-and-partia
>>
>> Which means a total function is guaranteed to not have any errors,
>> like exceptions or division by zero. Compare with languages F* or Koka
>> which support this notation.
>
> That... is literally what I said.  There was no making up definitions.  I
> was using the actual mathematical definition.  PHP is quite capable of
> having total functions, they're a good thing, and we should try to encourage
> them where feasible.

What's the point of encouraging total functions if you can't express
the totality in the type system?

Olle

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



Re: [PHP-DEV] [RFC][Draft] Sealed Classes

2021-04-25 Thread Olle Härstedt
> In practice, I think all of the use cases for sealed classes are ADT-esque.
> As I noted before, combining sealed classes with Nikita's new-in-expressions
> RFC would allow for this (also using my short-functions RFC for this
> example, although that's a nice-to-have):
>
> sealed class Maybe permits Some, None {
>
>   public const None = new None();
>
>   static public function Some($x) => new Some($x);
>
>   public function value() => throw new NotFoundException();
>
>   public function bind(callable $c) => static::None;
> }
>
> final class None extends Maybe {}
>
> final class Some extends Maybe {
>   private $val;
>   private function __construct($x) { $this->val = $x; }
>
>   public function value() => $this->val;
>
>   public function bind(callable $c) => new static($c($this->val));
> }

Yes, the Maybe/Option type is a good example! Because you know there
will never be another extension. But it's worth noting that whenever
you do *not* know that, these concepts suffer, even in functional
programming, by the same issues as I mentioned before with regard to
maintainability - you can't easily extend it without touching old code
(there are attempts to fix this by making algebraic datatypes
extensible, but it didn't get widely adopted AFAIK). Also see this
thread about the expression problem:
https://stackoverflow.com/a/871375/2138090

Disregarding the limitations of maintainability, the real power of
algebraic datatypes is of course the pattern matching functionality
seen in OCaml and Haskell. I'm leaning towards tagged unions + pattern
matching have more to offer PHP than sealed classes (and even more so
when pattern matching can be extended with guard clauses and catching
exceptions). The RFC author(s) might want to extend the RFC to reflect
the relation to tagged unions, and how they overlap (or not)?

Olle

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



Re: [PHP-DEV] [RFC][Draft] Sealed Classes

2021-04-25 Thread Olle Härstedt
> For a more typical PHP example, getUser(int $id) is not a total function,
> unless you have PHP_MAX_INT user objects defined in your database.  If you
> pass an int that does not correspond to a defined user, you now have to deal
> with "user not found" error handling.  getUser() is not a total function.
> getUsers(array $criteria), however, arguably is, because it's logical and
> reasonable to map all not-found cases to an empty array/collection, which
> doesn't require any special error handling.

getUser() could return a nullable type. But totality assumes purity,
and I'm assuming you didn't hard-code all users inside the getUser()
function. :) As soon as you interact with the outside world, you can
have exception and errors, and thus you can't guarantee termination.
In any case, I think the concept of totality is pretty foreign to PHP,
and we can probably leave it behind (you'd have to make sure -
statically, in the type-system - there are no infinite recursion, no
infinite loops, ...).

Olle

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



Re: [PHP-DEV] [RFC][Draft] Sealed Classes

2021-04-25 Thread Olle Härstedt
> A total function is a function that is defined over the entire domain of its
> inputs.  For example, addition is a total function over integers, because
> for every possible pair of integers you pass to it there is a logical return
> value.  However, square root is not a total function over integers because
> there are some integers you pass it for which there is not representable
> return value.  (Negative numbers, unless you get into imaginary numbers
> which PHP doesn't support.)  In those cases, you have to throw an exception
> or return an error code or similar.

Maybe nitpicking, but PHP-land shouldn't make up their own
definitions: "A total function is a function that is defined for all
possible values of its input. That is, it terminates and returns a
value." 
https://softwareengineering.stackexchange.com/questions/334874/in-the-context-of-functional-programming-what-are-total-functions-and-partia

Which means a total function is guaranteed to not have any errors,
like exceptions or division by zero. Compare with languages F* or Koka
which support this notation.

I get your point tho. :)

Olle

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



Re: [PHP-DEV] [RFC][Draft] Sealed Classes

2021-04-24 Thread Olle Härstedt
2021-04-24 21:51 GMT+02:00, Marco Pivetta :
> On Sat, Apr 24, 2021, 21:44 Olle Härstedt  wrote:
>
>> 2021-04-24 17:59 GMT+02:00, Saif Eddin Gmati :
>> >> Doesn't this violate the principle: It should be possible to add new
>> >> features without touching old code?
>> >
>> > This depends on which syntax is picked, both `for` and attribute syntax
>> will
>> > be completely BC.
>>
>> I'm not talking about BC, but the maintainability of the new feature
>> itself. For the shape example, you'd need to edit the original file
>> for each new shape you add, which is detrimental for maintainability
>> and scalability. So what's a good use-case?
>>
>
> The main use-case of sealed types is being able to declare total functions
> around them.

What is "total function" in your discourse? :) Can you find a more
concrete example? Preferably one that's relevant for web site/app
development. Shapes is a bit too generic, I think.

Olle

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



Re: [PHP-DEV] [RFC][Draft] Sealed Classes

2021-04-24 Thread Olle Härstedt
2021-04-24 17:59 GMT+02:00, Saif Eddin Gmati :
>> Doesn't this violate the principle: It should be possible to add new
>> features without touching old code?
>
> This depends on which syntax is picked, both `for` and attribute syntax will
> be completely BC.

I'm not talking about BC, but the maintainability of the new feature
itself. For the shape example, you'd need to edit the original file
for each new shape you add, which is detrimental for maintainability
and scalability. So what's a good use-case?

Olle

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



Re: [PHP-DEV] [RFC][Draft] Sealed Classes

2021-04-24 Thread Olle Härstedt
2021-04-24 12:56 GMT, Pierre :
> Le 24/04/2021 à 12:55, Saif Eddin Gmati a écrit :
>> Hello Internals,
>>
>> I'm sending this email to open discussion about sealed classes,
>> interfaces, and traits feature for PHP 8.1.
>>
>> I have create a Draft RFC here:
>> https://wiki.php.net/rfc/sealed_classes
>> 
>>
>> A major concern for few people have been the syntax, in which it
>> introduces 2 new keywords into the languages, therefor, i have added a
>> section about alternative syntax which could be used to avoid this
>> problem.
>>
>> Regards,
>>
>> Saif.

1) Doesn't this violate the principle: It should be possible to add
new features without touching old code?

2) Isn't namespace-internal access a better feature for the same
purpose? That is, only allows a class to be extended within the same
namespace.

Olle

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



Re: [PHP-DEV] Why is assert limited to a debugging feature only?

2021-04-01 Thread Olle Härstedt
2021-04-01 10:24 GMT+02:00, Arnold Daniels :
> Hi,
>
> The documentation of `assert`
> ([https://php.net/assert)](https://www.php.net/manual/en/function.assert.php))
> states that's debugging only. This is further enforced by php.ini flags to
> disable assertions in production.
>
> Why are the use cases of this feature being limited to debugging? We can see
> from the popularity of user-space assertion libraries, like
> [webmozart/asset](https://packagist.org/packages/webmozart/assert) and
> [beberlei/assert](https://packagist.org/packages/beberlei/assert), that
> there is a need for runtime assertions.
>
> [Arnold Daniels - Chat @
> Spike](https://spikenow.com/r/a/?ref=spike-organic-signature&_ts=yux2k)   
> [yux2k]

Dunno about the motivation of the implementors, but usually assertions
are used for internal invariants and mental checks while exceptions
should be used for interaction with the outside world (database
errors, user input errors etc). If you follow this, an assert error
will never be useful for a user, it will always be an "internal
error", and that's why it can (should?) be disabled in production.

Olle

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



Re: [PHP-DEV] Any reason why backed enums are limited to int and string only?

2021-03-31 Thread Olle Härstedt
2021-03-31 20:52 GMT+02:00, Ilija Tovilo :
> Hi Olle
>
>> I was trying to implement the result type from OCaml using enums, and
>> noticed that they can only carry int or string data, not arbitrary
>> data. Any specific reason for this?
>>
>> Example:
>>
>> enum Result: mixed {
>> case Ok = null;
>> case Error = null;
>> }
>>
>> Error with:
>>
>> Fatal error: Enum backing type must be int or string, mixed given in
>> /tmp/enum.php on line 3
>>
>> More specifically, for this idiom to work, "Ok" needs to be mixed and
>> "Error" should be string.
>>
>> OCaml idiom:
>> https://ocaml.org/learn/tutorials/error_handling.html#Result-type
>
> What you're trying to achieve here is not what backed enums are for.
> Backed enums are for assigning each enum case a single, constant
> representation that can be converted back and forth. As for Result,
> what you'd want here is a dynamic, arbitrary value for both Ok and
> Error, which is exactly what ADTs / tagged unions would allow you to
> do:
>
> https://wiki.php.net/rfc/tagged_unions
>
> enum Result
> {
> case Ok(mixed $result);
> case Error(mixed $error);
> }
>
> Optimally we'd define Result as "Result" but that's
> another discussion :)
>
> Note that work on ADT hasn't started yet.
>
> Ilija
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>

Got it, thanks guys!

Olle

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



[PHP-DEV] Any reason why backed enums are limited to int and string only?

2021-03-31 Thread Olle Härstedt
Hello,

I was trying to implement the result type from OCaml using enums, and
noticed that they can only carry int or string data, not arbitrary
data. Any specific reason for this?

Example:

enum Result: mixed {
case Ok = null;
case Error = null;
}

Error with:

Fatal error: Enum backing type must be int or string, mixed given in
/tmp/enum.php on line 3

More specifically, for this idiom to work, "Ok" needs to be mixed and
"Error" should be string.

OCaml idiom: https://ocaml.org/learn/tutorials/error_handling.html#Result-type

Olle

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



Re: [PHP-DEV] Making "match" catch exceptions

2021-03-27 Thread Olle Härstedt
2021-03-27 15:30 GMT+01:00, Rowan Tommins :
> On 26/03/2021 22:58, Olle Härstedt wrote:
>> You can't catch the value of $temp in the match-case?
>>
>>  $foo = $bar + match (doSomething()) {
>>$temp => $temp,
>>exception SomeException => 0
>>  };
>
>
> $temp doesn't have an outside value, it was an inline assignment to
> capture the value of doSomething(); essentially, I wanted this, but
> without executing doSomething() twice:
>
> $foo = $bar + match (doSomething()) {
>default => doSomething(),
>exception SomeException => 0
> };

Yeah, I got it. Maybe I didn't read enough about the match-expression
implementation in PHP, but in OCaml it's possible to capture whatever
value the match evaluated to, like:

let number_as_string = match number with
| 1 -> "one"
| v -> "number is " ^ string_of_int v

("^" is string concatenation.)

The point of using a variable name like "v" (could be anything)
instead of "default" is that like in your example, you don't have to
execute the method twice. You can also add guard clauses, like "v when
v > 10 -> ...". If you don't plan to use the value, you can use
underscore, "_", which I guess would be the corresponding
functionality to "default" in the PHP implementation.

Olle

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



Re: [PHP-DEV] Making "match" catch exceptions

2021-03-26 Thread Olle Härstedt
2021-03-26 23:00 GMT+01:00, Rowan Tommins :
> On 26/03/2021 16:45, Olle Härstedt wrote:
>> That made me think of a recent
>> extension to OCaml which makes it possible to catch exceptions in a
>> match-expressions (here's one blog post about it:
>> https://blog.janestreet.com/pattern-matching-and-exception-handling-unite/).
>
>
> That's an interesting idea. I wonder if it would provide a way to
> implement the "data-flow" or "expression context" exception handling I
> was discussing on a different thread recently.
>
> Looking at my previous example:
>
> try {
> $foo = doSomething() + $bar;
> }
> catch ( SomeException $e ) {
> $foo = $bar;
> }
>
> Would become something like this:
>
> $foo = match($temp = doSomething()) {
> exception SomeException => 0,
> default => $temp
> } + $bar;

You can't catch the value of $temp in the match-case?

$foo = $bar + match (doSomething()) {
  $temp => $temp,
  exception SomeException => 0
};

Olle

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



Re: [PHP-DEV] [RFC] Auto-capture multi-line closures and shortfunctions take 2

2021-03-26 Thread Olle Härstedt
2021-03-26 17:11 GMT+01:00, Mike Schinkel :
>> On Mar 26, 2021, at 8:12 AM, Olle Härstedt 
>> wrote:
>>
>> 2021-03-26 3:38 GMT+01:00, Mike Schinkel :
>>>
>>>
>>>> On Mar 25, 2021, at 4:09 PM, Olle Härstedt 
>>>> wrote:
>>>>
>>>> 2021-03-25 17:49 GMT+01:00, Mike Schinkel :
>>>>>> On Mar 25, 2021, at 11:22 AM, Olle Härstedt 
>>>>>> wrote:
>>>>>>
>>>>>> 2021-03-25 16:02 GMT+01:00, Mike Schinkel :
>>>>>>>
>>>>>>>
>>>>>>>> On Mar 25, 2021, at 10:41 AM, Rowan Tommins
>>>>>>>> 
>>>>>>>> wrote:
>>>>>>>>
>>>>>>>> On 25/03/2021 12:31, Nuno Maduro wrote:
>>>>>>>>
>>>>>>>>> The reason why we believe the vast majority of PHP Developers are
>>>>>>>>> going
>>>>>>>>> to
>>>>>>>>> appreciate this RFC is because multi-line short closures (aka
>>>>>>>>> Auto-capturing multi-statement closures) *are more simple, shorter
>>>>>>>>> to
>>>>>>>>> write, and prettier to read *— and the community love these
>>>>>>>>> changes
>>>>>>>>> as
>>>>>>>>> proven on "property promotions", "one-line short closures", etc.
>>>>>>>>
>>>>>>>>
>>>>>>>> My main point was that the RFC needs to spell out this argument,
>>>>>>>> rather
>>>>>>>> than taking it for granted that everyone agrees on "those
>>>>>>>> situations
>>>>>>>> where
>>>>>>>> that is warranted".
>>>>>>>>
>>>>>>>> Most of the current text should be summarised in a "syntax choices"
>>>>>>>> section somewhere near the end. I would like to see much more space
>>>>>>>> devoted to:
>>>>>>>>
>>>>>>>> * Why we need this feature. What has changed since it was left out
>>>>>>>> of
>>>>>>>> the
>>>>>>>> arrow functions RFC? What problems is it addressing? Why do you
>>>>>>>> think
>>>>>>>> it
>>>>>>>> is the best approach to those problems?
>>>>>>>> * The exact semantics proposed: How will the variables to be
>>>>>>>> captured
>>>>>>>> be
>>>>>>>> determined? Will it distinguish variables which are written before
>>>>>>>> they're
>>>>>>>> read, and if so how is that defined? Can auto-capturing closures be
>>>>>>>> nested, i.e. will "fn() { return fn() { echo $a; } }" capture $a
>>>>>>>> from
>>>>>>>> the
>>>>>>>> outermost scope? And so on...
>>>>>>>>
>>>>>>>>
>>>>>>>>> Besides, one advantage of this RFC is that it is consistent with
>>>>>>>>> the
>>>>>>>>> current syntax of the language and with the short-functions
>>>>>>>>> RFC[2].
>>>>>>>>> For
>>>>>>>>> example, by proposing that "fn" keyword indicates a function will
>>>>>>>>> auto-capture variables, by value.
>>>>>>>>
>>>>>>>>
>>>>>>>> While it's a cute rationalisation, there's no intuitive reason why
>>>>>>>> "fn"
>>>>>>>> should have that meaning; we could pick any aspect of the current
>>>>>>>> arrow
>>>>>>>> function syntax and say "the 'fn' keyword means that".
>>>>>>>>
>>>>>>>>
>>>>>>>>
>>>>>>>>> On the other hand "use (*)" has no usages / or current meaning in
>>>>>>>>> the
>>>>>>>>> language.
>>>>>>>>
>>>>>>>>
>>>>>>>> This is a straw man argument. I could equally say that "f

[PHP-DEV] Making "match" catch exceptions

2021-03-26 Thread Olle Härstedt
Hi,

Someone mentioned that they prefer lambdas over try-catch blocks,
which surprised me, since try-catch is completely idiomatic in both
PHP and OCaml (Haskell I don't know). That made me think of a recent
extension to OCaml which makes it possible to catch exceptions in a
match-expressions (here's one blog post about it:
https://blog.janestreet.com/pattern-matching-and-exception-handling-unite/).

Now when PHP also has `match`, are there any plans to extend it with
exception catching? So far I did not find anything about exceptions in
the match RFC v2: https://wiki.php.net/rfc/match_expression_v2

Kind regards
Olle

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



Re: [PHP-DEV] [RFC] Auto-capture multi-line closures and shortfunctions take 2

2021-03-26 Thread Olle Härstedt
2021-03-26 3:38 GMT+01:00, Mike Schinkel :
>
>
>> On Mar 25, 2021, at 4:09 PM, Olle Härstedt 
>> wrote:
>>
>> 2021-03-25 17:49 GMT+01:00, Mike Schinkel :
>>>> On Mar 25, 2021, at 11:22 AM, Olle Härstedt 
>>>> wrote:
>>>>
>>>> 2021-03-25 16:02 GMT+01:00, Mike Schinkel :
>>>>>
>>>>>
>>>>>> On Mar 25, 2021, at 10:41 AM, Rowan Tommins 
>>>>>> wrote:
>>>>>>
>>>>>> On 25/03/2021 12:31, Nuno Maduro wrote:
>>>>>>
>>>>>>> The reason why we believe the vast majority of PHP Developers are
>>>>>>> going
>>>>>>> to
>>>>>>> appreciate this RFC is because multi-line short closures (aka
>>>>>>> Auto-capturing multi-statement closures) *are more simple, shorter
>>>>>>> to
>>>>>>> write, and prettier to read *— and the community love these changes
>>>>>>> as
>>>>>>> proven on "property promotions", "one-line short closures", etc.
>>>>>>
>>>>>>
>>>>>> My main point was that the RFC needs to spell out this argument,
>>>>>> rather
>>>>>> than taking it for granted that everyone agrees on "those situations
>>>>>> where
>>>>>> that is warranted".
>>>>>>
>>>>>> Most of the current text should be summarised in a "syntax choices"
>>>>>> section somewhere near the end. I would like to see much more space
>>>>>> devoted to:
>>>>>>
>>>>>> * Why we need this feature. What has changed since it was left out of
>>>>>> the
>>>>>> arrow functions RFC? What problems is it addressing? Why do you think
>>>>>> it
>>>>>> is the best approach to those problems?
>>>>>> * The exact semantics proposed: How will the variables to be captured
>>>>>> be
>>>>>> determined? Will it distinguish variables which are written before
>>>>>> they're
>>>>>> read, and if so how is that defined? Can auto-capturing closures be
>>>>>> nested, i.e. will "fn() { return fn() { echo $a; } }" capture $a from
>>>>>> the
>>>>>> outermost scope? And so on...
>>>>>>
>>>>>>
>>>>>>> Besides, one advantage of this RFC is that it is consistent with the
>>>>>>> current syntax of the language and with the short-functions RFC[2].
>>>>>>> For
>>>>>>> example, by proposing that "fn" keyword indicates a function will
>>>>>>> auto-capture variables, by value.
>>>>>>
>>>>>>
>>>>>> While it's a cute rationalisation, there's no intuitive reason why
>>>>>> "fn"
>>>>>> should have that meaning; we could pick any aspect of the current
>>>>>> arrow
>>>>>> function syntax and say "the 'fn' keyword means that".
>>>>>>
>>>>>>
>>>>>>
>>>>>>> On the other hand "use (*)" has no usages / or current meaning in
>>>>>>> the
>>>>>>> language.
>>>>>>
>>>>>>
>>>>>> This is a straw man argument. I could equally say that "fn() { } has
>>>>>> no
>>>>>> usages or current meaning in the language" - of course it doesn't, we
>>>>>> haven't added it yet!
>>>>>>
>>>>>> The "function use() {}" part of "function use(*) {}" has a
>>>>>> well-established meaning, and "*" to mean "everything" is a notation
>>>>>> developers are likely to be very familiar with.
>>>>>>
>>>>>> The two disadvantages I see with using "fn" as proposed are:
>>>>>>
>>>>>> * Because it's shorter, people will decide it's the "better" version,
>>>>>> when
>>>>>> they don't actually need any variable capture. An explicit syntax
>>>>>> like
>>>>>> "use(*)" instead makes this a deliberate choice.
>>>>>

Re: [PHP-DEV] [RFC] Auto-capture multi-line closures and shortfunctions take 2

2021-03-25 Thread Olle Härstedt
2021-03-25 17:49 GMT+01:00, Mike Schinkel :
>> On Mar 25, 2021, at 11:22 AM, Olle Härstedt 
>> wrote:
>>
>> 2021-03-25 16:02 GMT+01:00, Mike Schinkel :
>>>
>>>
>>>> On Mar 25, 2021, at 10:41 AM, Rowan Tommins 
>>>> wrote:
>>>>
>>>> On 25/03/2021 12:31, Nuno Maduro wrote:
>>>>
>>>>> The reason why we believe the vast majority of PHP Developers are
>>>>> going
>>>>> to
>>>>> appreciate this RFC is because multi-line short closures (aka
>>>>> Auto-capturing multi-statement closures) *are more simple, shorter to
>>>>> write, and prettier to read *— and the community love these changes as
>>>>> proven on "property promotions", "one-line short closures", etc.
>>>>
>>>>
>>>> My main point was that the RFC needs to spell out this argument, rather
>>>> than taking it for granted that everyone agrees on "those situations
>>>> where
>>>> that is warranted".
>>>>
>>>> Most of the current text should be summarised in a "syntax choices"
>>>> section somewhere near the end. I would like to see much more space
>>>> devoted to:
>>>>
>>>> * Why we need this feature. What has changed since it was left out of
>>>> the
>>>> arrow functions RFC? What problems is it addressing? Why do you think
>>>> it
>>>> is the best approach to those problems?
>>>> * The exact semantics proposed: How will the variables to be captured
>>>> be
>>>> determined? Will it distinguish variables which are written before
>>>> they're
>>>> read, and if so how is that defined? Can auto-capturing closures be
>>>> nested, i.e. will "fn() { return fn() { echo $a; } }" capture $a from
>>>> the
>>>> outermost scope? And so on...
>>>>
>>>>
>>>>> Besides, one advantage of this RFC is that it is consistent with the
>>>>> current syntax of the language and with the short-functions RFC[2].
>>>>> For
>>>>> example, by proposing that "fn" keyword indicates a function will
>>>>> auto-capture variables, by value.
>>>>
>>>>
>>>> While it's a cute rationalisation, there's no intuitive reason why "fn"
>>>> should have that meaning; we could pick any aspect of the current arrow
>>>> function syntax and say "the 'fn' keyword means that".
>>>>
>>>>
>>>>
>>>>> On the other hand "use (*)" has no usages / or current meaning in the
>>>>> language.
>>>>
>>>>
>>>> This is a straw man argument. I could equally say that "fn() { } has no
>>>> usages or current meaning in the language" - of course it doesn't, we
>>>> haven't added it yet!
>>>>
>>>> The "function use() {}" part of "function use(*) {}" has a
>>>> well-established meaning, and "*" to mean "everything" is a notation
>>>> developers are likely to be very familiar with.
>>>>
>>>> The two disadvantages I see with using "fn" as proposed are:
>>>>
>>>> * Because it's shorter, people will decide it's the "better" version,
>>>> when
>>>> they don't actually need any variable capture. An explicit syntax like
>>>> "use(*)" instead makes this a deliberate choice.
>>>
>>> And yet adding " use (*)" makes the syntax longer, which goes against one
>>> of
>>> the goals many people have for it: to be shorter.
>>
>> I don't understand why this is a target in the first place. Shorter
>> does not mean more readable, and readable is more important than
>> writable.
>
> I agree that readable is more important than writable, but shorter also does
> not necessarily mean it is *less* readable, either.

Sure. The brain removes noise and reads in "symbols" anyway (where
"fn" or "function" is a symbol of size 1).

A more important aspect of readability is the cognitive load on
short-term memory, or how many "chunks" the programmer has to keep in
memory to understand a piece of code. In this case, I think
immutability and local scope helps a lot, of which PHP has neither. Or
maybe predictability of the scope? All

Re: [PHP-DEV] [RFC] Auto-capture multi-line closures and shortfunctions take 2

2021-03-25 Thread Olle Härstedt
2021-03-25 16:02 GMT+01:00, Mike Schinkel :
>
>
>> On Mar 25, 2021, at 10:41 AM, Rowan Tommins 
>> wrote:
>>
>> On 25/03/2021 12:31, Nuno Maduro wrote:
>>
>>> The reason why we believe the vast majority of PHP Developers are going
>>> to
>>> appreciate this RFC is because multi-line short closures (aka
>>> Auto-capturing multi-statement closures) *are more simple, shorter to
>>> write, and prettier to read *— and the community love these changes as
>>> proven on "property promotions", "one-line short closures", etc.
>>
>>
>> My main point was that the RFC needs to spell out this argument, rather
>> than taking it for granted that everyone agrees on "those situations where
>> that is warranted".
>>
>> Most of the current text should be summarised in a "syntax choices"
>> section somewhere near the end. I would like to see much more space
>> devoted to:
>>
>> * Why we need this feature. What has changed since it was left out of the
>> arrow functions RFC? What problems is it addressing? Why do you think it
>> is the best approach to those problems?
>> * The exact semantics proposed: How will the variables to be captured be
>> determined? Will it distinguish variables which are written before they're
>> read, and if so how is that defined? Can auto-capturing closures be
>> nested, i.e. will "fn() { return fn() { echo $a; } }" capture $a from the
>> outermost scope? And so on...
>>
>>
>>> Besides, one advantage of this RFC is that it is consistent with the
>>> current syntax of the language and with the short-functions RFC[2]. For
>>> example, by proposing that "fn" keyword indicates a function will
>>> auto-capture variables, by value.
>>
>>
>> While it's a cute rationalisation, there's no intuitive reason why "fn"
>> should have that meaning; we could pick any aspect of the current arrow
>> function syntax and say "the 'fn' keyword means that".
>>
>>
>>
>>> On the other hand "use (*)" has no usages / or current meaning in the
>>> language.
>>
>>
>> This is a straw man argument. I could equally say that "fn() { } has no
>> usages or current meaning in the language" - of course it doesn't, we
>> haven't added it yet!
>>
>> The "function use() {}" part of "function use(*) {}" has a
>> well-established meaning, and "*" to mean "everything" is a notation
>> developers are likely to be very familiar with.
>>
>> The two disadvantages I see with using "fn" as proposed are:
>>
>> * Because it's shorter, people will decide it's the "better" version, when
>> they don't actually need any variable capture. An explicit syntax like
>> "use(*)" instead makes this a deliberate choice.
>
> And yet adding " use (*)" makes the syntax longer, which goes against one of
> the goals many people have for it: to be shorter.

I don't understand why this is a target in the first place. Shorter
does not mean more readable, and readable is more important than
writable.

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



Re: [PHP-DEV] [RFC] Auto-capture multi-line closures andshortfunctions take 2

2021-03-25 Thread Olle Härstedt
2021-03-25 15:23 GMT+01:00, Christian Schneider :
> Am 25.03.2021 um 14:29 schrieb Mark Randall :
>> On 25/03/2021 09:28, Rowan Tommins wrote:
>>> That's not quite what I meant. I meant that you can't say "capture by
>>> default, but this variable is definitely local".
>>
>> I think if there's one argument against, this would be it, but IMHO it is
>> a weakness in PHP as a whole.
>
> I'm not sure if I misunderstand what you're saying but to me it is one of
> the greatest things about PHP that everything is local by default (minus a
> narrow set of well-known and easily enough recognizable things).
>
>> The solution would be adding JS-like let / const statements. Which would
>> be a benefit to other things too.
>
>
> I disagree that this is the solution. I think JS had to add var and later
> let because of the unfortunate decision to have C-like scoping rules.
> Making scoping in PHP more complex to be able to repeat this mistake in some
> form seems ill-advised to me.
>
> - Chris

You could make the change that *all* variables are now block-scoped,
not function-scoped. That would make auto-capture less dangerous, but
I don't know how much code it would break.

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



Re: [PHP-DEV] [RFC] Auto-capture multi-line closures andshortfunctions take 2

2021-03-25 Thread Olle Härstedt
2021-03-25 14:29 GMT+01:00, Mark Randall :
> On 25/03/2021 09:28, Rowan Tommins wrote:
>> That's not quite what I meant. I meant that you can't say "capture by
>> default, but this variable is definitely local".
>
> I think if there's one argument against, this would be it, but IMHO it
> is a weakness in PHP as a whole.
>
> The solution would be adding JS-like let / const statements. Which would
> be a benefit to other things too.

JS does not support "definitely local". No language does, AFAIK.
Unless you count value types.

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



Re: [PHP-DEV] [RFC] Auto-capture multi-line closures and shortfunctions take 2

2021-03-25 Thread Olle Härstedt
I feel like some of these examples would be better covered by command
object pattern and data-transaction objects, instead of FP idioms.
wrap_in_buffer pretty clearly so.

2021-03-25 10:28 GMT+01:00, Rowan Tommins :
> On 25/03/2021 04:12, Mike Schinkel wrote:
>
>> Actually, there is a way to declare a local variable.  Use the long
>> function syntax instead as there is no proposal to deprecate it.
>
> That's not quite what I meant. I meant that you can't say "capture by
> default, but this variable is definitely local".
>
> I'm guessing maybe "$foo = null;" at the top of the function would stop
> it auto-capturing, but the semantics of what exactly gets captured
> aren't spelled out in the RFC. That really needs to be added IMO.
>
>
>> Instead of using array_filter() with a side-effect free closure, I use a
>> for loop because it is easier to reason about visually.
>
>
> Is that a bad thing? In many cases it's probably more efficient, and
> easier to read.
>
>
>
>
>> It is not clear to me from reading the PEP how a "with" statement obviates
>> the benefit of variable auto-capture? Maybe because I don't "think" in
>> Python, so from reading their examples I cannot see how this relates?
>
>
> I didn't mean to say that the "with" statement would replace closures in
> general, but it would make them unnecessary *for some specific use
> cases*. You mentioned:
>
>  > prime examples are database transactions and using throw-aware
> buffering handlers.
>
> If your current code looks something like this:
>
> wrap_in_buffer(function($transaction) use ($to, $library, $thread,
> $author, $title, $library_name, $top_post) {
>  doSomething($to, $library, $thread);
>  andThenSomethingElse($author, $title, $library_name, $top_post);
> });
>
> That's a perfect use case for a Context Manager:
>
> with ( wrap_in_buffer() ) {
>  doSomething($to, $library, $thread);
>  andThenSomethingElse($author, $title, $library_name, $top_post);
> }
>
> There's no callback, so no need to capture anything, and the
> implementation of all the try-catch-finally logic would be baked into
> the language, so the implementation of wrap_in_buffer() would also be
> much simpler.
>
>
> Regards,
>
> --
> Rowan Tommins
> [IMSoP]
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>

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



Re: [PHP-DEV] [RFC] Auto-capture multi-line closures and shortfunctions take 2

2021-03-25 Thread Olle Härstedt
> prettier to read

Are they though? Because if it implicitly captures anything in scope,
there are more lines to read to figure out what's actually captured.

2021-03-25 13:31 GMT+01:00, Nuno Maduro :
> Hi,
>
> Thank you for the feedback on this thread so far. Programmers are
> opinionated, therefore you will find developers that see themselves using
> this RFC and others who don't. Just like "Fibers", "Type-hints", or any
> other feature in the language really.
>
> The reason why we believe the vast majority of PHP Developers are going to
> appreciate this RFC is because multi-line short closures (aka
> Auto-capturing multi-statement closures) *are more simple, shorter to
> write, and prettier to read *— and the community love these changes as
> proven on "property promotions", "one-line short closures", etc. [1]
>
> Besides, one advantage of this RFC is that it is consistent with the
> current syntax of the language and with the short-functions RFC[2]. For
> example, by proposing that "fn" keyword indicates a function will
> auto-capture variables, by value. And, the "=>" sigil always means
> "evaluates to the expression on the right" in all circumstances - one-line
> short closures, named functions, arrays, and match() already follow these
> patterns. [3]
>
> On the other hand "use (*)" has no usages / or current meaning in the
> language.
>
> Thanks,
> Nuno.
>
> [1] Pretty much "Brent Roose" have said here:
> https://externals.io/email/112010/source
> [2] https://wiki.php.net/rfc/short-functions
> [3] Check "Auto-capture multi-statement closures" -
> https://wiki.php.net/rfc/auto-capture-closure.
>

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



Re: [PHP-DEV] Does PHP ever stack allocate?

2021-01-09 Thread Olle Härstedt
2021-01-05 10:51 GMT, Nikita Popov :
> On Mon, Jan 4, 2021 at 11:53 AM Olle Härstedt 
> wrote:
>
>> 2021-01-03 17:43 GMT, tyson andre :
>> > Hi Olle,
>> >
>> >> Thanks Sara! I realize I should have been more precise: Can PHP
>> >> allocate non-reference counted memory that automatically is freed when
>> >> leaving scope, similar to what Go does with escape analysis?
>> >>
>> >> Article describing the Go mechanism:
>> >>
>> https://segment.com/blog/allocation-efficiency-in-high-performance-go-services/
>> >
>> > Could you give some concrete examples of what type of code you're
>> > talking
>> > about?
>> > As Sara Golemon said, scalars (null, bool, int, float) are allocated on
>> > a
>> > php call frame,
>> > and the call frames go on a stack. That stack is separate from the C
>> stack,
>> > but still a stack
>> >
>> > The call frame is "freed" when leaving scope - i.e. that part of the
>> stack
>> > will be reused on subsequent calls.
>>
>> Sure. Consider the following trivial snippet:
>>
>> ```php
>> class Point {
>>   public $x;
>>   public $y;
>> }
>> function foo() {
>>   $p = new Point();
>>   return $p->x + $p->y;
>> }
>> ```
>>
>> Since we know the lifetime of $p, we don't have to ref count it.
>> Escape analysis helps with checking lifetimes and to remove needles
>> ref counting (and heap allocations in compiled languages). There is a
>> file in php-src for this:
>>
>> https://github.com/php/php-src/blob/master/ext/opcache/Optimizer/escape_analysis.c
>>
>> My question was about how this functionality is used.
>>
>
> I believe the escape analysis is currently only used as part of SCCP to
> perform constant folding on objects. For example, we would be able to fold
> the following function down to "return 3;":
>
> function foo() {
> $p = new Point();
> $p->x = 1;
> $p->y = 2;
> return $p->x + $p->y;
> }
>
> However, I think the optimization you have in mind is more along the lines
> of dropping the object and storing its properties as local variables
> instead.

Hm, this is called scalar replacement, I think.

Olle

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



Re: [PHP-DEV] Does PHP ever stack allocate?

2021-01-04 Thread Olle Härstedt
2021-01-03 17:43 GMT, tyson andre :
> Hi Olle,
>
>> Thanks Sara! I realize I should have been more precise: Can PHP
>> allocate non-reference counted memory that automatically is freed when
>> leaving scope, similar to what Go does with escape analysis?
>>
>> Article describing the Go mechanism:
>> https://segment.com/blog/allocation-efficiency-in-high-performance-go-services/
>
> Could you give some concrete examples of what type of code you're talking
> about?
> As Sara Golemon said, scalars (null, bool, int, float) are allocated on a
> php call frame,
> and the call frames go on a stack. That stack is separate from the C stack,
> but still a stack
>
> The call frame is "freed" when leaving scope - i.e. that part of the stack
> will be reused on subsequent calls.

Sure. Consider the following trivial snippet:

```php
class Point {
  public $x;
  public $y;
}
function foo() {
  $p = new Point();
  return $p->x + $p->y;
}
```

Since we know the lifetime of $p, we don't have to ref count it.
Escape analysis helps with checking lifetimes and to remove needles
ref counting (and heap allocations in compiled languages). There is a
file in php-src for this:
https://github.com/php/php-src/blob/master/ext/opcache/Optimizer/escape_analysis.c

My question was about how this functionality is used.

>> A single PHP call frame holds a block of storage space for (among other
>> things) all* local variables.  This can be thought of analogously to "the
>> stack" as it's used by native applications.  Basic scalars (null, bool,
>> int, float) sit in this space with no additional pointers to anywhere.
>> Non-scalars use pointers to elsewhere in the heap to store the actual
>> payload.  This isn't unique to PHP, as these structures have runtime
>> determined size and thus can't** be stack allocated.
>
> https://nikic.github.io/2017/04/14/PHP-7-Virtual-machine.html may help if
> you want to learn more about what the PHP VM currently does

Nice link, thanks!

Olle

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



Re: [PHP-DEV] Analysis of property visibility, immutability, and cloning proposals

2021-01-03 Thread Olle Härstedt
2021-01-03 16:55 GMT, Larry Garfield :
> On Sun, Jan 3, 2021, at 8:28 AM, Olle Härstedt wrote:
>
>> >> I like that you connect higher level design patterns with language
>> >> design. This is the way to go, IMO. Personally, I'd prefer support for
>> >> the Psalm notation `@psalm-readonly`, which is the same as your
>> >> initonly. Clone-with makes sense too, as this construct is already
>> >> supported in multiple languages. The exact notation doesn't matter
>> >> that much - my personal choice is OCaml {record with x = 10} over JS
>> >> spread operator, but OCaml is pretty "wordy" in notation in contrast
>> >> to the C tradition that PHP is part of.
>> >>
>> >> Reintroducing "objects that pass by value" is a hard pass from me. The
>> >> way forward is immutability and constrained mutability (ownership,
>> >> escape analysis, etc). Psalm also supports array shapes - maybe this
>> >> can be investigated as an alternative? Since PHP has no tuples.
>> >>
>> >> I'm not convinced the added complexity of asymmetric visibility is
>> >> powerful enough to motivate its existence. Feel free to prove me
>> >> wrong. :) My choice here would be namespace "internal" (also supported
>> >> by Psalm already), but this requires implementation of namespace
>> >> visibility, a PR that was abandoned.
>> >>
>> >> And also, happy new year!
>> >
>> > Happy New Year!
>> >
>> > I agree that "objects, but passing by value" would not be the right
>> > solution. I used to think that would be a good part of the solution,
>> > but
>> > eventually concluded that it would introduce more complexity, not less.
>> > Eventually, everything people wanted to do with objects they'd want to
>> > do
>> > with "Records" (for lack of a better term), and if they pass by value
>> > but
>> > are still mutable then you have a weird situation where sometimes
>> > changes
>> > propagate and some don't (depending on if you have a record or object).
>> > Making it easier to use objects in a value-esque way will get us closer
>> > to
>> > the desired end state.
>> >
>> > I think the tldr of my post is this: A single "immutable" flag
>> > (whatever
>> > it's called) on a class or property would require having lots of holes
>> > poked
>> > in it in order to make it useful in practice (mostly what "initonly"
>> > would
>> > do), but those holes would introduce other holes we don't want (cloning
>> > an
>> > object from the outside when you shouldn't).
>>
>> I new language feature needs to be both simple and powerful - it's not
>> enough to be only powerful. A second problem I see is how asymmetric
>> visibility would affect the readability of a class, putting extra
>> strain in understanding it. Thirdly, how does PHP differ from FP
>> languages like OCaml and Haskell in this regard, neither who uses
>> visibility in this way? What's acceptable in those languages that
>> would be unacceptable in PHP?
>>
>> Olle
>
> I'll disagree slightly.  A language feature should introduce more power than
> it does complexity.  Not everything *can* be made absolutely simple, but the
> power it offers is worth it.  I'd say it should minimize introduced
> complexity, relative to the power offered.  Complexity ideally is super low,
> but it's never zero simply by virtue of being "one more thing" that
> developers need to know how to read.
>
> So in this case, we need to compare the power/complexity of asymmetric
> visibility vs the power/complexity of "immutable... except in these
> situations."  I would argue that asymmetric visibility is more
> self-documenting, because it states explicitly what those situations are.
>
> The other point is that, as noted, "initonly" creates a gap if you have
> properties that are inter-dependent.  Those then cannot be made public-read,
> because that would also mean public-clone-with, and thus allow callers to
> violate property relationships.  Asymmetric visibility does not have that
> problem.

Can you perhaps be a bit more clear on why initonly/readonly would be
a deal breaker? Seems to me like readonly would cover 80% of
use-cases? Which is to make data-value objects humane (and fast, since
you don't need getters anymore) to work with. Seems like you're
focusing too much on an edge case here. Maybe we should list the
possibly use-cases? Or at least the main target use-case.

If an object has invariants that need to hold, just throw an exception
in __clone to force use with withX() instead? Or, as you suggested,
improve __clone by giving it arguments?

Olle

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



Re: [PHP-DEV] Does PHP ever stack allocate?

2021-01-03 Thread Olle Härstedt
2021-01-03 16:15 GMT, Sara Golemon :
> On Fri, Jan 1, 2021 at 3:18 PM Olle Härstedt 
> wrote:
>
>> Or is everything reference counted with heap allocation? Since PHP has
>> escape analysis, this could be used to use the stack instead, and kill
>> the
>> memory when the scope ends. If PHP uses the stack, can this be seen in
>> the
>> opcode?
>>
>>
> Well, you're not going to like this answer, but yes and no.
>
> A single PHP call frame holds a block of storage space for (among other
> things) all* local variables.  This can be thought of analogously to "the
> stack" as it's used by native applications.  Basic scalars (null, bool,
> int, float) sit in this space with no additional pointers to anywhere.
> Non-scalars use pointers to elsewhere in the heap to store the actual
> payload.  This isn't unique to PHP, as these structures have runtime
> determined size and thus can't** be stack allocated.
>
> There's further asterii below all of those statements, but that's the
> high-level generalized answer to your question as posed.
>
> The implied question you asked is actually handled using another
> mechanism.  PHP's internals have two separate memory allocation pools.
> "Persistent" memory allocation, which creates blocks of memory for the
> lifetime of the process, and "Engine" memory allocation, which are bulk
> de-allocated*** at the end of every request (after relevant
> destructors have fired).
>
> -Sara
>
> * All variables which are explicitly references as $foo (excluding
> auto-globals).  ${'bar'} and $$baz style references to locals are special
> and require their own separate conversation.
> ** C's alloca() and similar techniques in other languages can reserve
> dynamic amounts of stack space, but let's ignore that power-move for the
> sake of this argument.
> *** Deallocated from the request handler's point of view, though the
> runtime's memory manager (usually) doesn't give it back to the OS
> immediately, since it's likely to be used by the next request anyway.
>

Thanks Sara! I realize I should have been more precise: Can PHP
allocate non-reference counted memory that automatically is freed when
leaving scope, similar to what Go does with escape analysis?

Article describing the Go mechanism:
https://segment.com/blog/allocation-efficiency-in-high-performance-go-services/

Olle

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



Re: [PHP-DEV] Analysis of property visibility, immutability, and cloning proposals

2021-01-03 Thread Olle Härstedt
2021-01-02 16:06 GMT, Larry Garfield :
> On Fri, Jan 1, 2021, at 5:51 PM, Olle Härstedt wrote:
>
>> >> The web dev discourse is
>> >> one-sided with regard to immutability,
>> >
>> > Yes, if you've heard any of the regular whining about PSR-7 being an
>> > immutable object you'd think it's one-sided in favor of mutability. ;-)
>> >
>> > As you say, the point here is to add tools.  Right now, doing
>> > immutability
>> > in PHP in syntactically clumsy and ugly.  We want to fix that, and that
>> > has
>> > to include some means of "give me a new value based on this existing
>> > value
>> > but with some difference."  (aka, exactly what with-er methods do,
>> > although
>> > I agree entirely that if you have the option of less generic names, use
>> > them).
>> >
>> > So, can we get back to the original post, which is proposing specifics
>> > of
>> > the tools to make that happen? :-)  (Asymmetric visibility and
>> > clone-with,
>> > specifically.)
>> >
>>
>> OK!
>>
>> I like that you connect higher level design patterns with language
>> design. This is the way to go, IMO. Personally, I'd prefer support for
>> the Psalm notation `@psalm-readonly`, which is the same as your
>> initonly. Clone-with makes sense too, as this construct is already
>> supported in multiple languages. The exact notation doesn't matter
>> that much - my personal choice is OCaml {record with x = 10} over JS
>> spread operator, but OCaml is pretty "wordy" in notation in contrast
>> to the C tradition that PHP is part of.
>>
>> Reintroducing "objects that pass by value" is a hard pass from me. The
>> way forward is immutability and constrained mutability (ownership,
>> escape analysis, etc). Psalm also supports array shapes - maybe this
>> can be investigated as an alternative? Since PHP has no tuples.
>>
>> I'm not convinced the added complexity of asymmetric visibility is
>> powerful enough to motivate its existence. Feel free to prove me
>> wrong. :) My choice here would be namespace "internal" (also supported
>> by Psalm already), but this requires implementation of namespace
>> visibility, a PR that was abandoned.
>>
>> And also, happy new year!
>
> Happy New Year!
>
> I agree that "objects, but passing by value" would not be the right
> solution. I used to think that would be a good part of the solution, but
> eventually concluded that it would introduce more complexity, not less.
> Eventually, everything people wanted to do with objects they'd want to do
> with "Records" (for lack of a better term), and if they pass by value but
> are still mutable then you have a weird situation where sometimes changes
> propagate and some don't (depending on if you have a record or object).
> Making it easier to use objects in a value-esque way will get us closer to
> the desired end state.
>
> I think the tldr of my post is this: A single "immutable" flag (whatever
> it's called) on a class or property would require having lots of holes poked
> in it in order to make it useful in practice (mostly what "initonly" would
> do), but those holes would introduce other holes we don't want (cloning an
> object from the outside when you shouldn't).

I new language feature needs to be both simple and powerful - it's not
enough to be only powerful. A second problem I see is how asymmetric
visibility would affect the readability of a class, putting extra
strain in understanding it. Thirdly, how does PHP differ from FP
languages like OCaml and Haskell in this regard, neither who uses
visibility in this way? What's acceptable in those languages that
would be unacceptable in PHP?

Olle

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



Re: [PHP-DEV] Analysis of property visibility, immutability, and cloning proposals

2021-01-02 Thread Olle Härstedt
2021-01-02 21:25 GMT, Larry Garfield :
> On Sat, Jan 2, 2021, at 12:56 PM, Rowan Tommins wrote:
>> On 01/01/2021 20:31, Paul M. Jones wrote:
>> > The complaints against the incomplete and inconsistent immutability of
>> > PSR-7 have merit.
>>
>>
>> The big mistake of PSR-7, in my view, is mixing immutable objects with
>> streams, which are inherently mutable/stateful. I wonder if there are
>> any lessons to be learned there in terms of what kinds of immutability
>> the language should encourage / make easy.
>>
>> For instance, is it better to constrain entire objects to be immutable
>> rather than individual properties? And should there be restrictions on
>> what you can declare as immutable, since "immutable resource" is largely
>> nonsensical?
>>
>> Or is it rather a reflection that building purely immutable
>> implementations is hard, and the language needs other facilities
>> (monads? ownership?) to mix in those parts that don't fit?
>>
>> Regards,
>
> I rarely hear that called out as a PSR-7 complaint specifically, in
> practice, but moving on...
>
> IMO, it's better to put the focus on immutable properties.  There are use
> cases where you want only some properties to be immutable, but not the whole
> class.  If you do want the whole class, then marking all the properties
> immutable is effectively the same thing.
>
> Though, again, in practice, at least in PHP, I don't think immutable
> properties should be the goal.  Asymmetric visibility lets us built safely
> immutable-from-the-outside objects that are "up to you" on the inside.  I
> think that gives us a better end result given the nature of PHP.  In other
> languages that wouldn't make as much sense, but PHP is what it is.
>
> Copy on write makes "immutable data structures" not something we need to
> build explicitly; we get "close enough" for free.  If you really wanted to
> micro-optimize the memory and CPU usage further than that... go build it in
> Rust instead.

Correct me if I'm wrong, but copy-on-write is only beneficial with
values, not references to values (objects)? When you clone with a
`with` method, you always write, so you always have to copy. And
objects are already free to pass around without any copying happening
automatically (as is the case with arrays, which have value semantics,
which is why copy-on-write was implemented to not copy needlessly when
an array is only read from).

Olle

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



Re: [PHP-DEV] Analysis of property visibility, immutability, and cloning proposals

2021-01-01 Thread Olle Härstedt
2021-01-01 19:14 GMT, Larry Garfield :
> On Thu, Dec 31, 2020, at 8:04 AM, Olle Härstedt wrote:
>> 2020-12-31 12:37 GMT, Rowan Tommins :
>
>> > On 30/12/2020 18:42, Olle Härstedt wrote:
>> >>> To put it a different way, value types naturally form*expressions*,
>> >>> which mutable objects model clumsily. It would be very tedious if we
>> >>> had
>> >>> to avoid accidentally mutating the speed of light:
>> >>>
>> >>> $e = (clone $m) * ((clone $c) ** 2);
>> >> Using a variable on right-hand side does not automatically create an
>> >> alias, so in the above case you don't have to use clone.
>> >
>> >
>> > Whether or not the type system forced you to, you'd have to use clone
>> > if
>> > the values were implemented as mutable. Switching to methods again may
>> > make that clearer:
>> >
>> > $c = new MyNumber(299_792_458);
>> > $m = new MyNumber(10);
>> > $e = $m->multiply( $c->square() );
>> >
>> > If multiply() and square() are mutating state, rather than returning
>> > new
>> > instances, $c is now 89875517873681764, which is going to totally mess
>> > up the universe...
>> >
>> >
>> > Regards,
>> >
>> > --
>> > Rowan Tommins
>> > [IMSoP]
>>
>> Yes, of course you can find use-cases where immutability is a better
>> choice, just like I can find use-cases where (constrained) mutability
>> is better. The point is not to replace one tool with another, but
>> rather adding another tool to the toolbox. The web dev discourse is
>> one-sided with regard to immutability, I think. Wish I had time to
>> implement a PR to Psalm to show something more concrete... Again, if
>> you only have a hammer, everything looks like a nail. :)
>>
>> Olle
>
>> The web dev discourse is
>> one-sided with regard to immutability,
>
> Yes, if you've heard any of the regular whining about PSR-7 being an
> immutable object you'd think it's one-sided in favor of mutability. ;-)
>
> As you say, the point here is to add tools.  Right now, doing immutability
> in PHP in syntactically clumsy and ugly.  We want to fix that, and that has
> to include some means of "give me a new value based on this existing value
> but with some difference."  (aka, exactly what with-er methods do, although
> I agree entirely that if you have the option of less generic names, use
> them).
>
> So, can we get back to the original post, which is proposing specifics of
> the tools to make that happen? :-)  (Asymmetric visibility and clone-with,
> specifically.)
>

OK!

I like that you connect higher level design patterns with language
design. This is the way to go, IMO. Personally, I'd prefer support for
the Psalm notation `@psalm-readonly`, which is the same as your
initonly. Clone-with makes sense too, as this construct is already
supported in multiple languages. The exact notation doesn't matter
that much - my personal choice is OCaml {record with x = 10} over JS
spread operator, but OCaml is pretty "wordy" in notation in contrast
to the C tradition that PHP is part of.

Reintroducing "objects that pass by value" is a hard pass from me. The
way forward is immutability and constrained mutability (ownership,
escape analysis, etc). Psalm also supports array shapes - maybe this
can be investigated as an alternative? Since PHP has no tuples.

I'm not convinced the added complexity of asymmetric visibility is
powerful enough to motivate its existence. Feel free to prove me
wrong. :) My choice here would be namespace "internal" (also supported
by Psalm already), but this requires implementation of namespace
visibility, a PR that was abandoned.

And also, happy new year!

Olle

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



[PHP-DEV] Does PHP ever stack allocate?

2021-01-01 Thread Olle Härstedt
Or is everything reference counted with heap allocation? Since PHP has
escape analysis, this could be used to use the stack instead, and kill the
memory when the scope ends. If PHP uses the stack, can this be seen in the
opcode?

This stackoverflow thread does not really answer my question.

https://stackoverflow.com/questions/24223249/stack-and-heap-in-php#:~:text=In%20static%20typed%20languages%20all,known%20until%20the%20run%20time
.

Olle


Re: [PHP-DEV] Analysis of property visibility, immutability, and cloning proposals

2020-12-31 Thread Olle Härstedt
2020-12-31 12:37 GMT, Rowan Tommins :
> Hi Mike and Olle,
>
>
> On 31/12/2020 00:24, Mike Schinkel wrote:
>> A different perspective is that "withX" methods require a mental
>> translation where "addX" methods do not, much like how a person whose
>> native language is English will find it a challenge to (or cannot) "think"
>> in French.
>
>
> I wonder if that's just about the choice of names, rather than the
> mutability/immutability itself?
>
>
>>> $start = MyDate::today();
>>> $end = $start->withAddedDays(5);
>>>
>>> vs
>>>
>>> $start = MyDate::today();
>>> $end = clone $start;
>>> $end->addDays(5);
>> Ignoring that you are comparing apples and oranges (scalars to objects,)
>> the latter is easier to reason about IMO.
>
>
> Ignoring the distinction between "scalar" and "object" was kind of the
> point: they are both "values", and are more naturally treated the same
> as differently.
>
>
> To take a different example, consider writing a new number type (for
> arbitrary precision, or complex numbers, or whatever), with an "add"
> method.
>
> The mutable version looks something like this:
>
> public function add($other) {
>  $this->value = $this->value + $other;
> }
>
> and has to be used like this:
>
> $start = new MyNumber(1);
> $end = clone $start;
> $end->add(5);
>
>
> The immutable version might look more like this:
>
> public function add($other) {
>  return clone $this with { value: $this->value + $other };
> }
>
> and is used like this:
>
> $start = new MyNumber(1);
> $end = $start->add(5);
>
> That's much closer to the "$end = $start + 5;" we're used to.
>
>
> On 30/12/2020 18:42, Olle Härstedt wrote:
>>> To put it a different way, value types naturally form*expressions*,
>>> which mutable objects model clumsily. It would be very tedious if we had
>>> to avoid accidentally mutating the speed of light:
>>>
>>> $e = (clone $m) * ((clone $c) ** 2);
>> Using a variable on right-hand side does not automatically create an
>> alias, so in the above case you don't have to use clone.
>
>
> Whether or not the type system forced you to, you'd have to use clone if
> the values were implemented as mutable. Switching to methods again may
> make that clearer:
>
> $c = new MyNumber(299_792_458);
> $m = new MyNumber(10);
> $e = $m->multiply( $c->square() );
>
> If multiply() and square() are mutating state, rather than returning new
> instances, $c is now 89875517873681764, which is going to totally mess
> up the universe...
>
>
> Regards,
>
> --
> Rowan Tommins
> [IMSoP]

Yes, of course you can find use-cases where immutability is a better
choice, just like I can find use-cases where (constrained) mutability
is better. The point is not to replace one tool with another, but
rather adding another tool to the toolbox. The web dev discourse is
one-sided with regard to immutability, I think. Wish I had time to
implement a PR to Psalm to show something more concrete... Again, if
you only have a hammer, everything looks like a nail. :)

Olle

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



  1   2   >