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
use std::cell::RefCell;

use neure::neure;
use neure::regex;
use neure::CharsCtx;
use neure::MatchPolicy;
use neure::SpanStore;
use neure::SpanStorer;

use super::{ConstrctInfo, OptParser};
use crate::opt::Index;
use crate::Error;
use crate::Str;

/// Parse the option string with given prefixes, return an [`ConstrctInfo`].
///
/// The struct of the option string are:
///
/// ```!
/// [--option][=][type][!*][@index]
///      |     |    |   |   |
///      |     |    |   |   |
///      |     |    |   |   |
///      |     |    |   |   The index part of option. Here are all the possible string:
///      |     |    |   |   @0 means first position
///      |     |    |   |   @-0 means last position
///      |     |    |   |   @[1, 2, 3] means the position 1, 2 and 3
///      |     |    |   |   @-[1, 2] means except the position 1, 2
///      |     |    |   |   @>2 means position that bigger than 2
///      |     |    |   |   @<3 means position less than 3
///      |     |    |   |   @* means all the position
///      |     |    |   |
///      |     |    |   Indicate the option wether is force required(!) or not(*).
///      |     |    |
///      |     |    |
///      |     |    |
///      |     |    The type name of option.
///      |     |    
///      |     The delimiter of option name and type.
///      |
///      The option name part, it must be provide by user.
/// ```
///
/// # Example
///
/// ```rust
/// # use aopt::prelude::*;
/// # use aopt::astr;
/// # use aopt::Error;
/// #
/// # fn main() -> Result<(), Error> {
///     let parser = StrParser::default();
///     let ret = parser.parse_opt("--aopt=t!".into())?;
///
///     assert_eq!(ret.name() , Some(&astr("--aopt")));
///     assert_eq!(ret.ctor(), Some(&astr("t")));
///     assert_eq!(ret.force(), Some(true));
///     assert_eq!(ret.index(), None);
///
///     let ret = parser.parse_opt("bopt=t@[1,2,3]".into())?;
///
///     assert_eq!(ret.name(), Some(&astr("bopt")));
///     assert_eq!(ret.ctor(), Some(&astr("t")));
///     assert_eq!(ret.force(), None);
///     assert_eq!(ret.index(), Some(&Index::list(vec![1, 2, 3])));
///
/// #   Ok(())
/// # }
/// ```
///
/// For more examples, please reference test case [`test_option_str_parser`](../../src/aopt/set/parser.rs.html#542).
///
#[derive(Debug, Default)]
pub struct StrParser;

thread_local! {
    static STR_PARSER: RefCell<SpanStorer> = RefCell::new(SpanStorer::new(KEY_TOTAL));
}

impl StrParser {
    pub fn new() -> Self {
        Self {}
    }

    pub fn parse_ctx(storer: &mut SpanStorer, str: &str) -> Result<(), neure::err::Error> {
        let start = neure::start();
        let end = neure::end();
        let name = neure!([^'=' '!' '*' '@' ';' ':']+);
        let semi = neure!(';');
        let equal = neure!('=');
        let ty = neure!([a-z A-Z]+);
        let optional = neure!(['!' '*']);
        let at = neure!('@');
        let index = neure!([^ '@' ':']+);
        let colon = neure!(':');
        let usage = neure!(.+);
        let space = neure!(*);
        let parser = |storer: &mut SpanStorer, str| -> Result<(), neure::err::Error> {
            let mut ctx = CharsCtx::new(str);

            ctx.try_mat(&start)?;
            if ctx.cap(KEY_NAME, storer, &name) {
                // name
                while ctx.mat(&semi) {
                    ctx.cap(KEY_ALIAS, storer, &name);
                }
            }
            if ctx.mat(&equal) {
                // = type
                ctx.try_cap(KEY_CTOR, storer, &ty)?;
            }
            ctx.cap(KEY_OPTIONAL, storer, &optional); // ! or *
            if ctx.mat(&at) {
                // @index
                ctx.try_cap(KEY_INDEX, storer, &index)?;
            }
            if ctx.mat(&colon) {
                ctx.mat(&space);
                ctx.try_cap(KEY_HELP, storer, &usage)?;
            }
            ctx.try_mat(&end)?;
            Ok(())
        };

        parser(storer, str)
    }

    pub fn parse_creator_string(&self, pattern: Str) -> Result<ConstrctInfo, Error> {
        let pattern_clone = pattern.clone();
        let pattern = pattern.as_str();

        STR_PARSER
            .try_with(|storer| {
                if Self::parse_ctx(storer.borrow_mut().reset(), pattern).is_ok() {
                    let mut force = None;
                    let mut idx = None;
                    let mut alias = None;
                    let storer = storer.borrow();
                    let name = storer.substr(pattern, KEY_NAME, 0).ok();
                    let help = storer.substr(pattern, KEY_HELP, 0).ok();
                    let ctor = storer.substr(pattern, KEY_CTOR, 0).ok();

                    if let Ok(opt) = storer.substr(pattern, KEY_OPTIONAL, 0) {
                        match opt {
                            "!" => {
                                force = Some(true);
                            }
                            "*" => {
                                force = Some(false);
                            }
                            _ => {
                                unreachable!(
                                    "Oops ?!! Regex make sure option string correctly: {}",
                                    &pattern
                                )
                            }
                        }
                    }
                    if let Ok(vals) = storer.substrs(pattern, KEY_ALIAS) {
                        alias = Some(
                            vals.filter(|v| !v.trim().is_empty())
                                .map(|v| Str::from(v.trim()))
                                .collect(),
                        );
                    }
                    if let Ok(index) = storer.substr(pattern, KEY_INDEX, 0) {
                        idx = Some(Index::parse(index)?);
                    }
                    Ok(ConstrctInfo::default()
                        .with_force(force)
                        .with_index(idx)
                        .with_pat(pattern_clone)
                        .with_name(name.map(|v| Str::from(v.trim())))
                        .with_help(help.map(|v| Str::from(v.trim())))
                        .with_ctor(ctor.map(|v| Str::from(v.trim())))
                        .with_alias(alias))
                } else {
                    Err(Error::invalid_create_str(
                        pattern_clone.as_str(),
                        "option create string parsing failed",
                    ))
                }
            })
            .map_err(|e| {
                Error::local_access("can not access str parser regex").cause_by(e.into())
            })?
    }
}

const KEY_NAME: usize = 0;
const KEY_ALIAS: usize = 1;
const KEY_CTOR: usize = 2;
const KEY_OPTIONAL: usize = 3;
const KEY_INDEX: usize = 4;
const KEY_HELP: usize = 5;
const KEY_TOTAL: usize = KEY_HELP + 1;

impl OptParser for StrParser {
    type Output = ConstrctInfo;

    type Error = Error;

    fn parse_opt(&self, pattern: Str) -> Result<Self::Output, Self::Error> {
        if pattern.trim().is_empty() {
            Ok(Self::Output::default())
        } else {
            self.parse_creator_string(pattern)
        }
    }
}

#[cfg(test)]
mod test {

    use crate::astr;
    use crate::prelude::*;

    #[test]
    fn test_str_parser() {
        let options = [
            "-b",
            "--bool",
            "bool",
            "-b;--bool",
            "-?;-h;--help",
            "--bool;-b",
            "b;bool",
            "-b;bool",
            "-/b;--/bool",
            "-/b;bool",
            "-b=i",
            "--bool=u",
            "bool=s",
            "-b;--bool=b",
            "-?;-h;--help=p",
            "--bool;-b=c",
            "b;bool=m",
            "-b;bool=f",
            "-/b;--/bool=i",
            "-/b;bool=a",
            "",
        ];
        let options_test = [
            (Some(astr("-b")), None, None),
            (Some(astr("--bool")), None, None),
            (Some(astr("bool")), None, None),
            (Some(astr("-b")), Some(vec![astr("--bool")]), None),
            (
                Some(astr("-?")),
                Some(vec![astr("-h"), astr("--help")]),
                None,
            ),
            (Some(astr("--bool")), Some(vec![astr("-b")]), None),
            (Some(astr("b")), Some(vec![astr("bool")]), None),
            (Some(astr("-b")), Some(vec![astr("bool")]), None),
            (Some(astr("-/b")), Some(vec![astr("--/bool")]), None),
            (Some(astr("-/b")), Some(vec![astr("bool")]), None),
            (Some(astr("-b")), None, Some(astr("i"))),
            (Some(astr("--bool")), None, Some(astr("u"))),
            (Some(astr("bool")), None, Some(astr("s"))),
            (
                Some(astr("-b")),
                Some(vec![astr("--bool")]),
                Some(astr("b")),
            ),
            (
                Some(astr("-?")),
                Some(vec![astr("-h"), astr("--help")]),
                Some(astr("p")),
            ),
            (
                Some(astr("--bool")),
                Some(vec![astr("-b")]),
                Some(astr("c")),
            ),
            (Some(astr("b")), Some(vec![astr("bool")]), Some(astr("m"))),
            (Some(astr("-b")), Some(vec![astr("bool")]), Some(astr("f"))),
            (
                Some(astr("-/b")),
                Some(vec![astr("--/bool")]),
                Some(astr("i")),
            ),
            (Some(astr("-/b")), Some(vec![astr("bool")]), Some(astr("a"))),
            (None, None, None),
        ];
        let helps = [": This is an option help message", ""];
        let helps_test = [Some(astr("This is an option help message")), None];
        let forces = ["!", "*", ""];
        let forces_test = [Some(true), Some(false), None];
        let positions = [
            "@1",
            "@68",
            "@-6",
            "@+42",
            "@1..5",
            "@..8",
            "@2..",
            "@[1,3,5]",
            "@+[2,3,4]",
            "@-[3,56]",
            "@*",
            "",
        ];
        let positions_test = [
            Some(Index::forward(1)),
            Some(Index::forward(68)),
            Some(Index::backward(6)),
            Some(Index::forward(42)),
            Some(Index::range(Some(1), Some(5))),
            Some(Index::range(None, Some(8))),
            Some(Index::range(Some(2), None)),
            Some(Index::list(vec![1, 3, 5])),
            Some(Index::list(vec![2, 3, 4])),
            Some(Index::except(vec![3, 56])),
            Some(Index::anywhere()),
            None,
        ];
        let parser = StrParser::default();

        for (option, option_test) in options.iter().zip(options_test.iter()) {
            for (help, help_test) in helps.iter().zip(helps_test.iter()) {
                for (force, force_test) in forces.iter().zip(forces_test.iter()) {
                    for (position, position_test) in positions.iter().zip(positions_test.iter()) {
                        let creator = astr(format!("{}{}{}{}", option, force, position, help));

                        println!("\"{}\",", creator);
                        if let Ok(cap) = parser.parse_opt(creator) {
                            assert_eq!(option_test.0.as_ref(), cap.name());
                            assert_eq!(option_test.1.as_ref(), cap.alias());
                            assert_eq!(help_test.as_ref(), cap.help());
                            assert_eq!(force_test, &cap.force());
                            assert_eq!(position_test.as_ref(), cap.index());
                            assert_eq!(option_test.2.as_ref(), cap.ctor());
                        } else {
                            assert!(
                                option_test.0.is_none(),
                                "{}{}{}{}",
                                option,
                                force,
                                position,
                                help
                            );
                            assert!(option_test.1.is_none());
                        }
                    }
                }
            }
        }
    }
}