xp-framework/compiler


README

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

将未来的 PHP 编译成今天的 PHP。

用法

通过在项目中添加编译器 composer require xp-framework/compiler,它将挂钩到类加载链,并按需编译 .php 文件。这保持了 PHP 典型的代码保存-重新加载/重新运行的开发过程。

示例

以下代码使用 Hack 语言,PHP 8.4、PHP 8.3、PHP 8.2、8.1 和 8.0 功能,但可以在任何 >= PHP 7.4 的环境中运行。如果需要,新版本 PHP 的内置功能将被转换为与当前执行环境兼容。

<?php // In a file "HelloWorld.php"

use lang\Reflection;
use util\Date;
use util\cmd\Console;

#[Author('Timm Friebe')]
#[Permissions(0o777)]
class HelloWorld {
  private const string GREETING= 'Hello';

  public static function main(array<string> $args): void {
    $greet= fn($to, $from) => self::GREETING.' '.$to.' from '.$from;
    $author= Reflection::type(self::class)->annotation(Author::class)->argument(0);

    Console::writeLine(new Date()->toString(), ': ', $greet($args[0] ?? 'World', from: $author));
  }
}

要在终端窗口中运行此代码,请使用 xp -m /path/to/xp/reflection HelloWorld

编译

也可以通过调用编译器显式地执行编译

# Compile code and write result to a class file
$ xp compile HelloWorld.php HelloWorld.class.php

# Compile standard input and write to standard output.
$ echo "<?php ..." | xp compile -

# Compile src/main/php and src/test/php to the dist folder.
$ xp compile -o dist src/main/php/ src/test/php/

# Compile src/main/php to the dist.xar archive
$ xp compile -o dist.xar src/main/php/

# Compile src/main/php, do not write output
$ xp compile -n src/main/php/

# Target PHP 7.4 (default target is current PHP version)
$ xp compile -t php:7.4 HelloWorld.php HelloWorld.class.php

# Emit XP meta information (includes lang.ast.emit.php.XpMeta):
$ xp compile -t php:7.4 -a php:xp-meta -o dist src/main/php

-o 和 -n 选项接受多个输入源。-q 选项抑制所有诊断输出,除了错误。

支持的功能

XP 编译器支持诸如注解、箭头函数、枚举、属性类型提示、null 安全实例操作符以及 PHP 7 和 PHP 8 语法添加的所有功能。完整列表包括示例,可以在我们的 Wiki 中找到 这里

更多功能

可以通过安装来自 这里 的编译器插件添加额外的语法,如 is 操作符、泛型或记录类型。

$ composer require xp-lang/php-is-operator
# ...

$ xp compile
Usage: xp compile <in> [<out>]

@FileSystemCL<./vendor/xp-framework/compiler/src/main/php>
lang.ast.emit.PHP74
lang.ast.emit.PHP80
lang.ast.emit.PHP81
lang.ast.emit.PHP82
lang.ast.emit.PHP83 [*]
lang.ast.emit.PHP84
lang.ast.syntax.php.Using [*]

@FileSystemCL<./vendor/xp-lang/php-is-operator/src/main/php>
lang.ast.syntax.php.IsOperator

实现状态

新版本 PHP 的一些功能以及 Hack 语言的功能仍然缺失。然而,目标是实现所有功能——除了 Hack 的方向与 PHP 冲突的地方!概述可以在 这个 Wiki 页面 上看到。

要贡献,请打开问题报告和/或拉取请求。

另请参阅