Macro synom::switch [] [src]

macro_rules! switch {
    ($i:expr, $submac:ident!( $($args:tt)* ), $($p:pat => $subrule:ident!( $($args2:tt)* ))|* ) => { ... };
}

Pattern-match the result of a parser to select which other parser to run.

  • Syntax: switch!(TARGET, PAT1 => THEN1 | PAT2 => THEN2 | ...)
  • Output: T, the return type of THEN1 and THEN2 and ...
extern crate syn;
#[macro_use] extern crate synom;

use syn::{Ident, Ty};
use syn::parse::{ident, ty};

#[derive(Debug)]
enum UnitType {
    Struct {
        name: Ident,
    },
    Enum {
        name: Ident,
        variant: Ident,
    },
}

// Parse a unit struct or enum: either `struct S;` or `enum E { V }`.
named!(unit_type -> UnitType, do_parse!(
    which: alt!(keyword!("struct") | keyword!("enum")) >>
    id: ident >>
    item: switch!(value!(which),
        "struct" => map!(
            punct!(";"),
            move |_| UnitType::Struct {
                name: id,
            }
        )
        |
        "enum" => map!(
            delimited!(punct!("{"), ident, punct!("}")),
            move |variant| UnitType::Enum {
                name: id,
                variant: variant,
            }
        )
    ) >>
    (item)
));

fn main() {
    let input = "struct S;";
    let parsed = unit_type(input).expect("unit struct or enum");
    println!("{:?}", parsed);

    let input = "enum E { V }";
    let parsed = unit_type(input).expect("unit struct or enum");
    println!("{:?}", parsed);
}