Skip to main content

swls_lang_jsonld/ecs/
mod.rs

1use std::{collections::HashMap, future::Future, pin::Pin, sync::Arc};
2
3use bevy_ecs::{
4    prelude::*, schedule::ScheduleLabel, system::RunSystemOnce as _, world::CommandQueue,
5};
6use futures::{channel, SinkExt};
7use rdf_parsers::{
8    jsonld::{
9        convert::{
10            convert_with_loader, parse_jsonld_for_context, ActiveContext, ContextLoader, JsonLdVal,
11        },
12        parser::{Lang, Rule, SyntaxKind},
13    },
14    IncrementalBias, PrevParseInfo,
15};
16use rowan::{GreenNode, NodeOrToken};
17use swls_core::{
18    lsp_types::{request::InlayHintRefreshRequest, TextDocumentItem, Url},
19    prelude::*,
20};
21use swls_lang_turtle::{ecs::parse::derive_triples_system, lang::parser::TurtleParseError};
22use tracing::instrument;
23
24use crate::{cjs, JsonLdLang, Registry};
25
26pub mod completion;
27pub use completion::setup_completion;
28
29/// Caches remotely-fetched `@context` documents so they survive across parse ticks.
30#[derive(Resource, Default)]
31pub struct ContextCache(pub HashMap<String, String>);
32
33/// ECS component that carries the accumulated JSON-LD active context for a document.
34///
35/// Populated by [`parse_jsonld_system`] and consumed by JSON-LD-specific
36/// completion systems to offer term-alias and prefix-based completions.
37#[derive(Component, Debug, Default, Clone)]
38pub struct JsonLdActiveContext(pub ActiveContext);
39
40/// Resolves `@context` URLs for a single document parse.
41///
42/// Resolution order:
43/// 1. Per-invocation [`local_cache`](Self::local_cache) — avoids re-fetching
44///    the same URL twice within one document's context chain.
45/// 2. [`cjs_contexts`](Self::cjs_contexts) — the pre-loaded CJS context map from
46///    [`ModuleState`].  Returning the value here avoids the full ECS round-trip
47///    (spawn entity → run `FetchLabel` → wait for oneshot channel) for the
48///    common case where every `.jsonld` file references the same CJS context URL.
49/// 3. ECS world / network fallback — for contexts not known at startup.
50struct WorldContextLoader {
51    sender: CommandSender,
52    /// Pre-loaded CJS contexts shared from [`ModuleState::contexts`].
53    cjs_contexts: Arc<HashMap<String, JsonLdVal>>,
54    /// Cache of already-resolved contexts within this loader's lifetime.
55    local_cache: HashMap<String, JsonLdVal>,
56}
57
58impl ContextLoader for WorldContextLoader {
59    fn load_val<'a>(
60        &'a mut self,
61        url: &'a str,
62    ) -> Pin<Box<dyn Future<Output = Option<rdf_parsers::jsonld::convert::JsonLdVal>> + 'a>> {
63        // 1. Per-invocation cache.
64        if let Some(val) = self.local_cache.get(url) {
65            let val = val.clone();
66            return Box::pin(std::future::ready(Some(val)));
67        }
68
69        // 2. CJS contexts — direct map lookup, no ECS round-trip needed.
70        if let Some(result) = self.cjs_contexts.get(url).map(|ctx_doc| {
71            if let Some(ctx) = ctx_doc.get("@context") {
72                ctx.clone()
73            } else {
74                ctx_doc.clone()
75            }
76        }) {
77            self.local_cache.insert(url.to_string(), result.clone());
78            return Box::pin(std::future::ready(Some(result)));
79        }
80
81        // 3. ECS world / network fallback.
82        tracing::debug!("context loader load val {}", url);
83        let cs = self.sender.clone();
84        let url = url.to_string();
85        Box::pin(async move {
86            let (sender, receiver) = futures::channel::oneshot::channel::<Result<String, _>>();
87            let mut command_queue = CommandQueue::default();
88            let url2 = url.clone();
89            tracing::debug!("Trying to find context {}", url.as_str());
90            command_queue.push(move |world: &mut World| {
91                world.spawn(ContextRequest {
92                    url: url2,
93                    on_ready: Some(sender),
94                });
95                world.run_schedule(FetchLabel);
96            });
97
98            let _ = cs.unbounded_send(command_queue);
99
100            let v = receiver.await.ok()?;
101            tracing::debug!("context loader got response for {}", url);
102            match v {
103                Ok(s) => parse_jsonld_for_context(&s),
104                Err(x) => {
105                    if let JsonLdVal::Object(members, _) = &x {
106                        if let Some((_, _, _, ctx)) =
107                            members.iter().find(|(k, _, _, _)| k == "@context")
108                        {
109                            return Some(ctx.clone());
110                        }
111                    }
112
113                    Some(x)
114                }
115            }
116        })
117    }
118    fn load<'a>(&'a mut self, url: &'a str) -> Pin<Box<dyn Future<Output = Option<String>> + 'a>> {
119        tracing::debug!("context loader load string {}", url);
120        Box::pin(std::future::ready(None))
121    }
122}
123
124pub fn setup_parsing<C: Client + Resource + Clone>(world: &mut World) {
125    use swls_core::feature::parse::*;
126    world.schedule_scope(ParseLabel, |_, schedule| {
127        schedule.add_systems((
128            parse_jsonld_system::<C>,
129            derive_jsonld_prefixes
130                .after(parse_jsonld_system::<C>)
131                .before(prefixes),
132            derive_triples_system::<JsonLdLang>
133                .after(parse_jsonld_system::<C>)
134                .before(triples),
135        ));
136    });
137
138    let mut schedule = bevy_ecs::schedule::Schedule::new(FetchLabel);
139    schedule.add_systems((
140        cjs::cjs_loader.before(fetch_from_world),
141        fetch_from_world,
142        fetch_from_web::<C>.after(fetch_from_world),
143        return_empty.after(fetch_from_web::<C>),
144    ));
145    world.add_schedule(schedule);
146}
147
148/// Indicates that something should be fetched
149#[derive(ScheduleLabel, Clone, Eq, PartialEq, Debug, Hash)]
150pub struct FetchLabel;
151
152fn return_empty(requests: Query<(Entity, &mut ContextRequest)>, mut commander: Commands) {
153    for (e, mut r) in requests {
154        if let Some(sender) = r.on_ready.take() {
155            tracing::debug!("loader sending empty {}", r.url);
156            let _ = sender.send(Result::Ok(String::new()));
157        } else {
158            tracing::debug!("loader cannot send empty {}", r.url);
159        }
160        commander.entity(e).despawn();
161    }
162}
163
164fn fetch_from_world(
165    mut requests: Query<(Entity, &mut ContextRequest)>,
166    documents: Query<(&Label, Option<&Wrapped<JsonLdVal>>, Option<&Source>)>,
167    mut commander: Commands,
168) {
169    // NOTE: do NOT call run_schedule(ParseLabel) here even when a
170    // Wrapped<JsonLdVal> context entity is found.  The value has already been
171    // delivered to the waiting async task via the oneshot channel; that task
172    // will call run_schedule(ParseLabel) itself when it finishes inserting the
173    // Element.  Calling ParseLabel here is premature and was the source of a
174    // cascading loop: the persistent context entity (Wrapped<JsonLdVal>,
175    // created by cjs_loader and never despawned) would be found again by every
176    // subsequent load_val call, each triggering another ParseLabel which could
177    // re-fire parse_jsonld_system, spawning more tasks that each called
178    // load_val again.  With the WorldContextLoader now returning CJS contexts
179    // directly from cjs_contexts (no ContextRequest spawned), this code path
180    // is unreachable for CJS contexts.  Removing the ParseLabel trigger here
181    // closes the loop for any future code that might recreate the pattern.
182    for (entity, mut request) in requests.iter_mut() {
183        for (labels, jsonld_val, s) in documents {
184            if labels.as_str() == request.url.as_str() {
185                if let Some(sender) = request.on_ready.take() {
186                    let o = match (jsonld_val, s) {
187                        (Some(val), _) => {
188                            let char_count = format!("{:?}", val).len();
189                            tracing::debug!(
190                                "loader fetch_from_world sent {} (found val {} {})",
191                                request.url,
192                                jsonld_val.is_some(),
193                                char_count
194                            );
195                            sender.send(Result::Err(val.as_ref().clone()))
196                        }
197                        (_, Some(source)) => {
198                            tracing::debug!(
199                                "loader fetch_from_world sent {} (found val false {})",
200                                request.url,
201                                source.len()
202                            );
203                            sender.send(Result::Ok(source.to_string()))
204                        }
205                        _ => {
206                            tracing::debug!(
207                                "loader fetch_from_world sent {} (empty string)",
208                                request.url,
209                            );
210                            sender.send(Result::Ok("".to_string()))
211                        }
212                    };
213                    tracing::debug!("Sent successful {:?}", o);
214                }
215                if let Ok(mut e) = commander.get_entity(entity) {
216                    e.despawn();
217                }
218            }
219        }
220    }
221}
222
223fn fetch_from_web<C: Client + Resource + Clone>(
224    mut requests: Query<(&mut ContextRequest,), Added<ContextRequest>>,
225    sender: Res<CommandSender>,
226    client: Res<C>,
227    fs: Res<Fs>,
228) {
229    for (r,) in requests.iter_mut() {
230        let client_clone = client.as_ref().clone();
231        let url = r.url.to_string();
232
233        let Ok(label) = Url::parse(&url) else {
234            continue;
235        };
236        let sender = sender.clone();
237        if label.scheme().starts_with("http") {
238            client.spawn(async move {
239                if let Ok(resp) = client_clone.fetch(&url, &HashMap::new()).await {
240                    let mut cq = CommandQueue::default();
241                    cq.push(move |world: &mut World| {
242                        if find_document(world, &label).is_none() {
243                            world.spawn((Source(resp.body), Label(label)));
244                            let _ = world.run_system_once(derive_jsonld_triples::<C>);
245                        }
246                    });
247                    let _ = sender.unbounded_send(cq);
248                }
249            });
250        } else {
251            let fs = fs.clone();
252            client.spawn(async move {
253                if let Some(resp) = fs.0.read_file(&label).await {
254                    let mut cq = CommandQueue::default();
255                    cq.push(move |world: &mut World| {
256                        if find_document(world, &label).is_none() {
257                            let item = TextDocumentItem {
258                                version: 1,
259                                uri: label.clone(),
260                                language_id: String::from("turtle"),
261                                text: String::new(),
262                            };
263                            let e = world
264                                .spawn((
265                                    RopeC(LineIndex::new(&resp)),
266                                    Source(resp),
267                                    Label(label.clone()),
268                                    Wrapped(item),
269                                    Types(HashMap::new()),
270                                ))
271                                .id();
272
273                            world.trigger(CreateEvent {
274                                url: label,
275                                language_id: Some("jsonld".to_string()),
276                                entity: e,
277                            });
278                            tracing::debug!("Found local file, rerunning the deriving {}", url);
279                            let _ = world.run_system_once(derive_jsonld_triples::<C>);
280                        }
281                    });
282                    let _ = sender.unbounded_send(cq);
283                }
284            });
285        }
286    }
287}
288
289#[derive(bevy_ecs::prelude::Component)]
290pub struct ContextRequest {
291    pub url: String,
292    pub on_ready: Option<channel::oneshot::Sender<Result<String, JsonLdVal>>>,
293}
294
295fn extract_jsonld_cst_tokens(node: &rowan::SyntaxNode<Lang>) -> Vec<Spanned<rowan::SyntaxKind>> {
296    let mut tokens = Vec::new();
297    for not in node.descendants_with_tokens() {
298        if let NodeOrToken::Token(t) = not {
299            if t.kind() == SyntaxKind::WhiteSpace {
300                continue;
301            }
302            let range = t.text_range();
303            let span = usize::from(range.start())..usize::from(range.end());
304            tokens.push(spanned(rowan::SyntaxKind(t.kind() as u16), span));
305        }
306    }
307    tokens
308}
309
310fn collect_errors(node: &rowan::SyntaxNode<Lang>) -> Vec<TurtleParseError> {
311    let mut errors = Vec::new();
312    let mut stack = vec![node.clone()];
313    while let Some(current) = stack.pop() {
314        for child in current.children_with_tokens() {
315            match child {
316                NodeOrToken::Node(n) => {
317                    if n.kind() == SyntaxKind::Error {
318                        let range = rdf_parsers::effective_error_span::<Lang>(&n);
319                        let msg = n
320                            .parent()
321                            .map(|p| format!("Expected: {:?}", p.kind()))
322                            .unwrap_or_else(|| format!("Unexpected: {}", n.text()));
323                        errors.push(TurtleParseError { range, msg });
324                    } else {
325                        stack.push(n);
326                    }
327                }
328                NodeOrToken::Token(t) => {
329                    if t.kind() == SyntaxKind::Error {
330                        let r = t.text_range();
331                        errors.push(TurtleParseError {
332                            range: r.start().into()..r.end().into(),
333                            msg: format!("Unexpected: {}", t.text()),
334                        });
335                    }
336                }
337            }
338        }
339    }
340    errors
341}
342
343/// Re-derive JSON-LD triples for every open JSON-LD document.
344///
345/// All documents are processed sequentially inside **one** spawned task.  A
346/// single [`CommandQueue`] is sent at the end that inserts all derived elements
347/// at once and runs [`ParseLabel`] exactly once.  This means
348/// `derive_triples_system`, `load_store`, and `derive_ontologies` each execute
349/// once for the whole batch instead of once per document — the dominant cost
350/// during initial CJS workspace loading.
351pub fn derive_jsonld_triples<C: Client + Resource + Clone>(
352    query: Query<(Entity, &Wrapped<GreenNode>, &Label, &Source), With<JsonLdLang>>,
353    sender: Res<CommandSender>,
354    client: Res<C>,
355    registry: Res<Registry>,
356) {
357    // Collect owned data up front so we can move it into the async block.
358    let items: Vec<(Entity, rowan::GreenNode, String, usize)> = query
359        .iter()
360        .map(|(e, gn, label, source)| (e, gn.0.clone(), label.0.to_string(), source.0.len()))
361        .collect();
362
363    if items.is_empty() {
364        return;
365    }
366
367    let cjs_contexts = registry.1.contexts.clone();
368    let mut sender_clone = sender.clone();
369    let c2 = client.clone();
370
371    client.spawn_local(move || async move {
372        let mut all_results: Vec<(Entity, Element, JsonLdActiveContext)> =
373            Vec::with_capacity(items.len());
374
375        for (e, gn, base, span_len) in items {
376            let mut loader = WorldContextLoader {
377                sender: sender_clone.clone(),
378                cjs_contexts: cjs_contexts.clone(),
379                local_cache: HashMap::new(),
380            };
381            let syntax = rowan::SyntaxNode::new_root(gn);
382            let (jsonld_model, ctx) = convert_with_loader(&syntax, &mut loader, Some(base)).await;
383
384            tracing::debug!("{} triples", jsonld_model.triples.len());
385            let element = Element(spanned(jsonld_model, 0..span_len));
386            all_results.push((e, element, JsonLdActiveContext(ctx)));
387        }
388
389        // Insert all elements and run ParseLabel once so derive_ontologies
390        // only executes once regardless of how many documents were processed.
391        let mut command_queue = CommandQueue::default();
392        command_queue.push(move |world: &mut World| {
393            for (e, element, ctx) in all_results {
394                world.entity_mut(e).insert((element, ctx));
395            }
396            world.run_schedule(ParseLabel);
397        });
398        let _ = sender_clone.0.send(command_queue).await;
399        c2.send_request::<InlayHintRefreshRequest>(()).await;
400    });
401}
402
403#[instrument(skip(query, sender, commands, client, registry))]
404fn parse_jsonld_system<C: Client + Resource + Clone>(
405    query: Query<
406        (Entity, &Source, &Label, Option<&Wrapped<PrevParseInfo>>),
407        (Changed<Source>, With<JsonLdLang>, With<Open>),
408    >,
409    mut commands: Commands,
410    sender: Res<CommandSender>,
411    client: Res<C>,
412    registry: Res<Registry>,
413    config: Res<ServerConfig>,
414) {
415    if !config.config.jsonld.unwrap_or(true) {
416        return;
417    }
418    let cjs_contexts = registry.1.contexts.clone();
419
420    for (entity, source, label, prev) in &query {
421        let (parse, new_prev) = rdf_parsers::parse_incremental(
422            Rule::new(SyntaxKind::JsonldDoc),
423            source.0.as_str(),
424            prev.map(|x| &x.0),
425            IncrementalBias::default(),
426        );
427        commands.entity(entity).insert(Wrapped(new_prev));
428
429        let syntax = parse.syntax::<Lang>();
430        let errors = collect_errors(&syntax);
431        let cst_tokens = extract_jsonld_cst_tokens(&syntax);
432
433        let gn = parse.green_node.clone();
434        let base = label.0.to_string();
435        let span = 0..source.0.len();
436        let e = entity;
437        let mut sender = sender.clone();
438        let cjs_contexts = cjs_contexts.clone();
439        client.spawn_local(move || async move {
440            let mut loader = WorldContextLoader {
441                sender: sender.clone(),
442                cjs_contexts,
443                local_cache: HashMap::new(),
444            };
445            let syntax = rowan::SyntaxNode::new_root(gn.clone());
446            let (jsonld_model, ctx) = convert_with_loader(&syntax, &mut loader, Some(base)).await;
447
448            tracing::debug!("{} triples", jsonld_model.triples.len());
449
450            let element = Element(spanned(jsonld_model, span));
451
452            let mut command_queue = CommandQueue::default();
453            command_queue.push(move |world: &mut World| {
454                world
455                    .entity_mut(e)
456                    .insert((element, JsonLdActiveContext(ctx)));
457                // Re-run ParseLabel so that derive_triples_system and
458                // derive_jsonld_prefixes see the newly-inserted element
459                // (they react to Changed<Element> filtered by With<JsonLdLang>).
460                // Without
461                // this, those systems only fire on the *next* user edit.
462                world.run_schedule(ParseLabel);
463            });
464            let _ = sender.0.send(command_queue).await;
465        });
466
467        if errors.is_empty() {
468            commands
469                .entity(entity)
470                .insert((
471                    Errors(errors),
472                    CstTokens(cst_tokens),
473                    Wrapped(parse.green_node),
474                ))
475                .remove::<Dirty>();
476        } else {
477            commands.entity(entity).insert((
478                Errors(errors),
479                CstTokens(cst_tokens),
480                Wrapped(parse.green_node),
481                Dirty,
482            ));
483        }
484    }
485}
486
487/// Derives a [`Prefixes`] component for a JSON-LD document from the prefixes
488/// declared in its `@context` (e.g. `"foaf": "http://xmlns.com/foaf/0.1/"`).
489///
490/// This mirrors the equivalent system in `lang-turtle` and is required so that
491/// generic completion and hover systems that rely on [`Prefixes`] work for
492/// JSON-LD documents.
493fn derive_jsonld_prefixes(
494    query: Query<(Entity, &Label, &Element), (Changed<Element>, With<JsonLdLang>)>,
495    mut commands: Commands,
496) {
497    use swls_lang_rdf_base::traits::NamedNodeExt;
498
499    for (entity, url, turtle) in &query {
500        let prefixes: Vec<_> = turtle
501            .prefixes
502            .iter()
503            .flat_map(|prefix| {
504                let expanded = prefix.value.value().expand(turtle.value())?;
505                let parsed_url = swls_core::lsp_types::Url::parse(&expanded).ok()?;
506                Some(Prefix {
507                    url: parsed_url,
508                    prefix: prefix.prefix.value().clone(),
509                })
510            })
511            .collect();
512
513        let base = turtle
514            .base
515            .as_ref()
516            .and_then(|b| {
517                b.0 .1
518                    .value()
519                    .expand(turtle.value())
520                    .and_then(|x| swls_core::lsp_types::Url::parse(&x).ok())
521            })
522            .unwrap_or_else(|| url.0.clone());
523
524        commands.entity(entity).insert(Prefixes(prefixes, base));
525    }
526}
527
528pub(crate) fn format_jsonld_system(
529    mut query: Query<(&RopeC, &Wrapped<GreenNode>, &mut FormatRequest), With<JsonLdLang>>,
530    config: Res<ServerConfig>,
531) {
532    use swls_core::lsp_types::{Position, Range};
533    if !config.config.local.format.jsonld() {
534        tracing::debug!("JSON-LD formatting disabled by config");
535        return;
536    }
537    for (source, node, mut request) in &mut query {
538        if request.0.is_some() {
539            tracing::debug!("Didn't format with the jsonld format system, already formatted");
540            continue;
541        }
542        tracing::debug!("Formatting with turtle format system");
543
544        let root = rowan::SyntaxNode::new_root(node.0.clone());
545
546        let formatted = rdf_parsers::jsonld::format::format(&root, 80);
547
548        request.0 = Some(vec![swls_core::lsp_types::TextEdit::new(
549            Range::new(
550                Position::new(0, 0),
551                Position::new(source.0.len_lines() as u32 + 1, 0),
552            ),
553            formatted,
554        )]);
555    }
556}
557
558#[cfg(test)]
559mod id_highlight {
560    use swls_core::feature::semantic::{HighlightRequest, TokenTypesComponent};
561    use swls_core::feature::{ParseLabel, SemanticLabel};
562    use swls_core::lsp_types::SemanticTokenType;
563    use swls_core::prelude::*;
564    use swls_test_utils::{create_file, setup_world, TestClient};
565
566    /// A prefixed IRI must be highlighted the same way whether it appears as a
567    /// subject `"@id": "ex:obs1"` or as an object reference `{ "@id": "ex:x" }`:
568    /// `prefix:` as NAMESPACE and the local part as an IRI colour — never STRING.
569    #[test]
570    fn id_iris_consistently_highlighted_not_string() {
571        let (mut world, _) = setup_world(TestClient::new(), crate::setup_world::<TestClient>);
572        let src = "{\n  \"@context\": { \"ex\": \"https://example.org/\", \"sosa\": \"http://www.w3.org/ns/sosa/\" },\n  \"@graph\": [\n    { \"@type\": \"sosa:Message\", \"sosa:primaryTopic\": { \"@id\": \"ex:obs1\" } },\n    { \"@id\": \"ex:obs1\", \"sosa:isObservedBy\": { \"@id\": \"ex:sensor-1\" } }\n  ]\n}";
573        let entity = create_file(&mut world, src, "http://example.com/ns#", "jsonld", Open);
574        world.run_schedule(ParseLabel);
575        let client = world.resource::<TestClient>().clone();
576        futures::executor::block_on(client.await_futures(|| world.run_schedule(swls_core::Tasks)));
577        world.entity_mut(entity).insert(HighlightRequest(vec![]));
578        world.run_schedule(SemanticLabel);
579
580        let ttc = world
581            .entity(entity)
582            .get::<TokenTypesComponent>()
583            .expect("ttc");
584        let mut ts: Vec<Option<SemanticTokenType>> = vec![None; src.len()];
585        for s in &ttc.0 {
586            for j in s.span().clone() {
587                if j < ts.len() {
588                    ts[j] = Some(s.value().clone());
589                }
590            }
591        }
592        let ty_at = |b: usize| ts[b].as_ref().map(|t| t.as_str().to_string());
593
594        // Check the full `"prefix:local"` token, quotes included, for every
595        // occurrence — subject and object alike.  This pins down the byte
596        // boundaries so a one-off (the parser's `idx` points at the opening quote)
597        // is caught.
598        let check = |iri: &str| {
599            let quoted = format!("\"{iri}\"");
600            let colon = iri.find(':').unwrap();
601            for (q, _) in src.match_indices(&quoted) {
602                let open = q; // opening quote
603                let content = q + 1; // first char of the IRI
604                let close = q + 1 + iri.len(); // closing quote
605                assert_ne!(
606                    ty_at(open).as_deref(),
607                    Some("namespace"),
608                    "opening quote of {quoted} at {open} must not be coloured as the IRI"
609                );
610                // `prefix:` (through the ':') is NAMESPACE.
611                for b in content..content + colon + 1 {
612                    assert_eq!(
613                        ty_at(b).as_deref(),
614                        Some("namespace"),
615                        "{quoted}: byte {b} ({:?}) should be NAMESPACE",
616                        &src[b..b + 1]
617                    );
618                }
619                // The whole local part — including the last char — is enumMember.
620                for b in content + colon + 1..close {
621                    assert_eq!(
622                        ty_at(b).as_deref(),
623                        Some("enumMember"),
624                        "{quoted}: byte {b} ({:?}) should be enumMember (not string)",
625                        &src[b..b + 1]
626                    );
627                }
628            }
629        };
630        check("ex:obs1");
631        check("ex:sensor-1");
632    }
633
634    /// The model is authoritative for term-shaped content while the lexer keeps
635    /// keywords: `@context` prefix keys are NAMESPACE, keyword tokens (`@id`,
636    /// `@type`) stay KEYWORD (even though `@type` is the `rdf:type` predicate in
637    /// the model), a compact-IRI value splits NAMESPACE/enumMember, and a plain
638    /// string literal stays STRING (the lexer's job, not overwritten).
639    #[test]
640    fn context_keywords_and_literals_coloured_correctly() {
641        let (mut world, _) = setup_world(TestClient::new(), crate::setup_world::<TestClient>);
642        let src = "{\n  \"@context\": { \"ex\": \"https://example.org/\" },\n  \"@id\": \"ex:alice\",\n  \"@type\": \"ex:Person\",\n  \"ex:label\": \"Alice\"\n}";
643        let entity = create_file(&mut world, src, "http://example.com/ns#", "jsonld", Open);
644        world.run_schedule(ParseLabel);
645        let client = world.resource::<TestClient>().clone();
646        futures::executor::block_on(client.await_futures(|| world.run_schedule(swls_core::Tasks)));
647        world.entity_mut(entity).insert(HighlightRequest(vec![]));
648        world.run_schedule(SemanticLabel);
649
650        let ttc = world
651            .entity(entity)
652            .get::<TokenTypesComponent>()
653            .expect("ttc");
654        let mut ts: Vec<Option<SemanticTokenType>> = vec![None; src.len()];
655        for s in &ttc.0 {
656            for j in s.span().clone() {
657                if j < ts.len() {
658                    ts[j] = Some(s.value().clone());
659                }
660            }
661        }
662        // Assert every byte of `needle`'s single occurrence has type `expected`.
663        let all = |needle: &str, expected: &str| {
664            let q = src
665                .find(needle)
666                .unwrap_or_else(|| panic!("missing {needle:?}"));
667            for b in q..q + needle.len() {
668                assert_eq!(
669                    ts[b].as_ref().map(|t| t.as_str()),
670                    Some(expected),
671                    "{needle:?} byte {b} ({:?})",
672                    &src[b..b + 1]
673                );
674            }
675        };
676
677        all("\"ex\"", "namespace"); // @context prefix key (from the model)
678        all("\"@id\"", "keyword"); // keyword kept by the lexer
679        all("\"@type\"", "keyword"); // keyword, not the rdf:type predicate colour
680        all("\"Alice\"", "string"); // plain literal, lexer's job, not overwritten
681        all("\"https://example.org/\"", "string"); // @context IRI value stays a literal
682    }
683}