1use crate::ExtensionManifest;
2use crate::{extension_manifest::ExtensionLibraryKind, GrammarManifestEntry};
3use anyhow::{anyhow, bail, Context as _, Result};
4use async_compression::futures::bufread::GzipDecoder;
5use async_tar::Archive;
6use futures::io::BufReader;
7use futures::AsyncReadExt;
8use serde::Deserialize;
9use std::{
10 env, fs, mem,
11 path::{Path, PathBuf},
12 process::{Command, Stdio},
13 sync::Arc,
14};
15use util::http::{self, AsyncBody, HttpClient};
16use wasm_encoder::{ComponentSectionId, Encode as _, RawSection, Section as _};
17use wasmparser::Parser;
18use wit_component::ComponentEncoder;
19
20/// Currently, we compile with Rust's `wasm32-wasi` target, which works with WASI `preview1`.
21/// But the WASM component model is based on WASI `preview2`. So we need an 'adapter' WASM
22/// module, which implements the `preview1` interface in terms of `preview2`.
23///
24/// Once Rust 1.78 is released, there will be a `wasm32-wasip2` target available, so we will
25/// not need the adapter anymore.
26const RUST_TARGET: &str = "wasm32-wasi";
27const WASI_ADAPTER_URL: &str =
28 "https://github.com/bytecodealliance/wasmtime/releases/download/v18.0.2/wasi_snapshot_preview1.reactor.wasm";
29
30/// Compiling Tree-sitter parsers from C to WASM requires Clang 17, and a WASM build of libc
31/// and clang's runtime library. The `wasi-sdk` provides these binaries.
32///
33/// Once Clang 17 and its wasm target are available via system package managers, we won't need
34/// to download this.
35const WASI_SDK_URL: &str = "https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-21/";
36const WASI_SDK_ASSET_NAME: Option<&str> = if cfg!(target_os = "macos") {
37 Some("wasi-sdk-21.0-macos.tar.gz")
38} else if cfg!(target_os = "linux") {
39 Some("wasi-sdk-21.0-linux.tar.gz")
40} else {
41 None
42};
43
44pub struct ExtensionBuilder {
45 cache_dir: PathBuf,
46 pub http: Arc<dyn HttpClient>,
47}
48
49pub struct CompileExtensionOptions {
50 pub release: bool,
51}
52
53#[derive(Deserialize)]
54struct CargoToml {
55 package: CargoTomlPackage,
56}
57
58#[derive(Deserialize)]
59struct CargoTomlPackage {
60 name: String,
61}
62
63impl ExtensionBuilder {
64 pub fn new(cache_dir: PathBuf) -> Self {
65 Self {
66 cache_dir,
67 http: http::client(),
68 }
69 }
70
71 pub async fn compile_extension(
72 &self,
73 extension_dir: &Path,
74 extension_manifest: &ExtensionManifest,
75 options: CompileExtensionOptions,
76 ) -> Result<()> {
77 if extension_dir.is_relative() {
78 bail!(
79 "extension dir {} is not an absolute path",
80 extension_dir.display()
81 );
82 }
83
84 fs::create_dir_all(&self.cache_dir)?;
85
86 let cargo_toml_path = extension_dir.join("Cargo.toml");
87 if extension_manifest.lib.kind == Some(ExtensionLibraryKind::Rust)
88 || fs::metadata(&cargo_toml_path)?.is_file()
89 {
90 self.compile_rust_extension(extension_dir, options).await?;
91 }
92
93 for (grammar_name, grammar_metadata) in &extension_manifest.grammars {
94 self.compile_grammar(extension_dir, grammar_name.as_ref(), grammar_metadata)
95 .await?;
96 }
97
98 log::info!("finished compiling extension {}", extension_dir.display());
99 Ok(())
100 }
101
102 async fn compile_rust_extension(
103 &self,
104 extension_dir: &Path,
105 options: CompileExtensionOptions,
106 ) -> Result<(), anyhow::Error> {
107 self.install_rust_wasm_target_if_needed()?;
108 let adapter_bytes = self.install_wasi_preview1_adapter_if_needed().await?;
109
110 let cargo_toml_content = fs::read_to_string(&extension_dir.join("Cargo.toml"))?;
111 let cargo_toml: CargoToml = toml::from_str(&cargo_toml_content)?;
112
113 log::info!("compiling rust extension {}", extension_dir.display());
114 let output = Command::new("cargo")
115 .args(["build", "--target", RUST_TARGET])
116 .args(options.release.then_some("--release"))
117 .arg("--target-dir")
118 .arg(extension_dir.join("target"))
119 .current_dir(&extension_dir)
120 .output()
121 .context("failed to run `cargo`")?;
122 if !output.status.success() {
123 bail!(
124 "failed to build extension {}",
125 String::from_utf8_lossy(&output.stderr)
126 );
127 }
128
129 let mut wasm_path = PathBuf::from(extension_dir);
130 wasm_path.extend([
131 "target",
132 RUST_TARGET,
133 if options.release { "release" } else { "debug" },
134 cargo_toml.package.name.as_str(),
135 ]);
136 wasm_path.set_extension("wasm");
137
138 let wasm_bytes = fs::read(&wasm_path)
139 .with_context(|| format!("failed to read output module `{}`", wasm_path.display()))?;
140
141 let encoder = ComponentEncoder::default()
142 .module(&wasm_bytes)?
143 .adapter("wasi_snapshot_preview1", &adapter_bytes)
144 .context("failed to load adapter module")?
145 .validate(true);
146
147 let component_bytes = encoder
148 .encode()
149 .context("failed to encode wasm component")?;
150
151 let component_bytes = self
152 .strip_custom_sections(&component_bytes)
153 .context("failed to strip debug sections from wasm component")?;
154
155 fs::write(extension_dir.join("extension.wasm"), &component_bytes)
156 .context("failed to write extension.wasm")?;
157
158 Ok(())
159 }
160
161 async fn compile_grammar(
162 &self,
163 extension_dir: &Path,
164 grammar_name: &str,
165 grammar_metadata: &GrammarManifestEntry,
166 ) -> Result<()> {
167 let clang_path = self.install_wasi_sdk_if_needed().await?;
168
169 let mut grammar_repo_dir = extension_dir.to_path_buf();
170 grammar_repo_dir.extend(["grammars", grammar_name]);
171
172 let mut grammar_wasm_path = grammar_repo_dir.clone();
173 grammar_wasm_path.set_extension("wasm");
174
175 log::info!("checking out {grammar_name} parser");
176 self.checkout_repo(
177 &grammar_repo_dir,
178 &grammar_metadata.repository,
179 &grammar_metadata.rev,
180 )?;
181
182 let src_path = grammar_repo_dir.join("src");
183 let parser_path = src_path.join("parser.c");
184 let scanner_path = src_path.join("scanner.c");
185
186 log::info!("compiling {grammar_name} parser");
187 let clang_output = Command::new(&clang_path)
188 .args(["-fPIC", "-shared", "-Os"])
189 .arg(format!("-Wl,--export=tree_sitter_{grammar_name}"))
190 .arg("-o")
191 .arg(&grammar_wasm_path)
192 .arg("-I")
193 .arg(&src_path)
194 .arg(&parser_path)
195 .args(scanner_path.exists().then_some(scanner_path))
196 .output()
197 .context("failed to run clang")?;
198 if !clang_output.status.success() {
199 bail!(
200 "failed to compile {} parser with clang: {}",
201 grammar_name,
202 String::from_utf8_lossy(&clang_output.stderr),
203 );
204 }
205
206 Ok(())
207 }
208
209 fn checkout_repo(&self, directory: &Path, url: &str, rev: &str) -> Result<()> {
210 let git_dir = directory.join(".git");
211
212 if directory.exists() {
213 let remotes_output = Command::new("git")
214 .arg("--git-dir")
215 .arg(&git_dir)
216 .args(["remote", "-v"])
217 .output()?;
218 let has_remote = remotes_output.status.success()
219 && String::from_utf8_lossy(&remotes_output.stdout)
220 .lines()
221 .any(|line| {
222 let mut parts = line.split(|c: char| c.is_whitespace());
223 parts.next() == Some("origin") && parts.any(|part| part == url)
224 });
225 if !has_remote {
226 bail!(
227 "grammar directory '{}' already exists, but is not a git clone of '{}'",
228 directory.display(),
229 url
230 );
231 }
232 } else {
233 fs::create_dir_all(&directory).with_context(|| {
234 format!("failed to create grammar directory {}", directory.display(),)
235 })?;
236 let init_output = Command::new("git")
237 .arg("init")
238 .current_dir(&directory)
239 .output()?;
240 if !init_output.status.success() {
241 bail!(
242 "failed to run `git init` in directory '{}'",
243 directory.display()
244 );
245 }
246
247 let remote_add_output = Command::new("git")
248 .arg("--git-dir")
249 .arg(&git_dir)
250 .args(["remote", "add", "origin", url])
251 .output()
252 .context("failed to execute `git remote add`")?;
253 if !remote_add_output.status.success() {
254 bail!(
255 "failed to add remote {url} for git repository {}",
256 git_dir.display()
257 );
258 }
259 }
260
261 let fetch_output = Command::new("git")
262 .arg("--git-dir")
263 .arg(&git_dir)
264 .args(["fetch", "--depth", "1", "origin", &rev])
265 .output()
266 .context("failed to execute `git fetch`")?;
267
268 let checkout_output = Command::new("git")
269 .arg("--git-dir")
270 .arg(&git_dir)
271 .args(["checkout", &rev])
272 .current_dir(&directory)
273 .output()
274 .context("failed to execute `git checkout`")?;
275 if !checkout_output.status.success() {
276 if !fetch_output.status.success() {
277 bail!(
278 "failed to fetch revision {} in directory '{}'",
279 rev,
280 directory.display()
281 );
282 }
283 bail!(
284 "failed to checkout revision {} in directory '{}': {}",
285 rev,
286 directory.display(),
287 String::from_utf8_lossy(&checkout_output.stderr)
288 );
289 }
290
291 Ok(())
292 }
293
294 fn install_rust_wasm_target_if_needed(&self) -> Result<()> {
295 let rustc_output = Command::new("rustc")
296 .arg("--print")
297 .arg("sysroot")
298 .output()
299 .context("failed to run rustc")?;
300 if !rustc_output.status.success() {
301 bail!(
302 "failed to retrieve rust sysroot: {}",
303 String::from_utf8_lossy(&rustc_output.stderr)
304 );
305 }
306
307 let sysroot = PathBuf::from(String::from_utf8(rustc_output.stdout)?.trim());
308 if sysroot.join("lib/rustlib").join(RUST_TARGET).exists() {
309 return Ok(());
310 }
311
312 let output = Command::new("rustup")
313 .args(["target", "add", RUST_TARGET])
314 .stderr(Stdio::inherit())
315 .stdout(Stdio::inherit())
316 .output()
317 .context("failed to run `rustup target add`")?;
318 if !output.status.success() {
319 bail!("failed to install the `{RUST_TARGET}` target");
320 }
321
322 Ok(())
323 }
324
325 async fn install_wasi_preview1_adapter_if_needed(&self) -> Result<Vec<u8>> {
326 let cache_path = self.cache_dir.join("wasi_snapshot_preview1.reactor.wasm");
327 if let Ok(content) = fs::read(&cache_path) {
328 if Parser::is_core_wasm(&content) {
329 return Ok(content);
330 }
331 }
332
333 fs::remove_file(&cache_path).ok();
334
335 log::info!(
336 "downloading wasi adapter module to {}",
337 cache_path.display()
338 );
339 let mut response = self
340 .http
341 .get(WASI_ADAPTER_URL, AsyncBody::default(), true)
342 .await?;
343
344 let mut content = Vec::new();
345 let mut body = BufReader::new(response.body_mut());
346 body.read_to_end(&mut content).await?;
347
348 fs::write(&cache_path, &content)
349 .with_context(|| format!("failed to save file {}", cache_path.display()))?;
350
351 if !Parser::is_core_wasm(&content) {
352 bail!("downloaded wasi adapter is invalid");
353 }
354 Ok(content)
355 }
356
357 async fn install_wasi_sdk_if_needed(&self) -> Result<PathBuf> {
358 let url = if let Some(asset_name) = WASI_SDK_ASSET_NAME {
359 format!("{WASI_SDK_URL}/{asset_name}")
360 } else {
361 bail!("wasi-sdk is not available for platform {}", env::consts::OS);
362 };
363
364 let wasi_sdk_dir = self.cache_dir.join("wasi-sdk");
365 let mut clang_path = wasi_sdk_dir.clone();
366 clang_path.extend(["bin", "clang-17"]);
367
368 if fs::metadata(&clang_path).map_or(false, |metadata| metadata.is_file()) {
369 return Ok(clang_path);
370 }
371
372 let mut tar_out_dir = wasi_sdk_dir.clone();
373 tar_out_dir.set_extension("archive");
374
375 fs::remove_dir_all(&wasi_sdk_dir).ok();
376 fs::remove_dir_all(&tar_out_dir).ok();
377
378 log::info!("downloading wasi-sdk to {}", wasi_sdk_dir.display());
379 let mut response = self.http.get(&url, AsyncBody::default(), true).await?;
380 let body = BufReader::new(response.body_mut());
381 let body = GzipDecoder::new(body);
382 let tar = Archive::new(body);
383 tar.unpack(&tar_out_dir)
384 .await
385 .context("failed to unpack wasi-sdk archive")?;
386
387 let inner_dir = fs::read_dir(&tar_out_dir)?
388 .next()
389 .ok_or_else(|| anyhow!("no content"))?
390 .context("failed to read contents of extracted wasi archive directory")?
391 .path();
392 fs::rename(&inner_dir, &wasi_sdk_dir).context("failed to move extracted wasi dir")?;
393 fs::remove_dir_all(&tar_out_dir).ok();
394
395 Ok(clang_path)
396 }
397
398 // This was adapted from:
399 // https://github.com/bytecodealliance/wasm-tools/1791a8f139722e9f8679a2bd3d8e423e55132b22/src/bin/wasm-tools/strip.rs
400 fn strip_custom_sections(&self, input: &Vec<u8>) -> Result<Vec<u8>> {
401 use wasmparser::Payload::*;
402
403 let strip_custom_section = |name: &str| name.starts_with(".debug");
404
405 let mut output = Vec::new();
406 let mut stack = Vec::new();
407
408 for payload in Parser::new(0).parse_all(input) {
409 let payload = payload?;
410
411 // Track nesting depth, so that we don't mess with inner producer sections:
412 match payload {
413 Version { encoding, .. } => {
414 output.extend_from_slice(match encoding {
415 wasmparser::Encoding::Component => &wasm_encoder::Component::HEADER,
416 wasmparser::Encoding::Module => &wasm_encoder::Module::HEADER,
417 });
418 }
419 ModuleSection { .. } | ComponentSection { .. } => {
420 stack.push(mem::take(&mut output));
421 continue;
422 }
423 End { .. } => {
424 let mut parent = match stack.pop() {
425 Some(c) => c,
426 None => break,
427 };
428 if output.starts_with(&wasm_encoder::Component::HEADER) {
429 parent.push(ComponentSectionId::Component as u8);
430 output.encode(&mut parent);
431 } else {
432 parent.push(ComponentSectionId::CoreModule as u8);
433 output.encode(&mut parent);
434 }
435 output = parent;
436 }
437 _ => {}
438 }
439
440 match &payload {
441 CustomSection(c) => {
442 if strip_custom_section(c.name()) {
443 continue;
444 }
445 }
446
447 _ => {}
448 }
449
450 if let Some((id, range)) = payload.as_section() {
451 RawSection {
452 id,
453 data: &input[range],
454 }
455 .append_to(&mut output);
456 }
457 }
458
459 Ok(output)
460 }
461}