Skip to content

Add support for single-expression methods#58

Closed
thekid wants to merge 1 commit into
masterfrom
feature/single-expression-methods
Closed

Add support for single-expression methods#58
thekid wants to merge 1 commit into
masterfrom
feature/single-expression-methods

Conversation

@thekid
Copy link
Copy Markdown
Member

@thekid thekid commented Jul 19, 2025

This PR adds syntactic support for single-expression methods

class Person {
  public function __construct(private string $name) { }

  // Equivalent of public function name() { return $this->name; }
  public function name() => $this->name;
}

See:

@thekid
Copy link
Copy Markdown
Member Author

thekid commented Aug 2, 2025

RFC has been declined

@thekid
Copy link
Copy Markdown
Member Author

thekid commented Oct 3, 2025

This would be consistent with the abbreviated property hooks syntax:

class User {
  public function __construct(private string $first, private string $last) {}
 
  // Long form
  public string $fullName {
    get { 
      return $this->first.' '.$this->last;
    }
  }

  // Short form
  public string $fullName {
    get => $this->first.' '.$this->last;
  }

  // Long form
  public string $username {
    set(string $value) {
      $this->username= strtolower($value);
    }
  }
 
  // Short form
  public string $username {
    set => strtolower($value);
  }
}

...which sets => [exor] as an equivalent of { return [expr]; }.

$parse->expecting('}', 'method declaration');
} else if ('=>' === $parse->token->value) { // Single expression
$parse->forward();
$statements= [new ReturnStatement($this->expression($parse, 0), $parse->token->line)];
Copy link
Copy Markdown
Member Author

@thekid thekid Oct 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is inconsistent with how short and long forms of property accessors are parsed - they make use of the Block class:

  • body for => [expr]: Expr
  • body for { [statement]; }: Block([Statement])

@thekid
Copy link
Copy Markdown
Member Author

thekid commented May 16, 2026

This adds an inconsistency with fn() => { ... } (see https://wiki.php.net/rfc/arrow_functions_v2#multi-statement_bodies) which is supported by this parser.

Idea

What should work

Methods:

class T {
  public function name() => $this->name; // 🆕

  // Equivalent of
  // public function name() { return $this->name; }
}

Binding closures:

fn($a, $b) => $a + $b;

// Equivalent of
// fn($a, $b) { return $a + $b; } // 🆕

Closures:

function($a, $b) => $a + $b; // 🆕

// Equivalent of
// function($a, $b) { return $a + $b; }

Functions:

function add($a, $b) => $a + $b; // 🆕

// Equivalent of
// function add($a, $b) { return $a + $b; }

Consistency with other constructs

Property hooks:

class Entry implements Value {
  private $attributes= [];

  public string $slug {
    get => $this->attributes['slug'];

    // Equivalent of
    // get { return $this->attributes['slug']; }
  }
}

Match statement:

match ($response->status()) {
  204 => null,
  200 => $response->value(),
  404 {                         // 🆕 https://wiki.php.net/rfc/match_expression_v2#blocks
    if ($optional) return null;

    throw new NoSuchElementException('...');
  },
}

In all cases, a single expression should be parsed into the node representing it, while multiple statements should form a Block.


Another way to think about this is in the video https://youtu.be/bYnJA9qt_94

image


⚠️ The fn() => { ... } form should be deprecated.

@thekid
Copy link
Copy Markdown
Member Author

thekid commented May 23, 2026

Support fn() { ... }

This library:

diff --git a/src/main/php/lang/ast/syntax/PHP.class.php b/src/main/php/lang/ast/syntax/PHP.class.php
index 35346ca..5b2e7db 100755
--- a/src/main/php/lang/ast/syntax/PHP.class.php
+++ b/src/main/php/lang/ast/syntax/PHP.class.php
@@ -400,9 +400,8 @@ class PHP extends Language {
 
     $this->prefix('fn', 0, function($parse, $token) {
       $signature= $this->signature($parse);
-      $parse->expecting('=>', 'fn');
-
-      return new LambdaExpression($signature, $this->expression($parse, 0), false, $token->line);
+      $function= $this->function($parse, 'fn');
+      return new LambdaExpression($signature, $function, false, $token->line);
     });
 
     $this->prefix('function', 0, function($parse, $token) {
@@ -435,8 +434,8 @@ class PHP extends Language {
       } else if ('fn' === $parse->token->value) {
         $parse->forward();
         $signature= $this->signature($parse);
-        $parse->expecting('=>', 'fn');
-        return new LambdaExpression($signature, $this->expression($parse, 0), true, $token->line);
+        $function= $this->function($parse, 'fn');
+        return new LambdaExpression($signature, $function, true, $token->line);
       } else {
         return new Literal($token->value, $token->line);
       }
@@ -1591,6 +1590,22 @@ class PHP extends Language {
     return $parameters;
   }
 
+  public function function($parse, $context) {
+    if ('=>' === $parse->token->value) {
+      $parse->forward();
+      return $this->expression($parse, 0);
+    } else if ('{' === $parse->token->value) {
+      $line= $parse->token->line;
+      $parse->forward();
+      $statements= $this->statements($parse);
+      $parse->expecting('}', $context);
+      return new Block($statements, $line);
+    } else {
+      $parse->expecting('=> or { ... }', $context);
+      return null;
+    }
+  }
+
   public function body($id, $func) {
     $this->body[$id]= $func->bindTo($this, static::class);
   }
diff --git a/src/test/php/lang/ast/unittest/parse/LambdasTest.class.php b/src/test/php/lang/ast/unittest/parse/LambdasTest.class.php
index ad6ce41..86565a2 100755
--- a/src/test/php/lang/ast/unittest/parse/LambdasTest.class.php
+++ b/src/test/php/lang/ast/unittest/parse/LambdasTest.class.php
@@ -42,6 +42,33 @@ class LambdasTest extends ParseTest {
 
   #[Test]
   public function short_closure_with_block() {
+    $this->assertParsed(
+      [new LambdaExpression(
+        new Signature([$this->parameter], null, false, self::LINE),
+        new Block([new ReturnStatement($this->expression, self::LINE)], self::LINE),
+        false,
+        self::LINE
+      )],
+      'fn($a) { return $a + 1; };'
+    );
+  }
+
+  #[Test]
+  public function static_short_closure_with_block() {
+    $this->assertParsed(
+      [new LambdaExpression(
+        new Signature([$this->parameter], null, false, self::LINE),
+        new Block([new ReturnStatement($this->expression, self::LINE)], self::LINE),
+        true,
+        self::LINE
+      )],
+      'static fn($a) { return $a + 1; };'
+    );
+  }
+
+  /** @deprecated */
+  #[Test]
+  public function short_closure_with_arrow_and_block() {
     $this->assertParsed(
       [new LambdaExpression(
         new Signature([$this->parameter], null, false, self::LINE),

Compiler:

diff --git a/src/test/php/lang/ast/unittest/emit/LambdasTest.class.php b/src/test/php/lang/ast/unittest/emit/LambdasTest.class.php
index 26ad8fd..1de0506 100755
--- a/src/test/php/lang/ast/unittest/emit/LambdasTest.class.php
+++ b/src/test/php/lang/ast/unittest/emit/LambdasTest.class.php
@@ -193,7 +193,7 @@ class LambdasTest extends EmittingTest {
   public function with_block() {
     $r= $this->run('class %T {
       public function run() {
-        return fn() => {
+        return fn() {
           $a= 1;
           return $a + 1;
         };
@@ -208,7 +208,7 @@ class LambdasTest extends EmittingTest {
     $r= $this->run('class %T {
       public function run() {
         $a= 1;
-        return fn() => {
+        return fn() {
           return $a + 1;
         };
       }
@@ -231,7 +231,7 @@ class LambdasTest extends EmittingTest {
     $r= $this->run('class %T {
       public function run(iterable $records) {
         $nonNull= fn($record) => null !== $record;
-        $process= fn($records, $filter) => {
+        $process= fn($records, $filter) {
           foreach ($records as $record) {
             if ($filter($record)) yield $record;
           }

@thekid
Copy link
Copy Markdown
Member Author

thekid commented May 23, 2026

Superseded by #61

@thekid thekid closed this May 23, 2026
@thekid thekid deleted the feature/single-expression-methods branch May 23, 2026 18:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant