links-notation 0.13.0

Rust implementation of the Links Notation parser
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
pub mod format_config;
pub mod parser;

use format_config::FormatConfig;
use std::error::Error as StdError;
use std::fmt;

/// Error type for Lino parsing
#[derive(Debug)]
pub enum ParseError {
    /// Input string is empty or contains only whitespace
    EmptyInput,
    /// Syntax error during parsing
    SyntaxError(String),
    /// Internal parser error
    InternalError(String),
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ParseError::EmptyInput => write!(f, "Empty input"),
            ParseError::SyntaxError(msg) => write!(f, "Syntax error: {}", msg),
            ParseError::InternalError(msg) => write!(f, "Internal error: {}", msg),
        }
    }
}

impl StdError for ParseError {}

#[derive(Debug, Clone, PartialEq)]
pub enum LiNo<T> {
    Link { id: Option<T>, values: Vec<Self> },
    Ref(T),
}

impl<T> LiNo<T> {
    pub fn is_ref(&self) -> bool {
        matches!(self, LiNo::Ref(_))
    }

    pub fn is_link(&self) -> bool {
        matches!(self, LiNo::Link { .. })
    }
}

impl<T: ToString + Clone> LiNo<T> {
    /// Format the link using FormatConfig configuration.
    ///
    /// # Arguments
    /// * `config` - The FormatConfig to use for formatting
    ///
    /// # Returns
    /// Formatted string representation
    pub fn format_with_config(&self, config: &FormatConfig) -> String {
        match self {
            LiNo::Ref(value) => {
                let escaped = escape_reference(&value.to_string());
                if config.less_parentheses {
                    escaped
                } else {
                    format!("({})", escaped)
                }
            }
            LiNo::Link { id, values } => {
                // Empty link
                if id.is_none() && values.is_empty() {
                    return if config.less_parentheses {
                        String::new()
                    } else {
                        "()".to_string()
                    };
                }

                // Link with only ID, no values
                if values.is_empty() {
                    if let Some(ref id_val) = id {
                        let escaped_id = escape_reference(&id_val.to_string());
                        return if config.less_parentheses && !needs_parentheses(&id_val.to_string())
                        {
                            escaped_id
                        } else {
                            format!("({})", escaped_id)
                        };
                    }
                    return if config.less_parentheses {
                        String::new()
                    } else {
                        "()".to_string()
                    };
                }

                // Check if we should use indented format
                let mut should_indent = false;
                if config.should_indent_by_ref_count(values.len()) {
                    should_indent = true;
                } else {
                    // Try inline format first to check line length
                    let values_str = values
                        .iter()
                        .map(|v| format_value(v))
                        .collect::<Vec<_>>()
                        .join(" ");

                    let test_line = if let Some(ref id_val) = id {
                        let id_str = escape_reference(&id_val.to_string());
                        if config.less_parentheses {
                            format!("{}: {}", id_str, values_str)
                        } else {
                            format!("({}: {})", id_str, values_str)
                        }
                    } else if config.less_parentheses {
                        values_str.clone()
                    } else {
                        format!("({})", values_str)
                    };

                    if config.should_indent_by_length(&test_line) {
                        should_indent = true;
                    }
                }

                // Format with indentation if needed
                if should_indent && !config.prefer_inline {
                    return self.format_indented(config);
                }

                // Standard inline formatting
                let values_str = values
                    .iter()
                    .map(|v| format_value(v))
                    .collect::<Vec<_>>()
                    .join(" ");

                // Link with values only (null id)
                if id.is_none() {
                    if config.less_parentheses {
                        // Check if all values are simple (no nested values)
                        let all_simple = values.iter().all(|v| matches!(v, LiNo::Ref(_)));
                        if all_simple {
                            return values
                                .iter()
                                .map(|v| match v {
                                    LiNo::Ref(r) => escape_reference(&r.to_string()),
                                    _ => format_value(v),
                                })
                                .collect::<Vec<_>>()
                                .join(" ");
                        }
                        return values_str;
                    }
                    return format!("({})", values_str);
                }

                // Link with ID and values
                let id_str = escape_reference(&id.as_ref().unwrap().to_string());
                let with_colon = format!("{}: {}", id_str, values_str);
                if config.less_parentheses && !needs_parentheses(&id.as_ref().unwrap().to_string())
                {
                    with_colon
                } else {
                    format!("({})", with_colon)
                }
            }
        }
    }

    /// Format the link with indentation.
    fn format_indented(&self, config: &FormatConfig) -> String {
        match self {
            LiNo::Ref(value) => {
                let escaped = escape_reference(&value.to_string());
                format!("({})", escaped)
            }
            LiNo::Link { id, values } => {
                if id.is_none() {
                    // Values only - format each on separate line
                    values
                        .iter()
                        .map(|v| format!("{}{}", config.indent_string, format_value(v)))
                        .collect::<Vec<_>>()
                        .join("\n")
                } else {
                    // Link with ID - format as id:\n  value1\n  value2
                    let id_str = escape_reference(&id.as_ref().unwrap().to_string());
                    let mut lines = vec![format!("{}:", id_str)];
                    for v in values {
                        lines.push(format!("{}{}", config.indent_string, format_value(v)));
                    }
                    lines.join("\n")
                }
            }
        }
    }
}

impl<T: ToString> fmt::Display for LiNo<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LiNo::Ref(value) => write!(f, "{}", value.to_string()),
            LiNo::Link { id, values } => {
                let id_str = id
                    .as_ref()
                    .map(|id| format!("{}: ", id.to_string()))
                    .unwrap_or_default();

                if f.alternate() {
                    // Format top-level as lines
                    let lines = values
                        .iter()
                        .map(|value| {
                            // For alternate formatting, ensure standalone references are wrapped in parentheses
                            // so that flattened structures like indented blocks render as "(ref)" lines
                            match value {
                                LiNo::Ref(_) => format!("{}({})", id_str, value),
                                _ => format!("{}{}", id_str, value),
                            }
                        })
                        .collect::<Vec<_>>()
                        .join("\n");
                    write!(f, "{}", lines)
                } else {
                    let values_str = values
                        .iter()
                        .map(|value| value.to_string())
                        .collect::<Vec<_>>()
                        .join(" ");
                    write!(f, "({}{})", id_str, values_str)
                }
            }
        }
    }
}

// Convert from parser::Link to LiNo (without flattening)
impl From<parser::Link> for LiNo<String> {
    fn from(link: parser::Link) -> Self {
        if link.values.is_empty() && link.children.is_empty() {
            if let Some(id) = link.id {
                LiNo::Ref(id)
            } else {
                LiNo::Link {
                    id: None,
                    values: vec![],
                }
            }
        } else {
            let values: Vec<LiNo<String>> = link.values.into_iter().map(|v| v.into()).collect();
            LiNo::Link {
                id: link.id,
                values,
            }
        }
    }
}

// Helper function to flatten indented structures according to Lino spec
fn flatten_links(links: Vec<parser::Link>) -> Vec<LiNo<String>> {
    let mut result = vec![];

    for link in links {
        flatten_link_recursive(&link, None, &mut result);
    }

    result
}

fn flatten_link_recursive(
    link: &parser::Link,
    parent: Option<&LiNo<String>>,
    result: &mut Vec<LiNo<String>>,
) {
    // Special case: If this is an indented ID (with colon) with children,
    // the children should become the values of the link (indented ID syntax)
    if link.is_indented_id
        && link.id.is_some()
        && link.values.is_empty()
        && !link.children.is_empty()
    {
        let child_values: Vec<LiNo<String>> = link
            .children
            .iter()
            .map(|child| {
                // For indented children, if they have single values, extract them
                if child.values.len() == 1
                    && child.values[0].values.is_empty()
                    && child.values[0].children.is_empty()
                {
                    // Use if let to safely extract the ID instead of unwrap()
                    if let Some(ref id) = child.values[0].id {
                        LiNo::Ref(id.clone())
                    } else {
                        // If no ID, create an empty link
                        parser::Link {
                            id: child.id.clone(),
                            values: child.values.clone(),
                            children: vec![],
                            is_indented_id: false,
                        }
                        .into()
                    }
                } else {
                    parser::Link {
                        id: child.id.clone(),
                        values: child.values.clone(),
                        children: vec![],
                        is_indented_id: false,
                    }
                    .into()
                }
            })
            .collect();

        let current = LiNo::Link {
            id: link.id.clone(),
            values: child_values,
        };

        let combined = if let Some(parent) = parent {
            // Wrap parent in parentheses if it's a reference
            let wrapped_parent = match parent {
                LiNo::Ref(ref_id) => LiNo::Link {
                    id: None,
                    values: vec![LiNo::Ref(ref_id.clone())],
                },
                link => link.clone(),
            };

            LiNo::Link {
                id: None,
                values: vec![wrapped_parent, current],
            }
        } else {
            current
        };

        result.push(combined);
        return; // Don't process children again
    }

    // Create the current link without children
    let current = if link.values.is_empty() {
        if let Some(id) = &link.id {
            LiNo::Ref(id.clone())
        } else {
            LiNo::Link {
                id: None,
                values: vec![],
            }
        }
    } else {
        let values: Vec<LiNo<String>> = link
            .values
            .iter()
            .map(|v| {
                parser::Link {
                    id: v.id.clone(),
                    values: v.values.clone(),
                    children: vec![],
                    is_indented_id: false,
                }
                .into()
            })
            .collect();
        LiNo::Link {
            id: link.id.clone(),
            values,
        }
    };

    // Create the combined link (parent + current) with proper wrapping
    let combined = if let Some(parent) = parent {
        // Wrap parent in parentheses if it's a reference
        let wrapped_parent = match parent {
            LiNo::Ref(ref_id) => LiNo::Link {
                id: None,
                values: vec![LiNo::Ref(ref_id.clone())],
            },
            link => link.clone(),
        };

        // Wrap current in parentheses if it's a reference
        let wrapped_current = match &current {
            LiNo::Ref(ref_id) => LiNo::Link {
                id: None,
                values: vec![LiNo::Ref(ref_id.clone())],
            },
            link => link.clone(),
        };

        LiNo::Link {
            id: None,
            values: vec![wrapped_parent, wrapped_current],
        }
    } else {
        current.clone()
    };

    result.push(combined.clone());

    // Process children
    for child in &link.children {
        flatten_link_recursive(child, Some(&combined), result);
    }
}

pub fn parse_lino(document: &str) -> Result<LiNo<String>, ParseError> {
    // Handle empty or whitespace-only input by returning empty result
    if document.trim().is_empty() {
        return Ok(LiNo::Link {
            id: None,
            values: vec![],
        });
    }

    match parser::parse_document(document) {
        Ok((_, links)) => {
            if links.is_empty() {
                Ok(LiNo::Link {
                    id: None,
                    values: vec![],
                })
            } else {
                // Flatten the indented structure according to Lino spec
                let flattened = flatten_links(links);
                Ok(LiNo::Link {
                    id: None,
                    values: flattened,
                })
            }
        }
        Err(e) => Err(ParseError::SyntaxError(format!("{:?}", e))),
    }
}

// New function that matches C# and JS API - returns collection of links
pub fn parse_lino_to_links(document: &str) -> Result<Vec<LiNo<String>>, ParseError> {
    // Handle empty or whitespace-only input by returning empty collection
    if document.trim().is_empty() {
        return Ok(vec![]);
    }

    match parser::parse_document(document) {
        Ok((_, links)) => {
            if links.is_empty() {
                Ok(vec![])
            } else {
                // Flatten the indented structure according to Lino spec
                let flattened = flatten_links(links);
                Ok(flattened)
            }
        }
        Err(e) => Err(ParseError::SyntaxError(format!("{:?}", e))),
    }
}

/// Formats a collection of LiNo links as a multi-line string.
/// Each link is formatted on a separate line.
pub fn format_links(links: &[LiNo<String>]) -> String {
    links
        .iter()
        .map(|link| format!("{}", link))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Formats a collection of LiNo links as a multi-line string using FormatConfig.
/// Supports all formatting options including consecutive link grouping.
///
/// # Arguments
/// * `links` - The collection of links to format
/// * `config` - The FormatConfig to use for formatting
///
/// # Returns
/// Formatted string in Lino notation
pub fn format_links_with_config(links: &[LiNo<String>], config: &FormatConfig) -> String {
    if links.is_empty() {
        return String::new();
    }

    // Apply consecutive link grouping if enabled
    let links_to_format = if config.group_consecutive {
        group_consecutive_links(links)
    } else {
        links.to_vec()
    };

    links_to_format
        .iter()
        .map(|link| link.format_with_config(config))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Groups consecutive links with the same ID.
///
/// For example:
/// ```text
/// SetA a
/// SetA b
/// SetA c
/// ```
/// Becomes:
/// ```text
/// SetA
///   a
///   b
///   c
/// ```
fn group_consecutive_links(links: &[LiNo<String>]) -> Vec<LiNo<String>> {
    if links.is_empty() {
        return vec![];
    }

    let mut grouped = vec![];
    let mut i = 0;

    while i < links.len() {
        let current = &links[i];

        // Look ahead for consecutive links with same ID
        if let LiNo::Link {
            id: Some(ref current_id),
            values: ref current_values,
        } = current
        {
            if !current_values.is_empty() {
                // Collect all values with same ID
                let mut same_id_values = current_values.clone();
                let mut j = i + 1;

                while j < links.len() {
                    if let LiNo::Link {
                        id: Some(ref next_id),
                        values: ref next_values,
                    } = &links[j]
                    {
                        if next_id == current_id && !next_values.is_empty() {
                            same_id_values.extend(next_values.clone());
                            j += 1;
                        } else {
                            break;
                        }
                    } else {
                        break;
                    }
                }

                // If we found consecutive links, create grouped link
                if j > i + 1 {
                    grouped.push(LiNo::Link {
                        id: Some(current_id.clone()),
                        values: same_id_values,
                    });
                    i = j;
                    continue;
                }
            }
        }

        grouped.push(current.clone());
        i += 1;
    }

    grouped
}

/// Escape a reference string by adding quotes if necessary.
fn escape_reference(reference: &str) -> String {
    if reference.is_empty() || reference.trim().is_empty() {
        return String::new();
    }

    let has_single_quote = reference.contains('\'');
    let has_double_quote = reference.contains('"');

    let needs_quoting = reference.contains(':')
        || reference.contains('(')
        || reference.contains(')')
        || reference.contains(' ')
        || reference.contains('\t')
        || reference.contains('\n')
        || reference.contains('\r')
        || has_double_quote
        || has_single_quote;

    // Handle edge case: reference contains both single and double quotes
    if has_single_quote && has_double_quote {
        // Escape single quotes and wrap in single quotes
        return format!("'{}'", reference.replace('\'', "\\'"));
    }

    // Prefer single quotes if double quotes are present
    if has_double_quote {
        return format!("'{}'", reference);
    }

    // Use double quotes if single quotes are present
    if has_single_quote {
        return format!("\"{}\"", reference);
    }

    // Use single quotes for special characters
    if needs_quoting {
        return format!("'{}'", reference);
    }

    // No quoting needed
    reference.to_string()
}

/// Check if a string needs to be wrapped in parentheses.
fn needs_parentheses(s: &str) -> bool {
    s.contains(' ') || s.contains(':') || s.contains('(') || s.contains(')')
}

/// Format a value within a link.
fn format_value<T: ToString>(value: &LiNo<T>) -> String {
    match value {
        LiNo::Ref(r) => escape_reference(&r.to_string()),
        LiNo::Link { id, values } => {
            // Simple link with just an ID - don't wrap in extra parentheses
            if values.is_empty() {
                if let Some(ref id_val) = id {
                    return escape_reference(&id_val.to_string());
                }
                return String::new();
            }
            // Complex value - format with parentheses
            format!("{}", value)
        }
    }
}