Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Extract PHP support into an extension (#9966)
Marshall Bowerse252f90e30f2
diff --git a/Cargo.lock b/Cargo.lockindex e1b2f8711b0..865965ea7c8 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -5458,7 +5458,6 @@ dependencies = ["tree-sitter-nix","tree-sitter-nu","tree-sitter-ocaml",- "tree-sitter-php","tree-sitter-proto","tree-sitter-python","tree-sitter-racket",@@ -10587,16 +10586,6 @@ dependencies = ["tree-sitter",]-[[package]]-name = "tree-sitter-php"-version = "0.21.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0db3788e709a5adfb583683a4b686a084e41a0f9e5a2fcb9a8e358f11481036a"-dependencies = [- "cc",- "tree-sitter",-]-[[package]]name = "tree-sitter-proto"version = "0.0.2"@@ -12708,6 +12697,13 @@ dependencies = ["zed_extension_api 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)",]+[[package]]+name = "zed_php"+version = "0.0.1"+dependencies = [+ "zed_extension_api 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)",+]+[[package]]name = "zed_prisma"version = "0.0.1"diff --git a/Cargo.toml b/Cargo.tomlindex b3c4d205148..db4ea2e7b04 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -100,6 +100,7 @@ members = ["extensions/astro","extensions/gleam","extensions/haskell",+ "extensions/php","extensions/prisma","extensions/purescript","extensions/svelte",@@ -319,7 +320,6 @@ tree-sitter-markdown = { git = "https://github.com/MDeiml/tree-sitter-markdown",tree-sitter-nix = { git = "https://github.com/nix-community/tree-sitter-nix", rev = "66e3e9ce9180ae08fc57372061006ef83f0abde7" }tree-sitter-nu = { git = "https://github.com/nushell/tree-sitter-nu", rev = "7dd29f9616822e5fc259f5b4ae6c4ded9a71a132" }tree-sitter-ocaml = { git = "https://github.com/tree-sitter/tree-sitter-ocaml", rev = "4abfdc1c7af2c6c77a370aee974627be1c285b3b" }-tree-sitter-php = "0.21.1"tree-sitter-proto = { git = "https://github.com/rewinfrey/tree-sitter-proto", rev = "36d54f288aee112f13a67b550ad32634d0c2cb52" }tree-sitter-python = "0.20.2"tree-sitter-racket = { git = "https://github.com/zed-industries/tree-sitter-racket", rev = "eb010cf2c674c6fd9a6316a84e28ef90190fe51a" }diff --git a/crates/extension/src/extension_lsp_adapter.rs b/crates/extension/src/extension_lsp_adapter.rsindex 19a6b75ec9d..86c3a26154b 100644--- a/crates/extension/src/extension_lsp_adapter.rs+++ b/crates/extension/src/extension_lsp_adapter.rs@@ -1,6 +1,7 @@use crate::wasm_host::{wit::LanguageServerConfig, WasmExtension, WasmHost};use anyhow::{anyhow, Context, Result};use async_trait::async_trait;+use collections::HashMap;use futures::{Future, FutureExt};use gpui::AsyncAppContext;use language::{Language, LanguageServerName, LspAdapter, LspAdapterDelegate};@@ -106,6 +107,17 @@ impl LspAdapter for ExtensionLspAdapter {None}+ fn language_ids(&self) -> HashMap<String, String> {+ // TODO: Eventually we'll want to expose an extension API for doing this, but for+ // now we just manually language ID mappings for extensions that we know need it.++ if self.extension.manifest.id.as_ref() == "php" {+ return HashMap::from_iter([("PHP".into(), "php".into())]);+ }++ Default::default()+ }+async fn initialization_options(self: Arc<Self>,delegate: &Arc<dyn LspAdapterDelegate>,diff --git a/crates/extensions_ui/src/extension_suggest.rs b/crates/extensions_ui/src/extension_suggest.rsindex e761f7336c1..704c0584c8f 100644--- a/crates/extensions_ui/src/extension_suggest.rs+++ b/crates/extensions_ui/src/extension_suggest.rs@@ -36,6 +36,7 @@ fn suggested_extensions() -> &'static HashMap<&'static str, Arc<str>> {("latex", "tex"),("make", "Makefile"),("nix", "nix"),+ ("php", "php"),("prisma", "prisma"),("purescript", "purs"),("r", "r"),diff --git a/crates/languages/Cargo.toml b/crates/languages/Cargo.tomlindex 78afaf65590..be06d2266f0 100644--- a/crates/languages/Cargo.toml+++ b/crates/languages/Cargo.toml@@ -61,7 +61,6 @@ tree-sitter-markdown.workspace = truetree-sitter-nix.workspace = truetree-sitter-nu.workspace = truetree-sitter-ocaml.workspace = true-tree-sitter-php.workspace = truetree-sitter-proto.workspace = truetree-sitter-python.workspace = truetree-sitter-racket.workspace = truediff --git a/crates/languages/src/lib.rs b/crates/languages/src/lib.rsindex ce80bfa9de6..90e3f181b82 100644--- a/crates/languages/src/lib.rs+++ b/crates/languages/src/lib.rs@@ -26,7 +26,6 @@ mod json;mod lua;mod nu;mod ocaml;-mod php;mod python;mod ruby;mod rust;@@ -90,7 +89,6 @@ pub fn init("ocaml_interface",tree_sitter_ocaml::language_ocaml_interface(),),- ("php", tree_sitter_php::language_php()),("proto", tree_sitter_proto::language()),("python", tree_sitter_python::language()),("racket", tree_sitter_racket::language()),@@ -309,13 +307,6 @@ pub fn init("yaml",vec![Arc::new(yaml::YamlLspAdapter::new(node_runtime.clone()))]);- language!(- "php",- vec![- Arc::new(php::IntelephenseLspAdapter::new(node_runtime.clone())),- Arc::new(tailwind::TailwindLspAdapter::new(node_runtime.clone())),- ]- );language!("elm",vec![Arc::new(elm::ElmLspAdapter::new(node_runtime.clone()))]@@ -342,6 +333,10 @@ pub fn init("Astro".into(),Arc::new(tailwind::TailwindLspAdapter::new(node_runtime.clone())),);+ languages.register_secondary_lsp_adapter(+ "PHP".into(),+ Arc::new(tailwind::TailwindLspAdapter::new(node_runtime.clone())),+ );languages.register_secondary_lsp_adapter("Svelte".into(),Arc::new(tailwind::TailwindLspAdapter::new(node_runtime.clone())),diff --git a/crates/languages/src/php.rs b/crates/languages/src/php.rsdeleted file mode 100644index aaf5ff3d425..00000000000--- a/crates/languages/src/php.rs+++ /dev/null@@ -1,135 +0,0 @@-use anyhow::{anyhow, Result};--use async_trait::async_trait;-use collections::HashMap;--use language::{LanguageServerName, LspAdapter, LspAdapterDelegate};-use lsp::LanguageServerBinary;-use node_runtime::NodeRuntime;--use smol::{fs, stream::StreamExt};-use std::{- any::Any,- ffi::OsString,- path::{Path, PathBuf},- sync::Arc,-};-use util::{maybe, ResultExt};--fn intelephense_server_binary_arguments(server_path: &Path) -> Vec<OsString> {- vec![server_path.into(), "--stdio".into()]-}--pub struct IntelephenseVersion(String);--pub struct IntelephenseLspAdapter {- node: Arc<dyn NodeRuntime>,-}--impl IntelephenseLspAdapter {- const SERVER_PATH: &'static str = "node_modules/intelephense/lib/intelephense.js";-- pub fn new(node: Arc<dyn NodeRuntime>) -> Self {- Self { node }- }-}--#[async_trait(?Send)]-impl LspAdapter for IntelephenseLspAdapter {- fn name(&self) -> LanguageServerName {- LanguageServerName("intelephense".into())- }-- async fn fetch_latest_server_version(- &self,- _delegate: &dyn LspAdapterDelegate,- ) -> Result<Box<dyn 'static + Send + Any>> {- Ok(Box::new(IntelephenseVersion(- self.node.npm_package_latest_version("intelephense").await?,- )) as Box<_>)- }-- async fn fetch_server_binary(- &self,- latest_version: Box<dyn 'static + Send + Any>,- container_dir: PathBuf,- _delegate: &dyn LspAdapterDelegate,- ) -> Result<LanguageServerBinary> {- let latest_version = latest_version.downcast::<IntelephenseVersion>().unwrap();- let server_path = container_dir.join(Self::SERVER_PATH);- let package_name = "intelephense";-- let should_install_language_server = self- .node- .should_install_npm_package(- package_name,- &server_path,- &container_dir,- latest_version.0.as_str(),- )- .await;-- if should_install_language_server {- self.node- .npm_install_packages(&container_dir, &[(package_name, latest_version.0.as_str())])- .await?;- }-- Ok(LanguageServerBinary {- path: self.node.binary_path().await?,- env: None,- arguments: intelephense_server_binary_arguments(&server_path),- })- }-- async fn cached_server_binary(- &self,- container_dir: PathBuf,- _: &dyn LspAdapterDelegate,- ) -> Option<LanguageServerBinary> {- get_cached_server_binary(container_dir, &*self.node).await- }-- async fn installation_test_binary(- &self,- container_dir: PathBuf,- ) -> Option<LanguageServerBinary> {- get_cached_server_binary(container_dir, &*self.node).await- }-- fn language_ids(&self) -> HashMap<String, String> {- HashMap::from_iter([("PHP".into(), "php".into())])- }-}--async fn get_cached_server_binary(- container_dir: PathBuf,- node: &dyn NodeRuntime,-) -> Option<LanguageServerBinary> {- maybe!(async {- let mut last_version_dir = 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_dir() {- last_version_dir = Some(entry.path());- }- }- let last_version_dir = last_version_dir.ok_or_else(|| anyhow!("no cached binary"))?;- let server_path = last_version_dir.join(IntelephenseLspAdapter::SERVER_PATH);- if server_path.exists() {- Ok(LanguageServerBinary {- path: node.binary_path().await?,- env: None,- arguments: intelephense_server_binary_arguments(&server_path),- })- } else {- Err(anyhow!(- "missing executable in directory {:?}",- last_version_dir- ))- }- })- .await- .log_err()-}diff --git a/extensions/php/Cargo.toml b/extensions/php/Cargo.tomlnew file mode 100644index 00000000000..5cfb4e43f3c--- /dev/null+++ b/extensions/php/Cargo.toml@@ -0,0 +1,16 @@+[package]+name = "zed_php"+version = "0.0.1"+edition = "2021"+publish = false+license = "Apache-2.0"++[lints]+workspace = true++[lib]+path = "src/php.rs"+crate-type = ["cdylib"]++[dependencies]+zed_extension_api = "0.0.4"diff --git a/extensions/php/LICENSE-APACHE b/extensions/php/LICENSE-APACHEnew file mode 120000index 00000000000..1cd601d0a3a--- /dev/null+++ b/extensions/php/LICENSE-APACHE@@ -0,0 +1 @@+../../LICENSE-APACHE\ No newline at end of filediff --git a/extensions/php/extension.toml b/extensions/php/extension.tomlnew file mode 100644index 00000000000..a2c6ed3d63e--- /dev/null+++ b/extensions/php/extension.toml@@ -0,0 +1,16 @@+id = "php"+name = "PHP"+description = "PHP support."+version = "0.0.1"+schema_version = 1+authors = ["Piotr Osiewicz <[email protected]>"]+repository = "https://github.com/zed-industries/zed"++[language_servers.intelephense]+name = "Intelephense"+language = "PHP"++[grammars.php]+repository = "https://github.com/tree-sitter/tree-sitter-php"+commit = "8ab93274065cbaf529ea15c24360cfa3348ec9e4"+path = "php"diff --git a/crates/languages/src/php/config.toml b/extensions/php/languages/php/config.tomlsimilarity index 100%rename from crates/languages/src/php/config.tomlrename to extensions/php/languages/php/config.tomldiff --git a/crates/languages/src/php/embedding.scm b/extensions/php/languages/php/embedding.scmsimilarity index 100%rename from crates/languages/src/php/embedding.scmrename to extensions/php/languages/php/embedding.scmdiff --git a/crates/languages/src/php/highlights.scm b/extensions/php/languages/php/highlights.scmsimilarity index 100%rename from crates/languages/src/php/highlights.scmrename to extensions/php/languages/php/highlights.scmdiff --git a/crates/languages/src/php/injections.scm b/extensions/php/languages/php/injections.scmsimilarity index 100%rename from crates/languages/src/php/injections.scmrename to extensions/php/languages/php/injections.scmdiff --git a/crates/languages/src/php/outline.scm b/extensions/php/languages/php/outline.scmsimilarity index 100%rename from crates/languages/src/php/outline.scmrename to extensions/php/languages/php/outline.scmdiff --git a/crates/languages/src/php/tags.scm b/extensions/php/languages/php/tags.scmsimilarity index 100%rename from crates/languages/src/php/tags.scmrename to extensions/php/languages/php/tags.scmdiff --git a/extensions/php/src/php.rs b/extensions/php/src/php.rsnew file mode 100644index 00000000000..a0f700e452d--- /dev/null+++ b/extensions/php/src/php.rs@@ -0,0 +1,85 @@+use std::{env, fs};+use zed_extension_api::{self as zed, Result};++const SERVER_PATH: &str = "node_modules/intelephense/lib/intelephense.js";+const PACKAGE_NAME: &str = "intelephense";++struct PhpExtension {+ did_find_server: bool,+}++impl PhpExtension {+ fn server_exists(&self) -> bool {+ fs::metadata(SERVER_PATH).map_or(false, |stat| stat.is_file())+ }++ fn server_script_path(&mut self, config: zed::LanguageServerConfig) -> Result<String> {+ let server_exists = self.server_exists();+ if self.did_find_server && server_exists {+ return Ok(SERVER_PATH.to_string());+ }++ zed::set_language_server_installation_status(+ &config.name,+ &zed::LanguageServerInstallationStatus::CheckingForUpdate,+ );+ let version = zed::npm_package_latest_version(PACKAGE_NAME)?;++ if !server_exists+ || zed::npm_package_installed_version(PACKAGE_NAME)?.as_ref() != Some(&version)+ {+ zed::set_language_server_installation_status(+ &config.name,+ &zed::LanguageServerInstallationStatus::Downloading,+ );+ let result = zed::npm_install_package(PACKAGE_NAME, &version);+ match result {+ Ok(()) => {+ if !self.server_exists() {+ Err(format!(+ "installed package '{PACKAGE_NAME}' did not contain expected path '{SERVER_PATH}'",+ ))?;+ }+ }+ Err(error) => {+ if !self.server_exists() {+ Err(error)?;+ }+ }+ }+ }++ self.did_find_server = true;+ Ok(SERVER_PATH.to_string())+ }+}++impl zed::Extension for PhpExtension {+ fn new() -> Self {+ Self {+ did_find_server: false,+ }+ }++ fn language_server_command(+ &mut self,+ config: zed::LanguageServerConfig,+ _worktree: &zed::Worktree,+ ) -> Result<zed::Command> {+ let server_path = self.server_script_path(config)?;+ Ok(zed::Command {+ command: zed::node_binary_path()?,+ args: vec![+ env::current_dir()+ .unwrap()+ .join(&server_path)+ .to_string_lossy()+ .to_string(),+ "--stdio".to_string(),+ ],+ env: Default::default(),+ })+ }+}++zed::register_extension!(PhpExtension);