用 LLM 移植 TypeScript 編譯器到 Rust

用 LLM 移植 TypeScript 編譯器到 Rust

📌 本文重點

  • 大型移植關鍵在維持語意與行為等價
  • 以子系統拆分讓 LLM 做機械轉譯,人類控邊界
  • 原 test suite + differential testing 是驗證核心
  • 先從診斷系統等資料密集模組試行 AI 流水線

大型重構與跨語言移植最痛的點,不是「會不會寫 Rust」,而是怎麼在幾十萬行程式碼裡維持語意等價、行為一致,同時還要不把人類工程師炸乾。近期將 TypeScript 編譯器 / checker / LSP 移植到 Rust(如 ts-rust 專案)的經驗,證明了:只要把系統切對塊、工作流設計好,LLM 可以負責大量機械、易錯、跨語言的轉譯工作,人類工程師則專注在邊界、架構與驗證。


重點說明

1. 怎麼把「整個編譯器」拆給 LLM

一個 TS 編譯器可粗分為幾個 LLM 可處理的子系統:

  1. AST 與 Parser:語法樹節點結構、lexer/parser
  2. Type Checker:型別圖、約束求解、泛型推導
  3. Emit / Transpiler:從 AST 輸出 JS / d.ts 等
  4. 錯誤與診斷系統:診斷碼、訊息模板、range/position
  5. LSP 服務:語言伺服器 protocol、request/response 型別、增量分析

給 LLM 的單位不要是「整個 repo」,而是:

  • 單檔級別:小模組、純資料結構、單一 utility
  • 子系統級別:一組互相高度耦合的檔案 + 明確的 public API

實務上會先由人類畫出一張粗略架構圖(甚至是文字版):

[parser]
  - scanner.ts -> scanner.rs
  - parser.ts -> parser.rs
[types]
  - types.ts (型別節點定義)
  - checker.ts (大型,拆成多個 rs 模組)
[diagnostics]
  - diagnosticMessages.json -> diagnostics.rs (enum + format)
[lsp]
  - tsserver.ts / session.ts -> lsp/mod.rs, lsp/session.rs

然後為每個子系統定義不變量(invariants),例如:

  • AST 節點 ID 不變:SyntaxKind 枚舉值與原版一一對應
  • 診斷碼不變:TS2345 這類 error code 與 message key 不可改
  • LSP 行為不變:相同檔案、同一位置,textDocument/hover 結果結構一致

💡 關鍵: 先定義清楚 AST、診斷碼與 LSP 行為等不變量,才能在大規模 AI 移植下維持編譯器語意完全一致

這些不變量會在後面被用來設計測試與 differential testing。


2. AI 開發工作流:如何讓 LLM 當穩定的轉譯器

一個穩定的 AI 驅動移植流程,通常長這樣:

  1. 人類先寫 scaffold:Rust crate 結構、目錄、主要模組邊界
  2. 為每個檔案/子系統建立 prompt 模板:輸入原始 TS/JS + 公開 API 描述 + 目前已有的 Rust 型別
  3. 單檔→子系統迭代:先讓每一檔在 Rust 可編譯,再拉高到整個子系統一起修
  4. 自動測試 + differential testing:每次生成後自動跑 test、比對行為

一個實用的單檔轉譯 prompt 範本:

System: 你是一位資深 Rust 工程師,正在把 TypeScript 編譯器移植到 Rust。

User:
請把下面這支 TypeScript 檔案移植到 Rust。

約束:
- 保持所有 public API 的語意等價
- 保留原有錯誤碼與訊息 key
- 不要發明新功能或重構演算法,只做語言層級移植
- 若需要共用型別,優先使用我提供的 Rust 型別定義

已有型別定義(Rust):
```rust
{{shared_types_rs}}

原始程式碼(TypeScript):

{{source_ts}}

請輸出單一 Rust 模組檔案內容,使用 mod {{module_name}}; 風格的 idiomatic Rust,確保可以被 cargo check 通過。

對於大型檔案(像 `checker.ts`),建議改成**子系統級別轉譯**:先由人類切出 logical module,讓 LLM 逐一處理:

```text
// checker_subtyping.ts
// checker_relations.ts
// checker_inference.ts
// ...

每一段 prompt 都加上子系統行為說明,例如「這個模組只處理 assignability,不評估泛型約束」。這可以大幅降低 LLM 自動「順手重構」的風險。


3. 測試與驗證:原 test suite + differential + fuzzing

LLM 生成的程式碼最大問題不是編不編得過,而是隱性行為偏移。建議的驗證三段式:

  1. 沿用原專案 test suite
  2. 直接把 TypeScript 原本的測試(特別是 compiler tests)當作 oracle
  3. 寫一個小工具把 .ts 測試檔丟給:

    • 原版 TS 編譯器 → 產出 expected.json
    • Rust 版 TS 編譯器 → 產出 actual.json
  4. 自動 differential testing

    “`bash

    假設已有兩個 binary:tsc_original, tsc_rust

    for f in tests/cases/*/.ts; do
    node tsc_original $f –json > out/original/$(basename $f).json
    tsc_rust $f –json > out/rust/$(basename $f).json
    node tools/compare.js out/original out/rust || echo “diff in $f”
    done
    “`

    compare.js 比對:

    • 診斷碼集合
    • 錯誤位置 (line/column)
    • emit 結果(hash 或 string equality)
  5. fuzzing / random program generation

    • 使用簡單 grammar 產生隨機 .ts 程式
    • 或利用 QuickCheck / proptest 風格工具在 Rust 端生成 AST,再 round-trip 檢查(AST→emit→parse→AST)

    rust
    proptest! {
    #[test]
    fn ast_roundtrip_preserves_structure(random_ast in arb_ts_ast()) {
    let source = emit_ts(&random_ast);
    let reparsed = parse_ts(&source).unwrap();
    prop_assert_eq!(normalize(&random_ast), normalize(&reparsed));
    }
    }

💡 關鍵: 原始 test suite 加上自動 differential testing,是偵測 LLM 生成程式碼「語意微偏移」的最有效手段


實作範例:從一個錯誤系統模組開始

以 診斷訊息系統 為例,它是跨編譯器 / LSP 的關鍵共用元件,適合拿來做第一個 AI 驅動子系統。

1. 原始 TypeScript 資料

// diagnosticMessages.json (簡化)
{
  "TS2345": {
    "category": "error",
    "code": 2345,
    "key": "Argument of type '{0}' is not assignable to parameter of type '{1}'."
  },
  "TS1005": {
    "category": "error",
    "code": 1005,
    "key": "'{' expected."
  }
}

2. 給 LLM 的轉譯 prompt(片段)

請將以下 diagnosticMessages.json 結構,轉成一個 Rust 模組:
- 使用 `enum DiagnosticCode`,變體名稱以 key 命名,例如 `TS2345`
- 保留 `code` 數值不變
- 提供 `fn message(&self, args: &[String]) -> String`,支援 {0}, {1} 參數替換
- 不要改寫任何字串內容

JSON:
```json
{{diagnostic_json}}
### 3. LLM 期望輸出(整理後的人類版)

```rust
// src/diagnostics.rs

pub enum DiagnosticCode {
    TS2345,
    TS1005,
    // ...
}

impl DiagnosticCode {
    pub fn code(&self) -> u32 {
        match self {
            DiagnosticCode::TS2345 => 2345,
            DiagnosticCode::TS1005 => 1005,
        }
    }

    pub fn template(&self) -> &'static str {
        match self {
            DiagnosticCode::TS2345 => "Argument of type '{0}' is not assignable to parameter of type '{1}'.",
            DiagnosticCode::TS1005 => "'{' expected.",
        }
    }

    pub fn message(&self, args: &[String]) -> String {
        let mut s = self.template().to_string();
        for (i, arg) in args.iter().enumerate() {
            let placeholder = format!("{{{}}}", i);
            s = s.replace(&placeholder, arg);
        }
        s
    }
}

4. 測試:用原專案 snapshot 當 oracle

#[test]
fn test_ts2345_message() {
    let msg = DiagnosticCode::TS2345
        .message(&["string".into(), "number".into()]);
    assert_eq!(
        msg,
        "Argument of type 'string' is not assignable to parameter of type 'number'."
    );
}

這類模組非常適合交給 LLM 做「一次性大量生成」,人類的工作重點就變成檢查 enum 命名、字串有無誤植、是否漏 key,而不是手動搬運幾百條 message。

💡 關鍵: 先用診斷系統這種「資料多、邏輯單」模組練 AI 流程,能低風險驗證整套移植管線是否可靠


建議與注意事項

1. 人類工程師在 loop 裡要做的事

  • 設計邊界與不變量:什麼可以改(重寫成 idiomatic Rust)、什麼絕對不能改(error code、AST 結構)
  • 寫 scaffold 與共用型別:先定義好 AST enum、Symbol 結構、LSP request/response 型別,讓 LLM 不會各自發明
  • 審核危險修改:遇到 type checker、flow analysis 這類核心演算法時,禁止 LLM 自己「優化」,必要時只允許小範圍 patch

2. 工具與流程建議

  • 編輯器:Copilot / Claude Code 做 in-editor 建議
  • 大段轉譯:使用支援長 context 的模型(雲端或自架),搭配腳本自動呼叫
  • 本地工具鏈:
  • Rust:cargo check + cargo test 作為每次生成後的最小驗收
  • CI:pull request 必跑完整 test suite + differential testing

簡單的自動化腳本片段:

# scripts/llm_translate.sh
FILE=$1
python tools/call_llm.py --template ts_to_rust --input $FILE > tmp.rs
mv tmp.rs src/$(basename ${FILE/.ts/.rs})
cargo check

3. 常見坑與防呆策略

  1. 隱性共享狀態
  2. JS/TS 常用 mutable global / singleton,Rust 需要顯式傳遞或使用 Arc<Mutex<...>>
  3. 建議先由人類掃過原始碼,把這些 global 收斂成少數幾個 context 結構,再讓 LLM 移植

  4. 效能退化

  5. LLM 喜歡產生安全但笨重的實作,例如大量 clone()、使用 String 而不是 &str
  6. 用 benchmarks 比對原實作,對熱點模組(scanner、parser、checker critical path)做手動優化

  7. 錯誤訊息品質劣化

  8. 容易發生在 LSP / diagnostics:LLM 會「順手改寫」訊息或合併 path
  9. 防禦手法:

    • 把 diagnostics 定義視為資料,不允許 LLM「改文案」
    • snapshot 測試錯誤訊息全文,確保逐字一致
  10. 語意不一致的微小差異

  11. 例如邊角 case:any、never、unknown 在 assignability 上的特殊規則
  12. 做法:
    • 用 原編譯器 自動生成邊角 case 測試
    • 把這些測試固定在 repo 裡,作為 regression test

給你的實戰藍圖(精簡版)

  1. 切分 repo:畫出子系統圖,挑選一個「資料多、邏輯單」的模組先試(如 diagnostics 或 AST 定義)
  2. 搭起 scaffold:建立 Rust crate 結構、共用型別、basic CI
  3. 設計 prompt 模板:特別是明確的限制(只移植、不重構)與不變量說明
  4. 導入自動化腳本:批次呼叫 LLM → 寫檔 → cargo check → 測試
  5. 接上原 test suite + differential testing:任何「看起來沒問題」的變更,都必須通過行為對比
  6. 逐步攻下核心模組:先 parser/AST,再 type checker,最後 LSP,高風險部分加強人類 code review

做到這一步,你就擁有一套可重用的AI 驅動大型重構/跨語言移植流水線,下次要把 JS runtime 移植到 Go,或是把 Python library 搬到 Rust,只需要換一組 prompt 和 scaffold,而不是從頭再被大型專案榨乾一次。


🚀 你現在可以做的事

  • 在自己的 TS 專案中畫出子系統與不變量清單,選一個診斷或 AST 模組試做 AI 移植
  • 寫一個簡單的 tsc_original / tsc_rust differential testing 腳本,開始比對行為差異
  • 建立標準化 ts_to_rust prompt 模板與 cargo check 整合腳本,讓 LLM 移植流程可以一鍵重複執行

留言

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *