Skip to main content

swls_lang_jsonld/
lib.rs

1#![doc(
2    html_logo_url = "https://ajuvercr.github.io/semantic-web-lsp/assets/icons/favicon.png",
3    html_favicon_url = "https://ajuvercr.github.io/semantic-web-lsp/assets/icons/favicon.ico"
4)]
5pub mod cjs;
6
7use std::{borrow::Cow, ops::Range};
8
9use bevy_ecs::{
10    component::Component,
11    observer::On,
12    query::With,
13    resource::Resource,
14    schedule::IntoScheduleConfigs,
15    system::{Commands, Query, Res, RunSystemOnce},
16    world::{CommandQueue, World},
17};
18use components_rs::{
19    components::registry::{resolve_iri_to_url, ComponentRegistry},
20    module_state::ModuleState,
21};
22use oxigraph::model::{GraphName, Literal, NamedNode, Quad};
23use swls_core::{
24    lang::{Lang, LangHelper},
25    lsp_types::{SemanticTokenType, Url},
26    prelude::{goto_definition::GotoDefinitionRequest, *},
27    util::resolve_iri,
28    Started,
29};
30use swls_lang_rdf_base::register_rdf_lang;
31use swls_lang_turtle::lang::parser::TurtleParseError;
32
33pub mod ecs;
34use crate::{
35    ecs::{
36        derive_jsonld_triples, format_jsonld_system, setup_completion, setup_parsing, ContextCache,
37        JsonLdActiveContext,
38    },
39    fs::build_registry,
40};
41
42#[derive(Component, Default)]
43pub struct JsonLdLang;
44
45#[derive(Debug, Default)]
46pub struct JsonLdHelper;
47
48impl LangHelper for JsonLdHelper {
49    /// JSON-LD compact IRIs accept any suffix (`css:dist/Server#port`).
50    fn shorten(&self, prefixes: &Prefixes, iri: &str) -> Option<String> {
51        prefixes.shorten_compact(iri)
52    }
53
54    /// A full IRI is a plain JSON string value.
55    fn write_iri(&self, prefixes: &Prefixes, iri: &str) -> String {
56        self.shorten(prefixes, iri)
57            .unwrap_or_else(|| iri.to_string())
58    }
59
60    fn keyword(&self) -> &[&'static str] {
61        &[
62            "@context",
63            "@id",
64            "@type",
65            "@graph",
66            "@base",
67            "@vocab",
68            "@language",
69            "@value",
70            "@list",
71            "@set",
72            "@reverse",
73            "@index",
74            "@container",
75        ]
76    }
77
78    fn default_position(&self) -> TripleTarget {
79        TripleTarget::Predicate
80    }
81
82    fn unquote<'a>(&self, text: &'a str) -> &'a str {
83        let s = text.strip_prefix('"').unwrap_or(text);
84        s.strip_suffix('"').unwrap_or(s)
85    }
86    fn quote(&self, inp: &str) -> String {
87        format!("\"{}\"", inp)
88    }
89    fn rename_placeholder<'a>(&self, raw: &'a str) -> &'a str {
90        self.unquote(raw)
91    }
92    fn rename_wrap(&self, new_text: &str) -> String {
93        self.quote(new_text)
94    }
95    fn handles_prefix_completion(&self) -> bool {
96        true
97    }
98
99    /// Opt JSON-LD out of the generic prefix-diagnostics system.
100    ///
101    /// `@context` has no syntactic distinction between a namespace prefix and a
102    /// term alias, and terms can be declared via shared/remote contexts or used
103    /// purely to define other terms — none of which the span-based, body-walking
104    /// detector models correctly, so it produces false positives (see the module
105    /// docs on [`swls_core::systems::prefix_diagnostic_helper`]). Undefined-prefix
106    /// detection is moot too: JSON-LD silently drops terms with unknown prefixes,
107    /// so they never reach a triple to flag.
108    fn supports_prefix_diagnostics(&self) -> bool {
109        false
110    }
111
112    /// Extract the prefix name whose `:` was just typed *inside a JSON string*
113    /// (e.g. typing `:` in `"foaf:knows"`), so on-type formatting can splice the
114    /// prefix into `@context`.  Unlike the text-RDF default, the term boundary is
115    /// the opening double-quote of the string.
116    fn prefix_name_at<'a>(&self, source: &'a str, offset: usize) -> Option<&'a str> {
117        let bytes = source.as_bytes();
118        if offset == 0 || offset > source.len() || bytes[offset - 1] != b':' {
119            return None;
120        }
121        let colon = offset - 1;
122
123        let mut start = colon;
124        while start > 0 {
125            let c = bytes[start - 1];
126            if c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-' | b'.') {
127                start -= 1;
128            } else {
129                break;
130            }
131        }
132        if start == colon {
133            return None;
134        }
135        // Must sit inside a JSON string: the char before the name is the opening
136        // quote.  A context *key* like `"foaf":` has the `:` outside the quotes,
137        // so it has no name char before the `:` and is correctly ignored.
138        if start == 0 || bytes[start - 1] != b'"' {
139            return None;
140        }
141        Some(&source[start..colon])
142    }
143
144    fn prefix_edits(
145        &self,
146        source: &str,
147        rope: &LineIndex,
148        name: &str,
149        namespace: &str,
150        _format: swls_core::components::PrefixFormat,
151    ) -> Option<Vec<swls_core::lsp_types::TextEdit>> {
152        crate::ecs::completion::add_to_context(
153            source,
154            rope,
155            crate::ecs::completion::ContextEntry::Prefix { name, namespace },
156        )
157    }
158
159    fn inlay_types_hint(
160        &self,
161        subject: &Range<usize>,
162        rope: &LineIndex,
163        last_type: Option<&Range<usize>>,
164        types: Vec<Cow<'_, str>>,
165    ) -> Option<swls_core::lsp_types::InlayHint> {
166        let (label, position) = if let Some(lt) = last_type {
167            {
168                let pos = offset_to_position(lt.end, rope)?;
169                let label = format!(", {}", types.join(", "));
170                (label, pos)
171            }
172        } else {
173            let offset = if rope.char_at_byte(subject.start) == Some('[') {
174                subject.start + 1
175            } else {
176                subject.end
177            };
178
179            {
180                let pos = offset_to_position(offset + 1, rope)?;
181                let label = if types.len() == 1 {
182                    format!(r#" "@type": "{}";"#, types[0])
183                } else {
184                    format!(
185                        r#" "@type": [ {} ],"#,
186                        types
187                            .into_iter()
188                            .map(|x| format!("\"{}\"", x))
189                            .collect::<Vec<_>>()
190                            .join(", ")
191                    )
192                };
193                (label, pos)
194            }
195        };
196
197        Some(swls_core::lsp_types::InlayHint {
198            position,
199            label: swls_core::lsp_types::InlayHintLabel::String(label),
200            kind: None,
201            text_edits: None,
202            tooltip: None,
203            padding_left: None,
204            padding_right: None,
205            data: None,
206        })
207    }
208}
209
210pub fn setup_world<C: Client + ClientSync + Resource + Clone>(world: &mut World) {
211    register_rdf_lang::<JsonLdLang, JsonLdHelper>(world, &["jsonld"], &[".jsonld"]);
212
213    // For .json files and the "json" language ID, only activate JSON-LD when the
214    // source actually contains "@context" — plain JSON files should be left alone.
215    world.add_observer(
216        |trigger: On<CreateEvent>, mut commands: Commands, query: Query<&Source>| {
217            let e = trigger.event();
218            let is_json = trigger
219                .language_id
220                .as_ref()
221                .map(|l| l == "json")
222                .unwrap_or_default()
223                || e.url.as_str().ends_with(".json");
224            if !is_json {
225                return;
226            }
227            let entity = e.entity;
228            if let Ok(source) = query.get(entity) {
229                if source.0.contains("\"@context\"") {
230                    commands
231                        .entity(entity)
232                        .insert(JsonLdLang)
233                        .insert(DynLang(Box::new(JsonLdHelper)));
234                }
235            }
236        },
237    );
238    world.insert_resource(ContextCache::default());
239    world.insert_resource(Registry::empty());
240    setup_parsing::<C>(world);
241    setup_completion(world);
242
243    world.schedule_scope(FormatLabel, |_, schedule| {
244        schedule.add_systems(format_jsonld_system);
245    });
246
247    world.schedule_scope(Started, |_, schedule| {
248        schedule.add_systems((start_jsonld::<C>,));
249    });
250
251    world.schedule_scope(GotoDefinitionLabel, |_, schedule| {
252        schedule.add_systems(goto_cjs.after(swls_core::systems::get_current_prefix));
253    });
254}
255
256/// Convert a byte offset to an LSP `Position` (line + character).
257fn byte_offset_to_position(source: &str, offset: usize) -> swls_core::lsp_types::Position {
258    let offset = offset.min(source.len());
259    let before = &source[..offset];
260    let line = before.matches('\n').count() as u32;
261    let col = before.rfind('\n').map(|p| offset - p - 1).unwrap_or(offset) as u32;
262    swls_core::lsp_types::Position::new(line, col)
263}
264
265/// Convert a byte-range span to an LSP `Range` using the file's source text.
266fn span_to_lsp_range(source: &str, span: &std::ops::Range<usize>) -> swls_core::lsp_types::Range {
267    swls_core::lsp_types::Range::new(
268        byte_offset_to_position(source, span.start),
269        byte_offset_to_position(source, span.end),
270    )
271}
272
273/// Expand a JSON-LD compact IRI or bare term name using the document's active context.
274///
275/// Handles chains like `css:dist/...` → `npmd:@solid/...dist/...` → `https://...dist/...`
276/// and bare term names like `BearerWebIdExtractor` → `css:dist/...BearerWebIdExtractor`.
277fn expand_iri_with_context(
278    active: &rdf_parsers::jsonld::convert::ActiveContext,
279    value: &str,
280) -> String {
281    expand_iri_inner(active, value, 0)
282}
283
284fn expand_iri_inner(
285    active: &rdf_parsers::jsonld::convert::ActiveContext,
286    value: &str,
287    depth: usize,
288) -> String {
289    if depth > 10 || value.is_empty() || value.starts_with('@') {
290        return value.to_string();
291    }
292    // Already absolute — well-known schemes only, so we don't mistake `css:` for absolute.
293    if value.starts_with("https://")
294        || value.starts_with("http://")
295        || value.starts_with("file://")
296        || value.starts_with("urn:")
297    {
298        return value.to_string();
299    }
300    // Bare term lookup (e.g. "BearerWebIdExtractor")
301    if let Some(def) = active.terms.get(value) {
302        if let Some(iri) = &def.iri {
303            if iri != value {
304                return expand_iri_inner(active, iri, depth + 1);
305            }
306        }
307    }
308    // Compact IRI like "prefix:suffix"
309    if let Some(colon_pos) = value.find(':') {
310        if colon_pos > 0 {
311            let prefix = &value[..colon_pos];
312            let suffix = &value[colon_pos + 1..];
313            if let Some(def) = active.terms.get(prefix) {
314                if let Some(iri) = &def.iri {
315                    let expanded_prefix = expand_iri_inner(active, iri, depth + 1);
316                    return format!("{}{}", expanded_prefix, suffix);
317                }
318            }
319        }
320    }
321    value.to_string()
322}
323
324#[tracing::instrument(skip(query, res))]
325fn goto_cjs(
326    mut query: Query<
327        (
328            &TokenComponent,
329            Option<&TripleComponent>,
330            &Label,
331            &mut GotoDefinitionRequest,
332            Option<&JsonLdActiveContext>,
333            Option<&PrefixComponent>,
334        ),
335        With<JsonLdLang>,
336    >,
337    res: Res<Registry>,
338    config: Res<ServerConfig>,
339) {
340    use swls_core::lsp_types::{Location, Range};
341
342    if config
343        .config
344        .local
345        .is_disabled(Disabled::GotoDefinitionComponentsJs)
346    {
347        return;
348    }
349
350    for (token, triple, label, mut req, active_ctx, prefix) in &mut query {
351        // A real namespace prefix (`"foaf": "…/"`) is handled by the shared
352        // `goto_prefix`, which jumps to the ontology file. Term aliases
353        // (`"Component": "oo:Component"`) are not namespaces and still resolve to
354        // their Components.js definition here.
355        if prefix.map(|p| p.is_namespace()).unwrap_or(false) {
356            continue;
357        }
358        // Only use the expanded IRI from the TripleComponent if the cursor token
359        // actually overlaps the matched term's span.  get_current_triple is lenient
360        // and may fall back to a nearby triple (e.g. the first triple in the
361        // document) when the cursor is on @context or other non-triple content.
362        let triple_term_str = triple.and_then(|tc| {
363            let term_span = match tc.target {
364                TripleTarget::Subject => &tc.triple.subject.span,
365                TripleTarget::Predicate => &tc.triple.predicate.span,
366                TripleTarget::Object => &tc.triple.object.span,
367                TripleTarget::Graph => return None,
368            };
369            let cursor = token.source_span.start;
370            if term_span.start <= cursor && cursor <= term_span.end {
371                tc.term().map(|t| t.as_str())
372            } else {
373                None
374            }
375        });
376        let raw_token = token.text.as_str().trim_matches('"');
377        // When no triple term is available (e.g. cursor in @context), expand compact
378        // IRIs like `css:dist/...` using the document's active context so that
379        // resolve_iri_to_url can match them against import_paths.
380        let context_expanded = if triple_term_str.is_none() {
381            active_ctx.map(|ctx| expand_iri_with_context(&ctx.0, raw_token))
382        } else {
383            None
384        };
385        let st: &str = triple_term_str
386            .or(context_expanded.as_deref())
387            .unwrap_or(raw_token);
388
389        tracing::debug!("Goto definition {:?} {}", triple_term_str, st,);
390
391        // Components: navigate to the component's own source file at the exact @id span.
392        let found_target = if let Some(component) = res.0.components.get(st) {
393            Some((component.source_file.as_str(), component.iri_span.clone()))
394        } else if let Some(module) = res.0.modules.get(st) {
395            Some((module.source_file.as_str(), module.iri_span.clone()))
396        } else if let Some((file, span)) = res.0.parameters.get(st) {
397            Some((file.as_str(), span.clone()))
398        } else {
399            None
400        };
401
402        tracing::debug!(
403            "CJS from {:?} {:?}",
404            found_target,
405            resolve_iri_to_url(st, &res.1.import_paths),
406        );
407        if let Some((file, span)) = found_target {
408            if let Ok(uri) = swls_core::lsp_types::Url::parse(file) {
409                let range = res
410                    .0
411                    .file_sources
412                    .get(file)
413                    .map(|src| span_to_lsp_range(src, &span))
414                    .unwrap_or_default();
415                req.0.push(Location { uri, range });
416                continue;
417            }
418        }
419
420        let iri_no_fragment = st.split('#').next().unwrap_or(st);
421        let resolved = resolve_iri_to_url(iri_no_fragment, &res.1.import_paths)
422            .or_else(|| res.1.context_urls.get(iri_no_fragment).cloned());
423        if let Some(t) = resolved {
424            tracing::debug!("target {}", t.as_str());
425            req.0.push(Location {
426                uri: t,
427                range: Range::default(),
428            });
429            continue;
430        }
431
432        if triple_term_str.is_none() {
433            // Import IRIs: strip any fragment, then resolve to a local file path.
434            let target = resolve_iri(label.as_str(), st);
435            if let Ok(uri) = swls_core::lsp_types::Url::parse(&target) {
436                req.0.push(Location {
437                    uri,
438                    range: Range::default(),
439                });
440                continue;
441            }
442        }
443
444        tracing::debug!("goto_cjs: no definition found for '{}'", st);
445    }
446}
447
448mod fs {
449    use components_rs::{
450        error::{ComponentsJsError, Result},
451        fs::FsDirEntry,
452    };
453    use swls_core::{lsp_types::Url, prelude::Fs};
454
455    use crate::Registry;
456
457    pub struct LocalFs(Fs);
458
459    #[async_trait::async_trait]
460    impl components_rs::fs::Fs for LocalFs {
461        /// Read the entire contents of a file as a UTF-8 string.
462        async fn read_to_string(&self, url: &Url) -> Result<String> {
463            self.0
464                 .0
465                .read_file(url)
466                .await
467                .ok_or(ComponentsJsError::General(format!(
468                    "Failed to read file {}",
469                    url.as_str()
470                )))
471        }
472
473        /// List the immediate children of a directory.
474        async fn read_dir(&self, path: &Url) -> Result<Vec<components_rs::fs::FsDirEntry>> {
475            let entries = self
476                .0
477                 .0
478                .read_dir(path)
479                .await
480                .ok_or(ComponentsJsError::General(format!(
481                    "Failed to read dir {:?}",
482                    path.as_str()
483                )))?;
484            Ok(entries
485                .into_iter()
486                .map(|entry| components_rs::fs::FsDirEntry {
487                    name: entry.name,
488                    path: entry.path,
489                    is_dir: entry.is_dir,
490                })
491                .collect())
492        }
493
494        /// Check whether `path` is a file.
495        async fn is_file(&self, path: &Url) -> bool {
496            self.0 .0.is_file(path).await
497        }
498
499        /// Check whether `path` is a directory.
500        async fn is_dir(&self, path: &Url) -> bool {
501            self.0 .0.is_dir(path).await
502        }
503
504        async fn glob(&self, base: &Url, pattern: &str) -> Result<Vec<FsDirEntry>> {
505            let entries = self
506                .0
507                 .0
508                .glob(base, pattern)
509                .await
510                .ok_or(ComponentsJsError::General(format!(
511                    "Failed to read dir {:?} {}",
512                    base.as_str(),
513                    pattern
514                )))?;
515            Ok(entries
516                .into_iter()
517                .map(|entry| components_rs::fs::FsDirEntry {
518                    name: entry.name,
519                    path: entry.path,
520                    is_dir: entry.is_dir,
521                })
522                .collect())
523        }
524    }
525
526    pub async fn build_registry(fs: &Fs, path: &Url) -> Result<Registry> {
527        use components_rs::components::registry::ComponentRegistry;
528        use components_rs::module_state::ModuleState;
529
530        let fs = LocalFs(fs.clone());
531        let state = ModuleState::build(&fs, path).await?;
532
533        let mut registry = ComponentRegistry::new();
534        registry.register_available_modules(&fs, &state).await?;
535        registry.finalize();
536
537        Ok(Registry(registry, state))
538    }
539}
540
541fn build_cjs_quads(registry: &ComponentRegistry) -> Vec<Quad> {
542    let rdf_type = NamedNode::new_unchecked("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
543    let rdfs_class = NamedNode::new_unchecked("http://www.w3.org/2000/01/rdf-schema#Class");
544    let rdfs_subclass_of =
545        NamedNode::new_unchecked("http://www.w3.org/2000/01/rdf-schema#subClassOf");
546    let rdfs_comment = NamedNode::new_unchecked("http://www.w3.org/2000/01/rdf-schema#comment");
547    let rdf_property =
548        NamedNode::new_unchecked("http://www.w3.org/1999/02/22-rdf-syntax-ns#Property");
549    let rdfs_domain = NamedNode::new_unchecked("http://www.w3.org/2000/01/rdf-schema#domain");
550    let rdfs_range = NamedNode::new_unchecked("http://www.w3.org/2000/01/rdf-schema#range");
551
552    let graph = GraphName::DefaultGraph;
553    let mut quads = Vec::new();
554
555    for comp in registry.components.values() {
556        let iri = NamedNode::new_unchecked(&comp.iri);
557
558        quads.push(Quad::new(
559            iri.clone(),
560            rdf_type.clone(),
561            rdfs_class.clone(),
562            graph.clone(),
563        ));
564
565        if let Some(comment) = &comp.comment {
566            quads.push(Quad::new(
567                iri.clone(),
568                rdfs_comment.clone(),
569                Literal::new_simple_literal(comment.as_str()),
570                graph.clone(),
571            ));
572        }
573
574        for parent in &comp.extends {
575            let parent_node = NamedNode::new_unchecked(parent);
576            quads.push(Quad::new(
577                iri.clone(),
578                rdfs_subclass_of.clone(),
579                parent_node,
580                graph.clone(),
581            ));
582        }
583
584        for param in &comp.parameters {
585            let param_iri = NamedNode::new_unchecked(&param.iri);
586
587            quads.push(Quad::new(
588                param_iri.clone(),
589                rdf_type.clone(),
590                rdf_property.clone(),
591                graph.clone(),
592            ));
593            quads.push(Quad::new(
594                param_iri.clone(),
595                rdfs_domain.clone(),
596                iri.clone(),
597                graph.clone(),
598            ));
599
600            if let Some(range) = &param.range {
601                let range_node = NamedNode::new_unchecked(range);
602                quads.push(Quad::new(
603                    param_iri.clone(),
604                    rdfs_range.clone(),
605                    range_node,
606                    graph.clone(),
607                ));
608            }
609
610            if let Some(comment) = &param.comment {
611                quads.push(Quad::new(
612                    param_iri.clone(),
613                    rdfs_comment.clone(),
614                    Literal::new_simple_literal(comment.as_str()),
615                    graph.clone(),
616                ));
617            }
618        }
619    }
620
621    quads
622}
623
624#[derive(Resource)]
625pub struct Registry(pub ComponentRegistry, pub ModuleState);
626impl Registry {
627    pub fn empty() -> Self {
628        Self(ComponentRegistry::new(), ModuleState::empty())
629    }
630}
631
632#[tracing::instrument(skip(fs, client, config, commands))]
633fn start_jsonld<C: Client + Resource + Clone>(
634    fs: Res<Fs>,
635    client: Res<C>,
636    config: Res<ServerConfig>,
637    commands: Res<CommandSender>,
638) {
639    if !config.config.jsonld.unwrap_or(true) {
640        return;
641    }
642    let fs = fs.clone();
643    tracing::debug!("loading CJS registry, config: {:?}", config);
644    if let Some(ws) = config.workspaces.first().and_then(|x| {
645        if x.uri.as_str().ends_with('/') {
646            Some(x.uri.clone())
647        } else {
648            Url::parse(&format!("{}/", x.uri.as_str())).ok()
649        }
650    }) {
651        tracing::debug!("CJS workspace root: {:?}", ws.as_str());
652        let commands = commands.clone();
653        let thing = async move {
654            tracing::debug!("Starting CJS registry build for {:?}", ws.as_str());
655            if let Ok(reg) = build_registry(&fs, &ws).await {
656                let mut command_queue = CommandQueue::default();
657                command_queue.push(move |world: &mut World| {
658                    let quads = build_cjs_quads(&reg.0);
659                    world.insert_resource(reg);
660
661                    let store_clone = world.get_resource::<swls_core::store::Store>();
662                    //
663                    if let Some(store) = store_clone {
664                        tracing::debug!("Derive store found adding {} triples", quads.len());
665                        let mut loader = store.0.bulk_loader();
666                        let _ = loader.load_quads(quads.into_iter());
667                        let _ = loader.commit();
668                    }
669
670                    let _ = world.run_system_once(derive_jsonld_triples::<C>);
671                });
672                let _ = commands.unbounded_send(command_queue);
673            }
674        };
675        client.spawn(thing);
676    } else {
677        tracing::warn!("No workspace root found, skipping CJS registry build");
678    }
679}
680
681impl Lang for JsonLdLang {
682    type ElementError = TurtleParseError;
683
684    const LANG: &'static str = "jsonld";
685    const TRIGGERS: &'static [&'static str] = &["\"@", "\""];
686    const CODE_ACTION: bool = false;
687    const HOVER: bool = true;
688    const PATTERN: Option<&'static str> = None;
689
690    const LEGEND_TYPES: &'static [SemanticTokenType] = &[
691        semantic_token::BOOLEAN,
692        SemanticTokenType::COMMENT,
693        SemanticTokenType::ENUM_MEMBER,
694        SemanticTokenType::KEYWORD,
695        SemanticTokenType::NAMESPACE,
696        SemanticTokenType::NUMBER,
697        SemanticTokenType::PROPERTY,
698        SemanticTokenType::STRING,
699    ];
700
701    fn semantic_token_type(kind: rowan::SyntaxKind) -> Option<SemanticTokenType> {
702        use rdf_parsers::jsonld::parser::SyntaxKind as SK;
703        let k = kind.0;
704        if k == SK::Comment as u16 {
705            Some(SemanticTokenType::COMMENT)
706        } else if k == SK::StringToken as u16 {
707            Some(SemanticTokenType::STRING)
708        } else if k == SK::JsonNumber as u16 {
709            Some(SemanticTokenType::NUMBER)
710        } else if k == SK::TrueLit as u16 || k == SK::FalseLit as u16 || k == SK::NullLit as u16 {
711            Some(semantic_token::BOOLEAN)
712        } else {
713            None
714        }
715    }
716
717    fn semantic_token_spans(
718        kind: rowan::SyntaxKind,
719        span: std::ops::Range<usize>,
720        text: &str,
721    ) -> Vec<(SemanticTokenType, std::ops::Range<usize>)> {
722        // Keywords (`"@id"`, `"@type"`, …) are the one thing only the lexer knows.
723        if text.get(span.start + 1..span.start + 2) == Some("@") {
724            return vec![(SemanticTokenType::KEYWORD, span)];
725        }
726        // Everything term-shaped — compact/full IRIs and `@context` prefix keys —
727        // is coloured from the parsed model (`semantic_tokens` / `add_term`), which
728        // knows the prefix/local split and the resolved IRI. The lexer only sees an
729        // opaque JSON string, so it must not guess; it just supplies the STRING /
730        // NUMBER / BOOLEAN base for real literals, which the model overrides for the
731        // strings that are actually IRIs.
732        Self::semantic_token_type(kind)
733            .map(|t| vec![(t, span)])
734            .unwrap_or_default()
735    }
736}