Skip to main content

meta_language/grammar/
decorators.rs

1//! The grammar and syntax tree levels of [`DecoratorSet`].
2
3use super::feature_runtime::{LeafText, SyntaxTree};
4use super::merge::rename_grammar_rule;
5use super::{Grammar, GrammarFormat, RuleKind};
6use crate::decorators::{
7    DecoratorAction, DecoratorError, DecoratorLevel, DecoratorRecord, DecoratorSet,
8    decorator_record, record_field,
9};
10
11mod composition;
12
13/// The grammar the `importer` or `grammar-rule` decorators of `decorators`
14/// make of `grammar`.
15///
16/// Each rule is shown as `{ name, kind, concept, composition }`, with
17/// `format` (the grammar's source format) added at the `importer` level.
18/// Setting `name` renames the rule and every reference to it, setting `kind`
19/// or `concept` changes the rule, and `drop` removes it. A nonempty composition
20/// is one closed any/all Links template with an empty insertion slot for the
21/// original expression. The rules are
22/// decorated in grammar order; a grammar without decorators of the level is
23/// returned unchanged.
24///
25/// # Errors
26///
27/// A [`DecoratorError`] for an unknown rule kind or a rename the grammar
28/// refuses.
29pub fn decorate_grammar(
30    grammar: &Grammar,
31    decorators: &DecoratorSet,
32    level: DecoratorLevel,
33) -> Result<Grammar, DecoratorError> {
34    if !decorators.has(level) {
35        return Ok(grammar.clone());
36    }
37    let mut renames = Vec::new();
38    let mut rules = Vec::new();
39    let composition = decorators.for_level(level).any(|decorator| {
40        decorator.actions().iter().any(|action| match action {
41            DecoratorAction::Set { field, .. } | DecoratorAction::Replace { field, .. } => {
42                field == "composition"
43            }
44            DecoratorAction::Drop => false,
45        })
46    });
47    let tree_decorators =
48        decorators.has(DecoratorLevel::Executor) || decorators.has(DecoratorLevel::Recovery);
49    for rule in grammar.rules() {
50        if composition {
51            composition::check_grammar_composition_rule_data(rule)?;
52        }
53        let mut record = DecoratorRecord::new();
54        record.insert("name".to_owned(), rule.name.clone());
55        record.insert("kind".to_owned(), rule.kind.as_str().to_owned());
56        record.insert(
57            "concept".to_owned(),
58            rule.concept.clone().unwrap_or_default(),
59        );
60        record.insert("composition".to_owned(), String::new());
61        if level == DecoratorLevel::Importer {
62            let format = grammar.source_format().map_or("", GrammarFormat::as_str);
63            record.insert("format".to_owned(), format.to_owned());
64        }
65        let Some(decorated) = decorators.decorate(level, &record) else {
66            continue;
67        };
68        let mut rule = rule.clone();
69        let kind = record_field(&decorated, "kind");
70        rule.kind = RuleKind::from_tag(kind).ok_or_else(|| {
71            DecoratorError::new(format!("a decorator set the unknown rule kind {kind:?}"))
72        })?;
73        let concept = record_field(&decorated, "concept");
74        rule.concept = (!concept.is_empty()).then(|| concept.to_owned());
75        let source = record_field(&decorated, "composition");
76        if !source.is_empty() {
77            rule.expr =
78                composition::compose_grammar_rule_expression(&rule, source, kind, tree_decorators)?;
79        }
80        let name = record_field(&decorated, "name");
81        if name != rule.name {
82            renames.push((rule.name.clone(), name.to_owned()));
83        }
84        rules.push(rule);
85    }
86    let mut result = grammar.clone();
87    result.rules = rules;
88    for (from, to) in renames {
89        result = rename_grammar_rule(&result, &from, &to, None, &[])
90            .map_err(|error| DecoratorError::new(error.to_string()))?
91            .grammar;
92    }
93    Ok(result)
94}
95
96fn optional(text: &str) -> Option<String> {
97    (!text.is_empty()).then(|| text.to_owned())
98}
99
100/// The syntax tree the `executor` and `recovery` decorators of `decorators`
101/// make of `tree`.
102///
103/// The `executor` level shows every node and token as
104/// `{ type, kind, field, text }` (`text` for tokens): setting `kind` or
105/// `field` changes it, and `drop` replaces a node with its children, so the
106/// tree still holds every byte; a token cannot be dropped. The `recovery`
107/// level shows every ERROR node as `{ type, reason, text }` and every MISSING
108/// node as `{ type, kind }`: setting `reason` or `kind` changes it, and
109/// `drop` removes a MISSING node, which spans no input; an ERROR node cannot
110/// be dropped.
111///
112/// # Errors
113///
114/// A [`DecoratorError`] when a decorator drops a token, an ERROR node or the
115/// root.
116pub fn decorate_syntax_tree(
117    tree: &SyntaxTree,
118    decorators: &DecoratorSet,
119    source: &[u8],
120) -> Result<SyntaxTree, DecoratorError> {
121    if !decorators.has(DecoratorLevel::Executor) && !decorators.has(DecoratorLevel::Recovery) {
122        return Ok(tree.clone());
123    }
124    let mut roots = visit(tree, decorators, source, false)?;
125    if roots.len() != 1 {
126        return Err(DecoratorError::new(
127            "a decorator dropped the root of the syntax tree",
128        ));
129    }
130    Ok(roots.remove(0))
131}
132
133fn visit(
134    tree: &SyntaxTree,
135    decorators: &DecoratorSet,
136    source: &[u8],
137    decoded_text: bool,
138) -> Result<Vec<SyntaxTree>, DecoratorError> {
139    let text_of = |text: &LeafText, start: usize, end: usize| {
140        if decoded_text {
141            match text {
142                LeafText::Text(text) => text.clone(),
143                LeafText::Hex(_) => String::new(),
144            }
145        } else {
146            String::from_utf8_lossy(source.get(start..end).unwrap_or_default()).into_owned()
147        }
148    };
149    let mut copy = tree.clone();
150    match &mut copy {
151        SyntaxTree::Node {
152            kind,
153            field,
154            children,
155            ..
156        } => {
157            let mut record = DecoratorRecord::new();
158            record.insert("type".to_owned(), "node".to_owned());
159            record.insert("kind".to_owned(), kind.clone());
160            record.insert("field".to_owned(), field.clone().unwrap_or_default());
161            let decorated = decorators.decorate(DecoratorLevel::Executor, &record);
162            let mut visited = Vec::new();
163            for child in children.iter() {
164                visited.extend(visit(child, decorators, source, decoded_text)?);
165            }
166            let Some(decorated) = decorated else {
167                return Ok(visited);
168            };
169            record_field(&decorated, "kind").clone_into(kind);
170            *field = optional(record_field(&decorated, "field"));
171            *children = visited;
172        }
173        SyntaxTree::Token {
174            kind,
175            field,
176            start,
177            end,
178            text,
179            ..
180        } => {
181            let mut record = DecoratorRecord::new();
182            record.insert("type".to_owned(), "token".to_owned());
183            record.insert("kind".to_owned(), kind.clone().unwrap_or_default());
184            record.insert("field".to_owned(), field.clone().unwrap_or_default());
185            record.insert("text".to_owned(), text_of(text, *start, *end));
186            let Some(decorated) = decorators.decorate(DecoratorLevel::Executor, &record) else {
187                return Err(DecoratorError::new(format!(
188                    "a decorator dropped the token {}; the executor level keeps every token",
189                    kind.as_deref().unwrap_or_default()
190                )));
191            };
192            *kind = optional(record_field(&decorated, "kind"));
193            *field = optional(record_field(&decorated, "field"));
194        }
195        SyntaxTree::Error {
196            start,
197            end,
198            reason,
199            text,
200            ..
201        } => {
202            let mut record = DecoratorRecord::new();
203            record.insert("type".to_owned(), "error".to_owned());
204            record.insert("reason".to_owned(), reason.clone().unwrap_or_default());
205            record.insert("text".to_owned(), text_of(text, *start, *end));
206            let Some(decorated) = decorators.decorate(DecoratorLevel::Recovery, &record) else {
207                return Err(DecoratorError::new(
208                    "a decorator dropped an ERROR node; only a MISSING node can be dropped",
209                ));
210            };
211            *reason = optional(record_field(&decorated, "reason"));
212        }
213        SyntaxTree::Missing { kind, .. } => {
214            let mut record = DecoratorRecord::new();
215            record.insert("type".to_owned(), "missing".to_owned());
216            record.insert("kind".to_owned(), kind.clone().unwrap_or_default());
217            let Some(decorated) = decorators.decorate(DecoratorLevel::Recovery, &record) else {
218                return Ok(Vec::new());
219            };
220            *kind = optional(record_field(&decorated, "kind"));
221        }
222        SyntaxTree::Embed {
223            root,
224            source_children,
225            selection,
226            ..
227        } => {
228            let mapped = source_children.is_some();
229            let mut roots = visit(root, decorators, source, decoded_text || mapped)?;
230            if roots.len() != 1 {
231                return Err(DecoratorError::new(if mapped {
232                    "a mapped grammar keeps one complete decoded CST root"
233                } else {
234                    "a decorator dropped the root of an embedded tree"
235                }));
236            }
237            **root = roots.remove(0);
238            if let Some(children) = source_children {
239                let mut physical = Vec::new();
240                for child in &*children {
241                    physical.extend(visit(child, decorators, source, decoded_text)?);
242                }
243                *children = physical;
244                if let Some(selection) = selection {
245                    for alternative in &mut selection.alternatives {
246                        let mut roots = visit(&alternative.root, decorators, source, true)?;
247                        if roots.len() != 1 {
248                            return Err(DecoratorError::new(
249                                "a mapped grammar witness keeps one complete decoded CST root",
250                            ));
251                        }
252                        *alternative.root = roots.remove(0);
253                    }
254                }
255            }
256        }
257    }
258    Ok(vec![copy])
259}
260
261/// The emitted grammar `source` after the `emitter` decorators of
262/// `decorators`.
263///
264/// They see each line as `{ format, number, line }` (`number`
265/// counts from 1): setting `line` rewrites it and `drop` removes it. Apply it
266/// to the source an emitter such as [`super::emit_gbnf`] returns; the emit
267/// report is kept as it is.
268#[must_use]
269pub fn decorate_emitted(format: &str, source: &str, decorators: &DecoratorSet) -> String {
270    if !decorators.has(DecoratorLevel::Emitter) {
271        return source.to_owned();
272    }
273    let (body, ending) = source
274        .strip_suffix('\n')
275        .map_or((source, ""), |body| (body, "\n"));
276    let kept: Vec<String> = body
277        .split('\n')
278        .enumerate()
279        .filter_map(|(index, line)| {
280            let number = (index + 1).to_string();
281            let record = decorator_record([
282                ("format", format),
283                ("number", number.as_str()),
284                ("line", line),
285            ]);
286            decorators
287                .decorate(DecoratorLevel::Emitter, &record)
288                .map(|decorated| record_field(&decorated, "line").to_owned())
289        })
290        .collect();
291    if kept.is_empty() {
292        String::new()
293    } else {
294        format!("{}{ending}", kept.join("\n"))
295    }
296}