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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
use async_trait::async_trait;
use endbasic_core::ast::{ArgSep, Expr, Value, VarType};
use endbasic_core::eval::eval_all;
use endbasic_core::exec::Machine;
use endbasic_core::syms::{
CallError, CallableMetadata, CallableMetadataBuilder, Command, CommandResult, Function,
FunctionResult, Symbols,
};
use rand::rngs::SmallRng;
use rand::{RngCore, SeedableRng};
use std::cell::RefCell;
use std::cmp::Ordering;
use std::rc::Rc;
const CATEGORY: &str = "Numerical functions";
pub struct Prng {
prng: SmallRng,
last: u32,
}
impl Prng {
pub fn new_from_entryopy() -> Self {
let mut prng = SmallRng::from_entropy();
let last = prng.next_u32();
Self { prng, last }
}
pub fn new_from_seed(seed: i32) -> Self {
let mut prng = SmallRng::seed_from_u64(seed as u64);
let last = prng.next_u32();
Self { prng, last }
}
fn last(&self) -> f64 {
(self.last as f64) / (std::u32::MAX as f64)
}
fn next(&mut self) -> f64 {
self.last = self.prng.next_u32();
self.last()
}
}
pub struct DtoiFunction {
metadata: CallableMetadata,
}
impl DtoiFunction {
pub fn new() -> Rc<Self> {
Rc::from(Self {
metadata: CallableMetadataBuilder::new("DTOI", VarType::Integer)
.with_syntax("expr#")
.with_category(CATEGORY)
.with_description(
"Rounds the given double to the closest integer.
If the value is too small or too big to fit in the integer's range, returns the smallest or \
biggest possible integer that fits, respectively.",
)
.build(),
})
}
}
impl Function for DtoiFunction {
fn metadata(&self) -> &CallableMetadata {
&self.metadata
}
fn exec(&self, args: &[Expr], symbols: &mut Symbols) -> FunctionResult {
let args = eval_all(args, symbols)?;
match args.as_slice() {
[Value::Double(n)] => Ok(Value::Integer(*n as i32)),
_ => Err(CallError::SyntaxError),
}
}
}
pub struct ItodFunction {
metadata: CallableMetadata,
}
impl ItodFunction {
pub fn new() -> Rc<Self> {
Rc::from(Self {
metadata: CallableMetadataBuilder::new("ITOD", VarType::Double)
.with_syntax("expr%")
.with_category(CATEGORY)
.with_description("Converts the given integer to a double.")
.build(),
})
}
}
impl Function for ItodFunction {
fn metadata(&self) -> &CallableMetadata {
&self.metadata
}
fn exec(&self, args: &[Expr], symbols: &mut Symbols) -> FunctionResult {
let args = eval_all(args, symbols)?;
match args.as_slice() {
[Value::Integer(n)] => Ok(Value::Double(*n as f64)),
_ => Err(CallError::SyntaxError),
}
}
}
pub struct RandomizeCommand {
metadata: CallableMetadata,
prng: Rc<RefCell<Prng>>,
}
impl RandomizeCommand {
pub fn new(prng: Rc<RefCell<Prng>>) -> Rc<Self> {
Rc::from(Self {
metadata: CallableMetadataBuilder::new("RANDOMIZE", VarType::Void)
.with_syntax("[seed%]")
.with_category(CATEGORY)
.with_description(
"Reinitializes the pseudo-random number generator.
If no seed is given, uses system entropy to create a new sequence of random numbers.
WARNING: These random numbers offer no cryptographic guarantees.",
)
.build(),
prng,
})
}
}
#[async_trait(?Send)]
impl Command for RandomizeCommand {
fn metadata(&self) -> &CallableMetadata {
&self.metadata
}
async fn exec(&self, args: &[(Option<Expr>, ArgSep)], machine: &mut Machine) -> CommandResult {
match args {
[] => {
*self.prng.borrow_mut() = Prng::new_from_entryopy();
}
[(Some(expr), ArgSep::End)] => match expr.eval(machine.get_mut_symbols())? {
Value::Integer(n) => {
*self.prng.borrow_mut() = Prng::new_from_seed(n);
}
_ => {
return Err(CallError::ArgumentError(
"Random seed must be an integer".to_owned(),
))
}
},
_ => {
return Err(CallError::ArgumentError(
"RANDOMIZE takes zero or one argument".to_owned(),
))
}
};
Ok(())
}
}
pub struct RndFunction {
metadata: CallableMetadata,
prng: Rc<RefCell<Prng>>,
}
impl RndFunction {
pub fn new(prng: Rc<RefCell<Prng>>) -> Rc<Self> {
Rc::from(Self {
metadata: CallableMetadataBuilder::new("RND", VarType::Double)
.with_syntax("n%")
.with_category(CATEGORY)
.with_description(
"Returns a random number in the [0..1] range.
If n% is zero, returns the previously generated random number. If n% is positive, returns a new \
random number.
If you need to generate an integer random number within a specific range, say [0..100], compute it \
with an expression like DTOI%(RND#(1) * 100.0).
WARNING: These random numbers offer no cryptographic guarantees.",
)
.build(),
prng,
})
}
}
impl Function for RndFunction {
fn metadata(&self) -> &CallableMetadata {
&self.metadata
}
fn exec(&self, args: &[Expr], symbols: &mut Symbols) -> FunctionResult {
let args = eval_all(args, symbols)?;
match args.as_slice() {
[] => Ok(Value::Double(self.prng.borrow_mut().next())),
[Value::Integer(n)] => match n.cmp(&0) {
Ordering::Equal => Ok(Value::Double(self.prng.borrow_mut().last())),
Ordering::Greater => Ok(Value::Double(self.prng.borrow_mut().next())),
Ordering::Less => Err(CallError::ArgumentError("n% cannot be negative".to_owned())),
},
_ => Err(CallError::SyntaxError),
}
}
}
pub fn add_all(machine: &mut Machine) {
let prng = Rc::from(RefCell::from(Prng::new_from_entryopy()));
machine.add_command(RandomizeCommand::new(prng.clone()));
machine.add_function(DtoiFunction::new());
machine.add_function(ItodFunction::new());
machine.add_function(RndFunction::new(prng));
}
#[cfg(test)]
mod tests {
use crate::testutils::*;
#[test]
fn test_dtoi() {
check_expr_ok(0, "DTOI( 0.1)");
check_expr_ok(0, "DTOI(-0.1)");
check_expr_ok(0, "DTOI( 0.9)");
check_expr_ok(0, "DTOI(-0.9)");
check_expr_ok(100, "DTOI( 100.1)");
check_expr_ok(-100, "DTOI(-100.1)");
check_expr_ok(100, "DTOI( 100.9)");
check_expr_ok(-100, "DTOI(-100.9)");
check_expr_ok(std::i32::MAX, "DTOI(12345678901234567890.0)");
check_expr_ok(std::i32::MIN, "DTOI(-12345678901234567890.0)");
check_expr_error("Syntax error in call to DTOI: expected expr#", "DTOI()");
check_expr_error("Syntax error in call to DTOI: expected expr#", "DTOI(3)");
check_expr_error("Syntax error in call to DTOI: expected expr#", "DTOI(3.0, 4)");
}
#[test]
fn test_itod() {
check_expr_ok(0.0, "ITOD(0)");
check_expr_ok(10.0, "ITOD(10)");
check_expr_ok(-10.0, "ITOD(-10)");
check_expr_ok(std::i32::MAX as f64, &format!("ITOD({})", std::i32::MAX));
check_expr_ok(std::i32::MIN as f64, &format!("ITOD({} - 1)", std::i32::MIN + 1));
check_expr_error("Syntax error in call to ITOD: expected expr%", "ITOD()");
check_expr_error("Syntax error in call to ITOD: expected expr%", "ITOD(3.0)");
check_expr_error("Syntax error in call to ITOD: expected expr%", "ITOD(3, 4)");
}
#[test]
fn test_randomize_and_rnd() {
check_expr_ok(false, "RND(1) = RND(1)");
check_expr_ok(false, "RND(1) = RND(10)");
check_expr_ok(true, "RND(0) = RND(0)");
let mut t = Tester::default();
t.run("RANDOMIZE 10").check();
t.run("result = RND(1)").expect_var("result", 0.7097578208683426).check();
t.run("result = RND(1)").expect_var("result", 0.2205558922655312).check();
t.run("result = RND(0)").expect_var("result", 0.2205558922655312).check();
t.run("result = RND(1)").expect_var("result", 0.8273883964464507).check();
check_expr_error("Syntax error in call to RND: expected n%", "RND(3.0)");
check_expr_error("Syntax error in call to RND: expected n%", "RND(1, 7)");
check_expr_error("Syntax error in call to RND: n% cannot be negative", "RND(-1)");
check_stmt_err("Random seed must be an integer", "RANDOMIZE 3.0");
check_stmt_err("RANDOMIZE takes zero or one argument", "RANDOMIZE ,");
}
}