meta_language/grammar/metadata.rs
1//! The metadata of a grammar that keeps the names its rules and node kinds
2//! have in the grammars it was imported or merged from, for the reverse
3//! conversion and for the default trees that keep the upstream node kinds,
4//! and the format a grammar comes from.
5
6use std::fmt;
7
8/// A name a rule has in a grammar it was merged from, such as its tree-sitter
9/// or ANTLR name, kept for the reverse conversion.
10#[derive(Clone, Debug, PartialEq, Eq)]
11pub struct GrammarSourceName {
12 /// The grammar source, such as `tree-sitter` or `antlr`.
13 pub source: String,
14 /// The rule name in that source.
15 pub name: String,
16}
17
18/// A node kind no rule defines, with its names in the grammars it came from.
19///
20/// Such a kind is one an alias names: tree-sitter's
21/// `alias($._line_doc_content, $.doc_comment)` imports as the kind
22/// `documentation_comment` with the tree-sitter name `doc_comment`.
23#[derive(Clone, Debug, PartialEq, Eq)]
24pub struct GrammarKind {
25 /// The native kind name.
26 pub name: String,
27 /// The names of the kind in its sources.
28 pub source_names: Vec<GrammarSourceName>,
29}
30
31/// Origin grammar format.
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub enum GrammarFormat {
34 /// The meta-language's own grammar notation.
35 MetaLanguage,
36 /// Backus-Naur Form.
37 Bnf,
38 /// Extended Backus-Naur Form.
39 Ebnf,
40 /// Augmented Backus-Naur Form.
41 Abnf,
42 /// Parsing Expression Grammar.
43 Peg,
44 /// ANTLR grammar.
45 Antlr,
46 /// Lark grammar.
47 Lark,
48 /// GBNF grammar.
49 Gbnf,
50 /// Tree-sitter grammar.
51 TreeSitter,
52 /// Grammar inferred from examples or observations.
53 Inferred,
54}
55
56impl GrammarFormat {
57 /// Stable tag used in links encoding and display output.
58 #[must_use]
59 pub const fn as_str(self) -> &'static str {
60 match self {
61 Self::MetaLanguage => "meta-language",
62 Self::Bnf => "bnf",
63 Self::Ebnf => "ebnf",
64 Self::Abnf => "abnf",
65 Self::Peg => "peg",
66 Self::Antlr => "antlr",
67 Self::Lark => "lark",
68 Self::Gbnf => "gbnf",
69 Self::TreeSitter => "tree-sitter",
70 Self::Inferred => "inferred",
71 }
72 }
73
74 pub(crate) fn from_tag(value: &str) -> Option<Self> {
75 match value {
76 "meta-language" => Some(Self::MetaLanguage),
77 "bnf" => Some(Self::Bnf),
78 "ebnf" => Some(Self::Ebnf),
79 "abnf" => Some(Self::Abnf),
80 "peg" => Some(Self::Peg),
81 "antlr" => Some(Self::Antlr),
82 "lark" => Some(Self::Lark),
83 "gbnf" => Some(Self::Gbnf),
84 "tree-sitter" => Some(Self::TreeSitter),
85 "inferred" => Some(Self::Inferred),
86 _ => None,
87 }
88 }
89}
90
91impl fmt::Display for GrammarFormat {
92 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
93 formatter.write_str(self.as_str())
94 }
95}