1use std::{collections::HashSet, ops::Deref};
2
3use crate::lsp_types::Range;
4use bevy_ecs::prelude::*;
5use swls_lov::LocalPrefix;
6use tracing::instrument;
7
8use crate::{
9 lsp_types::{CompletionItemKind, TextEdit},
10 prelude::*,
11 systems::PrefixEntry,
12};
13
14pub const PREFIX_CC: &str = include_str!("./prefix_cc.txt");
15
16#[derive(Debug, Clone)]
18pub struct Prefix {
19 pub prefix: String,
20 pub url: crate::lsp_types::Url,
21}
22
23#[derive(Component, Debug)]
25pub struct Prefixes(pub Vec<Prefix>, pub crate::lsp_types::Url);
26
27impl Deref for Prefixes {
28 type Target = Vec<Prefix>;
29
30 fn deref(&self) -> &Self::Target {
31 &self.0
32 }
33}
34
35impl Prefixes {
36 pub fn shorten(&self, value: &str) -> Option<String> {
44 self.shorten_with(value, is_local_name)
45 }
46
47 pub fn shorten_compact(&self, value: &str) -> Option<String> {
51 self.shorten_with(value, |_| true)
52 }
53
54 fn shorten_with(&self, value: &str, valid: impl Fn(&str) -> bool) -> Option<String> {
55 self.0
56 .iter()
57 .filter_map(|prefix| {
58 let local = value.strip_prefix(prefix.url.as_str())?;
59 valid(local).then_some((prefix.url.as_str().len(), prefix, local))
60 })
61 .max_by_key(|(len, prefix, _)| {
65 (
66 *len,
67 !prefix.prefix.is_empty(),
68 std::cmp::Reverse(prefix.prefix.clone()),
69 )
70 })
71 .map(|(_, prefix, local)| format!("{}:{}", prefix.prefix, local))
72 }
73}
74
75fn is_pn_chars_base(c: char) -> bool {
76 c.is_ascii_alphabetic() || (!c.is_ascii() && c.is_alphabetic())
77}
78
79fn is_pn_chars_u(c: char) -> bool {
80 is_pn_chars_base(c) || c == '_'
81}
82
83fn is_pn_chars(c: char) -> bool {
84 is_pn_chars_u(c)
85 || c == '-'
86 || c.is_ascii_digit()
87 || c == '\u{B7}'
88 || ('\u{300}'..='\u{36F}').contains(&c)
89 || ('\u{203F}'..='\u{2040}').contains(&c)
90}
91
92pub fn is_local_name(local: &str) -> bool {
97 let chars: Vec<char> = local.chars().collect();
98 let mut i = 0;
99 while i < chars.len() {
100 let c = chars[i];
101 let first = i == 0;
102 if c == '%' {
103 let hex = |j: usize| chars.get(j).is_some_and(|c| c.is_ascii_hexdigit());
104 if !(hex(i + 1) && hex(i + 2)) {
105 return false;
106 }
107 i += 3;
108 continue;
109 }
110 let ok = if first {
111 is_pn_chars_u(c) || c == ':' || c.is_ascii_digit()
112 } else {
113 is_pn_chars(c) || c == '.' || c == ':'
114 };
115 if !ok {
116 return false;
117 }
118 i += 1;
119 }
120 !local.ends_with('.')
121}
122
123enum PrefixLike<'a> {
124 Prefix(&'a Prefix),
125 Local(&'a LocalPrefix),
126 Entry(&'a PrefixEntry),
127}
128impl PrefixLike<'_> {
129 fn as_completion(
130 &self,
131 lang: &DynLang,
132 range: Range,
133 extra: Option<Vec<TextEdit>>,
134 ) -> SimpleCompletion {
135 let (name, title, namespace) = match self {
136 PrefixLike::Prefix(prefix) => (prefix.prefix.as_str(), None, prefix.url.as_str()),
137 PrefixLike::Local(local_prefix) => (
138 local_prefix.name.as_ref(),
139 Some(local_prefix.title.as_ref()),
140 local_prefix.namespace.as_ref(),
141 ),
142 PrefixLike::Entry(prefix_entry) => (
143 prefix_entry.name.as_ref(),
144 None,
145 prefix_entry.namespace.as_ref(),
146 ),
147 };
148
149 let nt = format!("{}:$0", name);
150 let mut completion = SimpleCompletion::new(
151 CompletionItemKind::MODULE,
152 name.to_string(),
153 crate::lsp_types::TextEdit {
154 new_text: lang.quote(&nt),
155 range,
156 },
157 )
158 .documentation(namespace)
159 .as_snippet();
161
162 if let Some(title) = title {
163 completion = completion.label_description(title);
164 }
165
166 if let Some(extra) = extra {
167 for e in extra {
168 completion = completion.text_edit(e);
169 }
170 }
171
172 completion
173 }
174
175 fn name(&self) -> &str {
176 match self {
177 PrefixLike::Prefix(prefix) => prefix.prefix.as_str(),
178 PrefixLike::Local(local_prefix) => local_prefix.name.as_ref(),
179 PrefixLike::Entry(prefix_entry) => prefix_entry.name.as_ref(),
180 }
181 }
182
183 fn namespace(&self) -> &str {
184 match self {
185 PrefixLike::Prefix(prefix) => prefix.url.as_str(),
186 PrefixLike::Local(local_prefix) => local_prefix.namespace.as_ref(),
187 PrefixLike::Entry(prefix_entry) => prefix_entry.namespace.as_ref(),
188 }
189 }
190}
191
192pub const MAX_UNDECLARED_PREFIXES: usize = 30;
195
196pub fn prefix_completion_helper<'a>(
204 word: &TokenComponent,
205 prefixes: &'a Prefixes,
206 completions: &mut Vec<SimpleCompletion>,
207 mut extra_edits: impl FnMut(&str, &str) -> Option<Vec<TextEdit>>,
208 lovs: impl Iterator<Item = &'a LocalPrefix>,
209 prefix_cc: impl Iterator<Item = &'a PrefixEntry>,
210 lang: &DynLang,
211) {
212 let mut suggested = HashSet::new();
213 let text = lang.unquote(&word.text);
214 tracing::debug!("completion helper {:?}", word);
215
216 let mut undeclared = 0;
217 let candidates = prefixes
218 .iter()
219 .map(PrefixLike::Prefix)
220 .chain(lovs.map(PrefixLike::Local))
221 .chain(prefix_cc.map(PrefixLike::Entry));
222 for prefix in candidates {
223 let declared = matches!(prefix, PrefixLike::Prefix(_));
224 if !declared && (text.is_empty() || undeclared >= MAX_UNDECLARED_PREFIXES) {
225 continue;
226 }
227 if !prefix.name().starts_with(text)
228 || !(prefix.namespace().ends_with('#') || prefix.namespace().ends_with('/'))
229 || !suggested.insert(prefix.name().to_string())
230 {
231 continue;
232 }
233 if !declared {
234 undeclared += 1;
235 }
236 let edits = extra_edits(prefix.name(), prefix.namespace());
237 completions.push(prefix.as_completion(lang, word.range, edits));
238 }
239}
240
241#[instrument(skip(query, lovs, prefix_cc, config))]
254pub fn rdf_lov_undefined_prefix_completion(
255 mut query: Query<(
256 &TokenComponent,
257 &Source,
258 &RopeC,
259 &Prefixes,
260 &mut CompletionRequest,
261 &DynLang,
262 )>,
263 lovs: Query<&LocalPrefix>,
264 prefix_cc: Query<&PrefixEntry>,
265 config: Res<ServerConfig>,
266) {
267 if config.config.local.is_disabled(Disabled::CompletionPrefix) {
268 return;
269 }
270 let fmt = config.config.local.prefix_format.unwrap_or_default();
271 for (word, source, rope, prefixes, mut req, lang) in &mut query {
272 if lang.handles_prefix_completion() {
273 continue;
274 }
275 prefix_completion_helper(
276 word,
277 prefixes,
278 &mut req.0,
279 |name, location| {
280 if prefixes.iter().any(|p| p.prefix == name) {
281 None
282 } else {
283 lang.prefix_edits(&source.0, &rope.0, name, location, fmt)
284 }
285 },
286 lovs.iter(),
287 prefix_cc.iter(),
288 lang,
289 );
290 }
291}
292
293#[cfg(test)]
294mod shorten_tests {
295 use super::*;
296
297 fn prefixes(decls: &[(&str, &str)]) -> Prefixes {
298 Prefixes(
299 decls
300 .iter()
301 .map(|(p, u)| Prefix {
302 prefix: p.to_string(),
303 url: crate::lsp_types::Url::parse(u).unwrap(),
304 })
305 .collect(),
306 crate::lsp_types::Url::parse("file:///doc.ttl").unwrap(),
307 )
308 }
309
310 #[test]
311 fn local_names() {
312 for ok in [
313 "",
314 "name",
315 "Name_1",
316 "a.b",
317 "1abc",
318 "a:b",
319 "caf\u{e9}",
320 "a%20b",
321 "a-b",
322 ] {
323 assert!(is_local_name(ok), "{ok:?} should be valid");
324 }
325 for bad in [
326 "a/b", "a#b", "a.", "-a", ".a", "a b", "a?b", "a%2", "a~b", "a,b",
327 ] {
328 assert!(!is_local_name(bad), "{bad:?} should be invalid");
329 }
330 }
331
332 #[test]
333 fn shorten_only_to_valid_prefixed_names() {
334 let p = prefixes(&[("rml", "http://w3id.org/rml/")]);
335 assert_eq!(
336 p.shorten("http://w3id.org/rml/TriplesMap").as_deref(),
337 Some("rml:TriplesMap")
338 );
339 assert_eq!(p.shorten("http://w3id.org/rml/shapes/X"), None);
340 assert_eq!(
341 p.shorten_compact("http://w3id.org/rml/shapes/X").as_deref(),
342 Some("rml:shapes/X")
343 );
344 assert_eq!(p.shorten("http://other.test/x"), None);
345 }
346
347 #[test]
348 fn ties_prefer_a_named_prefix_then_alphabetical() {
349 let p = prefixes(&[
350 ("", "http://w3id.org/rml/shapes/"),
351 ("zz", "http://w3id.org/rml/shapes/"),
352 ("rmlsh", "http://w3id.org/rml/shapes/"),
353 ]);
354 assert_eq!(
355 p.shorten("http://w3id.org/rml/shapes/X").as_deref(),
356 Some("rmlsh:X")
357 );
358 }
359
360 #[test]
361 fn longest_namespace_wins() {
362 let p = prefixes(&[
363 ("rml", "http://w3id.org/rml/"),
364 ("rmlsh", "http://w3id.org/rml/shapes/"),
365 ]);
366 assert_eq!(
367 p.shorten("http://w3id.org/rml/shapes/X").as_deref(),
368 Some("rmlsh:X")
369 );
370 assert_eq!(
371 p.shorten_compact("http://w3id.org/rml/shapes/X").as_deref(),
372 Some("rmlsh:X")
373 );
374 assert_eq!(
375 p.shorten("http://w3id.org/rml/source").as_deref(),
376 Some("rml:source")
377 );
378 }
379}