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