summaryrefslogtreecommitdiff
path: root/index.zig
blob: 7351515fdaf997c6596cafbcf3760a18ecd9c1f3 (plain) (blame)
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
pub const core = @import("core.zig");

const builtin = @import("builtin");
const std     = @import("std");

const mem   = std.mem;
const fmt   = std.fmt;
const debug = std.debug;
const io    = std.io;

const assert = debug.assert;

pub const Param = struct {
    field: []const u8,
    short: ?u8,
    long: ?[]const u8,
    takes_value: ?Parser,
    required: bool,
    position: ?usize,

    pub fn short(s: u8) Param {
        return Param{
            .field = []u8{s},
            .short = s,
            .long = null,
            .takes_value = null,
            .required = false,
            .position = null,
        };
    }

    pub fn long(l: []const u8) Param {
        return Param{
            .field = l,
            .short = null,
            .long = l,
            .takes_value = null,
            .required = false,
            .position = null,
        };
    }

    pub fn value(f: []const u8) Param {
        return Param{
            .field = f,
            .short = null,
            .long = null,
            .takes_value = null,
            .required = false,
            .position = null,
        };
    }

    /// Initialize a ::Param.
    /// If ::name.len == 0, then it's a value parameter: "value".
    /// If ::name.len == 1, then it's a short parameter: "-s".
    /// If ::name.len > 1, then it's a long parameter: "--long".
    pub fn smart(name: []const u8) Param {
        return Param{
            .field = name,
            .short = if (name.len == 1) name[0] else null,
            .long = if (name.len > 1) name else null,
            .takes_value = null,
            .required = false,
            .position = null,
        };
    }

    pub fn with(param: &const Param, comptime field_name: []const u8, v: var) Param {
        var res = *param;
        @field(res, field_name) = v;
        return res;
    }
};

pub fn Clap(comptime Result: type) type {
    return struct {
        const Self = this;

        defaults: Result,
        params: []const Param,

        pub fn parse(comptime clap: &const Self, allocator: &mem.Allocator, arg_iter: &core.ArgIterator) !Result {
            var result = clap.defaults;
            const core_params = comptime blk: {
                var res: [clap.params.len]core.Param(usize) = undefined;

                for (clap.params) |p, i| {
                    res[i] = core.Param(usize) {
                        .id = i,
                        .command = null,
                        .short = p.short,
                        .long = p.long,
                        .takes_value = p.takes_value != null,
                    };
                }

                break :blk res;
            };

            var handled = comptime blk: {
                var res: [clap.params.len]bool = undefined;
                for (clap.params) |p, i| {
                    res[i] = !p.required;
                }

                break :blk res;
            };

            var pos: usize = 0;
            var iter = core.Iterator(usize).init(core_params, arg_iter, allocator);
            defer iter.deinit();
            while (try iter.next()) |arg| : (pos += 1) {
                inline for(clap.params) |param, i| {
                    if (arg.id == i) {
                        if (param.position) |expected| {
                            if (expected != pos)
                                return error.InvalidPosition;
                        }

                        if (param.takes_value) |parser| {
                            try parser.parse(getFieldPtr(&result, param.field), ??arg.value);
                        } else {
                            *getFieldPtr(&result, param.field) = true;
                        }
                        handled[i] = true;
                    }
                }
            }

            return result;
        }

        fn GetFieldPtrReturn(comptime Struct: type, comptime field: []const u8) type {
            var inst: Struct = undefined;
            const dot_index = comptime mem.indexOfScalar(u8, field, '.') ?? {
                return @typeOf(&@field(inst, field));
            };

            return GetFieldPtrReturn(@typeOf(@field(inst, field[0..dot_index])), field[dot_index + 1..]);
        }

        fn getFieldPtr(curr: var, comptime field: []const u8) GetFieldPtrReturn(@typeOf(curr).Child, field) {
            const dot_index = comptime mem.indexOfScalar(u8, field, '.') ?? {
                return &@field(curr, field);
            };

            return getFieldPtr(&@field(curr, field[0..dot_index]), field[dot_index + 1..]);
        }
    };
}

pub const Parser = struct {
    const UnsafeFunction = &const void;

    FieldType: type,
    Errors: type,
    func: UnsafeFunction,

    pub fn init(comptime FieldType: type, comptime Errors: type, func: parseFunc(FieldType, Errors)) Parser {
        return Parser {
            .FieldType = FieldType,
            .Errors = Errors,
            .func = @ptrCast(UnsafeFunction, func),
        };
    }

    fn parse(comptime parser: Parser, field_ptr: TakePtr(parser.FieldType), arg: []const u8) parser.Errors!void {
        return @ptrCast(parseFunc(parser.FieldType, parser.Errors), parser.func)(field_ptr, arg);
    }

    // TODO: This is a workaround, since we don't have pointer reform yet.
    fn TakePtr(comptime T: type) type { return &T; }

    fn parseFunc(comptime FieldType: type, comptime Errors: type) type {
        return fn(&FieldType, []const u8) Errors!void;
    }

    pub fn int(comptime Int: type, comptime radix: u8) Parser {
        const func = struct {
            fn i(field_ptr: &Int, arg: []const u8) !void {
                *field_ptr = try fmt.parseInt(Int, arg, radix);
            }
        }.i;
        return Parser.init(
            Int,
            @typeOf(func).ReturnType.ErrorSet,
            func
        );
    }

    const string = Parser.init(
        []const u8,
        error{},
        struct {
            fn s(field_ptr: &[]const u8, arg: []const u8) (error{}!void) {
                *field_ptr = arg;
            }
        }.s
    );
};


const Options = struct {
    str: []const u8,
    int: i64,
    uint: u64,
    a: bool,
    b: bool,
    cc: bool,

    pub fn with(op: &const Options, comptime field: []const u8, value: var) Options {
        var res = *op;
        @field(res, field) = value;
        return res;
    }
};

const default = Options {
    .str = "",
    .int = 0,
    .uint = 0,
    .a = false,
    .b = false,
    .cc = false,
};

fn testNoErr(comptime clap: &const Clap(Options), args: []const []const u8, expected: &const Options) void {
    var arg_iter = core.ArgSliceIterator.init(args);
    const actual = clap.parse(debug.global_allocator, &arg_iter.iter) catch unreachable;
    assert(mem.eql(u8, expected.str, actual.str));
    assert(expected.int == actual.int);
    assert(expected.uint == actual.uint);
    assert(expected.a == actual.a);
    assert(expected.b == actual.b);
    assert(expected.cc == actual.cc);
}

fn testErr(comptime clap: &const Clap(Options), args: []const []const u8, expected: error) void {
    var arg_iter = core.ArgSliceIterator.init(args);
    if (clap.parse(debug.global_allocator, &arg_iter.iter)) |actual| {
        unreachable;
    } else |err| {
        assert(err == expected);
    }
}

test "clap.core" {
    _ = core;
}

test "clap: short" {
    const clap = comptime Clap(Options) {
        .defaults = default,
        .params = []Param {
            Param.smart("a"),
            Param.smart("b"),
            Param.smart("int")
                .with("short", 'i')
                .with("takes_value", Parser.int(i64, 10))
        }
    };

    testNoErr(clap, [][]const u8 { "-a" },       default.with("a", true));
    testNoErr(clap, [][]const u8 { "-a", "-b" }, default.with("a", true).with("b",  true));
    testNoErr(clap, [][]const u8 { "-i=100" },   default.with("int", 100));
    testNoErr(clap, [][]const u8 { "-i100" },   default.with("int", 100));
    testNoErr(clap, [][]const u8 { "-i", "100" },   default.with("int", 100));
    testNoErr(clap, [][]const u8 { "-ab" },      default.with("a", true).with("b",  true));
    testNoErr(clap, [][]const u8 { "-abi", "100" }, default.with("a", true).with("b", true).with("int",  100));
    testNoErr(clap, [][]const u8 { "-abi=100" }, default.with("a", true).with("b", true).with("int",  100));
    testNoErr(clap, [][]const u8 { "-abi100" }, default.with("a", true).with("b", true).with("int",  100));
}

test "clap: long" {
    const clap = comptime Clap(Options) {
        .defaults = default,
        .params = []Param {
            Param.smart("cc"),
            Param.smart("int").with("takes_value", Parser.int(i64, 10)),
            Param.smart("uint").with("takes_value", Parser.int(u64, 10)),
            Param.smart("str").with("takes_value", Parser.string),
        }
    };

    testNoErr(clap, [][]const u8 { "--cc" },         default.with("cc",  true));
    testNoErr(clap, [][]const u8 { "--int", "100" }, default.with("int",  100));
}

test "clap: value bool" {
    const clap = comptime Clap(Options) {
        .defaults = default,
        .params = []Param {
            Param.smart("a"),
        }
    };

    testNoErr(clap, [][]const u8 { "-a" }, default.with("a",  true));
}

test "clap: value str" {
    const clap = comptime Clap(Options) {
        .defaults = default,
        .params = []Param {
            Param.smart("str").with("takes_value", Parser.string),
        }
    };

    testNoErr(clap, [][]const u8 { "--str", "Hello World!" }, default.with("str", "Hello World!"));
}

test "clap: value int" {
    const clap = comptime Clap(Options) {
        .defaults = default,
        .params = []Param {
            Param.smart("int").with("takes_value", Parser.int(i64, 10)),
        }
    };

    testNoErr(clap, [][]const u8 { "--int", "100" }, default.with("int", 100));
}

test "clap: position" {
    const clap = comptime Clap(Options) {
        .defaults = default,
        .params = []Param {
            Param.smart("a").with("position", 0),
            Param.smart("b").with("position", 1),
        }
    };

    testNoErr(clap, [][]const u8 { "-a", "-b" }, default.with("a", true).with("b", true));
    testErr(clap, [][]const u8 { "-b", "-a" }, error.InvalidPosition);
}

test "clap: sub fields" {
    const B = struct {
        a: bool,
    };
    const A = struct {
        b: B,
    };

    const clap = comptime Clap(A) {
        .defaults = A { .b = B { .a = false } },
        .params = []Param {
            Param.short('a')
                .with("field", "b.a"),
        }
    };

    var arg_iter = core.ArgSliceIterator.init([][]const u8{ "-a" });
    const res = clap.parse(debug.global_allocator, &arg_iter.iter) catch unreachable;
    debug.assert(res.b.a == true);
}