qlue-ls 3.2.1

A language server for SPARQL
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
use futures::lock::Mutex;
use ll_sparql_parser::{
    SyntaxNode,
    ast::{AstNode, Path, Prologue, QueryUnit},
    syntax_kind::SyntaxKind,
};
use std::rc::Rc;
use tera::Context;
use text_size::TextSize;

use crate::{
    server::{
        Server,
        configuration::BackendConfiguration,
        lsp::{
            Command, CompletionItem, CompletionItemKind, CompletionItemLabelDetails,
            CompletionList,
            textdocument::{Range, TextEdit},
        },
        sparql_operations::execute_query,
    },
    sparql::results::RDFTerm,
};

use super::{environment::CompletionEnvironment, error::CompletionError};

/// Returns true if the label matches the search term as a case-insensitive prefix.
/// If no search term is provided (or it's empty), returns true to show all completions.
pub(super) fn matches_search_term(label: &str, search_term: Option<&str>) -> bool {
    match search_term {
        // NOTE: byte-wise ASCII comparison, avoids allocating uppercased copies;
        // slicing the bytes instead of the str avoids char-boundary panics
        Some(term) if !term.is_empty() => {
            label.len() >= term.len()
                && label.as_bytes()[..term.len()].eq_ignore_ascii_case(term.as_bytes())
        }
        _ => true,
    }
}

pub(super) type CompletionTemplate = crate::server::configuration::CompletionTemplate;

pub(super) async fn dispatch_completion_query(
    server_rc: Rc<Mutex<Server>>,
    environment: &CompletionEnvironment,
    template_context: Context,
    completion_template: CompletionTemplate,
    trigger_on_accept: bool,
) -> Result<CompletionList, CompletionError> {
    match environment.backend.as_ref() {
        Some(backend) => {
            let query_unit = QueryUnit::cast(environment.truncated_tree.clone()).ok_or(
                CompletionError::Resolve("Could not cast root to QueryUnit".to_string()),
            )?;
            Ok(to_completion_items(
                fetch_online_completions(
                    server_rc.clone(),
                    &query_unit,
                    backend,
                    &format!("{}-{}", backend.name, completion_template),
                    template_context,
                )
                .await?,
                environment.replace_range.clone(),
                trigger_on_accept.then_some("triggerNewCompletion"),
                server_rc.lock().await.settings.completion.result_size_limit,
                environment.search_term.as_deref(),
            ))
        }
        _ => {
            tracing::info!("No Backend for completion query found");
            Err(CompletionError::Resolve("No Backend defined".to_string()))
        }
    }
}

pub(super) struct InternalCompletionItem {
    label: String,
    detail: Option<String>,
    value: String,
    _filter_text: Option<String>,
    score: Option<usize>,
    import_edit: Option<TextEdit>,
}

pub(super) async fn fetch_online_completions(
    server_rc: Rc<Mutex<Server>>,
    query_unit: &QueryUnit,
    backend: &BackendConfiguration,
    query_template: &str,
    mut query_template_context: Context,
) -> Result<Vec<InternalCompletionItem>, CompletionError> {
    let (url, query, timeout_ms, method) = {
        let server = server_rc.lock().await;
        query_template_context.insert("limit", &server.settings.completion.result_size_limit);
        query_template_context.insert("offset", &0);
        let query = server
            .tools
            .tera
            .render(query_template, &query_template_context)
            .map_err(|err| CompletionError::Template(query_template.to_string(), err))?;

        let url = backend.url.clone();
        let timeout_ms = server.settings.completion.timeout_ms;
        let method = server.state.get_backend_request_method(&backend.name);
        (url, query, timeout_ms, method)
    };

    tracing::debug!("Completion Query: \"{query_template}\"\n{query}");

    let result = execute_query(
        server_rc.clone(),
        url,
        query,
        None,
        None,
        Some(timeout_ms),
        method,
        None,
        0,
        false,
    )
    .await
    .map_err(|err| match err {
        crate::server::sparql_operations::SparqlRequestError::Timeout => {
            CompletionError::Request("Completion query timed out".to_string())
        }
        crate::server::sparql_operations::SparqlRequestError::Connection(_err) => {
            CompletionError::Request("Completion query failed, connection errored".to_string())
        }
        crate::server::sparql_operations::SparqlRequestError::Canceled(_err) => {
            CompletionError::Request("Completion query was canceled".to_string())
        }
        crate::server::sparql_operations::SparqlRequestError::Http(err) => {
            CompletionError::Request(format!(
                "Completion query failed with status {} {}",
                err.status, err.status_text
            ))
        }
        crate::server::sparql_operations::SparqlRequestError::Deserialization(msg) => {
            CompletionError::Request(msg)
        }
        crate::server::sparql_operations::SparqlRequestError::QLeverException(exception) => {
            CompletionError::Request(exception.exception)
        }
    })?
    .expect("Non-lazy request should always return a result.");
    tracing::info!("Result size: {}", result.results.bindings.len());

    let mut server = server_rc.lock().await;
    result
        .results
        .bindings
        .into_iter()
        .map(|binding| {
            let rdf_term = binding.get("qls_entity").ok_or_else(|| {
                CompletionError::Request(
                    "Completion query result is missing the `qls_entity` binding".to_string(),
                )
            })?;
            let (value, import_edit) =
                render_rdf_term(&server, query_unit, rdf_term, &backend.name);
            let label = binding
                .get("qls_label")
                .map_or(String::new(), |rdf_term| rdf_term.value().to_string());
            let detail = binding
                .get("qls_alias")
                .map(|rdf_term: &RDFTerm| rdf_term.value().to_string());
            let score = binding
                .get("qls_count")
                .and_then(|rdf_term: &RDFTerm| rdf_term.value().parse().ok());
            // NOTE: This is the text the in editor filter uses.
            // If a compressed IRI is used as search term i.e. "wdt:p" the expanded iri is used as
            // filter text. Otherwise the label and detail is used as filter text.
            // This is currently not used, but should be redone at some point
            let filter_text = query_template_context
                .get("search_term_uncompressed")
                .is_some()
                .then_some(value.to_string())
                .or((!label.is_empty()).then_some(format!(
                    "{}{}",
                    label,
                    detail.as_ref().unwrap_or(&String::new())
                )))
                .or(Some(rdf_term.to_string()));
            if !label.is_empty() {
                server
                    .state
                    .label_memory
                    .insert(value.clone(), label.clone());
            }
            Ok(InternalCompletionItem {
                label,
                detail,
                value,
                _filter_text: filter_text,
                score,
                import_edit,
            })
        })
        .collect()
}

fn render_rdf_term(
    server: &Server,
    query_unit: &QueryUnit,
    rdf_term: &RDFTerm,
    backend_name: &str,
) -> (String, Option<TextEdit>) {
    match rdf_term {
        RDFTerm::Uri { value, curie: _ } => match server.shorten_uri(value, Some(backend_name)) {
            Some((prefix, uri, curie)) => {
                let prefix_decl_edit = if query_unit.prologue().as_ref().is_none_or(|prologue| {
                    prologue
                        .prefix_declarations()
                        .iter()
                        .all(|prefix_declaration| {
                            prefix_declaration
                                .prefix()
                                .is_some_and(|declared_prefix| declared_prefix != prefix)
                        })
                }) {
                    Some(TextEdit::new(
                        Range::new(0, 0, 0, 0),
                        &format!("PREFIX {}: <{}>\n", prefix, uri),
                    ))
                } else {
                    None
                };
                (curie, prefix_decl_edit)
            }
            None => (rdf_term.to_string(), None),
        },
        _ => (rdf_term.to_string(), None),
    }
}

pub(super) async fn get_prefix_declarations(root: &SyntaxNode) -> Vec<(String, String)> {
    root.first_child()
        .and_then(|child| child.first_child())
        .and_then(Prologue::cast)
        .map(|prologue| {
            prologue
                .prefix_declarations()
                .iter()
                .filter_map(|prefix_declaration| {
                    match (
                        prefix_declaration.prefix(),
                        prefix_declaration.raw_uri_prefix(),
                    ) {
                        (Some(prefix), Some(uri_prefix)) => Some((prefix, uri_prefix)),
                        _ => None,
                    }
                })
                .collect()
        })
        .unwrap_or_default()
}

pub(super) fn reduce_path(
    subject: &str,
    path: &Path,
    object: &str,
    offset: TextSize,
) -> Option<String> {
    if path.syntax().text_range().start() >= offset {
        return Some(format!("{} ?qls_entity {}", subject, object));
    }
    match path.syntax().kind() {
        SyntaxKind::PathPrimary | SyntaxKind::PathElt | SyntaxKind::Path | SyntaxKind::VerbPath => {
            reduce_path(
                subject,
                &Path::cast(path.syntax().first_child()?)?,
                object,
                offset,
            )
        }
        SyntaxKind::PathAlternative => {
            reduce_path(subject, &path.sub_paths().last()?, object, offset)
        }
        SyntaxKind::PathSequence => {
            let sub_paths = path
                .sub_paths()
                .map(|sub_path| sub_path.text())
                .collect::<Vec<_>>();
            let path_seq_len = sub_paths.len();
            // NOTE: a dangling separator ("<p0>/") has no sub-path after the
            // slash; the existing sub-paths become the prefix and the cursor
            // position is the empty final element
            if path
                .syntax()
                .last_child_or_token()
                .is_some_and(|elt| elt.kind() == SyntaxKind::Slash)
            {
                return Some(format!(
                    "{} {} ?qls_inner . ?qls_inner ?qls_entity {}",
                    subject,
                    sub_paths.join("/"),
                    object
                ));
            }
            if path_seq_len > 1 {
                let path_prefix = sub_paths[..path_seq_len - 1].join("/");
                let prefix = format!("{} {} {}", subject, path_prefix, "?qls_inner");
                Some(format!(
                    "{} . {}",
                    prefix,
                    reduce_path("?qls_inner", &path.sub_paths().last()?, object, offset)?
                ))
            } else {
                reduce_path(subject, &path.sub_paths().last()?, object, offset)
            }
        }
        SyntaxKind::PathEltOrInverse => {
            if path.syntax().first_child_or_token()?.kind() == SyntaxKind::Zirkumflex {
                reduce_path(
                    object,
                    &Path::cast(path.syntax().last_child()?)?,
                    subject,
                    offset,
                )
            } else {
                reduce_path(
                    subject,
                    &Path::cast(path.syntax().last_child()?)?,
                    object,
                    offset,
                )
            }
        }
        SyntaxKind::PathNegatedPropertySet => match path.syntax().last_child() {
            Some(last_child) => reduce_path(subject, &Path::cast(last_child)?, object, offset),
            _ => Some(format!("{} ?qls_entity {}", subject, object)),
        },
        SyntaxKind::PathOneInPropertySet => {
            let first_child = path.syntax().first_child_or_token()?;
            if first_child.kind() == SyntaxKind::Zirkumflex {
                if first_child.text_range().end() == offset {
                    Some(format!("{} ?qls_entity {}", object, subject))
                } else {
                    Some(format!("{} ?qls_entity {}", subject, object))
                }
            } else {
                Some(path.text().to_string())
            }
        }
        _ => panic!("unknown path kind"),
    }
}

pub(super) fn to_completion_items(
    items: Vec<InternalCompletionItem>,
    range: Range,
    command: Option<&str>,
    _limit: u32,
    search_term: Option<&str>,
) -> CompletionList {
    let items: Vec<_> = items
        .into_iter()
        .enumerate()
        .map(
            |(
                idx,
                InternalCompletionItem {
                    label,
                    detail,
                    value,
                    _filter_text,
                    score,
                    import_edit,
                },
            )| {
                CompletionItem {
                    label: value.clone(),
                    label_details: Some(CompletionItemLabelDetails {
                        detail: format!(
                            "{}{}",
                            &label,
                            detail
                                .as_ref()
                                .map_or(String::new(), |detail| format!("/{detail}"))
                        ),
                    }),
                    detail: None,
                    documentation: Some(format!(
                        "Label: {label}\nAlias: {}\nScore: {}",
                        detail.unwrap_or_default(),
                        score.map_or("None".to_string(), |score| score.to_string()),
                    )),
                    // NOTE: The first 100 ID's are reserved
                    sort_text: Some(format!("{:0>5}", idx + 100)),
                    insert_text: None,
                    // NOTE: Use the search term as filter_text for all items.
                    // This gives all items the same fuzzy match score in Monaco,
                    // forcing it to fall back to sortText for ordering.
                    filter_text: search_term.map(|s| s.to_string()),
                    text_edit: Some(TextEdit {
                        range: range.clone(),
                        new_text: format!("{} ", value),
                    }),
                    kind: Some(CompletionItemKind::Value),
                    insert_text_format: None,
                    additional_text_edits: import_edit.map(|edit| vec![edit]),
                    command: command.map(|command| Command {
                        title: command.to_string(),
                        command: command.to_string(),
                        arguments: None,
                    }),
                }
            },
        )
        .collect();
    CompletionList {
        is_incomplete: true,
        items,
        item_defaults: None,
    }
}

#[cfg(test)]
mod test {
    use ll_sparql_parser::{
        ast::{AstNode, QueryUnit},
        parse_query,
    };

    use super::{matches_search_term, reduce_path};

    #[test]
    fn matches_search_term_exact_match() {
        assert!(matches_search_term("FILTER", Some("FILTER")));
    }

    #[test]
    fn matches_search_term_prefix_match() {
        assert!(matches_search_term("FILTER", Some("FI")));
        assert!(matches_search_term("FILTER", Some("F")));
        assert!(matches_search_term("OPTIONAL", Some("OP")));
        assert!(matches_search_term("GROUP BY", Some("GR")));
    }

    #[test]
    fn matches_search_term_case_insensitive() {
        assert!(matches_search_term("FILTER", Some("fi")));
        assert!(matches_search_term("FILTER", Some("filter")));
        assert!(matches_search_term("FILTER", Some("Filter")));
        assert!(matches_search_term("OPTIONAL", Some("opt")));
        assert!(matches_search_term("GROUP BY", Some("group")));
    }

    #[test]
    fn matches_search_term_no_match() {
        assert!(!matches_search_term("FILTER", Some("Germany")));
        assert!(!matches_search_term("FILTER", Some("BI")));
        assert!(!matches_search_term("OPTIONAL", Some("FI")));
        assert!(!matches_search_term("BIND", Some("FILTER")));
    }

    #[test]
    fn matches_search_term_none_shows_all() {
        assert!(matches_search_term("FILTER", None));
        assert!(matches_search_term("BIND", None));
        assert!(matches_search_term("OPTIONAL", None));
    }

    #[test]
    fn matches_search_term_empty_string_shows_all() {
        assert!(matches_search_term("FILTER", Some("")));
        assert!(matches_search_term("BIND", Some("")));
        assert!(matches_search_term("OPTIONAL", Some("")));
    }

    #[test]
    fn matches_search_term_partial_word_not_prefix() {
        // "ILTER" is not a prefix of "FILTER"
        assert!(!matches_search_term("FILTER", Some("ILTER")));
        // "TER" is not a prefix of "FILTER"
        assert!(!matches_search_term("FILTER", Some("TER")));
    }

    #[test]
    fn reduce_sequence_path() {
        //       0123456789012345678901
        let s = "Select * { ?a <p0>/  }";
        let reduced = "?a <p0> ?qls_inner . ?qls_inner ?qls_entity []";
        let offset = 19;
        let (tree, _) = parse_query(s);
        let query_unit = QueryUnit::cast(tree).unwrap();
        let triples = query_unit
            .select_query()
            .unwrap()
            .where_clause()
            .unwrap()
            .group_graph_pattern()
            .unwrap()
            .triple_blocks()
            .first()
            .unwrap()
            .triples();
        let triple = triples.first().unwrap();
        println!(
            "{:#?}",
            &triple.properties_list_path().unwrap().properties().last()
        );
        let res = reduce_path(
            &triple.subject().unwrap().text(),
            &triple
                .properties_list_path()
                .unwrap()
                .properties()
                .last()
                .unwrap()
                .verb,
            "[]",
            offset.into(),
        )
        .unwrap();
        assert_eq!(res, reduced);
    }

    #[test]
    fn reduce_alternating_path() {
        //       012345678901234567890123456
        let s = "Select * { ?a <p0>/<p1>|  <x>}";
        let reduced = "?a ?qls_entity []";
        let offset = 24;
        let (tree, _) = parse_query(s);
        let query_unit = QueryUnit::cast(tree).unwrap();
        let triples = query_unit
            .select_query()
            .unwrap()
            .where_clause()
            .unwrap()
            .group_graph_pattern()
            .unwrap()
            .triple_blocks()
            .first()
            .unwrap()
            .triples();
        let triple = triples.first().unwrap();
        let res = reduce_path(
            &triple.subject().unwrap().text(),
            &triple
                .properties_list_path()
                .unwrap()
                .properties()
                .last()
                .unwrap()
                .verb,
            "[]",
            offset.into(),
        )
        .unwrap();
        assert_eq!(res, reduced);
    }

    #[test]
    fn reduce_inverse_path() {
        //       012345678901234567890123456
        let s = "Select * { ?a ^  <x>}";
        let reduced = "[] ?qls_entity ?a";
        let offset = 15;
        let (tree, _) = parse_query(s);
        let query_unit = QueryUnit::cast(tree).unwrap();
        let triples = query_unit
            .select_query()
            .unwrap()
            .where_clause()
            .unwrap()
            .group_graph_pattern()
            .unwrap()
            .triple_blocks()
            .first()
            .unwrap()
            .triples();
        let triple = triples.first().unwrap();
        let res = reduce_path(
            &triple.subject().unwrap().text(),
            &triple
                .properties_list_path()
                .unwrap()
                .properties()
                .last()
                .unwrap()
                .verb,
            "[]",
            offset.into(),
        )
        .unwrap();
        assert_eq!(res, reduced);
    }

    #[test]
    fn reduce_negated_path() {
        //       012345678901234567890123456
        let s = "Select * { ?a !()}";
        let reduced = "?a ?qls_entity []";
        let offset: u32 = 16;
        let (tree, _) = parse_query(&s[..offset as usize]);
        let query_unit = QueryUnit::cast(tree).unwrap();
        let triples = query_unit
            .select_query()
            .unwrap()
            .where_clause()
            .unwrap()
            .group_graph_pattern()
            .unwrap()
            .triple_blocks()
            .first()
            .unwrap()
            .triples();
        let triple = triples.first().unwrap();
        let res = reduce_path(
            &triple.subject().unwrap().text(),
            &triple
                .properties_list_path()
                .unwrap()
                .properties()
                .last()
                .unwrap()
                .verb,
            "[]",
            offset.into(),
        )
        .unwrap();
        assert_eq!(res, reduced);
    }

    #[test]
    fn reduce_complex_path1() {
        //       0123456789012345678901234567890123456
        let s = "Select * { ?a <p0>|<p1>/(<p2>)/^  <x>}";
        let reduced = "?a <p1>/(<p2>) ?qls_inner . [] ?qls_entity ?qls_inner";
        let offset = 32;
        let (tree, _) = parse_query(s);
        let query_unit = QueryUnit::cast(tree).unwrap();
        let triples = query_unit
            .select_query()
            .unwrap()
            .where_clause()
            .unwrap()
            .group_graph_pattern()
            .unwrap()
            .triple_blocks()
            .first()
            .unwrap()
            .triples();
        let triple = triples.first().unwrap();
        let res = reduce_path(
            &triple.subject().unwrap().text(),
            &triple
                .properties_list_path()
                .unwrap()
                .properties()
                .last()
                .unwrap()
                .verb,
            "[]",
            offset.into(),
        )
        .unwrap();
        assert_eq!(res, reduced);
    }
    #[test]
    fn reduce_complex_path2() {
        //       01234567890123456789012345678901234567890
        let s = "Select * { ?a <p0>|<p1>/(<p2>)/^<p2>/!(^)  <x>}";
        let reduced = "?a <p1>/(<p2>)/^<p2> ?qls_inner . [] ?qls_entity ?qls_inner";
        let offset = 40;
        let (tree, _) = parse_query(s);
        let query_unit = QueryUnit::cast(tree).unwrap();
        let triples = query_unit
            .select_query()
            .unwrap()
            .where_clause()
            .unwrap()
            .group_graph_pattern()
            .unwrap()
            .triple_blocks()
            .first()
            .unwrap()
            .triples();
        let triple = triples.first().unwrap();
        let res = reduce_path(
            &triple.subject().unwrap().text(),
            &triple
                .properties_list_path()
                .unwrap()
                .properties()
                .last()
                .unwrap()
                .verb,
            "[]",
            offset.into(),
        )
        .unwrap();
        assert_eq!(res, reduced);
    }

    #[test]
    fn reduce_complex_path3() {
        //       0123456789012345678901234567890123456
        let s = "Select * { ?a ^(^<a>/)  <x>}";
        let reduced = "[] ^<a> ?qls_inner . ?qls_inner ?qls_entity ?a";
        let offset = 21;
        let (tree, _) = parse_query(s);
        let query_unit = QueryUnit::cast(tree).unwrap();
        let triples = query_unit
            .select_query()
            .unwrap()
            .where_clause()
            .unwrap()
            .group_graph_pattern()
            .unwrap()
            .triple_blocks()
            .first()
            .unwrap()
            .triples();
        let triple = triples.first().unwrap();
        let res = reduce_path(
            &triple.subject().unwrap().text(),
            &triple
                .properties_list_path()
                .unwrap()
                .properties()
                .last()
                .unwrap()
                .verb,
            "[]",
            offset.into(),
        )
        .unwrap();
        assert_eq!(res, reduced);
    }

    #[test]
    fn reduce_complex_path4() {
        //       01234567890123456
        let s = "Select * { ?a !^  <x>}";
        let reduced = "[] ?qls_entity ?a";
        let offset = 16;

        let (tree, _) = parse_query(s);
        let query_unit = QueryUnit::cast(tree).unwrap();
        let triples = query_unit
            .select_query()
            .unwrap()
            .where_clause()
            .unwrap()
            .group_graph_pattern()
            .unwrap()
            .triple_blocks()
            .first()
            .unwrap()
            .triples();
        let triple = triples.first().unwrap();
        let res = reduce_path(
            &triple.subject().unwrap().text(),
            &triple
                .properties_list_path()
                .unwrap()
                .properties()
                .last()
                .unwrap()
                .verb,
            "[]",
            offset.into(),
        )
        .unwrap();
        assert_eq!(res, reduced);
    }
}