Skip to main content

canadensis_dsdl_parser/
lib.rs

1//!
2//! This library parses Cyphal data structure definition language (DSDL) files.
3//!
4
5pub extern crate num_bigint;
6pub extern crate num_rational;
7extern crate num_traits;
8extern crate pest;
9extern crate pest_derive;
10
11mod ast;
12
13use crate::parser::{DsdlParser, Rule};
14use pest::Parser;
15
16pub use crate::ast::types::*;
17
18use pest::error::ErrorVariant;
19/// A range of characters in the input text
20///
21pub use pest::Span;
22
23mod parser {
24    use pest_derive::Parser;
25    #[derive(Parser)]
26    #[grammar = "dsdl.pest"]
27    pub struct DsdlParser;
28}
29
30/// A parse error
31///
32/// This type is returned from [`parse`] and can also be used in other libraries
33/// to represent errors in other steps of the process
34#[derive(Debug, Clone)]
35pub struct Error(Box<pest::error::Error<Rule>>);
36
37/// Attempts to parse the text of a DSDL file into an abstract syntax tree
38///
39/// # Errors
40///
41/// This function returns an error if the DSDL has invalid syntax.
42pub fn parse<'i>(dsdl: &'i str) -> Result<Definition<'i>, Error> {
43    let parse_tree = DsdlParser::parse(Rule::definition, dsdl).map_err(|e| Error(Box::new(e)))?;
44    ast::parse_to_ast(parse_tree)
45}
46
47/// Convenience function to make an error value with a custom message
48pub fn make_error<S>(message: S, span: Span<'_>) -> Error
49where
50    S: Into<String>,
51{
52    Error(Box::new(pest::error::Error::new_from_span(
53        ErrorVariant::CustomError {
54            message: message.into(),
55        },
56        span,
57    )))
58}
59
60mod error_impl {
61    use super::Error;
62    use std::fmt;
63
64    impl fmt::Display for Error {
65        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66            fmt::Display::fmt(&self.0, f)
67        }
68    }
69
70    impl std::error::Error for Error {
71        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
72            self.0.source()
73        }
74    }
75}