rudof_lib 0.2.20-rc.1

RDF data shapes implementation in Rust
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
use crate::{
    Result, Rudof,
    errors::DataError,
    formats::{IriNormalizationMode, NodeInspectionMode},
};
use prefixmap::IriRef;
use rudof_iri::IriS;
use rudof_rdf::rdf_core::{NeighsRDF, query::QueryRDF};
use shex_ast::{ShapeMapParser, shapemap::NodeSelector};
use std::{collections::HashMap, fmt::Debug, io};
use termtree::Tree;

pub fn show_node_info<W: io::Write>(
    rudof: &mut Rudof,
    node: &str,
    predicates: Option<&[String]>,
    show_node_mode: Option<&NodeInspectionMode>,
    depth: Option<usize>,
    show_hyperlinks: Option<bool>,
    show_colors: Option<bool>,
    iri_mode: IriNormalizationMode,
    writer: &mut W,
) -> Result<()> {
    let config = NodeDisplayConfig::from_options(predicates, show_node_mode, depth, show_hyperlinks, show_colors);

    let data = rudof.data.as_mut().ok_or(Box::new(DataError::NoRdfDataLoaded))?;

    if !data.is_rdf() {
        return Err(Box::new(DataError::NoRdfDataLoaded).into());
    }

    let node_selector = parse_node_selector(node, iri_mode)?;

    let node_infos = collect_node_information(data.unwrap_rdf_mut(), node_selector, &config)?;

    write_node_information_list(&node_infos, data.unwrap_rdf_mut(), writer, &config)?;

    Ok(())
}

/// Collects information for all nodes matching the selector.
///
/// This function:
/// 1. Resolves the node selector to concrete nodes
/// 2. For each node, gathers outgoing and incoming arcs based on configuration
/// 3. Returns a list of `NodeInfo` structures
fn collect_node_information<R>(
    rdf: &R,
    node_selector: NodeSelector,
    config: &NodeDisplayConfig,
) -> Result<Vec<NodeInfo<R>>>
where
    R: NeighsRDF + Debug + QueryRDF,
{
    let nodes = node_selector
        .nodes(rdf)
        .map_err(|e| Box::new(DataError::FailedArcRetrieval { error: e.to_string() }))?;

    nodes.iter().map(|node| build_node_info(rdf, node, config)).collect()
}

/// Builds complete information for a single node.
fn build_node_info<R>(rdf: &R, node: &R::Term, config: &NodeDisplayConfig) -> Result<NodeInfo<R>>
where
    R: NeighsRDF + Debug + QueryRDF,
{
    let subject =
        R::term_as_subject(node).map_err(|e| Box::new(DataError::FailedQualification { error: e.to_string() }))?;

    let subject_qualified = qualify_subject(rdf, &subject, config.show_colors)?;

    let outgoing = if config.mode.show_outgoing() {
        collect_outgoing_arcs_recursive(rdf, &subject, &config.predicates, config.depth)?
    } else {
        HashMap::new()
    };

    let incoming = if config.mode.show_incoming() {
        collect_incoming_arcs_recursive(rdf, &subject, config.depth)?
    } else {
        HashMap::new()
    };

    Ok(NodeInfo {
        subject,
        subject_qualified,
        outgoing,
        incoming,
    })
}

/// Recursively collects outgoing arcs up to the specified depth.
///
/// # Depth Behavior
///
/// * `depth = 1`: Returns only direct neighbors as `OutgoingNeighsNode::Term`
/// * `depth > 1`: Recursively traverses, storing nested relationships in `OutgoingNeighsNode::More`
fn collect_outgoing_arcs_recursive<S: NeighsRDF>(
    rdf: &S,
    subject: &S::Subject,
    predicates: &[String],
    depth: usize,
) -> Result<HashMap<S::IRI, Vec<OutgoingNeighsNode<S>>>> {
    // Base case: depth 1 means no recursion
    if depth == 1 {
        return Ok(collect_outgoing_arcs(rdf, subject, predicates)?
            .into_iter()
            .map(|(predicate, terms)| {
                let nodes = terms
                    .into_iter()
                    .map(|term| OutgoingNeighsNode::Term { term })
                    .collect();
                (predicate, nodes)
            })
            .collect());
    }

    // Recursive case: depth > 1
    let arc_map = if predicates.is_empty() {
        rdf.outgoing_arcs(subject)
            .map_err(|e| Box::new(DataError::FailedArcRetrieval { error: e.to_string() }))?
    } else {
        let predicate_iris = convert_predicate_strings_to_iris(predicates, rdf)?;
        let (map, _not_found) = rdf
            .outgoing_arcs_from_list(subject, &predicate_iris)
            .map_err(|e| Box::new(DataError::FailedArcRetrieval { error: e.to_string() }))?;
        map
    };

    let mut result = HashMap::new();

    for (predicate, objects) in arc_map {
        let mut nodes = Vec::new();

        for object in objects {
            // Attempt to treat the object as a subject for further traversal
            let nested_arcs = match S::term_as_subject(&object) {
                Ok(obj_as_subject) => {
                    // Successfully converted to subject, recurse
                    collect_outgoing_arcs_recursive(rdf, &obj_as_subject, predicates, depth - 1)?
                },
                Err(_) => {
                    // Cannot be a subject (e.g., it's a literal), no further traversal
                    HashMap::new()
                },
            };

            nodes.push(OutgoingNeighsNode::More {
                term: object,
                rest: nested_arcs,
            });
        }

        result.insert(predicate, nodes);
    }

    Ok(result)
}

/// Retrieves outgoing arcs for a subject with optional predicate filtering.
///
/// This is a non-recursive version that returns a simple HashMap of predicates to terms.
fn collect_outgoing_arcs<S: NeighsRDF>(
    rdf: &S,
    subject: &S::Subject,
    predicates: &[String],
) -> Result<HashMap<S::IRI, Vec<S::Term>>> {
    let arc_map = if predicates.is_empty() {
        rdf.outgoing_arcs(subject)
            .map_err(|e| Box::new(DataError::FailedArcRetrieval { error: e.to_string() }))?
    } else {
        let predicate_iris = convert_predicate_strings_to_iris(predicates, rdf)?;
        let (map, _not_found) = rdf
            .outgoing_arcs_from_list(subject, &predicate_iris)
            .map_err(|e| Box::new(DataError::FailedArcRetrieval { error: e.to_string() }))?;
        map
    };

    Ok(arc_map
        .into_iter()
        .map(|(predicate, objects)| (predicate, objects.into_iter().collect()))
        .collect())
}

/// Recursively collects incoming arcs up to the specified depth.
///
/// # Depth Behavior
///
/// * `depth = 1`: Returns only direct parents as `IncomingNeighsNode::Term`
/// * `depth > 1`: Recursively traverses upward, storing nested relationships
fn collect_incoming_arcs_recursive<S: NeighsRDF>(
    rdf: &S,
    subject: &S::Subject,
    depth: usize,
) -> Result<HashMap<S::IRI, Vec<IncomingNeighsNode<S>>>> {
    // Base case: depth 1 means no recursion
    if depth == 1 {
        let incoming_arcs = collect_incoming_arcs(rdf, subject)?;
        return Ok(incoming_arcs
            .into_iter()
            .map(|(predicate, subjects)| {
                let nodes = subjects
                    .iter()
                    .map(|s| IncomingNeighsNode::Term {
                        term: S::subject_as_term(s),
                    })
                    .collect();
                (predicate, nodes)
            })
            .collect());
    }

    // Recursive case: depth > 1
    let object: S::Term = subject.clone().into();
    let arc_map = rdf
        .incoming_arcs(&object)
        .map_err(|e| Box::new(DataError::FailedArcRetrieval { error: e.to_string() }))?;

    let mut result = HashMap::new();

    for (predicate, subjects) in arc_map {
        let mut nodes = Vec::new();

        for subj in subjects {
            // Recurse on each incoming subject
            let nested_arcs = collect_incoming_arcs_recursive(rdf, &subj, depth - 1)?;
            nodes.push(IncomingNeighsNode::More {
                term: S::subject_as_term(&subj),
                rest: nested_arcs,
            });
        }

        result.insert(predicate, nodes);
    }

    Ok(result)
}

/// Retrieves incoming arcs for a subject (non-recursive).
///
/// Finds all subjects that have this node as an object.
fn collect_incoming_arcs<S: NeighsRDF>(rdf: &S, subject: &S::Subject) -> Result<HashMap<S::IRI, Vec<S::Subject>>> {
    let object: S::Term = subject.clone().into();

    let arc_map = rdf
        .incoming_arcs(&object)
        .map_err(|e| Box::new(DataError::FailedArcRetrieval { error: e.to_string() }))?;

    Ok(arc_map
        .into_iter()
        .map(|(predicate, subjects)| (predicate, subjects.into_iter().collect()))
        .collect())
}

/// Writes formatted node information for multiple nodes.
fn write_node_information_list<S: NeighsRDF, W: io::Write>(
    node_infos: &[NodeInfo<S>],
    rdf: &S,
    writer: &mut W,
    config: &NodeDisplayConfig,
) -> Result<()> {
    for node_info in node_infos {
        write_node_information(node_info, rdf, writer, config)?;
    }
    Ok(())
}

/// Writes formatted information for a single node.
///
/// Outputs:
/// * Outgoing arcs as a tree (if enabled)
/// * Incoming arcs as a tree (if enabled)
fn write_node_information<S: NeighsRDF, W: io::Write>(
    node_info: &NodeInfo<S>,
    rdf: &S,
    writer: &mut W,
    config: &NodeDisplayConfig,
) -> Result<()> {
    // Display outgoing arcs if requested and present
    if config.mode.show_outgoing() && !node_info.outgoing.is_empty() {
        writeln!(writer, "Outgoing arcs")
            .map_err(|e| Box::new(DataError::FailedIoOperation { error: e.to_string() }))?;

        let mut tree = Tree::new(node_info.subject_qualified.clone()).with_glyphs(create_outgoing_glyphs());

        build_outgoing_tree(&mut tree, &node_info.outgoing, rdf, config)?;

        writeln!(writer, "{}", tree).map_err(|e| Box::new(DataError::FailedIoOperation { error: e.to_string() }))?;
    }

    if config.mode.show_incoming() && !node_info.incoming.is_empty() {
        writeln!(writer, "Incoming arcs")
            .map_err(|e| Box::new(DataError::FailedIoOperation { error: e.to_string() }))?;

        let subject_qualified = qualify_subject(rdf, &node_info.subject, config.show_colors)?;
        let root_label = format!("{}\nâ–²", subject_qualified);

        let mut tree = Tree::new(root_label).with_glyphs(create_incoming_glyphs());

        build_incoming_tree(&mut tree, &node_info.incoming, rdf, config)?;

        writeln!(writer, "{}", tree).map_err(|e| Box::new(DataError::FailedIoOperation { error: e.to_string() }))?;
    }

    Ok(())
}

/// Recursively builds a tree representation of outgoing arcs.
fn build_outgoing_tree<S: NeighsRDF>(
    tree: &mut Tree<String>,
    outgoing_arcs: &HashMap<S::IRI, Vec<OutgoingNeighsNode<S>>>,
    rdf: &S,
    config: &NodeDisplayConfig,
) -> Result<()> {
    let mut predicates: Vec<_> = outgoing_arcs.keys().collect();
    predicates.sort();

    for predicate in predicates {
        let pred_str = qualify_iri(rdf, predicate, config.show_colors);

        if let Some(objects) = outgoing_arcs.get(predicate) {
            for object_node in objects {
                match object_node {
                    OutgoingNeighsNode::Term { term } => {
                        let obj_str = qualify_term(rdf, term, config.show_colors)?;
                        let label = format!("─ {} ─► {}", pred_str, obj_str);
                        tree.leaves.push(Tree::new(label).with_glyphs(create_outgoing_glyphs()));
                    },
                    OutgoingNeighsNode::More { term, rest } => {
                        let obj_str = qualify_term(rdf, term, config.show_colors)?;
                        let label = format!("─ {} ─► {}", pred_str, obj_str);

                        let mut subtree = Tree::new(label).with_glyphs(create_outgoing_glyphs());

                        build_outgoing_tree(&mut subtree, rest, rdf, config)?;
                        tree.leaves.push(subtree);
                    },
                }
            }
        }
    }

    Ok(())
}

/// Recursively builds a tree representation of incoming arcs.
fn build_incoming_tree<S: NeighsRDF>(
    tree: &mut Tree<String>,
    incoming_arcs: &HashMap<S::IRI, Vec<IncomingNeighsNode<S>>>,
    rdf: &S,
    config: &NodeDisplayConfig,
) -> Result<()> {
    let mut predicates: Vec<_> = incoming_arcs.keys().collect();
    predicates.sort();

    for predicate in predicates {
        let pred_str = qualify_iri(rdf, predicate, config.show_colors);

        if let Some(subjects) = incoming_arcs.get(predicate) {
            for subject_node in subjects {
                match subject_node {
                    IncomingNeighsNode::Term { term } => {
                        let subj_str = qualify_term(rdf, term, config.show_colors)?;
                        let label = format!("─ {} ── {}", pred_str, subj_str);
                        tree.leaves.push(Tree::new(label).with_glyphs(create_incoming_glyphs()));
                    },
                    IncomingNeighsNode::More { term, rest } => {
                        let subj_str = qualify_term(rdf, term, config.show_colors)?;
                        let label = format!("─ {} ── {}", pred_str, subj_str);

                        let mut subtree = Tree::new(label).with_glyphs(create_incoming_glyphs());

                        build_incoming_tree(&mut subtree, rest, rdf, config)?;
                        tree.leaves.push(subtree);
                    },
                }
            }
        }
    }

    Ok(())
}

/// Creates glyph configuration for incoming arc trees.
fn create_incoming_glyphs() -> termtree::GlyphPalette {
    termtree::GlyphPalette {
        middle_item: "├",
        last_item: "â””",
        item_indent: "──",
        middle_skip: "│",
        last_skip: "",
        skip_indent: "   ",
    }
}

/// Creates glyph configuration for outgoing arc trees.
fn create_outgoing_glyphs() -> termtree::GlyphPalette {
    termtree::GlyphPalette {
        middle_item: "├",
        last_item: "â””",
        item_indent: "──",
        middle_skip: "│",
        last_skip: "",
        skip_indent: "   ",
    }
}

/// Parses a node selector string into a `NodeSelector` instance.
///
/// Supports various formats:
/// * Full IRIs: `<http://example.org/node>` or `http://example.org/node` (lax mode only)
/// * Prefixed names: `ex:node`
/// * Blank nodes: `_:b1`
fn parse_node_selector(node_str: &str, iri_mode: IriNormalizationMode) -> Result<NodeSelector> {
    let normalized = crate::utils::normalize_iri_str(node_str, iri_mode);
    let node_str = normalized.as_str();
    ShapeMapParser::parse_node_selector(node_str).map_err(|e| {
        Box::new(DataError::FailedNodeSelectorParse {
            node: node_str.to_string(),
            error: e.to_string(),
        })
        .into()
    })
}

/// Parses an IRI reference string into a structured `IriRef`.
fn parse_iri_ref(iri: &str) -> Result<IriRef> {
    ShapeMapParser::parse_iri_ref(iri).map_err(|e| {
        Box::new(DataError::FailedIriRefParse {
            iri: iri.to_string(),
            error: e.to_string(),
        })
        .into()
    })
}

/// Converts predicate strings to IRI objects.
///
/// Handles both prefixed names (e.g., `"rdf:type"`) and full IRIs.
fn convert_predicate_strings_to_iris<S>(predicates: &[String], rdf: &S) -> Result<Vec<S::IRI>>
where
    S: NeighsRDF,
{
    predicates
        .iter()
        .map(|pred_str| {
            let iri_ref = parse_iri_ref(pred_str)?;

            let iri_s = match iri_ref {
                IriRef::Prefixed { prefix, local } => {
                    // Resolve prefix:local to full IRI
                    rdf.resolve_prefix_local(prefix.as_str(), local.as_str()).map_err(|e| {
                        Box::new(DataError::FailedPrefixResolution {
                            prefix: prefix.to_string(),
                            error: e.to_string(),
                        })
                    })?
                },
                IriRef::Iri(iri) => iri,
            };

            Ok(iri_s.into())
        })
        .collect()
}

/// Converts a subject to its qualified string representation.
fn qualify_subject<S: NeighsRDF>(rdf: &S, subject: &S::Subject, show_colors: bool) -> Result<String> {
    if show_colors {
        Ok(rdf.qualify_subject(subject))
    } else {
        let prefixmap = rdf.prefixmap().unwrap_or_default().clone().without_colors();

        let subject_term = S::subject_as_term(subject);
        let node = S::term_as_object(&subject_term)
            .map_err(|e| Box::new(DataError::FailedQualification { error: e.to_string() }))?;

        Ok(node.show_qualified(&prefixmap))
    }
}

/// Converts an IRI to its qualified string representation.
fn qualify_iri<S: NeighsRDF>(rdf: &S, iri: &S::IRI, show_colors: bool) -> String {
    if show_colors {
        rdf.qualify_iri(iri)
    } else {
        let prefixmap = rdf.prefixmap().unwrap_or_default().clone().without_colors();

        let iri_s: IriS = iri.clone().into();
        prefixmap.qualify(&iri_s)
    }
}

/// Converts an RDF term to its qualified string representation.
fn qualify_term<S: NeighsRDF>(rdf: &S, term: &S::Term, show_colors: bool) -> Result<String> {
    if show_colors {
        Ok(rdf.qualify_term(term))
    } else {
        let prefixmap = rdf.prefixmap().unwrap_or_default().clone().without_colors();

        let node =
            S::term_as_object(term).map_err(|e| Box::new(DataError::FailedQualification { error: e.to_string() }))?;

        Ok(node.show_qualified(&prefixmap))
    }
}

/// Configuration for node display operations.
///
/// Encapsulates all display preferences to avoid passing many individual parameters.
#[derive(Debug, Clone)]
struct NodeDisplayConfig {
    predicates: Vec<String>,
    mode: NodeInspectionMode,
    depth: usize,
    _show_hyperlinks: bool,
    show_colors: bool,
}

impl NodeDisplayConfig {
    /// Creates a configuration from optional parameters, applying defaults.
    fn from_options(
        predicates: Option<&[String]>,
        mode: Option<&NodeInspectionMode>,
        depth: Option<usize>,
        show_hyperlinks: Option<bool>,
        show_colors: Option<bool>,
    ) -> Self {
        Self {
            predicates: predicates.map(|p| p.to_vec()).unwrap_or_default(),
            mode: mode.copied().unwrap_or_default(),
            depth: depth.unwrap_or(1),
            _show_hyperlinks: show_hyperlinks.unwrap_or(false),
            show_colors: show_colors.unwrap_or(true),
        }
    }
}

/// Complete information about a node in the RDF graph.
///
/// Contains both the raw subject and its qualified (prefixed) string representation,
/// along with all incoming and outgoing relationships.
#[derive(Debug, Clone)]
pub struct NodeInfo<S: NeighsRDF> {
    /// The RDF subject being described
    pub subject: S::Subject,
    /// Human-readable qualified name (e.g., "ex:Person1")
    pub subject_qualified: String,
    /// Outgoing arcs grouped by predicate
    pub outgoing: HashMap<S::IRI, Vec<OutgoingNeighsNode<S>>>,
    /// Incoming arcs grouped by predicate
    pub incoming: HashMap<S::IRI, Vec<IncomingNeighsNode<S>>>,
}

/// Represents a neighboring node in the outgoing direction.
///
/// This enum supports recursive depth traversal by storing either a simple term
/// or a term with additional nested relationships.
#[derive(Debug, Clone)]
pub enum OutgoingNeighsNode<S: NeighsRDF> {
    /// Leaf node with no further traversal
    Term { term: S::Term },
    /// Node with additional outgoing relationships
    More {
        term: S::Term,
        /// Nested relationships keyed by predicate
        rest: HashMap<S::IRI, Vec<OutgoingNeighsNode<S>>>,
    },
}

/// Represents a neighboring node in the incoming direction.
///
/// Similar to `OutgoingNeighsNode` but for incoming arcs (subjects pointing to this node).
#[derive(Debug, Clone)]
pub enum IncomingNeighsNode<S: NeighsRDF> {
    /// Leaf node with no further traversal
    Term { term: S::Term },
    /// Node with additional incoming relationships
    More {
        term: S::Term,
        /// Nested relationships keyed by predicate
        rest: HashMap<S::IRI, Vec<IncomingNeighsNode<S>>>,
    },
}