
# 简介

Greph 是一款纯 PHP 源代码树搜索和重构引擎，以 Composer 软件包 `greph/greph` 的形式安装。它可以完成通常需要三个原生二进制程序才能完成的三项工作：

- **文本搜索**：提供与 grep 兼容的输出和 ripgrep 风格的易用性，类似于 `grep` 和 `rg`。
- **AST 搜索**：支持 PHP 结构模式和元变量，类似于 `ast-grep`。
- **AST 改写**：保留格式的结构化重构，类似于 `ast-grep --rewrite`。

此外，它还提供预热索引模式，用于重复执行文本和 AST 查询，并提供 `rg` 和 `sg` 包装器，可接受 ripgrep 和 ast-grep 命令行参数。所有模式都在 PHP 中运行：Greph 不会通过 shell 调用 `grep`、`rg` 或 `ast-grep`。

## Greph 的由来

PHP应用和智能体通常需要快速代码搜索，因此会调用原生工具（`grep`、`ripgrep`、`ast-grep`），牺牲可移植性并增加部署阻力。结构化搜索和重写更麻烦：通常需要完全离开 PHP 进程。

Greph 填补了这一空缺。你的 PHP 代码只需使用 PHP 捆绑的扩展和 `nikic/php-parser`，即可执行文本搜索、结构匹配和重构改写。输出格式和退出代码遵循规范工具，因此现有脚本以及解析 `grep` 或 `rg` 输出的代理无需修改。

## 模式

| 模式 | 命令 | Facade 方法 | 用途 |
|---|---|---|---|
| [文本搜索](https://greph.inline0.dev/zh/docs/modes/text/) | `greph "pattern" src` | `Greph::searchText()` | 逐行搜索固定字符串和 PCRE2 正则表达式 |
| [AST 搜索](https://greph.inline0.dev/zh/docs/modes/ast/) | `greph -p 'new $CLASS()' src` | `Greph::searchAst()` | PHP 代码结构，不受格式和注释影响 |
| [AST 改写](https://greph.inline0.dev/zh/docs/modes/rewrite/) | `greph -p 'array($$$ITEMS)' -r '[$$$ITEMS]' src` | `Greph::rewriteAst()` | 保留周边代码不变的机械式重构 |
| [索引文本](https://greph.inline0.dev/zh/docs/indexed/text/) | `greph-index search -F "function" .` | `Greph::searchTextIndexed()` | 在大型代码树中重复执行文本查询 |
| [索引 AST](https://greph.inline0.dev/zh/docs/indexed/ast/) | `greph-index ast-index search 'new $CLASS()' src` | `Greph::searchAstIndexed()` | 重复执行具有可识别开头的结构化查询 |
| [缓存 AST](https://greph.inline0.dev/zh/docs/indexed/cache/) | `greph-index ast-cache search 'array($$$ITEMS)' src` | `Greph::searchAstCached()` | 重复执行结构化查询，无需重新解析 |
| [rg 包装器](https://greph.inline0.dev/zh/docs/compatibility/rg/) | `rg -F "function" src` | | 已在调用 ripgrep 的工具和代理 |
| [sg 包装器](https://greph.inline0.dev/zh/docs/compatibility/sg/) | `sg run --pattern 'new $CLASS()' src` | | 已在调用 ast-grep 的工具和代理 |

三种普通模式每次调用都会读取源代码树，因此结果始终是最新的。三种索引模式会将数据存储在搜索根目录下的磁盘上（`.greph-index`、`.greph-ast-index`、`.greph-ast-cache`），以构建步骤换取更快的重复查询。[索引文本搜索](https://greph.inline0.dev/zh/docs/indexed/text/#indexed-or-plain-text-search) 说明了何时值得这样做。

所有模式共用一个 [文件遍历器](https://greph.inline0.dev/zh/docs/advanced/walker/)，因此 `.gitignore` 和 `.grephignore` 规则、隐藏文件处理、二进制检测以及 `--type` 和 `--glob` 过滤器在各模式中的行为都一致。如果有 `ext-pcntl`，纯文本和 AST 扫描可通过 [并行工作进程](https://greph.inline0.dev/zh/docs/advanced/parallel/)分担工作。

## 可执行文件

安装软件包后，会向 `vendor/bin/` 添加四个可执行文件：

- `greph`：原生文本搜索、AST 搜索和 AST 改写
- `greph-index`：预热文本索引、AST 事实索引和缓存 AST 搜索
- `rg`：ripgrep 风格的兼容包装器
- `sg`：ast-grep 风格的兼容包装器，还可使用 `sg outline` 打印 PHP 代码大纲

`vendor/bin` 可执行文件要求 Greph 0.2.3 或更高版本，前提是 Greph 已作为项目依赖安装。[CLI 参考](https://greph.inline0.dev/zh/docs/cli/)列出了这四个可执行文件的所有标志。

## 最简示例

安装软件包：

```bash
composer require greph/greph
```

假设项目中有一个文件位于 `src/e.php`：

```php
<?php
$config = array('debug' => true);
$logger = new Logger();
```

固定字符串文本搜索会输出 grep 风格的 `file:line:content` 行：

```bash
vendor/bin/greph -F "Logger" src
```

```text
src/e.php:3:$logger = new Logger();
```

AST 搜索会匹配代码结构，无论类名是什么：

```bash
vendor/bin/greph -p 'new $CLASS()' src
```

```text
src/e.php:3:new Logger()
```

使用 `--dry-run` 改写时，会打印改写后的文件内容，但不会写入文件：

```bash
vendor/bin/greph -p 'array($$$ITEMS)' -r '[$$$ITEMS]' --dry-run src
```

```text
=== src/e.php ===
<?php
$config = ['debug' => true];
$logger = new Logger();
```

省略 `--dry-run` 即可写入更改。使用 PHP 执行相同的三项操作：

```php
use Greph\Greph;
use Greph\Ast\AstSearchOptions;
use Greph\Text\TextSearchOptions;

$matches = Greph::searchText(
    'Logger',
    'src',
    new TextSearchOptions(fixedString: true),
);

foreach ($matches as $file) {
    foreach ($file->matches as $match) {
        echo "{$file->file}:{$match->line}:{$match->content}\n";
    }
}

$nodes = Greph::searchAst(
    'new $CLASS()',
    'src',
    new AstSearchOptions(),
);

$rewrites = Greph::rewriteAst(
    'array($$$ITEMS)',
    '[$$$ITEMS]',
    'src',
);
```

`Greph::rewriteAst()` 会返回 `RewriteResult` 对象，其中包含原始内容和改写后的内容，并且不会写入文件；是否保存由调用方决定。结果类记录在 [API参考](https://greph.inline0.dev/zh/docs/api/#result-objects) 中。

## 文档结构

**从这里开始**

- [入门](https://greph.inline0.dev/zh/docs/getting-started/)：安装、要求，以及首次执行文本搜索、AST 搜索和改写。
- [CLI](https://greph.inline0.dev/zh/docs/cli/)：`greph`、`greph-index`、`rg` 和 `sg` 的所有标志，以及退出代码。
- [API](https://greph.inline0.dev/zh/docs/api/)：`Greph\Greph` facade、选项类、结果对象和异常。

**模式**：每次调用都会读取代码树的普通引擎：

- [文本搜索](https://greph.inline0.dev/zh/docs/modes/text/)：固定字符串和正则表达式搜索、文件筛选、上下文、计数和 JSON 输出。
- [AST 搜索](https://greph.inline0.dev/zh/docs/modes/ast/)：模式语法、`$VAR`、`$_` 和 `$$$VARIADIC` 元变量、重复捕获。
- [AST 重写](https://greph.inline0.dev/zh/docs/modes/rewrite/)：替换模板、试运行和交互模式、格式保留。

**索引模式**，用于重复查询的预热存储：

- [索引文本搜索](https://greph.inline0.dev/zh/docs/indexed/text/)：三元组和标识符倒排表、生命周期配置、索引集，以及索引何时比普通扫描更快。
- [索引 AST 搜索](https://greph.inline0.dev/zh/docs/indexed/ast/)：AST 事实索引，可按调用名称、类名和声明预筛选文件。
- [缓存 AST 搜索](https://greph.inline0.dev/zh/docs/indexed/cache/)：存储的语法树，可在重复结构查询时跳过解析器。

**兼容性**，即直接替换式封装：

- [rg 兼容性](https://greph.inline0.dev/zh/docs/compatibility/rg/)：在 Greph 引擎上提供 ripgrep 命令行和 JSON 事件格式。
- [sg 兼容性](https://greph.inline0.dev/zh/docs/compatibility/sg/)：提供 ast-grep 命令行、重写和 PHP 大纲。

**高级**，内部机制与验证：

- [文件遍历器](https://greph.inline0.dev/zh/docs/advanced/walker/)：忽略规则、类型别名、二进制检测、符号链接和大小限制。
- [并行工作进程](https://greph.inline0.dev/zh/docs/advanced/parallel/)：`pcntl` 工作进程池何时启动，以及它如何回退。
- [进程受限的主机](https://greph.inline0.dev/zh/docs/advanced/process-restricted-hosts/)：在禁用 `proc_open()`、`shell_exec()` 或 `pcntl_fork()` 的环境中运行。
- [功能矩阵](https://greph.inline0.dev/zh/docs/advanced/feature-matrix/)：通过探测生成的封装支持情况报告。
- [测试](https://greph.inline0.dev/zh/docs/advanced/testing/)：单元测试，以及将 Greph 与 grep、ripgrep 和 ast-grep 进行差异比较的基准语料库。
- [基准测试](https://greph.inline0.dev/zh/docs/advanced/benchmarks/)：基准测试工具、语料库，以及已发布数据的生成方式。

## 运行要求

- PHP 8.2 或更高版本
- `ext-json`、`ext-ctype` 和 `ext-tokenizer`，几乎所有 PHP 构建都已启用这些扩展
- `ext-zlib`，用于缓存 AST 存储（`greph-index ast-cache`）
- `nikic/php-parser`（唯一的 Composer 依赖项）

核心文本和 AST 功能在纯 PHP 中运行。可选的基准测试对比依赖 `rg`、`grep` 和 `sg` 等外部工具，但 Greph 本身无需这些工具即可运行。并行扫描在可用时使用 `ext-pcntl`，否则回退到单进程执行。`proc_open()` 和 `shell_exec()` 被禁用的主机环境，详见 [进程受限的主机](https://greph.inline0.dev/zh/docs/advanced/process-restricted-hosts/)。

## 它不是什么

Greph 可用于查找代码，也可选择重写代码。它不是代码检查工具（请使用 PHPStan 或 Psalm），不是格式化工具（请使用 PHP-CS-Fixer），也不是 IDE。AST 搜索和重写仅解析 PHP；文本搜索适用于任何文本文件。
