Skip to main content

rustledger_parser/
lib.rs

1//! Beancount parser using chumsky parser combinators.
2//!
3//! This crate provides a parser for the Beancount file format. It produces
4//! a stream of [`Directive`]s from source text, along with any parse errors.
5//!
6//! # Features
7//!
8//! - Full Beancount syntax support (all 12 directive types)
9//! - Error recovery (continues parsing after errors)
10//! - Precise source locations for error reporting
11//! - Support for includes, options, plugins
12//!
13//! # Example
14//!
15//! ```ignore
16//! use rustledger_parser::parse;
17//!
18//! let source = r#"
19//! 2024-01-15 * "Coffee Shop" "Morning coffee"
20//!   Expenses:Food:Coffee  5.00 USD
21//!   Assets:Cash
22//! "#;
23//!
24//! let (directives, errors) = parse(source);
25//! assert!(errors.is_empty());
26//! assert_eq!(directives.len(), 1);
27//! ```
28
29#![forbid(unsafe_code)]
30#![warn(missing_docs)]
31
32mod error;
33pub mod logos_lexer;
34mod span;
35mod token_parser;
36
37pub use error::{ParseError, ParseErrorKind};
38pub use span::{Span, Spanned};
39
40use rustledger_core::Directive;
41
42/// Result of parsing a beancount file.
43#[derive(Debug)]
44pub struct ParseResult {
45    /// Successfully parsed directives.
46    pub directives: Vec<Spanned<Directive>>,
47    /// Options found in the file.
48    pub options: Vec<(String, String, Span)>,
49    /// Include directives found.
50    pub includes: Vec<(String, Span)>,
51    /// Plugin directives found.
52    pub plugins: Vec<(String, Option<String>, Span)>,
53    /// Parse errors encountered.
54    pub errors: Vec<ParseError>,
55    /// Deprecation warnings.
56    pub warnings: Vec<ParseWarning>,
57}
58
59/// A warning from the parser (non-fatal).
60#[derive(Debug, Clone)]
61pub struct ParseWarning {
62    /// The warning message.
63    pub message: String,
64    /// Location in source.
65    pub span: Span,
66}
67
68impl ParseWarning {
69    /// Create a new warning.
70    pub fn new(message: impl Into<String>, span: Span) -> Self {
71        Self {
72            message: message.into(),
73            span,
74        }
75    }
76}
77
78/// Parse beancount source code.
79///
80/// Uses a fast token-based parser (Logos lexer + Chumsky combinators).
81///
82/// # Arguments
83///
84/// * `source` - The beancount source code to parse
85///
86/// # Returns
87///
88/// A `ParseResult` containing directives, options, includes, plugins, and errors.
89pub fn parse(source: &str) -> ParseResult {
90    token_parser::parse(source)
91}
92
93/// Parse beancount source code, returning only directives and errors.
94///
95/// This is a simpler interface when you don't need options/includes/plugins.
96pub fn parse_directives(source: &str) -> (Vec<Spanned<Directive>>, Vec<ParseError>) {
97    let result = parse(source);
98    (result.directives, result.errors)
99}