AST for the XP Framework


README

Build status on GitHub XP Framework Module BSD Licence Requires PHP 7.4+ Supports PHP 8.0+ Latest Stable Version

Abstract syntax tree library used for XP Compiler.

Example

use lang\ast\{Language, Tokens};

$tree= Language::named('PHP')->parse(new Tokens('echo PHP_VERSION;'))->tree();

// lang.ast.ParseTree(source: (string))@{
//   scope => lang.ast.Scope {
//     parent => null
//     package => null
//     imports => []
//     types => []
//   }
//   children => [lang.ast.nodes.EchoStatement {
//     kind => "echo"
//     expressions => [lang.ast.nodes.Literal {
//       kind => "literal"
//       expression => "PHP_VERSION"
//       line => 1
//     }]
//     line => 1
//   }]
// }

Compile-time metaprogramming

Register transformations by creating classes inside the lang.ast.syntax.php package - see xp-framework/rfc#327

namespace lang\ast\syntax\php;

use lang\ast\Code;
use lang\ast\nodes\{Method, Signature};
use lang\ast\syntax\Extension;
use codegen\Getters;

class CreateGetters implements Extension {

  public function setup($language, $emitter) {
    $emitter->transform('class', function($codegen, $class) {
      if ($class->annotation(Getters::class)) {
        foreach ($class->properties() as $property) {
          $class->declare(new Method(
            ['public'],
            $property->name,
            new Signature([], $property->type),
            [new Code('return $this->'.$property->name)]
          ));
        }
      }
      return $class;
    });
  }
}

When compiling the following sourcecode, getters for the id and name members will automatically be added.

use codegen\Getters;

#[Getters]
class Person {
  private int $id;
  private string $name;

  public function __construct(int $id, string $name) {
    $this->id= $id;
    $this->name= $name;
  }
}