argx 0.2.2

Expressive command-line parsing and configuration for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! Private static projection of normalized command semantics.
//!
//! These immutable tables are generated once per derive and shared by parsing, help rendering,
//! typed binding, and machine-readable schema discovery. Typed binding refers back to arguments
//! through stable [`Key`] values, while semantic Rust value types remain in a separate lazy
//! projection so parsing does not require schema support.

/// Stable semantic identity assigned to one command or argument declaration.
pub type Key = u64;

/// One normalized relationship between semantic argument identities.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Constraint {
    /// Relationship behavior.
    pub kind: ConstraintKind,
    /// Semantic identity of the argument declaring the relationship.
    pub source: Key,
    /// Semantic identity of the referenced argument.
    pub target: Key,
}

/// Supported argument relationship kinds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConstraintKind {
    /// Supplying the source requires the target to have a value.
    Requires,
    /// Supplying both source and target is invalid.
    Conflicts,
}

/// Runtime presence state for one semantic argument identity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ArgumentState {
    /// Canonical user-facing label used by diagnostics.
    pub diagnostic: &'static str,
    /// Whether argv supplied this argument.
    pub given: bool,
    /// Whether the argument has a value after considering typed defaults.
    pub satisfied: bool,
}

/// Built-in parser action available in one command scope.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Action<'a> {
    /// Canonical semantic action name.
    pub name: &'a str,
    /// Canonical user-facing spelling used by diagnostics.
    pub diagnostic: &'a str,
    /// One-line description shown in generated help.
    pub help: &'a str,
    /// Long spellings without the leading `--`.
    pub longs: &'a [&'a str],
    /// ASCII short spellings without the leading `-`.
    pub shorts: &'a [u8],
    /// Behavior triggered when the action is selected.
    pub kind: ActionKind<'a>,
}

/// Behavior associated with one built-in parser action.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ActionKind<'a> {
    /// Render generated help for the selected command scope.
    Help,
    /// Render machine-readable schema for the selected command scope.
    Schema,
    /// Render command version information.
    Version {
        /// Text rendered when the short spelling is used.
        short: &'a str,
        /// Text rendered when the long spelling is used.
        long: &'a str,
    },
}

/// One user-authored help section derived from command documentation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HelpSection<'a> {
    /// Section heading without Markdown syntax.
    pub heading: &'a str,
    /// Section body rendered verbatim after generated command sections.
    pub body: &'a str,
}

/// One documented group of arguments contributed through a flattened `Args` field.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HelpGroup<'a> {
    /// Group heading supplied by the flatten field's Rust documentation.
    pub heading: &'a str,
    /// Named arguments contributed by the flattened declaration.
    pub flags: &'a [&'a Flag<'a>],
    /// Positional arguments contributed by the flattened declaration.
    pub args: &'a [&'a Arg<'a>],
}

impl HelpGroup<'static> {
    /// Empty group used as a const-composition placeholder.
    pub const EMPTY: Self = Self { heading: "", flags: &[], args: &[] };
}

/// Help is present in every command scope and is modeled as an ordinary built-in action.
pub static HELP_ACTION: Action<'static> = Action {
    name: "help",
    diagnostic: "--help",
    help: "Print help",
    longs: &["help"],
    shorts: b"h",
    kind: ActionKind::Help,
};

/// Schema discovery is injected dynamically only for schema-enabled parser roots.
pub static SCHEMA_ACTION: Action<'static> = Action {
    name: "schema",
    diagnostic: "--schema",
    help: "Print machine-readable schema",
    longs: &["schema"],
    shorts: b"S",
    kind: ActionKind::Schema,
};

/// Static command semantics shared by parsing, help generation, and schema discovery.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Command<'a> {
    /// Command name as exposed on the command line.
    pub name: &'a str,
    /// One-line description shown in generated help.
    pub about: Option<&'a str>,
    /// Full command prose shown before generated help sections.
    pub description: Option<&'a str>,
    /// User-authored help sections shown after generated command sections.
    pub help_sections: &'a [HelpSection<'a>],
    /// Documented flattened argument groups in composition order.
    pub help_groups: &'a [&'a HelpGroup<'a>],
    /// Hidden spellings accepted in addition to the canonical command name.
    pub aliases: &'a [&'a str],
    /// Built-in parser actions available in this command scope.
    pub actions: &'a [&'a Action<'a>],
    /// Flags accepted by this command.
    pub flags: &'a [&'a Flag<'a>],
    /// Positional arguments accepted by this command.
    pub args: &'a [&'a Arg<'a>],
    /// Normalized argument relationships in this command scope.
    pub constraints: &'a [Constraint],
    /// Child commands accepted by this command.
    pub subcommands: &'a [&'a Self],
    /// Derive-assigned semantic command identity.
    pub key: Key,
}

impl Command<'static> {
    /// Empty command metadata for use with struct update syntax.
    pub const EMPTY: Self = Self {
        name: "",
        about: None,
        description: None,
        help_sections: &[],
        help_groups: &[],
        aliases: &[],
        actions: &[&HELP_ACTION],
        flags: &[],
        args: &[],
        constraints: &[],
        subcommands: &[],
        key: 0,
    };
}

/// Schema-relevant semantic type of one CLI value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValueSchema {
    /// Ordinary lexical string value.
    Lexical,
    /// Chrono date value recognized when the `chrono` integration is enabled.
    Date,
    /// Chrono date-time value recognized when the `chrono` integration is enabled.
    DateTime,
    /// UUID value recognized when the `uuid` integration is enabled.
    Uuid,
    /// URL value recognized when the `url` integration is enabled.
    Url,
}

impl ValueSchema {
    /// Returns the JSON Schema string format exposed by the enabled integration.
    #[must_use]
    pub(crate) const fn format(self) -> Option<&'static str> {
        match self {
            Self::Date if cfg!(feature = "chrono") => Some("date"),
            Self::DateTime if cfg!(feature = "chrono") => Some("date-time"),
            Self::Uuid if cfg!(feature = "uuid") => Some("uuid"),
            Self::Url if cfg!(feature = "url") => Some("uri"),
            Self::Lexical | Self::Date | Self::DateTime | Self::Uuid | Self::Url => None,
        }
    }
}

/// Static semantics for one named argument.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Flag<'a> {
    /// Derive-assigned semantic argument identity.
    pub key: Key,
    /// Canonical field name used for value placeholders and semantic identity.
    pub name: &'a str,
    /// Canonical user-facing spelling used by diagnostics.
    pub diagnostic: &'a str,
    /// One-line description shown in compact generated help.
    pub help: Option<&'a str>,
    /// Full description shown in long generated help.
    pub long_help: Option<&'a str>,
    /// Canonical long spellings without the leading `--`.
    pub longs: &'a [&'a str],
    /// Hidden long aliases without the leading `--`.
    pub aliases: &'a [&'a str],
    /// ASCII short spellings without the leading `-`.
    pub shorts: &'a [u8],
    /// Whether this flag remains in scope for descendant commands.
    pub global: bool,
    /// Whether one occurrence consumes a value.
    pub takes_value: bool,
    /// Canonical finite values accepted by this option, when declared as a `ValueEnum`.
    pub accepted_values: &'a [&'a str],
    /// Lazy schema metadata for the destination value type.
    pub value_schema: ValueSchema,
    /// Whether this named argument may occur more than once.
    pub repeatable: bool,
    /// Whether this flag must occur at least once.
    pub required: bool,
    /// Whether absence is satisfied by a typed Rust default expression.
    pub has_default: bool,
    /// Static user-facing spelling of the declared default, when it can be derived safely.
    pub default_value: Option<&'a str>,
    /// Whether a detached value may itself be flag-like.
    pub allow_hyphen_values: bool,
    /// Whether a detached negative number may be consumed while other flag-like values are
    /// refused.
    pub allow_negative_numbers: bool,
}

impl Flag<'static> {
    /// A value-less flag for use with struct update syntax.
    pub const BOOL: Self = Self {
        key: 0,
        name: "",
        diagnostic: "",
        help: None,
        long_help: None,
        longs: &[],
        aliases: &[],
        shorts: &[],
        global: false,
        takes_value: false,
        accepted_values: &[],
        value_schema: ValueSchema::Lexical,
        repeatable: false,
        required: false,
        has_default: false,
        default_value: None,
        allow_hyphen_values: false,
        allow_negative_numbers: false,
    };

    /// A flag that consumes one value for use with struct update syntax.
    pub const VALUE: Self = Self { takes_value: true, ..Self::BOOL };
}

/// Static semantics for one positional argument.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Arg<'a> {
    /// Derive-assigned semantic argument identity.
    pub key: Key,
    /// Canonical field name used by generated binding and help.
    pub name: &'a str,
    /// One-line description shown in compact generated help.
    pub help: Option<&'a str>,
    /// Full description shown in long generated help.
    pub long_help: Option<&'a str>,
    /// Whether this positional must receive at least one value.
    pub required: bool,
    /// Whether this positional may receive multiple values.
    pub variadic: bool,
    /// Canonical finite values accepted by this positional, when declared as a `ValueEnum`.
    pub accepted_values: &'a [&'a str],
    /// Lazy schema metadata for the destination value type.
    pub value_schema: ValueSchema,
    /// Whether a negative number may bind here while flag parsing remains enabled.
    pub allow_negative_numbers: bool,
}

impl Arg<'static> {
    /// A required single-value positional for use with struct update syntax.
    pub const REQUIRED: Self = Self {
        key: 0,
        name: "",
        help: None,
        long_help: None,
        required: true,
        variadic: false,
        accepted_values: &[],
        value_schema: ValueSchema::Lexical,
        allow_negative_numbers: false,
    };
}

/// Computes the high 32 bits shared by keys from one derived declaration.
///
/// Generated code supplies the containing module so declarations expanded independently can
/// still be distinguished when their source tokens are otherwise identical.
pub const fn key_base(module: &str, declaration: u32) -> Key {
    let bytes = module.as_bytes();
    let mut state = declaration;
    let mut index = 0;
    while index < bytes.len() {
        state = (state ^ bytes[index] as u32).wrapping_mul(0x0100_0193);
        index += 1;
    }
    (state as Key) << 32
}

// Lexical name resolution is kept with the command metadata it resolves so parsing and help
// share one lookup policy.

/// One named parser entry resolved in the selected command scope.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Named<'a> {
    /// A built-in action declared on the current command.
    Action(&'a Action<'a>),
    /// A local flag or inherited global flag together with its command-path scope index.
    Flag {
        /// Static metadata for the resolved flag.
        flag: &'a Flag<'a>,
        /// Zero-based command-path index where the flag is mounted.
        scope: usize,
    },
}

/// Resolves one long spelling using the parser's lexical scope rules.
pub(crate) fn long<'a>(
    command: &'a Command<'a>,
    ancestors: &[&'a Command<'a>],
    name: &[u8],
) -> Option<Named<'a>> {
    command
        .actions
        .iter()
        .copied()
        .find(|action| action.longs.iter().any(|long| long.as_bytes() == name))
        .map(Named::Action)
        .or_else(|| {
            command
                .flags
                .iter()
                .copied()
                .find(|flag| {
                    flag.longs.iter().chain(flag.aliases).any(|long| long.as_bytes() == name)
                })
                .map(|flag| Named::Flag { flag, scope: ancestors.len() })
        })
        .or_else(|| {
            ancestors.iter().enumerate().rev().find_map(|(scope, command)| {
                command
                    .flags
                    .iter()
                    .copied()
                    .find(|flag| {
                        flag.global
                            && flag
                                .longs
                                .iter()
                                .chain(flag.aliases)
                                .any(|long| long.as_bytes() == name)
                    })
                    .map(|flag| Named::Flag { flag, scope })
            })
        })
}

/// Resolves one short spelling using the parser's lexical scope rules.
pub(crate) fn short<'a>(
    command: &'a Command<'a>,
    ancestors: &[&'a Command<'a>],
    spelling: u8,
) -> Option<Named<'a>> {
    command
        .actions
        .iter()
        .copied()
        .find(|action| action.shorts.contains(&spelling))
        .map(Named::Action)
        .or_else(|| {
            command
                .flags
                .iter()
                .copied()
                .find(|flag| flag.shorts.contains(&spelling))
                .map(|flag| Named::Flag { flag, scope: ancestors.len() })
        })
        .or_else(|| {
            ancestors.iter().enumerate().rev().find_map(|(scope, command)| {
                command
                    .flags
                    .iter()
                    .copied()
                    .find(|flag| flag.global && flag.shorts.contains(&spelling))
                    .map(|flag| Named::Flag { flag, scope })
            })
        })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn module_path_contributes_to_key_base() {
        assert_ne!(key_base("argx::add", 42), key_base("argx::remove", 42));
    }
}