atoxide-parser 0.1.3

Parser for the Ato hardware description 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
//! Parser for the Ato hardware description language.
//!
//! This crate provides a complete parser for the Ato DSL, producing a typed AST
//! with error recovery using the chumsky parser combinator library.
//!
//! # Example
//!
//! ```
//! use atoxide_parser::parse;
//!
//! let source = r#"
//! module MyModule:
//!     pin p1
//!     signal sig
//!     p1 ~ sig
//! "#;
//!
//! match parse(source) {
//!     Ok(file) => {
//!         println!("Parsed {} statements", file.statements.len());
//!     }
//!     Err(errors) => {
//!         for e in errors {
//!             eprintln!("Parse error: {}", e);
//!         }
//!     }
//! }
//! ```
//!
//! # Error Recovery
//!
//! The parser supports error recovery, allowing it to continue parsing after
//! encountering errors. Use `parse_with_recovery` to get both the AST and errors:
//!
//! ```
//! use atoxide_parser::parse_with_recovery;
//!
//! let source = "module M:\n    pass\n";
//! let (ast, errors) = parse_with_recovery(source);
//!
//! if let Some(file) = ast {
//!     println!("Parsed {} statements", file.statements.len());
//! }
//! for error in &errors {
//!     eprintln!("Error: {}", error);
//! }
//! ```

pub mod ast;
mod chumsky;
pub mod error;

pub use ast::*;
pub use chumsky::{ParseError as ChumskyParseError, format_errors};
pub use error::{ParseError, ParseResult};

/// Parse Ato source code into an AST.
///
/// This is the main entry point for parsing Ato source code.
/// Returns an error if parsing fails completely.
///
/// For error recovery (getting partial AST even with errors), use `parse_with_recovery`.
pub fn parse(source: &str) -> Result<File, Vec<ChumskyParseError>> {
    let (ast, errors) = chumsky::parse(source);

    if let Some(file) = ast {
        if errors.is_empty() {
            Ok(file)
        } else {
            // We got an AST but also had errors - return the errors
            // (the AST might be incomplete or have placeholder values)
            Err(errors)
        }
    } else {
        // No AST at all - definitely an error
        if errors.is_empty() {
            Err(vec![ChumskyParseError {
                span: atoxide_lexer::Span::new(0, 0, 1, 1),
                message: "failed to parse".to_string(),
                expected: vec![],
                found: None,
                help: None,
            }])
        } else {
            Err(errors)
        }
    }
}

/// Parse Ato source code with error recovery.
///
/// Returns both the AST (if any could be parsed) and all errors encountered.
/// This is useful when you want to continue processing even with errors,
/// or when you want to collect all errors for display.
pub fn parse_with_recovery(source: &str) -> (Option<File>, Vec<ChumskyParseError>) {
    chumsky::parse(source)
}

/// Parse Ato source code and format any errors using ariadne.
///
/// Returns the AST if parsing succeeded (possibly with recovered errors),
/// and a formatted error string if there were any errors.
pub fn parse_with_formatted_errors(source: &str, filename: &str) -> (Option<File>, Option<String>) {
    chumsky::parse_with_errors(source, filename)
}

/// Parse Ato source code, returning both the AST and a source code wrapper for error display.
///
/// This is useful when you want to display nice error messages with miette.
pub fn parse_with_source(
    source: &str,
) -> (
    Result<File, Vec<ChumskyParseError>>,
    miette::NamedSource<String>,
) {
    let named_source = miette::NamedSource::new("<input>", source.to_string());
    let result = parse(source);
    (result, named_source)
}

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

    #[test]
    fn test_parse_empty() {
        let source = "";
        let file = parse(source).unwrap();
        assert!(file.statements.is_empty());
    }

    #[test]
    fn test_parse_pragma() {
        let source = "#pragma experiment(\"FOR_LOOP\")\n";
        let file = parse(source).unwrap();
        assert_eq!(file.statements.len(), 1);
        assert!(matches!(file.statements[0], Statement::Pragma(_)));
    }

    #[test]
    fn test_parse_import() {
        let source = "import ElectricPower\n";
        let file = parse(source).unwrap();
        assert_eq!(file.statements.len(), 1);
        assert!(matches!(file.statements[0], Statement::Import(_)));
    }

    #[test]
    fn test_parse_from_import() {
        let source = "from \"path/to/file.ato\" import Module\n";
        let file = parse(source).unwrap();
        assert_eq!(file.statements.len(), 1);
        if let Statement::Import(import) = &file.statements[0] {
            assert!(import.from_path.is_some());
        } else {
            panic!("Expected import statement");
        }
    }

    #[test]
    fn test_parse_simple_module() {
        let source = "module M:\n    pass\n";
        let file = parse(source).unwrap();
        assert_eq!(file.statements.len(), 1);
        if let Statement::BlockDef(block) = &file.statements[0] {
            assert_eq!(block.kind, BlockKind::Module);
            assert_eq!(block.name.name, "M");
            assert_eq!(block.body.len(), 1);
        } else {
            panic!("Expected block definition");
        }
    }

    #[test]
    fn test_parse_module_with_super() {
        let source = "module Child from Parent:\n    pass\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            assert!(block.super_type.is_some());
            assert_eq!(block.super_type.as_ref().unwrap().parts[0].name, "Parent");
        } else {
            panic!("Expected block definition");
        }
    }

    #[test]
    fn test_parse_component() {
        let source = "component C:\n    pin p1\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            assert_eq!(block.kind, BlockKind::Component);
        } else {
            panic!("Expected component");
        }
    }

    #[test]
    fn test_parse_interface() {
        let source = "interface I:\n    pass\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            assert_eq!(block.kind, BlockKind::Interface);
        } else {
            panic!("Expected interface");
        }
    }

    #[test]
    fn test_parse_pin() {
        let source = "module M:\n    pin p1\n    pin 1\n    pin \"GND\"\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            assert_eq!(block.body.len(), 3);
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_signal() {
        let source = "module M:\n    signal sig\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            assert!(matches!(block.body[0], Statement::SignalDef(_)));
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_assignment() {
        let source = "module M:\n    x = 5\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            assert!(matches!(block.body[0], Statement::Assignment(_)));
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_new_expression() {
        let source = "module M:\n    x = new SomeType\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            if let Statement::Assignment(assign) = &block.body[0] {
                assert!(matches!(assign.value, Assignable::New(_)));
            } else {
                panic!("Expected assignment");
            }
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_new_with_count() {
        let source = "module M:\n    x = new SomeType[10]\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            if let Statement::Assignment(assign) = &block.body[0] {
                if let Assignable::New(new_expr) = &assign.value {
                    assert!(new_expr.count.is_some());
                } else {
                    panic!("Expected new expression");
                }
            } else {
                panic!("Expected assignment");
            }
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_new_with_template() {
        let source = "module M:\n    x = new SomeType<param=1>\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            if let Statement::Assignment(assign) = &block.body[0] {
                if let Assignable::New(new_expr) = &assign.value {
                    assert!(new_expr.template.is_some());
                } else {
                    panic!("Expected new expression");
                }
            } else {
                panic!("Expected assignment");
            }
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_connection() {
        let source = "module M:\n    a ~ b\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            assert!(matches!(block.body[0], Statement::Connection(_)));
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_directed_connection() {
        let source = "module M:\n    a ~> b ~> c\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            if let Statement::DirectedConnection(conn) = &block.body[0] {
                assert_eq!(conn.direction, ConnectionDirection::Forward);
                assert_eq!(conn.elements.len(), 3);
            } else {
                panic!("Expected directed connection");
            }
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_backward_connection() {
        let source = "module M:\n    a <~ b <~ c\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            if let Statement::DirectedConnection(conn) = &block.body[0] {
                assert_eq!(conn.direction, ConnectionDirection::Backward);
            } else {
                panic!("Expected directed connection");
            }
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_retype() {
        let source = "module M:\n    x -> NewType\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            assert!(matches!(block.body[0], Statement::Retype(_)));
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_assert() {
        let source = "module M:\n    assert x > 5\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            assert!(matches!(block.body[0], Statement::Assert(_)));
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_assert_within() {
        let source = "module M:\n    assert x within 1 to 10\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            if let Statement::Assert(assert_stmt) = &block.body[0] {
                assert_eq!(
                    assert_stmt.comparison.operations[0].kind,
                    CompareOpKind::Within
                );
            } else {
                panic!("Expected assert");
            }
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_trait() {
        let source = "module M:\n    trait some_trait\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            assert!(matches!(block.body[0], Statement::Trait(_)));
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_trait_with_constructor() {
        let source = "module M:\n    trait some_trait::constructor\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            if let Statement::Trait(trait_stmt) = &block.body[0] {
                assert!(trait_stmt.constructor.is_some());
            } else {
                panic!("Expected trait");
            }
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_trait_with_template() {
        let source = "module M:\n    trait some_trait<arg=1>\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            if let Statement::Trait(trait_stmt) = &block.body[0] {
                assert!(trait_stmt.template.is_some());
            } else {
                panic!("Expected trait");
            }
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_for_loop() {
        let source = "module M:\n    for item in container:\n        pass\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            if let Statement::For(for_stmt) = &block.body[0] {
                assert_eq!(for_stmt.variable.name, "item");
            } else {
                panic!("Expected for loop");
            }
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_declaration() {
        let source = "module M:\n    field: ohm\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            assert!(matches!(block.body[0], Statement::Declaration(_)));
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_declaration_with_assignment() {
        let source = "module M:\n    field: ohm = 100\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            if let Statement::Assignment(assign) = &block.body[0] {
                assert!(matches!(assign.target, AssignTarget::Declaration(_)));
            } else {
                panic!("Expected assignment");
            }
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_physical_quantity() {
        let source = "module M:\n    x = 10kohm\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            if let Statement::Assignment(assign) = &block.body[0] {
                assert!(matches!(assign.value, Assignable::Physical(_)));
            } else {
                panic!("Expected assignment");
            }
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_range() {
        let source = "module M:\n    x = 1 to 10\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            if let Statement::Assignment(assign) = &block.body[0] {
                if let Assignable::Physical(PhysicalLiteral::Range(_)) = &assign.value {
                    // OK
                } else {
                    panic!("Expected range");
                }
            } else {
                panic!("Expected assignment");
            }
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_bilateral() {
        let source = "module M:\n    x = 10 +/- 5%\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            if let Statement::Assignment(assign) = &block.body[0] {
                if let Assignable::Physical(PhysicalLiteral::Bilateral(_)) = &assign.value {
                    // OK
                } else {
                    panic!("Expected bilateral");
                }
            } else {
                panic!("Expected assignment");
            }
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_arithmetic() {
        let source = "module M:\n    x = a + b * c\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            if let Statement::Assignment(assign) = &block.body[0] {
                assert!(matches!(assign.value, Assignable::Arithmetic(_)));
            } else {
                panic!("Expected assignment");
            }
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_string_stmt() {
        let source = "module M:\n    \"docstring\"\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            assert!(matches!(block.body[0], Statement::StringStmt(_)));
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_semicolon_separated() {
        let source = "module M:\n    pass; pass; pass\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            assert_eq!(block.body.len(), 3);
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_single_line_block() {
        let source = "module M: pass\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            assert_eq!(block.body.len(), 1);
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_nested_modules() {
        let source = "module A:\n    module B:\n        pass\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(outer) = &file.statements[0] {
            if let Statement::BlockDef(inner) = &outer.body[0] {
                assert_eq!(inner.name.name, "B");
            } else {
                panic!("Expected inner block");
            }
        } else {
            panic!("Expected outer block");
        }
    }

    #[test]
    fn test_parse_field_reference() {
        let source = "module M:\n    a.b.c = 1\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            if let Statement::Assignment(assign) = &block.body[0] {
                if let AssignTarget::FieldRef(field_ref) = &assign.target {
                    assert_eq!(field_ref.parts.len(), 3);
                } else {
                    panic!("Expected field ref");
                }
            } else {
                panic!("Expected assignment");
            }
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_field_with_index() {
        let source = "module M:\n    a[0].b = 1\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            if let Statement::Assignment(assign) = &block.body[0] {
                if let AssignTarget::FieldRef(field_ref) = &assign.target {
                    assert!(field_ref.parts[0].index.is_some());
                } else {
                    panic!("Expected field ref");
                }
            } else {
                panic!("Expected assignment");
            }
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_assert_multiply() {
        let source = "module M:\n    assert x >= y * 1.5\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            assert!(matches!(block.body[0], Statement::Assert(_)));
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_assign_multiply() {
        // Basic: x = a * b
        let source = "module M:\n    x = 300 * y\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            if let Statement::Assignment(assign) = &block.body[0] {
                assert!(matches!(assign.value, Assignable::Arithmetic(_)));
            } else {
                panic!("Expected assignment");
            }
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_assign_chained_multiply() {
        // k_iset = 300 * k_i * k_r (from BQ25185)
        let source = "module M:\n    k_iset = 300 * k_i * k_r\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            if let Statement::Assignment(assign) = &block.body[0] {
                assert!(matches!(assign.value, Assignable::Arithmetic(_)));
            } else {
                panic!("Expected assignment");
            }
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_assert_multiply_rhs() {
        // assert x >= y * 1.5 (from BQ25185)
        let source = "module M:\n    assert x >= y * 1.5\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            assert!(matches!(block.body[0], Statement::Assert(_)));
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_physical_literal_still_assignable() {
        // Plain physical literals should still be Assignable::Physical
        let source = "module M:\n    x = 10kohm +/- 10%\n";
        let file = parse(source).unwrap();
        if let Statement::BlockDef(block) = &file.statements[0] {
            if let Statement::Assignment(assign) = &block.body[0] {
                assert!(matches!(
                    assign.value,
                    Assignable::Physical(PhysicalLiteral::Bilateral(_))
                ));
            } else {
                panic!("Expected assignment");
            }
        } else {
            panic!("Expected block");
        }
    }

    #[test]
    fn test_parse_from_py_import() {
        // BQ25185 has: from "ResistanceMapper.py" import ResistanceMapper
        // This should parse (even though .py files won't be loaded)
        let source = r#"from "ResistanceMapper.py" import ResistanceMapper
module M:
    pass
"#;
        let file = parse(source).unwrap();
        assert!(!file.statements.is_empty());
    }

    #[test]
    fn test_error_recovery() {
        // This has an error (missing colon after module name)
        let source = "module Bad\n    pass\n";
        let (ast, errors) = parse_with_recovery(source);

        // Should have errors
        assert!(!errors.is_empty(), "Should have parse errors");
        // With error recovery, we may or may not get an AST
        let _ = ast;
    }
}