#1.8. WASM 元件模型:ffi::wit
本頁內容
WebAssembly 元件模型(Component Model,bytecodealliance.org;Preview 2 於 2024 年 1 月穩定)是定義具型別跨語言介面的基礎。它以 record / variant / resource 這類豐富的型別,取代傳統 C ABI FFI(1.7)所依賴的原始指標加長度模型。
#1.8.1. WIT:WebAssembly Interface Types
WIT 是一種與語言無關的介面定義語言。
package example:fs;
interface fs {
record stat {
size: u64,
mtime: u64,
is-dir: bool,
}
variant error {
not-found,
permission-denied,
io-error(string),
}
resource file {
constructor(path: string);
read: func(buf-size: u32) -> result<list<u8>, error>;
close: func();
}
open: func(path: string) -> result<file, error>;
}
以這種方式定義的介面,可以從任何語言匯入或匯出:Rust、Go、Python、Nabi 等。
#1.8.2. Nabi 端的繫結形式
匯入端使用外部元件。這裡的 wit/fs.wit 存放 1.8.1 的介面,檔案開頭為 package example:fs;。
ffi::wit::import { "wit/fs.wit" } // relative to this source file
use example::fs::fs::{File, Error};
let f = File::new("data.txt");
let bytes = try f.read(1024); // throws (Error) -> List<u8>
f.close();
匯出端提供一個元件;calculator.wit 在一個 world 中宣告 add: func(a: s32, b: s32) -> s32。
ffi::wit::export { "calculator.wit" }
#[wit::export]
fn add(a: i32, b: i32) -> i32 { a + b }
#路徑與位置
- 路徑相對於原始檔。它指向一個
.wit檔案或一個套件目錄,該目錄的deps/存放其相依套件。 - 此項目可以出現在程式的套件中,也可以出現在相依套件中。它的繫結放在包含它的模組(在相依套件中,就是該相依套件的模組)裡,位於
ns::pkg::iface(wasi::filesystem::types)之下。 - WIT 型別成為 PascalCase 的 Nabi 型別(
descriptor-type→DescriptorType,file→File);函式和欄位成為 snake_case。
#World
具名檔案中的 world 就是元件。否則由關鍵字決定:ffi::wit::import 匯入這些介面,ffi::wit::export 匯出它們。include ... with { a as b } 會重新命名被納入的項目。
#型別對應
| WIT | Nabi |
|---|---|
record | struct |
variant, enum | enum |
flags | 由 bool 欄位組成、實作 Default 的 struct(最多 32 個旗標) |
option<T> | T?(巢狀的 option 保留其層數:option<option<T>> → T??) |
result<T, E> | Result<T, E>;回傳它的函式為 throws (E) -> T |
tuple<..> | 元組 |
list<T> | List<T> |
list<T, N> | [T; N] |
string | str(UTF-8) |
char, bool, f32, f64 | 相同 |
sN / uN | iN / uN |
future<T> | AsyncFuture<T> |
stream<T> | core::channel::Receiver<T>(關閉傳送端即結束) |
error-context | bare::ffi::wit::ErrorContext |
匯入的 resource | 控制代碼結構,以 using / Drop 釋放 |
匯出的 resource | 使用者的 #[wit::export] pub struct |
#非同步
async func 就是 async fn,匯入與匯出皆然。同步任務(preview 2 的 main、同步匯出)不能等待元件模型;這樣做會在執行時觸發 panic,因此非同步匯入要在非同步匯出內部等待。preview 3 指令以 #[wit::export] async fn run() -> Result<(), ()> 匯出 wasi:cli/[email protected]。非同步匯出的呼叫並行執行,每個呼叫都是一個元件模型任務;呼叫在自己的輪次回傳結果。在非同步匯出內部,通訊端和計時器在主機的事件之間等待;若同時有元件模型事件待處理,至少每 10 ms 檢查一次(preview 2 的 pollable 與元件模型的事件無法同時等待)。等待某個沒有任何東西會送達之物的非同步匯出會一直等待;另一個呼叫仍可能將它送達。
產生的繫結所呼叫的非同步 canonical ABI 位於 std::wit:它在執行器上執行,stream<T> 對應到一個 core 型別。記憶體輔助函式、區塊、控制代碼和 ErrorContext 則留在 bare::ffi::wit。
#匯出
匯出的函式是項目所在模組中的 #[wit::export] fn,以其 snake_case 名稱與 WIT 函式對應。匯出的 resource 是 #[wit::export] pub struct,其 impl 提供 new(建構子)、方法和靜態函式;可能失敗的建構子(result<r, ..>)是會擲回錯誤的 new,而 resource 的解構子執行它的 Drop。缺少匯出是編譯錯誤。
匯出 WIT、且進入檔案既沒有 fn main 也沒有頂層陳述式的套件是一個 reactor:它不匯出 wasi:cli/run(4.16.1)。
#目標
WIT 需要 wasm32-wasip2(WASI preview 2 元件);在其他任何目標上都是編譯錯誤。匯出可以在 main 之前被呼叫:執行環境在第一次匯出呼叫時啟動。
預先建置的相依套件會在其 NABIHIR 中攜帶它的 ffi::wit 項目所讀取的 .wit 檔案(refs-lang 9.4.7);相依於它的套件不會從磁碟讀取這些檔案。
#限制
匯入的介面不能使用元件所匯出介面的型別;這是編譯錯誤。
#繫結執行環境:bare::ffi::wit
產生的繫結呼叫這些輔助函式;一般程式碼使用繫結即可。區塊來自 C 配置器,包括主機透過 cabi_realloc 填入的區塊;提升(lift)後的字串或串列在複製到 GC 記憶體之後,就會釋放其區塊。一次匯入呼叫降階到區塊中的值,會在呼叫結束後一起釋放;匯出的值則由其 post-return 函式釋放。
// bare::ffi::wit: linear memory at canonical ABI addresses (i32)
unsafe fn load_u8(a: i32) -> u8; // also load_u16 / load_i32 / load_i64 / load_f32 / load_f64
unsafe fn store_u8(a: i32, v: u8); // also store_u16 / store_i32 / store_i64 / store_f32 / store_f64
// joined flat slots of a variant
fn f32_bits(x: f32) -> i32;
fn f32_from(x: i32) -> f32;
fn f64_bits(x: f64) -> i64;
fn f64_from(x: i64) -> f64;
fn char_from(x: i32) -> char; // panics on a non-scalar
fn bad_case() -> !; // panics: discriminant out of range
const BLOCKED: i32 = -1; // a copy or call did not finish at once
const DROPPED: i32 = 1; // a copy's other end was dropped
unsafe fn free(a: i32);
unsafe fn str_take(p: i32, n: i32) -> str; // copies, then frees the block
unsafe fn bytes_take(p: i32, n: i32) -> List<u8>; // copies, then frees the block
struct Blocks { /* private */ }
impl Blocks {
fn new() -> Blocks;
fn alloc(self, size: i32, align: i32) -> i32; // an empty block is the address `align`
fn str(self, s: str) -> (i32, i32); // (address, length)
fn bytes(self, l: List<u8>) -> (i32, i32); // (address, length)
fn free(self); // frees every block
}
struct Handle { /* private */ }
impl Handle {
fn own(h: i32) -> Handle;
fn borrowed(h: i32) -> Handle;
fn get(self) -> i32; // panics once dropped or passed on
fn take(self) -> i32; // gives an own away; panics on a borrow
fn release(self) -> i32 | none; // the handle to drop, if still owned
}
struct Table<T> { /* private */ }
unsafe impl<T> Sync for Table<T> {}
impl<T> Table<T> {
unsafe fn new() -> Table<T>; // the caller keeps it to one thread at a time
fn insert(self, v: T) -> i32; // the rep
fn get(self, rep: i32) -> T; // panics once taken
fn take(self, rep: i32) -> T?; // frees the slot; none if taken already
}
struct ErrorContext { /* private */ }
impl ErrorContext { // WASI targets only
fn new(msg: str) -> ErrorContext;
fn debug_message(self) -> str; // the host may give an empty one
fn raw(self) -> i32;
fn from_raw(h: i32) -> ErrorContext;
}
impl Drop for ErrorContext { /* error-context.drop */ }
Handle 的各個副本共用同一個儲存格:把 own 傳遞出去或釋放它,會清空所有副本。Table<T> 依表示值(rep)保存匯出 resource 的值,直到主機釋放其控制代碼([dtor])為止。
ErrorContext 型別存在於每個目標上;它的方法和 Drop 只存在於 WASI 目標上。Blocks、Handle 和 Table<T> 以其型別名稱實作 Debug,ErrorContext 則以 ErrorContext { handle: n } 實作(0.5.12);std::wit 的型別 Waiting、FutureOps<T> 和 StreamOps<T> 也是如此。遇到錯誤引數會觸發 panic 的函式(char_from、bad_case、Handle::get / take、Table::get)都是 #[track_caller],其訊息遵循 0.5.10 規則 6(wit::char_from: not a Unicode scalar value、Handle::get: resource used after it was dropped or passed on)。槽位輔助函式 f32_bits、f32_from、f64_bits、f64_from 和 char_from 保留產生的繫結所呼叫的名稱;它們是 canonical ABI 名稱,不在 0.5.11 命名表之內。
#1.8.3. C FFI 與 WIT 的差異
這兩種做法在幾個面向上有明顯差異。
| 面向 | C FFI(1.7) | WIT(本章) |
|---|---|---|
| 型別系統 | C 基本型別 + 使用者結構 | record / variant / resource |
| 安全性 | 低(原始指標需手動管理) | 高(具型別) |
| 記憶體管理 | malloc/free | resource(自動解構子) |
| 錯誤處理 | errno / 回傳值慣例 | 一等公民的 result<T, E> |
| 字串 | 以 null 結尾 | 帶長度前綴的 UTF-8 |
| 串列 | (ptr, len) 手動 | list<T> 自動 |
| 呼叫成本 | 幾乎為零(直接呼叫) | trampoline(~ns) |
| 範圍 | 所有原生目標 | wasm32-wasip2(preview 2 元件) |
| 需要 unsafe | ✓ | ✗ |
#1.8.4. 選擇準則
準則很簡單:取決於要呼叫什麼,以及部署在哪裡。
| 情境 | 建議 |
|---|---|
| 呼叫傳統 C 函式庫 | C FFI(1.7) |
| 系統呼叫(libc、Win32) | C FFI |
| GPU / SIMD 內建函式 | C FFI |
| 與其他語言之間的安全介面 | WIT |
| 部署到 WASM 環境 | WIT |
| 外掛 / 沙箱隔離 | WIT |
| 多語言(Modular / Mojo 等) | WIT |
本章的主要意義在於:Nabi 同時支援傳統 C FFI 和 WIT。使用者依照安全性、效能和目標環境的限制,選擇其中一種。
#1.8.5. 參考資料
延伸閱讀:
發現錯誤? 在 GitHub 上編輯此頁 最後更新: