rowl 0.1.3

Parser for the Dolfin Ontology Language
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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
//! Core parsing logic for Dolfin.

use lalrpop_util::lalrpop_mod;

// Auto-generated LALRPOP parser for Dolfin language
lalrpop_mod!(
    #[allow(clippy::all)]
    #[allow(dead_code)]
    pub dolfin,
    "/dolfin.rs"
);

use crate::PackageError;
use crate::ast::{OntologyFile, PackageFile};
use crate::comment::{Comment, CommentSink};
use crate::error::{
    /* Diagnostic,  */ DiagnosticBuilder, ErrorCode, LexerError, Location, ParseError,
    ParseResult, /*Severity , Span, */
};
use crate::lexer::{Lexer, Token};

/// Result of parsing with comment preservation.
pub struct ParseWithComments {
    pub result: ParseResult,
    pub comments: Vec<Comment>,
}

/// Parse and collect comments for formatting.
pub fn parse_ontology_with_comments(source: &str) -> ParseWithComments {
    let sink = CommentSink::new();
    let lexer = Lexer::with_comment_sink(source, sink.clone());
    let parser = dolfin::OntologyFileParser::new();

    let result = match parser.parse(lexer) {
        Ok(ontology) => ParseResult::success(ontology, vec![]),
        Err(lalrpop_err) => {
            let parse_error = convert_lalrpop_error(lalrpop_err, source);
            let diagnostic = parse_error.into_diagnostic();
            ParseResult::failure(vec![diagnostic])
        }
    };

    // Comments survive because sink has been cloned (Rc)
    ParseWithComments {
        result,
        comments: sink.take(),
    }
}

/// Parse Dolfin source code from a string.
pub fn parse_ontology(source: &str) -> ParseResult {
    let lexer = Lexer::new(source);
    let parser = dolfin::OntologyFileParser::new();

    match parser.parse(lexer) {
        Ok(ontology) => ParseResult::success(ontology, vec![]),
        Err(lalrpop_err) => {
            let parse_error = convert_lalrpop_error(lalrpop_err, source);
            let diagnostic = parse_error.into_diagnostic();
            ParseResult::failure(vec![diagnostic])
        }
    }
}

/// Parse Dolfin source code and return a `Result` (legacy API).
///
/// Returns `Ok(Ontology)` on success, or `Err(ParseError)` on failure.
/// Prefer `parse()` for richer diagnostics.
pub fn parse_result_strict(result: ParseResult) -> Result<OntologyFile, Box<ParseError>> {
    match result.ontology {
        Some(ontology) if !result.has_errors() => Ok(ontology),
        _ => {
            let first_error = result
                .errors()
                .into_iter()
                .next()
                .expect("parse failed but no errors collected");

            Err(Box::new(ParseError {
                message: first_error.message.clone(),
                location: first_error.span.map(|s| s.start),
                end_location: first_error.span.map(|s| s.end),
                code: first_error.code,
                expected: vec![],
                help: first_error.help.clone(),
            }))
        }
    }
}

/// Parse Dolfin source code from a file.
pub fn parse_ontology_file<P: AsRef<std::path::Path>>(path: P) -> ParseResult {
    let path_ref = path.as_ref();
    let source = match std::fs::read_to_string(path_ref) {
        Ok(s) => s,
        Err(e) => {
            let diag = DiagnosticBuilder::error(
                ErrorCode::UnexpectedEof, // closest code; could add a dedicated IO code
                format!("Failed to read file '{}': {}", path_ref.display(), e),
            )
            .build();
            return ParseResult::failure(vec![diag]);
        }
    };
    parse_ontology(&source)
}

/// Parse a Dolfin package manifest (package.dlf).
pub fn parse_package(source: &str) -> Result<PackageFile, Box<ParseError>> {
    let lexer = Lexer::new(source);
    let parser = dolfin::PackageFileParser::new();

    parser
        .parse(lexer)
        .map_err(|e| convert_lalrpop_error(e, source))
}

/// Parse a package manifest from disk.
pub fn parse_package_file<P: AsRef<std::path::Path>>(path: P) -> Result<PackageFile, PackageError> {
    let source = std::fs::read_to_string(path.as_ref()).map_err(|e| PackageError::IoError {
        path: path.as_ref().to_path_buf(),
        source: e,
    })?;
    parse_package(&source).map_err(|e| PackageError::ParseError {
        path: path.as_ref().to_path_buf(),
        source: e,
    })
}

/// Convert a LALRPOP error into our `ParseError` with rich context.
fn convert_lalrpop_error(
    error: lalrpop_util::ParseError<Location, Token, LexerError>,
    source: &str,
) -> Box<ParseError> {
    match error {
        lalrpop_util::ParseError::InvalidToken { location } => Box::new(
            ParseError::new("Invalid token", ErrorCode::UnexpectedToken).with_location(location),
        ),

        lalrpop_util::ParseError::UnrecognizedEof { location, expected } => {
            let help = suggest_for_eof(source, &location);
            let mut err = ParseError::new("Unexpected end of file", ErrorCode::UnexpectedEof)
                .with_location(location)
                .with_expected(expected);
            if let Some(h) = help {
                err = err.with_help(h);
            }
            Box::new(err)
        }

        lalrpop_util::ParseError::UnrecognizedToken {
            token: (start, ref tok, end),
            expected,
        } => {
            let message = format_unexpected_token_message(tok, source, &start);
            let help = suggest_for_unexpected_token(tok, &expected, source, &start);
            let code = classify_unexpected_token(tok);

            let mut err = ParseError::new(message, code)
                .with_span(start, end)
                .with_expected(expected);
            if let Some(h) = help {
                err = err.with_help(h);
            }
            Box::new(err)
        }

        lalrpop_util::ParseError::ExtraToken {
            token: (start, ref tok, end),
        } => Box::new(
            ParseError::new(
                format!("Extra token '{}' after valid input", tok),
                ErrorCode::ExtraToken,
            )
            .with_span(start, end)
            .with_help("Remove this token or check for a missing newline"),
        ),

        lalrpop_util::ParseError::User { error } => Box::new(
            ParseError::new(error.message.clone(), error.code).with_location(error.location),
        ),
    }
}

/// Produce a context-aware message for unexpected tokens.
fn format_unexpected_token_message(tok: &Token, source: &str, loc: &Location) -> String {
    let context = identify_parsing_context(source, loc);
    match context {
        ParsingContext::ConceptBody => {
            format!("Unexpected '{}' in concept body", tok)
        }
        ParsingContext::OntologyBody => {
            format!("Unexpected '{}' in ontology body", tok)
        }
        ParsingContext::EnumBody => {
            format!("Unexpected '{}' in enum definition", tok)
        }
        ParsingContext::MatchBlock => {
            format!("Unexpected '{}' in match block", tok)
        }
        ParsingContext::ThenBlock => {
            format!("Unexpected '{}' in then block", tok)
        }
        ParsingContext::PropertyDef => {
            format!("Unexpected '{}' in property definition", tok)
        }
        ParsingContext::TopLevel => match tok {
            Token::Indent => {
                "Unexpected indentation at top level, did you forgot the ':' ?".to_string()
            }
            _ => format!("Unexpected '{}' at top level", tok),
        },
        ParsingContext::Unknown => {
            format!("Unexpected token '{}'", tok)
        }
    }
}

/// Classify an unexpected token into a more specific error code when possible.
fn classify_unexpected_token(tok: &Token) -> ErrorCode {
    match tok {
        Token::Arrow => ErrorCode::MissingArrow, // arrow in wrong place
        Token::Indent | Token::Dedent => ErrorCode::InvalidIndentation,
        _ => ErrorCode::UnexpectedToken,
    }
}

/// Suggest fixes for unexpected tokens based on context.
fn suggest_for_unexpected_token(
    tok: &Token,
    expected: &[String],
    source: &str,
    loc: &Location,
) -> Option<String> {
    // Check for common mistakes
    match tok {
        Token::Name(_) => {
            // Check if a colon was expected (common: `concept Foo` without `:`)
            if expected
                .iter()
                .any(|e| e.contains("Colon") || e.contains(":"))
            {
                return Some(
                    "Did you forget a ':' ? Blocks require a colon, e.g., 'concept Foo:'"
                        .to_string(),
                );
            }
        }
        Token::Newline => {
            if expected
                .iter()
                .any(|e| e.contains("Indent") || e.contains("INDENT"))
            {
                return Some("Expected an indented block on the next line".to_string());
            }
        }
        Token::Dedent => {
            return Some(
                "Unexpected decrease in indentation. Check that your block is properly indented"
                    .to_string(),
            );
        }
        Token::Arrow => {
            let ctx = identify_parsing_context(source, loc);
            if ctx == ParsingContext::ConceptBody {
                return Some("'->' is used in property definitions, not in concept bodies. Use 'has' for concept attributes".to_string());
            }
        }
        _ => {}
    }

    None
}

/// Suggest fixes for unexpected EOF.
fn suggest_for_eof(source: &str, _loc: &Location) -> Option<String> {
    // Check if there's an unclosed block
    let lines: Vec<&str> = source.lines().collect();
    if let Some(last_line) = lines.last() {
        let trimmed = last_line.trim();
        if trimmed.ends_with(':') {
            return Some(format!(
                "The block starting with '{}' needs an indented body",
                trimmed,
            ));
        }
    }

    // Check indent stack depth heuristic: if source has indented content
    // at the end, maybe a DEDENT is missing
    let trailing = source.trim_end();
    if !trailing.is_empty() {
        let last_line = trailing.lines().last().unwrap_or("");
        let indent = last_line.len() - last_line.trim_start().len();
        if indent > 0 {
            return Some(
                "The file ends inside an indented block. Ensure all blocks are properly closed"
                    .to_string(),
            );
        }
    }

    None
}

// ============================================================================
// PARSING CONTEXT DETECTION
// ============================================================================

/// Rough classification of where in the grammar the parser currently is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ParsingContext {
    TopLevel,
    OntologyBody,
    ConceptBody,
    EnumBody,
    MatchBlock,
    ThenBlock,
    PropertyDef,
    Unknown,
}

/// Heuristic: look at preceding lines to determine the parsing context.
fn identify_parsing_context(source: &str, loc: &Location) -> ParsingContext {
    let lines: Vec<&str> = source.lines().collect();
    let target_line = loc.line.saturating_sub(1); // 0-based

    // Walk backward from the error line looking for context clues
    let mut current_indent = if target_line < lines.len() {
        let line = lines[target_line];
        line.len() - line.trim_start().len()
    } else {
        0
    };

    for i in (0..=target_line.min(lines.len().saturating_sub(1))).rev() {
        let line = lines[i];
        let trimmed = line.trim();
        let indent = line.len() - line.trim_start().len();

        // Only consider lines at a lesser or equal indent (enclosing blocks)
        if indent < current_indent || i == target_line {
            if trimmed.starts_with("concept ") && trimmed.ends_with(':') {
                return ParsingContext::ConceptBody;
            }
            if trimmed.starts_with("ontology ") && trimmed.ends_with(':') {
                return ParsingContext::OntologyBody;
            }
            if trimmed.starts_with("enum ") && trimmed.ends_with(':') {
                return ParsingContext::EnumBody;
            }
            if trimmed.starts_with("match") && trimmed.ends_with(':') {
                return ParsingContext::MatchBlock;
            }
            if trimmed.starts_with("then") && trimmed.ends_with(':') {
                return ParsingContext::ThenBlock;
            }
            if trimmed.starts_with("property ") {
                return ParsingContext::PropertyDef;
            }
            current_indent = indent;
        }
    }

    // Check if we're at top level (no indentation)
    if current_indent == 0 {
        return ParsingContext::TopLevel;
    }

    ParsingContext::Unknown
}

// ============================================================================
// TESTS
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    use crate::error::{Severity, Span};

    #[test]
    fn test_parse_empty() {
        let result = parse_ontology("");
        assert!(result.is_ok());
        let onto = result.ontology.unwrap();
        assert!(onto.iri_name.is_none());
        assert!(onto.prefixes.is_empty());
        assert!(onto.declarations.is_empty());
    }

    #[test]
    fn test_parse_error_has_diagnostic() {
        let result = parse_ontology("namespace\n"); // missing qualified name
        assert!(!result.is_ok());
        assert!(result.has_errors());
        assert_eq!(result.error_count(), 1);

        let diag = &result.diagnostics[0];
        assert_eq!(diag.severity, Severity::HardError);
        assert!(diag.span.is_some());
    }

    #[test]
    fn test_parse_error_shows_source_context() {
        let source = "concept Bar:\n    has name string\n";
        let result = parse_ontology(source);

        if result.has_errors() {
            for diag in &result.diagnostics {
                let formatted = diag.display(Some(source), Some("test.dlf"));
                // Should contain file reference
                assert!(
                    formatted.contains("test.dlf"),
                    "Missing filename in: {}",
                    formatted
                );
                // Should contain error code
                assert!(
                    formatted.contains("[E"),
                    "Missing error code in: {}",
                    formatted
                );
            }
        }
    }

    #[test]
    fn test_parse_iri_name() {
        let source = r#"@iri_name "Mammifère"

concept Mammal:
  has name: string
"#;
        let result = parse_ontology(source);
        assert!(result.is_ok(), "Error: {:?}", result.errors());
        let onto = result.ontology.unwrap();
        assert_eq!(onto.iri_name, Some("Mammifère".to_string()));
        assert_eq!(onto.declarations.len(), 1);
    }

    #[test]
    fn test_parse_prefixes() {
        let source = r#"prefix com.example.common
prefix com.example.other as other

concept Thing:
  has name: string
"#;
        let result = parse_ontology(source);
        assert!(result.is_ok(), "Error: {:?}", result.errors());
        let onto = result.ontology.unwrap();
        assert_eq!(onto.prefixes.len(), 2);
        assert_eq!(onto.prefixes[0].alias, "common");
        assert_eq!(onto.prefixes[1].alias, "other");
    }

    #[test]
    fn test_parse_package() {
        let source = r#"package com.example.biology:
  dolfin_version "1"
  version "1.0.0"
  author "Jane Doe"
  description "Biology ontology"
"#;
        let result = parse_package(source);
        assert!(result.is_ok(), "Error: {:?}", result.err());
        let pkg = result.unwrap();
        assert_eq!(pkg.name.full(), "com.example.biology");
        assert_eq!(pkg.dolfin_version, "1");
        assert_eq!(pkg.version, "1.0.0");
        assert_eq!(pkg.author, Some("Jane Doe".to_string()));
    }

    #[test]
    fn test_parse_error_expected_colon() {
        // Missing colon after ontology name
        let source = "concept Bar\n    has name: string\n";
        let result = parse_ontology(source);
        assert!(!result.is_ok());

        let diag = &result.diagnostics[0];
        let formatted = diag.display(Some(source), None);
        // The help should mention the colon
        assert!(
            formatted.contains("':'"),
            "expected a colon -> <{}>",
            formatted
        );
    }

    #[test]
    fn test_parse_file_not_found() {
        let result = parse_ontology_file("/nonexistent/file.dlf");
        assert!(!result.is_ok());
        assert!(result.has_errors());
    }

    #[test]
    fn test_parse_simple_ontology() {
        let source = "concept Bar:\n  has name: string\n";
        let result = parse_ontology(source);
        assert!(result.is_ok(), "Error: {:?}", result.errors());
    }

    #[test]
    fn test_parse_concept_with_inheritance() {
        let source = r#"concept Employee:
  sub Person
  has employeeId: string
  has salary: optional int
"#;
        let result = parse_ontology(source);
        assert!(result.is_ok(), "Error: {:?}", result.errors());
    }

    #[test]
    fn test_parse_property_def() {
        let source = r#"property worksFor: Person -> Organization
"#;
        let result = parse_ontology(source);
        assert!(result.is_ok(), "Error: {:?}", result.errors());
    }

    #[test]
    fn test_parse_enum_def() {
        let source = r#"concept Status:
  one of:
    Active
    Inactive
    Pending
"#;
        let result = parse_ontology(source);
        assert!(result.is_ok(), "Error: {:?}", result.errors());
    }

    #[test]
    fn test_parse_rule() {
        let source = r#"

rule EmployeeAccess:
  match:
    ?emp a Employee
    ?emp worksFor ?company
  then:
    ?emp hasAccess true
"#;
        let result = parse_ontology(source);
        assert!(result.is_ok(), "Error: {:?}", result.errors());

        let declarations = result.ontology.unwrap().declarations;
        assert_eq!(declarations.len(), 1, "Error: Exactly one rule expected");

        let declaration = declarations.first().unwrap();
        assert!(
            matches!(declaration, crate::Declaration::Rule { .. }),
            "Error: rule expected"
        );

        let crate::Declaration::Rule(rule) = declaration else {
            panic!()
        };
        assert_eq!(rule.name, "EmployeeAccess");
        let match_patterns = rule.match_block.patterns.clone();
        assert_eq!(match_patterns.len(), 2);
        let first = match_patterns
            .first()
            .expect("Match block must have a first pattern");
        assert!(matches!(first, crate::Pattern::Type { .. }));
    }

        #[test]
    fn test_parse_two_rule() {
        let source = r#"
rule flag_unvaccinated:
  match:
    ?animal a Animal
  then:
    ?animal a UnvaccinatedAnimal

# End of rules

rule flag_intern_emergency:
  match:
    ?appt animal [ treatedBy [ a Intern ] ]
  then:
    ?appt a UnsafeAssignment

"#;
        let result = parse_ontology(source);
        assert!(result.is_ok(), "Error: {:?}", result.errors());

        let declarations = result.ontology.unwrap().declarations;
        assert_eq!(declarations.len(), 2, "Error: Exactly two rule expected");

        let declaration = declarations.first().unwrap();
        assert!(
            matches!(declaration, crate::Declaration::Rule { .. }),
            "Error: rule expected"
        );

        let crate::Declaration::Rule(rule) = declaration else {
            panic!()
        };
        assert_eq!(rule.name, "flag_unvaccinated");
        let match_patterns = rule.match_block.patterns.clone();
        assert_eq!(match_patterns.len(), 1);
        let first = match_patterns
            .first()
            .expect("Match block must have a first pattern");
        assert!(matches!(first, crate::Pattern::Type { .. }));
      }

    #[test]
    fn test_parse_with_comments() {
        let source = r#"
# comment in ontology
concept A:
    has x: string  # property comment
"#;
        let result = parse_ontology(source);
        assert!(result.is_ok(), "Error: {:?}", result.errors());
    }

    #[test]
    fn test_parse_complete_ontology() {
        let source = r#"

concept Department:
  one of:
    engineering
    sales
    marketing
    hr

concept Person:
  has firstName: string
  has lastName: string

concept Employee:
  sub Person
  has employeeId: string
  has salary: float

property worksFor: Employee -> Organization
"#;
        let result = parse_ontology(source);
        assert!(
            result.is_ok(),
            "Errors: {}",
            result.format_diagnostics(Some(source), None)
        );
    }

    #[test]
    fn test_parse_result_format_diagnostics() {
        let source = "concept\n"; // incomplete
        let result = parse_ontology(source);
        if result.has_errors() {
            let formatted = result.format_diagnostics(Some(source), Some("broken.dlf"));
            assert!(!formatted.is_empty());
            assert!(formatted.contains("Expected identifier"));
        }
    }

    #[test]
    fn test_parsing_context_detection() {
        let source = "ontology Foo:\n  concept Bar:\n    has name: string\n";
        let loc = Location::new(3, 5, 30);
        let ctx = identify_parsing_context(source, &loc);
        assert_eq!(ctx, ParsingContext::ConceptBody);
    }

    #[test]
    fn test_parsing_context_top_level() {
        let source = "namespace com.example\n";
        let loc = Location::new(1, 1, 0);
        let ctx = identify_parsing_context(source, &loc);
        assert_eq!(ctx, ParsingContext::TopLevel);
    }

    #[test]
    fn test_parsing_context_enum_body() {
        let source = "ontology Foo:\n  enum Status:\n    active\n";
        let loc = Location::new(3, 5, 30);
        let ctx = identify_parsing_context(source, &loc);
        assert_eq!(ctx, ParsingContext::EnumBody);
    }

    #[test]
    fn test_parsing_context_match_block() {
        let source = "ontology Foo:\n  rule R:\n    match:\n      ?x is Person\n";
        let loc = Location::new(4, 7, 45);
        let ctx = identify_parsing_context(source, &loc);
        assert_eq!(ctx, ParsingContext::MatchBlock);
    }

    #[test]
    fn test_diagnostic_builder_fluent() {
        let span = Span::new(Location::new(1, 5, 4), Location::new(1, 10, 9));
        let diag = DiagnosticBuilder::error(ErrorCode::UnexpectedToken, "Expected ':'")
            .span(span)
            .help("Add a colon after the name")
            .label(span, "here")
            .build();

        assert_eq!(diag.severity, Severity::HardError);
        assert_eq!(diag.code, ErrorCode::UnexpectedToken);
        assert!(diag.help.is_some());
        assert_eq!(diag.labels.len(), 1);
    }

    #[test]
    fn test_span_merge() {
        let s1 = Span::new(Location::new(1, 1, 0), Location::new(1, 5, 4));
        let s2 = Span::new(Location::new(1, 10, 9), Location::new(1, 15, 14));
        let merged = s1.merge(&s2);
        assert_eq!(merged.start.offset, 0);
        assert_eq!(merged.end.offset, 14);
    }

    #[test]
    fn test_parse_result_unwrap_failure() {
        let result = ParseResult::failure(vec![
            DiagnosticBuilder::error(ErrorCode::UnexpectedToken, "bad token").build(),
        ]);
        // Can't call unwrap_program directly in Rust (it needs Python),
        // but we can check the fields:
        assert!(result.ontology.is_none());
        assert!(result.has_errors());
        assert!(!result.is_ok());
    }
}