Parser

Struct Parser 

Source
pub struct Parser<S, P: Policy<Set = S>> {
    pub policy: P,
    pub optset: S,
}
Expand description

Parser manage the components are using in parse of Policy.

§Example

let mut parser1 = Parser::new_policy(AFwdPolicy::default());

parser1.add_opt("Where=c")?;
parser1.add_opt("question=m")?.on(question)?;

let mut parser2 = Parser::new_policy(AFwdPolicy::default());

parser2.add_opt("Who=c")?;
parser2.add_opt("question=m")?.on(question)?;

fn question(_: &mut AHCSet, ctx: &mut Ctx) -> Result<Option<()>, Error> {
    let args = ctx.args();
    // Output: The question is: Where are you from ?
    println!(
        "The question is: {}",
        args.iter().skip(1)
            .map(|v| v.to_str().unwrap().to_owned())
            .collect::<Vec<String>>()
            .join(" ")
    );
    Ok(Some(()))
}

let ret = getopt!(
    Args::from(["app", "Where", "are", "you", "from", "?"]),
    &mut parser1,
    &mut parser2
)?;
let parser = ret.parser;

assert_eq!(
    parser[0].name(),
    "Where",
    "Parser with `Where` cmd matched"
);

Using it with macro getopt, which can process multiple Parser with same type Policy.

Fields§

§policy: P§optset: S

Implementations§

Source§

impl<S, P: Policy<Set = S>> Parser<S, P>

Source

pub fn new(policy: P, optset: S) -> Self

Source

pub fn policy(&self) -> &P

Source

pub fn policy_mut(&mut self) -> &mut P

Source

pub fn set_policy(&mut self, policy: P) -> &mut Self

Source

pub fn optset(&self) -> &S

Source

pub fn optset_mut(&mut self) -> &mut S

Source

pub fn set_optset(&mut self, optset: S) -> &mut Self

Source§

impl<'a, S, P> Parser<HCOptSet<'a, S>, P>
where S: Default, P: Policy<Set = HCOptSet<'a, S>, Inv<'a> = Invoker<'a, HCOptSet<'a, S>>>,

Source

pub fn new_policy(policy: P) -> Self

Source

pub fn new_with( policy: P, optset: S, invoker: Invoker<'a, HCOptSet<'a, S>>, ) -> Self

Source§

impl<'a, S, P> Parser<HCOptSet<'a, S>, P>
where S: Set, P: Policy<Set = HCOptSet<'a, S>, Inv<'a> = Invoker<'a, HCOptSet<'a, S>>>,

Source

pub fn reset(&mut self) -> Result<&mut Self, Error>

Reset the option set.

Source

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

Call the init of Opt initialize the option value.

Source

pub fn parse(&mut self, args: Args) -> Result<<P as Policy>::Ret, Error>

Examples found in repository?
examples/02_option_value.rs (lines 12-14)
3pub fn main() -> Result<(), aopt::Error> {
4    let mut parser = AFwdParser::default();
5
6    // add option need argument with type `i`, i.e. i64
7    parser.add_opt("-f=i")?;
8    parser.add_opt("--flag=s")?;
9    parser.add_opt("-flag".infer::<f32>())?;
10
11    parser
12        .parse(Args::from(
13            ["app", "-f42", "--flag", "foo", "-flag=2.1"].into_iter(),
14        ))?
15        .ok()?;
16
17    assert_eq!(parser.find_val::<i64>("-f")?, &42);
18    assert_eq!(parser.find_val::<String>("--flag")?, "foo");
19    assert_eq!(parser.find_val::<f32>("-flag")?, &2.1);
20
21    Ok(())
22}
More examples
Hide additional examples
examples/06_callback.rs (line 16)
3pub fn main() -> Result<(), aopt::Error> {
4    let mut parser = AFwdParser::default();
5
6    parser.add_opt("-flag".infer::<i32>())?.on(|_, _| {
7        println!("ignore the value set from command line");
8        Ok(Some(42))
9    })?;
10    parser
11        .add_opt("--/flag".infer::<bool>())?
12        .set_value(true)
13        .on(|_, ctx| Ok(Some(!ctx.value::<bool>()?)))?;
14
15    parser
16        .parse(Args::from(["app", "-flag=foo", "--/flag"].into_iter()))?
17        .ok()?;
18
19    assert_eq!(parser.find_val::<i32>("-flag")?, &42);
20    assert_eq!(parser.find_val::<bool>("--/flag")?, &false);
21
22    Ok(())
23}
examples/07_callback.rs (line 20)
11pub fn main() -> Result<(), aopt::Error> {
12    let mut parser = AFwdParser::default();
13
14    parser.add_opt("-flag;--flag=b")?.on(changed("--/flag"))?;
15    parser
16        .add_opt("-/flag;--/flag=b")?
17        .set_value_t(true)
18        .on(changed("--flag"))?;
19    parser
20        .parse(Args::from(["app", "-flag"].into_iter()))?
21        .ok()?;
22
23    assert_eq!(parser.find_val::<bool>("-flag")?, &true);
24    assert_eq!(parser.find_val::<bool>("--/flag")?, &false);
25
26    parser
27        .parse(Args::from(["app", "--/flag"].into_iter()))?
28        .ok()?;
29
30    assert_eq!(parser.find_val::<bool>("-flag")?, &false);
31    assert_eq!(parser.find_val::<bool>("--/flag")?, &true);
32
33    Ok(())
34}
examples/05_overload.rs (lines 13-15)
3pub fn main() -> Result<(), aopt::Error> {
4    let mut parser = AFwdParser::default();
5
6    parser.add_opt("-flag".infer::<i32>())?;
7    parser.add_opt("-flag".infer::<String>())?;
8    parser.add_opt("-flag".infer::<bool>())?;
9
10    // enable combination style
11    parser.set_overload(true);
12    parser
13        .parse(Args::from(
14            ["app", "-flag=foo", "-flag=42", "-flag"].into_iter(),
15        ))?
16        .ok()?;
17
18    assert_eq!(parser.find("-flag".infer::<i32>())?.val::<i32>()?, &42);
19    assert_eq!(
20        parser.find("-flag".infer::<String>())?.val::<String>()?,
21        "foo"
22    );
23    assert_eq!(parser.find("-flag".infer::<bool>())?.val::<bool>()?, &true);
24
25    Ok(())
26}
examples/04_positional.rs (lines 18-20)
3pub fn main() -> Result<(), aopt::Error> {
4    let mut parser = AFwdParser::default();
5
6    parser.add_opt("--flag=b")?;
7    parser.add_opt("--foo=s")?;
8    // In default, positional has bool value
9    parser.add_opt("first=p@1")?;
10    // A special positional argument match the name, and force required
11    parser.add_opt("list=c")?;
12    // Add a positional argument has String value
13    parser.add_opt("second@2".infer::<Pos<String>>())?;
14
15    // enable combination style
16    parser.enable_combined();
17    parser
18        .parse(Args::from(
19            ["app", "list", "--foo", "value", "bar"].into_iter(),
20        ))?
21        .ok()?;
22
23    assert_eq!(parser.find_val::<bool>("list")?, &true);
24    assert_eq!(parser.find_val::<bool>("first")?, &true);
25    assert_eq!(parser.find_val::<String>("second")?, "bar");
26
27    Ok(())
28}
examples/01_prefix_option.rs (line 10)
3pub fn main() -> Result<(), aopt::Error> {
4    let mut parser = AFwdParser::default();
5
6    // add option with value type `b`, i.e. option with bool value or flag
7    parser.add_opt("-f=b")?;
8    parser.add_opt("--flag".infer::<bool>())?;
9
10    parser.parse(Args::from(["app", "-f"].into_iter()))?.ok()?;
11
12    // option with bool type has default value `false`
13    assert_eq!(parser.find_val::<bool>("-f")?, &true);
14    assert_eq!(parser.find_val::<bool>("--flag")?, &false);
15
16    parser.add_opt("-flag=b!")?;
17    parser.add_opt("--/flag=b")?;
18
19    parser
20        .parse(Args::from(["app", "-flag", "--/flag"].into_iter()))?
21        .ok()?;
22
23    // option with bool type has default value `false`
24    assert_eq!(parser.find_val::<bool>("-flag")?, &true);
25    assert_eq!(parser.find_val::<bool>("--/flag")?, &true);
26
27    Ok(())
28}
Source§

impl<S, P> Parser<S, P>
where P: Policy<Set = S> + PolicySettings,

Source

pub fn enable_combined(&mut self) -> &mut Self

Enable CombinedOption option set style. This can support option style like -abc which set -a, -b and -c both.

Examples found in repository?
examples/04_positional.rs (line 16)
3pub fn main() -> Result<(), aopt::Error> {
4    let mut parser = AFwdParser::default();
5
6    parser.add_opt("--flag=b")?;
7    parser.add_opt("--foo=s")?;
8    // In default, positional has bool value
9    parser.add_opt("first=p@1")?;
10    // A special positional argument match the name, and force required
11    parser.add_opt("list=c")?;
12    // Add a positional argument has String value
13    parser.add_opt("second@2".infer::<Pos<String>>())?;
14
15    // enable combination style
16    parser.enable_combined();
17    parser
18        .parse(Args::from(
19            ["app", "list", "--foo", "value", "bar"].into_iter(),
20        ))?
21        .ok()?;
22
23    assert_eq!(parser.find_val::<bool>("list")?, &true);
24    assert_eq!(parser.find_val::<bool>("first")?, &true);
25    assert_eq!(parser.find_val::<String>("second")?, "bar");
26
27    Ok(())
28}
More examples
Hide additional examples
examples/03_combination_style.rs (line 15)
3pub fn main() -> Result<(), aopt::Error> {
4    let mut parser = AFwdParser::default();
5
6    // combination style only support bool type
7    parser.add_opt("-a=b")?;
8    parser.add_opt("-b=b")?;
9    parser.add_opt("-c".infer::<bool>())?;
10    parser.add_opt("d=b")?;
11    parser.add_opt("e=b")?;
12    parser.add_opt("f".infer::<bool>())?;
13
14    // enable combination style
15    parser.enable_combined();
16    parser
17        .parse(Args::from(["app", "-abc", "def"].into_iter()))?
18        .ok()?;
19
20    assert_eq!(parser.find_val::<bool>("-a")?, &true);
21    assert_eq!(parser.find_val::<bool>("-b")?, &true);
22    assert_eq!(parser.find_val::<bool>("-c")?, &true);
23    assert_eq!(parser.find_val::<bool>("d")?, &false);
24    assert_eq!(parser.find_val::<bool>("e")?, &false);
25    assert_eq!(parser.find_val::<bool>("f")?, &false);
26
27    // for support non-prefix option, need add prefix `""`,
28    // and disable the strict flag of policy
29    parser.validator_mut().add_prefix("");
30    parser.set_strict(false);
31    parser
32        .parse(Args::from(["app", "-abc", "def"].into_iter()))?
33        .ok()?;
34
35    assert_eq!(parser.find_val::<bool>("-a")?, &true);
36    assert_eq!(parser.find_val::<bool>("-b")?, &true);
37    assert_eq!(parser.find_val::<bool>("-c")?, &true);
38    assert_eq!(parser.find_val::<bool>("d")?, &true);
39    assert_eq!(parser.find_val::<bool>("e")?, &true);
40    assert_eq!(parser.find_val::<bool>("f")?, &true);
41
42    Ok(())
43}
Source

pub fn enable_embedded_plus(&mut self) -> &mut Self

Enable EmbeddedValuePlus option set style. This can support option style like --opt42 which set --opt value to 42. In default the EmbeddedValue style only support one letter option such as -i.

Source

pub fn enable_flag(&mut self) -> &mut Self

Enable Flag option set style. It will support set style like --flag, but the value will be set to None.

Trait Implementations§

Source§

impl<S: Debug, P: Debug + Policy<Set = S>> Debug for Parser<S, P>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<S: Default, P: Default + Policy<Set = S>> Default for Parser<S, P>

Source§

fn default() -> Parser<S, P>

Returns the “default value” for a type. Read more
Source§

impl<S, P: Policy<Set = S>> Deref for Parser<S, P>

Source§

type Target = S

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl<S, P: Policy<Set = S>> DerefMut for Parser<S, P>

Source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
Source§

impl<S, P> OptValidator for Parser<S, P>
where S: OptValidator, P: Policy<Set = S>,

Source§

type Error = Error

Source§

fn check(&mut self, name: &str) -> Result<bool, Self::Error>

Check the option string.
Source§

fn split<'b>( &self, name: &Cow<'b, str>, ) -> Result<(Cow<'b, str>, Cow<'b, str>), Self::Error>

Split the option string into prefix and name.
Source§

impl<S, P: Policy<Set = S>> PolicyParser<P> for Parser<S, P>
where S: Set + PolicyParser<P, Error = Error>,

Source§

type Error = Error

Source§

fn parse(&mut self, args: Args) -> Result<<P as Policy>::Ret, Self::Error>
where P: Default,

Source§

fn parse_policy( &mut self, args: Args, policy: &mut P, ) -> Result<<P as Policy>::Ret, Self::Error>

Source§

fn parse_env(&mut self) -> Result<P::Ret, Self::Error>
where P: Default,

Source§

fn parse_env_policy(&mut self, policy: &mut P) -> Result<P::Ret, Self::Error>

Source§

impl<S, P> PolicySettings for Parser<S, P>
where P: Policy<Set = S> + PolicySettings,

Source§

fn style_manager(&self) -> &OptStyleManager

Source§

fn style_manager_mut(&mut self) -> &mut OptStyleManager

Source§

fn strict(&self) -> bool

Source§

fn styles(&self) -> &[UserStyle]

Source§

fn no_delay(&self) -> Option<&[String]>

Source§

fn overload(&self) -> bool

Source§

fn prepolicy(&self) -> bool

Source§

fn set_strict(&mut self, strict: bool) -> &mut Self

Source§

fn set_styles(&mut self, styles: Vec<UserStyle>) -> &mut Self

Source§

fn set_no_delay(&mut self, name: impl Into<String>) -> &mut Self

Source§

fn set_overload(&mut self, overload: bool) -> &mut Self

Source§

fn set_prepolicy(&mut self, ignore_failure: bool) -> &mut Self

Source§

impl<S, P> PrefixedValidator for Parser<S, P>
where S: PrefixedValidator, P: Policy<Set = S>,

Source§

type Error = Error

Source§

fn reg_prefix(&mut self, val: &str) -> Result<(), Self::Error>

Register the prefix to current validator.
Source§

fn unreg_prefix(&mut self, val: &str) -> Result<(), Self::Error>

Unregister the prefix to current validator.

Auto Trait Implementations§

§

impl<S, P> Freeze for Parser<S, P>
where P: Freeze, S: Freeze,

§

impl<S, P> RefUnwindSafe for Parser<S, P>

§

impl<S, P> Send for Parser<S, P>
where P: Send, S: Send,

§

impl<S, P> Sync for Parser<S, P>
where P: Sync, S: Sync,

§

impl<S, P> Unpin for Parser<S, P>
where P: Unpin, S: Unpin,

§

impl<S, P> UnwindSafe for Parser<S, P>
where P: UnwindSafe, S: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> ConstructIntoOp for T

Source§

fn into_box(self) -> WrappedTy<BoxedCtor<T>>

Return a type that wraps Ctor with Box.

§Example
    let re = b'+'
        .or(b'-')
        .then(u8::is_ascii_hexdigit)
        .then(u8::is_ascii_hexdigit.repeat_times::<3>())
        .pat()
        .map(|v: &[u8]| String::from_utf8(v.to_vec()).map_err(|_| Error::Uid(0)))
        .into_box();

    assert_eq!(BytesCtx::new(b"+AE00").ctor(&re)?, "+AE00");
    assert!(BytesCtx::new(b"-GH66").ctor(&re).is_err());
    assert_eq!(BytesCtx::new(b"-83FD").ctor(&re)?, "-83FD");
    Ok(())
Source§

fn into_rc(self) -> WrappedTy<Rc<T>>

Return a type that wrap Ctor with Rc.

§Example
    color_eyre::install()?;
    let year = char::is_ascii_digit.repeat_times::<4>();
    let num = char::is_ascii_digit.repeat_times::<2>();
    let date = year.sep_once("-", num.sep_once("-", num)).into_rc();
    let time = num.sep_once(":", num.sep_once(":", num));
    let datetime = date.clone().sep_once(" ", time);

    assert_eq!(
        CharsCtx::new("2024-01-08").ctor(&date)?,
        ("2024", ("01", "08"))
    );
    assert_eq!(
        CharsCtx::new("2024-01-08 10:01:13").ctor(&datetime)?,
        (("2024", ("01", "08")), ("10", ("01", "13")))
    );
    Ok(())
Source§

fn into_dyn<'a, 'b, C, M, O, H, A>( self, ) -> WrappedTy<DynamicBoxedCtor<'a, 'b, C, M, O, H, A>>
where C: Context<'a> + Match<C>, T: Ctor<'a, C, M, O, H, A> + 'b,

§Example 2
    color_eyre::install()?;
    let num = u8::is_ascii_digit
        .repeat_one()
        .map(|v: &[u8]| String::from_utf8(v.to_vec()).map_err(|_| Error::Uid(0)))
        .map(map::from_str::<usize>());
    let num = num.clone().sep_once(b",", num);
    let re = num.into_dyn();

    assert_eq!(BytesCtx::new(b"3,0").ctor(&re)?, (3, 0));
    assert_eq!(BytesCtx::new(b"2,1").ctor(&re)?, (2, 1));
    assert_eq!(BytesCtx::new(b"0,3").ctor(&re)?, (0, 3));
    Ok(())
Source§

fn into_arc(self) -> WrappedTy<Arc<T>>

Source§

fn into_cell(self) -> WrappedTy<Cell<T>>

Source§

fn into_refcell(self) -> WrappedTy<RefCell<T>>

Source§

fn into_mutex(self) -> WrappedTy<Mutex<T>>

Source§

fn into_dyn_sync<'a, 'b, C, M, O, H, A>( self, ) -> WrappedTy<DynamicBoxedCtorSync<'a, 'b, C, M, O, H, A>>
where C: Context<'a> + Match<C>, T: Ctor<'a, C, M, O, H, A> + Send + 'b,

Source§

fn into_dyn_arc<'a, 'b, C, M, O, H, A>( self, ) -> WrappedTy<DynamicArcCtor<'a, 'b, C, M, O, H, A>>
where C: Context<'a> + Match<C>, T: Ctor<'a, C, M, O, H, A> + 'b,

Source§

fn into_dyn_rc<'a, 'b, C, M, O, H, A>( self, ) -> WrappedTy<DynamicRcCtor<'a, 'b, C, M, O, H, A>>
where C: Context<'a> + Match<C>, T: Ctor<'a, C, M, O, H, A> + 'b,

Source§

impl<'a, C, T> DynamicCreateCtorThenHelper<'a, C> for T
where C: Context<'a> + Match<C>,

Source§

fn dyn_then_ctor<F>(self, func: F) -> DynamicCreateCtorThen<C, T, F>

Construct a new regex with Ctor implementation based on previous result.

§Example
    let num = u8::is_ascii_digit
        .repeat_one()
        .map(|v: &[u8]| String::from_utf8(v.to_vec()).map_err(|_| Error::Uid(0)))
        .map(map::from_str::<usize>());
    let num = num.clone().sep_once(b",", num);
    let re = num.dyn_then_ctor(|a: &(usize, usize)| {
        // leave the a's type empty cause rustc reject compile
        Ok(b'+'
            .repeat_range(a.0..a.0 + 1)
            .then(b'-'.repeat_range(a.1..a.1 + 1)))
    });

    assert_eq!(
        BytesCtx::new(b"3,0+++").ctor(&re)?,
        ((3, 0), ([43, 43, 43].as_slice(), [].as_slice()))
    );
    assert_eq!(
        BytesCtx::new(b"2,1++-").ctor(&re)?,
        ((2, 1), ([43, 43].as_slice(), [45].as_slice()))
    );
    assert_eq!(
        BytesCtx::new(b"0,3---").ctor(&re)?,
        ((0, 3), ([].as_slice(), [45, 45, 45].as_slice()))
    );
    Ok(())
Source§

impl<'a, C, T> DynamicCreateRegexThenHelper<'a, C> for T
where C: Context<'a> + Match<C>,

Source§

fn dyn_then_regex<F>(self, func: F) -> DynamicCreateRegexThen<C, T, F>

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> RegexIntoOp for T

Source§

fn into_box_regex(self) -> WrappedTy<BoxedRegex<T>>

Source§

fn into_rc_regex(self) -> WrappedTy<Rc<T>>

Source§

fn into_arc_regex(self) -> WrappedTy<Arc<T>>

Source§

fn into_cell_regex(self) -> WrappedTy<Cell<T>>

Source§

fn into_refcell_regex(self) -> WrappedTy<RefCell<T>>

Source§

fn into_mutex_regex(self) -> WrappedTy<Mutex<T>>

Source§

fn into_dyn_regex<'a, 'b, C>( self, ) -> WrappedTy<DynamicBoxedRegex<'b, C, <T as Regex<C>>::Ret>>
where C: Context<'a>, T: Regex<C> + 'b,

Source§

fn into_dyn_arc_regex<'a, 'b, C>( self, ) -> WrappedTy<DynamicArcRegex<'b, C, <T as Regex<C>>::Ret>>
where C: Context<'a>, T: Regex<C> + 'b,

Source§

fn into_dyn_rc_regex<'a, 'b, C>( self, ) -> WrappedTy<DynamicRcRegex<'b, C, <T as Regex<C>>::Ret>>
where C: Context<'a>, T: Regex<C> + 'b,

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedTy for T
where T: Any + Debug + Sync + Send + 'static,

Source§

impl<T> MayDebug for T