forked from Hejsil/zig-clap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clap.zig
1929 lines (1756 loc) · 60.4 KB
/
clap.zig
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
const std = @import("std");
const builtin = std.builtin;
const debug = std.debug;
const heap = std.heap;
const io = std.io;
const math = std.math;
const mem = std.mem;
const meta = std.meta;
const process = std.process;
const testing = std.testing;
pub const args = @import("clap/args.zig");
pub const parsers = @import("clap/parsers.zig");
pub const streaming = @import("clap/streaming.zig");
pub const ccw = @import("clap/codepoint_counting_writer.zig");
test "clap" {
testing.refAllDecls(@This());
}
pub const default_assignment_separators = "=";
/// The names a `Param` can have.
pub const Names = struct {
/// '-' prefix
short: ?u8 = null,
/// '--' prefix
long: ?[]const u8 = null,
/// The longest of the possible names this `Names` struct can represent.
pub fn longest(names: *const Names) Longest {
if (names.long) |long|
return .{ .kind = .long, .name = long };
if (names.short) |*short|
return .{ .kind = .short, .name = @as(*const [1]u8, short) };
return .{ .kind = .positional, .name = "" };
}
pub const Longest = struct {
kind: Kind,
name: []const u8,
};
pub const Kind = enum {
long,
short,
positional,
pub fn prefix(kind: Kind) []const u8 {
return switch (kind) {
.long => "--",
.short => "-",
.positional => "",
};
}
};
};
/// Whether a param takes no value (a flag), one value, or can be specified multiple times.
pub const Values = enum {
none,
one,
many,
};
/// Represents a parameter for the command line.
/// Parameters come in three kinds:
/// * Short ("-a"): Should be used for the most commonly used parameters in your program.
/// * They can take a value three different ways.
/// * "-a value"
/// * "-a=value"
/// * "-avalue"
/// * They chain if they don't take values: "-abc".
/// * The last given parameter can take a value in the same way that a single parameter can:
/// * "-abc value"
/// * "-abc=value"
/// * "-abcvalue"
/// * Long ("--long-param"): Should be used for less common parameters, or when no single
/// character can describe the parameter.
/// * They can take a value two different ways.
/// * "--long-param value"
/// * "--long-param=value"
/// * Positional: Should be used as the primary parameter of the program, like a filename or
/// an expression to parse.
/// * Positional parameters have both names.long and names.short == null.
/// * Positional parameters must take a value.
pub fn Param(comptime Id: type) type {
return struct {
id: Id,
names: Names = Names{},
takes_value: Values = .none,
};
}
/// Takes a string and parses it into many Param(Help). Returned is a newly allocated slice
/// containing all the parsed params. The caller is responsible for freeing the slice.
pub fn parseParams(allocator: mem.Allocator, str: []const u8) ![]Param(Help) {
var end: usize = undefined;
return parseParamsEx(allocator, str, &end);
}
/// Takes a string and parses it into many Param(Help). Returned is a newly allocated slice
/// containing all the parsed params. The caller is responsible for freeing the slice.
pub fn parseParamsEx(allocator: mem.Allocator, str: []const u8, end: *usize) ![]Param(Help) {
var list = std.ArrayList(Param(Help)).init(allocator);
errdefer list.deinit();
try parseParamsIntoArrayListEx(&list, str, end);
return try list.toOwnedSlice();
}
/// Takes a string and parses it into many Param(Help) at comptime. Returned is an array of
/// exactly the number of params that was parsed from `str`. A parse error becomes a compiler
/// error.
pub fn parseParamsComptime(comptime str: []const u8) [countParams(str)]Param(Help) {
var end: usize = undefined;
var res: [countParams(str)]Param(Help) = undefined;
_ = parseParamsIntoSliceEx(&res, str, &end) catch {
const loc = std.zig.findLineColumn(str, end);
@compileError(std.fmt.comptimePrint("error:{}:{}: Failed to parse parameter:\n{s}", .{
loc.line + 1,
loc.column + 1,
loc.source_line,
}));
};
return res;
}
fn countParams(str: []const u8) usize {
// See parseParam for reasoning. I would like to remove it from parseParam, but people depend
// on that function to still work conveniently at comptime, so leaving it for now.
@setEvalBranchQuota(std.math.maxInt(u32));
var res: usize = 0;
var it = mem.splitScalar(u8, str, '\n');
while (it.next()) |line| {
const trimmed = mem.trimLeft(u8, line, " \t");
if (mem.startsWith(u8, trimmed, "-") or
mem.startsWith(u8, trimmed, "<"))
{
res += 1;
}
}
return res;
}
/// Takes a string and parses it into many Param(Help), which are written to `slice`. A subslice
/// is returned, containing all the parameters parsed. This function will fail if the input slice
/// is to small.
pub fn parseParamsIntoSlice(slice: []Param(Help), str: []const u8) ![]Param(Help) {
var null_alloc = heap.FixedBufferAllocator.init("");
var list = std.ArrayList(Param(Help)){
.allocator = null_alloc.allocator(),
.items = slice[0..0],
.capacity = slice.len,
};
try parseParamsIntoArrayList(&list, str);
return list.items;
}
/// Takes a string and parses it into many Param(Help), which are written to `slice`. A subslice
/// is returned, containing all the parameters parsed. This function will fail if the input slice
/// is to small.
pub fn parseParamsIntoSliceEx(slice: []Param(Help), str: []const u8, end: *usize) ![]Param(Help) {
var null_alloc = heap.FixedBufferAllocator.init("");
var list = std.ArrayList(Param(Help)){
.allocator = null_alloc.allocator(),
.items = slice[0..0],
.capacity = slice.len,
};
try parseParamsIntoArrayListEx(&list, str, end);
return list.items;
}
/// Takes a string and parses it into many Param(Help), which are appended onto `list`.
pub fn parseParamsIntoArrayList(list: *std.ArrayList(Param(Help)), str: []const u8) !void {
var end: usize = undefined;
return parseParamsIntoArrayListEx(list, str, &end);
}
/// Takes a string and parses it into many Param(Help), which are appended onto `list`.
pub fn parseParamsIntoArrayListEx(list: *std.ArrayList(Param(Help)), str: []const u8, end: *usize) !void {
var i: usize = 0;
while (i != str.len) {
var end_of_this: usize = undefined;
errdefer end.* = i + end_of_this;
try list.append(try parseParamEx(str[i..], &end_of_this));
i += end_of_this;
}
end.* = str.len;
}
pub fn parseParam(str: []const u8) !Param(Help) {
var end: usize = undefined;
return parseParamEx(str, &end);
}
/// Takes a string and parses it to a Param(Help).
pub fn parseParamEx(str: []const u8, end: *usize) !Param(Help) {
// This function become a lot less ergonomic to use once you hit the eval branch quota. To
// avoid this we pick a sane default. Sadly, the only sane default is the biggest possible
// value. If we pick something a lot smaller and a user hits the quota after that, they have
// no way of overriding it, since we set it here.
// We can recosider this again if:
// * We get parseParams: https://github.com/Hejsil/zig-clap/issues/39
// * We get a larger default branch quota in the zig compiler (stage 2).
// * Someone points out how this is a really bad idea.
@setEvalBranchQuota(std.math.maxInt(u32));
var res = Param(Help){ .id = .{} };
var start: usize = 0;
var state: enum {
start,
start_of_short_name,
end_of_short_name,
before_long_name_or_value_or_description,
before_long_name,
start_of_long_name,
first_char_of_long_name,
rest_of_long_name,
before_value_or_description,
first_char_of_value,
rest_of_value,
end_of_one_value,
second_dot_of_multi_value,
third_dot_of_multi_value,
before_description,
rest_of_description,
rest_of_description_new_line,
} = .start;
for (str, 0..) |c, i| {
errdefer end.* = i;
switch (state) {
.start => switch (c) {
' ', '\t', '\n' => {},
'-' => state = .start_of_short_name,
'<' => state = .first_char_of_value,
else => return error.InvalidParameter,
},
.start_of_short_name => switch (c) {
'-' => state = .first_char_of_long_name,
'a'...'z', 'A'...'Z', '0'...'9' => {
res.names.short = c;
state = .end_of_short_name;
},
else => return error.InvalidParameter,
},
.end_of_short_name => switch (c) {
' ', '\t' => state = .before_long_name_or_value_or_description,
'\n' => {
start = i + 1;
end.* = i + 1;
state = .rest_of_description_new_line;
},
',' => state = .before_long_name,
else => return error.InvalidParameter,
},
.before_long_name => switch (c) {
' ', '\t' => {},
'-' => state = .start_of_long_name,
else => return error.InvalidParameter,
},
.start_of_long_name => switch (c) {
'-' => state = .first_char_of_long_name,
else => return error.InvalidParameter,
},
.first_char_of_long_name => switch (c) {
'a'...'z', 'A'...'Z', '0'...'9', '-', '_' => {
start = i;
state = .rest_of_long_name;
},
else => return error.InvalidParameter,
},
.rest_of_long_name => switch (c) {
'a'...'z', 'A'...'Z', '0'...'9', '-', '_' => {},
' ', '\t' => {
res.names.long = str[start..i];
state = .before_value_or_description;
},
'\n' => {
res.names.long = str[start..i];
start = i + 1;
end.* = i + 1;
state = .rest_of_description_new_line;
},
else => return error.InvalidParameter,
},
.before_long_name_or_value_or_description => switch (c) {
' ', '\t' => {},
',' => state = .before_long_name,
'<' => state = .first_char_of_value,
else => {
start = i;
state = .rest_of_description;
},
},
.before_value_or_description => switch (c) {
' ', '\t' => {},
'<' => state = .first_char_of_value,
else => {
start = i;
state = .rest_of_description;
},
},
.first_char_of_value => switch (c) {
'>' => return error.InvalidParameter,
else => {
start = i;
state = .rest_of_value;
},
},
.rest_of_value => switch (c) {
'>' => {
res.takes_value = .one;
res.id.val = str[start..i];
state = .end_of_one_value;
},
else => {},
},
.end_of_one_value => switch (c) {
'.' => state = .second_dot_of_multi_value,
' ', '\t' => state = .before_description,
'\n' => {
start = i + 1;
end.* = i + 1;
state = .rest_of_description_new_line;
},
else => {
start = i;
state = .rest_of_description;
},
},
.second_dot_of_multi_value => switch (c) {
'.' => state = .third_dot_of_multi_value,
else => return error.InvalidParameter,
},
.third_dot_of_multi_value => switch (c) {
'.' => {
res.takes_value = .many;
state = .before_description;
},
else => return error.InvalidParameter,
},
.before_description => switch (c) {
' ', '\t' => {},
'\n' => {
start = i + 1;
end.* = i + 1;
state = .rest_of_description_new_line;
},
else => {
start = i;
state = .rest_of_description;
},
},
.rest_of_description => switch (c) {
'\n' => {
end.* = i;
state = .rest_of_description_new_line;
},
else => {},
},
.rest_of_description_new_line => switch (c) {
' ', '\t', '\n' => {},
'-', '<' => {
res.id.desc = str[start..end.*];
end.* = i;
break;
},
else => state = .rest_of_description,
},
}
} else {
defer end.* = str.len;
switch (state) {
.rest_of_description => res.id.desc = str[start..],
.rest_of_description_new_line => res.id.desc = str[start..end.*],
.rest_of_long_name => res.names.long = str[start..],
.end_of_short_name,
.end_of_one_value,
.before_value_or_description,
.before_description,
=> {},
else => return error.InvalidParameter,
}
}
return res;
}
fn testParseParams(str: []const u8, expected_params: []const Param(Help)) !void {
var end: usize = undefined;
const actual_params = parseParamsEx(testing.allocator, str, &end) catch |err| {
const loc = std.zig.findLineColumn(str, end);
std.debug.print("error:{}:{}: Failed to parse parameter:\n{s}\n", .{
loc.line + 1,
loc.column + 1,
loc.source_line,
});
return err;
};
defer testing.allocator.free(actual_params);
try testing.expectEqual(expected_params.len, actual_params.len);
for (expected_params, 0..) |_, i|
try expectParam(expected_params[i], actual_params[i]);
}
fn expectParam(expect: Param(Help), actual: Param(Help)) !void {
try testing.expectEqualStrings(expect.id.desc, actual.id.desc);
try testing.expectEqualStrings(expect.id.val, actual.id.val);
try testing.expectEqual(expect.names.short, actual.names.short);
try testing.expectEqual(expect.takes_value, actual.takes_value);
if (expect.names.long) |long| {
try testing.expectEqualStrings(long, actual.names.long.?);
} else {
try testing.expectEqual(@as(?[]const u8, null), actual.names.long);
}
}
test "parseParams" {
try testParseParams(
\\-s
\\--str
\\--str-str
\\--str_str
\\-s, --str
\\--str <str>
\\-s, --str <str>
\\-s, --long <val> Help text
\\-s, --long <val>... Help text
\\--long <val> Help text
\\-s <val> Help text
\\-s, --long Help text
\\-s Help text
\\--long Help text
\\--long <A | B> Help text
\\<A> Help text
\\<A>... Help text
\\--aa
\\ This is
\\ help spanning multiple
\\ lines
\\--aa This msg should end and the newline cause of new param
\\--bb This should be a new param
\\
, &.{
.{ .id = .{}, .names = .{ .short = 's' } },
.{ .id = .{}, .names = .{ .long = "str" } },
.{ .id = .{}, .names = .{ .long = "str-str" } },
.{ .id = .{}, .names = .{ .long = "str_str" } },
.{ .id = .{}, .names = .{ .short = 's', .long = "str" } },
.{
.id = .{ .val = "str" },
.names = .{ .long = "str" },
.takes_value = .one,
},
.{
.id = .{ .val = "str" },
.names = .{ .short = 's', .long = "str" },
.takes_value = .one,
},
.{
.id = .{ .desc = "Help text", .val = "val" },
.names = .{ .short = 's', .long = "long" },
.takes_value = .one,
},
.{
.id = .{ .desc = "Help text", .val = "val" },
.names = .{ .short = 's', .long = "long" },
.takes_value = .many,
},
.{
.id = .{ .desc = "Help text", .val = "val" },
.names = .{ .long = "long" },
.takes_value = .one,
},
.{
.id = .{ .desc = "Help text", .val = "val" },
.names = .{ .short = 's' },
.takes_value = .one,
},
.{
.id = .{ .desc = "Help text" },
.names = .{ .short = 's', .long = "long" },
},
.{
.id = .{ .desc = "Help text" },
.names = .{ .short = 's' },
},
.{
.id = .{ .desc = "Help text" },
.names = .{ .long = "long" },
},
.{
.id = .{ .desc = "Help text", .val = "A | B" },
.names = .{ .long = "long" },
.takes_value = .one,
},
.{
.id = .{ .desc = "Help text", .val = "A" },
.takes_value = .one,
},
.{
.id = .{ .desc = "Help text", .val = "A" },
.names = .{},
.takes_value = .many,
},
.{
.id = .{
.desc =
\\ This is
\\ help spanning multiple
\\ lines
,
},
.names = .{ .long = "aa" },
.takes_value = .none,
},
.{
.id = .{ .desc = "This msg should end and the newline cause of new param" },
.names = .{ .long = "aa" },
.takes_value = .none,
},
.{
.id = .{ .desc = "This should be a new param" },
.names = .{ .long = "bb" },
.takes_value = .none,
},
});
try testing.expectError(error.InvalidParameter, parseParam("--long, Help"));
try testing.expectError(error.InvalidParameter, parseParam("-s, Help"));
try testing.expectError(error.InvalidParameter, parseParam("-ss Help"));
try testing.expectError(error.InvalidParameter, parseParam("-ss <val> Help"));
try testing.expectError(error.InvalidParameter, parseParam("- Help"));
}
/// Optional diagnostics used for reporting useful errors
pub const Diagnostic = struct {
arg: []const u8 = "",
name: Names = Names{},
/// Default diagnostics reporter when all you want is English with no colors.
/// Use this as a reference for implementing your own if needed.
pub fn report(diag: Diagnostic, stream: anytype, err: anyerror) !void {
var longest = diag.name.longest();
if (longest.kind == .positional)
longest.name = diag.arg;
switch (err) {
streaming.Error.DoesntTakeValue => try stream.print(
"The argument '{s}{s}' does not take a value\n",
.{ longest.kind.prefix(), longest.name },
),
streaming.Error.MissingValue => try stream.print(
"The argument '{s}{s}' requires a value but none was supplied\n",
.{ longest.kind.prefix(), longest.name },
),
streaming.Error.InvalidArgument => try stream.print(
"Invalid argument '{s}{s}'\n",
.{ longest.kind.prefix(), longest.name },
),
else => try stream.print("Error while parsing arguments: {s}\n", .{@errorName(err)}),
}
}
};
fn testDiag(diag: Diagnostic, err: anyerror, expected: []const u8) !void {
var buf: [1024]u8 = undefined;
var slice_stream = io.fixedBufferStream(&buf);
diag.report(slice_stream.writer(), err) catch unreachable;
try testing.expectEqualStrings(expected, slice_stream.getWritten());
}
test "Diagnostic.report" {
try testDiag(.{ .arg = "c" }, error.InvalidArgument, "Invalid argument 'c'\n");
try testDiag(
.{ .name = .{ .long = "cc" } },
error.InvalidArgument,
"Invalid argument '--cc'\n",
);
try testDiag(
.{ .name = .{ .short = 'c' } },
error.DoesntTakeValue,
"The argument '-c' does not take a value\n",
);
try testDiag(
.{ .name = .{ .long = "cc" } },
error.DoesntTakeValue,
"The argument '--cc' does not take a value\n",
);
try testDiag(
.{ .name = .{ .short = 'c' } },
error.MissingValue,
"The argument '-c' requires a value but none was supplied\n",
);
try testDiag(
.{ .name = .{ .long = "cc" } },
error.MissingValue,
"The argument '--cc' requires a value but none was supplied\n",
);
try testDiag(
.{ .name = .{ .short = 'c' } },
error.InvalidArgument,
"Invalid argument '-c'\n",
);
try testDiag(
.{ .name = .{ .long = "cc" } },
error.InvalidArgument,
"Invalid argument '--cc'\n",
);
try testDiag(
.{ .name = .{ .short = 'c' } },
error.SomethingElse,
"Error while parsing arguments: SomethingElse\n",
);
try testDiag(
.{ .name = .{ .long = "cc" } },
error.SomethingElse,
"Error while parsing arguments: SomethingElse\n",
);
}
/// Options that can be set to customize the behavior of parsing.
pub const ParseOptions = struct {
allocator: mem.Allocator,
diagnostic: ?*Diagnostic = null,
assignment_separators: []const u8 = default_assignment_separators,
};
/// Same as `parseEx` but uses the `args.OsIterator` by default.
pub fn parse(
comptime Id: type,
comptime params: []const Param(Id),
comptime value_parsers: anytype,
opt: ParseOptions,
) !Result(Id, params, value_parsers) {
var arena = heap.ArenaAllocator.init(opt.allocator);
errdefer arena.deinit();
var iter = try process.ArgIterator.initWithAllocator(arena.allocator());
const exe_arg = iter.next();
const result = try parseEx(Id, params, value_parsers, &iter, .{
// Let's reuse the arena from the `OSIterator` since we already have it.
.allocator = arena.allocator(),
.diagnostic = opt.diagnostic,
.assignment_separators = opt.assignment_separators,
});
return Result(Id, params, value_parsers){
.args = result.args,
.positionals = result.positionals,
.exe_arg = exe_arg,
.arena = arena,
};
}
/// The result of `parse`. Is owned by the caller and should be freed with `deinit`.
pub fn Result(
comptime Id: type,
comptime params: []const Param(Id),
comptime value_parsers: anytype,
) type {
return struct {
args: Arguments(Id, params, value_parsers, .slice),
positionals: []const FindPositionalType(Id, params, value_parsers),
exe_arg: ?[]const u8,
arena: std.heap.ArenaAllocator,
pub fn deinit(result: @This()) void {
result.arena.deinit();
}
};
}
/// Parses the command line arguments passed into the program based on an array of parameters.
///
/// The result will contain an `args` field which contains all the non positional arguments passed
/// in. There is a field in `args` for each parameter. The name of that field will be the result
/// of this expression:
/// ```
/// param.names.longest().name`
/// ```
///
/// The fields can have types other that `[]const u8` and this is based on what `value_parsers`
/// you provide. The parser to use for each parameter is determined by the following expression:
/// ```
/// @field(value_parsers, param.id.value())
/// ```
///
/// Where `value` is a function that returns the name of the value this parameter takes. A parser
/// is simple a function with the signature:
/// ```
/// fn ([]const u8) Error!T
/// ```
///
/// `T` can be any type and `Error` can be any error. You can pass `clap.parsers.default` if you
/// just wonna get something up and running.
///
/// Caller owns the result and should free it by calling `result.deinit()`
pub fn parseEx(
comptime Id: type,
comptime params: []const Param(Id),
comptime value_parsers: anytype,
iter: anytype,
opt: ParseOptions,
) !ResultEx(Id, params, value_parsers) {
const allocator = opt.allocator;
const Positional = FindPositionalType(Id, params, value_parsers);
var positionals = std.ArrayList(Positional).init(allocator);
var arguments = Arguments(Id, params, value_parsers, .list){};
errdefer deinitArgs(Id, params, allocator, &arguments);
var stream = streaming.Clap(Id, meta.Child(@TypeOf(iter))){
.params = params,
.iter = iter,
.diagnostic = opt.diagnostic,
.assignment_separators = opt.assignment_separators,
};
while (try stream.next()) |arg| {
// TODO: We cannot use `try` inside the inline for because of a compiler bug that
// generates an infinite loop. For now, use a variable to store the error
// and use `try` outside. The downside of this is that we have to use
// `anyerror` :(
var res: anyerror!void = {};
inline for (params) |*param| {
if (param == arg.param) {
res = parseArg(
Id,
param.*,
value_parsers,
allocator,
&arguments,
&positionals,
arg,
);
}
}
try res;
}
// We are done parsing, but our arguments are stored in lists, and not slices. Map the list
// fields to slices and return that.
var result_args = Arguments(Id, params, value_parsers, .slice){};
inline for (meta.fields(@TypeOf(arguments))) |field| {
if (@typeInfo(field.type) == .@"struct" and
@hasDecl(field.type, "toOwnedSlice"))
{
const slice = try @field(arguments, field.name).toOwnedSlice(allocator);
@field(result_args, field.name) = slice;
} else {
@field(result_args, field.name) = @field(arguments, field.name);
}
}
return ResultEx(Id, params, value_parsers){
.args = result_args,
.positionals = try positionals.toOwnedSlice(),
.allocator = allocator,
};
}
fn parseArg(
comptime Id: type,
comptime param: Param(Id),
comptime value_parsers: anytype,
allocator: mem.Allocator,
arguments: anytype,
positionals: anytype,
arg: streaming.Arg(Id),
) !void {
const parser = comptime switch (param.takes_value) {
.none => undefined,
.one, .many => @field(value_parsers, param.id.value()),
};
const longest = comptime param.names.longest();
const name = longest.name[0..longest.name.len].*;
switch (longest.kind) {
.short, .long => switch (param.takes_value) {
.none => @field(arguments, &name) +|= 1,
.one => @field(arguments, &name) = try parser(arg.value.?),
.many => {
const value = try parser(arg.value.?);
try @field(arguments, &name).append(allocator, value);
},
},
.positional => try positionals.append(try parser(arg.value.?)),
}
}
/// The result of `parseEx`. Is owned by the caller and should be freed with `deinit`.
pub fn ResultEx(
comptime Id: type,
comptime params: []const Param(Id),
comptime value_parsers: anytype,
) type {
return struct {
args: Arguments(Id, params, value_parsers, .slice),
positionals: []const FindPositionalType(Id, params, value_parsers),
allocator: mem.Allocator,
pub fn deinit(result: *@This()) void {
deinitArgs(Id, params, result.allocator, &result.args);
result.allocator.free(result.positionals);
}
};
}
fn FindPositionalType(
comptime Id: type,
comptime params: []const Param(Id),
comptime value_parsers: anytype,
) type {
const pos = findPositional(Id, params) orelse return []const u8;
return ParamType(Id, pos, value_parsers);
}
fn findPositional(comptime Id: type, params: []const Param(Id)) ?Param(Id) {
for (params) |param| {
const longest = param.names.longest();
if (longest.kind == .positional)
return param;
}
return null;
}
/// Given a parameter figure out which type that parameter is parsed into when using the correct
/// parser from `value_parsers`.
fn ParamType(
comptime Id: type,
comptime param: Param(Id),
comptime value_parsers: anytype,
) type {
const parser = switch (param.takes_value) {
.none => parsers.string,
.one, .many => @field(value_parsers, param.id.value()),
};
return parsers.Result(@TypeOf(parser));
}
/// Deinitializes a struct of type `Argument`. Since the `Argument` type is generated, and we
/// cannot add the deinit declaration to it, we declare it here instead.
fn deinitArgs(
comptime Id: type,
comptime params: []const Param(Id),
allocator: mem.Allocator,
arguments: anytype,
) void {
inline for (params) |param| {
const longest = comptime param.names.longest();
if (longest.kind == .positional)
continue;
if (param.takes_value != .many)
continue;
const field = @field(arguments, longest.name);
// If the multi value field is a struct, we know it is a list and should be deinited.
// Otherwise, it is a slice that should be freed.
switch (@typeInfo(@TypeOf(field))) {
.@"struct" => @field(arguments, longest.name).deinit(allocator),
else => allocator.free(@field(arguments, longest.name)),
}
}
}
const MultiArgKind = enum { slice, list };
/// Turn a list of parameters into a struct with one field for each none positional parameter.
/// The type of each parameter field is determined by `ParamType`. Positional arguments will not
/// have a field in this struct.
fn Arguments(
comptime Id: type,
comptime params: []const Param(Id),
comptime value_parsers: anytype,
comptime multi_arg_kind: MultiArgKind,
) type {
var fields_len: usize = 0;
for (params) |param| {
const longest = param.names.longest();
if (longest.kind == .positional)
continue;
fields_len += 1;
}
var fields: [fields_len]builtin.Type.StructField = undefined;
var i: usize = 0;
for (params) |param| {
const longest = param.names.longest();
if (longest.kind == .positional)
continue;
const T = ParamType(Id, param, value_parsers);
const default_value = switch (param.takes_value) {
.none => @as(u8, 0),
.one => @as(?T, null),
.many => switch (multi_arg_kind) {
.slice => @as([]const T, &[_]T{}),
.list => std.ArrayListUnmanaged(T){},
},
};
const name = longest.name[0..longest.name.len] ++ ""; // Adds null terminator
fields[i] = .{
.name = name,
.type = @TypeOf(default_value),
.default_value = @ptrCast(&default_value),
.is_comptime = false,
.alignment = @alignOf(@TypeOf(default_value)),
};
i += 1;
}
return @Type(.{ .@"struct" = .{
.layout = .auto,
.fields = &fields,
.decls = &.{},
.is_tuple = false,
} });
}
test "str and u64" {
const params = comptime parseParamsComptime(
\\--str <str>
\\--num <u64>
\\
);
var iter = args.SliceIterator{
.args = &.{ "--num", "10", "--str", "cooley_rec_inp_ptr" },
};
var res = try parseEx(Help, ¶ms, parsers.default, &iter, .{
.allocator = testing.allocator,
});
defer res.deinit();
}
test "different assignment separators" {
const params = comptime parseParamsComptime(
\\-a, --aa <usize>...
\\
);
var iter = args.SliceIterator{
.args = &.{ "-a=0", "--aa=1", "-a:2", "--aa:3" },
};
var res = try parseEx(Help, ¶ms, parsers.default, &iter, .{
.allocator = testing.allocator,
.assignment_separators = "=:",
});
defer res.deinit();
try testing.expectEqualSlices(usize, &.{ 0, 1, 2, 3 }, res.args.aa);
}
test "everything" {
const params = comptime parseParamsComptime(
\\-a, --aa
\\-b, --bb
\\-c, --cc <str>
\\-d, --dd <usize>...
\\-h
\\<str>
\\
);
var iter = args.SliceIterator{
.args = &.{ "-a", "--aa", "-c", "0", "something", "-d", "1", "--dd", "2", "-h" },
};
var res = try parseEx(Help, ¶ms, parsers.default, &iter, .{
.allocator = testing.allocator,
});
defer res.deinit();