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: on when given, else as the variable
538/// says. Its own spelling, which an interpreter answers as an empty word, decodes on.
539macro_rules! switches {
540    ($($mode:ident),*) => {
541        $(
542            impl CliSourceFor<bool> for NamedSource<$mode, Switch> {
543                fn cli_describe(&self, name: &'static str, positions: &mut usize, out: &mut Vec<ArgumentInfo>) {
544                    out.push(self.describe(name, positions));
545                }
546            }
547
548            impl<Decoder, Error> CliSourceDecode<bool, Decoder, Error> for NamedSource<$mode, Switch>
549            where
550                Decoder: CliWordsAlg + CliWordAlg<bool, Decoder::Word, Error = Error>,
551            {
552                fn cli_decode_source(
553                    &self,
554                    arguments: &mut &[ArgumentInfo],
555                    decoder: &Decoder,
556                ) -> Result<bool, CliArgumentError<Error>> {
557                    let argument = next(arguments);
558                    let words = words(argument, decoder);
559                    if words.is_empty() { Ok(false) } else { one(argument.name, &words, decoder) }
560                }
561            }
562        )*
563    };
564}
565
566switches!(NoFallback, WithEnv);
567
568/// An option with a value written only in its own word: absent, given bare, which an interpreter
569/// answers as an empty word, or given a value.
570impl<Value> CliSourceFor<Option<Option<Value>>> for NamedSource<NoFallback, OptionalValue> {
571    fn cli_describe(&self, name: &'static str, positions: &mut usize, out: &mut Vec<ArgumentInfo>) {
572        out.push(self.describe(name, positions));
573    }
574}
575
576impl<Value, Decoder, Error> CliSourceDecode<Option<Option<Value>>, Decoder, Error>
577    for NamedSource<NoFallback, OptionalValue>
578where
579    Decoder: CliWordsAlg + CliWordAlg<Value, Decoder::Word, Error = Error>,
580    Decoder::Word: AsRef<OsStr>,
581{
582    fn cli_decode_source(
583        &self,
584        arguments: &mut &[ArgumentInfo],
585        decoder: &Decoder,
586    ) -> Result<Option<Option<Value>>, CliArgumentError<Error>> {
587        let argument = next(arguments);
588        match words(argument, decoder).as_slice() {
589            [] => Ok(None),
590            [word] if word.as_ref().is_empty() => Ok(Some(None)),
591            words => one(argument.name, words, decoder).map(|value| Some(Some(value))),
592        }
593    }
594}
595
596/// An alternative of a sum carrying no value: given by its spelling alone.
597impl CliSourceFor<()> for NamedSource<NoFallback, Switch> {
598    fn cli_describe(&self, name: &'static str, positions: &mut usize, out: &mut Vec<ArgumentInfo>) {
599        out.push(self.describe(name, positions));
600    }
601}
602
603impl<Decoder, Error> CliSourceDecode<(), Decoder, Error> for NamedSource<NoFallback, Switch>
604where
605    Decoder: CliWordsAlg,
606{
607    fn cli_decode_source(
608        &self,
609        arguments: &mut &[ArgumentInfo],
610        decoder: &Decoder,
611    ) -> Result<(), CliArgumentError<Error>> {
612        let argument = next(arguments);
613        match words(argument, decoder).len() {
614            0 => Err(CliArgumentError::Missing(argument.name)),
615            1 => Ok(()),
616            _ => Err(CliArgumentError::Repeated(argument.name)),
617        }
618    }
619}
620
621/// States that a declared product of sources supplies exactly the operation arguments `Args`.
622///
623/// The sources are written in the order of the operation's arguments, one each, so a missing,
624/// extra, or mismatched source fails to compile.
625#[diagnostic::on_unimplemented(
626    message = "the declared sources `{Self}` do not supply the operation arguments `{Args}`",
627    note = "declare one source per operation argument, in order, with `.arg(self.positional(..))` or `.arg(self.named(..))`"
628)]
629pub trait CliSources<Args> {
630    /// Describes every argument, named by the operation's `names`, in order.
631    fn cli_arguments(&self, names: &'static [&'static str]) -> Vec<ArgumentInfo>;
632}
633
634/// States that every source in a product is named.
635///
636/// A subtree's global arguments are named: a positional one would take positions every command of
637/// the subtree already numbers for its own arguments. A product's fields and a sum's alternatives
638/// are named for the same reason.
639#[diagnostic::on_unimplemented(
640    message = "the sources `{Self}` are not all named",
641    note = "declare global arguments, product fields, and alternatives with `self.named(..)`"
642)]
643pub trait CliNamedSources {}
644
645impl CliNamedSources for () {}
646
647impl<Previous, Mode, Shape, Spelling> CliNamedSources for (Previous, NamedSource<Mode, Shape, Spelling>) where
648    Previous: CliNamedSources
649{
650}
651
652/// Marks a source spelled by name, which is what a product's field or a sum's alternative takes.
653#[diagnostic::on_unimplemented(
654    message = "`{Self}` is not a named source",
655    note = "declare a product's fields and a sum's alternatives with `self.named(..)`"
656)]
657pub trait CliNamedSource {}
658
659impl<Mode, Shape, Spelling> CliNamedSource for NamedSource<Mode, Shape, Spelling> {}
660
661impl<Mode, Spelling> CliNamedSource for DelimitedSource<Mode, Spelling> {}
662
663impl<Previous, Mode, Spelling> CliNamedSources for (Previous, DelimitedSource<Mode, Spelling>) where
664    Previous: CliNamedSources
665{
666}
667
668/// Answers the words given for one argument and the environment it falls back to.
669///
670/// An interpreter reads both from what it was given. For a switch, it answers one word per
671/// occurrence.
672pub trait CliWordsAlg {
673    /// What one word is: text, an operating system string, bytes. The interpreter chooses, so a
674    /// word the command line gives reaches the value it denotes unchanged.
675    type Word;
676
677    /// Returns the words the command line gives for `argument`, in the order they were given.
678    fn cli_words(&self, argument: &ArgumentInfo) -> Vec<Self::Word>;
679
680    /// Returns the value of the environment variable `name`, if it is set.
681    fn cli_env(&self, name: &str) -> Option<Self::Word>;
682
683    /// Returns the word a declared default spells.
684    fn cli_default(&self, default: &'static str) -> Self::Word;
685
686    /// Splits `word` on `delimiter`, for a list one word gives.
687    fn cli_split(&self, word: Self::Word, delimiter: char) -> Vec<Self::Word>;
688}
689
690/// Returns the words that make `argument`: the command line's, else the environment's, else the
691/// default.
692pub(crate) fn words<Decoder: CliWordsAlg>(argument: &ArgumentInfo, decoder: &Decoder) -> Vec<Decoder::Word> {
693    let mut words = decoder.cli_words(argument);
694    if words.is_empty() {
695        let Fallback { env, default } = argument.fallback;
696        words = env
697            .and_then(|name| decoder.cli_env(name))
698            .or_else(|| default.map(|default| decoder.cli_default(default)))
699            .into_iter()
700            .collect();
701    }
702    match argument.delimiter {
703        Some(delimiter) => words.into_iter().flat_map(|word| decoder.cli_split(word, delimiter)).collect(),
704        None => words,
705    }
706}
707
708/// Decodes the operation arguments `Args` through declared sources, with `Decoder`.
709pub trait CliDecodeSources<Args, Decoder, Error> {
710    /// Decodes every argument from the words `decoder` gives for it, reading the arguments these
711    /// sources were described as, in order.
712    ///
713    /// # Errors
714    ///
715    /// Answers with the first argument whose words do not make its value.
716    fn cli_decode(&self, arguments: &[ArgumentInfo], decoder: &Decoder) -> Result<Args, CliArgumentError<Error>>;
717}
718
719impl CliSources<()> for () {
720    fn cli_arguments(&self, _: &'static [&'static str]) -> Vec<ArgumentInfo> {
721        Vec::new()
722    }
723}
724
725impl<Decoder, Error> CliDecodeSources<(), Decoder, Error> for () {
726    fn cli_decode(&self, _: &[ArgumentInfo], _: &Decoder) -> Result<(), CliArgumentError<Error>> {
727        Ok(())
728    }
729}
730
731/// Spells a product of sources as `.argument` builds it: `((((), S1), S2), S3)`.
732macro_rules! nested {
733    ($inner:ty;) => { $inner };
734    ($inner:ty; $head:ident $($tail:ident)*) => { nested!(($inner, $head); $($tail)*) };
735}
736
737/// Destructures a product of sources the same way, binding each source to a name.
738macro_rules! nested_pattern {
739    ($inner:tt;) => { $inner };
740    ($inner:tt; $head:ident $($tail:ident)*) => { nested_pattern!(($inner, $head); $($tail)*) };
741}
742
743pub(crate) use {nested, nested_pattern};
744
745macro_rules! sources {
746    ($(($source:ident, $argument:ident, $value:ident, $index:tt)),+) => {
747        impl<$($source, $argument),+> CliSources<($($argument,)+)> for nested!((); $($source)+)
748        where
749            $($source: CliSourceFor<$argument>,)+
750        {
751            fn cli_arguments(&self, names: &'static [&'static str]) -> Vec<ArgumentInfo> {
752                let nested_pattern!((); $($value)+) = self;
753                let mut positions = 0;
754                let mut out = Vec::new();
755                $(CliSourceFor::<$argument>::cli_describe($value, names[$index], &mut positions, &mut out);)+
756                out
757            }
758        }
759
760        impl<Decoder, Error, $($source, $argument),+> CliDecodeSources<($($argument,)+), Decoder, Error>
761            for nested!((); $($source)+)
762        where
763            $($source: CliSourceDecode<$argument, Decoder, Error>,)+
764        {
765            fn cli_decode(
766                &self,
767                mut arguments: &[ArgumentInfo],
768                decoder: &Decoder,
769            ) -> Result<($($argument,)+), CliArgumentError<Error>> {
770                let nested_pattern!((); $($value)+) = self;
771                Ok(($($value.cli_decode_source(&mut arguments, decoder)?,)+))
772            }
773        }
774    };
775}
776
777sources!((S0, A0, s0, 0));
778sources!((S0, A0, s0, 0), (S1, A1, s1, 1));
779sources!((S0, A0, s0, 0), (S1, A1, s1, 1), (S2, A2, s2, 2));
780sources!((S0, A0, s0, 0), (S1, A1, s1, 1), (S2, A2, s2, 2), (S3, A3, s3, 3));
781sources!((S0, A0, s0, 0), (S1, A1, s1, 1), (S2, A2, s2, 2), (S3, A3, s3, 3), (S4, A4, s4, 4));
782sources!((S0, A0, s0, 0), (S1, A1, s1, 1), (S2, A2, s2, 2), (S3, A3, s3, 3), (S4, A4, s4, 4), (S5, A5, s5, 5));
783sources!(
784    (S0, A0, s0, 0),
785    (S1, A1, s1, 1),
786    (S2, A2, s2, 2),
787    (S3, A3, s3, 3),
788    (S4, A4, s4, 4),
789    (S5, A5, s5, 5),
790    (S6, A6, s6, 6)
791);
792sources!(
793    (S0, A0, s0, 0),
794    (S1, A1, s1, 1),
795    (S2, A2, s2, 2),
796    (S3, A3, s3, 3),
797    (S4, A4, s4, 4),
798    (S5, A5, s5, 5),
799    (S6, A6, s6, 6),
800    (S7, A7, s7, 7)
801);
802sources!(
803    (S0, A0, s0, 0),
804    (S1, A1, s1, 1),
805    (S2, A2, s2, 2),
806    (S3, A3, s3, 3),
807    (S4, A4, s4, 4),
808    (S5, A5, s5, 5),
809    (S6, A6, s6, 6),
810    (S7, A7, s7, 7),
811    (S8, A8, s8, 8)
812);
813sources!(
814    (S0, A0, s0, 0),
815    (S1, A1, s1, 1),
816    (S2, A2, s2, 2),
817    (S3, A3, s3, 3),
818    (S4, A4, s4, 4),
819    (S5, A5, s5, 5),
820    (S6, A6, s6, 6),
821    (S7, A7, s7, 7),
822    (S8, A8, s8, 8),
823    (S9, A9, s9, 9)
824);
825sources!(
826    (S0, A0, s0, 0),
827    (S1, A1, s1, 1),
828    (S2, A2, s2, 2),
829    (S3, A3, s3, 3),
830    (S4, A4, s4, 4),
831    (S5, A5, s5, 5),
832    (S6, A6, s6, 6),
833    (S7, A7, s7, 7),
834    (S8, A8, s8, 8),
835    (S9, A9, s9, 9),
836    (S10, A10, s10, 10)
837);
838sources!(
839    (S0, A0, s0, 0),
840    (S1, A1, s1, 1),
841    (S2, A2, s2, 2),
842    (S3, A3, s3, 3),
843    (S4, A4, s4, 4),
844    (S5, A5, s5, 5),
845    (S6, A6, s6, 6),
846    (S7, A7, s7, 7),
847    (S8, A8, s8, 8),
848    (S9, A9, s9, 9),
849    (S10, A10, s10, 10),
850    (S11, A11, s11, 11)
851);
852sources!(
853    (S0, A0, s0, 0),
854    (S1, A1, s1, 1),
855    (S2, A2, s2, 2),
856    (S3, A3, s3, 3),
857    (S4, A4, s4, 4),
858    (S5, A5, s5, 5),
859    (S6, A6, s6, 6),
860    (S7, A7, s7, 7),
861    (S8, A8, s8, 8),
862    (S9, A9, s9, 9),
863    (S10, A10, s10, 10),
864    (S11, A11, s11, 11),
865    (S12, A12, s12, 12)
866);
867sources!(
868    (S0, A0, s0, 0),
869    (S1, A1, s1, 1),
870    (S2, A2, s2, 2),
871    (S3, A3, s3, 3),
872    (S4, A4, s4, 4),
873    (S5, A5, s5, 5),
874    (S6, A6, s6, 6),
875    (S7, A7, s7, 7),
876    (S8, A8, s8, 8),
877    (S9, A9, s9, 9),
878    (S10, A10, s10, 10),
879    (S11, A11, s11, 11),
880    (S12, A12, s12, 12),
881    (S13, A13, s13, 13)
882);
883sources!(
884    (S0, A0, s0, 0),
885    (S1, A1, s1, 1),
886    (S2, A2, s2, 2),
887    (S3, A3, s3, 3),
888    (S4, A4, s4, 4),
889    (S5, A5, s5, 5),
890    (S6, A6, s6, 6),
891    (S7, A7, s7, 7),
892    (S8, A8, s8, 8),
893    (S9, A9, s9, 9),
894    (S10, A10, s10, 10),
895    (S11, A11, s11, 11),
896    (S12, A12, s12, 12),
897    (S13, A13, s13, 13),
898    (S14, A14, s14, 14)
899);
900sources!(
901    (S0, A0, s0, 0),
902    (S1, A1, s1, 1),
903    (S2, A2, s2, 2),
904    (S3, A3, s3, 3),
905    (S4, A4, s4, 4),
906    (S5, A5, s5, 5),
907    (S6, A6, s6, 6),
908    (S7, A7, s7, 7),
909    (S8, A8, s8, 8),
910    (S9, A9, s9, 9),
911    (S10, A10, s10, 10),
912    (S11, A11, s11, 11),
913    (S12, A12, s12, 12),
914    (S13, A13, s13, 13),
915    (S14, A14, s14, 14),
916    (S15, A15, s15, 15)
917);