use core::marker::PhantomData;
use std::ffi::OsStr;
use crate::{Arity, CliArgumentError, CliWordAlg};
#[derive(Clone, Copy, Debug, Default)]
pub struct NoFallback;
#[derive(Clone, Copy, Debug, Default)]
pub struct WithEnv;
#[derive(Clone, Copy, Debug, Default)]
pub struct WithFallback;
pub trait EnvFallback {
type WithEnv;
}
impl EnvFallback for NoFallback {
type WithEnv = WithEnv;
}
impl EnvFallback for WithEnv {
type WithEnv = WithEnv;
}
impl EnvFallback for WithFallback {
type WithEnv = WithFallback;
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Fallback {
pub env: Option<&'static str>,
pub default: Option<&'static str>,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Whole;
#[derive(Clone, Copy, Debug, Default)]
pub struct Optional;
#[derive(Clone, Copy, Debug, Default)]
pub struct Many;
#[derive(Clone, Copy, Debug, Default)]
pub struct Switch;
#[derive(Clone, Copy, Debug, Default)]
pub struct OptionalValue;
pub trait CliShape {
const ARITY: Arity;
}
impl CliShape for Whole {
const ARITY: Arity = Arity::One;
}
impl CliShape for Optional {
const ARITY: Arity = Arity::Optional;
}
impl CliShape for Many {
const ARITY: Arity = Arity::Many;
}
impl CliShape for OptionalValue {
const ARITY: Arity = Arity::OptionalValue;
}
impl CliShape for Switch {
const ARITY: Arity = Arity::Presence;
}
#[derive(Clone, Copy, Debug)]
pub struct PositionalSource<Mode = NoFallback, Shape = Whole> {
doc: &'static str,
fallback: Fallback,
mode: PhantomData<fn() -> (Mode, Shape)>,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Options;
#[derive(Clone, Copy, Debug, Default)]
pub struct Assigned;
#[derive(Clone, Copy, Debug)]
pub struct NamedSource<Mode = NoFallback, Shape = Whole, Spelling = Options> {
long: Option<&'static str>,
short: Option<char>,
short_aliases: &'static [char],
doc: &'static str,
fallback: Fallback,
mode: Markers<Mode, Shape, Spelling>,
}
type Markers<Mode, Shape, Spelling> = PhantomData<fn() -> (Mode, Shape, Spelling)>;
impl PositionalSource {
pub fn new(doc: &'static str) -> Self {
Self { doc, fallback: Fallback::default(), mode: PhantomData }
}
}
impl<Mode> PositionalSource<Mode> {
pub fn optional(self) -> PositionalSource<Mode, Optional> {
PositionalSource { doc: self.doc, fallback: self.fallback, mode: PhantomData }
}
pub fn many(self) -> PositionalSource<Mode, Many> {
PositionalSource { doc: self.doc, fallback: self.fallback, mode: PhantomData }
}
}
impl<Mode, Shape> PositionalSource<Mode, Shape> {
pub fn env(self, name: &'static str) -> PositionalSource<Mode::WithEnv, Shape>
where
Mode: EnvFallback,
{
PositionalSource { doc: self.doc, fallback: Fallback { env: Some(name), ..self.fallback }, mode: PhantomData }
}
pub fn default(self, word: &'static str) -> PositionalSource<WithFallback, Shape> {
PositionalSource {
doc: self.doc,
fallback: Fallback { default: Some(word), ..self.fallback },
mode: PhantomData,
}
}
}
impl NamedSource {
pub fn new(doc: &'static str) -> Self {
Self { long: None, short: None, short_aliases: &[], doc, fallback: Fallback::default(), mode: PhantomData }
}
}
impl<Mode> NamedSource<Mode> {
pub fn assigned(self, name: &'static str) -> NamedSource<Mode, Whole, Assigned> {
NamedSource {
long: Some(name),
short: None,
short_aliases: &[],
doc: self.doc,
fallback: self.fallback,
mode: PhantomData,
}
}
pub fn switch(self) -> NamedSource<Mode, Switch> {
NamedSource {
long: self.long,
short: self.short,
short_aliases: self.short_aliases,
doc: self.doc,
fallback: self.fallback,
mode: PhantomData,
}
}
pub fn optional_value(self) -> NamedSource<Mode, OptionalValue> {
NamedSource {
long: self.long,
short: self.short,
short_aliases: self.short_aliases,
doc: self.doc,
fallback: self.fallback,
mode: PhantomData,
}
}
}
impl<Mode, Spelling> NamedSource<Mode, Whole, Spelling> {
pub fn optional(self) -> NamedSource<Mode, Optional, Spelling> {
NamedSource {
long: self.long,
short: self.short,
short_aliases: self.short_aliases,
doc: self.doc,
fallback: self.fallback,
mode: PhantomData,
}
}
pub fn many(self) -> NamedSource<Mode, Many, Spelling> {
NamedSource {
long: self.long,
short: self.short,
short_aliases: self.short_aliases,
doc: self.doc,
fallback: self.fallback,
mode: PhantomData,
}
}
}
impl<Mode, Shape> NamedSource<Mode, Shape> {
#[must_use]
pub fn long(self, long: &'static str) -> Self {
Self { long: Some(long), ..self }
}
#[must_use]
pub fn short(self, short: char) -> Self {
Self { short: Some(short), ..self }
}
#[must_use]
pub fn short_aliases(self, aliases: &'static [char]) -> Self {
Self { short_aliases: aliases, ..self }
}
}
impl<Mode, Shape, Spelling> NamedSource<Mode, Shape, Spelling> {
pub fn env(self, name: &'static str) -> NamedSource<Mode::WithEnv, Shape, Spelling>
where
Mode: EnvFallback,
{
let fallback = Fallback { env: Some(name), ..self.fallback };
NamedSource {
long: self.long,
short: self.short,
short_aliases: self.short_aliases,
doc: self.doc,
fallback,
mode: PhantomData,
}
}
pub fn default(self, word: &'static str) -> NamedSource<WithFallback, Shape, Spelling> {
let fallback = Fallback { default: Some(word), ..self.fallback };
NamedSource {
long: self.long,
short: self.short,
short_aliases: self.short_aliases,
doc: self.doc,
fallback,
mode: PhantomData,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SourceInfo {
Positional {
index: usize,
},
Assigned {
name: String,
},
Named {
long: String,
short: Option<char>,
short_aliases: &'static [char],
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Part {
Product(&'static str),
Sum(&'static str),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ArgumentInfo {
pub name: &'static str,
pub source: SourceInfo,
pub fallback: Fallback,
pub arity: Arity,
pub doc: &'static str,
pub part_of: Option<Part>,
pub delimiter: Option<char>,
}
#[diagnostic::on_unimplemented(
message = "`{Self}` cannot supply an argument of type `{Argument}`",
note = "sources bind to the operation's arguments in order, one `.arg(..)` each; check the order of the `.arg(..)` calls",
note = "a plain source supplies the value itself, `.optional()` an `Option`, `.many()` a `Vec`, `.switch()` a `bool`, `.product()` and `.sum()` their type"
)]
pub trait CliSourceFor<Argument> {
fn cli_describe(&self, name: &'static str, positions: &mut usize, out: &mut Vec<ArgumentInfo>);
}
pub trait CliSourceDecode<Argument, Decoder, Error> {
fn cli_decode_source(
&self,
arguments: &mut &[ArgumentInfo],
decoder: &Decoder,
) -> Result<Argument, CliArgumentError<Error>>;
}
pub(crate) fn next<'a>(arguments: &mut &'a [ArgumentInfo]) -> &'a ArgumentInfo {
let (argument, rest) = arguments.split_first().expect("a source decodes the argument it was described as");
*arguments = rest;
argument
}
pub trait CliSpelling {
fn cli_spelling(long: String, short: Option<char>, short_aliases: &'static [char]) -> SourceInfo;
}
impl CliSpelling for Options {
fn cli_spelling(long: String, short: Option<char>, short_aliases: &'static [char]) -> SourceInfo {
SourceInfo::Named { long, short, short_aliases }
}
}
impl CliSpelling for Assigned {
fn cli_spelling(name: String, _: Option<char>, _: &'static [char]) -> SourceInfo {
SourceInfo::Assigned { name }
}
}
impl<Mode, Shape: CliShape, Spelling: CliSpelling> NamedSource<Mode, Shape, Spelling> {
fn describe(&self, name: &'static str, _: &mut usize) -> ArgumentInfo {
let long = self.long.map_or_else(|| name.replace('_', "-"), str::to_owned);
ArgumentInfo {
name,
source: Spelling::cli_spelling(long, self.short, self.short_aliases),
fallback: self.fallback,
arity: Shape::ARITY,
doc: self.doc,
part_of: None,
delimiter: None,
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct DelimitedSource<Mode = NoFallback, Spelling = Options> {
source: NamedSource<Mode, Many, Spelling>,
delimiter: char,
}
impl<Mode, Spelling> NamedSource<Mode, Many, Spelling> {
pub fn delimiter(self, delimiter: char) -> DelimitedSource<Mode, Spelling> {
DelimitedSource { source: self, delimiter }
}
}
impl<Mode, Spelling: CliSpelling> DelimitedSource<Mode, Spelling> {
fn describe(&self, name: &'static str, positions: &mut usize) -> ArgumentInfo {
ArgumentInfo { delimiter: Some(self.delimiter), ..self.source.describe(name, positions) }
}
}
impl<Mode, Shape: CliShape> PositionalSource<Mode, Shape> {
fn describe(&self, name: &'static str, positions: &mut usize) -> ArgumentInfo {
let index = *positions;
*positions += 1;
ArgumentInfo {
name,
source: SourceInfo::Positional { index },
fallback: self.fallback,
arity: Shape::ARITY,
doc: self.doc,
part_of: None,
delimiter: None,
}
}
}
macro_rules! shaped_sources {
($([$($generic:ident),*] $source:ty, $shape:ident => $argument:ty;)*) => {
$(
impl<Mode, Value $(, $generic: CliSpelling)*> CliSourceFor<$argument> for $source {
fn cli_describe(&self, name: &'static str, positions: &mut usize, out: &mut Vec<ArgumentInfo>) {
out.push(self.describe(name, positions));
}
}
impl<Mode, Value, Decoder, Error $(, $generic)*> CliSourceDecode<$argument, Decoder, Error> for $source
where
Decoder: CliWordsAlg + CliWordAlg<Value, Decoder::Word, Error = Error>,
{
fn cli_decode_source(
&self,
arguments: &mut &[ArgumentInfo],
decoder: &Decoder,
) -> Result<$argument, CliArgumentError<Error>> {
let argument = next(arguments);
$shape(argument.name, &words(argument, decoder), decoder)
}
}
)*
};
}
shaped_sources! {
[] PositionalSource<Mode, Whole>, one => Value;
[] PositionalSource<Mode, Optional>, optional => Option<Value>;
[] PositionalSource<Mode, Many>, many => Vec<Value>;
[Spelling] NamedSource<Mode, Whole, Spelling>, one => Value;
[Spelling] NamedSource<Mode, Optional, Spelling>, optional => Option<Value>;
[Spelling] NamedSource<Mode, Many, Spelling>, many => Vec<Value>;
[Spelling] DelimitedSource<Mode, Spelling>, many => Vec<Value>;
}
fn one<Value, Decoder, Word, Error>(
name: &'static str,
words: &[Word],
decoder: &Decoder,
) -> Result<Value, CliArgumentError<Error>>
where
Decoder: CliWordAlg<Value, Word, Error = Error>,
{
match words {
[] => Err(CliArgumentError::Missing(name)),
[word] => decoder.cli_word(word).map_err(|error| CliArgumentError::Word(name, error)),
_ => Err(CliArgumentError::Repeated(name)),
}
}
fn optional<Value, Decoder, Word, Error>(
name: &'static str,
words: &[Word],
decoder: &Decoder,
) -> Result<Option<Value>, CliArgumentError<Error>>
where
Decoder: CliWordAlg<Value, Word, Error = Error>,
{
if words.is_empty() { Ok(None) } else { one(name, words, decoder).map(Some) }
}
fn many<Value, Decoder, Word, Error>(
name: &'static str,
words: &[Word],
decoder: &Decoder,
) -> Result<Vec<Value>, CliArgumentError<Error>>
where
Decoder: CliWordAlg<Value, Word, Error = Error>,
{
words.iter().map(|word| decoder.cli_word(word).map_err(|error| CliArgumentError::Word(name, error))).collect()
}
macro_rules! switches {
($($mode:ident),*) => {
$(
impl CliSourceFor<bool> for NamedSource<$mode, Switch> {
fn cli_describe(&self, name: &'static str, positions: &mut usize, out: &mut Vec<ArgumentInfo>) {
out.push(self.describe(name, positions));
}
}
impl<Decoder, Error> CliSourceDecode<bool, Decoder, Error> for NamedSource<$mode, Switch>
where
Decoder: CliWordsAlg + CliWordAlg<bool, Decoder::Word, Error = Error>,
{
fn cli_decode_source(
&self,
arguments: &mut &[ArgumentInfo],
decoder: &Decoder,
) -> Result<bool, CliArgumentError<Error>> {
let argument = next(arguments);
let words = words(argument, decoder);
if words.is_empty() { Ok(false) } else { one(argument.name, &words, decoder) }
}
}
)*
};
}
switches!(NoFallback, WithEnv);
impl<Value> CliSourceFor<Option<Option<Value>>> for NamedSource<NoFallback, OptionalValue> {
fn cli_describe(&self, name: &'static str, positions: &mut usize, out: &mut Vec<ArgumentInfo>) {
out.push(self.describe(name, positions));
}
}
impl<Value, Decoder, Error> CliSourceDecode<Option<Option<Value>>, Decoder, Error>
for NamedSource<NoFallback, OptionalValue>
where
Decoder: CliWordsAlg + CliWordAlg<Value, Decoder::Word, Error = Error>,
Decoder::Word: AsRef<OsStr>,
{
fn cli_decode_source(
&self,
arguments: &mut &[ArgumentInfo],
decoder: &Decoder,
) -> Result<Option<Option<Value>>, CliArgumentError<Error>> {
let argument = next(arguments);
match words(argument, decoder).as_slice() {
[] => Ok(None),
[word] if word.as_ref().is_empty() => Ok(Some(None)),
words => one(argument.name, words, decoder).map(|value| Some(Some(value))),
}
}
}
impl CliSourceFor<()> for NamedSource<NoFallback, Switch> {
fn cli_describe(&self, name: &'static str, positions: &mut usize, out: &mut Vec<ArgumentInfo>) {
out.push(self.describe(name, positions));
}
}
impl<Decoder, Error> CliSourceDecode<(), Decoder, Error> for NamedSource<NoFallback, Switch>
where
Decoder: CliWordsAlg,
{
fn cli_decode_source(
&self,
arguments: &mut &[ArgumentInfo],
decoder: &Decoder,
) -> Result<(), CliArgumentError<Error>> {
let argument = next(arguments);
match words(argument, decoder).len() {
0 => Err(CliArgumentError::Missing(argument.name)),
1 => Ok(()),
_ => Err(CliArgumentError::Repeated(argument.name)),
}
}
}
#[diagnostic::on_unimplemented(
message = "the declared sources `{Self}` do not supply the operation arguments `{Args}`",
note = "declare one source per operation argument, in order, with `.arg(self.positional(..))` or `.arg(self.named(..))`"
)]
pub trait CliSources<Args> {
fn cli_arguments(&self, names: &'static [&'static str]) -> Vec<ArgumentInfo>;
}
#[diagnostic::on_unimplemented(
message = "the sources `{Self}` are not all named",
note = "declare global arguments, product fields, and alternatives with `self.named(..)`"
)]
pub trait CliNamedSources {}
impl CliNamedSources for () {}
impl<Previous, Mode, Shape, Spelling> CliNamedSources for (Previous, NamedSource<Mode, Shape, Spelling>) where
Previous: CliNamedSources
{
}
#[diagnostic::on_unimplemented(
message = "`{Self}` is not a named source",
note = "declare a product's fields and a sum's alternatives with `self.named(..)`"
)]
pub trait CliNamedSource {}
impl<Mode, Shape, Spelling> CliNamedSource for NamedSource<Mode, Shape, Spelling> {}
impl<Mode, Spelling> CliNamedSource for DelimitedSource<Mode, Spelling> {}
impl<Previous, Mode, Spelling> CliNamedSources for (Previous, DelimitedSource<Mode, Spelling>) where
Previous: CliNamedSources
{
}
pub trait CliWordsAlg {
type Word;
fn cli_words(&self, argument: &ArgumentInfo) -> Vec<Self::Word>;
fn cli_env(&self, name: &str) -> Option<Self::Word>;
fn cli_default(&self, default: &'static str) -> Self::Word;
fn cli_split(&self, word: Self::Word, delimiter: char) -> Vec<Self::Word>;
}
pub(crate) fn words<Decoder: CliWordsAlg>(argument: &ArgumentInfo, decoder: &Decoder) -> Vec<Decoder::Word> {
let mut words = decoder.cli_words(argument);
if words.is_empty() {
let Fallback { env, default } = argument.fallback;
words = env
.and_then(|name| decoder.cli_env(name))
.or_else(|| default.map(|default| decoder.cli_default(default)))
.into_iter()
.collect();
}
match argument.delimiter {
Some(delimiter) => words.into_iter().flat_map(|word| decoder.cli_split(word, delimiter)).collect(),
None => words,
}
}
pub trait CliDecodeSources<Args, Decoder, Error> {
fn cli_decode(&self, arguments: &[ArgumentInfo], decoder: &Decoder) -> Result<Args, CliArgumentError<Error>>;
}
impl CliSources<()> for () {
fn cli_arguments(&self, _: &'static [&'static str]) -> Vec<ArgumentInfo> {
Vec::new()
}
}
impl<Decoder, Error> CliDecodeSources<(), Decoder, Error> for () {
fn cli_decode(&self, _: &[ArgumentInfo], _: &Decoder) -> Result<(), CliArgumentError<Error>> {
Ok(())
}
}
macro_rules! nested {
($inner:ty;) => { $inner };
($inner:ty; $head:ident $($tail:ident)*) => { nested!(($inner, $head); $($tail)*) };
}
macro_rules! nested_pattern {
($inner:tt;) => { $inner };
($inner:tt; $head:ident $($tail:ident)*) => { nested_pattern!(($inner, $head); $($tail)*) };
}
pub(crate) use {nested, nested_pattern};
macro_rules! sources {
($(($source:ident, $argument:ident, $value:ident, $index:tt)),+) => {
impl<$($source, $argument),+> CliSources<($($argument,)+)> for nested!((); $($source)+)
where
$($source: CliSourceFor<$argument>,)+
{
fn cli_arguments(&self, names: &'static [&'static str]) -> Vec<ArgumentInfo> {
let nested_pattern!((); $($value)+) = self;
let mut positions = 0;
let mut out = Vec::new();
$(CliSourceFor::<$argument>::cli_describe($value, names[$index], &mut positions, &mut out);)+
out
}
}
impl<Decoder, Error, $($source, $argument),+> CliDecodeSources<($($argument,)+), Decoder, Error>
for nested!((); $($source)+)
where
$($source: CliSourceDecode<$argument, Decoder, Error>,)+
{
fn cli_decode(
&self,
mut arguments: &[ArgumentInfo],
decoder: &Decoder,
) -> Result<($($argument,)+), CliArgumentError<Error>> {
let nested_pattern!((); $($value)+) = self;
Ok(($($value.cli_decode_source(&mut arguments, decoder)?,)+))
}
}
};
}
sources!((S0, A0, s0, 0));
sources!((S0, A0, s0, 0), (S1, A1, s1, 1));
sources!((S0, A0, s0, 0), (S1, A1, s1, 1), (S2, A2, s2, 2));
sources!((S0, A0, s0, 0), (S1, A1, s1, 1), (S2, A2, s2, 2), (S3, A3, s3, 3));
sources!((S0, A0, s0, 0), (S1, A1, s1, 1), (S2, A2, s2, 2), (S3, A3, s3, 3), (S4, A4, s4, 4));
sources!((S0, A0, s0, 0), (S1, A1, s1, 1), (S2, A2, s2, 2), (S3, A3, s3, 3), (S4, A4, s4, 4), (S5, A5, s5, 5));
sources!(
(S0, A0, s0, 0),
(S1, A1, s1, 1),
(S2, A2, s2, 2),
(S3, A3, s3, 3),
(S4, A4, s4, 4),
(S5, A5, s5, 5),
(S6, A6, s6, 6)
);
sources!(
(S0, A0, s0, 0),
(S1, A1, s1, 1),
(S2, A2, s2, 2),
(S3, A3, s3, 3),
(S4, A4, s4, 4),
(S5, A5, s5, 5),
(S6, A6, s6, 6),
(S7, A7, s7, 7)
);
sources!(
(S0, A0, s0, 0),
(S1, A1, s1, 1),
(S2, A2, s2, 2),
(S3, A3, s3, 3),
(S4, A4, s4, 4),
(S5, A5, s5, 5),
(S6, A6, s6, 6),
(S7, A7, s7, 7),
(S8, A8, s8, 8)
);
sources!(
(S0, A0, s0, 0),
(S1, A1, s1, 1),
(S2, A2, s2, 2),
(S3, A3, s3, 3),
(S4, A4, s4, 4),
(S5, A5, s5, 5),
(S6, A6, s6, 6),
(S7, A7, s7, 7),
(S8, A8, s8, 8),
(S9, A9, s9, 9)
);
sources!(
(S0, A0, s0, 0),
(S1, A1, s1, 1),
(S2, A2, s2, 2),
(S3, A3, s3, 3),
(S4, A4, s4, 4),
(S5, A5, s5, 5),
(S6, A6, s6, 6),
(S7, A7, s7, 7),
(S8, A8, s8, 8),
(S9, A9, s9, 9),
(S10, A10, s10, 10)
);
sources!(
(S0, A0, s0, 0),
(S1, A1, s1, 1),
(S2, A2, s2, 2),
(S3, A3, s3, 3),
(S4, A4, s4, 4),
(S5, A5, s5, 5),
(S6, A6, s6, 6),
(S7, A7, s7, 7),
(S8, A8, s8, 8),
(S9, A9, s9, 9),
(S10, A10, s10, 10),
(S11, A11, s11, 11)
);
sources!(
(S0, A0, s0, 0),
(S1, A1, s1, 1),
(S2, A2, s2, 2),
(S3, A3, s3, 3),
(S4, A4, s4, 4),
(S5, A5, s5, 5),
(S6, A6, s6, 6),
(S7, A7, s7, 7),
(S8, A8, s8, 8),
(S9, A9, s9, 9),
(S10, A10, s10, 10),
(S11, A11, s11, 11),
(S12, A12, s12, 12)
);
sources!(
(S0, A0, s0, 0),
(S1, A1, s1, 1),
(S2, A2, s2, 2),
(S3, A3, s3, 3),
(S4, A4, s4, 4),
(S5, A5, s5, 5),
(S6, A6, s6, 6),
(S7, A7, s7, 7),
(S8, A8, s8, 8),
(S9, A9, s9, 9),
(S10, A10, s10, 10),
(S11, A11, s11, 11),
(S12, A12, s12, 12),
(S13, A13, s13, 13)
);
sources!(
(S0, A0, s0, 0),
(S1, A1, s1, 1),
(S2, A2, s2, 2),
(S3, A3, s3, 3),
(S4, A4, s4, 4),
(S5, A5, s5, 5),
(S6, A6, s6, 6),
(S7, A7, s7, 7),
(S8, A8, s8, 8),
(S9, A9, s9, 9),
(S10, A10, s10, 10),
(S11, A11, s11, 11),
(S12, A12, s12, 12),
(S13, A13, s13, 13),
(S14, A14, s14, 14)
);
sources!(
(S0, A0, s0, 0),
(S1, A1, s1, 1),
(S2, A2, s2, 2),
(S3, A3, s3, 3),
(S4, A4, s4, 4),
(S5, A5, s5, 5),
(S6, A6, s6, 6),
(S7, A7, s7, 7),
(S8, A8, s8, 8),
(S9, A9, s9, 9),
(S10, A10, s10, 10),
(S11, A11, s11, 11),
(S12, A12, s12, 12),
(S13, A13, s13, 13),
(S14, A14, s14, 14),
(S15, A15, s15, 15)
);