Skip to main content

conjure_cp_essence_parser/parser/
macros.rs

1/// Get the i-th named child of a node, or return a syntax error with a message if it doesn't exist.
2#[macro_export]
3macro_rules! named_child {
4    ($node:ident) => {
5        named_child!($node, 0, "Missing sub-expression")
6    };
7    ($node:ident, $i:literal) => {
8        named_child!($node, $i, format!("Missing sub-expression #{}", $i + 1))
9    };
10    ($node:ident, $i:literal, $msg:expr) => {
11        $node.named_child($i).ok_or(FatalParseError::syntax_error(
12            format!("{} in expression of kind '{}'", $msg, $node.kind()),
13            Some($node.range()),
14        ))?
15    };
16}
17
18/// Get the i-th child of a node, or return a syntax error with a message if it doesn't exist.
19#[macro_export]
20macro_rules! child {
21    ($node:ident) => {
22        child!($node, 0, "Missing sub-expression")
23    };
24    ($node:ident, $i:literal) => {
25        child!($node, $i, format!("Missing sub-expression #{}", $i + 1))
26    };
27    ($node:ident, $i:literal, $msg:expr) => {
28        $node.child($i).ok_or(FatalParseError::syntax_error(
29            format!("{} in expression of kind '{}'", $msg, $node.kind()),
30            Some($node.range()),
31        ))?
32    };
33}
34
35/// Get the named field of a node, or return a syntax error with a message if it doesn't exist.
36#[macro_export]
37macro_rules! field {
38    ($node:ident, $name:expr) => {
39        $node
40            .child_by_field_name($name)
41            .ok_or(FatalParseError::syntax_error(
42                format!(
43                    "Missing field '{}' in expression of kind '{}'",
44                    $name,
45                    $node.kind()
46                ),
47                Some($node.range()),
48            ))?
49    };
50}