-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic.rs
More file actions
67 lines (59 loc) · 1.87 KB
/
basic.rs
File metadata and controls
67 lines (59 loc) · 1.87 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
//! Basic usage example for the Rable bash parser.
//!
//! Run with: `cargo run --example basic`
#![allow(clippy::expect_used)]
use rable::{NodeKind, parse};
fn main() {
// Parse a simple pipeline
let source = "echo $USER | grep root";
let nodes = parse(source, false).expect("valid bash");
println!("Source: {source}");
println!("S-expression: {}", nodes[0]);
println!();
// Inspect the AST
if let NodeKind::Pipeline { commands, .. } = &nodes[0].kind {
println!("Pipeline with {} commands:", commands.len());
for (i, cmd) in commands.iter().enumerate() {
if let NodeKind::Command {
words, redirects, ..
} = &cmd.kind
{
let word_values: Vec<_> = words
.iter()
.filter_map(|w| {
if let NodeKind::Word { value, .. } = &w.kind {
Some(value.as_str())
} else {
None
}
})
.collect();
println!(
" Command {}: {:?} ({} redirects)",
i,
word_values,
redirects.len()
);
}
}
}
println!();
// Parse a compound command
let source = r#"if [ -f /etc/passwd ]; then echo "exists"; fi"#;
let nodes = parse(source, false).expect("valid bash");
println!("Source: {source}");
println!("S-expression: {}", nodes[0]);
println!();
// Error handling
match parse("if", false) {
Ok(_) => println!("Unexpectedly parsed"),
Err(e) => {
println!(
"Parse error at line {}, pos {}: {}",
e.line(),
e.pos(),
e.message()
);
}
}
}