[][src]Macro egg::define_language

macro_rules! define_language {
    (
        $(#[$meta:meta])*
        $vis:vis enum $name:ident {
            $($variant:ident $(( $($t:ty),* ))? $(= $str:literal)? ),*
                $(,)?
        }
    ) => { ... };
    (@parse_arm $e:expr, $name:ident $variant:ident = $str:literal) => { ... };
    (@parse_arm $e:expr, $name:ident $variant:ident) => { ... };
    (@parse_arm $e:expr, $name:ident $variant:ident ( $t:ty ) ) => { ... };
    (@parse_arm $e:expr, $name:ident $variant:ident ( $($t:ty),* ) ) => { ... };
    (@print_arm $e:expr, $f:expr, $name:ident $variant:ident = $str:literal) => { ... };
    (@print_arm $e:expr, $f:expr, $name:ident $variant:ident ( $t:ty ) ) => { ... };
    (@print_arm $e:expr, $f:expr, $name:ident $variant:ident ( $($t:ty),* ) ) => { ... };
}

A macro to easily create a Language.

Example use:

define_language! {
    enum SimpleLanguage {
        Num(i32),
        Add = "+",
        Mul = "*",
        // language items are parsed in order, and we want symbol to
        // be a fallback, so we put it last
        Symbol(String),
    }
}

define_language derives Debug, PartialEq, Eq, Hash, and Clone on the given enum so it can implement Language. The macro also implements FromStr and Display for the enum based on either the data of variants or the provided strings.

Enum variants must be of one of two forms:

  • Variant = "name"

    This form's FromStr and Display parse and print the given string, in this case "name".

  • Variant(Data)

    This form uses the FromStr and Display implementations of the given type Data. So Data needs to implement those as well as all of the trait bounds of Language.

    Since the parser will not consider the name of the variant, your language cannot have two variants with the same data type; the second will never get parsed. Likewise, you must order your variants from most specific to most general; the parser will try to parse the variants from top to bottom.

Variants not in one of the two above forms will fail to compile:

This example deliberately fails to compile
define_language! {
    enum SimpleLanguage {
        Num,
    }
}

Note that you can always implement Language yourself, and that Language does not require FromStr or Display. But they are pretty handy.