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 output = 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 .output()
163 .context("failed to run `cargo`")?;
164 if !output.status.success() {
165 bail!(
166 "failed to build extension {}",
167 String::from_utf8_lossy(&output.stderr)
168 );
169 }
170
171 log::info!(
172 "compiled Rust crate for extension {}",
173 extension_dir.display()
174 );
175
176 let mut wasm_path = PathBuf::from(extension_dir);
177 wasm_path.extend([
178 "target",
179 RUST_TARGET,
180 if options.release { "release" } else { "debug" },
181 &cargo_toml
182 .package
183 .name
184 // The wasm32-wasip2 target normalizes `-` in package names to `_` in the resulting `.wasm` file.
185 .replace('-', "_"),
186 ]);
187 wasm_path.set_extension("wasm");
188
189 log::info!(
190 "encoding wasm component for extension {}",
191 extension_dir.display()
192 );
193
194 let component_bytes = fs::read(&wasm_path)
195 .with_context(|| format!("failed to read output module `{}`", wasm_path.display()))?;
196
197 let component_bytes = self
198 .strip_custom_sections(&component_bytes)
199 .context("failed to strip debug sections from wasm component")?;
200
201 let wasm_extension_api_version =
202 parse_wasm_extension_version(&manifest.id, &component_bytes)
203 .context("compiled wasm did not contain a valid zed extension api version")?;
204 manifest.lib.version = Some(wasm_extension_api_version);
205
206 let extension_file = extension_dir.join("extension.wasm");
207 fs::write(extension_file.clone(), &component_bytes)
208 .context("failed to write extension.wasm")?;
209
210 log::info!(
211 "extension {} written to {}",
212 extension_dir.display(),
213 extension_file.display()
214 );
215
216 Ok(())
217 }
218
219 async fn compile_grammar(
220 &self,
221 extension_dir: &Path,
222 grammar_name: &str,
223 grammar_metadata: &GrammarManifestEntry,
224 ) -> Result<()> {
225 let clang_path = self.install_wasi_sdk_if_needed().await?;
226
227 let mut grammar_repo_dir = extension_dir.to_path_buf();
228 grammar_repo_dir.extend(["grammars", grammar_name]);
229
230 let mut grammar_wasm_path = grammar_repo_dir.clone();
231 grammar_wasm_path.set_extension("wasm");
232
233 log::info!("checking out {grammar_name} parser");
234 self.checkout_repo(
235 &grammar_repo_dir,
236 &grammar_metadata.repository,
237 &grammar_metadata.rev,
238 )?;
239
240 let base_grammar_path = grammar_metadata
241 .path
242 .as_ref()
243 .map(|path| grammar_repo_dir.join(path))
244 .unwrap_or(grammar_repo_dir);
245
246 let src_path = base_grammar_path.join("src");
247 let parser_path = src_path.join("parser.c");
248 let scanner_path = src_path.join("scanner.c");
249
250 log::info!("compiling {grammar_name} parser");
251 let clang_output = util::command::new_std_command(&clang_path)
252 .args(["-fPIC", "-shared", "-Os"])
253 .arg(format!("-Wl,--export=tree_sitter_{grammar_name}"))
254 .arg("-o")
255 .arg(&grammar_wasm_path)
256 .arg("-I")
257 .arg(&src_path)
258 .arg(&parser_path)
259 .args(scanner_path.exists().then_some(scanner_path))
260 .output()
261 .context("failed to run clang")?;
262
263 if !clang_output.status.success() {
264 bail!(
265 "failed to compile {} parser with clang: {}",
266 grammar_name,
267 String::from_utf8_lossy(&clang_output.stderr),
268 );
269 }
270
271 Ok(())
272 }
273
274 fn checkout_repo(&self, directory: &Path, url: &str, rev: &str) -> Result<()> {
275 let git_dir = directory.join(".git");
276
277 if directory.exists() {
278 let remotes_output = util::command::new_std_command("git")
279 .arg("--git-dir")
280 .arg(&git_dir)
281 .args(["remote", "-v"])
282 .output()?;
283 let has_remote = remotes_output.status.success()
284 && String::from_utf8_lossy(&remotes_output.stdout)
285 .lines()
286 .any(|line| {
287 let mut parts = line.split(|c: char| c.is_whitespace());
288 parts.next() == Some("origin") && parts.any(|part| part == url)
289 });
290 if !has_remote {
291 bail!(
292 "grammar directory '{}' already exists, but is not a git clone of '{}'",
293 directory.display(),
294 url
295 );
296 }
297 } else {
298 fs::create_dir_all(directory).with_context(|| {
299 format!("failed to create grammar directory {}", directory.display(),)
300 })?;
301 let init_output = util::command::new_std_command("git")
302 .arg("init")
303 .current_dir(directory)
304 .output()?;
305 if !init_output.status.success() {
306 bail!(
307 "failed to run `git init` in directory '{}'",
308 directory.display()
309 );
310 }
311
312 let remote_add_output = util::command::new_std_command("git")
313 .arg("--git-dir")
314 .arg(&git_dir)
315 .args(["remote", "add", "origin", url])
316 .output()
317 .context("failed to execute `git remote add`")?;
318 if !remote_add_output.status.success() {
319 bail!(
320 "failed to add remote {url} for git repository {}",
321 git_dir.display()
322 );
323 }
324 }
325
326 let fetch_output = util::command::new_std_command("git")
327 .arg("--git-dir")
328 .arg(&git_dir)
329 .args(["fetch", "--depth", "1", "origin", rev])
330 .output()
331 .context("failed to execute `git fetch`")?;
332
333 let checkout_output = util::command::new_std_command("git")
334 .arg("--git-dir")
335 .arg(&git_dir)
336 .args(["checkout", rev])
337 .current_dir(directory)
338 .output()
339 .context("failed to execute `git checkout`")?;
340 if !checkout_output.status.success() {
341 if !fetch_output.status.success() {
342 bail!(
343 "failed to fetch revision {} in directory '{}'",
344 rev,
345 directory.display()
346 );
347 }
348 bail!(
349 "failed to checkout revision {} in directory '{}': {}",
350 rev,
351 directory.display(),
352 String::from_utf8_lossy(&checkout_output.stderr)
353 );
354 }
355
356 Ok(())
357 }
358
359 fn install_rust_wasm_target_if_needed(&self) -> Result<()> {
360 let rustc_output = util::command::new_std_command("rustc")
361 .arg("--print")
362 .arg("sysroot")
363 .output()
364 .context("failed to run rustc")?;
365 if !rustc_output.status.success() {
366 bail!(
367 "failed to retrieve rust sysroot: {}",
368 String::from_utf8_lossy(&rustc_output.stderr)
369 );
370 }
371
372 let sysroot = PathBuf::from(String::from_utf8(rustc_output.stdout)?.trim());
373 if sysroot.join("lib/rustlib").join(RUST_TARGET).exists() {
374 return Ok(());
375 }
376
377 let output = util::command::new_std_command("rustup")
378 .args(["target", "add", RUST_TARGET])
379 .stderr(Stdio::piped())
380 .stdout(Stdio::inherit())
381 .output()
382 .context("failed to run `rustup target add`")?;
383 if !output.status.success() {
384 bail!(
385 "failed to install the `{RUST_TARGET}` target: {}",
386 String::from_utf8_lossy(&rustc_output.stderr)
387 );
388 }
389
390 Ok(())
391 }
392
393 async fn install_wasi_sdk_if_needed(&self) -> Result<PathBuf> {
394 let url = if let Some(asset_name) = WASI_SDK_ASSET_NAME {
395 format!("{WASI_SDK_URL}{asset_name}")
396 } else {
397 bail!("wasi-sdk is not available for platform {}", env::consts::OS);
398 };
399
400 let wasi_sdk_dir = self.cache_dir.join("wasi-sdk");
401 let mut clang_path = wasi_sdk_dir.clone();
402 clang_path.extend(["bin", &format!("clang{}", env::consts::EXE_SUFFIX)]);
403
404 if fs::metadata(&clang_path).is_ok_and(|metadata| metadata.is_file()) {
405 return Ok(clang_path);
406 }
407
408 let mut tar_out_dir = wasi_sdk_dir.clone();
409 tar_out_dir.set_extension("archive");
410
411 fs::remove_dir_all(&wasi_sdk_dir).ok();
412 fs::remove_dir_all(&tar_out_dir).ok();
413
414 log::info!("downloading wasi-sdk to {}", wasi_sdk_dir.display());
415 let mut response = self.http.get(&url, AsyncBody::default(), true).await?;
416 let body = BufReader::new(response.body_mut());
417 let body = GzipDecoder::new(body);
418 let tar = Archive::new(body);
419
420 tar.unpack(&tar_out_dir)
421 .await
422 .context("failed to unpack wasi-sdk archive")?;
423
424 let inner_dir = fs::read_dir(&tar_out_dir)?
425 .next()
426 .context("no content")?
427 .context("failed to read contents of extracted wasi archive directory")?
428 .path();
429 fs::rename(&inner_dir, &wasi_sdk_dir).context("failed to move extracted wasi dir")?;
430 fs::remove_dir_all(&tar_out_dir).ok();
431
432 Ok(clang_path)
433 }
434
435 // This was adapted from:
436 // https://github.com/bytecodealliance/wasm-tools/blob/e8809bb17fcf69aa8c85cd5e6db7cff5cf36b1de/src/bin/wasm-tools/strip.rs
437 fn strip_custom_sections(&self, input: &Vec<u8>) -> Result<Vec<u8>> {
438 use wasmparser::Payload::*;
439
440 let strip_custom_section = |name: &str| {
441 // Default strip everything but:
442 // * the `name` section
443 // * any `component-type` sections
444 // * the `dylink.0` section
445 // * our custom version section
446 name != "name"
447 && !name.starts_with("component-type:")
448 && name != "dylink.0"
449 && name != "zed:api-version"
450 };
451
452 let mut output = Vec::new();
453 let mut stack = Vec::new();
454
455 for payload in Parser::new(0).parse_all(input) {
456 let payload = payload?;
457
458 // Track nesting depth, so that we don't mess with inner producer sections:
459 match payload {
460 Version { encoding, .. } => {
461 output.extend_from_slice(match encoding {
462 wasmparser::Encoding::Component => &wasm_encoder::Component::HEADER,
463 wasmparser::Encoding::Module => &wasm_encoder::Module::HEADER,
464 });
465 }
466 ModuleSection { .. } | ComponentSection { .. } => {
467 stack.push(mem::take(&mut output));
468 continue;
469 }
470 End { .. } => {
471 let mut parent = match stack.pop() {
472 Some(c) => c,
473 None => break,
474 };
475 if output.starts_with(&wasm_encoder::Component::HEADER) {
476 parent.push(ComponentSectionId::Component as u8);
477 output.encode(&mut parent);
478 } else {
479 parent.push(ComponentSectionId::CoreModule as u8);
480 output.encode(&mut parent);
481 }
482 output = parent;
483 }
484 _ => {}
485 }
486
487 if let CustomSection(c) = &payload
488 && strip_custom_section(c.name())
489 {
490 continue;
491 }
492 if let Some((id, range)) = payload.as_section() {
493 RawSection {
494 id,
495 data: &input[range],
496 }
497 .append_to(&mut output);
498 }
499 }
500
501 Ok(output)
502 }
503}
504
505fn populate_defaults(manifest: &mut ExtensionManifest, extension_path: &Path) -> Result<()> {
506 // For legacy extensions on the v0 schema (aka, using `extension.json`), clear out any existing
507 // contents of the computed fields, since we don't care what the existing values are.
508 if manifest.schema_version.is_v0() {
509 manifest.languages.clear();
510 manifest.grammars.clear();
511 manifest.themes.clear();
512 }
513
514 let cargo_toml_path = extension_path.join("Cargo.toml");
515 if cargo_toml_path.exists() {
516 manifest.lib.kind = Some(ExtensionLibraryKind::Rust);
517 }
518
519 let languages_dir = extension_path.join("languages");
520 if languages_dir.exists() {
521 for entry in fs::read_dir(&languages_dir).context("failed to list languages dir")? {
522 let entry = entry?;
523 let language_dir = entry.path();
524 let config_path = language_dir.join("config.toml");
525 if config_path.exists() {
526 let relative_language_dir =
527 language_dir.strip_prefix(extension_path)?.to_path_buf();
528 if !manifest.languages.contains(&relative_language_dir) {
529 manifest.languages.push(relative_language_dir);
530 }
531 }
532 }
533 }
534
535 let themes_dir = extension_path.join("themes");
536 if themes_dir.exists() {
537 for entry in fs::read_dir(&themes_dir).context("failed to list themes dir")? {
538 let entry = entry?;
539 let theme_path = entry.path();
540 if theme_path.extension() == Some("json".as_ref()) {
541 let relative_theme_path = theme_path.strip_prefix(extension_path)?.to_path_buf();
542 if !manifest.themes.contains(&relative_theme_path) {
543 manifest.themes.push(relative_theme_path);
544 }
545 }
546 }
547 }
548
549 let icon_themes_dir = extension_path.join("icon_themes");
550 if icon_themes_dir.exists() {
551 for entry in fs::read_dir(&icon_themes_dir).context("failed to list icon themes dir")? {
552 let entry = entry?;
553 let icon_theme_path = entry.path();
554 if icon_theme_path.extension() == Some("json".as_ref()) {
555 let relative_icon_theme_path =
556 icon_theme_path.strip_prefix(extension_path)?.to_path_buf();
557 if !manifest.icon_themes.contains(&relative_icon_theme_path) {
558 manifest.icon_themes.push(relative_icon_theme_path);
559 }
560 }
561 }
562 }
563
564 let snippets_json_path = extension_path.join("snippets.json");
565 if snippets_json_path.exists() {
566 manifest.snippets = Some(snippets_json_path);
567 }
568
569 // For legacy extensions on the v0 schema (aka, using `extension.json`), we want to populate the grammars in
570 // the manifest using the contents of the `grammars` directory.
571 if manifest.schema_version.is_v0() {
572 let grammars_dir = extension_path.join("grammars");
573 if grammars_dir.exists() {
574 for entry in fs::read_dir(&grammars_dir).context("failed to list grammars dir")? {
575 let entry = entry?;
576 let grammar_path = entry.path();
577 if grammar_path.extension() == Some("toml".as_ref()) {
578 #[derive(Deserialize)]
579 struct GrammarConfigToml {
580 pub repository: String,
581 pub commit: String,
582 #[serde(default)]
583 pub path: Option<String>,
584 }
585
586 let grammar_config = fs::read_to_string(&grammar_path)?;
587 let grammar_config: GrammarConfigToml = toml::from_str(&grammar_config)?;
588
589 let grammar_name = grammar_path
590 .file_stem()
591 .and_then(|stem| stem.to_str())
592 .context("no grammar name")?;
593 if !manifest.grammars.contains_key(grammar_name) {
594 manifest.grammars.insert(
595 grammar_name.into(),
596 GrammarManifestEntry {
597 repository: grammar_config.repository,
598 rev: grammar_config.commit,
599 path: grammar_config.path,
600 },
601 );
602 }
603 }
604 }
605 }
606 }
607
608 Ok(())
609}