Skip to main content

link_cli/
parser.rs

1//! LiNo Parser - Parses LiNo notation into LinoLink structures.
2//!
3//! This module adapts the upstream `links-notation` parser into the local
4//! `LinoLink` representation used by the query processor.
5
6use crate::error::LinkError;
7use crate::lino_link::LinoLink;
8use links_notation::{parse_lino_to_links, parse_lino_to_links_with_config, LiNo, ParserConfig};
9
10/// Parser for LiNo notation
11/// Corresponds to Link.Foundation.Links.Notation.Parser in C#
12pub struct Parser;
13
14impl Parser {
15    /// Creates a new Parser instance
16    pub fn new() -> Self {
17        Self
18    }
19
20    /// Parses a LiNo query string into a list of LinoLinks
21    pub fn parse(&self, query: &str) -> Result<Vec<LinoLink>, LinkError> {
22        parse_lino_to_links(query)
23            .map(|links| links.into_iter().map(Self::convert_link).collect())
24            .map_err(|error| LinkError::ParseError(error.to_string()))
25    }
26
27    /// Admit nesting with the notation grammar before converting its document.
28    pub fn parse_with_max_depth(
29        &self,
30        query: &str,
31        depth: usize,
32    ) -> Result<Vec<LinoLink>, LinkError> {
33        parse_lino_to_links_with_config(query, &ParserConfig::new().with_max_depth(depth))
34            .map(|links| links.into_iter().map(Self::convert_link).collect())
35            .map_err(|error| LinkError::ParseError(error.to_string()))
36    }
37
38    fn convert_link(link: LiNo<String>) -> LinoLink {
39        match link {
40            LiNo::Ref(id) => LinoLink::new(Some(id)),
41            LiNo::Link { id, values } if values.is_empty() => {
42                id.map(|id| LinoLink::new(Some(id))).unwrap_or_default()
43            }
44            LiNo::Link { id, values } => {
45                LinoLink::with_values(id, values.into_iter().map(Self::convert_link).collect())
46            }
47        }
48    }
49}
50
51impl Default for Parser {
52    fn default() -> Self {
53        Self::new()
54    }
55}