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
313
314
315
316
317
318
319
320
321
322
//! Contains pre-built predicates for use outside this library for creating command
//! specifications.
//!
//! ## Writing a custom predicate ##
//!
//! ```
//! use gameshell::{types::Type, Evaluate, Evaluator};
//! use gameshell::cmdmat::{Decider, Decision, SVec};
//!
//! // This is the general decider type to use
//! pub type SomeDec = Option<&'static Decider<Type, String>>;
//!
//! // This is your decider that you will use when registering a handler
//! pub const I32_NUMBER_ABOVE_123: SomeDec = Some(&Decider {
//!     description: "<i32-over-123>",
//!     decider: i32_number_above_123,
//! });
//!
//! fn i32_number_above_123(input: &[&str], out: &mut SVec<Type>) -> Decision<String> {
//!     // Check if input is non-empty
//!     if input.is_empty() {
//!         return Decision::Deny("No input received".into());
//!     }
//!
//!     // Ensure string contains no whitespaces
//!     for i in input[0].chars() {
//!         if i.is_whitespace() {
//!             return Decision::Deny(input[0].into());
//!         }
//!     }
//!
//!     // Parse string to i32
//!     let number = input[0].parse::<i32>();
//!     let number = match number {
//!         Ok(number) => number,
//!         Err(err) => return Decision::Deny(format!["{:?}", err]),
//!     };
//!
//!     // Ensure number is >123
//!     if !(number > 123) {
//!         return Decision::Deny("Number is not >123".into());
//!     }
//!
//!     // All checks passed, push the value to the output
//!     out.push(Type::I32(number));
//!
//!     // Tell the GameShell machinery that we have consumed 1 argument
//!     Decision::Accept(1)
//! }
//!
//! fn handler(_: &mut (), args: &[Type]) -> Result<String, String> {
//!     if let [Type::I32(number)] = args {
//!         println!("The number {} is definitely greater than 123", number);
//!         Ok("We can return whatever we want to here".into())
//!     } else {
//!         panic!("Wrong arguments");
//!     }
//! }
//!
//! let mut eval = Evaluator::new(());
//! eval.register((&[("my-command", I32_NUMBER_ABOVE_123)], handler));
//! eval.interpret_single("my-command 124").unwrap().unwrap();
//! assert_eq!(Err("Expected <i32-over-123>. Decider: Number is not >123".into()), eval.interpret_single("my-command -9").unwrap());
//! ```
use crate::types::Type;
use cmdmat::{Decider, Decision, SVec};

// ---

/// Decider type alias
pub type SomeDec = Option<&'static Decider<Type, String>>;

// Please keep this list sorted

/// Accepts a single string which does not contain whitespace
pub const ANY_ATOM: SomeDec = Some(&Decider {
    description: "<atom>",
    decider: any_atom_function,
});
/// Accepts any base64 string
pub const ANY_BASE64: SomeDec = Some(&Decider {
    description: "<base64>",
    decider: any_base64_function,
});
/// Accepts a single boolean
pub const ANY_BOOL: SomeDec = Some(&Decider {
    description: "<true/false>",
    decider: any_bool_function,
});
/// Accepts a single f32
pub const ANY_F32: SomeDec = Some(&Decider {
    description: "<f32>",
    decider: any_f32_function,
});
/// Accepts a single i32
pub const ANY_I32: SomeDec = Some(&Decider {
    description: "<i32>",
    decider: any_i32_function,
});
/// Accepts a single string
pub const ANY_STRING: SomeDec = Some(&Decider {
    description: "<string>",
    decider: any_string_function,
});
/// Accepts a single u8
pub const ANY_U8: SomeDec = Some(&Decider {
    description: "<u8>",
    decider: any_u8_function,
});
/// Accepts a single usize
pub const ANY_USIZE: SomeDec = Some(&Decider {
    description: "<usize>",
    decider: any_usize_function,
});
/// Ignores all arguments
pub const IGNORE_ALL: SomeDec = Some(&Decider {
    description: "<anything> ...",
    decider: ignore_all_function,
});
/// Accepts 1 or more i32s
pub const MANY_I32: SomeDec = Some(&Decider {
    description: "<i32> ...",
    decider: many_i32_function,
});
/// Accepts 1 or more strings
pub const MANY_STRING: SomeDec = Some(&Decider {
    description: "<string> ...",
    decider: many_string_function,
});
/// Accepts a positive f32
pub const POSITIVE_F32: SomeDec = Some(&Decider {
    description: "<f32>=0>",
    decider: positive_f32_function,
});
/// Accepts two strings
pub const TWO_STRINGS: SomeDec = Some(&Decider {
    description: "<string> <string>",
    decider: two_string_function,
});

// ---

fn any_atom_function(input: &[&str], out: &mut SVec<Type>) -> Decision<String> {
    aslen(input, 1)?;
    for i in input[0].chars() {
        if i.is_whitespace() {
            return Decision::Deny(input[0].into());
        }
    }
    out.push(Type::Atom(input[0].to_string()));
    Decision::Accept(1)
}

fn any_base64_function(input: &[&str], out: &mut SVec<Type>) -> Decision<String> {
    aslen(input, 1)?;
    match base64::decode(input[0]) {
        Ok(base64) => {
            out.push(Type::Raw(base64));
            Decision::Accept(1)
        }
        Err(err) => Decision::Deny(format!["{}", err]),
    }
}

fn any_bool_function(input: &[&str], out: &mut SVec<Type>) -> Decision<String> {
    aslen(input, 1)?;
    match input[0].parse::<bool>().ok().map(Type::Bool) {
        Some(num) => {
            out.push(num);
        }
        None => {
            return Decision::Deny("got string: ".to_string() + input[0]);
        }
    }
    Decision::Accept(1)
}

fn any_f32_function(input: &[&str], out: &mut SVec<Type>) -> Decision<String> {
    aslen(input, 1)?;
    match input[0].parse::<f32>().ok().map(Type::F32) {
        Some(num) => {
            out.push(num);
        }
        None => {
            return Decision::Deny("got string: ".to_string() + input[0]);
        }
    }
    Decision::Accept(1)
}

fn any_i32_function(input: &[&str], out: &mut SVec<Type>) -> Decision<String> {
    aslen(input, 1)?;
    match input[0].parse::<i32>().ok().map(Type::I32) {
        Some(num) => {
            out.push(num);
        }
        None => {
            return Decision::Deny("got string: ".to_string() + input[0]);
        }
    }
    Decision::Accept(1)
}

fn any_string_function(input: &[&str], out: &mut SVec<Type>) -> Decision<String> {
    aslen(input, 1)?;
    out.push(Type::String(input[0].to_string()));
    Decision::Accept(1)
}

fn any_u8_function(input: &[&str], out: &mut SVec<Type>) -> Decision<String> {
    aslen(input, 1)?;
    match input[0].parse::<u8>().ok().map(Type::U8) {
        Some(num) => {
            out.push(num);
        }
        None => {
            return Decision::Deny("got string: ".to_string() + input[0]);
        }
    }
    Decision::Accept(1)
}

fn any_usize_function(input: &[&str], out: &mut SVec<Type>) -> Decision<String> {
    aslen(input, 1)?;
    match input[0].parse::<usize>().ok().map(Type::Usize) {
        Some(num) => {
            out.push(num);
        }
        None => {
            return Decision::Deny("got string: ".to_string() + input[0]);
        }
    }
    Decision::Accept(1)
}

fn ignore_all_function(input: &[&str], _: &mut SVec<Type>) -> Decision<String> {
    Decision::Accept(input.len())
}

fn many_i32_function(input: &[&str], out: &mut SVec<Type>) -> Decision<String> {
    let mut cnt = 0;
    for i in input.iter() {
        if let Some(num) = i.parse::<i32>().ok().map(Type::I32) {
            aslen(input, cnt + 1)?;
            out.push(num);
            cnt += 1;
        } else {
            break;
        }
    }
    Decision::Accept(cnt)
}

fn many_string_function(input: &[&str], out: &mut SVec<Type>) -> Decision<String> {
    aslen(input, input.len())?;
    let mut cnt = 0;
    for (idx, i) in input.iter().enumerate() {
        out.push(Type::String((*i).into()));
        cnt = idx + 1;
    }
    Decision::Accept(cnt)
}

fn positive_f32_function(input: &[&str], out: &mut SVec<Type>) -> Decision<String> {
    aslen(input, 1)?;
    match input[0].parse::<f32>().ok().map(Type::F32) {
        Some(Type::F32(val)) if val >= 0.0f32 => {
            out.push(Type::F32(val));
        }
        _ => {
            return Decision::Deny("got string: ".to_string() + input[0]);
        }
    }
    Decision::Accept(1)
}

fn two_string_function(input: &[&str], out: &mut SVec<Type>) -> Decision<String> {
    if input.len() == 1 {
        return Decision::Deny("expected 1 more string".into());
    }
    aslen(input, 2)?;
    out.push(Type::String(input[0].to_string()));
    out.push(Type::String(input[1].to_string()));
    Decision::Accept(2)
}

// ---

fn aslen(input: &[&str], input_l: usize) -> Result<(), String> {
    if input.len() < input_l {
        Err(format![
            "Too few elements: {:?}, length: {}, expected: {}",
            input,
            input.len(),
            input_l
        ])
    } else {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[quickcheck_macros::quickcheck]
    fn basic_quickcheck(input: Vec<String>) {
        let input = &input.iter().map(|string| &string[..]).collect::<Vec<_>>()[..];
        let out = &mut SVec::new();

        any_atom_function(input, out);
        any_base64_function(input, out);
        any_bool_function(input, out);
        any_f32_function(input, out);
        any_string_function(input, out);
        any_u8_function(input, out);
        ignore_all_function(input, out);
        many_string_function(input, out);
        positive_f32_function(input, out);
        two_string_function(input, out);
    }
}