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
use std::{borrow::Cow, cell::Cell, ops::RangeBounds, range::Range};
use crate::{
ArgErrCtx, ArgErrKind, ArgError, ArgInto, FromArg, FromArgs, FromRead,
Result, arg_list, arg_to_string_lossy, bool_arg, key_arg, key_mval_arg,
key_val_arg, mval_arg, opt_bool_arg, split_arg, try_set_arg,
try_set_arg_with, utils::get_range, val_arg,
};
/// Helper for parsing arguments.
///
/// Reference to pareg structure. Mutating this can mutate original
/// [`crate::Pareg`] structure. You can use [`ParegRef::mutates_original`] to
/// check if this instance will mutate original pareg.
///
/// Note that the clones will not affect the original pareg even if the
/// original [`ParegRef`] did so you can clone if you don't want to mutate the
/// original.
///
/// In contrast to [`crate::Pareg`], it allows
/// calling mutable functions while there are immutable references to the
/// original arguments.
#[derive(Debug)]
pub struct ParegRef<'a, S: ArgInto<'a> = String> {
args: &'a [S],
cur: Cow<'a, Cell<usize>>,
}
impl<'a, S: ArgInto<'a>> ParegRef<'a, S> {
/// Creates referenced pareg from arguments and current index.
#[inline]
pub fn new(args: &'a [S], cur: impl Into<Cow<'a, Cell<usize>>>) -> Self {
Self {
args,
cur: cur.into(),
}
}
/// Checks if this instance will mutate original [`crate::Pareg`]. If you
/// don't want to mutate the orignal, you can create clone or call
/// [`ParegRef::detach`].
#[inline]
pub fn mutates_original(&self) -> bool {
matches!(self.cur, Cow::Borrowed(_))
}
/// Detach from the original pareg structure. Mutating this will no longer
/// mutate the original [`crate::Pareg`] structure (if it did before).
pub fn detach(&mut self) {
self.cur = Cow::Owned(self.cur.as_ref().clone());
}
/// Get the next string in the arguments.
///
/// Note that this may return empty string if the underlaying conversion to
/// string fails (e.g. when converting from OsString with invalid unicode)
pub fn next_str(&mut self) -> Option<&'a str> {
self.next().map(|a| a.arg_into().unwrap_or_default())
}
/// Get the last returned argument.
#[inline]
pub fn cur(&self) -> Option<&'a S> {
let idx = self.cur.get();
(idx != 0).then(|| &self.args[idx - 1])
}
/// Get argument at the given index.
#[inline]
pub fn get(&self, idx: usize) -> Option<&'a S> {
(idx < self.args.len()).then(|| &self.args[idx])
}
/// Get value that will be returned with the next call to `next`.
#[inline]
pub fn peek(&self) -> Option<&'a S> {
self.get(self.cur.get())
}
/// Gets the remaining arguments (not including the current).
#[inline]
pub fn remaining(&self) -> &'a [S] {
&self.args[self.cur.get()..]
}
/// Gets the remaining arguments (including the current).
#[inline]
pub fn cur_remaining(&self) -> &'a [S] {
&self.args[self.cur.get().saturating_sub(1)..]
}
/// Gets all the arguments (including the first one).
#[inline]
pub fn all_args(&self) -> &'a [S] {
self.args
}
/// Jump so that the argument at index `idx` is the next argument. Gets the
/// argument at `idx - 1`.
#[inline]
pub fn jump(&mut self, idx: usize) -> Option<&'a S> {
self.cur.set(idx.min(self.args.len()));
self.cur()
}
/// Equivalent to calling next `cnt` times.
#[inline]
pub fn skip_args(&mut self, cnt: usize) -> Option<&'a S> {
self.jump(self.cur.get() + cnt)
}
/// Skip all remaining arguments and return the last.
#[inline]
pub fn skip_all(&mut self) -> Option<&'a S> {
self.jump(self.args.len())
}
/// Jump to the zeroth argument.
#[inline]
pub fn reset(&mut self) {
self.jump(0);
}
/// Get the index of the next argument.
#[inline]
pub fn next_idx(&self) -> Option<usize> {
let cur = self.cur.get();
(cur < self.args.len()).then_some(cur)
}
/// Get index of the current argument.
#[inline]
pub fn cur_idx(&self) -> Option<usize> {
let cur = self.cur.get();
(cur != 0 && (cur - 1) < self.args.len()).then(|| cur - 1)
}
/// Perform manual parsing on the next argument. This is will make the
/// errors have better messages than just doing the parsing without
/// [`ParegRef`].
///
/// `pareg.next_manual(foo)` is equivalent to
/// `pareg.map_err(foo(pareg.next()))`.
#[inline]
pub fn next_manual<T>(
&mut self,
f: impl Fn(&'a str) -> Result<T>,
) -> Result<T> {
let a = self.next_arg()?;
self.map_res(f(a))
}
/// Perform manual parsing on the next argument. This is will make the
/// errors have better messages than just doing the parsing without
/// [`ParegRef`].
///
/// `pareg.cur_manual(foo)` is equivalent to
/// `pareg.map_err(foo(pareg.cur()))`.
pub fn cur_manual<T>(
&self,
f: impl Fn(&'a str) -> Result<T>,
) -> Result<T> {
self.map_res(f(self.cur_arg()?))
}
/// Parses the next value in the iterator.
#[inline]
pub fn next_arg<T: FromArg<'a>>(&mut self) -> Result<T> {
if let Some(a) = self.next() {
self.map_res(a.arg_into())
} else {
Err(self.err_no_more_arguments())
}
}
/// Uses the function [`key_mval_arg`] on the next argument.
///
/// If sep was `'='`, parses `"key=value"` into `"key"` and `value` that is
/// also parsed to the given type.
///
/// In case that there is no `'='`, value is `None`.
#[inline]
pub fn next_key_mval<K: FromArg<'a>, V: FromArg<'a>>(
&mut self,
sep: char,
) -> Result<(K, Option<V>)> {
let arg = self.next_arg()?;
self.map_res(key_mval_arg(arg, sep))
}
/// Uses the function [`key_val_arg`] on the next value.
///
/// If sep was `'='`, parses `"key=value"` into `"key"` and `value` that is
/// also parsed to the given type.
///
/// In case that there is no `'='`, returns [`ArgError::NoValue`].
#[inline]
pub fn next_key_val<K: FromArg<'a>, V: FromArg<'a>>(
&mut self,
sep: char,
) -> Result<(K, V)> {
let arg = self.next_arg()?;
self.map_res(key_val_arg(arg, sep))
}
/// Uses the function [`bool_arg`] on the next value.
///
/// Parse bool value in a specific way. If the value of lowercase `arg` is
/// equal to `t` returns true, if it is equal to `f` returns false and
/// otherwise returns error.
#[inline]
pub fn next_bool(&mut self, t: &str, f: &str) -> Result<bool> {
let arg = self.next_arg()?;
self.map_res(bool_arg(t, f, arg))
}
/// Uses the function [`opt_bool_arg`] on the next argument.
///
/// Parse bool value in a specific way. If the value of lowercase `arg` is
/// equal to `t` returns true, if it is equal to `f` returns false and
/// if it is equal to `n` returns [`None`]. Otherwise returns error.
#[inline]
pub fn next_opt_bool(
&mut self,
t: &str,
f: &str,
n: &str,
) -> Result<Option<bool>> {
let arg = self.next_arg()?;
self.map_res(opt_bool_arg(t, f, n, arg))
}
/// Uses the function [`key_arg`] on the next value.
///
/// If sep was `'='`, parses `"key=value"` into `"key"` and discards `value`.
///
/// In case that there is no `'='`, parses the whole input.
#[inline]
pub fn next_key<T: FromArg<'a>>(&mut self, sep: char) -> Result<T> {
let arg = self.next_arg()?;
self.map_res(key_arg(arg, sep))
}
/// Uses the function [`val_arg`] on the next value.
///
/// If sep was `'='`, parses `"key=value"` into `value` that is parsed to the
/// given type.
///
/// In case that there is no `'='`, returns [`ArgError::NoValue`].
#[inline]
pub fn next_val<T: FromArg<'a>>(&mut self, sep: char) -> Result<T> {
let arg = self.next_arg()?;
self.map_res(val_arg(arg, sep))
}
/// Uses the function [`mval_arg`] on the next argument.
///
/// If sep was `'='`, parses `"key=value"` into `value` that is parsed to the
/// given type.
///
/// In case that there is no `'='`, value is `None`.
#[inline]
pub fn next_mval<T: FromArg<'a>>(
&mut self,
sep: char,
) -> Result<Option<T>> {
let arg = self.next_arg()?;
self.map_res(mval_arg(arg, sep))
}
/// Parses the last returned value from the iterator.
#[inline]
pub fn cur_arg<T: FromArg<'a>>(&self) -> Result<T> {
if let Some(arg) = self.cur() {
self.map_res(arg.arg_into())
} else {
panic!("No last argument to parse.");
}
}
/// Uses the function [`key_mval_arg`] on the last argument. If there is no
/// last argument, returns `ArgError::NoLastArgument`.
///
/// If sep was `'='`, parses `"key=value"` into `"key"` and `value` that is
/// also parsed to the given type.
///
/// In case that there is no `'='`, value is `None`.
#[inline]
pub fn cur_key_mval<K: FromArg<'a>, V: FromArg<'a>>(
&self,
sep: char,
) -> Result<(K, Option<V>)> {
self.map_res(key_mval_arg(self.cur_arg()?, sep))
}
/// Uses the function [`key_val_arg`] on the next value. If there is no
/// last argument, returns `ArgError::NoLastArgument`.
///
/// If sep was `'='`, parses `"key=value"` into `"key"` and `value` that is
/// also parsed to the given type.
///
/// In case that there is no `'='`, returns [`ArgError::NoValue`].
#[inline]
pub fn cur_key_val<K: FromArg<'a>, V: FromArg<'a>>(
&self,
sep: char,
) -> Result<(K, V)> {
self.map_res(key_val_arg(self.cur_arg()?, sep))
}
/// Uses the function [`bool_arg`] on the next value. If there is no last
/// argument, returns `ArgError::NoLastArgument`.
///
/// Parse bool value in a specific way. If the value of lowercase `arg` is
/// equal to `t` returns true, if it is equal to `f` returns false and
/// otherwise returns error.
#[inline]
pub fn cur_bool(&self, t: &str, f: &str) -> Result<bool> {
self.map_res(bool_arg(t, f, self.cur_arg()?))
}
/// Uses the function [`opt_bool_arg`] on the next argument. If there is no
/// last argument, returns `ArgError::NoLastArgument`.
///
/// Parse bool value in a specific way. If the value of lowercase `arg` is
/// equal to `t` returns true, if it is equal to `f` returns false and
/// if it is equal to `n` returns [`None`]. Otherwise returns error.
#[inline]
pub fn cur_opt_bool(
&self,
t: &str,
f: &str,
n: &str,
) -> Result<Option<bool>> {
self.map_res(opt_bool_arg(t, f, n, self.cur_arg()?))
}
/// Uses the function [`key_arg`] on the next argument. If there is no
/// last argument, returns `ArgError::NoLastArgument`.
///
/// If sep was `'='`, parses `"key=value"` into `"key"` and discards `value`.
///
/// In case that there is no `'='`, parses the whole input.
#[inline]
pub fn cur_key<T: FromArg<'a>>(&self, sep: char) -> Result<T> {
self.map_res(key_arg(self.cur_arg()?, sep))
}
/// Uses the function [`val_arg`] on the next argument. If there is no
/// last argument, returns `ArgError::NoLastArgument`.
///
/// If sep was `'='`, parses `"key=value"` into `value` that is parsed to the
/// given type.
///
/// In case that there is no `'='`, returns [`ArgError::NoValue`].
#[inline]
pub fn cur_val<T: FromArg<'a>>(&self, sep: char) -> Result<T> {
self.map_res(val_arg(self.cur_arg()?, sep))
}
/// Uses the function [`mval_arg`] on the next argument. If there is no
/// last argument, returns `ArgError::NoLastArgument`.
///
/// If sep was `'='`, parses `"key=value"` into `value` that is parsed to the
/// given type.
///
/// In case that there is no `'='`, value is `None`.
#[inline]
pub fn cur_mval<T: FromArg<'a>>(&self, sep: char) -> Result<Option<T>> {
self.map_res(mval_arg(self.cur_arg()?, sep))
}
/// Split the current argument by the given separator and return the parsed
/// value after the separator or if there is no such separator, parse the
/// next argument.
#[inline]
pub fn cur_val_or_next<T: FromArg<'a>>(&mut self, sep: char) -> Result<T> {
if let Some(res) = self.cur_mval(sep)? {
Ok(res)
} else {
self.next_arg()
}
}
/// Tries to set the value of `res` to some if it is none. Throws error if it
/// is some.
#[inline]
pub fn try_set_cur_with<T>(
&self,
res: &mut Option<T>,
f: impl FnOnce(&'a str) -> Result<T>,
) -> Result<()> {
self.map_res(try_set_arg_with(res, self.cur_arg()?, f))
}
/// Tries to set the value of `res` to some if it is none. Throws error if it
/// is some.
#[inline]
pub fn try_set_next_with<T>(
&mut self,
res: &mut Option<T>,
f: impl FnOnce(&'a str) -> Result<T>,
) -> Result<()> {
let arg = self.next_arg()?;
self.map_res(try_set_arg_with(res, arg, f))
}
/// Tries to set the value of `res` to some if it is none. Throws error if it
/// is some.
#[inline]
pub fn try_set_cur<T: FromArg<'a>>(
&self,
res: &mut Option<T>,
) -> Result<()> {
self.map_res(try_set_arg(res, self.cur_arg()?))
}
/// Tries to set the value of `res` to some if it is none. Throws error if it
/// is some.
#[inline]
pub fn try_set_next<T: FromArg<'a>>(
&mut self,
res: &mut Option<T>,
) -> Result<()> {
let arg = self.next_arg()?;
self.map_res(try_set_arg(res, arg))
}
/// Splits last argument by separator `sep` and parses each word into a
/// resulting vector.
///
/// Difference from [`ParegRef::cur_list`] is that this will first to split
/// and than try to parse.
#[inline]
pub fn split_cur<T: FromArg<'a>>(&self, sep: &str) -> Result<Vec<T>> {
self.map_res(split_arg(self.cur_arg()?, sep))
}
/// Parses multiple values in last argument separated by `sep`.
///
/// Unlike [`ParegRef::split_cur`], this will first try to parse and than
/// check if the separator is present. So valid values may contain contents
/// of `sep`, and it will properly parse the vales, whereas
/// [`ParegRef::split_cur`] would split `arg` and than try to parse.
#[inline]
pub fn cur_list<T: FromRead>(&self, sep: &str) -> Result<Vec<T>> {
self.map_res(arg_list(self.cur_arg()?, sep))
}
/// Splits next argument by separator `sep` and parses each word into a
/// resulting vector.
///
/// Difference from [`ParegRef::next_list`] is that this will first to
/// split and than try to parse.
pub fn split_next<T: FromArg<'a>>(&mut self, sep: &str) -> Result<Vec<T>> {
let arg = self.next_arg()?;
self.map_res(split_arg(arg, sep))
}
/// Parses multiple values in next argument separated by `sep`.
///
/// Unlike [`ParegRef::split_next`], this will first try to parse and than
/// check if the separator is present. So valid values may contain contents
/// of `sep`, and it will properly parse the vales, whereas
/// [`ParegRef::split_next`] would split `arg` and than try to parse.
pub fn next_list<T: FromRead>(&mut self, sep: &str) -> Result<Vec<T>> {
let arg = self.next_arg()?;
self.map_res(arg_list(arg, sep))
}
/// Leave parsing of the next arguments to the `FromArgs` implementation of
/// `T`.
pub fn next_sub<T: FromArgs<'a>>(&mut self) -> Result<T> {
T::parse_args(self)
}
/// Leave the parsing of the current and following arguments to the
/// `FromArgs` implementation of `T`.
pub fn cur_sub<T: FromArgs<'a>>(&mut self) -> Result<T> {
self.cur.set(self.cur.get().saturating_sub(1));
self.next_sub()
}
/// Creates pretty error that the last argument (cur) is unknown.
#[inline]
pub fn err_unknown_argument(&self) -> ArgError {
let arg = self.cur().map(arg_to_string_lossy).unwrap_or_default();
let long_message = self
.cur()
.is_some()
.then(|| format!("Unknown argument `{arg}`").into());
ArgError::new(ArgErrCtx {
args: self.args.iter().map(arg_to_string_lossy).collect(),
error_idx: self.cur.get().saturating_sub(1),
error_span: (0..arg.len()).into(),
inline_msg: Some("Unknown argument.".into()),
long_msg: long_message,
..ArgErrCtx::new(ArgErrKind::UnknownArgument)
})
}
/// Creates error that says that the current argument has invalid value.
#[inline]
pub fn err_invalid(&self) -> ArgError {
self.err_invalid_span(usize::MAX..usize::MAX)
}
/// Creates error that says that the given part of the current argument has
/// invalid value.
#[inline]
pub fn err_invalid_value(&self, value: String) -> ArgError {
self.map_err(ArgError::invalid_value(
"Invalid value for argument.",
value,
))
}
/// Creates error that sais that the current argument is specified too many
/// times.
#[inline]
pub fn err_cur_too_many_arguments(&self) -> ArgError {
self.map_err(ArgError::too_many_arguments(
"Argument specified too many times.",
arg_to_string_lossy(&self.args[self.cur.get().saturating_sub(1)]),
))
}
/// Creates error that says that the given part of the current argument has
/// invalid value.
#[inline]
pub fn err_invalid_span(&self, span: impl RangeBounds<usize>) -> ArgError {
let value = self.cur().map(arg_to_string_lossy).unwrap_or_default();
let mut span = get_range(span);
if span.start > value.len() || span.end > value.len() {
span = Range::from(0..value.len());
}
self.map_err(ArgError::invalid_value(
"Invalid value for argument",
String::new(),
))
.spanned(span)
}
/// Creates pretty error that there should be more arguments but there are
/// no more arguments.
pub fn err_no_more_arguments(&self) -> ArgError {
let last = self.args.last().map(arg_to_string_lossy);
let pos = last.as_deref().map_or(0, |a| a.len());
let long_message = last.map(|a| {
format!("Expected more arguments after the argument `{a}`.",)
.into()
});
ArgError::new(ArgErrCtx {
args: self.args.iter().map(arg_to_string_lossy).collect(),
error_idx: self.args.len().saturating_sub(1),
error_span: (pos..pos).into(),
inline_msg: Some("Expected more arguments.".into()),
long_msg: long_message,
..ArgErrCtx::new(ArgErrKind::NoMoreArguments)
})
}
/// Adds additional information to error so that it has better error
/// message. Consider using [`ParegRef::cur_manual`] or
/// [`ParegRef::next_manual`] instead.
#[inline(always)]
pub fn map_err(&self, err: ArgError) -> ArgError {
err.add_args(
self.args.iter().map(arg_to_string_lossy).collect(),
self.cur.get().saturating_sub(1),
)
}
/// Adds additional information to error in result so that it has better
/// error message. Consider using [`ParegRef::cur_manual`] or
/// [`ParegRef::next_manual`] instead.
#[inline(always)]
pub fn map_res<T>(&self, res: Result<T>) -> Result<T> {
res.map_err(|e| self.map_err(e))
}
}
impl<'a, T: ArgInto<'a>> Iterator for ParegRef<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
let cur = self.cur.get();
(cur < self.args.len()).then(|| {
self.cur.set(cur + 1);
&self.args[cur]
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.remaining().len();
(len, Some(len))
}
fn count(self) -> usize {
self.remaining().len()
}
fn last(self) -> Option<Self::Item> {
self.remaining().last()
}
fn nth(&mut self, n: usize) -> Option<Self::Item> {
let cur = self.cur.get();
let new = cur + n;
(new < self.args.len()).then(|| {
self.cur.set(new);
&self.args[new]
})
}
}
impl<'a, T: ArgInto<'a>> Clone for ParegRef<'a, T> {
/// Note that the clones will not affect the original pareg even if the
/// original [`ParegRef`] did.
fn clone(&self) -> Self {
Self::new(self.args, Cow::Owned(self.cur.as_ref().clone()))
}
}