aboutsummaryrefslogtreecommitdiff
path: root/src/argument.zig
blob: 37d904576a2d908a5e767d0323a9c1895663b09d (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
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:
		\\         -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.
		\\
		\\  recognize [grammar] [options]
		\\       Options:
		\\         -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.
		\\
		\\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 {
	recognize,
	generate,
};

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

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

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

		return Self {
			.name = path,
			.file = cwd.openFile(path, flags) 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 RecognizeArgs = struct {
	input: Entry,
	grammar: Grammar,
};

pub const GenerateArgs = struct {
	count: usize,
	empty: bool,
	output: Entry,
	grammar: Grammar,
};

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

	recognize: RecognizeArgs,
	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);
		const grammar = Grammar.parse(
			text,
			allocator
		) catch |e| help(e);

		switch (mode) {
			.recognize => {
				var input: ?Entry = null;

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

				return Self {
					.recognize = .{
						.input = input orelse Entry.stdin(),
						.grammar = grammar,
					},
				};
			},

			.generate => {
				var count: usize = 1;
				var output: ?Entry = null;
				var empty: bool = true;

				while (args.next()) |arg| {
					if (check_flags(arg, &[_][]const u8 { "-o", "--output" })) {
						output = Entry.open(check(args.next()), .{ .mode = .write_only });
					} 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" })) {
						empty = false;
					} else help(error.InvalidArgument);
				}

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

	pub fn deinit(self: *Self, allocator: std.mem.Allocator) void {
		switch (self.*) {
			.recognize => |*rec| {
				rec.grammar.deinit(allocator);
			},
			.generate => |*gen| {
				gen.grammar.deinit(allocator);
			}
		}
	}
};