-
Notifications
You must be signed in to change notification settings - Fork 182
/
Copy pathconstants.rs
122 lines (103 loc) · 3.07 KB
/
constants.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
use rhai::{Engine, EvalAltResult, ParseErrorType, Scope, INT};
#[test]
fn test_constant() {
let engine = Engine::new();
assert_eq!(engine.eval::<INT>("const x = 123; x").unwrap(), 123);
assert!(matches!(
*engine.eval::<INT>("const x = 123; x = 42;").expect_err("expects error"),
EvalAltResult::ErrorParsing(ParseErrorType::AssignmentToConstant(x), ..) if x == "x"
));
#[cfg(not(feature = "no_index"))]
assert!(matches!(
*engine.run("const x = [1, 2, 3, 4, 5]; x[2] = 42;").expect_err("expects error"),
EvalAltResult::ErrorAssignmentToConstant(x, ..) if x == "x"
));
}
#[test]
fn test_constant_scope() {
let engine = Engine::new();
let mut scope = Scope::new();
scope.push_constant("x", 42 as INT);
assert!(matches!(
*engine.run_with_scope(&mut scope, "x = 1").expect_err("expects error"),
EvalAltResult::ErrorAssignmentToConstant(x, ..) if x == "x"
));
}
#[cfg(not(feature = "no_object"))]
#[test]
fn test_constant_mut() {
#[derive(Debug, Clone)]
struct TestStruct(INT); // custom type
let mut engine = Engine::new();
fn set_value(obj: &mut TestStruct, value: INT) {
obj.0 = value;
}
engine
.register_type_with_name::<TestStruct>("TestStruct")
.register_fn("new_ts", || TestStruct(123))
.register_get("value", |obj: &mut TestStruct| obj.0)
.register_set("value", set_value)
.register_fn("update_value", set_value);
assert_eq!(
engine
.eval::<INT>(
"
const MY_NUMBER = new_ts();
MY_NUMBER.update_value(42);
MY_NUMBER.value
",
)
.unwrap(),
42
);
assert_eq!(
engine
.eval::<INT>(
"
const MY_NUMBER = new_ts();
update_value(MY_NUMBER, 42);
MY_NUMBER.value
",
)
.unwrap(),
123
);
assert!(matches!(
*engine
.run(
"
const MY_NUMBER = new_ts();
MY_NUMBER.value = 42;
"
)
.unwrap_err(),
EvalAltResult::ErrorNonPureMethodCallOnConstant(..)
));
let mut scope = Scope::new();
scope.push_constant("MY_NUMBER", TestStruct(123));
assert_eq!(
engine
.eval_with_scope::<INT>(
&mut scope,
"
update_value(MY_NUMBER, 42);
MY_NUMBER.value
",
)
.unwrap(),
123
);
assert_eq!(
engine
.eval_with_scope::<INT>(
&mut scope,
"
MY_NUMBER.update_value(42);
MY_NUMBER.value
",
)
.unwrap(),
42
);
assert!(matches!(*engine.run_with_scope(&mut scope, "MY_NUMBER.value = 42;").unwrap_err(), EvalAltResult::ErrorNonPureMethodCallOnConstant(..)));
}