feat(lsp): send a server the documents it registers a selector for (#7558)

A language server marked dynamic-documents (Phoxite for PHP and Blade) is sent the other-language documents it registers a document selector for, such as a framework's YAML, XML or JSON files, alongside their own servers.

Malformed selectors match no documents, relative glob restrictions are kept, and withdrawing a selector closes the documents it opened.

Co-authored-by: samehelhawary <[email protected]>
Цей коміт міститься в:
Sameh Elhawaryтаsamehelhawary authored and GitHub committed 2026-12-03 00:39:11 +08:00
1 джерело 3078674a86
коміт 65686e246e
14 files changed
+401 -10

No files matched your search

+4
Переглянути файл
@@ -198,6 +198,10 @@ pub struct LanguageServerConfig {
/// this one serves the file.
#[serde(default)]
pub replaces: Vec<String>,
/// The server registers for the documents of other languages it reads (a framework's
/// configuration files), by document selector: it is sent those too, wherever it runs.
#[serde(default)]
pub dynamic_documents: bool,
/// The `languageId` this server is told for the language's documents, when it
/// knows them under another one (`php` for a PHP server on a Blade view).
#[serde(default)]
+1
Переглянути файл
@@ -66,6 +66,7 @@ fn server_config() -> LanguageServerConfig {
connect: None,
fallback: false,
replaces: Vec::new(),
dynamic_documents: false,
language_id: None,
joins: None,
files: Vec::new(),
+183
Переглянути файл
@@ -0,0 +1,183 @@
//! Documents a server asks for itself: its `client/registerCapability` requests that carry
//! a `documentSelector` (a PHP server on the YAML files of a Drupal project). They say
//! which documents of other languages the server is sent; its capabilities stay as it
//! announced them at startup, so taking a registration back takes nothing else away.
use crate::uri;
use globset::{GlobBuilder, GlobMatcher};
use serde_json::Value;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
const DID_OPEN: &str = "textDocument/didOpen";
struct Filter {
language: Option<String>,
pattern: Option<Pattern>,
}
/// A glob, matched against the whole path or, for a relative pattern, the path below its base.
struct Pattern {
base: Option<PathBuf>,
glob: GlobMatcher,
}
impl Pattern {
fn matches(&self, path: &Path) -> bool {
match &self.base {
Some(base) => path.strip_prefix(base).is_ok_and(|rel| self.glob.is_match(slashed(rel))),
None => self.glob.is_match(slashed(path)),
}
}
}
fn slashed(path: &Path) -> String {
path.to_string_lossy().replace('\\', "/")
}
/// Registrations by id, each with its method.
#[derive(Default)]
pub struct DocumentSelectors(BTreeMap<String, (String, Vec<Filter>)>);
impl DocumentSelectors {
/// Keeps the registration when it has a document selector; `false` when it has none
/// (it then applies to every document, as a capability does).
pub fn register(&mut self, id: &str, method: &str, options: Option<&Value>) -> bool {
let Some(selector) = options.and_then(|o| o.get("documentSelector")).filter(|value| !value.is_null()) else {
return false;
};
let filters = selector.as_array().into_iter().flatten().filter_map(parse).collect();
self.0.insert(id.to_owned(), (method.to_owned(), filters));
true
}
/// Whether `id` was one of these registrations.
pub fn unregister(&mut self, id: &str) -> bool {
self.0.remove(id).is_some()
}
/// Whether the server asked to be sent the `language` document at `path`.
pub fn opens(&self, language: &str, path: &Path) -> bool {
self.0.values().filter(|(method, _)| method == DID_OPEN).flat_map(|(_, filters)| filters).any(|filter| {
filter.language.as_deref().is_none_or(|l| l == language)
&& filter.pattern.as_ref().is_none_or(|p| p.matches(path))
})
}
}
/// A filter of a document selector. `None`, so that it takes no document, for one of another
/// scheme than `file`, for one that names nothing (it would take every document), and for
/// one with a part this cannot read (a notebook's cells, a value of another type): leaving
/// that part out would send the server documents it did not ask for.
fn parse(filter: &Value) -> Option<Filter> {
let filter = filter.as_object()?;
if filter.contains_key("notebook") {
return None;
}
// An absent part does not restrict; one of another type than the protocol's is not read.
let text = |key: &str| match filter.get(key) {
None | Some(Value::Null) => Some(None),
Some(Value::String(value)) => Some(Some(value.as_str())),
Some(_) => None,
};
if text("scheme")?.is_some_and(|scheme| scheme != "file") {
return None;
}
let language = text("language")?.map(str::to_owned);
let pattern = match filter.get("pattern") {
None | Some(Value::Null) => None,
Some(Value::String(glob)) => Some(Pattern { base: None, glob: matcher(glob)? }),
Some(relative) => {
// `{ baseUri, pattern }`, the base a `WorkspaceFolder` or a URI.
let base = relative.get("baseUri")?;
let base = uri::uri_to_path(base.get("uri").unwrap_or(base).as_str()?)?;
let base = dunce::canonicalize(&base).unwrap_or(base);
Some(Pattern { base: Some(base), glob: matcher(relative.get("pattern")?.as_str()?)? })
}
};
(language.is_some() || pattern.is_some()).then_some(Filter { language, pattern })
}
fn matcher(glob: &str) -> Option<GlobMatcher> {
Some(GlobBuilder::new(glob).literal_separator(true).build().ok()?.compile_matcher())
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn only_document_registrations_with_a_selector_are_kept() {
let mut selectors = DocumentSelectors::default();
assert!(!selectors.register("a", DID_OPEN, None));
assert!(!selectors.register("a", DID_OPEN, Some(&json!({ "documentSelector": null }))));
assert!(!selectors.unregister("a"));
// A malformed selector is still scoped, so it cannot become a global registration.
assert!(selectors.register("bad", DID_OPEN, Some(&json!({ "documentSelector": "yaml" }))));
assert!(!selectors.opens("yaml", Path::new("/site/file.yml")));
assert!(selectors.unregister("bad"));
let yaml = json!({ "documentSelector": [
{ "scheme": "file", "pattern": "**/*.yml" },
{ "scheme": "file", "language": "javascript" },
{ "scheme": "untitled", "language": "php" },
{ "scheme": "file" },
] });
assert!(selectors.register("open", DID_OPEN, Some(&yaml)));
assert!(selectors.register(
"hover",
"textDocument/hover",
Some(&json!({ "documentSelector": [{ "language": "xml" }] }))
));
let opens = |s: &DocumentSelectors, language: &str, path: &str| s.opens(language, Path::new(path));
assert!(opens(&selectors, "yaml", "/site/modules/blog/blog.services.yml"));
assert!(opens(&selectors, "yaml", r"C:\site\modules\blog\blog.routing.yml"));
assert!(opens(&selectors, "javascript", "/site/assets/app.js"));
// Another scheme, a filter that names nothing, and a method other than `didOpen`.
assert!(!opens(&selectors, "php", "/site/index.php"));
assert!(!opens(&selectors, "xml", "/site/etc/di.xml"));
assert!(!opens(&selectors, "yaml", "/site/config.yaml"));
assert!(selectors.unregister("open") && !selectors.unregister("open"));
assert!(!opens(&selectors, "yaml", "/site/modules/blog/blog.services.yml"));
assert!(selectors.unregister("hover"));
}
#[test]
fn a_filter_keeps_every_restriction_or_takes_nothing() {
let opens = |filter: Value, language: &str, path: &str| {
let mut selectors = DocumentSelectors::default();
selectors.register("open", DID_OPEN, Some(&json!({ "documentSelector": [filter] })));
selectors.opens(language, Path::new(path))
};
// A relative pattern is matched below its base, a URI or a workspace folder.
let base = uri::path_to_uri(Path::new("/site/modules"));
for base in [json!(base), json!({ "uri": base, "name": "modules" })] {
let relative =
json!({ "language": "yaml", "pattern": { "baseUri": base, "pattern": "**/*.services.yml" } });
assert!(opens(relative.clone(), "yaml", "/site/modules/blog/blog.services.yml"));
assert!(!opens(relative.clone(), "yaml", "/site/themes/x/x.services.yml"));
assert!(!opens(relative.clone(), "yaml", "/site/modules/blog/blog.routing.yml"));
assert!(!opens(relative, "xml", "/site/modules/blog/blog.services.yml"));
}
// A part that cannot be read does not widen the filter to the rest of it.
let unread = [
json!({ "language": "yaml", "pattern": { "pattern": "**/*.yml" } }),
json!({ "language": "yaml", "pattern": { "baseUri": 1, "pattern": "**/*.yml" } }),
json!({ "language": "yaml", "pattern": { "baseUri": base } }),
json!({ "language": "yaml", "pattern": 7 }),
json!({ "language": "yaml", "pattern": "[" }),
json!({ "language": "yaml", "scheme": ["file"] }),
json!({ "language": ["yaml"], "pattern": "**/*.yml" }),
json!({ "language": "yaml", "notebook": "jupyter-notebook" }),
json!({ "pattern": { "baseUri": base, "pattern": 7 } }),
json!({ "scheme": "file" }),
json!("yaml"),
];
for filter in unread {
assert!(!opens(filter.clone(), "yaml", "/site/modules/blog/blog.services.yml"), "{filter}");
}
// Absent and null parts do not restrict.
assert!(opens(json!({ "language": "yaml", "scheme": null, "pattern": null }), "yaml", "/site/a.yml"));
assert!(opens(json!({ "scheme": "file", "pattern": "**/*.yml" }), "yaml", "/site/a.yml"));
}
}
+19 -1
Переглянути файл
@@ -618,10 +618,25 @@ impl ClientHandler {
let list = params.get(key).or_else(|| params.get("unregistrations")).and_then(Value::as_array);
let mut caps = run.caps.write();
let mut watchers_changed = false;
// Its registrations by document selector name the documents it is sent, and leave
// the capabilities it started with alone.
let selective = self.server.config.dynamic_documents;
let mut documents_changed = false;
for reg in list.into_iter().flatten() {
let Some(method) = reg.get("method").and_then(Value::as_str) else { continue };
let id = reg.get("id").and_then(Value::as_str).unwrap_or_default();
if selective && method.starts_with("textDocument/") {
let mut documents = run.documents.write();
let kept = match register {
true => documents.register(id, method, reg.get("registerOptions")),
false => documents.unregister(id),
};
if kept {
documents_changed = true;
continue;
}
}
if method == "workspace/didChangeWatchedFiles" {
let id = reg.get("id").and_then(Value::as_str).unwrap_or_default();
let mut watchers = run.watchers.write();
if register {
watchers.register(id, reg.get("registerOptions"));
@@ -645,6 +660,9 @@ impl ClientHandler {
if watchers_changed {
mgr.file_watch_roots_changed();
}
if documents_changed {
mgr.document_selectors_changed();
}
}
}
+39 -9
Переглянути файл
@@ -13,6 +13,7 @@ mod clang_tidy;
mod closing_labels;
mod compose;
mod convert;
mod doc_selectors;
mod external_project;
mod file_ops;
mod file_watch;
@@ -813,7 +814,17 @@ impl LspManager {
/// only files below one, and stands in for no other. One that a server before
/// it `replaces` is left out while that server serves the file.
fn servers_for(&self, language: &LanguageId, path: &Path) -> Vec<Arc<Server>> {
self.declared_servers_for(language, path, true)
let mut out = self.declared_servers_for(language, path, true);
let path = &*self.in_project_spelling(path);
for server in self.servers.lock().iter().filter(|s| s.config.dynamic_documents && path.starts_with(&s.root)) {
if !out.iter().any(|s| s.id == server.id)
&& server.instance().is_some_and(|run| run.documents.read().opens(language.as_str(), path))
{
server.add_language(language);
out.push(server.clone());
}
}
out
}
fn declared_servers_for(&self, language: &LanguageId, path: &Path, allow_joins: bool) -> Vec<Arc<Server>> {
@@ -929,7 +940,7 @@ impl LspManager {
}
let mut attached = Attached { server: server.clone(), opened_gen: None };
if let Some(run) = server.running() {
if run.caps.read().open_close {
if run.opens_document(&d.language, &d.path) {
let language_id = self.languages.server_language_id(&d.language, &server.name);
user_did_open(server, &run, &d.path, &d.uri, d.did_open_params(&language_id));
}
@@ -958,6 +969,13 @@ impl LspManager {
}
}
/// Reconciles open documents when a server registers or withdraws a selector.
fn document_selectors_changed(&self) {
if let Some(me) = self.me.upgrade() {
self.runtime.spawn(async move { me.fallbacks_take_over().await });
}
}
fn ensure_started(&self, server: &Arc<Server>) {
if self.shutting_down.load(Ordering::Acquire) || !self.execution_allowed.load(Ordering::Acquire) {
return;
@@ -1175,8 +1193,13 @@ impl LspManager {
return;
}
};
let run =
Running { generation, peer: peer.clone(), caps: Arc::new(RwLock::new(caps)), watchers: Default::default() };
let run = Running {
generation,
peer: peer.clone(),
caps: Arc::new(RwLock::new(caps)),
watchers: Default::default(),
documents: Default::default(),
};
if !server.set_initializing(run.clone()) {
Self::kill_peer(&server, &peer).await;
return;
@@ -1204,8 +1227,8 @@ impl LspManager {
if !server.mark_ready(generation, run.clone()) {
false
} else {
let open_close = run.caps.read().open_close;
for (id, d) in docs.iter_mut().filter(|(_, d)| d.notebook.is_none()) {
let open_close = run.opens_document(&d.language, &d.path);
let params = d.did_open_params(&self.languages.server_language_id(&d.language, &server.name));
for a in
d.servers.iter_mut().filter(|a| a.server.id == server.id && a.opened_gen != Some(generation))
@@ -1251,6 +1274,9 @@ impl LspManager {
}
let Some(delay) = server.on_closed(generation, &self.sink, code) else { return };
self.file_watch_roots_changed();
if server.config.dynamic_documents {
self.document_selectors_changed();
}
if !server.root.is_dir() {
self.forget(std::slice::from_ref(&server));
return;
@@ -1323,6 +1349,9 @@ impl LspManager {
if server.name == "csharp-ls" {
params["capabilities"]["experimental"]["csharp"]["metadataUris"] = json!(true);
}
if cfg.dynamic_documents {
params["capabilities"]["textDocument"]["synchronization"]["dynamicRegistration"] = json!(true);
}
if server.name == razor::ROSLYN {
razor::configure_client_capabilities(&mut params["capabilities"]);
}
@@ -1454,7 +1483,7 @@ impl LspManager {
let mut servers = std::mem::take(&mut state.servers);
for a in &mut servers {
if let Some(run) = a.server.running() {
if run.caps.read().open_close {
if run.opens_document(&state.language, &state.path) {
let language_id = self.languages.server_language_id(&state.language, &a.server.name);
let params = state.did_open_params(&language_id);
user_did_open(&a.server, &run, &state.path, &state.uri, params);
@@ -1644,7 +1673,7 @@ impl LspManager {
self.forget_pulled(&a.server, &d.path, a.server.running().as_ref());
let Some(run) = a.server.running() else { continue };
if a.opened_gen == Some(run.generation)
&& run.caps.read().open_close
&& run.opens_document(&d.language, &d.path)
&& let Err(e) = run.peer.notify("textDocument/didClose", json!({ "textDocument": { "uri": d.uri } }))
{
tracing::debug!("{}: didClose: {e}", a.server.name);
@@ -4694,7 +4723,8 @@ impl LspManager {
.iter()
.filter(|a| {
!wanted.iter().any(|w| w.id == a.server.id)
&& (configs.iter().any(|c| (c.fallback || c.joins.is_some()) && c.name == a.server.name)
&& (a.server.config.dynamic_documents
|| configs.iter().any(|c| (c.fallback || c.joins.is_some()) && c.name == a.server.name)
|| configs.iter().any(|c| c.replaces.contains(&a.server.name))
|| (a.server.name == "clangd" && wanted.iter().any(|s| s.name == arduino::SERVER)))
})
@@ -4718,7 +4748,7 @@ impl LspManager {
for a in leaving {
if let Some(run) = a.server.running()
&& a.opened_gen == Some(run.generation)
&& run.caps.read().open_close
&& (a.server.config.dynamic_documents || run.caps.read().open_close)
&& let Err(e) =
run.peer.notify("textDocument/didClose", json!({ "textDocument": { "uri": d.uri } }))
{
+8
Переглянути файл
@@ -29,6 +29,14 @@ pub struct Running {
pub caps: Arc<RwLock<ServerCaps>>,
/// `workspace/didChangeWatchedFiles` registrations.
pub watchers: Arc<RwLock<crate::file_watch::FileWatchers>>,
/// The registrations by document selector of a `dynamic-documents` server.
pub documents: Arc<RwLock<crate::doc_selectors::DocumentSelectors>>,
}
impl Running {
pub(crate) fn opens_document(&self, language: &ide_core::LanguageId, path: &Path) -> bool {
self.caps.read().open_close || self.documents.read().opens(language.as_str(), path)
}
}
pub enum Conn {
+72
Переглянути файл
@@ -270,6 +270,7 @@ fn server_cfg(name: &str) -> LanguageServerConfig {
connect: None,
fallback: false,
replaces: Vec::new(),
dynamic_documents: false,
language_id: None,
joins: None,
files: Vec::new(),
@@ -9220,6 +9221,77 @@ async fn c_family_files_use_sourcekit_lsp_only_with_an_xcode_bsp_config() {
}
}
/// A `dynamic-documents` server registers for documents of another language by selector:
/// it is sent those, opened before or after, and keeps the capabilities it started with
/// when it takes the registrations back.
#[tokio::test(flavor = "multi_thread")]
async fn a_server_is_sent_the_documents_it_registers_a_selector_for() {
let mut caps = incremental_caps();
caps["textDocumentSync"]["openClose"] = json!(false);
let h =
harness_languages(&[("code", "cd", &[("fw", caps)]), ("data", "dt", &[("own", incremental_caps())])], |cfg| {
cfg.dynamic_documents = cfg.name == "fw";
});
let data = LanguageId::new("data");
let open_data = |name: &str| {
let path = h.root.join(name);
std::fs::write(&path, "x").unwrap();
h.mgr.did_open(DocId::next(), &path, &data, 1, "x");
path
};
let (code, _) = h.open("a.cd", "x");
let before = open_data("before.dt");
let unrelated = open_data("notes.txt");
h.wait_status("fw", ServerStatus::Ready).await;
h.wait_status("own", ServerStatus::Ready).await;
let (fw, own) = (h.launcher.state("fw"), h.launcher.state("own"));
let dynamic = |s: &MockState| {
s.requested("initialize")[0]["capabilities"]["textDocument"]["synchronization"]["dynamicRegistration"].clone()
};
assert_eq!((dynamic(&fw), dynamic(&own)), (json!(true), json!(false)));
eventually(|| own.docs.lock().contains_key(&uri_of(&before))).await;
assert!(!fw.docs.lock().contains_key(&uri_of(&before)));
let selector = json!({ "documentSelector": [{ "scheme": "file", "pattern": "**/*.dt" }] });
let registrations: Vec<Value> = ["textDocument/didOpen", "textDocument/hover"]
.iter()
.map(|method| json!({ "id": format!("data:{method}"), "method": method, "registerOptions": selector }))
.collect();
fw.peer()
.request::<_, Value>("client/registerCapability", json!({ "registrations": registrations }), None)
.await
.unwrap();
eventually(|| fw.docs.lock().contains_key(&uri_of(&before))).await;
let told = fw.notified("textDocument/didOpen");
let opened = told.iter().find(|o| o["textDocument"]["uri"] == json!(uri_of(&before))).unwrap();
assert_eq!(opened["textDocument"]["languageId"], "data");
let after = open_data("after.dt");
eventually(|| fw.docs.lock().contains_key(&uri_of(&after))).await;
// Its own server keeps the documents, and one the selector doesn't name stays with it alone.
assert!(own.docs.lock().contains_key(&uri_of(&after)) && own.docs.lock().contains_key(&uri_of(&unrelated)));
assert!(!fw.docs.lock().contains_key(&uri_of(&unrelated)));
// The server list names the language among the ones it serves.
let served = h.mgr.servers().into_iter().find(|s| s.name == "fw").unwrap().languages;
assert!(served.contains(&data), "{served:?}");
// Taken back: existing documents close, later ones stay local, and hover still works for code.
let gone: Vec<Value> = registrations.iter().map(|r| json!({ "id": r["id"], "method": r["method"] })).collect();
fw.peer()
.request::<_, Value>("client/unregisterCapability", json!({ "unregisterations": gone }), None)
.await
.unwrap();
eventually(|| !fw.docs.lock().contains_key(&uri_of(&before)) && !fw.docs.lock().contains_key(&uri_of(&after)))
.await;
let later = open_data("later.dt");
eventually(|| own.docs.lock().contains_key(&uri_of(&later))).await;
tokio::time::sleep(Duration::from_millis(100)).await;
assert!(!fw.docs.lock().contains_key(&uri_of(&later)));
let asked = fw.requested("textDocument/hover").len();
assert!(h.mgr.hover(code, Pos::new(0, 0), Default::default()).await.is_ok());
assert_eq!(fw.requested("textDocument/hover").len(), asked + 1);
h.mgr.shutdown_all().await;
}
/// A server that knows a language's documents under another id (a PHP server on a
/// Blade view) is told that one; the others are told the language's own.
#[tokio::test(flavor = "multi_thread")]
+47
Переглянути файл
@@ -421,6 +421,7 @@ async fn missing_binary_is_reported_with_install_hint() {
connect: None,
fallback: false,
replaces: Vec::new(),
dynamic_documents: false,
language_id: None,
joins: None,
files: Vec::new(),
@@ -718,6 +719,7 @@ async fn typescript_language_server_end_to_end() {
connect: None,
fallback: false,
replaces: Vec::new(),
dynamic_documents: false,
language_id: None,
joins: None,
files: Vec::new(),
@@ -776,6 +778,7 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Valu
connect: None,
fallback: false,
replaces: Vec::new(),
dynamic_documents: false,
language_id: None,
joins: None,
files: Vec::new(),
@@ -1834,6 +1837,50 @@ async fn phoxite_pulls_a_member_up_end_to_end() {
mgr.shutdown_all().await;
}
/// In a Drupal project Phoxite registers for the YAML files of its modules: it is sent a
/// `*.services.yml`, and answers there, though no YAML server is asked to.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires phoxite-lsp (OPENIDEA_TEST_PHOXITE_LSP) and its fixtures (OPENIDEA_TEST_PHOXITE_FIXTURES)"]
async fn phoxite_reads_the_yaml_of_a_drupal_project_it_registers_for() {
let fixtures = std::env::var("OPENIDEA_TEST_PHOXITE_FIXTURES").expect("OPENIDEA_TEST_PHOXITE_FIXTURES");
let root = Path::new(&fixtures).join("drupal-app").canonicalize().unwrap();
let root = dunce::simplified(&root).to_path_buf();
let registry = LanguageRegistry::load(None).unwrap();
let mut php = registry.get(&LanguageId::new("php")).unwrap();
php.language_servers.retain(|s| s.name == "phoxite");
assert!(php.language_servers[0].dynamic_documents);
if let Ok(bin) = std::env::var("OPENIDEA_TEST_PHOXITE_LSP") {
php.language_servers[0].command = bin;
}
let mut yaml = registry.get(&LanguageId::new("yaml")).unwrap();
yaml.language_servers.clear();
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![php, yaml]));
let open = |relative: &str, language: &str| {
let path = root.join(relative);
let doc = DocId::next();
mgr.did_open(doc, &path, &LanguageId::new(language), 1, &std::fs::read_to_string(&path).unwrap());
doc
};
let services = open("modules/shop/shop.services.yml", "yaml");
open("modules/shop/src/Catalog.php", "php");
retry("phoxite ready", Duration::from_secs(30), || {
let status = last_status(&events, "phoxite");
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, msg)) = &status {
panic!("phoxite failed: {msg:?}");
}
async move { matches!(status, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
})
.await;
// On `Prices` in `class: Drupal\shop\Prices`, once the project is indexed and found to be Drupal's.
let defs = retry("the service's class", Duration::from_secs(90), || {
let mgr = mgr.clone();
async move { mgr.goto(services, Pos::new(5, 26), GotoKind::Definition).await.ok().filter(|d| !d.is_empty()) }
})
.await;
assert_eq!(Path::new(&*defs[0].path).file_name().unwrap(), "Prices.php", "{defs:?}");
mgr.shutdown_all().await;
}
/// Phoxite as the project's PHP server also reads its Twig templates: a template opened
/// before any PHP file starts it, as a `twig` document, and it answers there.
#[tokio::test(flavor = "multi_thread")]
+1
Переглянути файл
@@ -1808,6 +1808,7 @@ fn custom_server(name: &str, ls: &LanguageServerSettings) -> LanguageServerConfi
connect: None,
fallback: false,
replaces: Vec::new(),
dynamic_documents: false,
language_id: None,
joins: None,
files: Vec::new(),
+1
Переглянути файл
@@ -39,6 +39,7 @@ pub(crate) fn server(name: &str) -> LanguageServerConfig {
connect: None,
fallback: false,
replaces: Vec::new(),
dynamic_documents: false,
language_id: None,
joins: None,
files: Vec::new(),
+11
Переглянути файл
@@ -20,6 +20,17 @@ A Blade view is served by the same servers as the project's PHP files. While Pho
Phoxite, where it is the project's PHP server, also reads files of other languages: Twig templates, `.env` files and Laravel's `lang/*.json`. It runs once for all of them, next to those languages' own servers, and is never started for a project without PHP.
Phoxite, once it finds one of these platforms in the project, also reads the platform's own files, so the names it knows in PHP (services, routes, hooks, configuration paths, language keys) complete and navigate there too:
| Platform | Files |
| --------- | ---------------------------------------------------------------------------------------------- |
| WordPress | JavaScript and TypeScript files, and `block.json` |
| Drupal | A module's or theme's `*.yml` (`*.services.yml`, `*.routing.yml`, `*.info.yml`, …) and `.info` |
| Magento | A module's `etc/**/*.xml`, layout and UI component XML, and `schema.graphqls` |
| Joomla | Manifests, forms and other XML, `language/**/*.ini` and `joomla.asset.json` |
Those files keep their own language servers (the YAML, XML and TypeScript ones); Phoxite adds its answers to theirs, in the project where it already runs for PHP.
DEVSENSE is usable without a licence for everyday code insight (completion, hover, go to definition, references, diagnostics, Laravel and Blade support); its refactorings and call/type hierarchy need a DEVSENSE licence.
Intelephense checks code against the project's PHP version (see [Language level](#language-level)) and indexes the stubs and include paths you configure.
+11
Переглянути файл
@@ -20,6 +20,17 @@ Blade 视图由为项目 PHP 文件提供服务的同一组服务器处理。Pho
Phoxite 作为项目的 PHP 服务器时,还会读取其他语言的文件:Twig 模板、`.env` 文件和 Laravel 的 `lang/*.json`。这些文件共用同一个 Phoxite 进程,与各自语言的服务器并存;没有 PHP 的项目不会启动它。
Phoxite 在项目中识别出下列平台后,还会读取平台自己的文件,因此它在 PHP 中认识的名字(服务、路由、钩子、配置路径、语言键)在这些文件中同样可以补全和跳转:
| 平台 | 文件 |
| --------- | ------------------------------------------------------------------------------------ |
| WordPress | JavaScript 和 TypeScript 文件,以及 `block.json` |
| Drupal | 模块或主题的 `*.yml`(`*.services.yml`、`*.routing.yml`、`*.info.yml` 等)和 `.info` |
| Magento | 模块的 `etc/**/*.xml`、布局和 UI 组件 XML,以及 `schema.graphqls` |
| Joomla | 清单、表单等 XML,`language/**/*.ini` 和 `joomla.asset.json` |
这些文件仍由各自语言的服务器(YAML、XML、TypeScript)处理,Phoxite 的结果与它们的合并;Phoxite 只在已为 PHP 运行的项目中读取这些文件。
DEVSENSE 无需许可证即可用于日常代码智能(补全、悬停、跳转、查找引用、诊断,以及 Laravel 和 Blade 支持);其重构以及调用/类型层次结构需要 DEVSENSE 许可证。
Intelephense 会按项目的 PHP 版本检查代码(见下文“语言级别”),并索引你配置的 stub 和包含路径。
+1
Переглянути файл
@@ -42,6 +42,7 @@ language-id = "php"
# Completion, hover, signature help, navigation and problems inside the view.
[[language-servers]]
name = "phoxite"
dynamic-documents = true
fallback = true
command = "phoxite-lsp"
args = []
+3
Переглянути файл
@@ -45,6 +45,9 @@ args = []
root-markers = ["composer.json", "artisan", "index.php"]
# It answers the Laravel strings itself.
replaces = ["laravel-lsp"]
# It asks for the files of the frameworks it finds: a WordPress project's scripts, a
# Drupal module's YAML, a Magento module's XML, a Joomla extension's manifests.
dynamic-documents = true
install-hint = "Install Phoxite in Settings › Languages & Frameworks › Language Servers"
# Alternative whose engine ships as native builds for Windows, macOS and Linux;