xp-framework / compiler

Compiles future PHP to today's PHP.
19 stars 0 forks source link

#Override annotation #149

Closed thekid closed 1 year ago

thekid commented 1 year ago

See https://github.com/php/php-src/pull/9836, here's a proof of concept in the PHP emitter:

diff --git a/src/main/php/lang/ast/emit/PHP.class.php b/src/main/php/lang/ast/emit/PHP.class.php
index f36183a..c94f2c0 100755
--- a/src/main/php/lang/ast/emit/PHP.class.php
+++ b/src/main/php/lang/ast/emit/PHP.class.php
@@ -607,7 +607,16 @@ abstract class PHP extends Emitter {
     ];

     $method->comment && $this->emitOne($result, $method->comment);
-    $method->annotations && $this->emitOne($result, $method->annotations);
+
+    if ($method->annotations) {
+      $this->emitOne($result, $method->annotations);
+      if ($method->annotations->named(\Override::class)) {
+        if (null === ($parent= $result->lookup('parent')) || !$parent->providesMethod($method->name)) {
+          throw new \lang\IllegalStateException($result->type[0]->name.'::'.$method->name.'() does not override anything');
+        }
+      }
+    }
+
     $result->at($method->declared)->out->write(implode(' ', $method->modifiers).' function '.$method->name);

     $promoted= [];

The questions that this raises:

thekid commented 1 year ago

This would also bring up the discussion whether https://wiki.php.net/rfc/deprecated_attribute should be implemented.

thekid commented 1 year ago

See https://externals.io/message/120233

thekid commented 1 year ago

https://blog.softwaremill.com/the-case-against-annotations-4b2fb170ed67

There are some great use-cases. For example, the @Override and @FunctionalInterface annotations in Java or @tailrec in Scala. These are checked at compile-time and provide actionable value to the programmer. [...] Some languages, like Ceylon, take this idea even further — there are no modifiers, only annotations; or Scala, where override is a regular keyword.

thekid commented 1 year ago

https://wiki.php.net/rfc/marking_overriden_methods is in voting, 22:1 at the time of writing.

thekid commented 1 year ago

Implemented -> https://github.com/php/php-src/commit/49ef6e209d8fbcb4694ecd59b9078498f0dffb73

thekid commented 1 year ago

Released in Released in https://github.com/xp-framework/compiler/releases/tag/v8.15.0