Skip to content

Instantly share code, notes, and snippets.

@darichey
Created December 19, 2023 08:02
Show Gist options
  • Save darichey/4d6626fc73a2af2fc62498fe0f782869 to your computer and use it in GitHub Desktop.
Save darichey/4d6626fc73a2af2fc62498fe0f782869 to your computer and use it in GitHub Desktop.
use crate::lexer::Token;
use crate::tree::{Ledger, Transaction, Posting};
use lalrpop_util::ErrorRecovery;
grammar<'input, 'err>(input: &'input str, errors: &'err mut Vec<ErrorRecovery<usize, Token<'input>, &'static str>>);
extern {
type Location = usize;
type Error = &'static str;
enum Token<'input> {
"date" => Token::Date(<&'input str>),
"description" => Token::Description(<&'input str>),
"account" => Token::Account(<&'input str>),
"amount" => Token::Amount(<&'input str>),
" " => Token::Space,
"\n" => Token::NewLine,
}
}
RecoverError: () = {
<!> => errors.push(<>),
};
pub Ledger: Ledger<'input> = {
<t:Transaction> <mut ts:("\n" <Transaction>)*> => {
ts.insert(0, t);
Ledger {
transactions: ts
}
},
}
Transaction: Transaction<'input> = {
<date:"date"> " " <description:"description"> "\n" <p:Posting> <mut ps:("\n" <Posting>)*> "\n" => {
ps.insert(0, p);
Transaction {
date,
description: Some(description),
postings: ps
}
},
// Missing description
<date:"date"> RecoverError "\n" <p:Posting> <mut ps:("\n" <Posting>)*> "\n" => {
ps.insert(0, p);
Transaction {
date,
description: None,
postings: ps
}
},
// Missing postings
<date:"date"> " " <description:"description"> RecoverError => {
Transaction {
date,
description: Some(description),
postings: vec![]
}
},
}
Posting: Posting<'input> = {
" " " " <account:"account"> <amount:(" "+ <"amount">)?> => {
Posting {
account,
amount
}
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment