dubp_documents_parser/
raw_text.rs

1//  Copyright (C) 2020  Éloïs SANCHEZ.
2//
3// This program is free software: you can redistribute it and/or modify
4// it under the terms of the GNU Affero General Public License as
5// published by the Free Software Foundation, either version 3 of the
6// License, or (at your option) any later version.
7//
8// This program is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11// GNU Affero General Public License for more details.
12//
13// You should have received a copy of the GNU Affero General Public License
14// along with this program.  If not, see <https://www.gnu.org/licenses/>.
15
16use crate::*;
17
18pub(super) mod certification;
19pub(super) mod document;
20pub(super) mod identity;
21pub(super) mod membership;
22pub(super) mod revocation;
23pub(super) mod transaction;
24pub(super) mod wallet_script;
25
26#[derive(Debug, Clone, Copy, Parser)]
27#[grammar = "documents_grammar.pest"]
28/// Parser for Documents
29pub(crate) struct RawDocumentsParser;
30
31pub trait FromPestPair: Sized {
32    /// Parse from pest pair
33    fn from_pest_pair(pair: Pair<Rule>) -> Result<Self, TextParseError>;
34}
35
36pub trait ParseFromRawText: FromPestPair {
37    /// Parse text document from raw format
38    fn parse_from_raw_text(doc: &str) -> Result<Self, TextParseError>;
39}
40
41macro_rules! impl_parse_from_raw_text {
42    ($Type:ty, $Rule:expr) => {
43        impl ParseFromRawText for $Type {
44            #[inline]
45            fn parse_from_raw_text(doc: &str) -> Result<Self, TextParseError> {
46                let mut doc_pairs = RawDocumentsParser::parse($Rule, doc)
47                    .map_err(|e| TextParseError::PestError(e.into()))?;
48                Self::from_pest_pair(doc_pairs.next().unwrap_or_else(|| unreachable!()))
49                // get and unwrap the `$Rule` rule; never fails
50            }
51        }
52    };
53}
54
55impl_parse_from_raw_text!(DubpDocument, Rule::document);
56impl_parse_from_raw_text!(IdentityDocument, Rule::idty);
57impl_parse_from_raw_text!(CertificationDocument, Rule::cert);
58impl_parse_from_raw_text!(MembershipDocument, Rule::membership);
59impl_parse_from_raw_text!(RevocationDocument, Rule::revoc);
60impl_parse_from_raw_text!(TransactionDocument, Rule::tx);
61impl_parse_from_raw_text!(TransactionDocumentV10, Rule::tx_v10);