PHP>> ast>> 返回
项目作者: xp-framework

项目描述 :
AST for the XP Framework
高级语言: PHP
项目地址: git://github.com/xp-framework/ast.git
创建时间: 2017-11-05T14:13:46Z
项目社区:https://github.com/xp-framework/ast

开源协议:

下载


XP AST

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

  1. use lang\ast\{Language, Tokens};
  2. $tree= Language::named('PHP')->parse(new Tokens('echo PHP_VERSION;'))->tree();
  3. // lang.ast.ParseTree(source: (string))@{
  4. // scope => lang.ast.Scope {
  5. // parent => null
  6. // package => null
  7. // imports => []
  8. // types => []
  9. // }
  10. // children => [lang.ast.nodes.EchoStatement {
  11. // kind => "echo"
  12. // expressions => [lang.ast.nodes.Literal {
  13. // kind => "literal"
  14. // expression => "PHP_VERSION"
  15. // line => 1
  16. // }]
  17. // line => 1
  18. // }]
  19. // }

Compile-time metaprogramming

Register transformations by creating classes inside the lang.ast.syntax.php package - see https://github.com/xp-framework/rfc/issues/327

  1. namespace lang\ast\syntax\php;
  2. use lang\ast\Code;
  3. use lang\ast\nodes\{Method, Signature};
  4. use lang\ast\syntax\Extension;
  5. use codegen\Getters;
  6. class CreateGetters implements Extension {
  7. public function setup($language, $emitter) {
  8. $emitter->transform('class', function($codegen, $class) {
  9. if ($class->annotation(Getters::class)) {
  10. foreach ($class->properties() as $property) {
  11. $class->declare(new Method(
  12. ['public'],
  13. $property->name,
  14. new Signature([], $property->type),
  15. [new Code('return $this->'.$property->name)]
  16. ));
  17. }
  18. }
  19. return $class;
  20. });
  21. }
  22. }

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

  1. use codegen\Getters;
  2. #[Getters]
  3. class Person {
  4. private int $id;
  5. private string $name;
  6. public function __construct(int $id, string $name) {
  7. $this->id= $id;
  8. $this->name= $name;
  9. }
  10. }