Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Extract Zig support into an extension (#9893)
Marshall Bowersff685b299db3
diff --git a/Cargo.lock b/Cargo.lockindex cf7dae676e5..c063b01fbc3 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -5330,7 +5330,6 @@ dependencies = ["tree-sitter-typescript","tree-sitter-vue","tree-sitter-yaml",- "tree-sitter-zig","unindent","util","workspace",@@ -10508,15 +10507,6 @@ dependencies = ["tree-sitter",]-[[package]]-name = "tree-sitter-zig"-version = "0.0.1"-source = "git+https://github.com/maxxnino/tree-sitter-zig?rev=0d08703e4c3f426ec61695d7617415fff97029bd#0d08703e4c3f426ec61695d7617415fff97029bd"-dependencies = [- "cc",- "tree-sitter",-]-[[package]]name = "try-lock"version = "0.2.4"@@ -12635,6 +12625,13 @@ dependencies = ["zed_extension_api 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)",]+[[package]]+name = "zed_zig"+version = "0.0.1"+dependencies = [+ "zed_extension_api 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)",+]+[[package]]name = "zeno"version = "0.2.3"diff --git a/Cargo.toml b/Cargo.tomlindex c9000f03431..b258d88697a 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -103,6 +103,7 @@ members = ["extensions/purescript","extensions/svelte","extensions/uiua",+ "extensions/zig","tooling/xtask",]@@ -325,7 +326,6 @@ tree-sitter-toml = { git = "https://github.com/tree-sitter/tree-sitter-toml", retree-sitter-typescript = { git = "https://github.com/tree-sitter/tree-sitter-typescript", rev = "5d20856f34315b068c41edaee2ac8a100081d259" }tree-sitter-vue = { git = "https://github.com/zed-industries/tree-sitter-vue", rev = "6608d9d60c386f19d80af7d8132322fa11199c42" }tree-sitter-yaml = { git = "https://github.com/zed-industries/tree-sitter-yaml", rev = "f545a41f57502e1b5ddf2a6668896c1b0620f930" }-tree-sitter-zig = { git = "https://github.com/maxxnino/tree-sitter-zig", rev = "0d08703e4c3f426ec61695d7617415fff97029bd" }unindent = "0.1.7"unicase = "2.6"url = "2.2"diff --git a/crates/extension/src/extension_lsp_adapter.rs b/crates/extension/src/extension_lsp_adapter.rsindex b045a733d1b..4e7a9490445 100644--- a/crates/extension/src/extension_lsp_adapter.rs+++ b/crates/extension/src/extension_lsp_adapter.rs@@ -56,6 +56,19 @@ impl LspAdapter for ExtensionLspAdapter {.host.path_from_extension(&self.extension.manifest.id, command.command.as_ref());+ // TODO: Eventually we'll want to expose an extension API for doing this, but for+ // now we just manually set the file permissions for extensions that we know need it.+ if self.extension.manifest.id.as_ref() == "zig" {+ #[cfg(not(windows))]+ {+ use std::fs::{self, Permissions};+ use std::os::unix::fs::PermissionsExt;++ fs::set_permissions(&path, Permissions::from_mode(0o755))+ .context("failed to set file permissions")?;+ }+ }+Ok(LanguageServerBinary {path,arguments: command.args.into_iter().map(|arg| arg.into()).collect(),diff --git a/crates/extensions_ui/src/extension_suggest.rs b/crates/extensions_ui/src/extension_suggest.rsindex 0283b621eff..326315dc691 100644--- a/crates/extensions_ui/src/extension_suggest.rs+++ b/crates/extensions_ui/src/extension_suggest.rs@@ -48,6 +48,7 @@ pub fn suggested_extension(file_extension_or_name: &str) -> Option<Arc<str>> {("swift", "swift"),("templ", "templ"),("wgsl", "wgsl"),+ ("zig", "zig"),].into_iter().map(|(name, file)| (file, name.into()))diff --git a/crates/languages/Cargo.toml b/crates/languages/Cargo.tomlindex ad23c912ec4..f9f36f46216 100644--- a/crates/languages/Cargo.toml+++ b/crates/languages/Cargo.toml@@ -73,7 +73,6 @@ tree-sitter-toml.workspace = truetree-sitter-typescript.workspace = truetree-sitter-vue.workspace = truetree-sitter-yaml.workspace = true-tree-sitter-zig.workspace = truetree-sitter.workspace = trueutil.workspace = truediff --git a/crates/languages/src/lib.rs b/crates/languages/src/lib.rsindex b8192e76f3f..23471528af8 100644--- a/crates/languages/src/lib.rs+++ b/crates/languages/src/lib.rs@@ -36,7 +36,6 @@ mod toml;mod typescript;mod vue;mod yaml;-mod zig;// 1. Add tree-sitter-{language} parser to zed crate// 2. Create a language directory in zed/crates/zed/src/languages and add the language to init function below@@ -105,7 +104,6 @@ pub fn init(("typescript", tree_sitter_typescript::language_typescript()),("vue", tree_sitter_vue::language()),("yaml", tree_sitter_yaml::language()),- ("zig", tree_sitter_zig::language()),("dart", tree_sitter_dart::language()),]);@@ -212,7 +210,6 @@ pub fn init(language!("go", vec![Arc::new(go::GoLspAdapter)]);language!("gomod");language!("gowork");- language!("zig", vec![Arc::new(zig::ZlsAdapter)]);language!("heex",vec![diff --git a/crates/languages/src/zig.rs b/crates/languages/src/zig.rsdeleted file mode 100644index 488c56513a2..00000000000--- a/crates/languages/src/zig.rs+++ /dev/null@@ -1,143 +0,0 @@-use anyhow::{anyhow, Context, Result};-use async_compression::futures::bufread::GzipDecoder;-use async_tar::Archive;-use async_trait::async_trait;-use futures::{io::BufReader, StreamExt};-use gpui::AsyncAppContext;-use language::{LanguageServerName, LspAdapter, LspAdapterDelegate};-use lsp::LanguageServerBinary;-use smol::fs;-use std::env::consts::{ARCH, OS};-use std::{any::Any, path::PathBuf};-use util::github::latest_github_release;-use util::maybe;-use util::{github::GitHubLspBinaryVersion, ResultExt};--pub struct ZlsAdapter;--#[async_trait(?Send)]-impl LspAdapter for ZlsAdapter {- fn name(&self) -> LanguageServerName {- LanguageServerName("zls".into())- }-- async fn fetch_latest_server_version(- &self,- delegate: &dyn LspAdapterDelegate,- ) -> Result<Box<dyn 'static + Send + Any>> {- let release =- latest_github_release("zigtools/zls", true, false, delegate.http_client()).await?;- let asset_name = format!("zls-{ARCH}-{OS}.tar.gz");- let asset = release- .assets- .iter()- .find(|asset| asset.name == asset_name)- .ok_or_else(|| anyhow!("no asset found matching {:?}", asset_name))?;- let version = GitHubLspBinaryVersion {- name: release.tag_name,- url: asset.browser_download_url.clone(),- };-- Ok(Box::new(version) as Box<_>)- }-- async fn check_if_user_installed(- &self,- delegate: &dyn LspAdapterDelegate,- _cx: &AsyncAppContext,- ) -> Option<LanguageServerBinary> {- let env = delegate.shell_env().await;- let path = delegate.which("zls".as_ref()).await?;- Some(LanguageServerBinary {- path,- arguments: vec![],- env: Some(env),- })- }-- async fn fetch_server_binary(- &self,- version: Box<dyn 'static + Send + Any>,- container_dir: PathBuf,- delegate: &dyn LspAdapterDelegate,- ) -> Result<LanguageServerBinary> {- let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();- let binary_path = container_dir.join("bin/zls");-- if fs::metadata(&binary_path).await.is_err() {- let mut response = delegate- .http_client()- .get(&version.url, Default::default(), true)- .await- .context("error downloading release")?;- let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));- let archive = Archive::new(decompressed_bytes);- archive.unpack(container_dir).await?;- }-- // todo("windows")- #[cfg(not(windows))]- {- fs::set_permissions(- &binary_path,- <fs::Permissions as fs::unix::PermissionsExt>::from_mode(0o755),- )- .await?;- }- Ok(LanguageServerBinary {- path: binary_path,- env: None,- arguments: vec![],- })- }-- async fn cached_server_binary(- &self,- container_dir: PathBuf,- _: &dyn LspAdapterDelegate,- ) -> Option<LanguageServerBinary> {- get_cached_server_binary(container_dir).await- }-- async fn installation_test_binary(- &self,- container_dir: PathBuf,- ) -> Option<LanguageServerBinary> {- get_cached_server_binary(container_dir)- .await- .map(|mut binary| {- binary.arguments = vec!["--help".into()];- binary- })- }-}--async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {- maybe!(async {- let mut last_binary_path = None;- let mut entries = fs::read_dir(&container_dir).await?;- while let Some(entry) = entries.next().await {- let entry = entry?;- if entry.file_type().await?.is_file()- && entry- .file_name()- .to_str()- .map_or(false, |name| name == "zls")- {- last_binary_path = Some(entry.path());- }- }-- if let Some(path) = last_binary_path {- Ok(LanguageServerBinary {- path,- env: None,- arguments: Vec::new(),- })- } else {- Err(anyhow!("no cached binary"))- }- })- .await- .log_err()-}diff --git a/extensions/zig/Cargo.toml b/extensions/zig/Cargo.tomlnew file mode 100644index 00000000000..852e776ef93--- /dev/null+++ b/extensions/zig/Cargo.toml@@ -0,0 +1,16 @@+[package]+name = "zed_zig"+version = "0.0.1"+edition = "2021"+publish = false+license = "Apache-2.0"++[lints]+workspace = true++[lib]+path = "src/zig.rs"+crate-type = ["cdylib"]++[dependencies]+zed_extension_api = "0.0.4"diff --git a/extensions/zig/LICENSE-APACHE b/extensions/zig/LICENSE-APACHEnew file mode 120000index 00000000000..1cd601d0a3a--- /dev/null+++ b/extensions/zig/LICENSE-APACHE@@ -0,0 +1 @@+../../LICENSE-APACHE\ No newline at end of filediff --git a/extensions/zig/extension.toml b/extensions/zig/extension.tomlnew file mode 100644index 00000000000..b813358d51a--- /dev/null+++ b/extensions/zig/extension.toml@@ -0,0 +1,15 @@+id = "zig"+name = "Zig"+description = "Zig support."+version = "0.0.1"+schema_version = 1+authors = ["Allan Calix <[email protected]>"]+repository = "https://github.com/zed-industries/zed"++[language_servers.zls]+name = "zls"+language = "Zig"++[grammars.zig]+repository = "https://github.com/maxxnino/tree-sitter-zig"+commit = "0d08703e4c3f426ec61695d7617415fff97029bd"diff --git a/crates/languages/src/zig/brackets.scm b/extensions/zig/languages/zig/brackets.scmsimilarity index 100%rename from crates/languages/src/zig/brackets.scmrename to extensions/zig/languages/zig/brackets.scmdiff --git a/crates/languages/src/zig/config.toml b/extensions/zig/languages/zig/config.tomlsimilarity index 100%rename from crates/languages/src/zig/config.tomlrename to extensions/zig/languages/zig/config.tomldiff --git a/crates/languages/src/zig/folds.scm b/extensions/zig/languages/zig/folds.scmsimilarity index 100%rename from crates/languages/src/zig/folds.scmrename to extensions/zig/languages/zig/folds.scmdiff --git a/crates/languages/src/zig/highlights.scm b/extensions/zig/languages/zig/highlights.scmsimilarity index 100%rename from crates/languages/src/zig/highlights.scmrename to extensions/zig/languages/zig/highlights.scmdiff --git a/crates/languages/src/zig/indents.scm b/extensions/zig/languages/zig/indents.scmsimilarity index 100%rename from crates/languages/src/zig/indents.scmrename to extensions/zig/languages/zig/indents.scmdiff --git a/crates/languages/src/zig/injections.scm b/extensions/zig/languages/zig/injections.scmsimilarity index 100%rename from crates/languages/src/zig/injections.scmrename to extensions/zig/languages/zig/injections.scmdiff --git a/crates/languages/src/zig/outline.scm b/extensions/zig/languages/zig/outline.scmsimilarity index 100%rename from crates/languages/src/zig/outline.scmrename to extensions/zig/languages/zig/outline.scmdiff --git a/extensions/zig/src/zig.rs b/extensions/zig/src/zig.rsnew file mode 100644index 00000000000..94568afad55--- /dev/null+++ b/extensions/zig/src/zig.rs@@ -0,0 +1,116 @@+use std::fs;+use zed_extension_api::{self as zed, Result};++struct ZigExtension {+ cached_binary_path: Option<String>,+}++impl ZigExtension {+ fn language_server_binary_path(+ &mut self,+ config: zed::LanguageServerConfig,+ worktree: &zed::Worktree,+ ) -> Result<String> {+ if let Some(path) = &self.cached_binary_path {+ if fs::metadata(path).map_or(false, |stat| stat.is_file()) {+ return Ok(path.clone());+ }+ }++ if let Some(path) = worktree.which("zls") {+ self.cached_binary_path = Some(path.clone());+ return Ok(path);+ }++ zed::set_language_server_installation_status(+ &config.name,+ &zed::LanguageServerInstallationStatus::CheckingForUpdate,+ );+ let release = zed::latest_github_release(+ "zigtools/zls",+ zed::GithubReleaseOptions {+ require_assets: true,+ pre_release: false,+ },+ )?;++ let (platform, arch) = zed::current_platform();+ let asset_name = format!(+ "zls-{arch}-{os}.{extension}",+ arch = match arch {+ zed::Architecture::Aarch64 => "aarch64",+ zed::Architecture::X86 => "x86",+ zed::Architecture::X8664 => "x86_64",+ },+ os = match platform {+ zed::Os::Mac => "macos",+ zed::Os::Linux => "linux",+ zed::Os::Windows => "windows",+ },+ extension = match platform {+ zed::Os::Mac | zed::Os::Linux => "tar.gz",+ zed::Os::Windows => "zip",+ }+ );++ let asset = release+ .assets+ .iter()+ .find(|asset| asset.name == asset_name)+ .ok_or_else(|| format!("no asset found matching {:?}", asset_name))?;++ let version_dir = format!("zls-{}", release.version);+ let binary_path = format!("{version_dir}/bin/zls");++ if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) {+ zed::set_language_server_installation_status(+ &config.name,+ &zed::LanguageServerInstallationStatus::Downloading,+ );++ zed::download_file(+ &asset.download_url,+ &version_dir,+ match platform {+ zed::Os::Mac | zed::Os::Linux => zed::DownloadedFileType::GzipTar,+ zed::Os::Windows => zed::DownloadedFileType::Zip,+ },+ )+ .map_err(|e| format!("failed to download file: {e}"))?;++ let entries =+ fs::read_dir(".").map_err(|e| format!("failed to list working directory {e}"))?;+ for entry in entries {+ let entry = entry.map_err(|e| format!("failed to load directory entry {e}"))?;+ if entry.file_name().to_str() != Some(&version_dir) {+ fs::remove_dir_all(&entry.path()).ok();+ }+ }+ }++ self.cached_binary_path = Some(binary_path.clone());+ Ok(binary_path)+ }+}++impl zed::Extension for ZigExtension {+ fn new() -> Self {+ Self {+ cached_binary_path: None,+ }+ }++ fn language_server_command(+ &mut self,+ config: zed::LanguageServerConfig,+ worktree: &zed::Worktree,+ ) -> Result<zed::Command> {+ Ok(zed::Command {+ command: self.language_server_binary_path(config, worktree)?,+ args: vec![],+ env: Default::default(),+ })+ }+}++zed::register_extension!(ZigExtension);