diff --git a/crates/ide-language/src/lib.rs b/crates/ide-language/src/lib.rs index 512a6dd95..a06522afc 100644 --- a/crates/ide-language/src/lib.rs +++ b/crates/ide-language/src/lib.rs @@ -24,8 +24,9 @@ pub use registry::{FileTypes, LanguageRegistry}; pub use syntax::{ CSS_CLASS, CSS_ID, CSS_VARIABLE, ConfigurationKey, ExternalFold, ExternalSymbol, ExternalSyntax, ExternalToken, FileReference, Literal, LiteralKind, MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, SpellingKind, SpellingRegion, - Syntax, SyntaxCache, SyntaxCacheStats, SyntaxHighlightKind, SyntaxHighlights, TreeError, WebReference, - WebReferenceKind, merge_visibility, set_external_syntax, shift_pos, shift_range, + Syntax, SyntaxCache, SyntaxCacheStats, SyntaxHighlightKind, SyntaxHighlights, TreeError, VueComponentImport, + VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_visibility, set_external_syntax, shift_pos, + shift_range, }; /// Parsed form of `languages/.toml`. Backend-only; the UI gets [`LanguageInfo`]. diff --git a/crates/ide-language/src/syntax/mod.rs b/crates/ide-language/src/syntax/mod.rs index a015c0c36..d91a43ae4 100644 --- a/crates/ide-language/src/syntax/mod.rs +++ b/crates/ide-language/src/syntax/mod.rs @@ -12,6 +12,7 @@ mod outline; mod rst; mod selection; mod sfc; +mod vue; mod web; use crate::{FoldRange, LanguageConfig, LanguageRegistry, ScriptRegion, SymbolTag}; @@ -28,6 +29,7 @@ use std::cell::RefCell; use std::collections::HashMap; use std::sync::OnceLock; use tree_sitter::{Language, Parser, Tree}; +pub use vue::{VueComponentImport, VueRefAccess, VueRefElement}; pub use web::{CSS_CLASS, CSS_ID, CSS_VARIABLE, FileReference, WebReference, WebReferenceKind}; /// Texts larger than this are not parsed (minified bundles, generated dumps). diff --git a/crates/ide-language/src/syntax/vue.rs b/crates/ide-language/src/syntax/vue.rs new file mode 100644 index 000000000..a1b99d17a --- /dev/null +++ b/crates/ide-language/src/syntax/vue.rs @@ -0,0 +1,370 @@ +//! Vue Options API `this.$refs`: Vue 2.7 types `$refs` as an index signature, so the +//! TypeScript service resolves `this.$refs.child` to that signature and `.child.focusIt` +//! to nothing. The template names each ref (`ref="child"`) and the element it is on, +//! which is all navigation needs. + +use super::lines::{LineIndex, byte_at}; +use super::web::walk; +use super::{Syntax, parse}; +use crate::ScriptRegion; +use ide_core::{LanguageId, Pos, Range}; +use tree_sitter::Node; + +/// The `$refs.` (or `$refs..`) expression a position is on. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VueRefAccess { + pub name: String, + /// The member read from the referenced element, when the position is on it. + pub member: Option, +} + +/// The template element that carries `ref=""`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VueRefElement { + /// The attribute value: the ref's declaration. + pub value: Range, + pub tag: String, +} + +/// A default import in a component's ` +"#; + + fn pos_of(text: &str, needle: &str, nth: usize, offset: usize) -> Pos { + let byte = text.match_indices(needle).nth(nth).unwrap().0 + offset; + LineIndex::new(text).pos(byte) + } + + #[test] + fn finds_the_ref_and_the_member_read_from_it() { + let s = Syntax::new(); + let child = s.vue_ref_access(APP, pos_of(APP, "this.$refs.child", 0, 12)).unwrap(); + assert_eq!(child, VueRefAccess { name: "child".into(), member: None }); + // At the end of the name too. + let end = s.vue_ref_access(APP, pos_of(APP, "this.$refs.child", 0, 16)).unwrap(); + assert_eq!(end.name, "child"); + let member = s.vue_ref_access(APP, pos_of(APP, "focusIt", 0, 2)).unwrap(); + assert_eq!(member, VueRefAccess { name: "child".into(), member: Some("focusIt".into()) }); + let optional = s.vue_ref_access(APP, pos_of(APP, "field?.focus", 0, 1)).unwrap(); + assert_eq!(optional.name, "field"); + assert!(s.vue_ref_access(APP, pos_of(APP, "$refs.child", 1, 2)).is_none(), "$refs itself"); + assert!(s.vue_ref_access(APP, pos_of(APP, "handler", 1, 1)).is_none()); + assert!(s.vue_ref_access(APP, pos_of(APP, "$refs.child }}", 0, 7)).is_none(), "template is the server's"); + } + + #[test] + fn finds_the_element_with_the_ref() { + let s = Syntax::new(); + let child = s.vue_ref_element(APP, "child").unwrap(); + assert_eq!(child.tag, "child-button"); + assert_eq!(child.value.start, pos_of(APP, "\"child\"", 0, 1)); + let field = s.vue_ref_element(APP, "field").unwrap(); + assert_eq!(field.tag, "input"); + assert!(s.vue_ref_element(APP, "missing").is_none()); + let last = ""; + assert_eq!(s.vue_ref_element(last, "x").unwrap().tag, "b"); + assert!(s.vue_ref_element("", "x").is_none()); + } + + #[test] + fn finds_the_import_a_tag_names() { + let s = Syntax::new(); + let import = s.vue_component_import(APP, "child-button").unwrap(); + assert_eq!(import.specifier, "./components/ChildButton.vue"); + assert_eq!(import.binding.start, pos_of(APP, "ChildButton from", 0, 0)); + assert_eq!(s.vue_component_import(APP, "ChildButton").unwrap().specifier, import.specifier); + assert!(s.vue_component_import(APP, "input").is_none()); + } + + #[test] + fn finds_instance_members_in_the_options() { + let s = Syntax::new(); + let child = r#" + +"#; + let vue = LanguageId::new("vue"); + let at = |name: &str| s.vue_component_member(&vue, child, name); + assert_eq!(at("focusIt").unwrap().start, pos_of(child, "focusIt", 0, 0)); + assert_eq!(at("reset").unwrap().start, pos_of(child, "reset", 0, 0)); + assert_eq!(at("double").unwrap().start, pos_of(child, "double", 0, 0)); + assert_eq!(at("quoted").unwrap().start, pos_of(child, "'quoted'", 0, 0)); + assert_eq!(at("size").unwrap().start, pos_of(child, "'size'", 0, 0)); + assert_eq!(at("count").unwrap().start, pos_of(child, "count: 0", 0, 0)); + assert_eq!(at("helper").unwrap().start, pos_of(child, "helper }", 0, 0)); + assert!(at("nope").is_none()); + assert!(at("name").is_none()); + + let ts = "import { defineComponent } from 'vue'\nexport default defineComponent({ methods: { go() {} } })\n"; + let at = s.vue_component_member(&LanguageId::new("typescript"), ts, "go").unwrap(); + assert_eq!(at.start, pos_of(ts, "go()", 0, 0)); + let props = "export default { props: { value: String } }"; + assert!(s.vue_component_member(&LanguageId::new("javascript"), props, "value").is_some()); + } +} diff --git a/crates/ide-lsp/src/jdtls/configuration.rs b/crates/ide-lsp/src/jdtls/configuration.rs index ea420e6e7..b5a752ca4 100644 --- a/crates/ide-lsp/src/jdtls/configuration.rs +++ b/crates/ide-lsp/src/jdtls/configuration.rs @@ -51,7 +51,7 @@ struct Response { #[serde(default)] incomplete: bool, } -fn syntax() -> &'static Syntax { +pub(crate) fn syntax() -> &'static Syntax { static SYNTAX: OnceLock = OnceLock::new(); SYNTAX.get_or_init(Syntax::new) } diff --git a/crates/ide-lsp/src/lib.rs b/crates/ide-lsp/src/lib.rs index 94220fe0c..48d958be8 100644 --- a/crates/ide-lsp/src/lib.rs +++ b/crates/ide-lsp/src/lib.rs @@ -37,6 +37,7 @@ pub mod types; mod uri; mod virtual_doc; mod vue_navigation; +mod vue_refs; pub use injections::{InjectedRange, InjectionProvider, MAX_INJECTED_DOCUMENT_BYTES}; pub use inspect::{FileInspection, InspectHost, InspectOptions}; @@ -1602,6 +1603,9 @@ impl LspManager { { return Ok(result.locations); } + if let Some(found) = self.vue_ref_navigation(doc, &snap, pos).await { + return Ok(found); + } } let (method, cap, feature) = goto_method(kind); let (snap, targets) = self.doc_targets(doc, feature, |c| c.has(cap)).await?; diff --git a/crates/ide-lsp/src/vue_refs.rs b/crates/ide-lsp/src/vue_refs.rs new file mode 100644 index 000000000..eb3739964 --- /dev/null +++ b/crates/ide-lsp/src/vue_refs.rs @@ -0,0 +1,131 @@ +//! Vue Options API `this.$refs`: the Vue 2.7 types declare `$refs` as an index signature, +//! so the TypeScript service sends `this.$refs.child` to that signature and finds nothing +//! for `this.$refs.child.focusIt`. The template says which element each ref is on: +//! `this.$refs.child` goes to its `ref="child"`, and a member read from a component's ref +//! goes to that member in the component's options. + +use crate::jdtls::configuration::syntax; +use crate::types::GotoKind; +use crate::{DocSnap, LspManager, goto_method}; +use ide_core::{DocId, LanguageId, Location, Pos}; +use std::path::{Component, Path, PathBuf}; + +impl LspManager { + pub(crate) async fn vue_ref_navigation(&self, doc: DocId, snap: &DocSnap, pos: Pos) -> Option> { + if snap.language.as_str() != "vue" || !snap.text.as_str().contains("$refs") { + return None; + } + let text = snap.text.clone(); + let (member, element, import) = tokio::task::spawn_blocking(move || { + let s = syntax(); + let access = s.vue_ref_access(text.as_str(), pos)?; + let element = s.vue_ref_element(text.as_str(), &access.name)?; + let import = access.member.as_ref().and_then(|_| s.vue_component_import(text.as_str(), &element.tag)); + Some((access.member, element, import)) + }) + .await + .ok() + .flatten()?; + let Some(member) = member else { + return Some(vec![Location { path: snap.path.clone().into(), range: element.value, uri: None }]); + }; + let import = import?; + let file = match relative_module(&snap.path, &import.specifier) { + Some(file) => file, + // An alias (`@/components/…`): the language service knows the project's paths; + // without them configured, `@` is the Vue CLI / Vite templates' `src`. + None => match self.definition_file(doc, import.binding.start).await { + Some(file) => file, + None => src_alias(&self.project_root_for(&snap.path), &import.specifier)?, + }, + }; + let lang = script_language(&file)?; + let open = self.docs.lock().values().find(|d| d.path == file).map(|d| d.text.clone()); + let range = tokio::task::spawn_blocking({ + let file = file.clone(); + move || { + let text = match open { + Some(text) => text.as_str().to_owned(), + None => std::fs::read_to_string(&file).ok()?, + }; + syntax().vue_component_member(&lang, &text, &member) + } + }) + .await + .ok() + .flatten()?; + Some(vec![Location { path: file.into(), range, uri: None }]) + } + + async fn definition_file(&self, doc: DocId, pos: Pos) -> Option { + let (method, cap, feature) = goto_method(GotoKind::Definition); + let (snap, targets) = self.doc_targets(doc, feature, |c| c.has(cap)).await.ok()?; + let found = self.goto_in(&snap, &targets, method, pos, None, None).await.ok()?; + // The import binding itself is no answer. + found.into_iter().find(|l| l.uri.is_none() && *l.path != snap.path).map(|l| l.path.into_path_buf()) + } +} + +/// The file a relative import names, with the extensions a bundler tries. +fn relative_module(from: &Path, specifier: &str) -> Option { + if !specifier.starts_with("./") && !specifier.starts_with("../") { + return None; + } + let mut base = from.parent()?.to_path_buf(); + for part in Path::new(specifier).components() { + match part { + Component::CurDir => {} + Component::ParentDir => { + base.pop(); + } + part => base.push(part), + } + } + let candidates = [String::new(), ".vue".into(), ".ts".into(), ".js".into()] + .into_iter() + .map(|ext| PathBuf::from(format!("{}{ext}", base.display()))) + .chain(["index.vue", "index.ts", "index.js"].into_iter().map(|index| base.join(index))); + candidates.into_iter().find(|p| p.is_file()) +} + +fn src_alias(root: &Path, specifier: &str) -> Option { + let rest = specifier.strip_prefix("@/")?; + relative_module(&root.join("src").join("_"), &format!("./{rest}")) +} + +fn script_language(file: &Path) -> Option { + let id = match file.extension()?.to_str()? { + "vue" => "vue", + "ts" | "mts" | "cts" => "typescript", + "tsx" => "tsx", + "js" | "mjs" | "cjs" | "jsx" => "javascript", + _ => return None, + }; + Some(LanguageId::new(id)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn resolves_relative_component_imports() { + let dir = tempfile::tempdir().unwrap(); + let src = dir.path().join("src"); + std::fs::create_dir_all(src.join("components/Panel")).unwrap(); + std::fs::write(src.join("components/ChildButton.vue"), "").unwrap(); + std::fs::write(src.join("components/Panel/index.vue"), "").unwrap(); + let app = src.join("App.vue"); + assert_eq!(relative_module(&app, "./components/ChildButton.vue"), Some(src.join("components/ChildButton.vue"))); + assert_eq!(relative_module(&app, "./components/ChildButton"), Some(src.join("components/ChildButton.vue"))); + assert_eq!(relative_module(&app, "./components/Panel"), Some(src.join("components/Panel/index.vue"))); + assert_eq!( + relative_module(&src.join("components/Panel/index.vue"), "../ChildButton.vue"), + Some(src.join("components/ChildButton.vue")) + ); + assert_eq!(relative_module(&app, "@/components/ChildButton.vue"), None); + assert_eq!(relative_module(&app, "./components/Missing.vue"), None); + assert_eq!(src_alias(dir.path(), "@/components/ChildButton"), Some(src.join("components/ChildButton.vue"))); + assert_eq!(src_alias(dir.path(), "~/components/ChildButton"), None); + } +}