Add raw API for custom syntax.
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
use rhai::{Engine, EvalAltResult, EvalContext, Expression, ParseErrorType, INT};
|
||||
use rhai::{Engine, EvalAltResult, ParseError, ParseErrorType, Position, INT};
|
||||
|
||||
#[test]
|
||||
fn test_custom_syntax() -> Result<(), Box<EvalAltResult>> {
|
||||
@@ -19,10 +19,10 @@ fn test_custom_syntax() -> Result<(), Box<EvalAltResult>> {
|
||||
|
||||
engine.register_custom_syntax(
|
||||
&[
|
||||
"do", "|", "$ident$", "|", "->", "$block$", "while", "$expr$",
|
||||
"exec", "|", "$ident$", "|", "->", "$block$", "while", "$expr$",
|
||||
],
|
||||
1,
|
||||
|context: &mut EvalContext, inputs: &[Expression]| {
|
||||
|context, inputs| {
|
||||
let var_name = inputs[0].get_variable_name().unwrap().to_string();
|
||||
let stmt = inputs.get(1).unwrap();
|
||||
let condition = inputs.get(2).unwrap();
|
||||
@@ -58,7 +58,7 @@ fn test_custom_syntax() -> Result<(), Box<EvalAltResult>> {
|
||||
assert_eq!(
|
||||
engine.eval::<INT>(
|
||||
r"
|
||||
do |x| -> { x += 1 } while x < 42;
|
||||
exec |x| -> { x += 1 } while x < 42;
|
||||
x
|
||||
"
|
||||
)?,
|
||||
@@ -71,7 +71,48 @@ fn test_custom_syntax() -> Result<(), Box<EvalAltResult>> {
|
||||
.register_custom_syntax(&["!"], 0, |_, _| Ok(().into()))
|
||||
.expect_err("should error")
|
||||
.0,
|
||||
ParseErrorType::BadInput("Improper symbol for custom syntax: '!'".to_string())
|
||||
ParseErrorType::BadInput(
|
||||
"Improper symbol for custom syntax at position #1: '!'".to_string()
|
||||
)
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_custom_syntax_raw() -> Result<(), Box<EvalAltResult>> {
|
||||
let mut engine = Engine::new();
|
||||
|
||||
engine.register_custom_syntax_raw(
|
||||
"hello",
|
||||
|stream| match stream.len() {
|
||||
0 => unreachable!(),
|
||||
1 => Ok(Some("$ident$".into())),
|
||||
2 => match stream[1].as_str() {
|
||||
"world" | "kitty" => Ok(None),
|
||||
s => Err(ParseError(
|
||||
Box::new(ParseErrorType::BadInput(s.to_string())),
|
||||
Position::none(),
|
||||
)),
|
||||
},
|
||||
_ => unreachable!(),
|
||||
},
|
||||
0,
|
||||
|_, inputs| {
|
||||
Ok(match inputs[0].get_variable_name().unwrap() {
|
||||
"world" => 123 as INT,
|
||||
"kitty" => 42 as INT,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
.into())
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(engine.eval::<INT>("hello world")?, 123);
|
||||
assert_eq!(engine.eval::<INT>("hello kitty")?, 42);
|
||||
assert_eq!(
|
||||
*engine.compile("hello hey").expect_err("should error").0,
|
||||
ParseErrorType::BadInput("hey".to_string())
|
||||
);
|
||||
|
||||
Ok(())
|
||||
|
Reference in New Issue
Block a user