Skip to main content

alux_cli/
source.rs

1use core::marker::PhantomData;
2use std::ffi::OsStr;
3
4use crate::{Arity, CliArgumentError, CliWordAlg};
5
6/// Marks a source whose argument comes only from the command line, with no fallback.
7#[derive(Clone, Copy, Debug, Default)]
8pub struct NoFallback;
9
10/// Marks a source that falls back to an environment variable and nothing else.
11///
12/// A switch takes this fallback, since off is already what it is when nothing turns it on.
13#[derive(Clone, Copy, Debug, Default)]
14pub struct WithEnv;
15
16/// Marks a source that falls back to a default word, after an environment variable if it has one.
17#[derive(Clone, Copy, Debug, Default)]
18pub struct WithFallback;
19
20/// States the fallback mode a source takes once it also reads an environment variable.
21pub trait EnvFallback {
22    /// The mode with the environment variable.
23    type WithEnv;
24}
25
26impl EnvFallback for NoFallback {
27    type WithEnv = WithEnv;
28}
29
30impl EnvFallback for WithEnv {
31    type WithEnv = WithEnv;
32}
33
34impl EnvFallback for WithFallback {
35    type WithEnv = WithFallback;
36}
37
38/// Names where an argument's words come from when the command line gives none.
39#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
40pub struct Fallback {
41    /// The environment variable read next.
42    pub env: Option<&'static str>,
43    /// The word used last.
44    pub default: Option<&'static str>,
45}
46
47/// Marks a source supplying exactly one value, the operation's argument itself.
48#[derive(Clone, Copy, Debug, Default)]
49pub struct Whole;
50
51/// Marks a source supplying `Option` of a value: at most one. A product takes all of its fields or
52/// none of them, a sum one alternative or none.
53#[derive(Clone, Copy, Debug, Default)]
54pub struct Optional;
55
56/// Marks a source supplying `Vec` of values: any number, in the order given.
57#[derive(Clone, Copy, Debug, Default)]
58pub struct Many;
59
60/// Marks a named source supplying `bool`: whether its spelling is given. It takes no value.
61#[derive(Clone, Copy, Debug, Default)]
62pub struct Switch;
63
64/// Marks a named source supplying `Option<Option<_>>`: whether its spelling is given, and the value
65/// written in the same word, as `sed -i.bak` gives one and `sed -i` none.
66#[derive(Clone, Copy, Debug, Default)]
67pub struct OptionalValue;
68
69/// States how many occurrences a source of one shape takes.
70pub trait CliShape {
71    /// The occurrences the shape takes.
72    const ARITY: Arity;
73}
74
75impl CliShape for Whole {
76    const ARITY: Arity = Arity::One;
77}
78
79impl CliShape for Optional {
80    const ARITY: Arity = Arity::Optional;
81}
82
83impl CliShape for Many {
84    const ARITY: Arity = Arity::Many;
85}
86
87impl CliShape for OptionalValue {
88    const ARITY: Arity = Arity::OptionalValue;
89}
90
91impl CliShape for Switch {
92    const ARITY: Arity = Arity::Presence;
93}
94
95/// Takes an argument's words by position, in the order the positional arguments are declared.
96///
97/// It supplies one value; `.optional()` and `.many()` state another shape.
98#[derive(Clone, Copy, Debug)]
99pub struct PositionalSource<Mode = NoFallback, Shape = Whole> {
100    doc: &'static str,
101    fallback: Fallback,
102    mode: PhantomData<fn() -> (Mode, Shape)>,
103}
104
105/// Marks a named source spelled as options: `--long` or `-s`, with the value after it.
106#[derive(Clone, Copy, Debug, Default)]
107pub struct Options;
108
109/// Marks a named source spelled as an operand assigning its value, `name=value`, as `dd if=FILE`.
110#[derive(Clone, Copy, Debug, Default)]
111pub struct Assigned;
112
113/// Takes an argument's words after its spelling, `--long` or `-s`, or from an operand `name=value`
114/// once `.assigned(name)` spells it so.
115///
116/// The long spelling defaults to the operation's argument name with `_` written as `-`. It supplies
117/// one value; `.optional()`, `.many()`, and `.switch()` state another shape.
118#[derive(Clone, Copy, Debug)]
119pub struct NamedSource<Mode = NoFallback, Shape = Whole, Spelling = Options> {
120    /// The long spelling, or the assigned name once `.assigned(..)` spells the source.
121    long: Option<&'static str>,
122    short: Option<char>,
123    short_aliases: &'static [char],
124    doc: &'static str,
125    fallback: Fallback,
126    mode: Markers<Mode, Shape, Spelling>,
127}
128
129/// The type-level choices a named source carries: its fallback, shape, and spelling.
130type Markers<Mode, Shape, Spelling> = PhantomData<fn() -> (Mode, Shape, Spelling)>;
131
132impl PositionalSource {
133    /// Declares a positional source documented by `doc`.
134    pub fn new(doc: &'static str) -> Self {
135        Self { doc, fallback: Fallback::default(), mode: PhantomData }
136    }
137}
138
139impl<Mode> PositionalSource<Mode> {
140    /// Supplies `Option` of the value: at most one word.
141    pub fn optional(self) -> PositionalSource<Mode, Optional> {
142        PositionalSource { doc: self.doc, fallback: self.fallback, mode: PhantomData }
143    }
144
145    /// Supplies `Vec` of values: every remaining positional word.
146    pub fn many(self) -> PositionalSource<Mode, Many> {
147        PositionalSource { doc: self.doc, fallback: self.fallback, mode: PhantomData }
148    }
149}
150
151impl<Mode, Shape> PositionalSource<Mode, Shape> {
152    /// Reads the environment variable `name` when the command line gives no words.
153    pub fn env(self, name: &'static str) -> PositionalSource<Mode::WithEnv, Shape>
154    where
155        Mode: EnvFallback,
156    {
157        PositionalSource { doc: self.doc, fallback: Fallback { env: Some(name), ..self.fallback }, mode: PhantomData }
158    }
159
160    /// Uses `word` when neither the command line nor the environment gives one.
161    pub fn default(self, word: &'static str) -> PositionalSource<WithFallback, Shape> {
162        PositionalSource {
163            doc: self.doc,
164            fallback: Fallback { default: Some(word), ..self.fallback },
165            mode: PhantomData,
166        }
167    }
168}
169
170impl NamedSource {
171    /// Declares a named source documented by `doc`, spelled after the argument name.
172    pub fn new(doc: &'static str) -> Self {
173        Self { long: None, short: None, short_aliases: &[], doc, fallback: Fallback::default(), mode: PhantomData }
174    }
175}
176
177impl<Mode> NamedSource<Mode> {
178    /// Spells the source as the operand `name=value` instead of an option: the value is everything
179    /// after the first `=`, and may be empty. It takes no positional place, and no other spelling.
180    pub fn assigned(self, name: &'static str) -> NamedSource<Mode, Whole, Assigned> {
181        NamedSource {
182            long: Some(name),
183            short: None,
184            short_aliases: &[],
185            doc: self.doc,
186            fallback: self.fallback,
187            mode: PhantomData,
188        }
189    }
190
191    /// Supplies `bool`: whether the spelling is given, with no value after it.
192    pub fn switch(self) -> NamedSource<Mode, Switch> {
193        NamedSource {
194            long: self.long,
195            short: self.short,
196            short_aliases: self.short_aliases,
197            doc: self.doc,
198            fallback: self.fallback,
199            mode: PhantomData,
200        }
201    }
202
203    /// Supplies `Option<Option<_>>`: whether the spelling is given, and the value written in its
204    /// own word, `-i.bak` or `--in-place=.bak`. The next word is never its value.
205    pub fn optional_value(self) -> NamedSource<Mode, OptionalValue> {
206        NamedSource {
207            long: self.long,
208            short: self.short,
209            short_aliases: self.short_aliases,
210            doc: self.doc,
211            fallback: self.fallback,
212            mode: PhantomData,
213        }
214    }
215}
216
217impl<Mode, Spelling> NamedSource<Mode, Whole, Spelling> {
218    /// Supplies `Option` of the value: at most one occurrence.
219    pub fn optional(self) -> NamedSource<Mode, Optional, Spelling> {
220        NamedSource {
221            long: self.long,
222            short: self.short,
223            short_aliases: self.short_aliases,
224            doc: self.doc,
225            fallback: self.fallback,
226            mode: PhantomData,
227        }
228    }
229
230    /// Supplies `Vec` of values: one per occurrence, in order.
231    pub fn many(self) -> NamedSource<Mode, Many, Spelling> {
232        NamedSource {
233            long: self.long,
234            short: self.short,
235            short_aliases: self.short_aliases,
236            doc: self.doc,
237            fallback: self.fallback,
238            mode: PhantomData,
239        }
240    }
241}
242
243impl<Mode, Shape> NamedSource<Mode, Shape> {
244    /// Spells the source `--long` instead of after the argument name.
245    #[must_use]
246    pub fn long(self, long: &'static str) -> Self {
247        Self { long: Some(long), ..self }
248    }
249
250    /// Also spells the source `-short`.
251    #[must_use]
252    pub fn short(self, short: char) -> Self {
253        Self { short: Some(short), ..self }
254    }
255
256    /// Also spells the source as each of `aliases`, as `cp -R` is `cp -r`. Help shows them after
257    /// the short spelling.
258    #[must_use]
259    pub fn short_aliases(self, aliases: &'static [char]) -> Self {
260        Self { short_aliases: aliases, ..self }
261    }
262}
263
264impl<Mode, Shape, Spelling> NamedSource<Mode, Shape, Spelling> {
265    /// Reads the environment variable `name` when the command line gives no words.
266    pub fn env(self, name: &'static str) -> NamedSource<Mode::WithEnv, Shape, Spelling>
267    where
268        Mode: EnvFallback,
269    {
270        let fallback = Fallback { env: Some(name), ..self.fallback };
271        NamedSource {
272            long: self.long,
273            short: self.short,
274            short_aliases: self.short_aliases,
275            doc: self.doc,
276            fallback,
277            mode: PhantomData,
278        }
279    }
280
281    /// Uses `word` when neither the command line nor the environment gives one.
282    pub fn default(self, word: &'static str) -> NamedSource<WithFallback, Shape, Spelling> {
283        let fallback = Fallback { default: Some(word), ..self.fallback };
284        NamedSource {
285            long: self.long,
286            short: self.short,
287            short_aliases: self.short_aliases,
288            doc: self.doc,
289            fallback,
290            mode: PhantomData,
291        }
292    }
293}
294
295/// Describes where an argument's words come from.
296#[derive(Clone, Debug, PartialEq, Eq)]
297pub enum SourceInfo {
298    /// The `index`th positional argument of the command, counting from zero.
299    Positional {
300        /// The position among the command's positional arguments.
301        index: usize,
302    },
303    /// The value after `name=` in an operand that assigns it, as `dd if=FILE` does.
304    Assigned {
305        /// The name before `=`.
306        name: String,
307    },
308    /// Words following `--long` or `-short`.
309    Named {
310        /// The long spelling, without `--`.
311        long: String,
312        /// The short spelling, without `-`.
313        short: Option<char>,
314        /// Other short spellings that mean the same, without `-`.
315        short_aliases: &'static [char],
316    },
317}
318
319/// Names the compound argument a described argument is one part of.
320#[derive(Clone, Copy, Debug, PartialEq, Eq)]
321pub enum Part {
322    /// A field of a product: given together with the product's other fields.
323    Product(&'static str),
324    /// An alternative of a sum: given instead of the sum's other alternatives.
325    Sum(&'static str),
326}
327
328/// Describes one argument of a command: the operation's argument and the source it is read from.
329#[derive(Clone, Debug, PartialEq, Eq)]
330pub struct ArgumentInfo {
331    /// The operation's argument name, or the field or alternative name within a compound argument.
332    pub name: &'static str,
333    /// Where its words come from on the command line.
334    pub source: SourceInfo,
335    /// Where its words come from when the command line gives none.
336    pub fallback: Fallback,
337    /// How many occurrences its type takes.
338    pub arity: Arity,
339    /// What the argument means on the command line.
340    pub doc: &'static str,
341    /// The compound argument this is a part of, if any.
342    pub part_of: Option<Part>,
343    /// The character every word is split on before decoding, for a list one word gives.
344    pub delimiter: Option<char>,
345}
346
347/// States that a source can supply an argument of type `Argument`.
348///
349/// A named source supplies any argument. A positional source supplies a value, an optional
350/// value, or many values, but not a switch, because a switch is only its spelling. For the same
351/// reason a switch has no fallback. A product source supplies a `Product`, and a sum source a `Sum`.
352#[diagnostic::on_unimplemented(
353    message = "`{Self}` cannot supply an argument of type `{Argument}`",
354    note = "sources bind to the operation's arguments in order, one `.arg(..)` each; check the order of the `.arg(..)` calls",
355    note = "a plain source supplies the value itself, `.optional()` an `Option`, `.many()` a `Vec`, `.switch()` a `bool`, `.product()` and `.sum()` their type"
356)]
357pub trait CliSourceFor<Argument> {
358    /// Describes this source for the argument `name` into `out`, counting positional sources in
359    /// `positions`. A compound source describes one argument per part.
360    fn cli_describe(&self, name: &'static str, positions: &mut usize, out: &mut Vec<ArgumentInfo>);
361}
362
363/// Decodes the argument a source supplies, with `Decoder`.
364pub trait CliSourceDecode<Argument, Decoder, Error> {
365    /// Decodes the argument from the words `decoder` gives for the arguments this source was
366    /// described as, taken from the front of `arguments`.
367    ///
368    /// # Errors
369    ///
370    /// Answers with the part of the argument whose words do not make its value.
371    fn cli_decode_source(
372        &self,
373        arguments: &mut &[ArgumentInfo],
374        decoder: &Decoder,
375    ) -> Result<Argument, CliArgumentError<Error>>;
376}
377
378/// Takes the next described argument, the one a source of one argument was described as.
379///
380/// A command is described from the same sources it decodes with, so there is always one.
381pub(crate) fn next<'a>(arguments: &mut &'a [ArgumentInfo]) -> &'a ArgumentInfo {
382    let (argument, rest) = arguments.split_first().expect("a source decodes the argument it was described as");
383    *arguments = rest;
384    argument
385}
386
387/// States how a named source is spelled on the command line.
388pub trait CliSpelling {
389    /// Describes the spelling of a source spelled `long`, `-short`, and `-aliases`.
390    fn cli_spelling(long: String, short: Option<char>, short_aliases: &'static [char]) -> SourceInfo;
391}
392
393impl CliSpelling for Options {
394    fn cli_spelling(long: String, short: Option<char>, short_aliases: &'static [char]) -> SourceInfo {
395        SourceInfo::Named { long, short, short_aliases }
396    }
397}
398
399impl CliSpelling for Assigned {
400    fn cli_spelling(name: String, _: Option<char>, _: &'static [char]) -> SourceInfo {
401        SourceInfo::Assigned { name }
402    }
403}
404
405impl<Mode, Shape: CliShape, Spelling: CliSpelling> NamedSource<Mode, Shape, Spelling> {
406    fn describe(&self, name: &'static str, _: &mut usize) -> ArgumentInfo {
407        let long = self.long.map_or_else(|| name.replace('_', "-"), str::to_owned);
408        ArgumentInfo {
409            name,
410            source: Spelling::cli_spelling(long, self.short, self.short_aliases),
411            fallback: self.fallback,
412            arity: Shape::ARITY,
413            doc: self.doc,
414            part_of: None,
415            delimiter: None,
416        }
417    }
418}
419
420/// Takes a list's words after its spelling, each word split on a delimiter: `--peers a,b` and
421/// `PEERS=a,b` both give two values.
422///
423/// It supplies only a `Vec`, the one arity a word that splits can fill.
424#[derive(Clone, Copy, Debug)]
425pub struct DelimitedSource<Mode = NoFallback, Spelling = Options> {
426    source: NamedSource<Mode, Many, Spelling>,
427    delimiter: char,
428}
429
430impl<Mode, Spelling> NamedSource<Mode, Many, Spelling> {
431    /// Splits every word, from the command line, the environment, or the default, on `delimiter`.
432    pub fn delimiter(self, delimiter: char) -> DelimitedSource<Mode, Spelling> {
433        DelimitedSource { source: self, delimiter }
434    }
435}
436
437impl<Mode, Spelling: CliSpelling> DelimitedSource<Mode, Spelling> {
438    fn describe(&self, name: &'static str, positions: &mut usize) -> ArgumentInfo {
439        ArgumentInfo { delimiter: Some(self.delimiter), ..self.source.describe(name, positions) }
440    }
441}
442
443impl<Mode, Shape: CliShape> PositionalSource<Mode, Shape> {
444    fn describe(&self, name: &'static str, positions: &mut usize) -> ArgumentInfo {
445        let index = *positions;
446        *positions += 1;
447        ArgumentInfo {
448            name,
449            source: SourceInfo::Positional { index },
450            fallback: self.fallback,
451            arity: Shape::ARITY,
452            doc: self.doc,
453            part_of: None,
454            delimiter: None,
455        }
456    }
457}
458
459/// Lets each shape of source supply its argument for any value, and decodes it by shape: the value
460/// is the interpreter's to read from a word, so the source states only how many words it takes.
461macro_rules! shaped_sources {
462    ($([$($generic:ident),*] $source:ty, $shape:ident => $argument:ty;)*) => {
463        $(
464            impl<Mode, Value $(, $generic: CliSpelling)*> CliSourceFor<$argument> for $source {
465                fn cli_describe(&self, name: &'static str, positions: &mut usize, out: &mut Vec<ArgumentInfo>) {
466                    out.push(self.describe(name, positions));
467                }
468            }
469
470            impl<Mode, Value, Decoder, Error $(, $generic)*> CliSourceDecode<$argument, Decoder, Error> for $source
471            where
472                Decoder: CliWordsAlg + CliWordAlg<Value, Decoder::Word, Error = Error>,
473            {
474                fn cli_decode_source(
475                    &self,
476                    arguments: &mut &[ArgumentInfo],
477                    decoder: &Decoder,
478                ) -> Result<$argument, CliArgumentError<Error>> {
479                    let argument = next(arguments);
480                    $shape(argument.name, &words(argument, decoder), decoder)
481                }
482            }
483        )*
484    };
485}
486
487shaped_sources! {
488    [] PositionalSource<Mode, Whole>, one => Value;
489    [] PositionalSource<Mode, Optional>, optional => Option<Value>;
490    [] PositionalSource<Mode, Many>, many => Vec<Value>;
491    [Spelling] NamedSource<Mode, Whole, Spelling>, one => Value;
492    [Spelling] NamedSource<Mode, Optional, Spelling>, optional => Option<Value>;
493    [Spelling] NamedSource<Mode, Many, Spelling>, many => Vec<Value>;
494    [Spelling] DelimitedSource<Mode, Spelling>, many => Vec<Value>;
495}
496
497/// Reads exactly one value from `words`.
498fn one<Value, Decoder, Word, Error>(
499    name: &'static str,
500    words: &[Word],
501    decoder: &Decoder,
502) -> Result<Value, CliArgumentError<Error>>
503where
504    Decoder: CliWordAlg<Value, Word, Error = Error>,
505{
506    match words {
507        [] => Err(CliArgumentError::Missing(name)),
508        [word] => decoder.cli_word(word).map_err(|error| CliArgumentError::Word(name, error)),
509        _ => Err(CliArgumentError::Repeated(name)),
510    }
511}
512
513/// Reads at most one value from `words`.
514fn optional<Value, Decoder, Word, Error>(
515    name: &'static str,
516    words: &[Word],
517    decoder: &Decoder,
518) -> Result<Option<Value>, CliArgumentError<Error>>
519where
520    Decoder: CliWordAlg<Value, Word, Error = Error>,
521{
522    if words.is_empty() { Ok(None) } else { one(name, words, decoder).map(Some) }
523}
524
525/// Reads one value from each of `words`, in order.
526fn many<Value, Decoder, Word, Error>(
527    name: &'static str,
528    words: &[Word],
529    decoder: &Decoder,
530) -> Result<Vec<Value>, CliArgumentError<Error>>
531where
532    Decoder: CliWordAlg<Value, Word, Error = Error>,
533{
534    words.iter().map(|word| decoder.cli_word(word).map_err(|error| CliArgumentError::Word(name, error))).collect()
535}
536
537/// A switch, and a switch read from the environment as well: as the command line says, else as the
538/// variable says, else off. Its bare spelling, which an interpreter answers as an empty word,
539/// decodes on, and a long spelling may state a truth either way: `--dev=false`. A variable set to
540/// nothing states nothing, so a cleared variable leaves the switch off.
541macro_rules! switches {
542    ($($mode:ident),*) => {
543        $(
544            impl CliSourceFor<bool> for NamedSource<$mode, Switch> {
545                fn cli_describe(&self, name: &'static str, positions: &mut usize, out: &mut Vec<ArgumentInfo>) {
546                    out.push(self.describe(name, positions));
547                }
548            }
549
550            impl<Decoder, Error> CliSourceDecode<bool, Decoder, Error> for NamedSource<$mode, Switch>
551            where
552                Decoder: CliWordsAlg + CliWordAlg<bool, Decoder::Word, Error = Error>,
553                Decoder::Word: AsRef<OsStr>,
554            {
555                fn cli_decode_source(
556                    &self,
557                    arguments: &mut &[ArgumentInfo],
558                    decoder: &Decoder,
559                ) -> Result<bool, CliArgumentError<Error>> {
560                    let argument = next(arguments);
561                    let mut words = decoder.cli_words(argument);
562                    if words.is_empty() {
563                        let env = argument.fallback.env.and_then(|name| decoder.cli_env(name));
564                        words.extend(env.filter(|word| !word.as_ref().is_empty()));
565                    }
566                    if words.is_empty() { Ok(false) } else { one(argument.name, &words, decoder) }
567                }
568            }
569        )*
570    };
571}
572
573switches!(NoFallback, WithEnv);
574
575/// An option with a value written only in its own word: absent, given bare, which an interpreter
576/// answers as an empty word, or given a value.
577impl<Value> CliSourceFor<Option<Option<Value>>> for NamedSource<NoFallback, OptionalValue> {
578    fn cli_describe(&self, name: &'static str, positions: &mut usize, out: &mut Vec<ArgumentInfo>) {
579        out.push(self.describe(name, positions));
580    }
581}
582
583impl<Value, Decoder, Error> CliSourceDecode<Option<Option<Value>>, Decoder, Error>
584    for NamedSource<NoFallback, OptionalValue>
585where
586    Decoder: CliWordsAlg + CliWordAlg<Value, Decoder::Word, Error = Error>,
587    Decoder::Word: AsRef<OsStr>,
588{
589    fn cli_decode_source(
590        &self,
591        arguments: &mut &[ArgumentInfo],
592        decoder: &Decoder,
593    ) -> Result<Option<Option<Value>>, CliArgumentError<Error>> {
594        let argument = next(arguments);
595        match words(argument, decoder).as_slice() {
596            [] => Ok(None),
597            [word] if word.as_ref().is_empty() => Ok(Some(None)),
598            words => one(argument.name, words, decoder).map(|value| Some(Some(value))),
599        }
600    }
601}
602
603/// An alternative of a sum carrying no value: given by its spelling alone.
604impl CliSourceFor<()> for NamedSource<NoFallback, Switch> {
605    fn cli_describe(&self, name: &'static str, positions: &mut usize, out: &mut Vec<ArgumentInfo>) {
606        out.push(self.describe(name, positions));
607    }
608}
609
610impl<Decoder, Error> CliSourceDecode<(), Decoder, Error> for NamedSource<NoFallback, Switch>
611where
612    Decoder: CliWordsAlg,
613{
614    fn cli_decode_source(
615        &self,
616        arguments: &mut &[ArgumentInfo],
617        decoder: &Decoder,
618    ) -> Result<(), CliArgumentError<Error>> {
619        let argument = next(arguments);
620        match words(argument, decoder).len() {
621            0 => Err(CliArgumentError::Missing(argument.name)),
622            1 => Ok(()),
623            _ => Err(CliArgumentError::Repeated(argument.name)),
624        }
625    }
626}
627
628/// States that a declared product of sources supplies exactly the operation arguments `Args`.
629///
630/// The sources are written in the order of the operation's arguments, one each, so a missing,
631/// extra, or mismatched source fails to compile.
632#[diagnostic::on_unimplemented(
633    message = "the declared sources `{Self}` do not supply the operation arguments `{Args}`",
634    note = "declare one source per operation argument, in order, with `.arg(name, self.positional(..))` or `.arg(name, self.named(..))`"
635)]
636pub trait CliSources<Args> {
637    /// Describes every argument, named by the operation's `names`, in order.
638    fn cli_arguments(&self, names: &'static [&'static str]) -> Vec<ArgumentInfo>;
639}
640
641/// States that every source in a product is named.
642///
643/// A subtree's global arguments are named: a positional one would take positions every command of
644/// the subtree already numbers for its own arguments. A product's fields and a sum's alternatives
645/// are named for the same reason.
646#[diagnostic::on_unimplemented(
647    message = "the sources `{Self}` are not all named",
648    note = "declare global arguments, product fields, and alternatives with `self.named(..)`"
649)]
650pub trait CliNamedSources {}
651
652impl CliNamedSources for () {}
653
654impl<Previous, Mode, Shape, Spelling> CliNamedSources for (Previous, NamedSource<Mode, Shape, Spelling>) where
655    Previous: CliNamedSources
656{
657}
658
659/// Marks a source spelled by name, which is what a product's field or a sum's alternative takes.
660#[diagnostic::on_unimplemented(
661    message = "`{Self}` is not a named source",
662    note = "declare a product's fields and a sum's alternatives with `self.named(..)`"
663)]
664pub trait CliNamedSource {}
665
666impl<Mode, Shape, Spelling> CliNamedSource for NamedSource<Mode, Shape, Spelling> {}
667
668impl<Mode, Spelling> CliNamedSource for DelimitedSource<Mode, Spelling> {}
669
670impl<Previous, Mode, Spelling> CliNamedSources for (Previous, DelimitedSource<Mode, Spelling>) where
671    Previous: CliNamedSources
672{
673}
674
675/// Answers the words given for one argument and the environment it falls back to.
676///
677/// An interpreter reads both from what it was given. For a switch, it answers one word per
678/// occurrence.
679pub trait CliWordsAlg {
680    /// What one word is: text, an operating system string, bytes. The interpreter chooses, so a
681    /// word the command line gives reaches the value it denotes unchanged.
682    type Word;
683
684    /// Returns the words the command line gives for `argument`, in the order they were given.
685    fn cli_words(&self, argument: &ArgumentInfo) -> Vec<Self::Word>;
686
687    /// Returns the value of the environment variable `name`, if it is set.
688    fn cli_env(&self, name: &str) -> Option<Self::Word>;
689
690    /// Returns the word a declared default spells.
691    fn cli_default(&self, default: &'static str) -> Self::Word;
692
693    /// Splits `word` on `delimiter`, for a list one word gives.
694    fn cli_split(&self, word: Self::Word, delimiter: char) -> Vec<Self::Word>;
695}
696
697/// Returns the words that make `argument`: the command line's, else the environment's, else the
698/// default.
699pub(crate) fn words<Decoder: CliWordsAlg>(argument: &ArgumentInfo, decoder: &Decoder) -> Vec<Decoder::Word> {
700    let mut words = decoder.cli_words(argument);
701    if words.is_empty() {
702        let Fallback { env, default } = argument.fallback;
703        words = env
704            .and_then(|name| decoder.cli_env(name))
705            .or_else(|| default.map(|default| decoder.cli_default(default)))
706            .into_iter()
707            .collect();
708    }
709    match argument.delimiter {
710        Some(delimiter) => words.into_iter().flat_map(|word| decoder.cli_split(word, delimiter)).collect(),
711        None => words,
712    }
713}
714
715/// Decodes the operation arguments `Args` through declared sources, with `Decoder`.
716pub trait CliDecodeSources<Args, Decoder, Error> {
717    /// Decodes every argument from the words `decoder` gives for it, reading the arguments these
718    /// sources were described as, in order.
719    ///
720    /// # Errors
721    ///
722    /// Answers with the first argument whose words do not make its value.
723    fn cli_decode(&self, arguments: &[ArgumentInfo], decoder: &Decoder) -> Result<Args, CliArgumentError<Error>>;
724}
725
726impl CliSources<()> for () {
727    fn cli_arguments(&self, _: &'static [&'static str]) -> Vec<ArgumentInfo> {
728        Vec::new()
729    }
730}
731
732impl<Decoder, Error> CliDecodeSources<(), Decoder, Error> for () {
733    fn cli_decode(&self, _: &[ArgumentInfo], _: &Decoder) -> Result<(), CliArgumentError<Error>> {
734        Ok(())
735    }
736}
737
738/// Spells a product of sources as `.argument` builds it: `((((), S1), S2), S3)`.
739macro_rules! nested {
740    ($inner:ty;) => { $inner };
741    ($inner:ty; $head:ident $($tail:ident)*) => { nested!(($inner, $head); $($tail)*) };
742}
743
744/// Destructures a product of sources the same way, binding each source to a name.
745macro_rules! nested_pattern {
746    ($inner:tt;) => { $inner };
747    ($inner:tt; $head:ident $($tail:ident)*) => { nested_pattern!(($inner, $head); $($tail)*) };
748}
749
750pub(crate) use {nested, nested_pattern};
751
752macro_rules! sources {
753    ($(($source:ident, $argument:ident, $value:ident, $index:tt)),+) => {
754        impl<$($source, $argument),+> CliSources<($($argument,)+)> for nested!((); $($source)+)
755        where
756            $($source: CliSourceFor<$argument>,)+
757        {
758            fn cli_arguments(&self, names: &'static [&'static str]) -> Vec<ArgumentInfo> {
759                let nested_pattern!((); $($value)+) = self;
760                let mut positions = 0;
761                let mut out = Vec::new();
762                $(CliSourceFor::<$argument>::cli_describe($value, names[$index], &mut positions, &mut out);)+
763                out
764            }
765        }
766
767        impl<Decoder, Error, $($source, $argument),+> CliDecodeSources<($($argument,)+), Decoder, Error>
768            for nested!((); $($source)+)
769        where
770            $($source: CliSourceDecode<$argument, Decoder, Error>,)+
771        {
772            fn cli_decode(
773                &self,
774                mut arguments: &[ArgumentInfo],
775                decoder: &Decoder,
776            ) -> Result<($($argument,)+), CliArgumentError<Error>> {
777                let nested_pattern!((); $($value)+) = self;
778                Ok(($($value.cli_decode_source(&mut arguments, decoder)?,)+))
779            }
780        }
781    };
782}
783
784sources!((S0, A0, s0, 0));
785sources!((S0, A0, s0, 0), (S1, A1, s1, 1));
786sources!((S0, A0, s0, 0), (S1, A1, s1, 1), (S2, A2, s2, 2));
787sources!((S0, A0, s0, 0), (S1, A1, s1, 1), (S2, A2, s2, 2), (S3, A3, s3, 3));
788sources!((S0, A0, s0, 0), (S1, A1, s1, 1), (S2, A2, s2, 2), (S3, A3, s3, 3), (S4, A4, s4, 4));
789sources!((S0, A0, s0, 0), (S1, A1, s1, 1), (S2, A2, s2, 2), (S3, A3, s3, 3), (S4, A4, s4, 4), (S5, A5, s5, 5));
790sources!(
791    (S0, A0, s0, 0),
792    (S1, A1, s1, 1),
793    (S2, A2, s2, 2),
794    (S3, A3, s3, 3),
795    (S4, A4, s4, 4),
796    (S5, A5, s5, 5),
797    (S6, A6, s6, 6)
798);
799sources!(
800    (S0, A0, s0, 0),
801    (S1, A1, s1, 1),
802    (S2, A2, s2, 2),
803    (S3, A3, s3, 3),
804    (S4, A4, s4, 4),
805    (S5, A5, s5, 5),
806    (S6, A6, s6, 6),
807    (S7, A7, s7, 7)
808);
809sources!(
810    (S0, A0, s0, 0),
811    (S1, A1, s1, 1),
812    (S2, A2, s2, 2),
813    (S3, A3, s3, 3),
814    (S4, A4, s4, 4),
815    (S5, A5, s5, 5),
816    (S6, A6, s6, 6),
817    (S7, A7, s7, 7),
818    (S8, A8, s8, 8)
819);
820sources!(
821    (S0, A0, s0, 0),
822    (S1, A1, s1, 1),
823    (S2, A2, s2, 2),
824    (S3, A3, s3, 3),
825    (S4, A4, s4, 4),
826    (S5, A5, s5, 5),
827    (S6, A6, s6, 6),
828    (S7, A7, s7, 7),
829    (S8, A8, s8, 8),
830    (S9, A9, s9, 9)
831);
832sources!(
833    (S0, A0, s0, 0),
834    (S1, A1, s1, 1),
835    (S2, A2, s2, 2),
836    (S3, A3, s3, 3),
837    (S4, A4, s4, 4),
838    (S5, A5, s5, 5),
839    (S6, A6, s6, 6),
840    (S7, A7, s7, 7),
841    (S8, A8, s8, 8),
842    (S9, A9, s9, 9),
843    (S10, A10, s10, 10)
844);
845sources!(
846    (S0, A0, s0, 0),
847    (S1, A1, s1, 1),
848    (S2, A2, s2, 2),
849    (S3, A3, s3, 3),
850    (S4, A4, s4, 4),
851    (S5, A5, s5, 5),
852    (S6, A6, s6, 6),
853    (S7, A7, s7, 7),
854    (S8, A8, s8, 8),
855    (S9, A9, s9, 9),
856    (S10, A10, s10, 10),
857    (S11, A11, s11, 11)
858);
859sources!(
860    (S0, A0, s0, 0),
861    (S1, A1, s1, 1),
862    (S2, A2, s2, 2),
863    (S3, A3, s3, 3),
864    (S4, A4, s4, 4),
865    (S5, A5, s5, 5),
866    (S6, A6, s6, 6),
867    (S7, A7, s7, 7),
868    (S8, A8, s8, 8),
869    (S9, A9, s9, 9),
870    (S10, A10, s10, 10),
871    (S11, A11, s11, 11),
872    (S12, A12, s12, 12)
873);
874sources!(
875    (S0, A0, s0, 0),
876    (S1, A1, s1, 1),
877    (S2, A2, s2, 2),
878    (S3, A3, s3, 3),
879    (S4, A4, s4, 4),
880    (S5, A5, s5, 5),
881    (S6, A6, s6, 6),
882    (S7, A7, s7, 7),
883    (S8, A8, s8, 8),
884    (S9, A9, s9, 9),
885    (S10, A10, s10, 10),
886    (S11, A11, s11, 11),
887    (S12, A12, s12, 12),
888    (S13, A13, s13, 13)
889);
890sources!(
891    (S0, A0, s0, 0),
892    (S1, A1, s1, 1),
893    (S2, A2, s2, 2),
894    (S3, A3, s3, 3),
895    (S4, A4, s4, 4),
896    (S5, A5, s5, 5),
897    (S6, A6, s6, 6),
898    (S7, A7, s7, 7),
899    (S8, A8, s8, 8),
900    (S9, A9, s9, 9),
901    (S10, A10, s10, 10),
902    (S11, A11, s11, 11),
903    (S12, A12, s12, 12),
904    (S13, A13, s13, 13),
905    (S14, A14, s14, 14)
906);
907sources!(
908    (S0, A0, s0, 0),
909    (S1, A1, s1, 1),
910    (S2, A2, s2, 2),
911    (S3, A3, s3, 3),
912    (S4, A4, s4, 4),
913    (S5, A5, s5, 5),
914    (S6, A6, s6, 6),
915    (S7, A7, s7, 7),
916    (S8, A8, s8, 8),
917    (S9, A9, s9, 9),
918    (S10, A10, s10, 10),
919    (S11, A11, s11, 11),
920    (S12, A12, s12, 12),
921    (S13, A13, s13, 13),
922    (S14, A14, s14, 14),
923    (S15, A15, s15, 15)
924);