qlue-ls 3.0.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
//! Server configuration and settings structures.
//!
//! This module defines the configuration schema for qlue-ls, loadable from
//! `qlue-ls.toml` or `qlue-ls.yml` files in the working directory.
//!
//! # Key Types
//!
//! - [`Settings`]: Top-level configuration container
//! - [`FormatSettings`]: Formatter options (alignment, capitalization, spacing)
//! - [`CompletionSettings`]: Timeout and result limits for completions
//! - [`BackendConfiguration`]: SPARQL endpoint with prefix map and custom queries
//!
//! # Configuration Loading
//!
//! [`Settings::new`] attempts to load from a config file. If not found or invalid,
//! it falls back to [`Settings::default`]. Settings can also be updated at runtime
//! via the `qlueLs/changeSettings` notification.
//!
//! # Backend Configuration
//!
//! Backends define SPARQL endpoints used for completions and query execution.
//! Each backend can have:
//! - Custom prefix maps for URI compression
//! - Request method (GET/POST)
//! - Custom SPARQL templates for completion queries
//!
//! # Related Modules
//!
//! - [`super::Server`]: Stores settings in `Server.settings`
//! - [`super::message_handler::settings`]: Handles runtime settings changes

use std::{collections::HashMap, fmt};

#[cfg(not(target_arch = "wasm32"))]
use config::{Config, ConfigError};
use serde::{Deserialize, Serialize};

use crate::server::lsp::{SparqlEngine, base_types::LSPAny};

#[derive(Debug, Serialize, Deserialize, Default, PartialEq)]
#[serde(default)]
pub struct BackendsSettings {
    pub backends: HashMap<String, BackendConfiguration>,
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct BackendConfiguration {
    pub name: String,
    pub url: String,
    pub health_check_url: Option<String>,
    pub engine: Option<SparqlEngine>,
    pub request_method: Option<RequestMethod>,
    #[serde(default)]
    pub prefix_map: HashMap<String, String>,
    #[serde(default)]
    pub default: bool,
    #[serde(default)]
    pub queries: HashMap<CompletionTemplate, String>,
    pub additional_data: Option<LSPAny>,
}

#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", try_from = "String")]
pub(crate) enum CompletionTemplate {
    Hover,
    SubjectCompletion,
    PredicateCompletionContextSensitive,
    PredicateCompletionContextInsensitive,
    ObjectCompletionContextSensitive,
    ObjectCompletionContextInsensitive,
    ValuesCompletionContextSensitive,
    ValuesCompletionContextInsensitive,
}

#[derive(Debug)]
pub struct UnknownTemplateError(String);

impl fmt::Display for UnknownTemplateError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "unknown completion query template \"{}\"", &self.0)
    }
}

impl TryFrom<String> for CompletionTemplate {
    type Error = UnknownTemplateError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        match s.as_str() {
            "hover" => Ok(CompletionTemplate::Hover),
            "subjectCompletion" => Ok(CompletionTemplate::SubjectCompletion),
            "predicateCompletionContextInsensitive" => {
                Ok(CompletionTemplate::PredicateCompletionContextInsensitive)
            }
            "predicateCompletionContextSensitive" => {
                Ok(CompletionTemplate::PredicateCompletionContextSensitive)
            }
            "objectCompletionContextInsensitive" => {
                Ok(CompletionTemplate::ObjectCompletionContextInsensitive)
            }
            "objectCompletionContextSensitive" => {
                Ok(CompletionTemplate::ObjectCompletionContextSensitive)
            }
            "valuesCompletionContextSensitive" => {
                Ok(CompletionTemplate::ValuesCompletionContextSensitive)
            }
            "valuesCompletionContextInsensitive" => {
                Ok(CompletionTemplate::ValuesCompletionContextInsensitive)
            }
            _ => Err(UnknownTemplateError(s.to_string())),
        }
    }
}

impl fmt::Display for CompletionTemplate {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CompletionTemplate::Hover => write!(f, "hover"),
            CompletionTemplate::SubjectCompletion => write!(f, "subjectCompletion"),
            CompletionTemplate::PredicateCompletionContextSensitive => {
                write!(f, "predicateCompletionContextSensitive")
            }
            CompletionTemplate::PredicateCompletionContextInsensitive => {
                write!(f, "predicateCompletionContextInsensitive")
            }
            CompletionTemplate::ObjectCompletionContextSensitive => {
                write!(f, "objectCompletionContextSensitive")
            }
            CompletionTemplate::ObjectCompletionContextInsensitive => {
                write!(f, "objectCompletionContextInsensitive")
            }
            CompletionTemplate::ValuesCompletionContextSensitive => {
                write!(f, "valuesCompletionContextSensitive")
            }
            CompletionTemplate::ValuesCompletionContextInsensitive => {
                write!(f, "valuesCompletionContextInsensitive")
            }
        }
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[allow(clippy::upper_case_acronyms)]
pub enum RequestMethod {
    GET,
    POST,
}

#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
#[serde(rename_all = "camelCase")]
pub struct CompletionSettings {
    pub timeout_ms: u32,
    pub result_size_limit: u32,
    pub subject_completion_trigger_length: u32,
    pub object_completion_suffix: bool,
    /// Maximum number of variable completions to suggest. None means unlimited.
    pub variable_completion_limit: Option<u32>,
    /// When completing a subject that matches the previous triple's subject,
    /// transform the completion to use semicolon notation instead of starting a new triple.
    pub same_subject_semicolon: bool,
}

impl Default for CompletionSettings {
    fn default() -> Self {
        Self {
            timeout_ms: 5000,
            result_size_limit: 100,
            subject_completion_trigger_length: 3,
            object_completion_suffix: true,
            variable_completion_limit: None,
            same_subject_semicolon: true,
        }
    }
}

#[derive(Debug, Deserialize, Serialize, PartialEq, Clone)]
#[serde(default)]
#[serde(rename_all = "camelCase")]
pub struct FormatSettings {
    pub align_predicates: bool,
    pub align_prefixes: bool,
    pub separate_prologue: bool,
    pub capitalize_keywords: bool,
    pub insert_spaces: Option<bool>,
    pub tab_size: Option<u8>,
    pub where_new_line: bool,
    pub filter_same_line: bool,
    pub compact: Option<u32>,
    pub line_length: u32,
    pub contract_triples: bool,
    /// When enabled, preserves intentional blank lines from the original source.
    /// Consecutive blank lines are collapsed into a single empty line.
    /// Disabled by default to preserve current behavior.
    pub keep_empty_lines: bool,
}

impl Default for FormatSettings {
    fn default() -> Self {
        Self {
            align_predicates: true,
            align_prefixes: false,
            separate_prologue: false,
            capitalize_keywords: true,
            insert_spaces: Some(true),
            tab_size: Some(2),
            where_new_line: false,
            filter_same_line: true,
            compact: None,
            line_length: 120,
            contract_triples: false,
            keep_empty_lines: false,
        }
    }
}

#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PrefixesSettings {
    pub add_missing: Option<bool>,
    pub remove_unused: Option<bool>,
}

impl Default for PrefixesSettings {
    fn default() -> Self {
        Self {
            add_missing: Some(true),
            remove_unused: Some(false),
        }
    }
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct Replacement {
    pub pattern: String,
    pub replacement: String,
}

impl Replacement {
    pub fn new(pattern: &str, replacement: &str) -> Self {
        Self {
            pattern: pattern.to_string(),
            replacement: replacement.to_string(),
        }
    }
}

#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Replacements {
    pub object_variable: Vec<Replacement>,
}

impl Default for Replacements {
    fn default() -> Self {
        Self {
            object_variable: vec![
                Replacement::new(r"^has (\w+)", "$1"),
                Replacement::new(r"^has([A-Z]\w*)", "$1"),
                Replacement::new(r"^(\w+)edBy", "$1"),
                Replacement::new(r"([^a-zA-Z0-9_])", ""),
            ],
        }
    }
}

#[derive(Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Settings {
    /// Format settings
    #[serde(default)]
    pub format: FormatSettings,
    /// Completion Settings
    #[serde(default)]
    pub completion: CompletionSettings,
    /// Backend configurations
    pub backends: Option<BackendsSettings>,
    /// Automatically add and remove prefix declarations
    pub prefixes: Option<PrefixesSettings>,
    /// Automatically add and remove prefix declarations
    pub replacements: Option<Replacements>,
    /// Automatically insert a line break after typing `;` or `.` following a valid triple.
    #[serde(default)]
    pub auto_line_break: bool,
}

impl Default for Settings {
    fn default() -> Self {
        Self {
            format: FormatSettings::default(),
            completion: CompletionSettings::default(),
            backends: None,
            prefixes: Some(PrefixesSettings::default()),
            replacements: Some(Replacements::default()),
            auto_line_break: false,
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn load_user_configuration() -> Result<Settings, ConfigError> {
    Config::builder()
        .add_source(config::File::with_name("qlue-ls"))
        .build()?
        .try_deserialize::<Settings>()
}

impl Settings {
    pub fn new() -> Self {
        #[cfg(not(target_arch = "wasm32"))]
        match load_user_configuration() {
            Ok(settings) => {
                tracing::info!("Loaded user configuration!!");
                settings
            }
            Err(error) => {
                tracing::info!(
                    "Did not load user-configuration:\n{}\n falling back to default values",
                    error
                );
                Settings::default()
            }
        }
        #[cfg(target_arch = "wasm32")]
        Settings::default()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use config::{Config, FileFormat};

    fn parse_yaml<T: serde::de::DeserializeOwned>(yaml: &str) -> T {
        Config::builder()
            .add_source(config::File::from_str(yaml, FileFormat::Yaml))
            .build()
            .unwrap()
            .try_deserialize()
            .unwrap()
    }

    #[test]
    fn test_backend_configuration_valid_queries_all_variants() {
        let yaml = r#"
            name: TestBackend
            url: https://example.com/sparql
            healthCheckUrl: https://example.com/health
            requestMethod: GET
            prefixMap:
              rdf: http://www.w3.org/1999/02/22-rdf-syntax-ns#
              rdfs: http://www.w3.org/2000/01/rdf-schema#
            default: false
            queries:
              subjectCompletion: SELECT ?qls_entity ?qls_label ?qls_detail WHERE { ?qls_entity a ?type }
              predicateCompletionContextSensitive: SELECT ?qls_entity WHERE { ?s ?qls_entity ?o }
              predicateCompletionContextInsensitive: SELECT ?qls_entity WHERE { [] ?qls_entity [] }
              objectCompletionContextSensitive: SELECT ?qls_entity WHERE { ?s ?p ?qls_entity }
              objectCompletionContextInsensitive: SELECT ?qls_entity WHERE { [] [] ?qls_entity }
              valuesCompletionContextSensitive: SELECT ?qls_entity WHERE { ?qls_entity ?p ?o }
              valuesCompletionContextInsensitive: SELECT ?qls_entity WHERE { ?qls_entity ?p ?o }
        "#;

        let config: BackendConfiguration = parse_yaml(yaml);

        assert_eq!(config.name, "TestBackend");
        assert_eq!(config.url, "https://example.com/sparql");
        assert!(!config.default);
        assert_eq!(config.queries.len(), 7);
        assert!(
            config
                .queries
                .contains_key(&CompletionTemplate::SubjectCompletion)
        );
        assert!(
            config
                .queries
                .contains_key(&CompletionTemplate::PredicateCompletionContextSensitive)
        );
        assert!(
            config
                .queries
                .contains_key(&CompletionTemplate::PredicateCompletionContextInsensitive)
        );
        assert!(
            config
                .queries
                .contains_key(&CompletionTemplate::ObjectCompletionContextSensitive)
        );
        assert!(
            config
                .queries
                .contains_key(&CompletionTemplate::ObjectCompletionContextInsensitive)
        );
        assert!(
            config
                .queries
                .contains_key(&CompletionTemplate::ValuesCompletionContextSensitive)
        );
        assert!(
            config
                .queries
                .contains_key(&CompletionTemplate::ValuesCompletionContextInsensitive)
        );
    }

    #[test]
    fn test_backend_configuration_queries_subset() {
        let yaml = r#"
            name: MinimalBackend
            url: https://example.com/sparql
            prefixMap: {}
            queries:
              subjectCompletion: SELECT ?qls_entity WHERE { ?qls_entity ?p ?o }
              objectCompletionContextInsensitive: SELECT ?qls_entity WHERE { ?s ?p ?qls_entity }
        "#;

        let config: BackendConfiguration = parse_yaml(yaml);

        assert_eq!(config.queries.len(), 2);
        assert!(
            config
                .queries
                .contains_key(&CompletionTemplate::SubjectCompletion)
        );
        assert!(
            config
                .queries
                .contains_key(&CompletionTemplate::ObjectCompletionContextInsensitive)
        );
        assert!(
            !config
                .queries
                .contains_key(&CompletionTemplate::PredicateCompletionContextSensitive)
        );
    }

    #[test]
    fn test_backend_configuration_rejects_invalid_query_key() {
        // This test ensures that invalid query keys are rejected
        let yaml = r#"
            name: TestBackend
            url: https://example.com/sparql
            prefixMap: {}
            queries:
              invalidQueryType: SELECT ?qls_entity WHERE { ?s ?p ?o }
              subjectCompletion: SELECT ?qls_entity WHERE { ?qls_entity ?p ?o }
        "#;

        let result = Config::builder()
            .add_source(config::File::from_str(yaml, FileFormat::Yaml))
            .build()
            .unwrap()
            .try_deserialize::<BackendConfiguration>();
        assert!(result.is_err());
    }

    #[test]
    fn test_backend_configuration_with_multiline_queries() {
        let yaml = r#"
            name: WikidataBackend
            url: https://query.wikidata.org/sparql
            healthCheckUrl: https://query.wikidata.org/
            prefixMap:
              wd: http://www.wikidata.org/entity/
              wdt: http://www.wikidata.org/prop/direct/
              rdfs: http://www.w3.org/2000/01/rdf-schema#
            default: false
            queries:
              subjectCompletion: |
                SELECT ?qls_entity ?qls_label ?qls_detail
                WHERE {
                  ?qls_entity rdfs:label ?qls_label .
                  OPTIONAL { ?qls_entity schema:description ?qls_detail }
                  FILTER(LANG(?qls_label) = "en")
                }
                LIMIT 100
              predicateCompletionContextSensitive: |
                SELECT ?qls_entity WHERE {
                  ?s ?qls_entity ?o
                }
              objectCompletionContextInsensitive: SELECT ?qls_entity WHERE { [] [] ?qls_entity }
        "#;

        let config: BackendConfiguration = parse_yaml(yaml);

        assert_eq!(config.name, "WikidataBackend");
        assert_eq!(config.url, "https://query.wikidata.org/sparql");
        assert!(!config.default);
        assert_eq!(config.prefix_map.len(), 3);
        assert_eq!(config.queries.len(), 3);

        // Verify multiline query was parsed correctly
        let subject_query = config
            .queries
            .get(&CompletionTemplate::SubjectCompletion)
            .unwrap();
        assert!(subject_query.contains("SELECT ?qls_entity ?qls_label ?qls_detail"));
        assert!(subject_query.contains("FILTER(LANG(?qls_label) = \"en\")"));
    }

    #[test]
    fn test_backends_settings_multiple_backends() {
        let yaml = r#"
            backends:
              wikidata:
                name: Wikidata
                url: https://query.wikidata.org/sparql
                prefixMap:
                  wd: http://www.wikidata.org/entity/
                queries:
                  subjectCompletion: SELECT ?qls_entity WHERE { ?qls_entity ?p ?o }
              dbpedia:
                name: DBpedia
                url: https://dbpedia.org/sparql
                prefixMap:
                  dbo: http://dbpedia.org/ontology/
                default: true
                queries:
                  objectCompletionContextSensitive: SELECT ?qls_entity WHERE { ?s ?p ?qls_entity }
        "#;

        let settings: BackendsSettings = parse_yaml(yaml);

        assert_eq!(settings.backends.len(), 2);
        assert!(settings.backends.contains_key("wikidata"));
        assert!(settings.backends.contains_key("dbpedia"));

        let wikidata = settings.backends.get("wikidata").unwrap();
        assert_eq!(wikidata.name, "Wikidata");
        assert_eq!(wikidata.queries.len(), 1);

        let dbpedia = settings.backends.get("dbpedia").unwrap();
        assert_eq!(dbpedia.name, "DBpedia");
        assert!(dbpedia.default);
    }

    #[test]
    fn test_full_settings_deserialization() {
        let yaml = r#"
            format:
              alignPredicates: true
              alignPrefixes: false
              separatePrologue: false
              capitalizeKeywords: true
              insertSpaces: true
              tabSize: 2
              whereNewLine: false
              filterSameLine: true
            completion:
              timeoutMs: 5000
              resultSizeLimit: 100
            backends:
              backends:
                wikidata:
                  name: Wikidata
                  url: https://query.wikidata.org/sparql
                  healthCheckUrl: https://query.wikidata.org/
                  prefixMap:
                    wd: http://www.wikidata.org/entity/
                    wdt: http://www.wikidata.org/prop/direct/
                  default: true
                  queries:
                    subjectCompletion: SELECT ?qls_entity WHERE { ?qls_entity ?p ?o }
                    predicateCompletionContextSensitive: SELECT ?qls_entity WHERE { ?s ?qls_entity ?o }
            prefixes:
              addMissing: true
              removeUnused: false
        "#;

        let settings: Settings = parse_yaml(yaml);

        assert!(settings.format.align_predicates);
        assert_eq!(settings.completion.timeout_ms, 5000);
        assert!(settings.backends.is_some());

        let backends = settings.backends.unwrap();
        assert_eq!(backends.backends.len(), 1);

        let wikidata = backends.backends.get("wikidata").unwrap();
        assert_eq!(wikidata.name, "Wikidata");
        assert!(wikidata.default);
        assert_eq!(wikidata.queries.len(), 2);
    }
}