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
pub(crate) mod action;
pub(crate) mod aopt;
pub(crate) mod config;
pub(crate) mod creator;
pub(crate) mod help;
pub(crate) mod index;
pub(crate) mod info;
pub(crate) mod parser;
#[cfg(feature = "serde")]
pub(crate) mod serialize;
pub(crate) mod style;
pub(crate) mod value;

pub use self::action::Action;
pub use self::aopt::AOpt;
pub use self::config::Config;
pub use self::config::ConfigValue;
pub use self::config::OptConfig;
pub use self::creator::BuiltInCtor;
pub use self::creator::Creator;
pub use self::help::Help;
pub use self::index::Index;
pub use self::info::ConstrctInfo;
pub use self::info::Information;
pub use self::parser::StrParser;
#[cfg(feature = "serde")]
pub use self::serialize::Deserialize;
#[cfg(feature = "serde")]
pub use self::serialize::Serde;
#[cfg(feature = "serde")]
pub use self::serialize::Serialize;
pub use self::style::Style;
pub use self::value::OptValueExt;

use std::any::TypeId;
use std::fmt::Debug;
use std::ops::Deref;
use std::ops::DerefMut;

use crate::value::ValAccessor;
use crate::Error;
use crate::Str;
use crate::Uid;

pub const BOOL_TRUE: &str = "true";

pub const BOOL_FALSE: &str = "false";

/// Cmd represents a sub command flag wrapped the `bool` option, it is force required in default.
///
/// See [`cmd_check`](crate::set::SetChecker::cmd_check) of
/// [`DefaultSetChecker`](crate::parser::DefaultSetChecker) for default checking behavior.
///
/// # Example
///
/// ```rust
/// # use aopt::prelude::*;
/// # use aopt::opt::Cmd;
/// #
/// # fn main() -> Result<(), aopt::Error> {
///     
/// let mut parser = AFwdParser::default();
///
/// // `Cmd` has a default position `@1`.
/// parser.add_opt_i::<Cmd>("list: Set the list sub command")?;
/// parser.parse(ARef::new(Args::from_array(["app", "list"])))?;
///
/// // Get the value by `Infer::Val` type of `bool`.
/// assert_eq!(parser.find_val::<bool>("list")?, &true);
///
/// # Ok(())
/// # }
/// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct Cmd(pub bool);

impl Cmd {
    pub fn new(value: bool) -> Self {
        Self(value)
    }
}

impl Deref for Cmd {
    type Target = bool;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for Cmd {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

/// Pos is a position option wrapper, it is matching based on position.
///
/// See [`pos_check`](crate::set::SetChecker::pos_check) of
/// [`DefaultSetChecker`](crate::parser::DefaultSetChecker) for default checking behavior.
///
/// # Example
///
/// ```rust
/// # use aopt::prelude::*;
/// # use aopt::opt::Pos;
/// #
/// # fn main() -> Result<(), aopt::Error> {
///     
/// let mut parser = AFwdParser::default();
///
/// // Name is not important.
/// parser.add_opt_i::<Pos<String>>("pos_accept_string@1: Set the string value")?;
///
/// parser.parse(ARef::new(Args::from_array(["app", "value"])))?;
///
/// // Get the value by `Infer::Val` type of `String`.
/// assert_eq!(parser.find_val::<String>("pos_accept_string")?, &String::from("value"));
///
/// # Ok(())
/// # }
/// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct Pos<T = bool>(pub T);

impl<T> Pos<T> {
    pub fn new(value: T) -> Self {
        Self(value)
    }
}

impl<T> Deref for Pos<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for Pos<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

/// Main are always matched; it is using for running logical before [`Policy`](crate::parser::Policy) ending.
///
/// See [`post_check`](crate::set::SetChecker::post_check) of
/// [`DefaultSetChecker`](crate::parser::DefaultSetChecker) for default checking behavior.
/// # Example
///
/// ```rust
/// # use aopt::prelude::*;
/// # use aopt::opt::Main;
/// # use std::ops::Deref;
/// #
/// # fn main() -> Result<(), aopt::Error> {
///     
/// let mut parser = AFwdParser::default();
///
/// // `Main` has a default position `@*`.
/// parser.add_opt_i::<Main>("main_function: Call the main function")?
///       // Main do nothing in default, you must change the `Action` if you want save value
///       .set_action(Action::Set)
///       .on(|_: &mut ASet, _: &mut ASer, val: ctx::RawVal|{
///             assert_eq!(val.deref(), &RawVal::from("app"));
///             Ok(Some(String::from("main_function called")))
///       })?;
///
/// parser.parse(ARef::new(Args::from_array(["app", "list"])))?;
///
/// // Get the value of main function returned.
/// assert_eq!(parser.find_val::<String>("main_function")?, &String::from("main_function called"));
///
/// # Ok(())
/// # }
/// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct Main<T = ()>(pub T);

impl<T> Main<T> {
    pub fn new(value: T) -> Self {
        Self(value)
    }
}

impl<T> Deref for Main<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for Main<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

/// Simple option type wrapper, implemented [`Infer`](crate::value::Infer).
/// It works with the types are implemented [`RawValParser`](crate::value::RawValParser).
///
/// # Example
///
/// ```rust
/// # use aopt::Error;
/// # use aopt::value::raw2str;
/// # use aopt::prelude::*;
/// # use std::ops::Deref;
///
/// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
/// pub struct Name(String);
///
/// impl RawValParser for Name {
///     type Error = Error;
///
///     fn parse(arg: Option<&RawVal>, _: &Ctx) -> Result<Self, Self::Error> {
///         Ok(Name(raw2str(arg)?.to_owned()))
///     }
/// }
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut parser = AFwdParser::default();
///
/// // add the option wrap with `MutOpt`
/// parser.add_opt_i::<MutOpt<Name>>("-e: Set the name")?;
///
/// parser.parse(ARef::new(Args::from_array(["app", "-e=foo"])))?;
///
/// // Get the value through value type `Name`
/// assert_eq!(parser.find_val::<Name>("-e")?, &Name("foo".to_owned()));
///
/// #    Ok(())
/// # }
/// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct MutOpt<T>(pub T);

impl<T> MutOpt<T> {
    pub fn new(value: T) -> Self {
        Self(value)
    }
}

impl<T> Deref for MutOpt<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for MutOpt<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

/// Simple option type wrapper, implemented [`Infer`](crate::value::Infer).
/// It works with the types are implemented [`RawValParser`](crate::value::RawValParser).
///
/// # Example
///
/// ```rust
/// # use aopt::Error;
/// # use aopt::value::raw2str;
/// # use aopt::prelude::*;
/// # use std::ops::Deref;
///
/// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
/// pub struct Name(String);
///
/// impl RawValParser for Name {
///     type Error = Error;
///
///     fn parse(arg: Option<&RawVal>, _: &Ctx) -> Result<Self, Self::Error> {
///         Ok(Name(raw2str(arg)?.to_owned()))
///     }
/// }
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut parser = AFwdParser::default();
///
/// // add the option wrap with `RefOpt`
/// parser.add_opt_i::<RefOpt<'_, Name>>("-e: Set the name")?;
///
/// parser.parse(ARef::new(Args::from_array(["app", "-e=foo"])))?;
///
/// // Get the value through value type `Name`
/// assert_eq!(parser.find_val::<Name>("-e")?, &Name("foo".to_owned()));
///
/// #    Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct RefOpt<'a, T>(pub &'a T);

impl<'a, T> RefOpt<'a, T> {
    pub fn new(value: &'a T) -> Self {
        Self(value)
    }
}

impl<'a, T> Deref for RefOpt<'a, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.0
    }
}

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct Any<T = ()>(pub T);

impl<T> Any<T> {
    pub fn new(value: T) -> Self {
        Self(value)
    }
}

impl<T> Deref for Any<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for Any<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

/// Option parser using for parsing option constructor string.
pub trait OptParser {
    type Output;
    type Error: Into<Error>;

    fn parse_opt(&self, pattern: Str) -> Result<Self::Output, Self::Error>;
}

pub trait Opt: Debug {
    fn reset(&mut self);

    fn uid(&self) -> Uid;

    /// The name of option.
    fn name(&self) -> &Str;

    /// The type of option.
    fn r#type(&self) -> &TypeId;

    /// The help hint of option such as `--flag`.
    fn hint(&self) -> &Str;

    /// The help message of option.
    fn help(&self) -> &Str;

    fn valid(&self) -> bool;

    /// If the option matched.
    fn matched(&self) -> bool;

    /// If the option is force required.
    fn force(&self) -> bool;

    /// The associaed action of option.
    fn action(&self) -> &Action;

    /// The index of option.
    fn index(&self) -> Option<&Index>;

    /// The alias the option.
    fn alias(&self) -> Option<&Vec<Str>>;

    fn accessor(&self) -> &ValAccessor;

    fn accessor_mut(&mut self) -> &mut ValAccessor;

    fn ignore_alias(&self) -> bool;

    fn ignore_name(&self) -> bool;

    fn ignore_index(&self) -> bool;

    fn set_uid(&mut self, uid: Uid);

    fn set_matched(&mut self, matched: bool);

    fn mat_style(&self, style: Style) -> bool;

    fn mat_force(&self, force: bool) -> bool;

    fn mat_name(&self, name: Option<&Str>) -> bool;

    fn mat_alias(&self, name: &Str) -> bool;

    fn mat_index(&self, index: Option<(usize, usize)>) -> bool;

    fn init(&mut self) -> Result<(), Error>;
}