PHPackages                             lwlwilliam/tiny-compiler - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. lwlwilliam/tiny-compiler

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

lwlwilliam/tiny-compiler
========================

A toy compiler written in PHP

03PHP

Since May 14Pushed 1mo agoCompare

[ Source](https://github.com/lwlwilliam/tiny-compiler)[ Packagist](https://packagist.org/packages/lwlwilliam/tiny-compiler)[ RSS](/packages/lwlwilliam-tiny-compiler/feed)WikiDiscussions main Synced today

READMEChangelogDependenciesVersions (1)Used By (0)

原生 PHP 实现的小型编译器
---------------

[](#原生-php-实现的小型编译器)

用原生 PHP 实现的一个小型编译器，无第三方依赖，包含词法分析、语法分析、字节码生成、虚拟机执行四个阶段。支持将源码编译为 `.bc` 字节码文件，之后可脱离编译器单独运行。

### 编译器流水线

[](#编译器流水线)

```
源码 (.l)
  → Lexer (词法分析) → Token 流
  → Parser (语法分析) → AST
  → CodeGen (代码生成) → ModuleBC (字节码模块)
  → VM (虚拟机执行)

        ↓ compile.php

      .bc 字节码文件（可单独分发、运行）

```

### 要求

[](#要求)

`PHP 8.3` 或 `PHP 8.4`。

### 安装

[](#安装)

```
$ composer require lwlwilliam/tiny-compiler:dev-main
```

### 运行源码

[](#运行源码)

```
$ php examples/run.php examples/codes/demo.l
```

输出：

```
y = 44; z = 9; foo = 10
arr = [1,42,3]
add(3, 4) = 7
fact(10) = 55
twice(8) = 16
GREETING = Hello
y > 20
sum = 10
Hello world number: 1
Hello world number: 2
Hello world number: 4
Hello world number: 6
Hello world number: 8
j == 666
true && 123 = 123
false && 123 = false
true || 456 = true
false || 456 = 456
PI = 3.14
null = null
10 % 3 = 1
flag is false
first element: 1
nested: 10
tabs:	between
say "hello"
inside block: 999

```

### 编译为字节码 &amp; 单独运行

[](#编译为字节码--单独运行)

将源码编译成二进制 `.bc` 字节码文件：

```
$ php examples/compile.php examples/codes/demo.l
Compiled: examples/codes/demo.l -> examples/codes/demo.bc
  size: 3,056 bytes
  consts: 47
  globals: 16
  functions: 4
  entry ops: 462
```

生成的 `.bc` 文件是紧凑的二进制格式（`TBC\x00` 魔数头），无需 Lexer / Parser / CodeGen，仅需 VM 即可运行：

```
$ php examples/run.php examples/codes/demo.bc
# 输出与直接运行源码完全一致
```

`.bc` 文件可分发到任何安装了 `TinyCompiler` 的环境中直接执行。如需人类可读的字节码文件，可使用 `--php` 导出为 `var_export` PHP 格式：

```
$ php examples/compile.php --php examples/codes/demo.l
Compiled: examples/codes/demo.l -> examples/codes/demo.bc.php (PHP (human-readable))
  size: 10,088 bytes
```

导出的 `.bc.php` 文件结构一览：

```
