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