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
use crate::{Arguments, CommandParserConfig};

/// Indicator that a command was used.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Command<'a> {
    /// A lazy iterator of command arguments. Refer to its documentation on
    /// how to use it.
    pub arguments: Arguments<'a>,
    /// The name of the command that was called.
    pub name: &'a str,
    /// The prefix used to call the command.
    pub prefix: &'a str,
}

/// A struct to parse prefixes, commands, and arguments out of messages.
///
/// While parsing, the parser takes into account the configuration that it was
/// configured with. This configuration is mutable during runtime via the
/// [`Parser::config_mut`] method.
///
/// After parsing, you're given an optional [`Command`]: a struct representing a
/// command and its relevant information. Refer to its documentation for more
/// information.
///
/// # Examples
///
/// Using a parser configured with the commands `"echo"` and `"ping"` and the
/// prefix `"!"`, parse the message "!echo foo bar baz":
///
/// ```rust
/// use twilight_command_parser::{Command, CommandParserConfig, Parser};
///
/// let mut config = CommandParserConfig::new();
/// config.add_command("echo", false);
/// config.add_command("ping", false);
/// config.add_prefix("!");
///
/// let parser = Parser::new(config);
///
/// if let Some(command) = parser.parse("!echo foo bar baz") {
///     match command {
///         Command { name: "echo", arguments, .. } => {
///             let content = arguments.as_str();
///
///             println!("Got a request to echo `{}`", content);
///         },
///         Command { name: "ping", .. } => {
///             println!("Got a ping request");
///         },
///         _ => {},
///     }
/// }
/// ```
///
/// [`Command`]: struct.Command.html
/// [`Parser::config_mut`]: #method.config_mut
#[derive(Clone, Debug)]
pub struct Parser<'a> {
    config: CommandParserConfig<'a>,
}

impl<'a> Parser<'a> {
    /// Creates a new parser from a given configuration.
    pub fn new(config: impl Into<CommandParserConfig<'a>>) -> Self {
        Self {
            config: config.into(),
        }
    }

    /// Returns an immutable reference to the configuration.
    pub fn config(&self) -> &CommandParserConfig<'a> {
        &self.config
    }

    /// Returns a mutable reference to the configuration.
    pub fn config_mut(&mut self) -> &mut CommandParserConfig<'a> {
        &mut self.config
    }

    /// Parses a command out of a buffer.
    ///
    /// If a configured prefix and command are in the buffer, then some
    /// [`Command`] is returned with them and a lazy iterator of the
    /// argument list.
    ///
    /// If a matching prefix or command weren't found, then `None` is returned.
    ///
    /// Refer to the struct-level documentation on how to use this.
    ///
    /// [`Command`]: struct.Command.html
    pub fn parse(&'a self, buf: &'a str) -> Option<Command<'a>> {
        let prefix = self.find_prefix(buf)?;
        self.parse_with_prefix(prefix, buf)
    }

    /// Parse a command out of a buffer with a specific prefix.
    ///
    /// Instead of using the list of set prefixes, give a specific prefix
    /// to parse the message, this can be used to have a kind of dynamic
    /// prefixes.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use twilight_command_parser::{Command, CommandParserConfig, Parser};
    /// # fn example() -> Option<()> {
    /// let mut config = CommandParserConfig::new();
    /// config.add_prefix("!");
    /// config.add_command("echo", false);
    ///
    /// let parser = Parser::new(config);
    ///
    /// let command = parser.parse_with_prefix("=", "=echo foo")?;
    ///
    /// assert_eq!("=", command.prefix);
    /// assert_eq!("echo", command.name);
    /// # Some(())
    /// # }
    /// ```
    ///
    /// [`Command`]: struct.Command.html
    pub fn parse_with_prefix(&'a self, prefix: &'a str, buf: &'a str) -> Option<Command<'a>> {
        if !buf.starts_with(prefix) {
            return None;
        }

        let mut idx = prefix.len();
        let command_buf = buf.get(idx..)?;
        let command = self.find_command(command_buf)?;

        idx += command.len();

        // Advance from the amount of whitespace that was between the prefix and
        // the command name.
        idx += command_buf.len() - command_buf.trim_start().len();

        Some(Command {
            arguments: Arguments::new(buf.get(idx..)?),
            name: command,
            prefix,
        })
    }

    fn find_command(&'a self, buf: &'a str) -> Option<&'a str> {
        let buf = buf.split_whitespace().next()?;
        self.config.commands.iter().find_map(|command| {
            if command == buf {
                Some(command.as_ref())
            } else {
                None
            }
        })
    }

    fn find_prefix(&self, buf: &str) -> Option<&str> {
        self.config.prefixes.iter().find_map(|prefix| {
            if buf.starts_with(prefix.as_ref()) {
                Some(prefix.as_ref())
            } else {
                None
            }
        })
    }
}

impl<'a, T: Into<CommandParserConfig<'a>>> From<T> for Parser<'a> {
    fn from(config: T) -> Self {
        Self::new(config)
    }
}

#[cfg(test)]
mod tests {
    use crate::{Command, CommandParserConfig, Parser};
    use static_assertions::{assert_fields, assert_impl_all};
    use std::fmt::Debug;

    assert_fields!(Command<'_>: arguments, name, prefix);
    assert_impl_all!(Command<'_>: Clone, Debug, Send, Sync);
    assert_impl_all!(Parser<'_>: Clone, Debug, Send, Sync);

    fn simple_config() -> Parser<'static> {
        let mut config = CommandParserConfig::new();
        config.add_prefix("!");
        config.add_command("echo", false);

        Parser::new(config)
    }

    #[test]
    fn double_command() {
        let parser = simple_config();
        if parser.parse("!echoecho").is_some() {
            panic!("Double match!")
        }
    }

    #[test]
    fn test_case_sensitive() {
        let mut parser = simple_config();
        let message_ascii = "!EcHo this is case insensitive";
        let message_unicode = "!wEiSS is white";
        let message_unicode_2 = "!\u{3b4} is delta";

        // Case insensitive - ASCII
        let command = parser
            .parse(message_ascii)
            .expect("Parser is case sensitive");
        assert_eq!(
            "echo", command.name,
            "Command name should have the same case as in the CommandParserConfig"
        );

        // Case insensitive - Unicode
        parser.config.add_command("wei\u{df}", false);
        let command = parser
            .parse(message_unicode)
            .expect("Parser is case sensitive");
        assert_eq!(
            "wei\u{df}", command.name,
            "Command name should have the same case as in the CommandParserConfig"
        );

        parser.config.add_command("\u{394}", false);
        let command = parser
            .parse(message_unicode_2)
            .expect("Parser is case sensitive");
        assert_eq!(
            "\u{394}", command.name,
            "Command name should have the same case as in the CommandParserConfig"
        );

        // Case sensitive
        let config = parser.config_mut();
        config.commands.clear();
        config.add_command("echo", true);
        config.add_command("wei\u{df}", true);
        config.add_command("\u{394}", true);
        assert!(
            parser.parse(message_ascii).is_none(),
            "Parser is not case sensitive"
        );
        assert!(
            parser.parse(message_unicode).is_none(),
            "Parser is not case sensitive"
        );
        assert!(
            parser.parse(message_unicode_2).is_none(),
            "Parser is not case sensitive"
        );
    }

    #[test]
    fn test_simple_config_no_prefix() {
        let mut parser = simple_config();
        parser.config_mut().remove_prefix("!");
    }

    #[test]
    fn test_simple_config_parser() {
        let parser = simple_config();

        match parser.parse("!echo what a test") {
            Some(Command { name, prefix, .. }) => {
                assert_eq!("echo", name);
                assert_eq!("!", prefix);
            }
            other => panic!("Not command: {:?}", other),
        }
    }

    #[test]
    fn test_unicode_command() {
        let mut parser = simple_config();
        parser.config_mut().add_command("\u{1f44e}", false);

        assert!(parser.parse("!\u{1f44e}").is_some());
    }

    #[test]
    fn test_unicode_prefix() {
        let mut parser = simple_config();
        parser.config_mut().add_prefix("\u{1f44d}"); // thumbs up unicode

        assert!(parser.parse("\u{1f44d}echo foo").is_some());
    }

    #[test]
    fn test_dynamic_prefix() {
        let parser = simple_config();

        let command = parser.parse_with_prefix("=", "=echo foo").unwrap();

        assert_eq!("=", command.prefix);
        assert_eq!("echo", command.name);
    }

    #[test]
    fn test_prefix_mention() {
        let mut config = CommandParserConfig::new();
        config.add_prefix("foo");
        config.add_command("dump", false);
        let parser = Parser::new(config);

        let Command {
            mut arguments,
            name,
            prefix,
        } = parser.parse("foo dump test").unwrap();
        assert_eq!("foo", prefix);
        assert_eq!("dump", name);
        assert_eq!(Some("test"), arguments.next());
        assert!(arguments.next().is_none());
    }
}