aboutsummaryrefslogtreecommitdiff
path: root/src/argument.zig
blob: 81172fb68e6f95e9d3cbc2b4dfabc80260cf4f54 (plain)
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
const std = @import("std");
pub const Grammar = @import("grammar.zig");

fn help(err: ?anyerror) noreturn {
    const stderr = std.io.getStdErr().writer();

    if (err) |e| {
        stderr.print("error: {s}\n", .{@errorName(e)}) catch unreachable;
    }

    stderr.writeAll(
        \\mry [command] [options]
        \\
        \\Commands:
        \\
        \\  generate [grammar] [options]
        \\       Options:
        \\         -e, --entry label   Name of the entry point. (default: main)
        \\
        \\         -o, --output entry  Output string to file
        \\                             By default stdout will be used.
        \\
        \\         -c, --count n       Number of texts to generate. (default: 1)
        \\
        \\         -n, --non-empty     Only output texts which are non-empty.
        \\
        \\         -m, --min-length n  Minimum length of sentential string.
        \\
        \\  benchmark [grammar] [options]
        \\       Options:
        \\         -e, --entry label   Name of the entry point. (default: main)
        \\
        \\         -i, --input entry   Specify input source, if the path
        \\                             points to a directory it will scan
        \\                             all files in it. By default stdin will
        \\                             be used as input.
        \\
        \\         --csv               output in CSV format.
        \\
        \\General Options
        \\  -h, --help                 Print usage
        \\
        ) catch unreachable;
    std.process.exit(@intFromBool(err != null));
}

fn check(arg_or_null: ?[]const u8) []const u8 {
    const arg = arg_or_null orelse help(error.MissingArgument);

    if (std.mem.eql(u8, arg, "-h") or std.mem.eql(u8, arg, "--help")) {
        help(null);
    }
    return arg;
}

fn parse_enum(T: type, arg: []const u8) T {
    return std.meta.stringToEnum(T, arg) orelse help(error.InvalidArgument);
}

fn parse_int(n: []const u8) usize {
    return std.fmt.parseInt(usize, n, 10) catch |e| help(e);
}

fn check_flags(arg: []const u8, comptime flags: []const []const u8) bool {
    inline for (flags) |flag| {
        if (std.mem.eql(u8, arg, flag)) {
            return true;
        }
    }

    return false;
}

pub const Mode = enum {
    benchmark,
    generate,
};

pub const Entry = struct {
    const Self = @This();

    name: []const u8,
    file: std.fs.File,

    pub fn open(path: []const u8, writer: bool) Self {
        var cwd = std.fs.cwd();

        return Self {
            .name = path,
            .file = (if (writer) cwd.createFile(path, .{})
                else cwd.openFile(path, .{})) catch |e| help(e)
            };
    }

    pub fn read_file(path: []const u8, allocator: std.mem.Allocator) []const u8 {
        var cwd = std.fs.cwd();

        var file = cwd.openFile(path, .{}) catch |e| help(e);
        defer file.close();
        const stat = file.stat() catch |e| help(e);

        return file.readToEndAlloc(allocator, stat.size) catch |e| help(e);
    }

    pub fn stdin() Self {
        return Self {
            .name = "[stdin]",
            .file = std.io.getStdIn(),
        };
    }

    pub fn stdout() Self {
        return Self {
            .name = "[stdout]",
            .file = std.io.getStdOut(),
        };
    }
};

pub const BenchmarkArgs = struct {
    input: Entry,
    grammar: Grammar,
    entry: []const u8,
    csv: bool,
};

pub const GenerateArgs = struct {
    count: usize,
    min_length: usize,
    output: Entry,
    grammar: Grammar,
    entry: []const u8,
};

pub const Args = union(Mode) {
    const Self = @This();

    benchmark: BenchmarkArgs,
    generate: GenerateArgs,

    pub fn parse(allocator: std.mem.Allocator) Self {
        var args = std.process.args();
        _ = args.next();

        const mode = parse_enum(Mode, check(args.next()));

        const text = Entry.read_file(check(args.next()), allocator);
        defer allocator.free(text);

        switch (mode) {
            .benchmark => {
                var input: ?Entry = null;
                var entry: []const u8 = "main";
                var csv = false;

                while (args.next()) |arg| {
                    if (check_flags(arg, &[_][]const u8 { "-i", "--input" })) {
                        input = Entry.open(check(args.next()), false);
                    } else if (check_flags(arg, &[_][]const u8 { "-e", "--entry" })) {
                        entry = check(args.next());
                    } else if (check_flags(arg, &[_][]const u8 { "--csv" })) {
                        csv = true;
                    } else help(error.InvalidArgument);
                }

                const grammar = Grammar.parse(
                    entry,
                    text,
                    allocator
                ) catch |e| help(e);

                return Self {
                    .benchmark = .{
                        .input = input orelse Entry.stdin(),
                        .grammar = grammar,
                        .entry = entry,
                        .csv = csv,
                    },
                };
            },

            .generate => {
                var count: usize = 1;
                var output: ?Entry = null;
                var min_length: usize = 0;
                var entry: []const u8 = "main";

                while (args.next()) |arg| {
                    if (check_flags(arg, &[_][]const u8 { "-o", "--output" })) {
                        output = Entry.open(check(args.next()), true);
                    } else if (check_flags(arg, &[_][]const u8 { "-c", "--count" })) {
                        count = parse_int(check(args.next()));
                    } else if (check_flags(arg, &[_][]const u8 { "-n", "--non-empty" })) {
                        min_length = 1;
                    } else if (check_flags(arg, &[_][]const u8 { "-m", "--min-length" })) {
                        min_length = parse_int(check(args.next()));
                    } else if (check_flags(arg, &[_][]const u8 { "-e", "--entry" })) {
                        entry = check(args.next());
                    } else help(error.InvalidArgument);
                }

                const grammar = Grammar.parse(
                    entry,
                    text,
                    allocator
                ) catch |e| help(e);

                return Self {
                    .generate = .{
                        .count = count,
                        .min_length = min_length,
                        .output = output orelse Entry.stdout(),
                        .grammar = grammar,
                        .entry = entry,
                    },
                };
            },
        }
    }

    pub fn deinit(self: *Self) void {
        switch (self.*) {
            .benchmark => |*rec| {
                rec.grammar.deinit();
            },
            .generate => |*gen| {
                gen.grammar.deinit();
            }
        }
    }
};