-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpattern_parser.rs
More file actions
808 lines (746 loc) · 30.2 KB
/
pattern_parser.rs
File metadata and controls
808 lines (746 loc) · 30.2 KB
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
//! Pattern and PatternToken data types, and the parser that converts
//! pattern strings into structured Pattern values.
use super::pattern_lexer::LexToken;
/// Represents the command name part of a pattern, which can be
/// either a literal string, an alternation of names, or a wildcard (`*`)
/// that matches any command.
#[derive(Debug, Clone, PartialEq)]
pub enum CommandPattern {
/// Matches a specific command name (e.g., "git", "curl").
Literal(String),
/// Matches any of the given command names (e.g., "ast-grep|sg").
Alternation(Vec<String>),
/// Matches any command name (`*`).
Wildcard,
}
impl CommandPattern {
/// Check if this command pattern matches the given command name.
pub fn matches(&self, command: &str) -> bool {
match self {
CommandPattern::Literal(s) => s == command,
CommandPattern::Alternation(alts) => alts.iter().any(|s| s == command),
CommandPattern::Wildcard => true,
}
}
}
/// A parsed pattern consisting of a command name and a sequence of tokens.
#[derive(Debug, Clone, PartialEq)]
pub struct Pattern {
pub command: CommandPattern,
pub tokens: Vec<PatternToken>,
}
/// Individual tokens within a pattern.
#[derive(Debug, Clone, PartialEq)]
pub enum PatternToken {
/// Fixed string (e.g., "git", "status"). `*` is treated as a glob wildcard.
Literal(String),
/// Quoted literal string where `*` is not a glob wildcard (e.g., `"WIP*"`).
QuotedLiteral(String),
/// Alternation (e.g., -X|--request -> ["-X", "--request"])
Alternation(Vec<String>),
/// Flag with its value (e.g., -X|--request POST -> aliases + value)
FlagWithValue {
aliases: Vec<String>,
value: Box<PatternToken>,
},
/// Negation (e.g., !GET, !describe|get|list-*)
Negation(Box<PatternToken>),
/// Optional group (e.g., [-X GET] -> matches with or without)
Optional(Vec<PatternToken>),
/// Wildcard: matches zero or more arbitrary tokens
Wildcard,
/// Path variable reference (e.g., <path:sensitive>)
PathRef(String),
/// Wrapper placeholder (e.g., <cmd>)
Placeholder(String),
/// Options placeholder for wrapper patterns (e.g., <opts>).
/// Consumes zero or more flag-like tokens (hyphen-prefixed) and their
/// arguments in the command.
Opts,
/// Variable-assignment placeholder for wrapper patterns (e.g., <vars>).
/// Consumes zero or more `KEY=VALUE` tokens from the command.
Vars,
}
/// Parse a pattern string into a Pattern struct.
///
/// The first whitespace-delimited token becomes the command name.
/// Remaining tokens are converted to PatternToken variants based on syntax:
/// - `*` -> Wildcard
/// - `<path:name>` -> PathRef
/// - `<cmd>` -> Placeholder (single word, no pipe, no colon)
/// - `!value` -> Negation
/// - `[...]` -> Optional group
/// - `-X|--request value` -> FlagWithValue (alternation signals value-taking flag)
/// - `word|word` -> Alternation
/// - everything else -> Literal
pub fn parse(pattern: &str) -> Result<Pattern, super::PatternParseError> {
let lex_tokens = tokenize_pattern(pattern)?;
build_pattern_from_tokens(&lex_tokens)
}
/// Parse a pattern string that may contain multi-word alternation.
///
/// For patterns with multi-word alternation (e.g., `"npx prettier"|prettier *`),
/// returns multiple `Pattern` instances — one for each alternative:
/// - `Pattern { command: "npx", tokens: [Literal("prettier"), Wildcard] }`
/// - `Pattern { command: "prettier", tokens: [Wildcard] }`
///
/// For regular patterns (no multi-word alternation), returns a single `Pattern`
/// in the vector, equivalent to calling `parse`.
pub fn parse_multi(pattern: &str) -> Result<Vec<Pattern>, super::PatternParseError> {
let lex_tokens = tokenize_pattern(pattern)?;
match &lex_tokens[0] {
LexToken::MultiWordAlternation(alternatives) => {
let rest = &lex_tokens[1..];
let rest_tokens = build_pattern_tokens(rest, false)?;
let mut patterns = Vec::with_capacity(alternatives.len());
for alt in alternatives {
// Each alternative is a list of words; the first word is the command name,
// the rest are prepended as Literal tokens before the shared remaining tokens.
let command = CommandPattern::Literal(alt[0].clone());
let prefix_tokens: Vec<PatternToken> = alt[1..]
.iter()
.map(|w| PatternToken::Literal(w.clone()))
.collect();
let mut tokens = prefix_tokens;
tokens.extend(rest_tokens.clone());
patterns.push(Pattern { command, tokens });
}
Ok(patterns)
}
_ => {
let pattern = build_pattern_from_tokens(&lex_tokens)?;
Ok(vec![pattern])
}
}
}
/// Tokenize a pattern string, returning an error if empty.
fn tokenize_pattern(pattern: &str) -> Result<Vec<LexToken>, super::PatternParseError> {
use super::PatternParseError;
let trimmed = pattern.trim();
if trimmed.is_empty() {
return Err(PatternParseError::InvalidSyntax("empty pattern".into()));
}
let lex_tokens = super::pattern_lexer::tokenize(trimmed)?;
if lex_tokens.is_empty() {
return Err(PatternParseError::InvalidSyntax("empty pattern".into()));
}
Ok(lex_tokens)
}
/// Build a single Pattern from already-tokenized lex tokens.
/// The first token becomes the command name, the rest become pattern tokens.
fn build_pattern_from_tokens(lex_tokens: &[LexToken]) -> Result<Pattern, super::PatternParseError> {
use super::PatternParseError;
let command = match &lex_tokens[0] {
LexToken::Literal(s) | LexToken::QuotedLiteral(s) => CommandPattern::Literal(s.clone()),
LexToken::Alternation(alts) => CommandPattern::Alternation(alts.clone()),
LexToken::Wildcard => CommandPattern::Wildcard,
other => {
return Err(PatternParseError::InvalidSyntax(format!(
"expected command name, got {other:?}"
)));
}
};
let rest = &lex_tokens[1..];
let tokens = build_pattern_tokens(rest, false)?;
Ok(Pattern { command, tokens })
}
/// Convert LexTokens into PatternToken values, handling
/// flag-with-value association, optional groups, and other pattern syntax.
fn build_pattern_tokens(
lex_tokens: &[LexToken],
inside_group: bool,
) -> Result<Vec<PatternToken>, super::PatternParseError> {
use super::PatternParseError;
let mut result = Vec::new();
let mut iter = lex_tokens.iter().enumerate().peekable();
while let Some((i, token)) = iter.next() {
match token {
LexToken::Wildcard => {
result.push(PatternToken::Wildcard);
}
LexToken::Literal(s) if is_flag(s) => {
// A bare flag (e.g. `-X`) is treated like a single-element
// alternation so that flag-with-value and order-independent
// matching work the same as for `-X|--request` style patterns.
if let Some(&(j, next)) = iter.peek() {
if should_consume_as_value_strict(next, j + 1 < lex_tokens.len(), inside_group)
{
let (_, next_token) = iter.next().ok_or(
PatternParseError::InvalidSyntax("unexpected end of tokens".into()),
)?;
let value = lex_to_pattern_value(next_token)?;
result.push(PatternToken::FlagWithValue {
aliases: vec![s.clone()],
value: Box::new(value),
});
} else {
result.push(PatternToken::Alternation(vec![s.clone()]));
}
} else {
result.push(PatternToken::Alternation(vec![s.clone()]));
}
}
LexToken::Literal(s) => {
result.push(PatternToken::Literal(s.clone()));
}
LexToken::QuotedLiteral(s) => {
result.push(PatternToken::QuotedLiteral(s.clone()));
}
LexToken::Alternation(alts) => {
if alts.iter().any(|a| is_flag(a)) {
// Check if the next token should be consumed as a flag value
if let Some(&(j, next)) = iter.peek() {
if should_consume_as_value(next, j + 1 < lex_tokens.len(), inside_group) {
let (_, next_token) = iter.next().ok_or(
PatternParseError::InvalidSyntax("unexpected end of tokens".into()),
)?;
let value = lex_to_pattern_value(next_token)?;
result.push(PatternToken::FlagWithValue {
aliases: alts.clone(),
value: Box::new(value),
});
} else {
result.push(PatternToken::Alternation(alts.clone()));
}
} else {
result.push(PatternToken::Alternation(alts.clone()));
}
} else {
result.push(PatternToken::Alternation(alts.clone()));
}
}
LexToken::Negation(s) => {
result.push(PatternToken::Negation(Box::new(PatternToken::Literal(
s.clone(),
))));
}
LexToken::NegationAlternation(alts) => {
result.push(PatternToken::Negation(Box::new(PatternToken::Alternation(
alts.clone(),
))));
}
LexToken::Placeholder(content) => {
let pt = parse_placeholder(content)?;
result.push(pt);
}
LexToken::OpenBracket => {
// Collect tokens until CloseBracket
let mut inner = Vec::new();
let bracket_pos = i;
loop {
match iter.next() {
Some((_, LexToken::CloseBracket)) => break,
Some((_, t)) => inner.push(t.clone()),
None => {
return Err(PatternParseError::UnclosedSquareBracket(bracket_pos));
}
}
}
let inner_tokens = build_pattern_tokens(&inner, true)?;
result.push(PatternToken::Optional(inner_tokens));
}
LexToken::CloseBracket => {
return Err(PatternParseError::InvalidSyntax(
"unexpected closing bracket".into(),
));
}
LexToken::MultiWordAlternation(_) => {
return Err(PatternParseError::InvalidSyntax(
"multi-word alternation is only supported in command position".into(),
));
}
}
}
Ok(result)
}
/// Convert a single LexToken into a PatternToken for use as a flag value.
fn lex_to_pattern_value(token: &LexToken) -> Result<PatternToken, super::PatternParseError> {
match token {
LexToken::Wildcard => Ok(PatternToken::Wildcard),
LexToken::Literal(s) => Ok(PatternToken::Literal(s.clone())),
LexToken::QuotedLiteral(s) => Ok(PatternToken::QuotedLiteral(s.clone())),
LexToken::Negation(s) => Ok(PatternToken::Negation(Box::new(PatternToken::Literal(
s.clone(),
)))),
LexToken::NegationAlternation(alts) => Ok(PatternToken::Negation(Box::new(
PatternToken::Alternation(alts.clone()),
))),
LexToken::Placeholder(content) => parse_placeholder(content),
LexToken::Alternation(alts) => Ok(PatternToken::Alternation(alts.clone())),
LexToken::OpenBracket | LexToken::CloseBracket => Err(
super::PatternParseError::InvalidSyntax("bracket cannot be used as flag value".into()),
),
LexToken::MultiWordAlternation(_) => Err(super::PatternParseError::InvalidSyntax(
"multi-word alternation cannot be used as flag value".into(),
)),
}
}
/// Parse angle-bracket placeholder content into PathRef or Placeholder.
fn parse_placeholder(content: &str) -> Result<PatternToken, super::PatternParseError> {
if content.is_empty() {
return Err(super::PatternParseError::InvalidSyntax(
"empty angle brackets".into(),
));
}
if content.contains('|') {
return Err(super::PatternParseError::InvalidSyntax(format!(
"alternation inside angle brackets is not supported, use bare pipe: {content}"
)));
}
if let Some(name) = content.strip_prefix("path:") {
return Ok(PatternToken::PathRef(name.to_string()));
}
if content == "opts" {
return Ok(PatternToken::Opts);
}
if content == "vars" {
return Ok(PatternToken::Vars);
}
Ok(PatternToken::Placeholder(content.to_string()))
}
/// Determine whether a LexToken should be consumed as a flag's value.
///
/// A token is consumed as a value when:
/// - It is a non-wildcard token that doesn't look like a flag itself, OR
/// - It is `Wildcard` AND there are more tokens after it (so `*` is the value, not the trailing wildcard).
///
/// This prevents `-f|--force *` (where `*` is the last token) from being parsed as
/// FlagWithValue, while allowing `-X|--request * *` to parse the first `*` as a value.
fn should_consume_as_value(next: &LexToken, has_more_after: bool, inside_group: bool) -> bool {
match next {
LexToken::OpenBracket | LexToken::CloseBracket => false,
// When `[` is used as a literal command name, the lexer emits `]` as
// `Literal("]")` rather than `CloseBracket`. Prevent flags from
// consuming this closing delimiter as a value.
LexToken::Literal(s) if s == "]" => false,
LexToken::Literal(s) if is_flag(s) => false,
LexToken::Alternation(alts) if alts.iter().any(|a| is_flag(a)) => false,
LexToken::Placeholder(_) => false,
LexToken::Wildcard => inside_group || has_more_after,
_ => true,
}
}
/// Like [`should_consume_as_value`], but stricter: also refuses to consume
/// placeholder tokens as flag values. Used for bare flags (e.g. `-c`) where
/// the flag is written without alternation syntax and the next token may be a
/// wrapper placeholder (e.g. `<cmd>`) rather than a flag value.
fn should_consume_as_value_strict(
next: &LexToken,
has_more_after: bool,
inside_group: bool,
) -> bool {
match next {
LexToken::Placeholder(_) => false,
_ => should_consume_as_value(next, has_more_after, inside_group),
}
}
/// Check if a string looks like a flag (starts with `-`).
fn is_flag(s: &str) -> bool {
s.starts_with('-')
}
#[cfg(test)]
mod tests {
use super::*;
use rstest::rstest;
fn assert_parse(input: &str, expected_command: &str, expected_tokens: Vec<PatternToken>) {
let result = parse(input).unwrap();
assert_eq!(
result.command,
CommandPattern::Literal(expected_command.to_string())
);
assert_eq!(result.tokens, expected_tokens);
}
#[rstest]
#[case::command_only("git", "git", vec![])]
#[case::simple("git status", "git", vec![
PatternToken::Literal("status".into()),
])]
#[case::multiple("git remote add origin", "git", vec![
PatternToken::Literal("remote".into()),
PatternToken::Literal("add".into()),
PatternToken::Literal("origin".into()),
])]
#[case::joined_equals("java -Denv=prod", "java", vec![
PatternToken::Alternation(vec!["-Denv=prod".into()]),
])]
#[case::single_quoted("git commit -m 'WIP*'", "git", vec![
PatternToken::Literal("commit".into()),
PatternToken::FlagWithValue {
aliases: vec!["-m".into()],
value: Box::new(PatternToken::QuotedLiteral("WIP*".into())),
},
])]
#[case::double_quoted(r#"git commit -m "WIP*""#, "git", vec![
PatternToken::Literal("commit".into()),
PatternToken::FlagWithValue {
aliases: vec!["-m".into()],
value: Box::new(PatternToken::QuotedLiteral("WIP*".into())),
},
])]
fn parse_literals(
#[case] input: &str,
#[case] expected_command: &str,
#[case] expected_tokens: Vec<PatternToken>,
) {
assert_parse(input, expected_command, expected_tokens);
}
#[rstest]
#[case::standalone("git *", "git", vec![PatternToken::Wildcard])]
#[case::between_literals("git push * --force", "git", vec![
PatternToken::Literal("push".into()),
PatternToken::Wildcard,
PatternToken::Alternation(vec!["--force".into()]),
])]
fn parse_wildcard(
#[case] input: &str,
#[case] expected_command: &str,
#[case] expected_tokens: Vec<PatternToken>,
) {
assert_parse(input, expected_command, expected_tokens);
}
#[rstest]
#[case::value_alternation("git push origin main|master", "git", vec![
PatternToken::Literal("push".into()),
PatternToken::Literal("origin".into()),
PatternToken::Alternation(vec!["main".into(), "master".into()]),
])]
#[case::non_flag("kubectl describe|get|list *", "kubectl", vec![
PatternToken::Alternation(vec!["describe".into(), "get".into(), "list".into()]),
PatternToken::Wildcard,
])]
fn parse_alternation(
#[case] input: &str,
#[case] expected_command: &str,
#[case] expected_tokens: Vec<PatternToken>,
) {
assert_parse(input, expected_command, expected_tokens);
}
#[rstest]
#[case::literal_value("curl -X|--request POST *", "curl", vec![
PatternToken::FlagWithValue {
aliases: vec!["-X".into(), "--request".into()],
value: Box::new(PatternToken::Literal("POST".into())),
},
PatternToken::Wildcard,
])]
#[case::wildcard_value("curl -X|--request * *", "curl", vec![
PatternToken::FlagWithValue {
aliases: vec!["-X".into(), "--request".into()],
value: Box::new(PatternToken::Wildcard),
},
PatternToken::Wildcard,
])]
#[case::named_value("aws -p|--profile prod *", "aws", vec![
PatternToken::FlagWithValue {
aliases: vec!["-p".into(), "--profile".into()],
value: Box::new(PatternToken::Literal("prod".into())),
},
PatternToken::Wildcard,
])]
#[case::trailing_wildcard_not_consumed("git commit -m|--message *", "git", vec![
PatternToken::Literal("commit".into()),
PatternToken::Alternation(vec!["-m".into(), "--message".into()]),
PatternToken::Wildcard,
])]
#[case::boolean_flag("git push -f|--force *", "git", vec![
PatternToken::Literal("push".into()),
PatternToken::Alternation(vec!["-f".into(), "--force".into()]),
PatternToken::Wildcard,
])]
#[case::placeholder_not_consumed_as_flag_value("cmd -o|--option <cmd>", "cmd", vec![
PatternToken::Alternation(vec!["-o".into(), "--option".into()]),
PatternToken::Placeholder("cmd".into()),
])]
#[case::path_ref_value("cmd -c|--config <path:config>", "cmd", vec![
PatternToken::Alternation(vec!["-c".into(), "--config".into()]),
PatternToken::PathRef("config".into()),
])]
fn parse_flag_with_value(
#[case] input: &str,
#[case] expected_command: &str,
#[case] expected_tokens: Vec<PatternToken>,
) {
assert_parse(input, expected_command, expected_tokens);
}
#[rstest]
#[case::flag_with_value("aws --profile prod *", "aws", vec![
PatternToken::FlagWithValue {
aliases: vec!["--profile".into()],
value: Box::new(PatternToken::Literal("prod".into())),
},
PatternToken::Wildcard,
])]
#[case::short_flag_with_value("git -C /tmp status", "git", vec![
PatternToken::FlagWithValue {
aliases: vec!["-C".into()],
value: Box::new(PatternToken::Literal("/tmp".into())),
},
PatternToken::Literal("status".into()),
])]
#[case::flag_consumes_next_non_flag("git push --force origin", "git", vec![
PatternToken::Literal("push".into()),
PatternToken::FlagWithValue {
aliases: vec!["--force".into()],
value: Box::new(PatternToken::Literal("origin".into())),
},
])]
#[case::flag_not_consuming_trailing_wildcard("git --verbose *", "git", vec![
PatternToken::Alternation(vec!["--verbose".into()]),
PatternToken::Wildcard,
])]
#[case::flag_at_end("git push --force", "git", vec![
PatternToken::Literal("push".into()),
PatternToken::Alternation(vec!["--force".into()]),
])]
#[case::combined_short_flag_with_value("rm -rf /", "rm", vec![
PatternToken::FlagWithValue {
aliases: vec!["-rf".into()],
value: Box::new(PatternToken::Literal("/".into())),
},
])]
fn parse_bare_flag(
#[case] input: &str,
#[case] expected_command: &str,
#[case] expected_tokens: Vec<PatternToken>,
) {
assert_parse(input, expected_command, expected_tokens);
}
#[rstest]
#[case::literal("aws --profile !prod *", "aws", vec![
PatternToken::FlagWithValue {
aliases: vec!["--profile".into()],
value: Box::new(PatternToken::Negation(Box::new(PatternToken::Literal("prod".into())))),
},
PatternToken::Wildcard,
])]
#[case::alternation("kubectl !describe|get|list *", "kubectl", vec![
PatternToken::Negation(Box::new(PatternToken::Alternation(vec![
"describe".into(), "get".into(), "list".into(),
]))),
PatternToken::Wildcard,
])]
fn parse_negation(
#[case] input: &str,
#[case] expected_command: &str,
#[case] expected_tokens: Vec<PatternToken>,
) {
assert_parse(input, expected_command, expected_tokens);
}
#[rstest]
#[case::single_flag("rm [-f] *", "rm", vec![
PatternToken::Optional(vec![PatternToken::Alternation(vec!["-f".into()])]),
PatternToken::Wildcard,
])]
#[case::flag_with_value("curl [-X|--request GET] *", "curl", vec![
PatternToken::Optional(vec![PatternToken::FlagWithValue {
aliases: vec!["-X".into(), "--request".into()],
value: Box::new(PatternToken::Literal("GET".into())),
}]),
PatternToken::Wildcard,
])]
#[case::multiple_tokens("git [-C *] status", "git", vec![
PatternToken::Optional(vec![
PatternToken::FlagWithValue {
aliases: vec!["-C".into()],
value: Box::new(PatternToken::Wildcard),
},
]),
PatternToken::Literal("status".into()),
])]
fn parse_optional(
#[case] input: &str,
#[case] expected_command: &str,
#[case] expected_tokens: Vec<PatternToken>,
) {
assert_parse(input, expected_command, expected_tokens);
}
#[rstest]
#[case::bracket_command_wildcard("[ *", "[", vec![
PatternToken::Wildcard,
])]
#[case::bracket_command_boolean_flag("[ -f ]", "[", vec![
PatternToken::Alternation(vec!["-f".into()]),
PatternToken::Literal("]".into()),
])]
#[case::bracket_command_with_args("[ -f file ]", "[", vec![
PatternToken::FlagWithValue {
aliases: vec!["-f".into()],
value: Box::new(PatternToken::Literal("file".into())),
},
PatternToken::Literal("]".into()),
])]
fn parse_literal_bracket_command(
#[case] input: &str,
#[case] expected_command: &str,
#[case] expected_tokens: Vec<PatternToken>,
) {
assert_parse(input, expected_command, expected_tokens);
}
#[rstest]
#[case::placeholder("sudo <cmd>", "sudo", vec![
PatternToken::Placeholder("cmd".into()),
])]
#[case::path_ref("cat <path:sensitive>", "cat", vec![
PatternToken::PathRef("sensitive".into()),
])]
#[case::flag_alternation_then_placeholder(
r"find * -exec|-execdir|-ok|-okdir <cmd> \;|+",
"find",
vec![
PatternToken::Wildcard,
PatternToken::Alternation(vec![
"-exec".into(), "-execdir".into(), "-ok".into(), "-okdir".into(),
]),
PatternToken::Placeholder("cmd".into()),
PatternToken::Alternation(vec![r"\;".into(), "+".into()]),
],
)]
fn parse_placeholder(
#[case] input: &str,
#[case] expected_command: &str,
#[case] expected_tokens: Vec<PatternToken>,
) {
assert_parse(input, expected_command, expected_tokens);
}
#[rstest]
#[case::wildcard_with_flag("* --help", vec![
PatternToken::Alternation(vec!["--help".into()]),
])]
#[case::wildcard_with_version("* --version", vec![
PatternToken::Alternation(vec!["--version".into()]),
])]
#[case::wildcard_only("*", vec![])]
#[case::wildcard_with_wildcard_args("* *", vec![PatternToken::Wildcard])]
fn parse_wildcard_command(#[case] input: &str, #[case] expected_tokens: Vec<PatternToken>) {
let result = parse(input).unwrap();
assert_eq!(result.command, CommandPattern::Wildcard);
assert_eq!(result.tokens, expected_tokens);
}
#[rstest]
#[case::two_aliases(
"ast-grep|sg scan *",
vec!["ast-grep".into(), "sg".into()],
vec![
PatternToken::Literal("scan".into()),
PatternToken::Wildcard,
],
)]
#[case::three_aliases(
"vim|nvim|vi *",
vec!["vim".into(), "nvim".into(), "vi".into()],
vec![PatternToken::Wildcard],
)]
#[case::aliases_no_args(
"python|python3",
vec!["python".into(), "python3".into()],
vec![],
)]
fn parse_command_alternation(
#[case] input: &str,
#[case] expected_alts: Vec<String>,
#[case] expected_tokens: Vec<PatternToken>,
) {
let result = parse(input).unwrap();
assert_eq!(result.command, CommandPattern::Alternation(expected_alts));
assert_eq!(result.tokens, expected_tokens);
}
#[rstest]
#[case::matches_first("ast-grep|sg", "ast-grep", true)]
#[case::matches_second("ast-grep|sg", "sg", true)]
#[case::no_match("ast-grep|sg", "rg", false)]
fn command_alternation_matches(
#[case] pattern: &str,
#[case] command: &str,
#[case] expected: bool,
) {
let parsed = parse(pattern).unwrap();
assert_eq!(parsed.command.matches(command), expected);
}
#[rstest]
#[case::empty_string("", "InvalidSyntax")]
#[case::whitespace_only(" ", "InvalidSyntax")]
#[case::unclosed_angle_bracket("curl <cmd", "UnclosedBracket")]
#[case::unclosed_square_bracket("rm [-f *", "UnclosedSquareBracket")]
#[case::nested_square_brackets("git [[-C *]] status", "NestedSquareBracket")]
#[case::empty_angle_brackets("curl <> GET", "InvalidSyntax")]
#[case::angle_bracket_with_pipe("curl <-X|--request> POST *", "InvalidSyntax")]
#[case::angle_bracket_value_alternation("git push origin <main|master>", "InvalidSyntax")]
#[case::empty_alternation("kubectl describe| *", "EmptyAlternation")]
#[case::empty_negation_alternation("kubectl !a||b *", "EmptyAlternation")]
#[case::unclosed_single_quote("git commit -m 'WIP", "InvalidSyntax")]
#[case::unclosed_double_quote(r#"git commit -m "WIP"#, "InvalidSyntax")]
fn parse_err(#[case] input: &str, #[case] expected_variant: &str) {
let err = parse(input).expect_err(&format!("expected error for: {input:?}"));
let debug = format!("{err:?}");
assert!(
debug.starts_with(expected_variant),
"wrong error variant for {input:?}: expected {expected_variant}, got {debug}"
);
}
// === Multi-word alternation (parse_multi) ===
#[rstest]
#[case::two_alternatives(
r#""npx prettier"|prettier *"#,
vec![
Pattern {
command: CommandPattern::Literal("npx".into()),
tokens: vec![PatternToken::Literal("prettier".into()), PatternToken::Wildcard],
},
Pattern {
command: CommandPattern::Literal("prettier".into()),
tokens: vec![PatternToken::Wildcard],
},
]
)]
#[case::three_alternatives(
r#""npx prettier"|"bunx prettier"|prettier *"#,
vec![
Pattern {
command: CommandPattern::Literal("npx".into()),
tokens: vec![PatternToken::Literal("prettier".into()), PatternToken::Wildcard],
},
Pattern {
command: CommandPattern::Literal("bunx".into()),
tokens: vec![PatternToken::Literal("prettier".into()), PatternToken::Wildcard],
},
Pattern {
command: CommandPattern::Literal("prettier".into()),
tokens: vec![PatternToken::Wildcard],
},
]
)]
#[case::multi_word_with_subcommand(
r#""python -m pytest"|pytest *"#,
vec![
Pattern {
command: CommandPattern::Literal("python".into()),
tokens: vec![
PatternToken::Literal("-m".into()),
PatternToken::Literal("pytest".into()),
PatternToken::Wildcard,
],
},
Pattern {
command: CommandPattern::Literal("pytest".into()),
tokens: vec![PatternToken::Wildcard],
},
]
)]
fn parse_multi_expands_alternatives(#[case] input: &str, #[case] expected: Vec<Pattern>) {
let result = parse_multi(input).unwrap();
assert_eq!(result, expected);
}
#[rstest]
#[case::single_word_alternation("ast-grep|sg scan *", 1)]
#[case::simple_literal("git status", 1)]
#[case::wildcard_command("* --help", 1)]
fn parse_multi_no_expansion(#[case] input: &str, #[case] expected_count: usize) {
let result = parse_multi(input).unwrap();
assert_eq!(
result.len(),
expected_count,
"expected {expected_count} patterns for {input:?}, got {}",
result.len()
);
}
}