extension_builder.rs

  1use crate::{
  2    ExtensionLibraryKind, ExtensionManifest, GrammarManifestEntry, build_debug_adapter_schema_path,
  3    parse_wasm_extension_version,
  4};
  5use anyhow::{Context as _, Result, bail};
  6use async_compression::futures::bufread::GzipDecoder;
  7use async_tar::Archive;
  8use futures::io::BufReader;
  9use heck::ToSnakeCase;
 10use http_client::{self, AsyncBody, HttpClient};
 11use serde::Deserialize;
 12use std::{
 13    env, fs, mem,
 14    path::{Path, PathBuf},
 15    process::Stdio,
 16    str::FromStr,
 17    sync::Arc,
 18};
 19use wasm_encoder::{ComponentSectionId, Encode as _, RawSection, Section as _};
 20use wasmparser::Parser;
 21
 22/// Currently, we compile with Rust's `wasm32-wasip2` target, which works with WASI `preview2` and the component model.
 23const RUST_TARGET: &str = "wasm32-wasip2";
 24
 25/// Compiling Tree-sitter parsers from C to WASM requires Clang 17, and a WASM build of libc
 26/// and clang's runtime library. The `wasi-sdk` provides these binaries.
 27///
 28/// Once Clang 17 and its wasm target are available via system package managers, we won't need
 29/// to download this.
 30const WASI_SDK_URL: &str = "https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-25/";
 31const WASI_SDK_ASSET_NAME: Option<&str> = if cfg!(all(target_os = "macos", target_arch = "x86_64"))
 32{
 33    Some("wasi-sdk-25.0-x86_64-macos.tar.gz")
 34} else if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
 35    Some("wasi-sdk-25.0-arm64-macos.tar.gz")
 36} else if cfg!(all(target_os = "linux", target_arch = "x86_64")) {
 37    Some("wasi-sdk-25.0-x86_64-linux.tar.gz")
 38} else if cfg!(all(target_os = "linux", target_arch = "aarch64")) {
 39    Some("wasi-sdk-25.0-arm64-linux.tar.gz")
 40} else if cfg!(all(target_os = "freebsd", target_arch = "x86_64")) {
 41    Some("wasi-sdk-25.0-x86_64-linux.tar.gz")
 42} else if cfg!(all(target_os = "freebsd", target_arch = "aarch64")) {
 43    Some("wasi-sdk-25.0-arm64-linux.tar.gz")
 44} else if cfg!(all(target_os = "windows", target_arch = "x86_64")) {
 45    Some("wasi-sdk-25.0-x86_64-windows.tar.gz")
 46} else {
 47    None
 48};
 49
 50pub struct ExtensionBuilder {
 51    cache_dir: PathBuf,
 52    pub http: Arc<dyn HttpClient>,
 53}
 54
 55pub struct CompileExtensionOptions {
 56    pub release: bool,
 57}
 58
 59#[derive(Deserialize)]
 60struct CargoToml {
 61    package: CargoTomlPackage,
 62}
 63
 64#[derive(Deserialize)]
 65struct CargoTomlPackage {
 66    name: String,
 67}
 68
 69impl ExtensionBuilder {
 70    pub fn new(http_client: Arc<dyn HttpClient>, cache_dir: PathBuf) -> Self {
 71        Self {
 72            cache_dir,
 73            http: http_client,
 74        }
 75    }
 76
 77    pub async fn compile_extension(
 78        &self,
 79        extension_dir: &Path,
 80        extension_manifest: &mut ExtensionManifest,
 81        options: CompileExtensionOptions,
 82    ) -> Result<()> {
 83        populate_defaults(extension_manifest, extension_dir)?;
 84
 85        if extension_dir.is_relative() {
 86            bail!(
 87                "extension dir {} is not an absolute path",
 88                extension_dir.display()
 89            );
 90        }
 91
 92        fs::create_dir_all(&self.cache_dir).context("failed to create cache dir")?;
 93
 94        if extension_manifest.lib.kind == Some(ExtensionLibraryKind::Rust) {
 95            log::info!("compiling Rust extension {}", extension_dir.display());
 96            self.compile_rust_extension(extension_dir, extension_manifest, options)
 97                .await
 98                .context("failed to compile Rust extension")?;
 99            log::info!("compiled Rust extension {}", extension_dir.display());
100        }
101
102        for (debug_adapter_name, meta) in &mut extension_manifest.debug_adapters {
103            let debug_adapter_schema_path =
104                extension_dir.join(build_debug_adapter_schema_path(debug_adapter_name, meta));
105
106            let debug_adapter_schema = fs::read_to_string(&debug_adapter_schema_path)
107                .with_context(|| {
108                    format!("failed to read debug adapter schema for `{debug_adapter_name}` from `{debug_adapter_schema_path:?}`")
109                })?;
110            _ = serde_json::Value::from_str(&debug_adapter_schema).with_context(|| {
111                format!("Debug adapter schema for `{debug_adapter_name}` (path: `{debug_adapter_schema_path:?}`) is not a valid JSON")
112            })?;
113        }
114        for (grammar_name, grammar_metadata) in &extension_manifest.grammars {
115            let snake_cased_grammar_name = grammar_name.to_snake_case();
116            if grammar_name.as_ref() != snake_cased_grammar_name.as_str() {
117                bail!(
118                    "grammar name '{grammar_name}' must be written in snake_case: {snake_cased_grammar_name}"
119                );
120            }
121
122            log::info!(
123                "compiling grammar {grammar_name} for extension {}",
124                extension_dir.display()
125            );
126            self.compile_grammar(extension_dir, grammar_name.as_ref(), grammar_metadata)
127                .await
128                .with_context(|| format!("failed to compile grammar '{grammar_name}'"))?;
129            log::info!(
130                "compiled grammar {grammar_name} for extension {}",
131                extension_dir.display()
132            );
133        }
134
135        log::info!("finished compiling extension {}", extension_dir.display());
136        Ok(())
137    }
138
139    async fn compile_rust_extension(
140        &self,
141        extension_dir: &Path,
142        manifest: &mut ExtensionManifest,
143        options: CompileExtensionOptions,
144    ) -> anyhow::Result<()> {
145        self.install_rust_wasm_target_if_needed()?;
146
147        let cargo_toml_content = fs::read_to_string(extension_dir.join("Cargo.toml"))?;
148        let cargo_toml: CargoToml = toml::from_str(&cargo_toml_content)?;
149
150        log::info!(
151            "compiling Rust crate for extension {}",
152            extension_dir.display()
153        );
154        let status = util::command::new_std_command("cargo")
155            .args(["build", "--target", RUST_TARGET])
156            .args(options.release.then_some("--release"))
157            .arg("--target-dir")
158            .arg(extension_dir.join("target"))
159            // WASI builds do not work with sccache and just stuck, so disable it.
160            .env("RUSTC_WRAPPER", "")
161            .current_dir(extension_dir)
162            .status()
163            .context("failed to run `cargo`")?;
164        if !status.success() {
165            bail!("failed to build extension",);
166        }
167
168        log::info!(
169            "compiled Rust crate for extension {}",
170            extension_dir.display()
171        );
172
173        let mut wasm_path = PathBuf::from(extension_dir);
174        wasm_path.extend([
175            "target",
176            RUST_TARGET,
177            if options.release { "release" } else { "debug" },
178            &cargo_toml
179                .package
180                .name
181                // The wasm32-wasip2 target normalizes `-` in package names to `_` in the resulting `.wasm` file.
182                .replace('-', "_"),
183        ]);
184        wasm_path.set_extension("wasm");
185
186        log::info!(
187            "encoding wasm component for extension {}",
188            extension_dir.display()
189        );
190
191        let component_bytes = fs::read(&wasm_path)
192            .with_context(|| format!("failed to read output module `{}`", wasm_path.display()))?;
193
194        let component_bytes = self
195            .strip_custom_sections(&component_bytes)
196            .context("failed to strip debug sections from wasm component")?;
197
198        let wasm_extension_api_version =
199            parse_wasm_extension_version(&manifest.id, &component_bytes)
200                .context("compiled wasm did not contain a valid zed extension api version")?;
201        manifest.lib.version = Some(wasm_extension_api_version);
202
203        let extension_file = extension_dir.join("extension.wasm");
204        fs::write(extension_file.clone(), &component_bytes)
205            .context("failed to write extension.wasm")?;
206
207        log::info!(
208            "extension {} written to {}",
209            extension_dir.display(),
210            extension_file.display()
211        );
212
213        Ok(())
214    }
215
216    async fn compile_grammar(
217        &self,
218        extension_dir: &Path,
219        grammar_name: &str,
220        grammar_metadata: &GrammarManifestEntry,
221    ) -> Result<()> {
222        let clang_path = self.install_wasi_sdk_if_needed().await?;
223
224        let mut grammar_repo_dir = extension_dir.to_path_buf();
225        grammar_repo_dir.extend(["grammars", grammar_name]);
226
227        let mut grammar_wasm_path = grammar_repo_dir.clone();
228        grammar_wasm_path.set_extension("wasm");
229
230        log::info!("checking out {grammar_name} parser");
231        self.checkout_repo(
232            &grammar_repo_dir,
233            &grammar_metadata.repository,
234            &grammar_metadata.rev,
235        )?;
236
237        let base_grammar_path = grammar_metadata
238            .path
239            .as_ref()
240            .map(|path| grammar_repo_dir.join(path))
241            .unwrap_or(grammar_repo_dir);
242
243        let src_path = base_grammar_path.join("src");
244        let parser_path = src_path.join("parser.c");
245        let scanner_path = src_path.join("scanner.c");
246
247        log::info!("compiling {grammar_name} parser");
248        let clang_status = util::command::new_std_command(&clang_path)
249            .args(["-fPIC", "-shared", "-Os"])
250            .arg(format!("-Wl,--export=tree_sitter_{grammar_name}"))
251            .arg("-o")
252            .arg(&grammar_wasm_path)
253            .arg("-I")
254            .arg(&src_path)
255            .arg(&parser_path)
256            .args(scanner_path.exists().then_some(scanner_path))
257            .status()
258            .context("failed to run clang")?;
259
260        if !clang_status.success() {
261            bail!("failed to compile {} parser with clang", grammar_name,);
262        }
263
264        Ok(())
265    }
266
267    fn checkout_repo(&self, directory: &Path, url: &str, rev: &str) -> Result<()> {
268        let git_dir = directory.join(".git");
269
270        if directory.exists() {
271            let remotes_output = util::command::new_std_command("git")
272                .arg("--git-dir")
273                .arg(&git_dir)
274                .args(["remote", "-v"])
275                .output()?;
276            let has_remote = remotes_output.status.success()
277                && String::from_utf8_lossy(&remotes_output.stdout)
278                    .lines()
279                    .any(|line| {
280                        let mut parts = line.split(|c: char| c.is_whitespace());
281                        parts.next() == Some("origin") && parts.any(|part| part == url)
282                    });
283            if !has_remote {
284                bail!(
285                    "grammar directory '{}' already exists, but is not a git clone of '{}'",
286                    directory.display(),
287                    url
288                );
289            }
290        } else {
291            fs::create_dir_all(directory).with_context(|| {
292                format!("failed to create grammar directory {}", directory.display(),)
293            })?;
294            let init_output = util::command::new_std_command("git")
295                .arg("init")
296                .current_dir(directory)
297                .output()?;
298            if !init_output.status.success() {
299                bail!(
300                    "failed to run `git init` in directory '{}'",
301                    directory.display()
302                );
303            }
304
305            let remote_add_output = util::command::new_std_command("git")
306                .arg("--git-dir")
307                .arg(&git_dir)
308                .args(["remote", "add", "origin", url])
309                .output()
310                .context("failed to execute `git remote add`")?;
311            if !remote_add_output.status.success() {
312                bail!(
313                    "failed to add remote {url} for git repository {}",
314                    git_dir.display()
315                );
316            }
317        }
318
319        let fetch_output = util::command::new_std_command("git")
320            .arg("--git-dir")
321            .arg(&git_dir)
322            .args(["fetch", "--depth", "1", "origin", rev])
323            .output()
324            .context("failed to execute `git fetch`")?;
325
326        let checkout_output = util::command::new_std_command("git")
327            .arg("--git-dir")
328            .arg(&git_dir)
329            .args(["checkout", rev])
330            .current_dir(directory)
331            .output()
332            .context("failed to execute `git checkout`")?;
333        if !checkout_output.status.success() {
334            if !fetch_output.status.success() {
335                bail!(
336                    "failed to fetch revision {} in directory '{}'",
337                    rev,
338                    directory.display()
339                );
340            }
341            bail!(
342                "failed to checkout revision {} in directory '{}': {}",
343                rev,
344                directory.display(),
345                String::from_utf8_lossy(&checkout_output.stderr)
346            );
347        }
348
349        Ok(())
350    }
351
352    fn install_rust_wasm_target_if_needed(&self) -> Result<()> {
353        let rustc_output = util::command::new_std_command("rustc")
354            .arg("--print")
355            .arg("sysroot")
356            .output()
357            .context("failed to run rustc")?;
358        if !rustc_output.status.success() {
359            bail!(
360                "failed to retrieve rust sysroot: {}",
361                String::from_utf8_lossy(&rustc_output.stderr)
362            );
363        }
364
365        let sysroot = PathBuf::from(String::from_utf8(rustc_output.stdout)?.trim());
366        if sysroot.join("lib/rustlib").join(RUST_TARGET).exists() {
367            return Ok(());
368        }
369
370        let output = util::command::new_std_command("rustup")
371            .args(["target", "add", RUST_TARGET])
372            .stderr(Stdio::piped())
373            .stdout(Stdio::inherit())
374            .output()
375            .context("failed to run `rustup target add`")?;
376        if !output.status.success() {
377            bail!(
378                "failed to install the `{RUST_TARGET}` target: {}",
379                String::from_utf8_lossy(&rustc_output.stderr)
380            );
381        }
382
383        Ok(())
384    }
385
386    async fn install_wasi_sdk_if_needed(&self) -> Result<PathBuf> {
387        let url = if let Some(asset_name) = WASI_SDK_ASSET_NAME {
388            format!("{WASI_SDK_URL}{asset_name}")
389        } else {
390            bail!("wasi-sdk is not available for platform {}", env::consts::OS);
391        };
392
393        let wasi_sdk_dir = self.cache_dir.join("wasi-sdk");
394        let mut clang_path = wasi_sdk_dir.clone();
395        clang_path.extend(["bin", &format!("clang{}", env::consts::EXE_SUFFIX)]);
396
397        if fs::metadata(&clang_path).is_ok_and(|metadata| metadata.is_file()) {
398            return Ok(clang_path);
399        }
400
401        let mut tar_out_dir = wasi_sdk_dir.clone();
402        tar_out_dir.set_extension("archive");
403
404        fs::remove_dir_all(&wasi_sdk_dir).ok();
405        fs::remove_dir_all(&tar_out_dir).ok();
406
407        log::info!("downloading wasi-sdk to {}", wasi_sdk_dir.display());
408        let mut response = self.http.get(&url, AsyncBody::default(), true).await?;
409        let body = BufReader::new(response.body_mut());
410        let body = GzipDecoder::new(body);
411        let tar = Archive::new(body);
412
413        tar.unpack(&tar_out_dir)
414            .await
415            .context("failed to unpack wasi-sdk archive")?;
416
417        let inner_dir = fs::read_dir(&tar_out_dir)?
418            .next()
419            .context("no content")?
420            .context("failed to read contents of extracted wasi archive directory")?
421            .path();
422        fs::rename(&inner_dir, &wasi_sdk_dir).context("failed to move extracted wasi dir")?;
423        fs::remove_dir_all(&tar_out_dir).ok();
424
425        Ok(clang_path)
426    }
427
428    // This was adapted from:
429    // https://github.com/bytecodealliance/wasm-tools/blob/e8809bb17fcf69aa8c85cd5e6db7cff5cf36b1de/src/bin/wasm-tools/strip.rs
430    fn strip_custom_sections(&self, input: &Vec<u8>) -> Result<Vec<u8>> {
431        use wasmparser::Payload::*;
432
433        let strip_custom_section = |name: &str| {
434            // Default strip everything but:
435            // * the `name` section
436            // * any `component-type` sections
437            // * the `dylink.0` section
438            // * our custom version section
439            name != "name"
440                && !name.starts_with("component-type:")
441                && name != "dylink.0"
442                && name != "zed:api-version"
443        };
444
445        let mut output = Vec::new();
446        let mut stack = Vec::new();
447
448        for payload in Parser::new(0).parse_all(input) {
449            let payload = payload?;
450
451            // Track nesting depth, so that we don't mess with inner producer sections:
452            match payload {
453                Version { encoding, .. } => {
454                    output.extend_from_slice(match encoding {
455                        wasmparser::Encoding::Component => &wasm_encoder::Component::HEADER,
456                        wasmparser::Encoding::Module => &wasm_encoder::Module::HEADER,
457                    });
458                }
459                ModuleSection { .. } | ComponentSection { .. } => {
460                    stack.push(mem::take(&mut output));
461                    continue;
462                }
463                End { .. } => {
464                    let mut parent = match stack.pop() {
465                        Some(c) => c,
466                        None => break,
467                    };
468                    if output.starts_with(&wasm_encoder::Component::HEADER) {
469                        parent.push(ComponentSectionId::Component as u8);
470                        output.encode(&mut parent);
471                    } else {
472                        parent.push(ComponentSectionId::CoreModule as u8);
473                        output.encode(&mut parent);
474                    }
475                    output = parent;
476                }
477                _ => {}
478            }
479
480            if let CustomSection(c) = &payload
481                && strip_custom_section(c.name())
482            {
483                continue;
484            }
485            if let Some((id, range)) = payload.as_section() {
486                RawSection {
487                    id,
488                    data: &input[range],
489                }
490                .append_to(&mut output);
491            }
492        }
493
494        Ok(output)
495    }
496}
497
498fn populate_defaults(manifest: &mut ExtensionManifest, extension_path: &Path) -> Result<()> {
499    // For legacy extensions on the v0 schema (aka, using `extension.json`), clear out any existing
500    // contents of the computed fields, since we don't care what the existing values are.
501    if manifest.schema_version.is_v0() {
502        manifest.languages.clear();
503        manifest.grammars.clear();
504        manifest.themes.clear();
505    }
506
507    let cargo_toml_path = extension_path.join("Cargo.toml");
508    if cargo_toml_path.exists() {
509        manifest.lib.kind = Some(ExtensionLibraryKind::Rust);
510    }
511
512    let languages_dir = extension_path.join("languages");
513    if languages_dir.exists() {
514        for entry in fs::read_dir(&languages_dir).context("failed to list languages dir")? {
515            let entry = entry?;
516            let language_dir = entry.path();
517            let config_path = language_dir.join("config.toml");
518            if config_path.exists() {
519                let relative_language_dir =
520                    language_dir.strip_prefix(extension_path)?.to_path_buf();
521                if !manifest.languages.contains(&relative_language_dir) {
522                    manifest.languages.push(relative_language_dir);
523                }
524            }
525        }
526    }
527
528    let themes_dir = extension_path.join("themes");
529    if themes_dir.exists() {
530        for entry in fs::read_dir(&themes_dir).context("failed to list themes dir")? {
531            let entry = entry?;
532            let theme_path = entry.path();
533            if theme_path.extension() == Some("json".as_ref()) {
534                let relative_theme_path = theme_path.strip_prefix(extension_path)?.to_path_buf();
535                if !manifest.themes.contains(&relative_theme_path) {
536                    manifest.themes.push(relative_theme_path);
537                }
538            }
539        }
540    }
541
542    let icon_themes_dir = extension_path.join("icon_themes");
543    if icon_themes_dir.exists() {
544        for entry in fs::read_dir(&icon_themes_dir).context("failed to list icon themes dir")? {
545            let entry = entry?;
546            let icon_theme_path = entry.path();
547            if icon_theme_path.extension() == Some("json".as_ref()) {
548                let relative_icon_theme_path =
549                    icon_theme_path.strip_prefix(extension_path)?.to_path_buf();
550                if !manifest.icon_themes.contains(&relative_icon_theme_path) {
551                    manifest.icon_themes.push(relative_icon_theme_path);
552                }
553            }
554        }
555    }
556
557    let snippets_json_path = extension_path.join("snippets.json");
558    if snippets_json_path.exists() {
559        manifest.snippets = Some(snippets_json_path);
560    }
561
562    // For legacy extensions on the v0 schema (aka, using `extension.json`), we want to populate the grammars in
563    // the manifest using the contents of the `grammars` directory.
564    if manifest.schema_version.is_v0() {
565        let grammars_dir = extension_path.join("grammars");
566        if grammars_dir.exists() {
567            for entry in fs::read_dir(&grammars_dir).context("failed to list grammars dir")? {
568                let entry = entry?;
569                let grammar_path = entry.path();
570                if grammar_path.extension() == Some("toml".as_ref()) {
571                    #[derive(Deserialize)]
572                    struct GrammarConfigToml {
573                        pub repository: String,
574                        pub commit: String,
575                        #[serde(default)]
576                        pub path: Option<String>,
577                    }
578
579                    let grammar_config = fs::read_to_string(&grammar_path)?;
580                    let grammar_config: GrammarConfigToml = toml::from_str(&grammar_config)?;
581
582                    let grammar_name = grammar_path
583                        .file_stem()
584                        .and_then(|stem| stem.to_str())
585                        .context("no grammar name")?;
586                    if !manifest.grammars.contains_key(grammar_name) {
587                        manifest.grammars.insert(
588                            grammar_name.into(),
589                            GrammarManifestEntry {
590                                repository: grammar_config.repository,
591                                rev: grammar_config.commit,
592                                path: grammar_config.path,
593                            },
594                        );
595                    }
596                }
597            }
598        }
599    }
600
601    Ok(())
602}