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
use std::collections::{HashMap, HashSet};
use crate::command::Command;
use crate::error::ParseError;
use crate::error::ParseError::{EscapeError, NameError, PrefixError};

#[derive(Debug, Copy, Clone)]
enum ParseState {
    Prefix,
    Name,
    Default,
    Argument,
    LongArgument,
    EscapeLongArg,
    Option,
    ParamConnector,
    ParamVal,
    ParamLongVal,
    EscapeLongParamVal,
}

/// Used to parse a [`Command`] from a string.
///
/// # Command Syntax
///
/// For more information about prefixes look at the fields of this struct.
/// In any examples in this documentation `!` will be used as a prefix and `-` will be used as a option prefix.
///
/// A command that this can parse could look like this:
///
/// `!foo arg1 "long arg 2" -opt -opt -key1:val1 -key2:"long val2"`
///
/// A command consists of 4 different parts:
/// - _name_: The name of the command is the first word after the prefix.
/// In the example above that's `foo`.
/// - _arguments_: Arguments are simple strings passed to the command.
/// They are either single words or strings with spaces enclosed by `"`.
/// In the example the two arguments are `arg1` and `long arg 2`.
/// - _options_: Options are a set of words.
/// They are prefixed with the `option_prefix`.
/// The only option in the example is `opt`.
/// - _parameters_: Parameters are key-value pairs.
/// They are prefixed with the `option_prefix` and seperated by `:`.
/// The value part of the pair can be a word or a string enclosed by `"`.
/// In the example above `key1`s value is `val1` and `key2`s value is `long val2`.
///
/// # Escaping
///
/// Since `"` is used to mark the borders of long arguments and values, it's not normally possible
/// to include them in the string of the argument.
///
/// You can escape a long argument or value using \\:
/// - `\"`: produces `"`
/// - `\\`: produces `\`
///
/// # Example
///
/// ```
/// use std::collections::{HashMap, HashSet};
/// use command_parser::{Parser, Command};
///
/// let p = Parser::new('!', '-');
/// let command_string = r##"!foo arg1 "long arg 2" -opt -opt -key1:val1 -key2:"long val2""##;
///
/// let command = Command {
///     prefix: '!',
///     option_prefix: '-',
///     name: "foo".to_string(),
///     arguments: vec!["arg1".to_string(), "long arg 2".to_string()],
///     options: HashSet::from(["opt".to_string()]),
///     parameters: HashMap::from([
///         ("key1".to_string(), "val1".to_string()),
///         ("key2".to_string(), "long val2".to_string())
///     ])
/// };
///
/// assert_eq!(p.parse(command_string).unwrap(), command);
/// ```
#[derive(Debug)]
pub struct Parser {
    /// Prefix of the command.
    ///
    /// `<prefix><name> ...`
    ///
    /// Should not be set to `' '` as most chats trim leading spaces.
    pub prefix: char,
    /// Prefix of options and parameters.
    ///
    /// `... <option_prefix><option> ... <option_prefix><param key>:<param value>`
    ///
    /// Should not be set to `' '` or `'"'` as it may not result in expected outcomes.
    pub option_prefix: char,
}

impl Parser {
    pub fn new(prefix: char, option_prefix: char) -> Parser {
        Parser {
            prefix,
            option_prefix,
        }
    }

    pub fn parse<'a>(&'_ self, raw: &'a str) -> Result<Command, ParseError> {
        let mut name = String::new();
        let mut arguments: Vec<String> = vec![];
        let mut options: HashSet<String> = HashSet::new();
        let mut parameters: HashMap<String, String> = HashMap::new();

        let mut state = ParseState::Prefix;
        let mut buffer = String::new();
        let mut key_buffer = String::new();

        for (cursor, c) in raw.chars().enumerate() {
            match state {
                ParseState::Prefix => {
                    match c {
                        x if x == self.prefix => {
                            state = ParseState::Name;
                        }
                        _ => {return Err(PrefixError(cursor, c))}
                    }
                }
                ParseState::Name => {
                    match c {
                        ' ' => {
                            if cursor == 1 {
                                return Err(NameError(cursor, c));
                            } else {
                                state = ParseState::Default;
                            }
                        }
                        _ => { name.push(c); }
                    }
                }
                ParseState::Argument => {
                    match c {
                        ' ' => {
                            arguments.push(buffer);
                            buffer = String::new();
                            state = ParseState::Default;
                        }
                        _ => {
                            buffer.push(c);
                        }
                    }
                }
                ParseState::LongArgument => {
                    match c {
                        '"' => {
                            arguments.push(buffer);
                            buffer = String::new();
                            state = ParseState::Default;
                        }
                        '\\' => {
                            state = ParseState::EscapeLongArg;
                        }
                        _ => {
                            buffer.push(c);
                        }
                    }
                }
                ParseState::EscapeLongArg => {
                    match c {
                        '"' | '\\' => {
                            state = ParseState::LongArgument;
                            buffer.push(c);
                        }
                        _ => {
                            return Err(EscapeError(cursor, c));
                        }
                    }
                }
                ParseState::Option => {
                    match c {
                        ' ' => {
                            options.insert(buffer);
                            buffer = String::new();
                            state = ParseState::Default;
                        }
                        ':' => {
                            key_buffer = buffer;
                            buffer = String::new();
                            state = ParseState::ParamConnector;
                        }
                        _ => {
                            buffer.push(c);
                        }
                    }
                }
                ParseState::ParamConnector => {
                    match c {
                        '"' => {
                            state = ParseState::ParamLongVal;
                        }
                        ' ' => {
                            parameters.insert(key_buffer, buffer);
                            key_buffer = String::new();
                            buffer = String::new();
                            state = ParseState::Default;
                        }
                        _ => {
                            state = ParseState::ParamVal;
                            buffer.push(c);
                        }
                    }
                }
                ParseState::ParamVal => {
                    match c {
                        ' ' => {
                            parameters.insert(key_buffer, buffer);
                            key_buffer = String::new();
                            buffer = String::new();
                            state = ParseState::Default;
                        }
                        _ => {
                            buffer.push(c);
                        }
                    }
                }
                ParseState::ParamLongVal => {
                    match c {
                        '"' => {
                            parameters.insert(key_buffer, buffer);
                            key_buffer = String::new();
                            buffer = String::new();
                            state = ParseState::Default;
                        }
                        '\\' => {
                            state = ParseState::EscapeLongParamVal;
                        }
                        _ => {
                            buffer.push(c);
                        }
                    }
                }
                ParseState::EscapeLongParamVal => {
                    match c {
                        '"' | '\\' => {
                            state = ParseState::ParamLongVal;
                            buffer.push(c);
                        }
                        _ => {
                            return Err(EscapeError(cursor, c));
                        }
                    }
                }
                ParseState::Default => {
                    match c {
                        ' ' => {}
                        '"' => {state = ParseState::LongArgument;}
                        x if x == self.option_prefix => {
                            state = ParseState::Option;
                        }
                        _ => {
                            state = ParseState::Argument;
                            buffer.push(c);
                        }
                    }
                }
            }
        }

        Ok(Command {
            prefix: self.prefix,
            option_prefix: self.option_prefix,
            name, arguments, options, parameters
        })
    }
}


#[cfg(test)]
pub mod tests {
    use std::time::{Duration, Instant};
    use super::*;

    #[test]
    fn parse_test() {
        let p = Parser::new('!', '-');
        let command_string = r##"!foo arg1 "long arg 2" -opt -opt -key1:val1 -key2:"long val2""##;

        let command = Command {
            prefix: '!',
            option_prefix: '-',
            name: "foo".to_string(),
            arguments: vec!["arg1".to_string(), "long arg 2".to_string()],
            options: HashSet::from(["opt".to_string()]),
            parameters: HashMap::from([
                ("key1".to_string(), "val1".to_string()),
                ("key2".to_string(), "long val2".to_string())
            ])
        };

        assert_eq!(p.parse(command_string).unwrap(), command);
    }

    #[test]
    fn time_test() {
        let p = Parser::new('!', '-');
        let command_string = r##"!foo arg1 "long arg 2" -opt -opt -key1:val1 -key2:"long val2""##;

        let now = Instant::now();

        for _ in 0..100000 {
            let _ = p.parse(command_string);
        }

        println!("{}", now.elapsed().as_micros());

        let p = Parser::new('!', '-');
        let command_string = r##"just a normal sentence"##;

        let now = Instant::now();

        for _ in 0..100000 {
            let _ = p.parse(command_string);
        }

        println!("{}", now.elapsed().as_micros());
    }

}