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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
/*!
# Argyle: Macros.
*/
/// # Generate a CLI Argument Enum and Parser/Iterator.
///
/// This macro generates a custom enum and iterator to help with CLI argument
/// parsing.
///
/// `argue!` is intended for use cases requiring more than the standard library's
/// barebones [`args_os`](::std::env::args_os) helper, but less than the
/// full-service offerings (and overhead) of a crate like [clap](https://crates.io/crates/clap).
///
/// It'll automatically convert UTF-8 arguments to `String`s (without
/// panicking), untangle combined key/value pair representations like `-kval`
/// or `--key=val`, and stop if/when it encounters an end-of-command terminator
/// (`"--"`).
///
/// The subsequent validation and handling, however, are left _entirely up to
/// you_. Loop, match, and proceed however you see fit!
///
/// ## Example
///
/// ```
/// use argyle::argue;
///
/// // Construct the enum and iterator.
/// argue! {
/// // By default, this macro will call the enum "Argument" and the
/// // iterator "ArgumentIter". If you'd rather they be called something
/// // else, or have a non-private scope, you can override the defaults
/// // by kicking things off with the following.
///
/// /// # My Arguments Enum.
/// ///
/// /// If you supply documentation like this
/// #[doc = "and/or like this"]
/// /// it'll be attached to the generated object.
/// pub // You can optionally change the scope like so.
/// MyArgument, // A name and trailing comma are required.
///
/// MyArgumentIter, // Naked works too if you don't care about docs/scope,
/// // though clippy may scold you. ;)
///
/// // --------------------
///
/// // If you have valueless keywords, they come next as a comma-separated
/// // list.
/// //
/// // Each entry needs an ident for the variant name and one or more
/// // string literals to match against.
/// Help "-h" "--help",
/// Version "-V" "--version",
/// Stderr "--stderr",
///
/// // --------------------
///
/// // If you have option keywords, those come next, but require an
/// // "@options" marker to announce their presence.
/// @options
///
/// // The list format is otherwise identical to their valueless
/// // counterparts.
/// Format "--format",
/// Level "-l" "--level",
///
/// // --------------------
///
/// // If you'd like to differentiate unmatched _paths_ from arbitrary
/// // string values, you can declare a variant for the purpose like so.
/// @catchall-paths Path,
///
/// // --------------------
///
/// // Last but not least, the enum will need two catchall variants to
/// // handle unmatched String and OsString values.
/// //
/// // By default, these are auto-generated as "Other" and "OtherOs",
/// // but if you'd like to call them something else, now's the time!
/// @catchall Invalid InvalidUtf8,
/// }
///
/// /// # Main.
/// fn main() {
/// # use std::path::PathBuf;
/// // Example settings.
/// let mut stderr = false;
/// let mut format: Option<Format> = None;
/// let mut level = 0_u8;
/// let mut paths: Vec<PathBuf> = Vec::new();
///
/// // Loop through the environmental arguments, taking whatever actions
/// // make sense for your application.
/// for arg in MyArgument::args_os() {
/// match arg {
/// // You named these!
/// MyArgument::Help => print_help(),
/// MyArgument::Version => print_version(),
/// MyArgument::Stderr => { stderr = true; },
///
/// // Options come with the value as a String.
/// MyArgument::Format(v) => {
/// format = Format::from_str(v);
/// },
/// MyArgument::Level(v) => {
/// level = v.parse().unwrap_or(0);
/// },
///
/// // If you specified @catchall-paths, unmatched OsString values
/// // that happen to be (valid) filesystem paths will be mapped
/// // thusly (instead of to a generic catchall).
/// MyArgument::Path(v) => {
/// paths.push(PathBuf::from(v));
/// },
///
/// // Unmatched String values map to the first generic catchall.
/// MyArgument::Invalid(v) => {
/// eprintln!("Warning: unrecognized CLI argument {v}.");
/// },
///
/// // Unmatched values with invalid UTF-8 will be passed through
/// // to the second generic catchall as OsString values.
/// MyArgument::InvalidUtf8(v) => {
/// eprintln!(
/// "Warning: unrecognized CLI argument {}.",
/// v.display(),
/// );
/// },
/// }
/// }
///
/// // Now that the settings have been worked out, do something!
/// // …
/// }
/// # fn print_help() {}
/// # fn print_version() {}
/// # enum Format { Plain, Json }
/// # impl Format {
/// # fn from_str(str: String) -> Option<Self> { None }
/// # }
/// ```
///
/// ## Generated Code.
///
/// If you're curious or need to do something more complicated, taking a look
/// at the generated code can be helpful.
///
/// The call to `argue!` in the previous example, for example, will have added
/// the following to the module:
///
/// ```
/// # use std::env::ArgsOs;
/// # use std::ffi::OsString;
/// # use std::iter::FusedIterator;
/// # use std::iter::Skip;
/// #[derive(Debug, Clone, Eq, PartialEq)]
/// /// # My Arguments Enum.
/// ///
/// /// If you supply documentation like this and/or like this it'll be
/// /// attached to the generated object.
/// pub enum MyArgument {
/// /// # Matches "-h" "--help".
/// Help,
///
/// /// # Matches "-V" "--version".
/// Version,
///
/// /// # Matches "--stderr".
/// Stderr,
///
/// /// # Matches "--format".
/// Format(String),
///
/// /// # Matches "-l" "--level".
/// Level(String),
///
/// /// # Unassociated Path Value.
/// Path(OsString),
///
/// /// # Unspecified Value.
/// Invalid(String),
///
/// /// # Unspecified Value (Invalid UTF-8).
/// InvalidUtf8(OsString),
/// }
///
/// impl MyArgument {
/// /// # Environmental Argument Iterator.
/// ///
/// /// Return a new [`MyArgumentIter`] instance seeded with [`ArgsOs`]
/// /// (minus the first entry corresponding to the executable path).
/// pub fn args_os() -> MyArgumentIter<Skip<ArgsOs>> {
/// # MyArgumentIter::new(::std::env::args_os().skip(1))
/// // …
/// }
/// }
///
/// #[derive(Debug, Clone)]
/// struct MyArgumentIter<T> {
/// # iter: T,
/// # done: bool,
/// // …
/// }
///
/// // Note: the generated member methods share the parent's scope. The
/// // iterator was left private in the example, so the generated methods are
/// // private too.
///
/// impl<T: Iterator<Item=OsString>> MyArgumentIter<T> {
/// #[inline]
/// #[must_use]
/// /// # New Instance.
/// ///
/// /// Create and return a new parsing iterator over any arbitrary
/// /// iterator of `OsString`.
/// const fn new(src: T) -> Self {
/// # Self {
/// # iter: src,
/// # done: false,
/// # }
/// // …
/// }
///
/// #[inline]
/// #[must_use]
/// /// # Into Inner (Iterator).
/// ///
/// /// Return what's left of the inner iterator.
/// fn into_inner(self) -> T {
/// # self.iter
/// // …
/// }
/// }
///
/// impl<T: Iterator<Item=OsString>> Iterator for MyArgumentIter<T> {
/// type Item = MyArgument;
///
/// fn next(&mut self) -> Option<Self::Item> {
/// # None
/// // …
/// }
/// }
///
/// impl<T: Iterator<Item=OsString>> FusedIterator for MyArgumentIter<T> {}
/// ```
///
/// ## Keyword Formatting
///
/// The macro supports (practically) any number of named keywords, with or without values,
/// but there are _rules_ for the literals they match against to ensure proper
/// parsing.
///
/// * Short keys — `"-k"` — must be exactly two bytes: a hyphen and an ASCII alphanumeric.
/// * Long keys — `"--key"` — must start with two hyphens and an ASCII alphanumeric, and contain only alphanumerics, hyphens, and underscores thereafter.
/// * Commands — `"keyword"` — must start with an ASCII alphanumeric, and contain only alphanumerics, hyphens, and underscores thereafter.
///
/// Format sanity is evaluated at compile-time, so issues like the following
/// will trigger an error.
///
/// ```compile_fail
/// argyle::argue! {
/// MyArgument,
/// MyArgumentIter,
///
/// Level "-level", // Not short enough.
/// }
/// ```
///
/// ```compile_fail
/// argyle::argue! {
/// MyArgument,
/// MyArgumentIter,
///
/// Level "-❤️", // Cute, but not ASCII alphanumeric.
/// }
/// ```
///
/// ```compile_fail
/// argyle::argue! {
/// MyArgument,
/// MyArgumentIter,
///
/// FooBar "--foo bar", // Whitespace is illegal.
/// }
/// ```
///
/// ```compile_fail
/// argyle::argue! {
/// MyArgument,
/// MyArgumentIter,
///
/// Build "build!!!", // Settle down…
/// }
/// ```
///
/// This probably goes without saying, but keyword idents and literals must
/// also be unique. Haha.
///
/// ## Parsing Particulars
///
/// Key/value pairs are parsed identically whether they appear consecutively
/// — e.g. `--key` then `value` — or combined in any of the following ways:
/// * `-kvalue`
/// * `-k=value`
/// * `-k = value`
/// * `--key=value`
/// * `--key = value`
///
/// Option values must, however, be valid UTF-8, otherwise the key and value
/// will be returned as a joint `OtherOs(OsString)` in `--key=value` format.
///
/// Keyword matches are otherwise a case-sensitive, all-or-nothing affair.
///
/// Parsing will stop early if an end-of-command terminator (`"--"`) is
/// encountered. If your program needs to handle what comes _after_, adjust
/// the loop like so:
///
/// ```
/// # argyle::argue! {};
/// # type MyArgument = Argument;
/// # type MyArgumentIter<T> = ArgumentIter<T>;
/// // Save the iterator to a variable and traverse it one value at a time
/// // to keep it in scope.
/// let mut args = MyArgument::args_os();
/// while let Some(arg) = args.next() {
/// // Process as normal.
/// }
///
/// // Create a second iterator instance from the remains of the first to
/// // loop through whatever was left, if anything.
/// for arg in MyArgumentIter::new(args.into_inner()) {
/// // Do something.
/// }
/// ```
/// # Check Key Validity.
///
/// The compiler should optimize this out.
const _: = ;
$*
$iter_vis $iter<
);
// Same as above, but without @catchall overrides.
=> ;
// Same as above, but without the enum/iterator overrides.
=> ;
}