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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
use lazy_static::lazy_static;
use regex::Regex;
use std::{iter::Peekable, str::CharIndices};

use crate::Error;

/// Iterates over the individual arguments in a command accounting for quoted arguments.
pub struct ArgumentTraverser<'cmd> {
    command: &'cmd str,
    chars: Peekable<CharIndices<'cmd>>,
    anchor: usize,
    index: usize,
}

impl<'cmd> ArgumentTraverser<'cmd> {
    /// Creates a traverser over the given command, stripping off the initial '/' if it exists.
    pub fn new(command: &'cmd str) -> Self {
        let mut traverser = ArgumentTraverser {
            command,
            chars: command.char_indices().peekable(),
            anchor: 0,
            index: 0,
        };
        traverser.skip_leading_spaces();
        traverser
    }

    /// Returns the remaining portion of the string being traversed, including the argument which
    /// was last read.
    pub fn gobble_remaining(&mut self) -> &'cmd str {
        // Note that it's important that we only modify the index here. This function should not
        // modify the anchor.
        self.index = self.command.len();
        &self.command[self.anchor ..]
    }

    /// Returns the remaining portion of the string being traversed from the current anchor
    /// position to the end of the string.
    pub fn gobble_remaining_truncated(&self, truncate_to: usize) -> &'cmd str {
        let mut end = self.anchor;
        let mut spanned_chars = 0;
        let mut chars = self.command[self.anchor ..].chars();
        while spanned_chars < truncate_to {
            match chars.next() {
                Some(ch) => {
                    end += ch.len_utf8();
                    spanned_chars += 1;
                }
                None => break,
            }
        }

        &self.command[self.anchor .. end]
    }

    /// Returns whether or not this traverser has more arguments. If this function returns true, then
    /// `next` will not return `None`.
    pub fn has_next(&self) -> bool {
        self.index < self.command.len()
    }

    /// Returns the next argument in the string being traversed, or `None` if no arguments remain.
    /// This function will not strip strings of any enclosing quotes, and will not resolve escape
    /// sequences.
    pub fn next(&mut self) -> Option<&'cmd str> {
        if self.index >= self.command.len() {
            return None;
        }

        self.skip_leading_spaces();

        self.anchor = self.index;

        // Single or double quotes
        let mut quote_type: char = '\0';
        // Whether we're in quotes and should ignore spaces
        let mut in_quotes = false;
        // Used for escaping quotes with the '\' character
        let mut ignore_quote = false;

        self.index = loop {
            if !in_quotes {
                match self.chars.peek().copied() {
                    Some((index, ' ')) => break index,
                    _ => {}
                }
            }

            let ch = match self.chars.next() {
                Some((_, ch)) => ch,
                None => break self.command.len(),
            };

            // Manage strings
            if (ch == '\'' || ch == '\"') && !ignore_quote {
                if in_quotes {
                    if ch == quote_type {
                        in_quotes = false;
                    }
                } else {
                    quote_type = ch;
                    in_quotes = true;
                }
            }

            // Unset the ignore quote variable
            if ignore_quote {
                ignore_quote = false;
            }

            // Set the ignore quote variable if the escape character is present
            if ch == '\\' {
                ignore_quote = true;
            }
        };

        Some(&self.command[self.anchor .. self.index])
    }

    fn skip_leading_spaces(&mut self) {
        while matches!(self.chars.peek().copied(), Some((_, ' '))) {
            self.index += 1;
            self.chars.next();
        }
    }

    #[doc(hidden)]
    #[inline]
    pub fn __anchor(&self) -> usize {
        self.anchor
    }
}

/// Trait for matching and converting string arguments to concrete types. Any type which implements this
/// trait can be used as a node type in a command module.
pub trait FromArgument<'a, C>: Sized {
    /// Returns whether or not the given argument matches the format of `Self`. Returning true does
    /// not imply that [`from_arg`](crate::arg::FromArgument::from_arg) will succeed, but it does
    /// imply that the argument could succeed given the correct context. In other words, this function
    /// should return true for any input that is in the set of all possible string representations
    /// of `Self` given all possible contexts. If `Self` is represented by multiple arguments, then
    /// this function should return true if the first of those arguments is valid.
    fn matches(arg: &str) -> bool;

    /// This function follows similar rules to [`matches`](crate::arg::FromArgument::matches), however
    /// it is not guaranteed that a full argument will be given to this function. This test is primarily
    /// used in suggestion generation while the user is part-way through typing an argument, and hence
    /// should return true whenever [`matches`](crate::arg::FromArgument::matches) returns true, and
    /// should also return true for every truncation of every input for which
    /// [`matches`](crate::arg::FromArgument::matches) returns true.
    fn partial_matches(partial_arg: &str) -> bool {
        Self::matches(partial_arg)
    }

    /// Parses the given argument given a context. This function should only fail if it is impossible
    /// to construct a valid `Self` from the given string, traverser, and context. Any logical checks
    /// should be performed in execution blocks.
    ///
    /// Note that it is not recommended to grab additional arguments from the given traverser. If the
    /// traverser is advanced, then suggestion generation will stop after this argument is visited.
    fn from_arg(arg: &'a str, args: &mut ArgumentTraverser<'a>, context: &C)
        -> Result<Self, Error>;
}

/// A wrapper around arguments which could be interpreted as the user asking for help with a
/// command. This wrapper will match on `help`, and `h` prefixed by zero, one, or two hyphens.
pub struct Help<'a> {
    /// The exact string the user typed.
    pub verbatim: &'a str,
}

impl<'a> Help<'a> {
    /// Returns the singleton `"-help"`.
    #[inline]
    pub fn suggestions() -> impl IntoIterator<Item = &'static str> {
        Some("-help")
    }
}

impl<'a, C> FromArgument<'a, C> for Help<'a> {
    fn matches(arg: &str) -> bool {
        matches!(arg, "help" | "-help" | "--help" | "-h" | "--h")
    }

    fn partial_matches(partial_arg: &str) -> bool {
        match partial_arg.len() {
            0 => true,
            1 => partial_arg == "-" || partial_arg == "h",
            _ => {
                let stripped = if partial_arg.starts_with("--") {
                    &partial_arg[2 ..]
                } else if partial_arg.starts_with("-") {
                    &partial_arg[1 ..]
                } else {
                    partial_arg
                };
                "help".starts_with(stripped)
            }
        }
    }

    fn from_arg(
        arg: &'a str,
        _args: &mut ArgumentTraverser<'a>,
        _context: &C,
    ) -> Result<Self, Error> {
        Ok(Help { verbatim: arg })
    }
}

macro_rules! impl_from_arg_for_uint {
    ($int:ty) => {
        impl<'a, C> FromArgument<'a, C> for $int {
            fn matches(arg: &str) -> bool {
                arg.chars().all(|ch| ch.is_digit(10))
            }

            fn from_arg(
                arg: &'a str,
                _args: &mut ArgumentTraverser<'a>,
                _ctx: &C,
            ) -> Result<Self, Error> {
                arg.parse::<$int>().map_err(|e| e.to_string())
            }
        }
    };
}

macro_rules! impl_from_arg_for_int {
    ($int:ty) => {
        impl<'a, C> FromArgument<'a, C> for $int {
            fn matches(arg: &str) -> bool {
                let mut chars = arg.chars().peekable();
                match chars.peek() {
                    Some('+' | '-') => {
                        chars.next();
                    }
                    Some(_) => {}
                    None => return true,
                };
                arg.chars().all(|ch| ch.is_digit(10))
            }

            fn from_arg(
                arg: &'a str,
                _args: &mut ArgumentTraverser<'a>,
                _ctx: &C,
            ) -> Result<Self, Error> {
                arg.parse::<$int>().map_err(|e| e.to_string())
            }
        }
    };
}

impl_from_arg_for_uint!(u8);
impl_from_arg_for_uint!(u16);
impl_from_arg_for_uint!(u32);
impl_from_arg_for_uint!(u64);
impl_from_arg_for_uint!(u128);
impl_from_arg_for_uint!(usize);
impl_from_arg_for_int!(i8);
impl_from_arg_for_int!(i16);
impl_from_arg_for_int!(i32);
impl_from_arg_for_int!(i64);
impl_from_arg_for_int!(i128);
impl_from_arg_for_int!(isize);

macro_rules! impl_from_arg_fo_float {
    ($float:ty, $full_regex:literal, $partial_regex:literal) => {
        impl<'a, C> FromArgument<'a, C> for $float {
            fn matches(arg: &str) -> bool {
                lazy_static! {
                    static ref FULL: Regex = Regex::new($full_regex).unwrap();
                }

                FULL.is_match(arg)
            }

            fn partial_matches(partial_arg: &str) -> bool {
                lazy_static! {
                    static ref PARTIAL: Regex = Regex::new($partial_regex).unwrap();
                }

                if partial_arg.is_empty() {
                    return true;
                }

                PARTIAL.is_match(partial_arg)
            }

            fn from_arg(
                arg: &'a str,
                _args: &mut ArgumentTraverser<'a>,
                _ctx: &C,
            ) -> Result<Self, Error> {
                let suffix_index = arg
                    .char_indices()
                    .rev()
                    .find(|&(_, ch)| !ch.is_digit(10) && ch != '.')
                    .map(|(index, _)| index)
                    .unwrap_or(arg.len());

                let trimmed = &arg[.. suffix_index];
                if trimmed.is_empty() {
                    return Err(format!("Invalid float: hanging suffix \"{}\"", arg));
                }

                if trimmed == "." {
                    return Err(format!("Invalid float: hanging point"));
                }

                let first = trimmed.chars().next().unwrap();
                let last = trimmed.chars().last().unwrap();

                if first == '.' {
                    ("0".to_owned() + trimmed)
                        .parse::<$float>()
                        .map_err(|e| e.to_string())
                } else if last == '.' {
                    (trimmed.to_owned() + "0")
                        .parse::<$float>()
                        .map_err(|e| e.to_string())
                } else {
                    trimmed.parse::<$float>().map_err(|e| e.to_string())
                }
            }
        }
    };
}

impl_from_arg_fo_float!(
    f32,
    r"^(\d+\.\d+|\d+\.|\.\d+|\d+)[fF]?$",
    r"^(\d+\.|\.\d*|\d+)[fF]?"
);
impl_from_arg_fo_float!(
    f64,
    r"^(\d+\.\d+|\d+\.|\.\d+|\d+)[dD]?$",
    r"^(\d+\.|\.\d*|\d+)[dD]?"
);

impl<'a, C> FromArgument<'a, C> for String {
    fn matches(_arg: &str) -> bool {
        true
    }

    fn from_arg(arg: &'a str, _args: &mut ArgumentTraverser<'a>, _ctx: &C) -> Result<Self, Error> {
        if arg.len() < 2 {
            Ok(arg.to_owned())
        } else {
            let first = arg.chars().next().unwrap();
            let last = arg.chars().last().unwrap();

            if first == last && (first == '"' || first == '\'') {
                Ok(arg[1 .. arg.len() - 1].to_owned())
            } else {
                Ok(arg.to_owned())
            }
        }
    }
}

impl<'a, C> FromArgument<'a, C> for &'a str {
    fn matches(_arg: &str) -> bool {
        true
    }

    fn from_arg(arg: &'a str, _args: &mut ArgumentTraverser<'a>, _ctx: &C) -> Result<Self, Error> {
        if arg.len() < 2 {
            Ok(arg)
        } else {
            let first = arg.chars().next().unwrap();
            let last = arg.chars().last().unwrap();

            if first == last && (first == '"' || first == '\'') {
                Ok(&arg[1 .. arg.len() - 1])
            } else {
                Ok(arg)
            }
        }
    }
}

impl<'a, C> FromArgument<'a, C> for bool {
    fn matches(arg: &str) -> bool {
        arg == "true" || arg == "false"
    }

    fn partial_matches(partial_arg: &str) -> bool {
        "true".starts_with(partial_arg) || "false".starts_with(partial_arg)
    }

    fn from_arg(arg: &'a str, _args: &mut ArgumentTraverser<'a>, _ctx: &C) -> Result<Self, Error> {
        match arg {
            "true" => Ok(true),
            "false" => Ok(false),
            _ => Err(format!(
                "\"{}\" is not a valid boolean, must be \"true\" or \"false\"",
                arg
            )),
        }
    }
}

impl<'a, C> FromArgument<'a, C> for char {
    fn matches(arg: &str) -> bool {
        arg.chars().count() == 1
    }

    fn partial_matches(partial_arg: &str) -> bool {
        partial_arg.chars().count() <= 1
    }

    fn from_arg(arg: &'a str, _args: &mut ArgumentTraverser<'a>, _ctx: &C) -> Result<Self, Error> {
        if arg.is_empty() {
            Err("Cannot parse an empty argument into a character".to_owned())
        } else {
            let mut chars = arg.chars();
            let ch = chars.next().unwrap();
            match chars.next() {
                Some(_) => Err(format!(
                    "Cannot parse \"{}\" into a character, length is greater than one",
                    arg
                )),
                None => Ok(ch),
            }
        }
    }
}

impl<'a, C, T> FromArgument<'a, C> for Option<T>
where T: FromArgument<'a, C>
{
    fn matches(arg: &str) -> bool {
        T::matches(arg)
    }

    fn partial_matches(partial_arg: &str) -> bool {
        T::partial_matches(partial_arg)
    }

    fn from_arg(
        arg: &'a str,
        args: &mut ArgumentTraverser<'a>,
        context: &C,
    ) -> Result<Self, Error> {
        Ok(Some(T::from_arg(arg, args, context)?))
    }
}

impl<'a, C, T> FromArgument<'a, C> for Box<T>
where T: FromArgument<'a, C>
{
    fn matches(arg: &str) -> bool {
        T::matches(arg)
    }

    fn partial_matches(partial_arg: &str) -> bool {
        T::partial_matches(partial_arg)
    }

    fn from_arg(
        arg: &'a str,
        args: &mut ArgumentTraverser<'a>,
        context: &C,
    ) -> Result<Self, Error> {
        Ok(Box::new(T::from_arg(arg, args, context)?))
    }
}