diff --git a/plugins/official/mybatis/Cargo.lock b/plugins/official/mybatis/Cargo.lock index 5ae6b1f25..15dc91b85 100644 --- a/plugins/official/mybatis/Cargo.lock +++ b/plugins/official/mybatis/Cargo.lock @@ -105,7 +105,7 @@ dependencies = [ [[package]] name = "openidea-plugin-openidea-mybatis" -version = "0.4.2" +version = "0.4.3" dependencies = [ "openidea-plugin", ] diff --git a/plugins/official/mybatis/Cargo.toml b/plugins/official/mybatis/Cargo.toml index d9db9918d..cebd0ff93 100644 --- a/plugins/official/mybatis/Cargo.toml +++ b/plugins/official/mybatis/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "openidea-plugin-openidea-mybatis" -version = "0.4.2" +version = "0.4.3" edition = "2024" publish = false diff --git a/plugins/official/mybatis/dist/plugin.wasm b/plugins/official/mybatis/dist/plugin.wasm index d0670aac6..10246725f 100644 Binary files a/plugins/official/mybatis/dist/plugin.wasm and b/plugins/official/mybatis/dist/plugin.wasm differ diff --git a/plugins/official/mybatis/dist/plugin.wasm.sources b/plugins/official/mybatis/dist/plugin.wasm.sources index 97fe15152..b0ffa6a81 100644 --- a/plugins/official/mybatis/dist/plugin.wasm.sources +++ b/plugins/official/mybatis/dist/plugin.wasm.sources @@ -1 +1 @@ -bcf00a07cfc9a894d3effd88a3dbc4d000ac2abc057358db1afe17f9fde93710 +9df4fce831ca53f8e26ae3148c2525c42f8d2473c88da344b0890c85dcac13d6 diff --git a/plugins/official/mybatis/plugin.toml b/plugins/official/mybatis/plugin.toml index dbc70694f..3b66d52e5 100644 --- a/plugins/official/mybatis/plugin.toml +++ b/plugins/official/mybatis/plugin.toml @@ -1,10 +1,10 @@ id = "openidea.mybatis" name = "MyBatis Navigator" -version = "0.4.2" +version = "0.4.3" description = "Jumps between MyBatis mapper interfaces and their XML statements, resultMaps, sql/include fragments, namespaces or annotation SQL (gutter arrows and Go to Definition), completes statement and sql ids and #{parameters}." authors = ["OpenIDEA contributors"] license = "Apache-2.0" -change-notes = "0.4.2 — the XML named like the mapper interface is found by its file name, and a found XML is kept, so gutter arrows no longer go missing in large projects. 0.4.1 — the XML for a mapper interface is found by a search, so gutter arrows no longer time out on projects with many XML files. 0.4.0 — result maps: @ResultMap navigates to @Results(id)/XML resultMap and completes ids; resultMap= in XML jumps too. 0.3.0 — annotation SQL: #{…}/${…} in @Select/@Insert/@Update/@Delete navigates to @Param/parameters and completes them; pure-annotation mappers need no XML. 0.2.0 — namespace, resultMap/extends and sql/include navigation, refid completion; 0.1.0 — first release: navigation both ways, line markers, id and parameter completion." +change-notes = "0.4.3 — navigate between Kotlin mapper interfaces and XML statements. 0.4.2 — the XML named like the mapper interface is found by its file name, and a found XML is kept, so gutter arrows no longer go missing in large projects. 0.4.1 — the XML for a mapper interface is found by a search, so gutter arrows no longer time out on projects with many XML files. 0.4.0 — result maps: @ResultMap navigates to @Results(id)/XML resultMap and completes ids; resultMap= in XML jumps too. 0.3.0 — annotation SQL: #{…}/${…} in @Select/@Insert/@Update/@Delete navigates to @Param/parameters and completes them; pure-annotation mappers need no XML. 0.2.0 — namespace, resultMap/extends and sql/include navigation, refid completion; 0.1.0 — first release: navigation both ways, line markers, id and parameter completion." categories = ["frameworks"] engines.openidea = "^1.4" wasm = "dist/plugin.wasm" @@ -16,3 +16,7 @@ required = ["project.read"] [[contributes.providers]] kinds = ["definition", "line-markers", "completion"] languages = ["java", "xml"] + +[[contributes.providers]] +kinds = ["definition", "line-markers"] +languages = ["kotlin"] diff --git a/plugins/official/mybatis/src/kotlin.rs b/plugins/official/mybatis/src/kotlin.rs new file mode 100644 index 000000000..d5ea02487 --- /dev/null +++ b/plugins/official/mybatis/src/kotlin.rs @@ -0,0 +1,206 @@ +use super::{MapperInterface, Named, Param, Positions, ident, skip_comment, skip_string}; + +#[derive(Clone, Copy)] +struct Token<'a> { + text: &'a str, + start: usize, +} + +impl<'a> Token<'a> { + fn name(self) -> &'a str { + self.text.trim_matches('`') + } + + fn is_name(self) -> bool { + self.text.starts_with('`') || self.text.starts_with(|c: char| c.is_alphabetic() || c == '_') + } + + fn named(self, positions: &mut Positions<'_>) -> Named { + let start = self.start + usize::from(self.text.starts_with('`')); + let name = self.name(); + Named { name: name.to_owned(), range: positions.range(start, start + name.len()) } + } +} + +fn skip_block_comment(text: &str) -> usize { + let mut rest = &text[2..]; + let mut depth = 1; + while let Some(at) = rest.find(['/', '*']) { + rest = &rest[at..]; + if let Some(next) = rest.strip_prefix("/*") { + depth += 1; + rest = next; + } else if let Some(next) = rest.strip_prefix("*/") { + depth -= 1; + rest = next; + if depth == 0 { + return text.len() - rest.len(); + } + } else { + rest = &rest[1..]; + } + } + text.len() +} + +fn tokens(text: &str) -> Vec> { + let bytes = text.as_bytes(); + let mut out = Vec::new(); + let mut at = 0; + while at < text.len() { + let rest = &text[at..]; + let c = rest.chars().next().unwrap(); + let end = if c.is_whitespace() { + at += c.len_utf8(); + continue; + } else if rest.starts_with("//") { + at = skip_comment(bytes, at); + continue; + } else if rest.starts_with("/*") { + at += skip_block_comment(rest); + continue; + } else if let Some(raw) = rest.strip_prefix("\"\"\"") { + raw.find("\"\"\"").map_or(text.len(), |end| at + end + 6) + } else if matches!(c, '"' | '\'') { + skip_string(bytes, at) + } else if let Some(quoted) = rest.strip_prefix('`') { + quoted.find('`').map_or(at + 1, |end| at + end + 2) + } else if ident(c) { + rest.find(|c| !ident(c)).map_or(text.len(), |end| at + end) + } else { + at + c.len_utf8() + }; + out.push(Token { text: &text[at..end], start: at }); + at = end; + } + out +} + +fn package(tokens: &[Token<'_>]) -> String { + let Some(start) = tokens.iter().position(|t| t.text == "package") else { return String::new() }; + let mut parts = Vec::new(); + let mut names = tokens[start + 1..].iter(); + while let Some(name) = names.next().filter(|t| t.is_name()) { + parts.push(name.name()); + if names.next().map(|t| t.text) != Some(".") { + break; + } + } + parts.join(".") +} + +fn method_name<'a>(tokens: &[Token<'a>]) -> Option<(Token<'a>, usize)> { + let mut generics = 0usize; + for (i, t) in tokens.iter().enumerate() { + match t.text { + "<" => generics += 1, + ">" => generics = generics.saturating_sub(1), + "(" if generics == 0 => { + let name = *tokens.get(i.checked_sub(1)?)?; + return name.is_name().then_some((name, i)); + } + "fun" | "val" | "var" | "interface" | "class" | "object" | "{" | "}" | ";" | "=" => break, + _ => {} + } + } + None +} + +fn parameters(tokens: &[Token<'_>], positions: &mut Positions<'_>) -> Vec { + let mut params = Vec::new(); + let mut nested = 0usize; + let mut generics = 0usize; + let mut first = 0; + let mut name = None; + for (i, t) in tokens.iter().enumerate() { + match t.text { + "(" | "[" | "{" => nested += 1, + ")" if nested == 0 => { + params.extend(name); + break; + } + ")" | "]" | "}" => nested = nested.saturating_sub(1), + "<" if nested == 0 => generics += 1, + ">" if nested == 0 => generics = generics.saturating_sub(1), + "," if nested == 0 && generics == 0 => { + params.extend(name.take()); + first = i + 1; + } + ":" if nested == 0 && generics == 0 && name.is_none() && i > first => { + let candidate = tokens[i - 1]; + if !candidate.is_name() || (i >= 2 && tokens[i - 2].text == "@") { + continue; + } + let explicit = tokens[first..i].windows(3).find_map(|args| match args { + [param, open, value] if param.text == "Param" && open.text == "(" => { + Some((*value, value.text.strip_prefix('"')?.strip_suffix('"')?)) + } + _ => None, + }); + let Named { name: label, range } = if let Some((token, label)) = explicit { + let start = token.start + 1; + Named { name: label.to_owned(), range: positions.range(start, start + label.len()) } + } else { + candidate.named(positions) + }; + name = Some(Param { name: label, range }); + } + _ => {} + } + } + params +} + +/// Read named interfaces and their direct members. Kotlin's `fun` introduces +/// a declaration even when there are no semicolons or explicit return types. +pub(super) fn parse(text: &str) -> Vec { + if !text.contains("interface") { + return Vec::new(); + } + let tokens = tokens(text); + let package = package(&tokens); + let mut positions = Positions::new(text); + let mut output: Vec = Vec::new(); + let mut pending = false; + let mut inside_interface = false; + let mut braces = 0usize; + let mut parens = 0usize; + for (i, t) in tokens.iter().enumerate() { + match t.text { + "(" => parens += 1, + ")" => parens = parens.saturating_sub(1), + "{" if parens == 0 => { + if braces == 0 { + inside_interface = std::mem::take(&mut pending); + } + braces += 1; + } + "}" if parens == 0 => { + braces = braces.saturating_sub(1); + if braces == 0 { + inside_interface = false; + } + } + "interface" if braces == 0 && parens == 0 => { + if let Some(name) = tokens.get(i + 1).filter(|t| t.is_name()) { + let decl = name.named(&mut positions); + let name = if package.is_empty() { decl.name.clone() } else { format!("{package}.{}", decl.name) }; + output.push(MapperInterface { name: Some(name), decl: Some(decl), ..MapperInterface::default() }); + pending = true; + } + } + "fun" if braces == 1 && parens == 0 && inside_interface => { + if let Some((name, parens)) = method_name(&tokens[i + 1..]) { + let method = name.named(&mut positions); + let params = parameters(&tokens[i + parens + 2..], &mut positions); + output.last_mut().unwrap().methods.push((method, params)); + } + } + "class" | "object" | "fun" | "val" | "var" | "typealias" | ";" if braces == 0 && parens == 0 => { + pending = false; + } + _ => {} + } + } + output +} diff --git a/plugins/official/mybatis/src/lib.rs b/plugins/official/mybatis/src/lib.rs index df970ecaa..6eea709f5 100644 --- a/plugins/official/mybatis/src/lib.rs +++ b/plugins/official/mybatis/src/lib.rs @@ -12,6 +12,8 @@ use openidea_plugin::{ use std::collections::{BTreeMap, BTreeSet}; use std::time::{Duration, Instant}; +mod kotlin; + /// How long a namespace without an XML file is not looked up again. const INDEX_TTL: Duration = Duration::from_secs(30); /// Lookups kept per project before the expired ones are dropped. @@ -57,7 +59,7 @@ pub struct Param { } /// `#{…}` / `${…}` inside one method's `@Select`/`@Insert`/`@Update`/`@Delete` -/// SQL strings: `method` indexes `MapperJava::methods`, `strings` covers the +/// SQL strings: `method` indexes `MapperInterface::methods`, `strings` covers the /// SQL string literals, each `Named` in `params` covers one whole `#{…}` / /// `${…}` match. #[derive(Clone, Debug, PartialEq, Eq)] @@ -67,7 +69,7 @@ pub struct AnnotationSql { pub params: Vec, } -/// `@ResultMap("…")` on one method: `method` indexes `MapperJava::methods`, +/// `@ResultMap("…")` on one method: `method` indexes `MapperInterface::methods`, /// `name` covers the id string (quotes excluded). #[derive(Clone, Debug, PartialEq, Eq)] pub struct ResultMapRef { @@ -75,9 +77,9 @@ pub struct ResultMapRef { pub name: Named, } -/// A Java interface. +/// A mapper interface. #[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct MapperJava { +pub struct MapperInterface { /// Fully qualified name. pub name: Option, /// The interface's own name (for `` targets). @@ -589,10 +591,10 @@ fn result_map_of(head: &str) -> (Vec, Vec) { } /// The interface's name and methods (with their parameter names). -pub fn parse_java(text: &str) -> MapperJava { +pub fn parse_java(text: &str) -> MapperInterface { let package = text.lines().find_map(|l| l.trim().strip_prefix("package ").map(|p| p.trim_end_matches(';').trim().to_owned())); - let Some(i) = text.find("interface ") else { return MapperJava::default() }; + let Some(i) = text.find("interface ") else { return MapperInterface::default() }; let rest = &text[i + 10..]; let indent = rest.len() - rest.trim_start().len(); let simple: String = rest[indent..].chars().take_while(|c| ident(*c)).collect(); @@ -688,7 +690,7 @@ pub fn parse_java(text: &str) -> MapperJava { _ => i += 1, } } - MapperJava { name, decl, methods, annotation_sql, result_refs, result_ids } + MapperInterface { name, decl, methods, annotation_sql, result_refs, result_ids } } /// `namespace="com.acme.UserMapper"` in an XML file, either quote. @@ -723,10 +725,13 @@ fn is_under(path: &str, root: &str) -> bool { .is_some_and(|rest| rest.is_empty() || root.ends_with(['/', '\\']) || rest.starts_with(['/', '\\'])) } +type FileIndex = BTreeMap)>>; + #[derive(Default)] pub struct Navigator { /// project root → namespace → (when it was looked up, the XML mapping it, if any). - xml_index: BTreeMap)>>, + xml_index: FileIndex, + kotlin_index: FileIndex, /// Other mappers looked up for the file being linked (see [`MAX_OTHER_MAPPERS`]). other_mappers: BTreeSet, } @@ -778,16 +783,66 @@ impl Navigator { hit } - /// The interface `namespace` names (`com.acme.UserMapper` → `**/com/acme/UserMapper.java`). - fn java_for(project: &Project, namespace: &str) -> Option<(String, MapperJava)> { - // A Java name only: anything else would be read as a glob. + /// Resolve the declaration by its package and name. A Kotlin interface can + /// live outside a package-named directory or in a differently named file. + fn interface_for(&mut self, project: &Project, namespace: &str) -> Option<(String, MapperInterface)> { if namespace.is_empty() || !namespace.chars().all(|c| ident(c) || c == '.') { return None; } let rel = format!("**/{}.java", namespace.replace('.', "/")); - let path = project.find_files(&rel, 1).ok()?.into_iter().next()?; - let java = parse_java(&project.read_file(&path).ok()?); - (java.name.as_deref() == Some(namespace)).then_some((path, java)) + let java = project.find_files(&rel, 1).ok().and_then(|paths| paths.into_iter().next()); + if let Some(path) = java + && let Ok(text) = project.read_file(&path) + { + let mapper = parse_java(&text); + if mapper.name.as_deref() == Some(namespace) { + return Some((path, mapper)); + } + } + let read = |path: &str| { + kotlin::parse(&project.read_file(path).ok()?) + .into_iter() + .find(|mapper| mapper.name.as_deref() == Some(namespace)) + }; + let simple = namespace.rsplit('.').next()?; + let paths = project.find_files(&format!("**/{simple}.kt"), MAX_MAPPERS).unwrap_or_default(); + let resolve = |path: String| { + let mapper = read(&path)?; + Some((path, mapper)) + }; + if let Some(found) = paths.into_iter().find_map(resolve) { + return Some(found); + } + let root = project.root().ok()?; + match self.kotlin_index.get(&root).and_then(|m| m.get(namespace)) { + Some((_, Some(path))) => { + if let Some(mapper) = read(path) { + return Some((path.clone(), mapper)); + } + } + Some((at, None)) if at.elapsed() < INDEX_TTL => return None, + _ => {} + } + if project.find_files("**/*.kt", 1).ok()?.is_empty() { + return None; + } + let name = simple.replace('$', "\\$"); + let query = TextQuery { + pattern: format!(r"\binterface\s+`?{name}`?\b"), + regex: true, + case_sensitive: true, + include: vec!["**/*.kt".into()], + ..Default::default() + }; + let search = project.search_text(&query, MAX_MAPPERS).ok()?; + let paths: BTreeSet<_> = search.matches.into_iter().map(|m| m.location.path).collect(); + let hit = paths.into_iter().find_map(resolve); + let index = self.kotlin_index.entry(root).or_default(); + if index.len() >= MAX_INDEXED { + index.retain(|_, (at, _)| at.elapsed() < INDEX_TTL); + } + index.insert(namespace.to_owned(), (Instant::now(), hit.as_ref().map(|(path, _)| path.clone()))); + hit } /// Where `resultMap="…"` / `` points: a `` / @@ -876,9 +931,9 @@ impl Navigator { let Some(ns) = xml.namespace.clone() else { return Vec::new() }; let mut out = Vec::new(); // `` → the interface; statement ids → methods. - if let Some((path, java)) = Self::java_for(&project, &ns.name) { + if let Some((path, mapper)) = self.interface_for(&project, &ns.name) { let simple = ns.name.rsplit('.').next().unwrap_or(&ns.name).to_owned(); - if let Some(decl) = java.decl { + if let Some(decl) = mapper.decl { out.push(( ns.clone(), Location { path: path.clone(), range: decl.range }, @@ -886,7 +941,7 @@ impl Navigator { )); } out.extend(xml.statements.iter().filter_map(|s| { - let (m, _) = java.methods.iter().find(|(m, _)| m.name == s.name)?; + let (m, _) = mapper.methods.iter().find(|(m, _)| m.name == s.name)?; let tip = format!("{simple}.{}()", m.name); Some((s.clone(), Location { path: path.clone(), range: m.range }, tip)) })); @@ -907,43 +962,56 @@ impl Navigator { out.sort_by_key(|a| a.0.range.start); out } else { - let java = parse_java(&doc.text); - let Some(name) = java.name.clone() else { return Vec::new() }; - let simple = name.rsplit('.').next().unwrap_or(&name).to_owned(); - // `@ResultMap("…")`: the `@Results(id = "…")` in this file when - // present, else the XML mapper's ``. Needs no XML for - // pure-annotation mappers. - let xml = self.xml_for(&project, &name); - let mut out: Vec<(Named, Location, String)> = Vec::new(); - for r in &java.result_refs { - if let Some((method, def)) = java.result_ids.iter().find(|(_, d)| d.name == r.name.name) { - let (m, _) = &java.methods[*method]; - out.push(( - r.name.clone(), - Location { path: doc.path.clone(), range: def.range }, - format!("{simple}.{}(): {}", m.name, def.name), - )); - } else if let Some((path, xml)) = &xml - && let Some(def) = xml.result_maps.iter().find(|m| m.name == r.name.name) - { - let file = path.rsplit(['/', '\\']).next().unwrap_or(path).to_owned(); - out.push(( - r.name.clone(), - Location { path: path.clone(), range: def.range }, - format!("{file}: {}", def.name), - )); - } - } - if let Some((path, xml)) = xml { - let file = path.rsplit(['/', '\\']).next().unwrap_or(&path).to_owned(); - out.extend(java.methods.into_iter().filter_map(|(m, _)| { - let s = xml.statements.iter().find(|s| s.name == m.name)?; - Some((m, Location { path: path.clone(), range: s.range }, format!("{file}: {}", s.name))) - })); - } - out + let interfaces = match doc.language.as_str() { + "kotlin" => kotlin::parse(&doc.text).into_iter().filter(|m| !m.methods.is_empty()).collect(), + "java" => vec![parse_java(&doc.text)], + _ => Vec::new(), + }; + interfaces.into_iter().flat_map(|mapper| self.interface_links(doc, &project, mapper)).collect() } } + + fn interface_links( + &mut self, + doc: &Document, + project: &Project, + mapper: MapperInterface, + ) -> Vec<(Named, Location, String)> { + let Some(name) = mapper.name.as_ref() else { return Vec::new() }; + let simple = name.rsplit('.').next().unwrap_or(name).to_owned(); + // `@ResultMap("…")`: the `@Results(id = "…")` in this file when + // present, else the XML mapper's ``. Needs no XML for + // pure-annotation mappers. + let xml = self.xml_for(project, name); + let mut out: Vec<(Named, Location, String)> = Vec::new(); + for r in &mapper.result_refs { + if let Some((method, def)) = mapper.result_ids.iter().find(|(_, d)| d.name == r.name.name) { + let (m, _) = &mapper.methods[*method]; + out.push(( + r.name.clone(), + Location { path: doc.path.clone(), range: def.range }, + format!("{simple}.{}(): {}", m.name, def.name), + )); + } else if let Some((path, xml)) = &xml + && let Some(def) = xml.result_maps.iter().find(|m| m.name == r.name.name) + { + let file = path.rsplit(['/', '\\']).next().unwrap_or(path).to_owned(); + out.push(( + r.name.clone(), + Location { path: path.clone(), range: def.range }, + format!("{file}: {}", def.name), + )); + } + } + if let Some((path, xml)) = xml { + let file = path.rsplit(['/', '\\']).next().unwrap_or(&path).to_owned(); + out.extend(mapper.methods.into_iter().filter_map(|(m, _)| { + let s = xml.statements.iter().find(|s| s.name == m.name)?; + Some((m, Location { path: path.clone(), range: s.range }, format!("{file}: {}", s.name))) + })); + } + out + } } fn contains(r: Range, p: Position) -> bool { @@ -1002,7 +1070,7 @@ impl Providers for Navigator { let xml = parse_xml(&doc.text); let Some(ns) = xml.namespace.clone().map(|n| n.name) else { return Vec::new() }; let Some(project) = project_of(&doc.path) else { return Vec::new() }; - let Some((_, java)) = Self::java_for(&project, &ns) else { return Vec::new() }; + let Some((_, mapper)) = self.interface_for(&project, &ns) else { return Vec::new() }; let line_start = before.rfind('\n').map_or(0, |i| i + 1); let line = &before[line_start..]; // Inside `id="…` of a statement tag: the interface's unmapped methods. @@ -1012,7 +1080,7 @@ impl Providers for Navigator { { let typed = &line[i + 4..]; let Some(start) = replace_start(at, typed) else { return Vec::new() }; - return java + return mapper .methods .iter() .filter(|(m, _)| m.name.starts_with(typed) && !xml.statements.iter().any(|s| s.name == m.name)) @@ -1048,7 +1116,8 @@ impl Providers for Navigator { let typed = &before[i + 2..]; let here = position(&doc.text, cursor); let statement = xml.statements.iter().rev().find(|s| s.range.start < here); - let Some((_, params)) = statement.and_then(|s| java.methods.iter().find(|(m, _)| m.name == s.name)) else { + let Some((_, params)) = statement.and_then(|s| mapper.methods.iter().find(|(m, _)| m.name == s.name)) + else { return Vec::new(); }; let Some(start) = replace_start(at, typed) else { return Vec::new() }; @@ -1256,6 +1325,74 @@ mod tests { Document { path: path.into(), language: language.into(), version: 1, text: text.into() } } + #[test] + fn navigates_between_kotlin_and_xml() { + const KOTLIN: &str = concat!( + "package com.acme\n", + "interface UserMapper : BaseMapper {\n", + " @MapperHint(\"😀\") fun findById(@Param(\"id\") userId: Long): User?\n", + " fun insert(user: User): Int\n", + " fun search(values: Map, limit: Int): List\n", + " object Other { fun unrelated() {} }\n", + "}\n", + ); + let host = MockHost::install(); + let kotlin_path = "module/src/main/kotlin/UserMapper.kt"; + let xml_path = "module/src/main/resources/mapper/UserMapper.xml"; + host.add_file(kotlin_path, KOTLIN); + add_mapper(&host, xml_path, XML); + let kotlin = doc(&format!("/project/{kotlin_path}"), "kotlin", KOTLIN); + let xml = doc(&format!("/project/{xml_path}"), "xml", XML); + let mut navigator = Navigator::default(); + let marker_lines = |markers: Vec| markers.iter().map(|m| m.line).collect::>(); + assert_eq!(marker_lines(navigator.line_markers(&kotlin)), [2, 3]); + assert_eq!(marker_lines(navigator.line_markers(&xml)), [1, 2, 5]); + + let from_kotlin = navigator.definition(&kotlin, Position::new(2, 26)); + assert_eq!(from_kotlin[0].path, xml.path); + assert_eq!(from_kotlin[0].range.start, Position::new(2, 14)); + let namespace = navigator.definition(&xml, Position::new(1, 25)); + assert_eq!(namespace[0].path, kotlin.path); + assert_eq!(namespace[0].range.start, Position::new(1, 10)); + let statement = navigator.definition(&xml, Position::new(2, 16)); + assert_eq!(statement[0].path, kotlin.path); + assert_eq!(statement[0].range.start, Position::new(2, 26)); + + let items = navigator.completion(&xml, Position::new(8, 14), None); + assert_eq!(items.iter().map(|c| c.label.as_str()).collect::>(), ["search"]); + let xml = doc(&xml.path, "xml", &XML.replace("#{id}", "#{")); + let params = navigator.completion(&xml, Position::new(3, 38), None); + assert_eq!(params.iter().map(|c| c.label.as_str()).collect::>(), ["id"]); + } + + #[test] + fn finds_kotlin_mapper_in_a_differently_named_file() { + let host = MockHost::install(); + let path = "module/src/main/kotlin/Mappers.kt"; + host.add_file(path, "package com.acme\n/* /* nested */ interface Fake */\ninterface Empty\ninterface UserMapper { fun findById(): User }\n"); + host.on_search(move |query, _| { + assert_eq!(query.include, ["**/*.kt"]); + assert!(query.pattern.contains("UserMapper")); + Ok(TextSearch { + matches: vec![TextMatch { + location: Location { + path: format!("/project/{path}"), + range: Range::new(Position::new(3, 0), Position::new(3, 0)), + }, + line: String::new(), + }], + limit_hit: false, + }) + }); + let mut navigator = Navigator::default(); + let xml = doc("/project/UserMapper.xml", "xml", XML); + let namespace = navigator.definition(&xml, Position::new(1, 25)); + assert_eq!(namespace[0].path, format!("/project/{path}")); + assert_eq!(namespace[0].range.start, Position::new(3, 10)); + let statement = navigator.definition(&xml, Position::new(2, 16)); + assert_eq!(statement[0].range.start, Position::new(3, 27)); + } + #[test] fn navigates_both_ways() { let _host = setup(); @@ -1668,9 +1805,10 @@ mod tests { assert!(pattern.contains(r"a\|b\.x\[0\]"), "{pattern}"); let _host = setup(); let project = host::projects().unwrap().remove(0); - assert!(Navigator::java_for(&project, "com.acme.UserMapper").is_some()); - assert!(Navigator::java_for(&project, "com.*.UserMapper").is_none()); - assert!(Navigator::java_for(&project, "").is_none()); + let mut navigator = Navigator::default(); + assert!(navigator.interface_for(&project, "com.acme.UserMapper").is_some()); + assert!(navigator.interface_for(&project, "com.*.UserMapper").is_none()); + assert!(navigator.interface_for(&project, "").is_none()); } #[test]