Skip to main content

meta_language/grammar/interchange/
feature_links.rs

1//! The grammar feature union in the native links form: the declaration links
2//! `(import NAME)`, `(mode NAME)`, `(extra EXPRESSION)`, `(conflict NAME...)`,
3//! `(precedences (name|rule NAME)...)`, `(macro NAME (parameters P...) EXPRESSION)` and `(scanner NAME (tokens
4//! T...) (operations OPERATION...))` between the grammar link and the first
5//! rule, the rule fields `(parameters P...)`, `(channel NAME)`, `(modes
6//! M...)` and `(action OPERATION...)` and the rule metadata `(concept ID)` and
7//! `(source-names (SOURCE NAME)...)` before `(doc TEXT)`, and the feature
8//! expressions. It mirrors `js/src/grammar-links.js`.
9
10use super::super::feature::class_expression;
11use super::super::{
12    FeatureExpr, GrammarDeclarations, GrammarExpr, GrammarImportError, GrammarLexer, GrammarMacro,
13    GrammarScanner, GrammarSourceName, Operation, OperationCategory, PrecedenceEntry,
14    RuleAttributes, UnicodeClassItem,
15};
16use super::feature_forms::{
17    FormCodec, LinksReader, read_links_feature, read_links_operation, render_feature_form,
18    render_operation,
19};
20use super::links::{
21    Node, arity, char_text, decoded_word, link, links_error, parse_node, parts,
22    percent_decode_links_text, percent_encode_links_text, render_links_expression, word,
23};
24
25/// The links spelling of the feature union forms.
26struct LinksCodec;
27
28impl FormCodec for LinksCodec {
29    fn name(&self, value: &str) -> String {
30        percent_encode_links_text(value)
31    }
32
33    fn text(&self, value: &str) -> String {
34        percent_encode_links_text(value)
35    }
36
37    fn expression(&self, expr: &GrammarExpr) -> String {
38        render_links_expression(expr)
39    }
40
41    fn call(&self, head: &str, parts: Vec<String>) -> String {
42        if parts.is_empty() {
43            return head.to_owned();
44        }
45        let mut all = vec![head.to_owned()];
46        all.extend(parts);
47        link(&all)
48    }
49
50    fn block(&self, word: &str, parts: Vec<String>) -> String {
51        let mut all = vec![word.to_owned()];
52        all.extend(parts);
53        link(&all)
54    }
55
56    fn byte_class(&self, negated: bool, items: Vec<String>) -> String {
57        let mut all = vec![
58            "byteClass".to_owned(),
59            if negated { "negated" } else { "plain" }.to_owned(),
60        ];
61        all.extend(items);
62        link(&all)
63    }
64}
65
66/// Renders one feature union expression of the native links form.
67pub(super) fn render_links_feature(feature: &FeatureExpr) -> String {
68    match feature {
69        FeatureExpr::UnicodeClass { negated, items } => {
70            let mut parts = vec![
71                "class".to_owned(),
72                if *negated { "negated" } else { "plain" }.to_owned(),
73            ];
74            parts.extend(items.iter().map(|item| match item {
75                UnicodeClassItem::Char(value) => link(&["char".to_owned(), char_text(*value)]),
76                UnicodeClassItem::Range(start, end) => {
77                    link(&["range".to_owned(), char_text(*start), char_text(*end)])
78                }
79                UnicodeClassItem::Category(value) => {
80                    link(&["category".to_owned(), percent_encode_links_text(value)])
81                }
82                UnicodeClassItem::Script(value) => {
83                    link(&["script".to_owned(), percent_encode_links_text(value)])
84                }
85            }));
86            link(&parts)
87        }
88        FeatureExpr::Call { name, arguments } => {
89            let mut parts = vec!["ref".to_owned(), percent_encode_links_text(name)];
90            parts.extend(arguments.iter().map(render_links_expression));
91            link(&parts)
92        }
93        FeatureExpr::Form(_) | FeatureExpr::ByteClass { .. } => {
94            render_feature_form(feature, &LinksCodec).unwrap_or_default()
95        }
96    }
97}
98
99fn render_names(head: &str, names: &[String]) -> String {
100    let mut parts = vec![head.to_owned()];
101    parts.extend(names.iter().map(|name| percent_encode_links_text(name)));
102    link(&parts)
103}
104
105fn render_operations(head: &str, operations: &[Operation]) -> String {
106    let mut parts = vec![head.to_owned()];
107    parts.extend(
108        operations
109            .iter()
110            .map(|operation| render_operation(operation, &LinksCodec)),
111    );
112    link(&parts)
113}
114
115/// The declaration links between the grammar link and the first rule.
116#[must_use]
117pub fn render_declaration_links(declarations: &GrammarDeclarations) -> Vec<String> {
118    let mut lines = Vec::new();
119    for name in &declarations.imports {
120        lines.push(format!("(import {})", percent_encode_links_text(name)));
121    }
122    for name in &declarations.modes {
123        lines.push(format!("(mode {})", percent_encode_links_text(name)));
124    }
125    for extra in &declarations.extras {
126        lines.push(format!("(extra {})", render_links_expression(extra)));
127    }
128    for group in &declarations.conflicts {
129        lines.push(render_names("conflict", group));
130    }
131    for order in &declarations.precedences {
132        let entries = order.iter().map(|entry| {
133            format!(
134                "({} {})",
135                entry.kind(),
136                percent_encode_links_text(entry.value())
137            )
138        });
139        lines.push(format!(
140            "(precedences {})",
141            entries.collect::<Vec<_>>().join(" ")
142        ));
143    }
144    for declared in &declarations.macros {
145        lines.push(format!(
146            "(macro {} {} {})",
147            percent_encode_links_text(&declared.name),
148            render_names("parameters", &declared.parameters),
149            render_links_expression(&declared.expression)
150        ));
151    }
152    for scanner in &declarations.scanners {
153        lines.push(format!(
154            "(scanner {} {} {})",
155            percent_encode_links_text(&scanner.name),
156            render_names("tokens", &scanner.tokens),
157            render_operations("operations", &scanner.operations)
158        ));
159    }
160    for lexer in &declarations.lexers {
161        lines.push(format!(
162            "(lexer {} {})",
163            percent_encode_links_text(&lexer.name),
164            render_links_expression(&lexer.expression)
165        ));
166    }
167    lines
168}
169
170/// The rule fields before the `(doc TEXT)` field.
171#[must_use]
172pub fn render_rule_fields(attributes: &RuleAttributes) -> Vec<String> {
173    let mut fields = Vec::new();
174    if !attributes.parameters.is_empty() {
175        fields.push(render_names("parameters", &attributes.parameters));
176    }
177    if let Some(channel) = &attributes.channel {
178        fields.push(format!("(channel {})", percent_encode_links_text(channel)));
179    }
180    if let Some(modes) = &attributes.modes {
181        fields.push(render_names("modes", modes));
182    }
183    if let Some(action) = &attributes.action {
184        fields.push(render_operations("action", action));
185    }
186    fields
187}
188
189/// The links reader of the shared feature form tables.
190struct Helpers;
191
192impl LinksReader for Helpers {
193    type Node = Node;
194
195    fn parts<'a>(&self, node: &'a Node) -> Result<(&'a str, &'a [Node]), GrammarImportError> {
196        parts(node)
197    }
198
199    fn word<'a>(&self, node: &'a Node, what: &str) -> Result<&'a str, GrammarImportError> {
200        word(Some(node), what)
201    }
202
203    fn decoded_word(&self, node: &Node, what: &str) -> Result<String, GrammarImportError> {
204        decoded_word(Some(node), what)
205    }
206
207    fn expression(&self, node: &Node) -> Result<GrammarExpr, GrammarImportError> {
208        parse_node(node)
209    }
210
211    fn fail(&self, detail: String) -> GrammarImportError {
212        links_error(detail)
213    }
214}
215
216/// Reads a feature union expression headed by `head`, or `None`.
217pub(super) fn read_feature(
218    head: &str,
219    args: &[Node],
220) -> Result<Option<GrammarExpr>, GrammarImportError> {
221    read_links_feature(&Helpers, head, args)
222}
223
224/// Reads a `(class plain|negated ITEM...)` link's items.
225pub(super) fn read_class(negated: bool, items: &[Node]) -> Result<GrammarExpr, GrammarImportError> {
226    let items = items
227        .iter()
228        .map(|item| {
229            let (head, args) = parts(item)?;
230            match head {
231                "char" => {
232                    arity(head, args, 1)?;
233                    Ok(UnicodeClassItem::Char(super::links::character(
234                        args.first(),
235                        "a class character",
236                    )?))
237                }
238                "range" => {
239                    arity(head, args, 2)?;
240                    Ok(UnicodeClassItem::Range(
241                        super::links::character(args.first(), "a range start")?,
242                        super::links::character(args.get(1), "a range end")?,
243                    ))
244                }
245                "category" | "script" => {
246                    arity(head, args, 1)?;
247                    let value = decoded_word(args.first(), &format!("a Unicode {head}"))?;
248                    Ok(if head == "category" {
249                        UnicodeClassItem::Category(value)
250                    } else {
251                        UnicodeClassItem::Script(value)
252                    })
253                }
254                other => Err(links_error(format!("unknown class item {other}"))),
255            }
256        })
257        .collect::<Result<_, _>>()?;
258    Ok(class_expression(negated, items))
259}
260
261fn names(node: &Node, head: &str) -> Result<Vec<String>, GrammarImportError> {
262    let (found, args) = parts(node)?;
263    if found != head {
264        return Err(links_error(format!("expected ({head} ...), not {found}")));
265    }
266    args.iter()
267        .map(|item| decoded_word(Some(item), &format!("a {head} name")))
268        .collect()
269}
270
271fn operations(node: &Node, head: &str) -> Result<Vec<Operation>, GrammarImportError> {
272    let (found, args) = parts(node)?;
273    if found != head {
274        return Err(links_error(format!("expected ({head} ...), not {found}")));
275    }
276    args.iter()
277        .map(|item| read_links_operation(&Helpers, item, OperationCategory::Statement))
278        .collect()
279}
280
281/// Reads one declaration link into `declarations`; `false` when `head` names none.
282pub(super) fn read_declaration(
283    head: &str,
284    args: &[Node],
285    declarations: &mut GrammarDeclarations,
286) -> Result<bool, GrammarImportError> {
287    let one = || arity(head, args, 1).map(|()| &args[0]);
288    match head {
289        "import" => declarations
290            .imports
291            .push(decoded_word(Some(one()?), "an imported grammar")?),
292        "mode" => declarations
293            .modes
294            .push(decoded_word(Some(one()?), "a mode")?),
295        "extra" => declarations.extras.push(parse_node(one()?)?),
296        "conflict" => {
297            if args.is_empty() {
298                return Err(links_error("conflict names at least one rule"));
299            }
300            declarations.conflicts.push(
301                args.iter()
302                    .map(|item| decoded_word(Some(item), "a rule name"))
303                    .collect::<Result<_, _>>()?,
304            );
305        }
306        "precedences" => {
307            if args.len() < 2 {
308                return Err(links_error("precedences orders at least two entries"));
309            }
310            let mut order = Vec::new();
311            for item in args {
312                let (kind, values) = parts(item)?;
313                let what = match kind {
314                    "name" => "a precedence name",
315                    "rule" => "a rule name",
316                    other => {
317                        return Err(links_error(format!(
318                            "a precedence entry is (name NAME) or (rule NAME), not {other}"
319                        )));
320                    }
321                };
322                arity(kind, values, 1)?;
323                let value = decoded_word(values.first(), what)?;
324                order.extend(PrecedenceEntry::from_kind(kind, value));
325            }
326            declarations.precedences.push(order);
327        }
328        "macro" => {
329            arity(head, args, 3)?;
330            declarations.macros.push(GrammarMacro {
331                name: decoded_word(args.first(), "a macro name")?,
332                parameters: names(&args[1], "parameters")?,
333                expression: parse_node(&args[2])?,
334            });
335        }
336        "lexer" => {
337            arity(head, args, 2)?;
338            declarations.lexers.push(GrammarLexer {
339                name: decoded_word(args.first(), "a lexer name")?,
340                expression: parse_node(&args[1])?,
341            });
342        }
343        "scanner" => {
344            arity(head, args, 3)?;
345            declarations.scanners.push(GrammarScanner {
346                name: decoded_word(args.first(), "a scanner name")?,
347                tokens: names(&args[1], "tokens")?,
348                operations: operations(&args[2], "operations")?,
349            });
350        }
351        _ => return Ok(false),
352    }
353    Ok(true)
354}
355
356/// The rule fields in order: the attributes, the metadata `(concept ID)` and
357/// `(source-names (SOURCE NAME)...)`, and `(doc TEXT)`.
358const RULE_FIELDS: [&str; 7] = [
359    "parameters",
360    "channel",
361    "modes",
362    "action",
363    "concept",
364    "source-names",
365    "doc",
366];
367
368/// The optional fields of a rule link.
369#[derive(Default)]
370pub(super) struct RuleFields {
371    pub attributes: RuleAttributes,
372    pub concept: Option<String>,
373    pub source_names: Vec<GrammarSourceName>,
374    pub doc: Option<String>,
375}
376
377/// Reads the `(SOURCE NAME)...` items of `(source-names (SOURCE NAME)...)`.
378pub(super) fn read_source_names(
379    args: &[Node],
380) -> Result<Vec<GrammarSourceName>, GrammarImportError> {
381    if args.is_empty() {
382        return Err(links_error("source-names lists at least one source name"));
383    }
384    args.iter()
385        .map(|item| {
386            let (source, name) = parts(item)?;
387            if name.len() != 1 {
388                return Err(links_error("a source name is (SOURCE NAME)"));
389            }
390            Ok(GrammarSourceName {
391                source: percent_decode_links_text(source)?,
392                name: decoded_word(name.first(), "a source name")?,
393            })
394        })
395        .collect()
396}
397
398/// Reads the optional fields of a rule link: its attributes, its metadata and
399/// its doc.
400pub(super) fn read_rule_fields(fields: &[Node]) -> Result<RuleFields, GrammarImportError> {
401    let mut read = RuleFields::default();
402    let mut order = 0;
403    for field in fields {
404        let (head, args) = parts(field)?;
405        let Some(position) = RULE_FIELDS.iter().position(|name| *name == head) else {
406            return Err(links_error(format!("unexpected rule field {head}")));
407        };
408        if position < order {
409            return Err(links_error(format!("rule field {head} is out of order")));
410        }
411        order = position + 1;
412        match head {
413            "parameters" => read.attributes.parameters = names(field, "parameters")?,
414            "modes" => read.attributes.modes = Some(names(field, "modes")?),
415            "action" => read.attributes.action = Some(operations(field, "action")?),
416            "source-names" => read.source_names = read_source_names(args)?,
417            "channel" => {
418                arity(head, args, 1)?;
419                read.attributes.channel = Some(decoded_word(args.first(), "a channel name")?);
420            }
421            "concept" => {
422                arity(head, args, 1)?;
423                read.concept = Some(decoded_word(args.first(), "a concept id")?);
424            }
425            _ => {
426                arity(head, args, 1)?;
427                read.doc = Some(decoded_word(args.first(), "a doc text")?);
428            }
429        }
430    }
431    Ok(read)
432}