Extract PHP support into an extension (#9966)

This PR extracts PHP support into an extension and removes the built-in
PHP support from Zed.

There's a small workaround necessary in order for us to provide the
`language_ids` on the `LspAdapter` that are needed for the language
server to run properly. Eventually we'll want to build this into the
extension API, but for now we're just hard-coding it on the host side.

Release Notes:

- Removed built-in support for PHP, in favor of making it available as
an extension. The PHP extension will be suggested for download when you
open a `.php` file.
This commit is contained in:
Marshall Bowers 2024-03-29 14:51:54 -04:00 committed by GitHub
parent 764e256755
commit e252f90e30
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
17 changed files with 143 additions and 157 deletions

18
Cargo.lock generated
View file

@ -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"

View file

@ -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" }

View file

@ -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>,

View file

@ -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"),

View file

@ -61,7 +61,6 @@ tree-sitter-markdown.workspace = true
tree-sitter-nix.workspace = true
tree-sitter-nu.workspace = true
tree-sitter-ocaml.workspace = true
tree-sitter-php.workspace = true
tree-sitter-proto.workspace = true
tree-sitter-python.workspace = true
tree-sitter-racket.workspace = true

View file

@ -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())),

View file

@ -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()
}

16
extensions/php/Cargo.toml Normal file
View file

@ -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"

View file

@ -0,0 +1 @@
../../LICENSE-APACHE

View file

@ -0,0 +1,16 @@
id = "php"
name = "PHP"
description = "PHP support."
version = "0.0.1"
schema_version = 1
authors = ["Piotr Osiewicz <piotr@zed.dev>"]
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"

85
extensions/php/src/php.rs Normal file
View file

@ -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);