extension_builder.rs

  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).context("failed to create 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).map_or(false, |stat| stat.is_file())
 89        {
 90            log::info!("compiling Rust extension {}", extension_dir.display());
 91            self.compile_rust_extension(extension_dir, options)
 92                .await
 93                .context("failed to compile Rust extension")?;
 94        }
 95
 96        for (grammar_name, grammar_metadata) in &extension_manifest.grammars {
 97            self.compile_grammar(extension_dir, grammar_name.as_ref(), grammar_metadata)
 98                .await
 99                .with_context(|| format!("failed to compile grammar '{grammar_name}'"))?;
100        }
101
102        log::info!("finished compiling extension {}", extension_dir.display());
103        Ok(())
104    }
105
106    async fn compile_rust_extension(
107        &self,
108        extension_dir: &Path,
109        options: CompileExtensionOptions,
110    ) -> Result<(), anyhow::Error> {
111        self.install_rust_wasm_target_if_needed()?;
112        let adapter_bytes = self.install_wasi_preview1_adapter_if_needed().await?;
113
114        let cargo_toml_content = fs::read_to_string(&extension_dir.join("Cargo.toml"))?;
115        let cargo_toml: CargoToml = toml::from_str(&cargo_toml_content)?;
116
117        log::info!("compiling rust extension {}", extension_dir.display());
118        let output = Command::new("cargo")
119            .args(["build", "--target", RUST_TARGET])
120            .args(options.release.then_some("--release"))
121            .arg("--target-dir")
122            .arg(extension_dir.join("target"))
123            .current_dir(&extension_dir)
124            .output()
125            .context("failed to run `cargo`")?;
126        if !output.status.success() {
127            bail!(
128                "failed to build extension {}",
129                String::from_utf8_lossy(&output.stderr)
130            );
131        }
132
133        let mut wasm_path = PathBuf::from(extension_dir);
134        wasm_path.extend([
135            "target",
136            RUST_TARGET,
137            if options.release { "release" } else { "debug" },
138            &cargo_toml
139                .package
140                .name
141                // The wasm32-wasi target normalizes `-` in package names to `_` in the resulting `.wasm` file.
142                .replace('-', "_"),
143        ]);
144        wasm_path.set_extension("wasm");
145
146        let wasm_bytes = fs::read(&wasm_path)
147            .with_context(|| format!("failed to read output module `{}`", wasm_path.display()))?;
148
149        let encoder = ComponentEncoder::default()
150            .module(&wasm_bytes)?
151            .adapter("wasi_snapshot_preview1", &adapter_bytes)
152            .context("failed to load adapter module")?
153            .validate(true);
154
155        let component_bytes = encoder
156            .encode()
157            .context("failed to encode wasm component")?;
158
159        let component_bytes = self
160            .strip_custom_sections(&component_bytes)
161            .context("failed to strip debug sections from wasm component")?;
162
163        fs::write(extension_dir.join("extension.wasm"), &component_bytes)
164            .context("failed to write extension.wasm")?;
165
166        Ok(())
167    }
168
169    async fn compile_grammar(
170        &self,
171        extension_dir: &Path,
172        grammar_name: &str,
173        grammar_metadata: &GrammarManifestEntry,
174    ) -> Result<()> {
175        let clang_path = self.install_wasi_sdk_if_needed().await?;
176
177        let mut grammar_repo_dir = extension_dir.to_path_buf();
178        grammar_repo_dir.extend(["grammars", grammar_name]);
179
180        let mut grammar_wasm_path = grammar_repo_dir.clone();
181        grammar_wasm_path.set_extension("wasm");
182
183        log::info!("checking out {grammar_name} parser");
184        self.checkout_repo(
185            &grammar_repo_dir,
186            &grammar_metadata.repository,
187            &grammar_metadata.rev,
188        )?;
189
190        let src_path = grammar_repo_dir.join("src");
191        let parser_path = src_path.join("parser.c");
192        let scanner_path = src_path.join("scanner.c");
193
194        log::info!("compiling {grammar_name} parser");
195        let clang_output = Command::new(&clang_path)
196            .args(["-fPIC", "-shared", "-Os"])
197            .arg(format!("-Wl,--export=tree_sitter_{grammar_name}"))
198            .arg("-o")
199            .arg(&grammar_wasm_path)
200            .arg("-I")
201            .arg(&src_path)
202            .arg(&parser_path)
203            .args(scanner_path.exists().then_some(scanner_path))
204            .output()
205            .context("failed to run clang")?;
206        if !clang_output.status.success() {
207            bail!(
208                "failed to compile {} parser with clang: {}",
209                grammar_name,
210                String::from_utf8_lossy(&clang_output.stderr),
211            );
212        }
213
214        Ok(())
215    }
216
217    fn checkout_repo(&self, directory: &Path, url: &str, rev: &str) -> Result<()> {
218        let git_dir = directory.join(".git");
219
220        if directory.exists() {
221            let remotes_output = Command::new("git")
222                .arg("--git-dir")
223                .arg(&git_dir)
224                .args(["remote", "-v"])
225                .output()?;
226            let has_remote = remotes_output.status.success()
227                && String::from_utf8_lossy(&remotes_output.stdout)
228                    .lines()
229                    .any(|line| {
230                        let mut parts = line.split(|c: char| c.is_whitespace());
231                        parts.next() == Some("origin") && parts.any(|part| part == url)
232                    });
233            if !has_remote {
234                bail!(
235                    "grammar directory '{}' already exists, but is not a git clone of '{}'",
236                    directory.display(),
237                    url
238                );
239            }
240        } else {
241            fs::create_dir_all(&directory).with_context(|| {
242                format!("failed to create grammar directory {}", directory.display(),)
243            })?;
244            let init_output = Command::new("git")
245                .arg("init")
246                .current_dir(&directory)
247                .output()?;
248            if !init_output.status.success() {
249                bail!(
250                    "failed to run `git init` in directory '{}'",
251                    directory.display()
252                );
253            }
254
255            let remote_add_output = Command::new("git")
256                .arg("--git-dir")
257                .arg(&git_dir)
258                .args(["remote", "add", "origin", url])
259                .output()
260                .context("failed to execute `git remote add`")?;
261            if !remote_add_output.status.success() {
262                bail!(
263                    "failed to add remote {url} for git repository {}",
264                    git_dir.display()
265                );
266            }
267        }
268
269        let fetch_output = Command::new("git")
270            .arg("--git-dir")
271            .arg(&git_dir)
272            .args(["fetch", "--depth", "1", "origin", &rev])
273            .output()
274            .context("failed to execute `git fetch`")?;
275
276        let checkout_output = Command::new("git")
277            .arg("--git-dir")
278            .arg(&git_dir)
279            .args(["checkout", &rev])
280            .current_dir(&directory)
281            .output()
282            .context("failed to execute `git checkout`")?;
283        if !checkout_output.status.success() {
284            if !fetch_output.status.success() {
285                bail!(
286                    "failed to fetch revision {} in directory '{}'",
287                    rev,
288                    directory.display()
289                );
290            }
291            bail!(
292                "failed to checkout revision {} in directory '{}': {}",
293                rev,
294                directory.display(),
295                String::from_utf8_lossy(&checkout_output.stderr)
296            );
297        }
298
299        Ok(())
300    }
301
302    fn install_rust_wasm_target_if_needed(&self) -> Result<()> {
303        let rustc_output = Command::new("rustc")
304            .arg("--print")
305            .arg("sysroot")
306            .output()
307            .context("failed to run rustc")?;
308        if !rustc_output.status.success() {
309            bail!(
310                "failed to retrieve rust sysroot: {}",
311                String::from_utf8_lossy(&rustc_output.stderr)
312            );
313        }
314
315        let sysroot = PathBuf::from(String::from_utf8(rustc_output.stdout)?.trim());
316        if sysroot.join("lib/rustlib").join(RUST_TARGET).exists() {
317            return Ok(());
318        }
319
320        let output = Command::new("rustup")
321            .args(["target", "add", RUST_TARGET])
322            .stderr(Stdio::inherit())
323            .stdout(Stdio::inherit())
324            .output()
325            .context("failed to run `rustup target add`")?;
326        if !output.status.success() {
327            bail!("failed to install the `{RUST_TARGET}` target");
328        }
329
330        Ok(())
331    }
332
333    async fn install_wasi_preview1_adapter_if_needed(&self) -> Result<Vec<u8>> {
334        let cache_path = self.cache_dir.join("wasi_snapshot_preview1.reactor.wasm");
335        if let Ok(content) = fs::read(&cache_path) {
336            if Parser::is_core_wasm(&content) {
337                return Ok(content);
338            }
339        }
340
341        fs::remove_file(&cache_path).ok();
342
343        log::info!(
344            "downloading wasi adapter module to {}",
345            cache_path.display()
346        );
347        let mut response = self
348            .http
349            .get(WASI_ADAPTER_URL, AsyncBody::default(), true)
350            .await?;
351
352        let mut content = Vec::new();
353        let mut body = BufReader::new(response.body_mut());
354        body.read_to_end(&mut content).await?;
355
356        fs::write(&cache_path, &content)
357            .with_context(|| format!("failed to save file {}", cache_path.display()))?;
358
359        if !Parser::is_core_wasm(&content) {
360            bail!("downloaded wasi adapter is invalid");
361        }
362        Ok(content)
363    }
364
365    async fn install_wasi_sdk_if_needed(&self) -> Result<PathBuf> {
366        let url = if let Some(asset_name) = WASI_SDK_ASSET_NAME {
367            format!("{WASI_SDK_URL}/{asset_name}")
368        } else {
369            bail!("wasi-sdk is not available for platform {}", env::consts::OS);
370        };
371
372        let wasi_sdk_dir = self.cache_dir.join("wasi-sdk");
373        let mut clang_path = wasi_sdk_dir.clone();
374        clang_path.extend(["bin", "clang-17"]);
375
376        if fs::metadata(&clang_path).map_or(false, |metadata| metadata.is_file()) {
377            return Ok(clang_path);
378        }
379
380        let mut tar_out_dir = wasi_sdk_dir.clone();
381        tar_out_dir.set_extension("archive");
382
383        fs::remove_dir_all(&wasi_sdk_dir).ok();
384        fs::remove_dir_all(&tar_out_dir).ok();
385
386        log::info!("downloading wasi-sdk to {}", wasi_sdk_dir.display());
387        let mut response = self.http.get(&url, AsyncBody::default(), true).await?;
388        let body = BufReader::new(response.body_mut());
389        let body = GzipDecoder::new(body);
390        let tar = Archive::new(body);
391        tar.unpack(&tar_out_dir)
392            .await
393            .context("failed to unpack wasi-sdk archive")?;
394
395        let inner_dir = fs::read_dir(&tar_out_dir)?
396            .next()
397            .ok_or_else(|| anyhow!("no content"))?
398            .context("failed to read contents of extracted wasi archive directory")?
399            .path();
400        fs::rename(&inner_dir, &wasi_sdk_dir).context("failed to move extracted wasi dir")?;
401        fs::remove_dir_all(&tar_out_dir).ok();
402
403        Ok(clang_path)
404    }
405
406    // This was adapted from:
407    // https://github.com/bytecodealliance/wasm-tools/1791a8f139722e9f8679a2bd3d8e423e55132b22/src/bin/wasm-tools/strip.rs
408    fn strip_custom_sections(&self, input: &Vec<u8>) -> Result<Vec<u8>> {
409        use wasmparser::Payload::*;
410
411        let strip_custom_section = |name: &str| name.starts_with(".debug");
412
413        let mut output = Vec::new();
414        let mut stack = Vec::new();
415
416        for payload in Parser::new(0).parse_all(input) {
417            let payload = payload?;
418
419            // Track nesting depth, so that we don't mess with inner producer sections:
420            match payload {
421                Version { encoding, .. } => {
422                    output.extend_from_slice(match encoding {
423                        wasmparser::Encoding::Component => &wasm_encoder::Component::HEADER,
424                        wasmparser::Encoding::Module => &wasm_encoder::Module::HEADER,
425                    });
426                }
427                ModuleSection { .. } | ComponentSection { .. } => {
428                    stack.push(mem::take(&mut output));
429                    continue;
430                }
431                End { .. } => {
432                    let mut parent = match stack.pop() {
433                        Some(c) => c,
434                        None => break,
435                    };
436                    if output.starts_with(&wasm_encoder::Component::HEADER) {
437                        parent.push(ComponentSectionId::Component as u8);
438                        output.encode(&mut parent);
439                    } else {
440                        parent.push(ComponentSectionId::CoreModule as u8);
441                        output.encode(&mut parent);
442                    }
443                    output = parent;
444                }
445                _ => {}
446            }
447
448            match &payload {
449                CustomSection(c) => {
450                    if strip_custom_section(c.name()) {
451                        continue;
452                    }
453                }
454
455                _ => {}
456            }
457
458            if let Some((id, range)) = payload.as_section() {
459                RawSection {
460                    id,
461                    data: &input[range],
462                }
463                .append_to(&mut output);
464            }
465        }
466
467        Ok(output)
468    }
469}