Skip to main content

meta_language/grammar/import/
mod.rs

1//! Importers for external grammar definition formats.
2
3use std::error::Error;
4use std::fmt;
5
6use crate::grammar::GrammarFormat;
7
8mod abnf;
9mod antlr;
10mod bnf;
11mod ebnf;
12mod gbnf;
13mod lark;
14mod pest;
15mod tree_sitter_json;
16
17pub use abnf::import_abnf;
18pub use antlr::import_antlr;
19pub use bnf::import_bnf;
20pub use ebnf::import_ebnf;
21pub use gbnf::import_gbnf;
22pub use lark::import_lark;
23pub use pest::import_pest;
24pub use tree_sitter_json::import_tree_sitter_json;
25
26/// Error raised while importing an external grammar notation.
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub enum GrammarImportError {
29    /// The source text could not be parsed or validated as the requested format.
30    Parse {
31        /// Grammar format being imported.
32        format: GrammarFormat,
33        /// Human-readable error message.
34        message: String,
35    },
36    /// The importer parsed the input but cannot lower this construct yet.
37    Unsupported {
38        /// Grammar format being imported.
39        format: GrammarFormat,
40        /// Construct name or summary.
41        construct: String,
42    },
43}
44
45impl fmt::Display for GrammarImportError {
46    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
47        match self {
48            Self::Parse { format, message } => {
49                write!(formatter, "{format} import parse error: {message}")
50            }
51            Self::Unsupported { format, construct } => {
52                write!(
53                    formatter,
54                    "{format} import unsupported construct: {construct}"
55                )
56            }
57        }
58    }
59}
60
61impl Error for GrammarImportError {}
62
63pub(super) fn parse_error(format: GrammarFormat, message: impl Into<String>) -> GrammarImportError {
64    GrammarImportError::Parse {
65        format,
66        message: message.into(),
67    }
68}
69
70pub(super) fn unsupported_error(
71    format: GrammarFormat,
72    construct: impl Into<String>,
73) -> GrammarImportError {
74    GrammarImportError::Unsupported {
75        format,
76        construct: construct.into(),
77    }
78}