Debian Codegraph @

helix-core/src/command_line.rs

raw symbols SCIP
1 //! Types and parsing code for command mode (`:`) input.
2 //!
3 //! Command line parsing is done in steps:
4 //!
5 //! * The `Tokenizer` iterator returns `Token`s from the command line input naively - without
6 //! accounting for a command's signature.
7 //! * When executing a command (pressing `<ret>` in command mode), tokens are expanded with
8 //! information from the editor like the current cursor line or column. Otherwise the tokens
9 //! are unwrapped to their inner content.
10 //! * `Args` interprets the contents (potentially expanded) as flags or positional arguments.
11 //! When executing a command, `Args` performs validations like checking the number of positional
12 //! arguments supplied and whether duplicate or unknown flags were supplied.
13 //!
14 //! `Args` is the interface used by typable command implementations. `Args` may be treated as a
15 //! slice of `Cow<str>` or `&str` to access positional arguments, for example `for arg in args`
16 //! iterates over positional args (never flags) and `&args[0]` always corresponds to the first
17 //! positional. Use `Args::has_flag` and `Args::get_flag` to read any specified flags.
18 //!
19 //! `Args` and `Tokenizer` are intertwined. `Args` may ask the `Tokenizer` for the rest of the
20 //! command line as a single token after the configured number of positionals has been reached
21 //! (according to `raw_after`). This is used for the custom parsing in `:set-option` and
22 //! `:toggle-option` for example. Outside of executing commands, the `Tokenizer` can be used
23 //! directly to interpret a string according to the regular tokenization rules.
24 //!
25 //! This module also defines structs for configuring the parsing of the command line for a
26 //! command. See `Flag` and `Signature`.
27
28 use std::{borrow::Cow, collections::HashMap, error::Error, fmt, ops, slice, vec};
29
30 /// Splits a command line into the command and arguments parts.
31 ///
32 /// The third tuple member describes whether the command part is finished. When this boolean is
33 /// true the completion code for the command line should complete command names, otherwise
34 /// command arguments.
35 pub fn split(line: &str) -> (&str, &str, bool) {
36 const SEPARATOR_PATTERN: [char; 2] = [' ', '\t'];
37
38 let (command, rest) = line.split_once(SEPARATOR_PATTERN).unwrap_or((line, ""));
39
40 let complete_command =
41 command.is_empty() || (rest.trim().is_empty() && !line.ends_with(SEPARATOR_PATTERN));
42
43 (command, rest, complete_command)
44 }
45
46 /// A Unix-like flag that a command may accept.
47 ///
48 /// For example the `:sort` command accepts a `--reverse` (or `-r` for shorthand) boolean flag
49 /// which controls the direction of sorting. Flags may accept an argument by setting the
50 /// `completions` field to `Some`.
51 #[derive(Debug, Clone, Copy)]
52 pub struct Flag {
53 /// The name of the flag.
54 ///
55 /// This value is also used to construct the "longhand" version of the flag. For example a
56 /// flag with a name "reverse" has a longhand `--reverse`.
57 ///
58 /// This value should be supplied when reading a flag out of the [Args] with [Args::get_flag]
59 /// and [Args::has_flag]. The `:sort` command implementation for example should ask for
60 /// `args.has_flag("reverse")`.
61 pub name: &'static str,
62 /// The character that can be used as a shorthand for the flag, optionally.
63 ///
64 /// For example a flag like "reverse" mentioned above might take an alias `Some('r')` to
65 /// allow specifying the flag as `-r`.
66 pub alias: Option<char>,
67 pub doc: &'static str,
68 /// The completion values to use when specifying an argument for a flag.
69 ///
70 /// This should be set to `None` for boolean flags and `Some(&["foo", "bar", "baz"])` for
71 /// example for flags which accept options, with the strings corresponding to values that
72 /// should be shown in completion.
73 pub completions: Option<&'static [&'static str]>,
74 }
75
76 impl Flag {
77 // This allows defining flags with the `..Flag::DEFAULT` shorthand. The `name` and `doc`
78 // fields should always be overwritten.
79 pub const DEFAULT: Self = Self {
80 name: "",
81 doc: "",
82 alias: None,
83 completions: None,
84 };
85 }
86
87 /// A description of how a command's input should be handled.
88 ///
89 /// Each typable command defines a signature (with the help of `Signature::DEFAULT`) at least to
90 /// declare how many positional arguments it accepts. Command flags are also declared in this
91 /// struct. The `raw_after` option may be set optionally to avoid evaluating quotes in parts of
92 /// the command line (useful for shell commands for example).
93 #[derive(Debug, Clone, Copy)]
94 #[allow(clippy::manual_non_exhaustive)]
95 pub struct Signature {
96 /// The minimum and (optionally) maximum number of positional arguments a command may take.
97 ///
98 /// For example accepting exactly one positional can be specified with `(1, Some(1))` while
99 /// accepting zero-or-more positionals can be specified as `(0, None)`.
100 ///
101 /// The number of positionals is checked when hitting `<ret>` in command mode. If the actual
102 /// number of positionals is outside the declared range then the command is not executed and
103 /// an error is shown instead. For example `:write` accepts zero or one positional arguments
104 /// (`(0, Some(1))`). A command line like `:write a.txt b.txt` is outside the declared range
105 /// and is not accepted.
106 pub positionals: (usize, Option<usize>),
107 /// The number of **positional** arguments for the parser to read with normal quoting rules.
108 ///
109 /// Once the number has been exceeded then the tokenizer returns the rest of the input as a
110 /// `TokenKind::Expand` token (see `Tokenizer::rest`), meaning that quoting rules do not apply
111 /// and none of the remaining text may be treated as a flag.
112 ///
113 /// If this is set to `None` then the entire command line is parsed with normal quoting and
114 /// flag rules.
115 ///
116 /// A good example use-case for this option is `:toggle-option` which sets `Some(1)`.
117 /// Everything up to the first positional argument is interpreted according to normal rules
118 /// and the rest of the input is parsed "raw". This allows `:toggle-option` to perform custom
119 /// parsing on the rest of the input - namely parsing complicated values as a JSON stream.
120 /// `:toggle-option` could accept a flag in the future. If so, the flag would need to come
121 /// before the first positional argument.
122 ///
123 /// Consider these lines for `:toggle-option` which sets `Some(1)`:
124 ///
125 /// * `:toggle foo` has one positional "foo" and no flags.
126 /// * `:toggle foo bar` has two positionals. Expansions for `bar` are evaluated but quotes
127 /// and anything that looks like a flag are treated literally.
128 /// * `:toggle foo --bar` has two positionals: `["foo", "--bar"]`. `--bar` is not considered
129 /// to be a flag because it comes after the first positional.
130 /// * `:toggle --bar foo` has one positional "foo" and one flag "--bar".
131 /// * `:toggle --bar foo --baz` has two positionals `["foo", "--baz"]` and one flag "--bar".
132 pub raw_after: Option<u8>,
133 /// A set of flags that a command may accept.
134 ///
135 /// See the `Flag` struct for more info.
136 pub flags: &'static [Flag],
137 /// Do not set this field. Use `..Signature::DEFAULT` to construct a `Signature` instead.
138 // This field allows adding new fields later with minimal code changes. This works like a
139 // `#[non_exhaustive]` annotation except that it supports the `..Signature::DEFAULT`
140 // shorthand.
141 pub _dummy: (),
142 }
143
144 impl Signature {
145 // This allows defining signatures with the `..Signature::DEFAULT` shorthand. The
146 // `positionals` field should always be overwritten.
147 pub const DEFAULT: Self = Self {
148 positionals: (0, None),
149 raw_after: None,
150 flags: &[],
151 _dummy: (),
152 };
153
154 fn check_positional_count(&self, actual: usize) -> Result<(), ParseArgsError<'static>> {
155 let (min, max) = self.positionals;
156 if min <= actual && max.unwrap_or(usize::MAX) >= actual {
157 Ok(())
158 } else {
159 Err(ParseArgsError::WrongPositionalCount { min, max, actual })
160 }
161 }
162 }
163
164 #[derive(Debug, PartialEq, Eq)]
165 pub enum ParseArgsError<'a> {
166 WrongPositionalCount {
167 min: usize,
168 max: Option<usize>,
169 actual: usize,
170 },
171 UnterminatedToken {
172 token: Token<'a>,
173 },
174 DuplicatedFlag {
175 flag: &'static str,
176 },
177 UnknownFlag {
178 text: Cow<'a, str>,
179 },
180 FlagMissingArgument {
181 flag: &'static str,
182 },
183 MissingExpansionDelimiter {
184 expansion: &'a str,
185 },
186 UnknownExpansion {
187 kind: &'a str,
188 },
189 }
190
191 impl fmt::Display for ParseArgsError<'_> {
192 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193 match self {
194 Self::WrongPositionalCount { min, max, actual } => {
195 write!(f, "expected ")?;
196 let maybe_plural = |n| if n == 1 { "" } else { "s" };
197 match (min, max) {
198 (0, Some(0)) => write!(f, "no arguments")?,
199 (min, Some(max)) if min == max => {
200 write!(f, "exactly {min} argument{}", maybe_plural(*min))?
201 }
202 (min, _) if actual < min => {
203 write!(f, "at least {min} argument{}", maybe_plural(*min))?
204 }
205 (_, Some(max)) if actual > max => {
206 write!(f, "at most {max} argument{}", maybe_plural(*max))?
207 }
208 // `actual` must be either less than `min` or greater than `max` for this type
209 // to be constructed.
210 _ => unreachable!(),
211 }
212
213 write!(f, ", got {actual}")
214 }
215 Self::UnterminatedToken { token } => {
216 write!(f, "unterminated token {}", token.content)
217 }
218 Self::DuplicatedFlag { flag } => {
219 write!(f, "flag '--{flag}' specified more than once")
220 }
221 Self::UnknownFlag { text } => write!(f, "unknown flag '{text}'"),
222 Self::FlagMissingArgument { flag } => {
223 write!(f, "flag '--{flag}' missing an argument")
224 }
225 Self::MissingExpansionDelimiter { expansion } => {
226 if expansion.is_empty() {
227 write!(f, "'%' was not properly escaped. Please use '%%'")
228 } else {
229 write!(f, "missing a string delimiter after '%{expansion}'")
230 }
231 }
232 Self::UnknownExpansion { kind } => {
233 write!(f, "unknown expansion '{kind}'")
234 }
235 }
236 }
237 }
238
239 impl Error for ParseArgsError<'_> {}
240
241 /// The kind of expansion to use on the token's content.
242 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
243 pub enum ExpansionKind {
244 /// Expand variables from the editor's state.
245 ///
246 /// For example `%{cursor_line}`.
247 Variable,
248 /// Treat the token contents as hexadecimal corresponding to a Unicode codepoint value.
249 ///
250 /// For example `%u{25CF}`.
251 Unicode,
252 /// Run the token's contents via the configured shell program.
253 ///
254 /// For example `%sh{echo hello}`.
255 Shell,
256 /// Expand registers from the editor's state.
257 ///
258 /// For example `%reg{a}`.
259 Register,
260 }
261
262 impl ExpansionKind {
263 pub const VARIANTS: &'static [Self] =
264 &[Self::Variable, Self::Unicode, Self::Shell, Self::Register];
265
266 pub const fn as_str(&self) -> &'static str {
267 match self {
268 Self::Variable => "",
269 Self::Unicode => "u",
270 Self::Shell => "sh",
271 Self::Register => "reg",
272 }
273 }
274
275 pub fn from_kind(name: &str) -> Option<Self> {
276 match name {
277 "" => Some(Self::Variable),
278 "u" => Some(Self::Unicode),
279 "sh" => Some(Self::Shell),
280 "reg" => Some(Self::Register),
281 _ => None,
282 }
283 }
284 }
285
286 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
287 pub enum Quote {
288 Single,
289 Backtick,
290 }
291
292 impl Quote {
293 pub const fn char(&self) -> char {
294 match self {
295 Self::Single => '\'',
296 Self::Backtick => '`',
297 }
298 }
299
300 // Quotes can be escaped by doubling them: `'hello '' world'` becomes `hello ' world`.
301 pub const fn escape(&self) -> &'static str {
302 match self {
303 Self::Single => "''",
304 Self::Backtick => "``",
305 }
306 }
307 }
308
309 /// The type of argument being written.
310 ///
311 /// The token kind decides how an argument in the command line will be expanded upon hitting
312 /// `<ret>` in command mode.
313 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
314 pub enum TokenKind {
315 /// Unquoted text.
316 ///
317 /// For example in `:echo hello world`, "hello" and "world" are raw tokens.
318 Unquoted,
319 /// Quoted text which is interpreted literally.
320 ///
321 /// The purpose of this kind is to avoid splitting arguments on whitespace. For example
322 /// `:open 'a b.txt'` will result in opening a file with a single argument `"a b.txt"`.
323 ///
324 /// Using expansions within single quotes or backticks will result in the expansion text
325 /// being shown literally. For example `:echo '%u{0020}'` will print `"%u{0020}"` to the
326 /// statusline.
327 Quoted(Quote),
328 /// Text within double quote delimiters (`"`).
329 ///
330 /// The inner text of a double quoted argument can be further expanded. For example
331 /// `:echo "line: #%{cursor_line}"` could print `"line: #1"` to the statusline.
332 Expand,
333 /// An expansion / "percent token".
334 ///
335 /// These take the form `%[<kind>]<open><contents><close>`. See `ExpansionKind`.
336 Expansion(ExpansionKind),
337 /// A token kind that exists for the sake of completion.
338 ///
339 /// In input like `%foo` this token contains the text `"%foo"`. The content start is the byte
340 /// after the percent token.
341 ///
342 /// When `Tokenizer` is passed `true` for its `validate` parameter this token cannot be
343 /// returned: inputs that would return this token get a validation error instead.
344 ExpansionKind,
345 }
346
347 #[derive(Debug, Clone, PartialEq, Eq)]
348 pub struct Token<'a> {
349 pub kind: TokenKind,
350 /// The byte index into the input where the token's content starts.
351 ///
352 /// For quoted text this means the byte after the quote. For expansions this means the byte
353 /// after the opening delimiter.
354 pub content_start: usize,
355 /// The inner content of the token.
356 ///
357 /// Usually this content borrows from the input but an owned value may be used in cases of
358 /// escaping. On Unix systems a raw token like `a\ b` has the contents `"a b"`.
359 pub content: Cow<'a, str>,
360 /// Whether the token's opening delimiter is closed.
361 ///
362 /// For example a quote `"foo"` is closed but not `"foo` or an expansion `%sh{..}` is closed
363 /// but not `%sh{echo {}`.
364 pub is_terminated: bool,
365 }
366
367 impl<'a> Token<'a> {
368 pub fn empty_at(content_start: usize) -> Self {
369 Self {
370 kind: TokenKind::Unquoted,
371 content_start,
372 content: Cow::Borrowed(""),
373 is_terminated: false,
374 }
375 }
376
377 pub fn expand(content: impl Into<Cow<'a, str>>) -> Self {
378 Self {
379 kind: TokenKind::Expand,
380 content_start: 0,
381 content: content.into(),
382 is_terminated: true,
383 }
384 }
385 }
386
387 #[derive(Debug)]
388 pub struct Tokenizer<'a> {
389 input: &'a str,
390 /// Whether to return errors in the iterator for failed validations like unterminated strings
391 /// or expansions. When this is set to `false` the iterator will never return `Err`.
392 validate: bool,
393 /// The current byte index of the input being considered.
394 pos: usize,
395 }
396
397 impl<'a> Tokenizer<'a> {
398 pub fn new(input: &'a str, validate: bool) -> Self {
399 Self {
400 input,
401 validate,
402 pos: 0,
403 }
404 }
405
406 /// Returns the current byte index position of the parser in the input.
407 pub fn pos(&self) -> usize {
408 self.pos
409 }
410
411 /// Returns the rest of the input as a single `TokenKind::Expand` token literally.
412 ///
413 /// Returns `None` if the tokenizer is already at the end of the input or advances the
414 /// tokenizer to the end of the input otherwise. Leading whitespace characters are skipped.
415 /// Quoting is not interpreted.
416 pub fn rest(&mut self) -> Option<Token<'a>> {
417 self.skip_blanks();
418
419 if self.pos == self.input.len() {
420 return None;
421 }
422
423 let content_start = self.pos;
424 self.pos = self.input.len();
425 Some(Token {
426 kind: TokenKind::Expand,
427 content_start,
428 content: Cow::Borrowed(&self.input[content_start..]),
429 is_terminated: false,
430 })
431 }
432
433 fn byte(&self) -> Option<u8> {
434 self.input.as_bytes().get(self.pos).copied()
435 }
436
437 fn peek_byte(&self) -> Option<u8> {
438 self.input.as_bytes().get(self.pos + 1).copied()
439 }
440
441 fn prev_byte(&self) -> Option<u8> {
442 self.pos
443 .checked_sub(1)
444 .map(|idx| self.input.as_bytes()[idx])
445 }
446
447 fn skip_blanks(&mut self) {
448 while let Some(b' ' | b'\t') = self.byte() {
449 self.pos += 1;
450 }
451 }
452
453 fn parse_unquoted(&mut self) -> Cow<'a, str> {
454 // Note that `String::new` starts with no allocation. We only allocate if we see a
455 // backslash escape (on Unix only).
456 let mut escaped = String::new();
457 let mut start = self.pos;
458
459 while let Some(byte) = self.byte() {
460 if matches!(byte, b' ' | b'\t') {
461 if cfg!(unix) && self.prev_byte() == Some(b'\\') {
462 // Push everything up to but not including the backslash and then this
463 // whitespace character.
464 escaped.push_str(&self.input[start..self.pos - 1]);
465 escaped.push(byte as char);
466 start = self.pos + 1;
467 } else if escaped.is_empty() {
468 return Cow::Borrowed(&self.input[start..self.pos]);
469 } else {
470 break;
471 }
472 }
473
474 self.pos += 1;
475 }
476
477 // Special case for a trailing backslash on Unix: exclude the backslash from the content.
478 // This improves the behavior of completions like `":open a\\"` (trailing backslash).
479 let end = if cfg!(unix) && self.prev_byte() == Some(b'\\') {
480 self.pos - 1
481 } else {
482 self.pos
483 };
484
485 if escaped.is_empty() {
486 assert_eq!(self.pos, self.input.len());
487 Cow::Borrowed(&self.input[start..end])
488 } else {
489 escaped.push_str(&self.input[start..end]);
490 Cow::Owned(escaped)
491 }
492 }
493
494 /// Parses a string quoted by the given grapheme cluster.
495 ///
496 /// The position of the tokenizer is asserted to be immediately after the quote grapheme
497 /// cluster.
498 fn parse_quoted(&mut self, quote: u8) -> (Cow<'a, str>, bool) {
499 assert_eq!(self.byte(), Some(quote));
500 self.pos += 1;
501
502 let mut escaped = String::new();
503 while let Some(offset) = self.input[self.pos..].find(quote as char) {
504 let idx = self.pos + offset;
505 if self.input.as_bytes().get(idx + 1) == Some(&quote) {
506 // Treat two quotes in a row as an escape.
507 escaped.push_str(&self.input[self.pos..idx + 1]);
508 // Advance past the escaped quote.
509 self.pos = idx + 2;
510 } else {
511 // Otherwise this quote string is finished.
512 let quoted = if escaped.is_empty() {
513 Cow::Borrowed(&self.input[self.pos..idx])
514 } else {
515 escaped.push_str(&self.input[self.pos..idx]);
516 Cow::Owned(escaped)
517 };
518 // Advance past the closing quote.
519 self.pos = idx + 1;
520 return (quoted, true);
521 }
522 }
523
524 let quoted = if escaped.is_empty() {
525 Cow::Borrowed(&self.input[self.pos..])
526 } else {
527 escaped.push_str(&self.input[self.pos..]);
528 Cow::Owned(escaped)
529 };
530 self.pos = self.input.len();
531
532 (quoted, false)
533 }
534
535 /// Parses the percent token expansion under the tokenizer's cursor.
536 ///
537 /// This function should only be called when the tokenizer's cursor is on a non-escaped
538 /// percent token.
539 pub fn parse_percent_token(&mut self) -> Option<Result<Token<'a>, ParseArgsError<'a>>> {
540 assert_eq!(self.byte(), Some(b'%'));
541
542 self.pos += 1;
543 let kind_start = self.pos;
544 self.pos += self.input[self.pos..]
545 .bytes()
546 .take_while(|b| b.is_ascii_lowercase())
547 .count();
548 let kind = &self.input[kind_start..self.pos];
549
550 let (open, close) = match self.byte() {
551 // We support a couple of hard-coded chars only to make sure we can provide more
552 // useful errors and avoid weird behavior in case of typos. These should cover
553 // practical cases.
554 Some(b'(') => (b'(', b')'),
555 Some(b'[') => (b'[', b']'),
556 Some(b'{') => (b'{', b'}'),
557 Some(b'<') => (b'<', b'>'),
558 Some(b'\'') => (b'\'', b'\''),
559 Some(b'\"') => (b'\"', b'\"'),
560 Some(b'|') => (b'|', b'|'),
561 Some(_) | None => {
562 return Some(if self.validate {
563 Err(ParseArgsError::MissingExpansionDelimiter { expansion: kind })
564 } else {
565 Ok(Token {
566 kind: TokenKind::ExpansionKind,
567 content_start: kind_start,
568 content: Cow::Borrowed(kind),
569 is_terminated: false,
570 })
571 });
572 }
573 };
574 // The content start for expansions is the start of the content - after the opening
575 // delimiter grapheme.
576 let content_start = self.pos + 1;
577 let kind = match ExpansionKind::from_kind(kind) {
578 Some(kind) => TokenKind::Expansion(kind),
579 None if self.validate => {
580 return Some(Err(ParseArgsError::UnknownExpansion { kind }));
581 }
582 None => TokenKind::Expand,
583 };
584
585 let (content, is_terminated) = if open == close {
586 self.parse_quoted(open)
587 } else {
588 self.parse_quoted_balanced(open, close)
589 };
590
591 let token = Token {
592 kind,
593 content_start,
594 content,
595 is_terminated,
596 };
597
598 if self.validate && !is_terminated {
599 return Some(Err(ParseArgsError::UnterminatedToken { token }));
600 }
601
602 Some(Ok(token))
603 }
604
605 /// Parse the next string under the cursor given an open and closing pair.
606 ///
607 /// The open and closing pair are different ASCII characters. The cursor is asserted to be
608 /// immediately after the opening delimiter.
609 ///
610 /// This function parses with nesting support. `%sh{echo {hello}}` for example should consume
611 /// the entire input and not quit after the first '}' character is found.
612 fn parse_quoted_balanced(&mut self, open: u8, close: u8) -> (Cow<'a, str>, bool) {
613 assert_eq!(self.byte(), Some(open));
614 self.pos += 1;
615 let start = self.pos;
616 let mut level = 1;
617
618 while let Some(offset) = self.input[self.pos..].find([open as char, close as char]) {
619 let idx = self.pos + offset;
620 // Move past the delimiter.
621 self.pos = idx + 1;
622
623 let byte = self.input.as_bytes()[idx];
624 if byte == open {
625 level += 1;
626 } else if byte == close {
627 level -= 1;
628 if level == 0 {
629 break;
630 }
631 } else {
632 unreachable!()
633 }
634 }
635
636 let is_terminated = level == 0;
637 let end = if is_terminated {
638 // Exclude the closing delimiter from the token's content.
639 self.pos - 1
640 } else {
641 // When the token is not closed, advance to the end of the input.
642 self.pos = self.input.len();
643 self.pos
644 };
645
646 (Cow::Borrowed(&self.input[start..end]), is_terminated)
647 }
648 }
649
650 impl<'a> Iterator for Tokenizer<'a> {
651 type Item = Result<Token<'a>, ParseArgsError<'a>>;
652
653 fn next(&mut self) -> Option<Self::Item> {
654 self.skip_blanks();
655
656 let byte = self.byte()?;
657 match byte {
658 b'"' | b'\'' | b'`' => {
659 let content_start = self.pos + 1;
660 let (content, is_terminated) = self.parse_quoted(byte);
661 let token = Token {
662 kind: match byte {
663 b'"' => TokenKind::Expand,
664 b'\'' => TokenKind::Quoted(Quote::Single),
665 b'`' => TokenKind::Quoted(Quote::Backtick),
666 _ => unreachable!(),
667 },
668 content_start,
669 content,
670 is_terminated,
671 };
672
673 Some(if self.validate && !is_terminated {
674 Err(ParseArgsError::UnterminatedToken { token })
675 } else {
676 Ok(token)
677 })
678 }
679 b'%' => self.parse_percent_token(),
680 _ => {
681 let content_start = self.pos;
682
683 // Allow backslash escaping on Unix for quotes or expansions
684 if cfg!(unix)
685 && byte == b'\\'
686 && matches!(self.peek_byte(), Some(b'"' | b'\'' | b'`' | b'%'))
687 {
688 self.pos += 1;
689 }
690
691 Some(Ok(Token {
692 kind: TokenKind::Unquoted,
693 content_start,
694 content: self.parse_unquoted(),
695 is_terminated: false,
696 }))
697 }
698 }
699 }
700 }
701
702 #[derive(Debug, Default, Clone, Copy)]
703 pub enum CompletionState {
704 #[default]
705 Positional,
706 Flag(Option<Flag>),
707 FlagArgument(Flag),
708 }
709
710 /// A set of arguments provided to a command on the command line.
711 ///
712 /// Regular arguments are called "positional" arguments (or "positionals" for short). Command line
713 /// input might also specify "flags" which can modify a command's behavior.
714 ///
715 /// ```rust,ignore
716 /// // Say that the command accepts a "bar" flag which doesn't accept an argument itself.
717 /// // This input has two positionals, "foo" and "baz" and one flag "--bar".
718 /// let args = Args::parse("foo --bar baz", /* .. */);
719 /// // `Args` may be treated like a slice to access positionals.
720 /// assert_eq!(args.len(), 2);
721 /// assert_eq!(&args[0], "foo");
722 /// assert_eq!(&args[1], "baz");
723 /// // Use `has_flag` or `get_flag` to access flags.
724 /// assert!(args.has_flag("bar"));
725 /// ```
726 ///
727 /// The `Args` type can be treated mostly the same as a slice when accessing positional arguments.
728 /// Common slice methods like `len`, `get`, `first` and `join` only expose positional arguments.
729 /// Additionally, common syntax like `for arg in args` or `&args[idx]` is supported for accessing
730 /// positional arguments.
731 ///
732 /// To look up flags, use `Args::get_flag` for flags which should accept an argument or
733 /// `Args::has_flag` for boolean flags.
734 ///
735 /// The way that `Args` is parsed from the input depends on a command's `Signature`. See the
736 /// `Signature` type for more details.
737 #[derive(Debug)]
738 pub struct Args<'a> {
739 signature: Signature,
740 /// Whether to validate the arguments.
741 /// See the `ParseArgsError` type for the validations.
742 validate: bool,
743 /// Whether args pushed with `Self::push` should be treated as positionals even if they
744 /// start with '-'.
745 only_positionals: bool,
746 state: CompletionState,
747 positionals: Vec<Cow<'a, str>>,
748 flags: HashMap<&'static str, Cow<'a, str>>,
749 }
750
751 impl Default for Args<'_> {
752 fn default() -> Self {
753 Self {
754 signature: Signature::DEFAULT,
755 validate: Default::default(),
756 only_positionals: Default::default(),
757 state: CompletionState::default(),
758 positionals: Default::default(),
759 flags: Default::default(),
760 }
761 }
762 }
763
764 impl<'a> Args<'a> {
765 pub fn new(signature: Signature, validate: bool) -> Self {
766 Self {
767 signature,
768 validate,
769 only_positionals: false,
770 positionals: Vec::new(),
771 flags: HashMap::new(),
772 state: CompletionState::default(),
773 }
774 }
775
776 /// Reads the next token out of the given parser.
777 ///
778 /// If the command's signature sets a maximum number of positionals (via `raw_after`) then
779 /// the token may contain the rest of the parser's input.
780 pub fn read_token<'p>(
781 &mut self,
782 parser: &mut Tokenizer<'p>,
783 ) -> Result<Option<Token<'p>>, ParseArgsError<'p>> {
784 if self
785 .signature
786 .raw_after
787 .is_some_and(|max| self.len() >= max as usize)
788 {
789 self.only_positionals = true;
790 Ok(parser.rest())
791 } else {
792 parser.next().transpose()
793 }
794 }
795
796 /// Parses the given command line according to a command's signature.
797 ///
798 /// The `try_map_fn` function can be used to try changing each token before it is considered
799 /// as an argument - this is used for variable expansion.
800 pub fn parse<M>(
801 line: &'a str,
802 signature: Signature,
803 validate: bool,
804 mut try_map_fn: M,
805 ) -> Result<Self, Box<dyn Error + 'a>>
806 where
807 // Note: this is a `FnMut` in case we decide to allow caching expansions in the future.
808 // The `mut` is not currently used.
809 M: FnMut(Token<'a>) -> Result<Cow<'a, str>, Box<dyn Error>>,
810 {
811 let mut tokenizer = Tokenizer::new(line, validate);
812 let mut args = Self::new(signature, validate);
813
814 while let Some(token) = args.read_token(&mut tokenizer)? {
815 let arg = try_map_fn(token)?;
816 args.push(arg)?;
817 }
818
819 args.finish()?;
820
821 Ok(args)
822 }
823
824 /// Adds the given argument token.
825 ///
826 /// Once all arguments have been added, `Self::finish` should be called to perform any
827 /// closing validations.
828 pub fn push(&mut self, arg: Cow<'a, str>) -> Result<(), ParseArgsError<'a>> {
829 if !self.only_positionals && arg == "--" {
830 // "--" marks the end of flags, everything after is a positional even if it starts
831 // with '-'.
832 self.only_positionals = true;
833 self.state = CompletionState::Flag(None);
834 } else if let Some(flag) = self.flag_awaiting_argument() {
835 // If the last token was a flag which accepts an argument, treat this token as a flag
836 // argument.
837 self.flags.insert(flag.name, arg);
838 self.state = CompletionState::FlagArgument(flag);
839 } else if !self.only_positionals && arg.starts_with('-') {
840 // If the token starts with '-' and we are not only accepting positional arguments,
841 // treat this token as a flag.
842 let flag = if let Some(longhand) = arg.strip_prefix("--") {
843 self.signature
844 .flags
845 .iter()
846 .find(|flag| flag.name == longhand)
847 } else {
848 let shorthand = arg.strip_prefix('-').unwrap();
849 self.signature.flags.iter().find(|flag| {
850 flag.alias
851 .is_some_and(|ch| shorthand == ch.encode_utf8(&mut [0; 4]))
852 })
853 };
854
855 let Some(flag) = flag else {
856 if self.validate {
857 return Err(ParseArgsError::UnknownFlag { text: arg });
858 }
859
860 self.positionals.push(arg);
861 self.state = CompletionState::Flag(None);
862 return Ok(());
863 };
864
865 if self.validate && self.flags.contains_key(flag.name) {
866 return Err(ParseArgsError::DuplicatedFlag { flag: flag.name });
867 }
868
869 self.flags.insert(flag.name, Cow::Borrowed(""));
870 self.state = CompletionState::Flag(Some(*flag));
871 } else {
872 // Otherwise this token is a positional argument.
873 self.positionals.push(arg);
874 self.state = CompletionState::Positional;
875 }
876
877 Ok(())
878 }
879
880 /// Performs any validations that must be done after the input args are finished being pushed
881 /// with `Self::push`.
882 fn finish(&self) -> Result<(), ParseArgsError<'a>> {
883 if !self.validate {
884 return Ok(());
885 };
886
887 if let Some(flag) = self.flag_awaiting_argument() {
888 return Err(ParseArgsError::FlagMissingArgument { flag: flag.name });
889 }
890 self.signature
891 .check_positional_count(self.positionals.len())?;
892
893 Ok(())
894 }
895
896 fn flag_awaiting_argument(&self) -> Option<Flag> {
897 match self.state {
898 CompletionState::Flag(flag) => flag.filter(|f| f.completions.is_some()),
899 _ => None,
900 }
901 }
902
903 /// Returns the kind of argument the last token is considered to be.
904 ///
905 /// For example if the last argument in the command line is `--foo` then the argument may be
906 /// considered to be a flag.
907 pub fn completion_state(&self) -> CompletionState {
908 self.state
909 }
910
911 /// Returns the number of positionals supplied in the input.
912 ///
913 /// This number does not account for any flags passed in the input.
914 pub fn len(&self) -> usize {
915 self.positionals.len()
916 }
917
918 /// Checks whether the arguments contain no positionals.
919 ///
920 /// Note that this function returns `true` if there are no positional arguments even if the
921 /// input contained flags.
922 pub fn is_empty(&self) -> bool {
923 self.positionals.is_empty()
924 }
925
926 /// Gets the first positional argument, if one exists.
927 pub fn first(&'a self) -> Option<&'a str> {
928 self.positionals.first().map(AsRef::as_ref)
929 }
930
931 /// Gets the positional argument at the given index, if one exists.
932 pub fn get(&'a self, index: usize) -> Option<&'a str> {
933 self.positionals.get(index).map(AsRef::as_ref)
934 }
935
936 /// Flattens all positional arguments together with the given separator between each
937 /// positional.
938 pub fn join(&self, sep: &str) -> String {
939 self.positionals.join(sep)
940 }
941
942 /// Returns an iterator over all positional arguments.
943 pub fn iter(&self) -> slice::Iter<'_, Cow<'_, str>> {
944 self.positionals.iter()
945 }
946
947 /// Gets the value associated with a flag's long name if the flag was provided.
948 ///
949 /// This function should be preferred over [Self::has_flag] when the flag accepts an argument.
950 pub fn get_flag(&'a self, name: &'static str) -> Option<&'a str> {
951 debug_assert!(
952 self.signature.flags.iter().any(|flag| flag.name == name),
953 "flag '--{name}' does not belong to the command's signature"
954 );
955 debug_assert!(
956 self.signature
957 .flags
958 .iter()
959 .any(|flag| flag.name == name && flag.completions.is_some()),
960 "Args::get_flag was used for '--{name}' but should only be used for flags with arguments, use Args::has_flag instead"
961 );
962
963 self.flags.get(name).map(AsRef::as_ref)
964 }
965
966 /// Checks if a flag was provided in the arguments.
967 ///
968 /// This function should be preferred over [Self::get_flag] for boolean flags - flags that
969 /// either are present or not.
970 pub fn has_flag(&self, name: &'static str) -> bool {
971 debug_assert!(
972 self.signature.flags.iter().any(|flag| flag.name == name),
973 "flag '--{name}' does not belong to the command's signature"
974 );
975 debug_assert!(
976 self.signature
977 .flags
978 .iter()
979 .any(|flag| flag.name == name && flag.completions.is_none()),
980 "Args::has_flag was used for '--{name}' but should only be used for flags without arguments, use Args::get_flag instead"
981 );
982
983 self.flags.contains_key(name)
984 }
985 }
986
987 // `arg[n]`
988 impl ops::Index<usize> for Args<'_> {
989 type Output = str;
990
991 fn index(&self, index: usize) -> &Self::Output {
992 self.positionals[index].as_ref()
993 }
994 }
995
996 // `for arg in args { .. }`
997 impl<'a> IntoIterator for Args<'a> {
998 type Item = Cow<'a, str>;
999 type IntoIter = vec::IntoIter<Cow<'a, str>>;
1000
1001 fn into_iter(self) -> Self::IntoIter {
1002 self.positionals.into_iter()
1003 }
1004 }
1005
1006 // `for arg in &args { .. }`
1007 impl<'i, 'a> IntoIterator for &'i Args<'a> {
1008 type Item = &'i Cow<'a, str>;
1009 type IntoIter = slice::Iter<'i, Cow<'a, str>>;
1010
1011 fn into_iter(self) -> Self::IntoIter {
1012 self.positionals.iter()
1013 }
1014 }
1015
1016 #[cfg(test)]
1017 mod test {
1018 use super::*;
1019
1020 #[track_caller]
1021 fn assert_tokens(input: &str, expected: &[&str]) {
1022 let actual: Vec<_> = Tokenizer::new(input, true)
1023 .map(|arg| arg.unwrap().content)
1024 .collect();
1025 let actual: Vec<_> = actual.iter().map(|c| c.as_ref()).collect();
1026
1027 assert_eq!(actual.as_slice(), expected);
1028 }
1029
1030 #[track_caller]
1031 fn assert_incomplete_tokens(input: &str, expected: &[&str]) {
1032 assert!(
1033 Tokenizer::new(input, true).collect::<Result<Vec<_>, _>>().is_err(),
1034 "`assert_incomplete_tokens` only accepts input that fails validation, consider using `assert_tokens` instead"
1035 );
1036
1037 let actual: Vec<_> = Tokenizer::new(input, false)
1038 .map(|arg| arg.unwrap().content)
1039 .collect();
1040 let actual: Vec<_> = actual.iter().map(|c| c.as_ref()).collect();
1041
1042 assert_eq!(actual.as_slice(), expected);
1043 }
1044
1045 #[test]
1046 fn tokenize_unquoted() {
1047 assert_tokens("", &[]);
1048 assert_tokens("hello", &["hello"]);
1049 assert_tokens("hello world", &["hello", "world"]);
1050 // Any amount of whitespace is considered a separator.
1051 assert_tokens("hello\t \tworld", &["hello", "world"]);
1052 }
1053
1054 // This escaping behavior is specific to Unix systems.
1055 #[cfg(unix)]
1056 #[test]
1057 fn tokenize_backslash_unix() {
1058 assert_tokens(r#"hello\ world"#, &["hello world"]);
1059 assert_tokens(r#"one\ two three"#, &["one two", "three"]);
1060 assert_tokens(r#"one two\ three"#, &["one", "two three"]);
1061 // Trailing backslash is ignored - this improves completions.
1062 assert_tokens(r#"hello\"#, &["hello"]);
1063 // The backslash at the start of the double quote makes the quote be treated as raw.
1064 // For the backslash before the ending quote the token is already considered raw so the
1065 // backslash and quote are treated literally.
1066 assert_tokens(
1067 r#"echo \"hello world\""#,
1068 &["echo", r#""hello"#, r#"world\""#],
1069 );
1070 }
1071
1072 #[test]
1073 fn tokenize_backslash() {
1074 assert_tokens(r#"\n"#, &["\\n"]);
1075 assert_tokens(r#"'\'"#, &["\\"]);
1076 }
1077
1078 #[test]
1079 fn tokenize_quoting() {
1080 // Using a quote character twice escapes it.
1081 assert_tokens(r#"''"#, &[""]);
1082 assert_tokens(r#""""#, &[""]);
1083 assert_tokens(r#"``"#, &[""]);
1084 assert_tokens(r#"echo """#, &["echo", ""]);
1085
1086 assert_tokens(r#"'hello'"#, &["hello"]);
1087 assert_tokens(r#"'hello world'"#, &["hello world"]);
1088
1089 assert_tokens(r#""hello "" world""#, &["hello \" world"]);
1090 }
1091
1092 #[test]
1093 fn tokenize_percent() {
1094 // Pair delimiters:
1095 assert_tokens(r#"echo %{hello world}"#, &["echo", "hello world"]);
1096 assert_tokens(r#"echo %[hello world]"#, &["echo", "hello world"]);
1097 assert_tokens(r#"echo %(hello world)"#, &["echo", "hello world"]);
1098 assert_tokens(r#"echo %<hello world>"#, &["echo", "hello world"]);
1099 assert_tokens(r#"echo %|hello world|"#, &["echo", "hello world"]);
1100 assert_tokens(r#"echo %'hello world'"#, &["echo", "hello world"]);
1101 assert_tokens(r#"echo %"hello world""#, &["echo", "hello world"]);
1102 // When invoking a command, double percents can be used within a string as an escape for
1103 // the percent. This is done in the expansion code though, not in the parser here.
1104 assert_tokens(r#"echo "%%hello world""#, &["echo", "%%hello world"]);
1105 // Different kinds of quotes nested:
1106 assert_tokens(
1107 r#"echo "%sh{echo 'hello world'}""#,
1108 &["echo", r#"%sh{echo 'hello world'}"#],
1109 );
1110 // Nesting of the expansion delimiter:
1111 assert_tokens(r#"echo %{hello {x} world}"#, &["echo", "hello {x} world"]);
1112 assert_tokens(
1113 r#"echo %{hello {{😎}} world}"#,
1114 &["echo", "hello {{😎}} world"],
1115 );
1116
1117 // Balanced nesting:
1118 assert_tokens(
1119 r#"echo %{hello {}} world}"#,
1120 &["echo", "hello {}", "world}"],
1121 );
1122
1123 // Recursive expansions:
1124 assert_tokens(
1125 r#"echo %sh{echo "%{cursor_line}"}"#,
1126 &["echo", r#"echo "%{cursor_line}""#],
1127 );
1128 // Completion should provide variable names here. (Unbalanced nesting)
1129 assert_incomplete_tokens(r#"echo %sh{echo "%{c"#, &["echo", r#"echo "%{c"#]);
1130 assert_incomplete_tokens(r#"echo %{hello {{} world}"#, &["echo", "hello {{} world}"]);
1131 }
1132
1133 fn parse_signature<'a>(
1134 input: &'a str,
1135 signature: Signature,
1136 ) -> Result<Args<'a>, Box<dyn std::error::Error + 'a>> {
1137 Args::parse(input, signature, true, |token| Ok(token.content))
1138 }
1139
1140 #[test]
1141 fn signature_validation_positionals() {
1142 let signature = Signature {
1143 positionals: (2, Some(3)),
1144 ..Signature::DEFAULT
1145 };
1146
1147 assert!(parse_signature("hello world", signature).is_ok());
1148 assert!(parse_signature("foo bar baz", signature).is_ok());
1149 assert!(parse_signature(r#"a "b c" d"#, signature).is_ok());
1150
1151 assert!(parse_signature("hello", signature).is_err());
1152 assert!(parse_signature("foo bar baz quiz", signature).is_err());
1153
1154 let signature = Signature {
1155 positionals: (1, None),
1156 ..Signature::DEFAULT
1157 };
1158
1159 assert!(parse_signature("a", signature).is_ok());
1160 assert!(parse_signature("a b", signature).is_ok());
1161 assert!(parse_signature(r#"a "b c" d"#, signature).is_ok());
1162
1163 assert!(parse_signature("", signature).is_err());
1164 }
1165
1166 #[test]
1167 fn flags() {
1168 let signature = Signature {
1169 positionals: (1, Some(2)),
1170 flags: &[
1171 Flag {
1172 name: "foo",
1173 alias: Some('f'),
1174 doc: "",
1175 completions: None,
1176 },
1177 Flag {
1178 name: "bar",
1179 alias: Some('b'),
1180 doc: "",
1181 completions: Some(&[]),
1182 },
1183 ],
1184 ..Signature::DEFAULT
1185 };
1186
1187 let args = parse_signature("hello", signature).unwrap();
1188 assert_eq!(args.len(), 1);
1189 assert_eq!(&args[0], "hello");
1190 assert!(!args.has_flag("foo"));
1191 assert!(args.get_flag("bar").is_none());
1192
1193 let args = parse_signature("--bar abcd hello world --foo", signature).unwrap();
1194 assert_eq!(args.len(), 2);
1195 assert_eq!(&args[0], "hello");
1196 assert_eq!(&args[1], "world");
1197 assert!(args.has_flag("foo"));
1198 assert_eq!(args.get_flag("bar"), Some("abcd"));
1199
1200 let args = parse_signature("hello -f -b abcd world", signature).unwrap();
1201 assert_eq!(args.len(), 2);
1202 assert_eq!(&args[0], "hello");
1203 assert_eq!(&args[1], "world");
1204 assert!(args.has_flag("foo"));
1205 assert_eq!(args.get_flag("bar"), Some("abcd"));
1206
1207 // The signature requires at least one positional.
1208 assert!(parse_signature("--foo", signature).is_err());
1209 // And at most two.
1210 assert!(parse_signature("abc --bar baz def efg", signature).is_err());
1211
1212 let args = parse_signature(r#"abc -b "xyz 123" def"#, signature).unwrap();
1213 assert_eq!(args.len(), 2);
1214 assert_eq!(&args[0], "abc");
1215 assert_eq!(&args[1], "def");
1216 assert_eq!(args.get_flag("bar"), Some("xyz 123"));
1217
1218 // Unknown flags are validation errors.
1219 assert!(parse_signature(r#"foo --quiz"#, signature).is_err());
1220 // Duplicated flags are parsing errors.
1221 assert!(parse_signature(r#"--foo bar --foo"#, signature).is_err());
1222 assert!(parse_signature(r#"-f bar --foo"#, signature).is_err());
1223
1224 // "--" can be used to mark the end of flags. Everything after is considered a positional.
1225 let args = parse_signature(r#"hello --bar baz -- --foo"#, signature).unwrap();
1226 assert_eq!(args.len(), 2);
1227 assert_eq!(&args[0], "hello");
1228 assert_eq!(&args[1], "--foo");
1229 assert_eq!(args.get_flag("bar"), Some("baz"));
1230 assert!(!args.has_flag("foo"));
1231 }
1232
1233 #[test]
1234 fn raw_after() {
1235 let signature = Signature {
1236 positionals: (1, Some(1)),
1237 raw_after: Some(0),
1238 ..Signature::DEFAULT
1239 };
1240
1241 // All quoting and escaping is treated literally in raw mode.
1242 let args = parse_signature(r#"'\'"#, signature).unwrap();
1243 assert_eq!(args.len(), 1);
1244 assert_eq!(&args[0], "'\\'");
1245 let args = parse_signature(r#"\''"#, signature).unwrap();
1246 assert_eq!(args.len(), 1);
1247 assert_eq!(&args[0], "\\''");
1248
1249 // Leading space is trimmed.
1250 let args = parse_signature(r#" %sh{foo}"#, signature).unwrap();
1251 assert_eq!(args.len(), 1);
1252 assert_eq!(&args[0], "%sh{foo}");
1253
1254 let signature = Signature {
1255 positionals: (1, Some(2)),
1256 raw_after: Some(1),
1257 ..Signature::DEFAULT
1258 };
1259
1260 let args = parse_signature("foo", signature).unwrap();
1261 assert_eq!(args.len(), 1);
1262 assert_eq!(&args[0], "foo");
1263
1264 // "--bar" is treated as a positional.
1265 let args = parse_signature("foo --bar", signature).unwrap();
1266 assert_eq!(args.len(), 2);
1267 assert_eq!(&args[0], "foo");
1268 assert_eq!(&args[1], "--bar");
1269
1270 let args = parse_signature("abc def ghi", signature).unwrap();
1271 assert_eq!(args.len(), 2);
1272 assert_eq!(&args[0], "abc");
1273 assert_eq!(&args[1], "def ghi");
1274
1275 let args = parse_signature("rulers [20, 30]", signature).unwrap();
1276 assert_eq!(args.len(), 2);
1277 assert_eq!(&args[0], "rulers");
1278 assert_eq!(&args[1], "[20, 30]");
1279
1280 let args =
1281 parse_signature(r#"gutters ["diff"] ["diff", "diagnostics"]"#, signature).unwrap();
1282 assert_eq!(args.len(), 2);
1283 assert_eq!(&args[0], "gutters");
1284 assert_eq!(&args[1], r#"["diff"] ["diff", "diagnostics"]"#);
1285 }
1286 }