swls_core/lang.rs
1use std::{borrow::Cow, ops::Range};
2
3use crate::{
4 lsp_types::SemanticTokenType, prelude::TripleTarget, text::LineIndex, util::offset_to_position,
5};
6
7pub fn head() -> crate::lsp_types::Range {
8 let start = crate::lsp_types::Position {
9 line: 0,
10 character: 0,
11 };
12 crate::lsp_types::Range { end: start, start }
13}
14
15pub trait Lang: 'static {
16 type ElementError: Into<crate::feature::diagnostics::SimpleDiagnostic>
17 + Send
18 + Sync
19 + std::fmt::Debug;
20
21 const CODE_ACTION: bool;
22 const HOVER: bool;
23 const LANG: &'static str;
24 const TRIGGERS: &'static [&'static str];
25 const LEGEND_TYPES: &'static [SemanticTokenType];
26 const PATTERN: Option<&'static str>;
27
28 /// Map a CST syntax kind to a semantic token type for highlighting.
29 fn semantic_token_type(_kind: rowan::SyntaxKind) -> Option<SemanticTokenType> {
30 None
31 }
32
33 /// Map a CST syntax kind + byte span to semantic token spans for highlighting.
34 fn semantic_token_spans(
35 kind: rowan::SyntaxKind,
36 span: std::ops::Range<usize>,
37 _text: &str,
38 ) -> Vec<(SemanticTokenType, std::ops::Range<usize>)> {
39 Self::semantic_token_type(kind)
40 .map(|t| vec![(t, span)])
41 .unwrap_or_default()
42 }
43}
44
45pub trait LangHelper: std::fmt::Debug {
46 fn keyword(&self) -> &[&'static str];
47 fn default_position(&self) -> TripleTarget {
48 TripleTarget::Subject
49 }
50 /// `iri` as written with the document's prefixes in this language, or
51 /// `None` when it must be written in full. Turtle-family syntaxes only
52 /// accept valid prefixed names (see [`Prefixes::shorten`]).
53 fn shorten(&self, prefixes: &crate::prelude::Prefixes, iri: &str) -> Option<String> {
54 prefixes.shorten(iri)
55 }
56 /// `iri` as written in this language: a prefixed name when possible,
57 /// else the full IRI (`<…>` in Turtle-family syntaxes).
58 fn write_iri(&self, prefixes: &crate::prelude::Prefixes, iri: &str) -> String {
59 self.shorten(prefixes, iri)
60 .unwrap_or_else(|| format!("<{}>", iri))
61 }
62 fn unquote<'a>(&self, inp: &'a str) -> &'a str {
63 inp
64 }
65 fn quote(&self, inp: &str) -> String {
66 inp.to_string()
67 }
68 /// Return the source keyword used to introduce a prefix declaration
69 /// (used only for display / span-finding purposes).
70 fn prefix_keyword(&self) -> &str {
71 "@prefix"
72 }
73 /// Format a prefix declaration string to be inserted into a document.
74 ///
75 /// Default (Turtle / TriG): honors the user's [`PrefixFormat`] preference —
76 /// `@prefix {name}: <{url}>.\n` (Turtle) or `PREFIX {name}: <{url}>\n` (SPARQL-style).
77 fn format_prefix_declaration(
78 &self,
79 name: &str,
80 url: &str,
81 format: crate::components::PrefixFormat,
82 ) -> String {
83 match format {
84 crate::components::PrefixFormat::Sparql => format!("PREFIX {}: <{}>\n", name, url),
85 crate::components::PrefixFormat::Turtle => format!("@prefix {}: <{}>.\n", name, url),
86 }
87 }
88 /// Produce the text edit(s) that declare prefix `name` → `namespace` in this
89 /// document, or `None` when it cannot / should not be inserted (e.g. the
90 /// prefix is already present).
91 ///
92 /// This is the single source of truth for "how do I add a prefix to a
93 /// document of this language", shared by prefix completion and the
94 /// "add missing prefix" diagnostic quick-fix so the two paths stay
95 /// consistent. The default (Turtle / SPARQL / TriG) inserts a declaration
96 /// line at the very top of the file; JSON-LD overrides this to splice the
97 /// prefix into the `@context` object.
98 fn prefix_edits(
99 &self,
100 _source: &str,
101 _rope: &LineIndex,
102 name: &str,
103 namespace: &str,
104 format: crate::components::PrefixFormat,
105 ) -> Option<Vec<crate::lsp_types::TextEdit>> {
106 let pos = crate::lsp_types::Position::new(0, 0);
107 Some(vec![crate::lsp_types::TextEdit {
108 range: crate::lsp_types::Range::new(pos, pos),
109 new_text: self.format_prefix_declaration(name, namespace, format),
110 }])
111 }
112 /// Return `true` if the generic prefix-diagnostics system should analyse this
113 /// language's documents.
114 ///
115 /// JSON-LD uses `@context` semantics where terms are pre-expanded before being
116 /// stored as `Triples`; its prefix model is not compatible with the span-based
117 /// detection used by the generic system. Override to return `false` to opt out.
118 fn supports_prefix_diagnostics(&self) -> bool {
119 true
120 }
121 /// Extract the prefix name of a prefixed term whose `:` was just typed at byte
122 /// `offset` (the cursor sits immediately after the `:`), or `None` when the
123 /// context is not a bare prefixed name. Used by on-type formatting to decide
124 /// whether to auto-declare a prefix.
125 ///
126 /// Default (Turtle / TriG / SPARQL): scan back over prefix-name characters and
127 /// require a term boundary before them, skipping comments and
128 /// `@prefix`/`@base` (or `PREFIX`/`BASE`) declaration lines. JSON-LD overrides
129 /// this to scan inside a JSON string instead.
130 fn prefix_name_at<'a>(&self, source: &'a str, offset: usize) -> Option<&'a str> {
131 let bytes = source.as_bytes();
132 if offset == 0 || offset > source.len() || bytes[offset - 1] != b':' {
133 return None;
134 }
135 let colon = offset - 1;
136
137 let mut start = colon;
138 while start > 0 {
139 let c = bytes[start - 1];
140 if c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-' | b'.') {
141 start -= 1;
142 } else {
143 break;
144 }
145 }
146 if start == colon {
147 return None;
148 }
149
150 // The character before the name must be a term boundary; keeps us from
151 // matching `:` inside an IRI (`<…:…>`), a string literal, or a pname.
152 let boundary_ok = start == 0
153 || matches!(
154 bytes[start - 1],
155 b' ' | b'\t' | b'\n' | b'\r' | b';' | b',' | b'[' | b'(' | b'{'
156 );
157 if !boundary_ok {
158 return None;
159 }
160
161 // Skip comments and prefix/base declaration lines.
162 let line_start = source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
163 let before = &source[line_start..start];
164 if before.contains('#') {
165 return None;
166 }
167 let keyword = before.trim();
168 if keyword.eq_ignore_ascii_case("@prefix")
169 || keyword.eq_ignore_ascii_case("prefix")
170 || keyword.eq_ignore_ascii_case("@base")
171 || keyword.eq_ignore_ascii_case("base")
172 {
173 return None;
174 }
175
176 Some(&source[start..colon])
177 }
178 /// Given a raw token string from the document (e.g. `<http://ex.org/foo>` or `ex:foo`),
179 /// return the bare text that should be pre-filled in the editor's rename input box.
180 fn rename_placeholder<'a>(&self, raw: &'a str) -> &'a str {
181 // Default (Turtle / SPARQL / TriG): strip surrounding `< >`
182 let s = raw.strip_prefix('<').unwrap_or(raw);
183 s.strip_suffix('>').unwrap_or(s)
184 }
185 /// Wrap the user-supplied rename text so that it is valid in the current language.
186 ///
187 /// Default (Turtle / SPARQL / TriG) smart rules:
188 /// - already has `< >` → keep as-is
189 /// - starts with `_:` → blank node, keep as-is
190 /// - contains `://` → full IRI with scheme (e.g. `http://`), wrap in `< >`
191 /// - contains `:` but no `://` → prefixed name (e.g. `ex:foo`), keep as-is
192 /// - otherwise → bare label, wrap in `< >` to be safe
193 fn rename_wrap(&self, new_text: &str) -> String {
194 if (new_text.starts_with('<') && new_text.ends_with('>')) || new_text.starts_with("_:") {
195 new_text.to_string()
196 } else if new_text.contains("://") {
197 format!("<{}>", new_text)
198 } else if new_text.contains(':') {
199 // Prefixed name like ex:foo
200 new_text.to_string()
201 } else {
202 format!("<{}>", new_text)
203 }
204 }
205 /// Return `true` if this language provides its own prefix completion and
206 /// the generic [`defined_prefix_completion`] system should be skipped.
207 fn handles_prefix_completion(&self) -> bool {
208 false
209 }
210 /// Return `true` if this language renames via the model-based systems in
211 /// `swls-lang-rdf-base` (registered through `setup_rename`). When `true`,
212 /// the core language-agnostic `prepare_rename`/`rename` systems skip this
213 /// language's documents to avoid producing duplicate edits.
214 ///
215 /// Text RDF syntaxes (Turtle / TriG / SPARQL) override this to `true`;
216 /// JSON-LD keeps the default and stays on the agnostic path.
217 fn model_based_rename(&self) -> bool {
218 false
219 }
220 /// Return `true` if this language supports the generic blank-node refactor
221 /// code actions (extract a nested `[ … ]` to a labelled `_:bN`, and inline a
222 /// labelled `_:bN` back into `[ … ]`).
223 ///
224 /// These actions emit Turtle-family syntax, so the text RDF syntaxes
225 /// (Turtle / TriG / SPARQL / N3) override this to `true`. JSON-LD keeps the
226 /// default because its blank nodes are JSON objects, not `[ … ]` / `_:bN`.
227 fn blank_node_code_actions(&self) -> bool {
228 false
229 }
230 fn supports_shape_validation(&self) -> bool {
231 true
232 }
233 /// Return `true` if SHACL shape templates can be offered as completions.
234 ///
235 /// Templates are written in Turtle syntax, so this defaults to languages
236 /// that use Turtle-family syntax and support shape validation.
237 fn shape_templates(&self) -> bool {
238 self.blank_node_code_actions() && self.supports_shape_validation()
239 }
240
241 fn inlay_types_hint(
242 &self,
243 subject: &Range<usize>,
244 rope: &LineIndex,
245 last_type: Option<&Range<usize>>,
246 types: Vec<Cow<'_, str>>,
247 ) -> Option<crate::lsp_types::InlayHint> {
248 let (label, position) = if let Some(lt) = last_type {
249 {
250 let pos = offset_to_position(lt.end, rope)?;
251 let label = format!(", {}", types.join(", "));
252 (label, pos)
253 }
254 } else {
255 let offset = if rope.char_at_byte(subject.start) == Some('[') {
256 subject.start + 1
257 } else {
258 subject.end
259 };
260
261 {
262 let pos = offset_to_position(offset, rope)?;
263 let label = format!(" a {};", types.join(", "));
264 (label, pos)
265 }
266 };
267
268 Some(crate::lsp_types::InlayHint {
269 position,
270 label: crate::lsp_types::InlayHintLabel::String(label),
271 kind: None,
272 text_edits: None,
273 tooltip: None,
274 padding_left: None,
275 padding_right: None,
276 data: None,
277 })
278 }
279}