Skip to main content

alux_cli_direct/
parse.rs

1use crate::command_line::{CommandLineAlg, ParseError, ParseErrorKind, Span, os_string, read};
2use alux_cli::{ArgumentInfo, Arity, CliWordAlg, CliWordsAlg, Conventions, SourceInfo};
3use std::{
4    ffi::{OsStr, OsString},
5    net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6},
6    num::{
7        NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize, NonZeroU8, NonZeroU16, NonZeroU32,
8        NonZeroU64, NonZeroU128, NonZeroUsize,
9    },
10    path::PathBuf,
11};
12
13/// The words after a command's path, assigned to the command's arguments.
14///
15/// A word is an operating system string, as the command line gives it, so a word that is not
16/// UTF-8 reaches an argument that takes it unchanged.
17#[derive(Debug, Default, PartialEq, Eq)]
18pub struct Parsed {
19    positional: Vec<OsString>,
20    /// How many operands the command's positional arguments take, when not without limit.
21    takes: Option<usize>,
22    /// The first operand beyond those, and its word's index.
23    unexpected: Option<(usize, OsString)>,
24    /// Each option occurrence, as its long spelling and its word, in command-line order.
25    named: Vec<(String, OsString)>,
26}
27
28impl Parsed {
29    /// Assigns `words` to `arguments` under `conventions`: options by spelling, everything else
30    /// by position.
31    pub(crate) fn new(
32        arguments: &[ArgumentInfo],
33        words: &[OsString],
34        conventions: Conventions,
35    ) -> Result<Self, ParseError> {
36        let positions = arguments.iter().filter(|argument| matches!(argument.source, SourceInfo::Positional { .. }));
37        let takes_many = positions.clone().any(|argument| argument.arity == Arity::Many);
38        // A verbatim command ignores operands beyond its own.
39        let takes = (!takes_many && !conventions.verbatim).then(|| positions.count());
40        let mut parsed = Self { takes, ..Self::default() };
41        read(arguments, words, conventions, &mut parsed)?;
42        if let Some((word, extra)) = parsed.unexpected {
43            let kind = ParseErrorKind::Unexpected(extra.to_string_lossy().into_owned());
44            return Err(ParseError { at: Span { word, byte: 0 }, kind });
45        }
46
47        Ok(parsed)
48    }
49
50    fn record(&mut self, argument: &ArgumentInfo, given: OsString) {
51        if let Some(key) = key(argument) {
52            self.named.push((key, given));
53        }
54    }
55}
56
57/// Keys a spelled argument's words by its spelling: a product's field can share its name with another
58/// argument, not its spelling. An assigned name keeps its `=`, so `if=` is never the option `--if`.
59fn key(argument: &ArgumentInfo) -> Option<String> {
60    match &argument.source {
61        SourceInfo::Named { long, .. } => Some(long.clone()),
62        SourceInfo::Assigned { name } => Some(format!("{name}=")),
63        SourceInfo::Positional { .. } => None,
64    }
65}
66
67/// A switch is recorded as the empty word, its own spelling.
68impl CommandLineAlg for Parsed {
69    fn switch(&mut self, argument: &ArgumentInfo) {
70        self.record(argument, OsString::new());
71    }
72
73    fn value(&mut self, argument: &ArgumentInfo, value: OsString) {
74        self.record(argument, value);
75    }
76
77    fn operand(&mut self, word: &OsStr, at: usize) {
78        if self.unexpected.is_none() && self.takes == Some(self.positional.len()) {
79            self.unexpected = Some((at, word.to_os_string()));
80        }
81        self.positional.push(word.to_os_string());
82    }
83}
84
85impl CliWordsAlg for Parsed {
86    type Word = OsString;
87
88    fn cli_words(&self, argument: &ArgumentInfo) -> Vec<OsString> {
89        match &argument.source {
90            SourceInfo::Positional { index } if argument.arity == Arity::Many => {
91                self.positional.get(*index..).unwrap_or_default().to_vec()
92            }
93            SourceInfo::Positional { index } => self.positional.get(*index).cloned().into_iter().collect(),
94            SourceInfo::Named { .. } | SourceInfo::Assigned { .. } => {
95                let key = key(argument);
96                self.named.iter().filter(|(own, _)| Some(own) == key.as_ref()).map(|(_, word)| word.clone()).collect()
97            }
98        }
99    }
100
101    fn cli_env(&self, name: &str) -> Option<OsString> {
102        std::env::var_os(name)
103    }
104
105    fn cli_default(&self, default: &'static str) -> OsString {
106        OsString::from(default)
107    }
108
109    fn cli_split(&self, word: OsString, delimiter: char) -> Vec<OsString> {
110        split(&word, delimiter)
111    }
112}
113
114/// Splits a word on an ASCII-compatible delimiter, keeping each part's bytes.
115pub(crate) fn split(word: &OsStr, delimiter: char) -> Vec<OsString> {
116    let mut encoded = [0; 4];
117    let delimiter = delimiter.encode_utf8(&mut encoded).as_bytes();
118    let bytes = word.as_encoded_bytes();
119    let mut parts = Vec::new();
120    let mut start = 0;
121    let mut at = 0;
122    while at + delimiter.len() <= bytes.len() {
123        if &bytes[at..at + delimiter.len()] == delimiter {
124            parts.push(os_string(&bytes[start..at]));
125            at += delimiter.len();
126            start = at;
127        } else {
128            at += 1;
129        }
130    }
131    parts.push(os_string(&bytes[start..]));
132    parts
133}
134
135/// States how one word on the command line denotes a value.
136///
137/// Text and numbers are read with `FromStr` from a word that is UTF-8; `OsString` and `PathBuf` are
138/// the word itself, whatever its bytes. A domain value implements it for itself.
139pub trait DirectWord: Sized {
140    /// Reads the value `word` denotes.
141    ///
142    /// # Errors
143    ///
144    /// Answers why `word` denotes no value.
145    fn direct_word(word: &OsStr) -> Result<Self, String>;
146}
147
148macro_rules! text_words {
149    ($($value:ty),* $(,)?) => {
150        $(
151            impl DirectWord for $value {
152                fn direct_word(word: &OsStr) -> Result<Self, String> {
153                    let text = word.to_str().ok_or_else(|| format!("`{}` is not UTF-8", word.to_string_lossy()))?;
154                    text.parse().map_err(|error: <$value as std::str::FromStr>::Err| error.to_string())
155                }
156            }
157        )*
158    };
159}
160
161text_words!(
162    NonZeroI8,
163    NonZeroI16,
164    NonZeroI32,
165    NonZeroI64,
166    NonZeroI128,
167    NonZeroIsize,
168    NonZeroU8,
169    NonZeroU16,
170    NonZeroU32,
171    NonZeroU64,
172    NonZeroU128,
173    NonZeroUsize,
174    IpAddr,
175    Ipv4Addr,
176    Ipv6Addr,
177    SocketAddr,
178    SocketAddrV4,
179    SocketAddrV6,
180    char,
181    f32,
182    f64,
183    i8,
184    i16,
185    i32,
186    i64,
187    i128,
188    isize,
189    u8,
190    u16,
191    u32,
192    u64,
193    u128,
194    usize
195);
196
197/// A switch's own spelling, an empty word, is on; a word from the environment is a truth:
198/// `true`, `false`, `1`, or `0`.
199impl DirectWord for bool {
200    fn direct_word(word: &OsStr) -> Result<Self, String> {
201        match word.to_str() {
202            Some("" | "true" | "1") => Ok(true),
203            Some("false" | "0") => Ok(false),
204            _ => Err(format!("`{}` is not true or false", word.to_string_lossy())),
205        }
206    }
207}
208
209/// Any UTF-8 word is its own text.
210impl DirectWord for String {
211    fn direct_word(word: &OsStr) -> Result<Self, String> {
212        word.to_str().map(str::to_owned).ok_or_else(|| format!("`{}` is not UTF-8", word.to_string_lossy()))
213    }
214}
215
216impl DirectWord for OsString {
217    fn direct_word(word: &OsStr) -> Result<Self, String> {
218        Ok(word.to_os_string())
219    }
220}
221
222impl DirectWord for PathBuf {
223    fn direct_word(word: &OsStr) -> Result<Self, String> {
224        Ok(Self::from(word))
225    }
226}
227
228/// Decodes a word with the value's `DirectWord`.
229impl<Value> CliWordAlg<Value, OsString> for Parsed
230where
231    Value: DirectWord,
232{
233    type Error = String;
234
235    fn cli_word(&self, word: &OsString) -> Result<Value, String> {
236        Value::direct_word(word)
237    }
238}