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
use std::error::Error;
use std::ffi::OsString;
use std::fmt::{ self, Display };
use std::path::PathBuf;

pub trait ArgsParse: Sized {
	fn parse <Iter> (iter: Iter) -> Result <Self, ArgsParseError>
		where Iter: IntoIterator <Item = OsString>;
}

#[ derive (Debug, Clone) ]
pub enum ArgsParseError {
	Unexpected (OsString),
	MissingArg (& 'static str),
	MissingValue (& 'static str),
	Duplicated (& 'static str),
	Invalid (& 'static str, OsString, String),
}

impl Display for ArgsParseError {

	#[ inline ]
	fn fmt (& self, fmtr: & mut fmt::Formatter) -> fmt::Result {
		match * self {
			Self::Unexpected (ref arg) =>
				write! (fmtr, "Unexpected argument {}", arg.to_string_lossy ()),
			Self::MissingArg (arg) =>
				write! (fmtr, "Missing argument {arg}"),
			Self::MissingValue (arg) =>
				write! (fmtr, "Missing value for {arg}"),
			Self::Duplicated (arg) =>
				write! (fmtr, "Duplicated argument {arg}"),
			Self::Invalid (arg, ref val, ref msg) =>
				write! (fmtr, "Invalid value for {arg}: {}: {msg}", val.to_string_lossy ()),
		}
	}
}

impl Error for ArgsParseError {
}

pub trait ArgsParseOuter: Sized {

	type State;

	fn init () -> Self::State;

	fn handle (
		name: & 'static str,
		state: & mut Self::State,
		args: & mut dyn Iterator <Item = OsString>,
	) -> Result <(), ArgsParseError>;

	fn finish (
		name: & 'static str,
		state: Self::State,
	) -> Result <Self, ArgsParseError>;

}

impl ArgsParseOuter for bool {

	type State = Self;

	#[ inline ]
	fn init () -> Self {
		false
	}

	#[ inline ]
	fn handle (
		name: & 'static str,
		state: & mut Self::State,
		_args: & mut dyn Iterator <Item = OsString>,
	) -> Result <(), ArgsParseError> {
		if * state {
			return Err (ArgsParseError::Duplicated (name));
		}
		* state = true;
		Ok (())
	}

	#[ inline ]
	fn finish (
		_name: & 'static str,
		state: Self::State,
	) -> Result <Self, ArgsParseError> {
		Ok (state)
	}

}

impl <Inner> ArgsParseOuter for Option <Inner> where Inner: ArgsParseInner {

	type State = Self;

	#[ inline ]
	fn init () -> Self {
		None
	}

	#[ inline ]
	fn handle (
		name: & 'static str,
		state: & mut Self,
		args: & mut dyn Iterator <Item = OsString>,
	) -> Result <(), ArgsParseError> {
		if state.is_some () { return Err (ArgsParseError::Duplicated (name)); }
		* state = Some (Inner::parse (name, args) ?);
		Ok (())
	}

	#[ inline ]
	fn finish (
		_name: & 'static str,
		state: Self,
	) -> Result <Self, ArgsParseError> {
		Ok (state)
	}

}

impl <Inner> ArgsParseOuter for Vec <Inner> where Inner: ArgsParseInner {

	type State = Self;

	#[ inline ]
	fn init () -> Self {
		Self::new ()
	}

	#[ inline ]
	fn handle (
		name: & 'static str,
		state: & mut Self,
		args: & mut dyn Iterator <Item = OsString>,
	) -> Result <(), ArgsParseError> {
		state.push (Inner::parse (name, args) ?);
		Ok (())
	}

	#[ inline ]
	fn finish (
		_name: & 'static str,
		state: Self,
	) -> Result <Self, ArgsParseError> {
		Ok (state)
	}

}

impl <Inner: ArgsParseInner> ArgsParseOuter for Inner {

	type State = Option <Self>;

	#[ inline ]
	fn init () -> Option <Self> {
		None
	}

	#[ inline ]
	fn handle (
		name: & 'static str,
		state: & mut Option <Self>,
		args: & mut dyn Iterator <Item = OsString>,
	) -> Result <(), ArgsParseError> {
		if state.is_some () { return Err (ArgsParseError::Duplicated (name)); }
		* state = Some (Inner::parse (name, args) ?);
		Ok (())
	}

	#[ inline ]
	fn finish (name: & 'static str, state: Option <Inner>) -> Result <Self, ArgsParseError> {
		state.ok_or (ArgsParseError::MissingArg (name))
	}

}

pub trait ArgsParseInner: Sized {

	fn parse (
		name: & 'static str,
		args: & mut dyn Iterator <Item = OsString>,
	) -> Result <Self, ArgsParseError>;

}

impl ArgsParseInner for PathBuf {

	#[ inline ]
	fn parse (
		name: & 'static str,
		args: & mut dyn Iterator <Item = OsString>,
	) -> Result <Self, ArgsParseError> {
		let arg_os = args.next ().ok_or (ArgsParseError::MissingValue (name)) ?;
		Ok (arg_os.into ())
	}

}

impl ArgsParseInner for String {

	#[ inline ]
	fn parse (
		name: & 'static str,
		args: & mut dyn Iterator <Item = OsString>,
	) -> Result <Self, ArgsParseError> {
		let arg_os = args.next ().ok_or (ArgsParseError::MissingValue (name)) ?;
		let arg = arg_os.into_string ().map_err (|arg_os|
			ArgsParseError::Invalid (name, arg_os, "Invalid UTF-8".to_owned ())) ?;
		Ok (arg)
	}

}

impl ArgsParseInner for u16 {

	#[ inline ]
	fn parse (
		name: & 'static str,
		args: & mut dyn Iterator <Item = OsString>,
	) -> Result <Self, ArgsParseError> {
		let arg_os = args.next ().ok_or (ArgsParseError::MissingValue (name)) ?;
		let arg = arg_os.to_str ().ok_or_else (||
			ArgsParseError::Invalid (name, arg_os.clone (), "Invalid number".to_owned ())) ?;
		arg.parse ().ok ().ok_or_else (||
			ArgsParseError::Invalid (name, arg_os, "Invalid number".to_owned ()))
	}

}

impl ArgsParseInner for u32 {

	#[ inline ]
	fn parse (
		name: & 'static str,
		args: & mut dyn Iterator <Item = OsString>,
	) -> Result <Self, ArgsParseError> {
		let arg_os = args.next ().ok_or (ArgsParseError::MissingValue (name)) ?;
		let arg = arg_os.to_str ().ok_or_else (||
			ArgsParseError::Invalid (name, arg_os.clone (), "Invalid number".to_owned ())) ?;
		arg.parse ().ok ().ok_or_else (||
			ArgsParseError::Invalid (name, arg_os, "Invalid number".to_owned ()))
	}

}

impl ArgsParseInner for u64 {

	#[ inline ]
	fn parse (
		name: & 'static str,
		args: & mut dyn Iterator <Item = OsString>,
	) -> Result <Self, ArgsParseError> {
		let arg_os = args.next ().ok_or (ArgsParseError::MissingValue (name)) ?;
		let arg = arg_os.to_str ().ok_or_else (||
			ArgsParseError::Invalid (name, arg_os.clone (), "Invalid number".to_owned ())) ?;
		arg.parse ().ok ().ok_or_else (||
			ArgsParseError::Invalid (name, arg_os, "Invalid number".to_owned ()))
	}

}

impl ArgsParseInner for usize {

	#[ inline ]
	fn parse (
		name: & 'static str,
		args: & mut dyn Iterator <Item = OsString>,
	) -> Result <Self, ArgsParseError> {
		let arg_os = args.next ().ok_or (ArgsParseError::MissingValue (name)) ?;
		let arg = arg_os.to_str ().ok_or_else (||
			ArgsParseError::Invalid (name, arg_os.clone (), "Invalid number".to_owned ())) ?;
		arg.parse ().ok ().ok_or_else (||
			ArgsParseError::Invalid (name, arg_os, "Invalid number".to_owned ()))
	}

}

#[ inline ]
#[ must_use ]
pub fn arg_matches (search: & str, arg_bytes: & [u8]) -> bool {
	2 < arg_bytes.len () && arg_bytes [0] == b'-' && arg_bytes [1] == b'-'
		&& arg_bytes [2 .. ].iter ().copied ().eq (
			search.bytes ().map (|ch| if ch == b'_' { b'-' } else { ch }))
}

#[ macro_export ]
macro_rules! args_decl {

	(
		$( #[ $($attr:tt)* ] )*
		$vis:vis struct $name:ident { $(
			$mem_vis:vis $mem_name:ident: $mem_type:ty
		),* $(,)? }
	) => {

		$( #[ $($attr)* ] )*
		$vis struct $name { $(
			$mem_vis $mem_name: $mem_type,
		)* }

		impl $crate::ArgsParse for $name {

			#[ allow (clippy::useless_let_if_seq) ]
			fn parse <Iter> (args_iter: Iter) -> Result <Self, $crate::ArgsParseError>
				where Iter: IntoIterator <Item = ::std::ffi::OsString> {

				$( let mut $mem_name = <$mem_type as $crate::ArgsParseOuter>::init (); )*

				let mut args_iter = args_iter.into_iter ();
				let mut literal_args = false;

				while let Some (arg) = args_iter.next () {
					let arg_bytes = ::std::os::unix::ffi::OsStrExt::as_bytes (arg.as_os_str ());
					let mut matched = false;
					if ! literal_args && arg_bytes == b"--" {
						literal_args = true;
						matched = true;
					}
					$(
						if ! literal_args && ! matched
								&& $crate::arg_matches (stringify! ($mem_name), arg_bytes) {
							<$mem_type>::handle (
								stringify! ($mem_name),
								& mut $mem_name,
								& mut args_iter) ?;
							matched = true;
						}
					)*
					if ! matched {
						return Err ($crate::ArgsParseError::Unexpected (arg));
					}
				}

				Ok (Self {
					$(
						$mem_name: <$mem_type as ArgsParseOuter>::finish (
							stringify! ($mem_name),
							$mem_name) ?
					),*
				})

			}

		}

	};

}