Macro easy_repl::command[][src]

macro_rules! command {
    ($description:expr, ( $($( $name:ident )? : $type:ty),* ) => $handler:expr $(,)?) => { ... };
    (@handler $($type:ty)*, $handler:expr) => { ... };
    (@handler_call $handler:ident; $args:ident; $($types:ty;)*) => { ... };
    (@handler_call $handler:ident, $args:ident, $num:expr; $type:ty; $($types:ty;)* => $($parsed:expr;)*) => { ... };
    (@handler_call $handler:ident, $args:ident, $num:expr; => $($parsed:expr;)*) => { ... };
}
Expand description

Generate Command based on desctiption, list of arg types and a closure used in handler.

This macro should be used when creating Commands. It takes a string description, a list of argument types with optional names (in the form name: type) and a closure. The closure should have the same number of arguments as provided in the argument list. The generated command handler will parse all the arguments and call the closure. The closure used for handler is move.

The following command description:

let cmd = command! {
    "Example command",
    (arg1: i32, arg2: String) => |arg1, arg2| {
        Ok(CommandStatus::Done)
    }
};

will roughly be translated into something like (code here is slightly simplified):

let cmd = Command {
    description: "Example command".into(),
    args_info: vec!["arg1:i32".into(), "arg2:String".into()],
    handler: Box::new(move |args| -> anyhow::Result<CommandStatus> {
        let validator = validator!(i32, String);
        validator(args)?;
        let mut handler = |arg1, arg2| {
            Ok(CommandStatus::Done)
        };
        handler(args[0].parse::<i32>().unwrap(), args[1].parse::<String>().unwrap())
    }),
};