forked from markuslaker/Argon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
argon.d
3710 lines (3160 loc) · 135 KB
/
argon.d
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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/rdmd --shebang -unittest -g -debug --main
module argon;
/+
Copyright (c) 2016, Mark Stephen Laker
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+/
import core.exception;
import std.algorithm.iteration;
import std.algorithm.searching;
import std.algorithm.sorting;
import std.array;
import std.conv;
import std.exception;
import std.regex;
import std.stdio;
import std.traits;
import std.uni;
@safe {
// These filenames are used for unittest blocks. Feel free to increase test
// coverage by adding stanzas for other operating systems.
version(linux) {
immutable existent_file = "/dev/zero";
immutable nonexistent_file = "/dev/onshire-ice-cream";
}
else {
immutable existent_file = "";
immutable nonexistent_file = "";
}
/++
+ If the user specifies invalid input at the command line, Argon will throw
+ a ParseException. This class is a subclass of Exception, and so you can
+ extract the text of the exception by calling `.msg()` on it.
+/
class ParseException: Exception {
this(A...) (A a) {
super(text(a));
}
}
/++
+ You can optionally use an indicator to tell whether an argument was supplied
+ at the command line.
+/
enum Indicator {
NotSeen, /// The user didn't specify the argument
UsedEolDefault, /// The user specified the named option at the end of the line and relied on the end-of-line default
UsedEqualsDefault, /// The user specified the named option but didn't follow it with `=' and a value
Seen /// The user specified the argument
}
// FArg -- formal argument (supplied in code); AArg -- actual argument (supplied
// by the user at runtime).
// This is the base class for all FArg classes:
class FArgBase {
private:
string[] names; // All long names, without dashes
string description; // The meaning of an argument: used when we auto-generate an element of a syntax summary from a named option
dchar shortname; // A single-char shortcut
bool needs_aarg; // Always true except for bool fargs
Indicator *p_indicator; // Pointer to the caller's indicator, or null
bool seen; // Have we matched an AArg with this FArg?
bool positional; // Is this positional -- identified by its position on the command line, matchable without an option name?
bool mandatory; // If true, some AArg must match this FArg or parsing will fail
bool documented = true; // True if this FArg should appear in syntax summaries
bool has_eol_default; // Has an end-of-line default value
bool has_equals_default; // Any actual arg must be attached with `=', and --switch without `=' is a shorthand for equals_default
bool is_incremental; // Is an incremental argument, which increments its receiver each time it's seen
auto SetSeen(in Indicator s) {
seen = s != Indicator.NotSeen;
if (p_indicator)
*p_indicator = s;
}
protected:
this(in string nms, in bool na, Indicator *pi) {
names = nms.splitter('|').filter!(name => !name.empty).array;
needs_aarg = na;
p_indicator = pi;
if (pi)
*pi = Indicator.NotSeen;
}
auto MarkSeen() { SetSeen(Indicator.Seen); }
auto MarkSeenWithEolDefault() { SetSeen(Indicator.UsedEolDefault); }
auto MarkSeenWithEqualsDefault() { SetSeen(Indicator.UsedEqualsDefault); }
auto MarkUnseen() { SetSeen(Indicator.NotSeen); }
auto SetShortName(in dchar snm) { shortname = snm; }
auto SetDescription(in string desc) { description = desc; }
auto MarkUndocumented() { documented = false; }
auto MarkIncremental() { is_incremental = true; }
auto MarkEolDefault() {
assert(!HasEqualsDefault, "A single argument can't have both an end-of-line default and an equals default");
has_eol_default = true;
}
auto MarkEqualsDefault() {
assert(!HasEolDefault, "A single argument can't have both an end-of-line default and an equals default");
has_equals_default = true;
}
public:
auto GetFirstName() const { return names[0]; }
auto GetNames() const { return names; }
auto HasShortName() const { return shortname != shortname.init; }
auto GetShortName() const { return shortname; }
auto GetDescription() const { return description; }
auto NeedsAArg() const { return needs_aarg; }
auto IsPositional() const { return positional; }
auto IsNamed() const { return !positional; }
auto IsMandatory() const { return mandatory; }
auto HasBeenSeen() const { return seen; }
auto IsDocumented() const { return documented; }
auto HasEolDefault() const { return has_eol_default; }
auto IsIncremental() const { return is_incremental; }
auto HasEqualsDefault() const { return has_equals_default; }
/++
+ Adds a single-letter short name (not necessarily Ascii) to avoid the need
+ for users to type out the long name.
+
+ Only a named option can have a short name. A positional argument
+ doesn't need one, because its name is never typed in by users.
+/
auto Short(this T) (in dchar snm) {
assert(!positional, "A positional argument can't have a short name");
assert(!std.uni.isWhite(snm), "An option's short name can't be a whitespace character");
assert(snm != '-', "An option's short name can't be a dash, because '--' would be interpreted as the end-of-options token");
assert(snm != '=', "An option's short name can't be an equals sign, because '=' is used to conjoin values with short option names and would be confusing with bundling enabled");
SetShortName(snm);
return cast(T) this;
}
/// Sugar for adding a single-character short name:
auto opCall(this T) (in dchar snm) {
return cast(T) Short(snm);
}
/++
+ Adds a description, which is used in error messages. It's also used when
+ syntax summaries are auto-generated, so that we can generate something
+ maximally descriptive like `--windows <number of windows>`. Without
+ this, we'd either generate the somewhat opaque `--windows <windows>`
+ or have to impose extra typing on the user by renaming the option as
+ `--number-of-windows`.
+
+ The description needn't be Ascii.
+
+ Only a named option can have a description. For a positional
+ argument, the name is never typed by the user and it does double duty
+ as a description.
+/
auto Description(this T) (in string desc) {
assert(!positional, "A positional argument doesn't need a description: use the ordinary name field for that");
FArgBase.SetDescription(desc);
return cast(T) this;
}
/// Sugar for adding a description:
auto opCall(this T) (in string desc) {
return cast(T) Description(desc);
}
/// Excludes an argument from auto-generated syntax summaries:
auto Undocumented(this T) () {
MarkUndocumented();
return cast(T) this;
}
// Indicate that this can be a positional argument:
auto MarkPositional() { positional = true; }
// Indicate that this argument is mandatory:
auto MarkMandatory() { mandatory = true; }
// The framework tells us to set default values before we start:
abstract void SetFArgToDefault();
// We've been passed an actual argument:
enum InvokedBy {LongName, ShortName, Position};
abstract void See(in string aarg, in InvokedBy);
abstract void SeeEolDefault();
abstract void SeeEqualsDefault();
// Overridden by BoolFArg and IncrementalFArg only:
void See() {
assert(false);
}
// Produce a string such as "the --alpha option (also known as --able and
// --alfie and --alfred)".
auto DisplayAllNames() const {
string result = "the --" ~ names[0] ~ " option";
if (names.length > 1) {
auto prefix = " (also known as --";
foreach (name; names[1..$]) {
result ~= prefix;
result ~= name;
prefix = " and --";
}
result ~= ')';
}
return result;
}
// Not capitalised; don't use the description at the start of a sentence:
auto DescribeArgumentForError(in InvokedBy invocation) const {
final switch (invocation) {
case InvokedBy.LongName:
assert(!positional);
return !description.empty? description: DisplayAllNames;
case InvokedBy.ShortName:
assert(!positional);
assert(HasShortName);
return !description.empty? description: text("the -", shortname, " option");
case InvokedBy.Position:
assert(positional);
return text("the ", names[0]);
}
}
auto DescribeArgumentOptimallyForError() const {
immutable invocation = IsPositional? InvokedBy.Position: InvokedBy.LongName;
return DescribeArgumentForError(invocation);
}
static FirstNonEmpty(string a, string b) {
return !a.empty? a: b;
}
auto BuildBareSyntaxElement() const {
if (IsPositional)
return text('<', GetFirstName, '>');
immutable stump = text("--", GetFirstName);
if (!NeedsAArg)
return stump;
return text(stump, " <", FirstNonEmpty(GetDescription, GetFirstName), '>');
}
auto BuildSyntaxElement() const {
return IsMandatory? BuildBareSyntaxElement:
IsIncremental? BuildBareSyntaxElement ~ '*':
text('[', BuildBareSyntaxElement, ']');
}
// After all aargs have been seen, every farg gets the chance to postprocess
// any aarg or default it's been given.
void Transform() { }
}
// Holding the receiver pointer in a templated base class separate from the
// rest of the inherited functionality makes it easier for the compiler to
// avoid bloat by reducing the amount of templated code.
class HasReceiver(FArg): FArgBase {
protected:
FArg *p_receiver;
FArg dfault;
FArg special_default; // Either an EOL default or an equals default -- no argument can have both
this(in string name, in bool needs_aarg, Indicator *p_indicator, FArg *pr, FArg df) {
super(name, needs_aarg, p_indicator);
p_receiver = pr;
dfault = df;
}
// Returns a non-empty error message on failure or null on success:
string ViolatesConstraints(in FArg, in InvokedBy) {
return null;
}
abstract FArg Parse(in char[] aarg, in InvokedBy invocation);
override void SeeEolDefault() {
*p_receiver = special_default;
MarkSeenWithEolDefault;
}
override void SeeEqualsDefault() {
*p_receiver = special_default;
MarkSeenWithEqualsDefault;
}
void SetEolDefault(FArg def) {
assert(IsNamed, "Only a named option can have an end-of-line default; for a positional argument, use an ordinary default");
special_default = def;
MarkEolDefault;
}
void SetEqualsDefault(FArg def) {
assert(IsNamed, "Only a named option can have an equals default; for a positional argument, use an ordinary default");
special_default = def;
MarkEqualsDefault;
}
public:
final override void SetFArgToDefault() {
*p_receiver = dfault;
MarkUnseen;
}
override void See(in string aarg, in InvokedBy invocation) {
*p_receiver = Parse(aarg, invocation);
if (const msg = ViolatesConstraints(*p_receiver, invocation))
throw new ParseException(msg);
MarkSeen;
}
}
/++
+ Adds the ability to set an end-of-line and equals defaults and return this.
+ The only FArg classes that don't get this are Booleans (for which the idea of
+ an EOL default makes no sense) and File (whose FArg makes its own provision).
+/
mixin template CanSetSpecialDefaults() {
/++
+ Provides an end-of-line default for a named option. This default is
+ used only if the user specifies the option name as the last token on
+ the command line and doesn't follow it with a value. For example:
+ ----
+ class MyHandler: argon.Handler {
+ uint width;
+
+ this() {
+ Named("wrap", width, 0).SetEolDefault(80);
+ }
+
+ // ...
+ }
+ ----
+ Suppose your command is called `list-it`. If the user runs `list-it`
+ with no command line arguments, `width` will be zero. If the user runs
+ `list-it --wrap` then `width` will equal 80. If the user runs
+ `list-it --wrap 132` then `width` will equal 132.
+
+ An end-of-line default provides the only way for a user to type the name
+ of a non-Boolean option without providing a value.
+/
auto EolDefault(T) (T def) {
SetEolDefault(def);
return this;
}
/++
+ Provides an equals default for a named option, which works like
+ grep's --colour option:
+
+ * Omitting --colour is equivalent to --colour=none
+
+ * Supplying --colour on its own is equivalent to --colour=auto
+
+ * Any other value must be attached to the --colour switch by one equals
+ sign and no space, as in --colour=always
+/
auto EqualsDefault(T) (T def) {
SetEqualsDefault(def);
return this;
}
}
// Holds a FArg for a Boolean AArg.
class BoolFArg: HasReceiver!bool {
this(in string name, bool *p_receiver, bool dfault) {
super(name, false, null, p_receiver, dfault);
}
alias See = HasReceiver!bool.See;
override void See() {
*p_receiver = !dfault;
MarkSeen;
}
protected:
override bool Parse(in char[] aarg, in InvokedBy invocation) {
if (!aarg.empty) {
if ("no" .startsWith(aarg) || "false".startsWith(aarg) || aarg == "0")
return false;
if ("yes".startsWith(aarg) || "true" .startsWith(aarg) || aarg == "1")
return true;
}
throw new ParseException("Invalid argument for ", DescribeArgumentForError(invocation));
}
}
@system unittest {
// unittest blocks such as this one have to be @system because they take
// the address of a local var, such as `target'.
alias InvokedBy = FArgBase.InvokedBy;
bool target;
auto ba0 = new BoolFArg("big red switch setting", &target, false);
assert(ba0.GetFirstName == "big red switch setting");
assert(!ba0.HasShortName);
assert(!ba0.IsPositional);
assert(!ba0.IsMandatory);
assert(!ba0.HasBeenSeen);
ba0.MarkMandatory;
assert(ba0.IsMandatory);
ba0.MarkPositional;
assert(ba0.IsPositional);
assert(!target);
ba0.See;
assert(target);
ba0.See("n", InvokedBy.Position);
assert(!target);
ba0.See("y", InvokedBy.Position);
assert(target);
ba0.See("no", InvokedBy.Position);
assert(!target);
ba0.See("yes", InvokedBy.Position);
assert(target);
ba0.See("f", InvokedBy.Position);
assert(!target);
ba0.See("t", InvokedBy.Position);
assert(target);
ba0.See("fa", InvokedBy.Position);
assert(!target);
ba0.See("tr", InvokedBy.Position);
assert(target);
ba0.See("fal", InvokedBy.Position);
assert(!target);
ba0.See("tru", InvokedBy.Position);
assert(target);
ba0.See("false", InvokedBy.Position);
assert(!target);
ba0.See("true", InvokedBy.Position);
assert(target);
ba0.See("0", InvokedBy.Position);
assert(!target);
ba0.See("1", InvokedBy.Position);
assert(target);
try {
ba0.See("no!", InvokedBy.Position);
assert(false, "BoolFArg should have thrown a ParseException as a result of an invalid actual argument");
}
catch (ParseException x)
assert(x.msg == "Invalid argument for the big red switch setting", "Message was: " ~ x.msg);
auto ba1 = new BoolFArg("big blue switch setting", &target, false);
ba1('j');
assert(ba1.HasShortName);
assert(ba1.GetShortName == 'j');
}
// Common functionality for all numeric FArgs, whether integral or floating:
class NumericFArgBase(Num, Num RangeInterval): HasReceiver!Num {
private:
// Implements AddRange(), which permits callers to specify one or more
// ranges of acceptable AArgs:
static struct ValRange(Num) {
alias Self = ValRange!Num;
Num minval, maxval;
auto MergeWith(in ref Self other) {
if (other.minval >= this.maxval && other.minval - this.maxval <= RangeInterval) {
this.maxval = other.maxval;
return true;
}
return false;
}
auto opCmp(in ref Self other) const {
return this.minval < other.minval? -1:
this.minval > other.minval? +1:
0;
}
auto toString() const {
return minval == maxval?
minval.to!string:
text("between ", minval, " and ", maxval);
}
auto Matches(Num n) const {
return n >= minval && n <= maxval;
}
}
alias Range = ValRange!Num;
Range[] vranges;
auto MergeRanges() {
if (vranges.length < 2)
return;
Range[] settled = [vranges[0]];
foreach (const ref vr; vranges[1..$])
if (!settled[$-1].MergeWith(vr))
settled ~= vr;
vranges = settled;
}
protected:
this(in string name, Num *p_receiver, Indicator *p_indicator, in Num dfault) {
super(name, true, p_indicator, p_receiver, dfault);
}
final AddRangeRaw(in Num min, in Num max) {
vranges ~= Range(min, max);
sort(vranges);
MergeRanges;
}
abstract Num ParseNumber(const(char)[] aarg) const;
final override Num Parse(in char[] aarg, in InvokedBy invocation) {
Num result = void;
try
result = ParseNumber(aarg);
catch (Exception e)
throw new ParseException("Invalid argument for ", DescribeArgumentForError(invocation), ": ", aarg);
return result;
}
final RangeErrorMessage(in InvokedBy invocation) const {
assert(!vranges.empty);
string result = "The argument for " ~ DescribeArgumentForError(invocation) ~ " must be ";
foreach (uint index, const ref vr; vranges) {
result ~= vr.toString;
const remaining = cast(uint) vranges.length - index - 1;
if (remaining > 1)
result ~= ", ";
else if (remaining == 1)
result ~= " or ";
}
return result;
}
final override string ViolatesConstraints(in Num n, in InvokedBy invocation) {
return
vranges.empty? null:
vranges.any!(vr => vr.Matches(n))? null:
RangeErrorMessage(invocation);
}
}
// short, ushort, int, uint, etc:
/++
+ By calling Pos() or Named() with an integral member variable, your program
+ creates an instance of (some template specialisation of) class IntegralFArg.
+ This class has methods governing the way numbers are interpreted and the
+ range of values your program is willing to accept.
+/
class IntegralFArg(Num): NumericFArgBase!(Num, 1) if (isIntegral!Num && !is(Num == enum)) {
private:
alias Radix = uint;
Radix def_radix = 10;
protected:
final override Num ParseNumber(const(char)[] aarg) const {
auto radices = ["0b": 2u, "0o": 8u, "0n": 10u, "0x": 16u];
Radix radix = def_radix;
if (aarg.length > 2)
if (const ptr = aarg[0..2] in radices) {
radix = *ptr;
aarg = aarg[2..$];
}
return aarg.to!Num(radix);
}
public:
mixin CanSetSpecialDefaults;
this(in string name, Num *p_receiver, Indicator *p_indicator, in Num dfault) {
super(name, p_receiver, p_indicator, dfault);
}
/++
+ The AddRange() methods enable you to specify any number of valid ranges
+ for the user's input. If you specify two or more overlapping or adjacent
+ ranges (in any order), Argon will amalgamate them when displaying error
+ messages. If you specify a default value for your argument, it can
+ safely lie outside all the ranges you specify; testing for a value
+ outside the permitted space is one way to test whether the user specified
+ a number explicitly or relied on the default.
+
+ The first overload adds a single permissible value.
+/
final AddRange(in Num n) {
AddRangeRaw(n, n);
return this;
}
/// The second overload adds a range of permissible values.
final AddRange(in Num min, in Num max) {
AddRangeRaw(min, max);
return this;
}
/++
+ The default radix for integral number is normally decimal; the user can
+ specify `0b`, `0o` or `0x` to have Argon parse integral numbers in
+ binary, octal or hex. (A leading zero is not enough to force
+ interpretation in octal.)
+
+ SetDefaultRadix() can changes the default radix to binary, octal or hex
+ (or, indeed, back to decimal); a user wishing to specify numbers in
+ decimal when that's not the default base must use a `0n` prefix.
+
+ Use this facility sparingly and document its use clearly. It's easy to
+ take users by surprise.
+/
final SetDefaultRadix(in uint dr) {
def_radix = dr;
return this;
}
}
@system unittest {
alias InvokedBy = FArgBase.InvokedBy;
alias IntArg = IntegralFArg!int;
alias Range = IntArg.Range;
int target;
Indicator seen;
auto ia0 = new IntArg("fred", &target, &seen, 5);
assert(target == target.init);
assert(seen == Indicator.NotSeen);
assert(ia0.vranges.empty);
assert(!ia0.HasShortName);
ia0('f');
assert(ia0.HasShortName);
assert(ia0.GetShortName == 'f');
ia0.See("8", InvokedBy.LongName);
assert(seen == Indicator.Seen);
assert(target == 8);
ia0.AddRange(50, 59);
assert(ia0.vranges == [Range(50, 59)]);
ia0.AddRange(49);
assert(ia0.vranges == [Range(49, 59)]);
ia0.AddRange(60);
assert(ia0.vranges == [Range(49, 60)]);
ia0.AddRange(70, 75);
assert(ia0.vranges == [Range(49, 60), Range(70, 75)]);
ia0.AddRange(42, 44);
assert(ia0.vranges == [Range(42, 44), Range(49, 60), Range(70, 75)]);
ia0.AddRange(45, 47);
assert(ia0.vranges == [Range(42, 47), Range(49, 60), Range(70, 75)]);
ia0.AddRange(48);
assert(ia0.vranges == [Range(42, 60), Range(70, 75)]);
ia0.AddRange(20, 24);
ia0.AddRange(100);
foreach (i; [20, 24, 42, 60, 70, 75, 100])
assert(ia0.ViolatesConstraints(i, InvokedBy.LongName) is null);
foreach (i; [19, 25, 41, 61, 69, 76, 99, 101]) {
immutable error = ia0.ViolatesConstraints(i, InvokedBy.LongName);
assert(error == "The argument for the --fred option must be between 20 and 24, between 42 and 60, between 70 and 75 or 100", "Error was: " ~ error);
}
auto ia1 = new IntArg("françoise", &target, null, 5);
foreach (radix, val; [2:4, 8:64, 10:100, 16:256]) {
ia1.SetDefaultRadix(radix);
ia1.See("100", InvokedBy.LongName);
assert(target == val);
foreach (str, meaning; ["0b100":4, "0o100":64, "0n100":100, "0x100":256]) {
ia1.See(str, InvokedBy.LongName);
assert(target == meaning);
}
}
try {
ia1.See("o", InvokedBy.LongName);
assert(false);
}
catch (ParseException x)
assert(x.msg == "Invalid argument for the --françoise option: o", "Message was: " ~ x.msg);
}
// float, double, real:
/++
+ By calling Pos() or Named() with a floating-point member variable, your
+ program creates an instance of (some template specialisation of) class
+ FloatingFArg. Like IntegralFArg, FloatingFArg enables you to limit the range
+ of numbers your program will accept. There is no provision, however, for
+ users to specify floating point numbers in radices other than 10.
+/
class FloatingFArg(Num): NumericFArgBase!(Num, 0.0) if (isFloatingPoint!Num) {
mixin CanSetSpecialDefaults;
this(in string name, Num *p_receiver, Indicator *p_indicator, in Num dfault) {
super(name, p_receiver, p_indicator, dfault);
}
protected:
final override Num ParseNumber(const(char)[] aarg) const {
return aarg.to!Num;
}
public:
/++
+ AddRange() enables you to specify any number of valid ranges
+ for the user's input. If you specify two or more overlapping or touching
+ ranges (in any order), Argon will amalgamate them when displaying error
+ messages. If you specify a default value for your argument, it can
+ safely lie outside all the ranges you specify; testing for a value
+ outside the permitted space is one way to test whether the user specified
+ a number explicitly or relied on the default.
+/
final AddRange(in Num min, in Num max) {
AddRangeRaw(min, max);
return this;
}
}
@system unittest {
alias InvokedBy = FArgBase.InvokedBy;
alias DblArg = FloatingFArg!double;
alias Range = DblArg.Range;
double receiver;
Indicator indicator;
auto da0 = new DblArg("fred", &receiver, &indicator, double.init);
assert(da0.ViolatesConstraints(0.0, InvokedBy.ShortName) is null);
da0.AddRange(1, 2);
da0.AddRange(0, 1);
assert(da0.vranges == [Range(0, 2)]);
da0.AddRange(3.5, 4.25);
assert(da0.vranges == [Range(0, 2), Range(3.5, 4.25)]);
foreach (double f; [0, 1, 2, 3.5, 4.25])
assert(da0.ViolatesConstraints(f, InvokedBy.LongName) is null);
foreach (f; [-0.5, 2.5, 3.0, 4.5]) {
immutable error = da0.ViolatesConstraints(f, InvokedBy.LongName);
assert(error == "The argument for the --fred option must be between 0 and 2 or between 3.5 and 4.25", "Error was: " ~ error);
}
}
// Enumerations:
class EnumeralFArg(E): HasReceiver!E if (is(E == enum)) {
private:
E *p_receiver;
E dfault;
protected:
final override E Parse(in char[] aarg, in InvokedBy invocation) {
uint nr_found;
E result;
foreach (val; EnumMembers!E) {
const txt = text(val);
if (txt.startsWith(aarg)) {
result = val;
if (txt.length == aarg.length)
// 'bar' isn't ambiguous if the available values are 'bar'
// and 'barfly':
return val;
++nr_found;
}
}
if (nr_found == 0)
throw new ParseException('\'', aarg, "' is not a permitted value for ",
DescribeArgumentForError(invocation),
"; permitted values are ", RenderValidOptions(""));
if (nr_found > 1)
throw new ParseException("In ", DescribeArgumentForError(invocation), ", '", aarg,
"' is ambiguous; permitted values starting with those characters are ",
RenderValidOptions(aarg));
return result;
}
public:
mixin CanSetSpecialDefaults;
this(in string name, E *p_receiver, Indicator *p_indicator, in E dfault) {
super(name, true, p_indicator, p_receiver, dfault);
}
static RenderValidOptions(in char[] root) {
return [EnumMembers!E]
.map!(e => e.text)
.filter!(str => str.startsWith(root))
.join(", ");
}
}
@system unittest {
alias InvokedBy = FArgBase.InvokedBy;
enum Colours {black, red, green, yellow, blue, magenta, cyan, white}
Colours colour;
Indicator cseen;
alias ColourArg = EnumeralFArg!Colours;
auto ca0 = new ColourArg("fred", &colour, &cseen, Colours.init);
assert(!ca0.HasShortName);
ca0('ä');
assert(ca0.HasShortName);
assert(ca0.GetShortName == 'ä');
assert(ca0.RenderValidOptions("") == "black, red, green, yellow, blue, magenta, cyan, white");
assert(ca0.RenderValidOptions("b") == "black, blue");
assert(ca0.RenderValidOptions("bl") == "black, blue");
assert(ca0.RenderValidOptions("bla") == "black");
assert(ca0.RenderValidOptions("X") == "");
enum Girls {Zoë, Françoise, Beyoncé}
Girls girl;
Indicator gseen;
alias GirlArg = EnumeralFArg!Girls;
auto ga0 = new GirlArg("name", &girl, &gseen, Girls.init);
assert(ga0.RenderValidOptions("") == "Zoë, Françoise, Beyoncé");
assert(ga0.RenderValidOptions("F") == "Françoise");
assert(cseen == Indicator.NotSeen);
ca0.See("yellow", InvokedBy.LongName);
assert(colour == Colours.yellow);
ca0.See("whi", InvokedBy.LongName);
assert(colour == Colours.white);
ca0.See("g", InvokedBy.LongName);
assert(colour == Colours.green);
foreach (offering; ["b", "bl"])
try {
ca0.See(offering, InvokedBy.LongName);
assert(false);
}
catch (ParseException x)
assert(x.msg == "In the --fred option, '" ~ offering ~ "' is ambiguous; permitted values starting with those characters are black, blue", "Message was: " ~ x.msg);
ca0.See("blu", InvokedBy.LongName);
assert(colour == Colours.blue);
ca0.See("bla", InvokedBy.LongName);
assert(colour == Colours.black);
assert(gseen == Indicator.NotSeen);
ga0.See("Z", InvokedBy.LongName);
assert(girl == Girls.Zoë);
assert(gseen == Indicator.Seen);
ga0.See("Françoise", InvokedBy.LongName);
assert(girl == Girls.Françoise);
try {
ga0.See("Jean-Paul", InvokedBy.LongName);
assert(false);
}
catch (ParseException x)
assert(x.msg == "'Jean-Paul' is not a permitted value for the --name option; permitted values are Zoë, Françoise, Beyoncé", "Message was: " ~ x.msg);
// EOL defaults:
auto ga1 = new GirlArg("name", &girl, &gseen, Girls.init);
ga1.EolDefault(Girls.Françoise);
ga1.SetFArgToDefault;
assert(girl == Girls.init);
assert(gseen == Indicator.NotSeen);
ga1.SeeEolDefault;
assert(girl == Girls.Françoise);
assert(gseen == Indicator.UsedEolDefault);
// Can't have an EOL default and an equals default for the same arg:
assertThrown!AssertError(ga1.SetEqualsDefault(Girls.Zoë));
// Equals defaults:
auto ga2 = new GirlArg("name", &girl, &gseen, Girls.init);
ga2.EqualsDefault(Girls.Françoise);
ga1.SetFArgToDefault;
assert(girl == Girls.init);
assert(gseen == Indicator.NotSeen);
ga2.SeeEqualsDefault;
assert(girl == Girls.Françoise);
assert(gseen == Indicator.UsedEqualsDefault);
// Can't have an EOL default and an equals default for the same arg:
assertThrown!AssertError(ga2.SetEolDefault(Girls.Zoë));
}
class IncrementalFArg(Num): HasReceiver!Num if (isIntegral!Num) {
public:
this(in string name, Num *pr) {
super(name, false, null, pr, Num.init);
MarkIncremental;
}
override void See() {
++*p_receiver;
}
override Num Parse(const char[], const InvokedBy) {
return Num.init;
}
}
// strings:
// struct Regex won't tolerate being instantiated with a const or immutable
// character type. Given an arbitrary string type, we must therefore find the
// element type and strip it of `const' and `immutable'.
template BareCharType(Str) {
// Find the qualified element type:
template ElementType(Str: Chr[], Chr) {
alias ElementType = Chr;
}
// Result: element type without qualifiers:
alias BareCharType = Unqual!(ElementType!Str);
}
// This class holds one regex and error message, which will be applied to an
// actual string argument at runtime.
class ArgRegex(Char) {
private:
alias Caps = Captures!(Char[]);
alias AllCaps = Caps[];
alias Str = const Char[];
Regex!Char rx;
string error_msg;
bool snip;
static Interpolate(in string msg, AllCaps *p_allcaps) {
if (!p_allcaps)
return msg;
// Receives a string of the form "{2:PORT}".
// Returns p_allcaps[2]["PORT"].
auto look_up_cap(Captures!string caps) {
immutable rx_no = caps[1].to!uint;
assert(rx_no < p_allcaps.length, "The format {" ~ caps[1] ~ ':' ~ caps[2] ~ "} refers to too high a regex number");
auto old_caps = (*p_allcaps)[rx_no];
const cap_name = caps[2];
return old_caps[cap_name];
}
static rx = ctRegex!(`\{ (\d+) : (\S+?) \}`, "x");