prttl 0.4.0

Pretty-printer for RDF Turtle
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
// SPDX-FileCopyrightText: 2025 Robin Vobruba <hoijui.quaero@gmail.com>
//
// SPDX-License-Identifier: Apache-2.0

use std::sync::LazyLock;

use clap::ValueEnum;

static CLS_ORDER_OWL: LazyLock<Vec<&'static str>> = LazyLock::new(|| {
    vec![
        "owl:Ontology",
        "ods:Dataset",
        "owl:Class",
        "owl:ObjectProperty",
        "owl:DatatypeProperty",
        "owl:NamedIndividual",
        // "owl:Thing",
        // "owl:AnnotationProperty",
        // "owl:AsymmetricProperty",
        // "owl:FunctionalProperty",
        // "owl:InverseFunctionalProperty",
        // "owl:IrreflexiveProperty",
        // "owl:OntologyProperty",
        // "owl:ReflexiveProperty",
        // "owl:SymmetricProperty",
        // "owl:TransitiveProperty",
    ]
});
static CLS_ORDER_SKOS: LazyLock<Vec<&'static str>> = LazyLock::new(|| {
    vec![
        "skos:ConceptScheme",
        "skos:Concept",
        "skos:OrderedCollection",
        "skos:Collection",
    ]
});
static CLS_ORDER_SHACL: LazyLock<Vec<&'static str>> =
    LazyLock::new(|| vec!["sh:NodeShape", "sh:PropertyShape", "sh:Shape"]);
static CLS_ORDER_SHEX: LazyLock<Vec<&'static str>> = LazyLock::new(|| {
    vec![
        "shex:Schema",
        "shex:ShapeExternal",
        "shex:ShapeAnd",
        "shex:ShapeOr",
        "shex:ShapeNot",
        "shex:Shape",
        "shex:TripleConstraint",
        "shex:Wildcard",
    ]
});
static CLS_ORDER_RDF: LazyLock<Vec<&'static str>> = LazyLock::new(|| {
    vec![
        "rdfs:Datatype",
        "rdfs:Class",
        "rdfs:Resource",
        "rdf:Property",
        // "rdfs:Container",
        // "rdfs:Literal",
        // "rdf:Bag",
        // "rdf:Seq",
        // "rdf:Alt",
        // "rdf:List",
        // "rdf:Statement",
    ]
});

static PRED_ORDER_OWL: LazyLock<Vec<&'static str>> = LazyLock::new(|| {
    vec![
        "rdf:type",
        "owl:imports",
        "rdf:first",
        "rdf:rest",
        "rdfs:label",
        "rdfs:comment",
        "rdf:language",
        "owl:sameAs",
        "rdfs:subClassOf",
        "rdfs:subPropertyOf",
        "rdfs:domain",
        "dcam:domainIncludes",
        "rdfs:range",
        "dcam:rangeIncludes",
        "rdfs:seeAlso",
        "owl:versionInfo",
        "owl:versionIRI",
        "vs:term_status",
        "owl:deprecated",
        "owl:cardinality",
        "owl:maxCardinality",
        "owl:minCardinality",
        // "owl:allValuesFrom",
        // "owl:annotatedProperty",
        // "owl:annotatedSource",
        // "owl:annotatedTarget",
        // "owl:assertionProperty",
        // "owl:backwardCompatibleWith",
        // "owl:bottomDataProperty",
        // "owl:bottomObjectProperty",
        // "owl:complementOf",
        // "owl:datatypeComplementOf",
        // "owl:differentFrom",
        // "owl:disjointUnionOf",
        // "owl:disjointWith",
        // "owl:distinctMembers",
        // "owl:equivalentClass",
        // "owl:equivalentProperty",
        // "owl:hasKey",
        // "owl:hasSelf",
        // "owl:hasValue",
        // "owl:incompatibleWith",
        // "owl:intersectionOf",
        // "owl:inverseOf",
        // "owl:maxQualifiedCardinality",
        // "owl:members",
        // "owl:minQualifiedCardinality",
        // "owl:onClass",
        // "owl:onDataRange",
        // "owl:onDatatype",
        // "owl:oneOf",
        // "owl:onProperties",
        // "owl:onProperty",
        // "owl:priorVersion",
        // "owl:propertyChainAxiom",
        // "owl:propertyDisjointWith",
        // "owl:qualifiedCardinality",
        // "owl:someValuesFrom",
        // "owl:sourceIndividual",
        // "owl:targetIndividual",
        // "owl:targetValue",
        // "owl:topDataProperty",
        // "owl:topObjectProperty",
        // "owl:unionOf",
        // "owl:withRestrictions",
    ]
});
static PRED_ORDER_SKOS: LazyLock<Vec<&'static str>> = LazyLock::new(|| {
    vec![
        "skos:prefLabel",
        "skos:altLabel",
        "skos:hiddenLabel",
        "skos:changeNote",
        "skos:editorialNote",
        "skos:historyNote",
        "skos:scopeNote",
        "skos:note",
        "skos:example",
        "skos:broader",
        "skos:narrower",
        "skos:related",
        "skos:member",
        "skos:memberList",
        "skos:broadMatch",
        "skos:narrowMatch",
        "skos:relatedMatch",
        "skos:exactMatch",
        "skos:closeMatch",
        // "skos:mappingRelation",
        // "skos:inScheme",
        // "skos:hasTopConcept",
        // "skos:topConceptOf",
        // "skos:notation",
        // "skos:definition",
        // "skos:semanticRelation",
        // "skos:broaderTransitive",
        // "skos:narrowerTransitive",
    ]
});
static PRED_ORDER_SHACL: LazyLock<Vec<&'static str>> = LazyLock::new(|| {
    vec![
        "sh:deactivated",
        "sh:name",
        "sh:description",
        "sh:namespace",
        "sh:targetClass",
        "sh:targetNode",
        "sh:targetObjectsOf",
        "sh:targetSubjectsOf",
        "sh:target",
        "sh:node",
        "sh:nodeKind",
        "sh:property",
        "sh:value",
        "sh:shapesGraph",
        "sh:suggestedShapesGraph",
        "sh:optional",
        "sh:class",
        "sh:datatype",
        "sh:equals",
        "sh:disjoint",
        "sh:lessThan",
        "sh:lessThanOrEquals",
        "sh:maxCount",
        "sh:maxExclusive",
        "sh:maxInclusive",
        "sh:maxLength",
        "sh:minCount",
        "sh:minExclusive",
        "sh:minInclusive",
        "sh:minLength",
        "sh:pattern",
        // "sh:message",
        // "sh:severity",
        // "sh:conforms",
        // "sh:result",
        // "sh:detail",
        // "sh:focusNode",
        // "sh:sourceConstraint",
        // "sh:sourceShape",
        // "sh:sourceConstraintComponent",
        // "sh:entailment",
        // "sh:path",
        // "sh:inversePath",
        // "sh:alternativePath",
        // "sh:zeroOrMorePath",
        // "sh:oneOrMorePath",
        // "sh:zeroOrOnePath",
        // "sh:parameter",
        // "sh:labelTemplate",
        // "sh:validator",
        // "sh:nodeValidator",
        // "sh:propertyValidator",
        // "sh:and",
        // "sh:closed",
        // "sh:ignoredProperties",
        // "sh:hasValue",
        // "sh:in",
        // "sh:languageIn",
        // "sh:not",
        // "sh:or",
        // "sh:flags",
        // "sh:qualifiedMaxCount",
        // "sh:qualifiedMinCount",
        // "sh:qualifiedValueShape",
        // "sh:qualifiedValueShapesDisjoint",
        // "sh:uniqueLang",
        // "sh:xone",
        // "sh:ask",
        // "sh:construct",
        // "sh:select",
        // "sh:update",
        // "sh:prefixes",
        // "sh:declare",
        // "sh:prefix",
        // "sh:sparql",
        // "sh:defaultValue",
        // "sh:group",
        // "sh:order",
        // "sh:returnType",
        // "sh:resultAnnotation",
        // "sh:annotationProperty",
        // "sh:annotationValue",
        // "sh:annotationVarName",
        // "sh:this",
        // "sh:filterShape",
        // "sh:nodes",
        // "sh:intersection",
        // "sh:union",
        // "sh:expression",
        // "sh:rule",
        // "sh:condition",
        // "sh:subject",
        // "sh:predicate",
        // "sh:object",
    ]
});
static PRED_ORDER_SHEX: LazyLock<Vec<&'static str>> = LazyLock::new(|| {
    // TODO Select and order some of the below
    vec![
        // "shex:annotation",
        // "shex:closed",
        // "shex:code",
        // "shex:datatype",
        // "shex:exclusion",
        // "shex:expression",
        // "shex:expressions",
        // "shex:extra",
        // "shex:extends",
        // "shex:flags",
        // "shex:fractiondigits",
        // "shex:inverse",
        // "shex:languageTag",
        // "shex:length",
        // "shex:max",
        // "shex:maxexclusive",
        // "shex:maxinclusive",
        // "shex:maxlength",
        // "shex:min",
        // "shex:minexclusive",
        // "shex:mininclusive",
        // "shex:minlength",
        // "shex:name",
        // "shex:nodeKind",
        // "shex:numericFacet",
        // "shex:object",
        // "shex:pattern",
        // "shex:predicate",
        // "shex:semActs",
        // "shex:shapeExpr",
        // "shex:shapeExprs",
        // "shex:shapes",
        // "shex:start",
        // "shex:startActs",
        // "shex:stem",
        // "shex:stringFacet",
        // "shex:totaldigits",
        // "shex:valueExpr",
        // "shex:values",
        // "shex:xsFacet",
        // "shex:bnode",
        // "shex:iri",
        // "shex:literal",
        // "shex:nonliteral",
    ]
});
static PRED_ORDER_RDF: LazyLock<Vec<&'static str>> = LazyLock::new(|| {
    vec![
        "rdf:type",
        "rdf:first",
        "rdf:rest",
        "rdfs:label",
        "rdfs:comment",
        "rdf:language",
        "rdfs:subClassOf",
        "rdfs:subPropertyOf",
        "rdfs:domain",
        "rdfs:range",
        "rdfs:seeAlso",
        // "rdf:value",
    ]
});

#[derive(ValueEnum, Clone, Copy, Debug)]
pub enum SpecialSubjectTypeOrder {
    Owl,
    Skos,
    Shacl,
    Shex,
    Rdf,
}

impl SpecialSubjectTypeOrder {
    #[must_use]
    pub fn as_list(&self) -> &'static Vec<&'static str> {
        match self {
            Self::Owl => &CLS_ORDER_OWL,
            Self::Skos => &CLS_ORDER_SKOS,
            Self::Shacl => &CLS_ORDER_SHACL,
            Self::Shex => &CLS_ORDER_SHEX,
            Self::Rdf => &CLS_ORDER_RDF,
        }
    }
}

#[derive(ValueEnum, Clone, Copy, Debug)]
pub enum SpecialPredicateOrder {
    Owl,
    Skos,
    Shacl,
    Shex,
    Rdf,
}

impl SpecialPredicateOrder {
    #[must_use]
    pub fn as_list(&self) -> &'static Vec<&'static str> {
        match self {
            Self::Owl => &PRED_ORDER_OWL,
            Self::Skos => &PRED_ORDER_SKOS,
            Self::Shacl => &PRED_ORDER_SHACL,
            Self::Shex => &PRED_ORDER_SHEX,
            Self::Rdf => &PRED_ORDER_RDF,
        }
    }
}

pub struct FormatOptions {
    /// Do not edit the file but only check if it already applies this tools format.
    pub check: bool,
    /// Space(s) or tab(s) representing one level of indentation.
    pub indentation: String,
    /// Whether to move a single/lone object
    /// (within one subject-predicate pair) onto a new line,
    /// or to keep it on the same line as the predicate.
    pub single_leafed_new_lines: bool,
    /// Whether to force-write the output,
    /// even if potential issues with the formatting have been detected.
    ///
    /// One such issue would be,
    /// if comments have been found in the input.
    /// Because they will be completely removed in the output,
    /// we require `force = true` to try to avoid unintentional loss of information.
    pub force: bool,
    /// Whether to generate a `prtr:sortingId` for blank nodes
    /// that do not yet have one,
    /// and adding those triples to the RDF content to be printed.
    pub generate_sorting_ids: bool,
    /// Prioritize maintaining the input order vs keeping already assigned sorting IDs..
    ///
    /// If we are to generate `prtr:sortingId` values for blank nodes
    /// that do not yet have one but need one (see [`Self::generate_sorting_ids`],
    /// how should we do it?
    ///
    /// 1. If `prioritize_input_order = true`,
    ///    we will ensure `prtr:sortingId` values are assigned in the order
    ///    the blank nodes appear in the input.
    ///    This means, we will also potentially assign different values
    ///    to blank nodes that already have a `prtr:sortingId` value.
    ///    This on the other hand, may make the result less compatible with
    ///    other versions/branches of the same file,
    ///    that do not have this (same) reassignment.
    ///
    ///    We suggest to only choose this if the order your nodes are in
    ///    within the input is more important to you
    ///    then to keep the already assigned sorting IDs.
    ///    or if a scenario of merging conflicts
    ///    with other versions of the file is very unlikely.
    /// 2. If `prioritize_input_order = false`,
    ///    already assigned sorting IDs will be preserved to 100%,
    ///    and the blank nodes without ID will only remain
    ///    within the same order as in the input,
    ///    if there are enough free IDs between the already assigned ones.
    pub prioritize_input_order: bool,
    /// Sort blank nodes according to their `prtr:sortingId` value.
    ///
    /// [`prtr`](https://codeberg.org/elevont/prtr)
    /// is an ontology concerned with
    /// [RDF Pretty Printing](https://www.w3.org/DesignIssues/Pretty.html).
    pub prtr_sorting: bool,
    /// Whether to use SPARQL-ish syntax for base and prefix,
    /// or the traditional Turtle syntax.
    ///
    /// - SPARQL-ish:
    ///
    ///   ```turtle
    ///   BASE <http://example.com/>
    ///   PREFIX foaf: <http://xmlns.com/foaf/0.1/>
    ///   ```
    ///
    /// - Traditional Turtle:
    ///
    ///   ```turtle
    ///   @base <http://example.com/> .
    ///   @prefix foaf: <http://xmlns.com/foaf/0.1/> .
    ///   ```
    pub sparql_syntax: bool,
    /// Whether maximize nesting of blank nodes,
    /// or rather use labels for all of them.
    ///
    /// NOTE That blank nodes referenced in more then one place can never be nested.
    pub max_nesting: bool,
    /// Whether to canonicalize the input before formatting.
    /// This refers to <https://www.w3.org/TR/rdf-canon/>,
    /// and effectively just label the blank nodes in a uniform way.
    pub canonicalize: bool,
    /// Warn if a double or decimal literal can not be formatted as native Turtle literal.
    ///
    /// Turtles DOUBLE supports less formats then `xsd:double`,
    /// and DECIMAL supports less formats then `xsd:decimal`.
    /// See <https://github.com/w3c/rdf-turtle/issues/98> for more details.
    pub warn_unsupported_numbers: bool,
    /// A special subject type sorting order.
    ///
    /// This allows to choose _one_ predefined order of subject types,
    /// which prescribes the way subjects will be sorted
    /// according to their `a` (aka `rdf:type`) predicate value.
    /// The available options are somewhat common ways
    /// for sorting subjects according to their type,
    /// used in a certain context,
    /// e.g. OWL Ontologies, SKOS Vocabularies, SHACL Rules, etc.
    ///
    /// It uses the top most ordered type found,
    /// so tries to place a subject with types `list_idx_1` and `list_idx_3`
    /// before an other subject with type `list_idx_2`.
    ///
    /// NOTE: This does not use RDF inference, only 1-to-1 type matching!
    pub subject_type_order_preset: Option<SpecialSubjectTypeOrder>,
    /// A custom subject type sorting order.
    ///
    /// This allows you to define your own set of subject types to be sorted on top,
    /// which prescribes the way subjects will be sorted
    /// according to their `a` (aka `rdf:type`) predicate value.
    /// Each type can be defined as wither an absolute IRI,
    /// or as a prefixed name.
    ///
    /// It uses the top most ordered type found,
    /// so tries to place a subject with types `list_idx_1` and `list_idx_3`
    /// before an other subject with type `list_idx_2`.
    ///
    /// NOTE: This does not use RDF inference, only 1-to-1 type matching!
    pub subject_type_order: Option<Vec<String>>,
    /// A special predicate sorting order.
    ///
    /// This allows to choose _one_ predefined order of predicates.
    /// The available options are somewhat common ways
    /// for sorting the primary few predicates used in a certain context,
    /// e.g. OWL Ontologies, SKOS Vocabularies, SHACL Rules, etc.
    ///
    /// If this is used, it overrides the special case
    /// of sorting `a` (aka `rdf:type`) at the top.
    pub predicate_order_preset: Option<SpecialPredicateOrder>,
    /// A custom predicates sorting order.
    ///
    /// This allows you to define your own set of predicates to be sorted on top,
    /// and the order they should be sorted in.
    /// Each predicate can be defined as wither an absolute IRI,
    /// or as a prefixed name.
    ///
    /// If this is used, it overrides the special case
    /// of sorting `a` (aka `rdf:type`) at the top.
    /// If you still want that,
    /// you have to manually add include it in this list.
    pub predicate_order: Option<Vec<String>>,
}

impl Default for FormatOptions {
    fn default() -> Self {
        Self {
            check: true,
            indentation: "  ".to_string(),
            single_leafed_new_lines: false,
            force: false,
            generate_sorting_ids: false,
            prioritize_input_order: false,
            prtr_sorting: true,
            sparql_syntax: false,
            max_nesting: true,
            canonicalize: true,
            warn_unsupported_numbers: true,
            subject_type_order_preset: None,
            subject_type_order: None,
            predicate_order_preset: None,
            predicate_order: None,
        }
    }
}

impl FormatOptions {
    #[must_use]
    pub fn subject_type_order(&self) -> Option<Vec<String>> {
        self.subject_type_order.clone().or_else(|| {
            self.subject_type_order_preset
                .as_ref()
                .map(|variant| variant.as_list().iter().map(ToString::to_string).collect())
        })
    }

    #[must_use]
    pub fn predicate_order(&self) -> Vec<String> {
        self.predicate_order
            .clone()
            .or_else(|| {
                self.predicate_order_preset
                    .as_ref()
                    .map(|variant| variant.as_list().iter().map(ToString::to_string).collect())
            })
            .unwrap_or_else(|| vec!["rdf:type".to_string()])
    }
}