tree-based source processing language
1/// tree-based source processor
2#[derive(argh::FromArgs)]
3struct Cli {
4 /// read the tbsp program source from a file
5 #[argh(option, short = 'f')]
6 program_file: std::path::PathBuf,
7
8 /// set the language that the file is written in
9 #[argh(option, short = 'l')]
10 language: String,
11
12 /// input file to process
13 #[argh(positional)]
14 file: Option<std::path::PathBuf>,
15}
16
17impl Cli {
18 fn program(&self) -> String {
19 std::fs::read_to_string(&self.program_file).unwrap_or_else(|e| {
20 eprintln!(
21 "failed to read program-file from `{}`: {e}",
22 self.program_file.display()
23 );
24 std::process::exit(-1);
25 })
26 }
27
28 fn language(&self) -> tree_sitter::Language {
29 match self.language.as_str() {
30 "md" => tree_sitter_md::language(),
31 "typescript" => tree_sitter_typescript::language_typescript(),
32 "javascript" => tree_sitter_javascript::language(),
33 "python" => tree_sitter_python::language(),
34 "rust" => tree_sitter_rust::language(),
35 lang => {
36 eprintln!("unknown language `{lang}`");
37 std::process::exit(-1);
38 }
39 }
40 }
41
42 fn file(&self) -> String {
43 match self.file.as_ref() {
44 Some(f) => std::fs::read_to_string(f).unwrap_or_else(|e| {
45 eprintln!("failed to read input-file from `{}`: {e}", f.display());
46 std::process::exit(-1);
47 }),
48 None => try_consume_stdin().unwrap_or_else(|e| {
49 eprintln!("failed to read input-file from stdin: {e}");
50 std::process::exit(-1);
51 }),
52 }
53 }
54}
55
56fn try_consume_stdin() -> std::io::Result<String> {
57 let mut buffer = String::new();
58 let mut lock = std::io::stdin().lock();
59
60 while let Ok(n) = std::io::Read::read_to_string(&mut lock, &mut buffer) {
61 if n == 0 {
62 break;
63 }
64 }
65
66 if buffer.is_empty() {
67 Err(std::io::Error::other("empty stdin"))
68 } else {
69 Ok(buffer)
70 }
71}
72
73fn main() {
74 let cli: Cli = argh::from_env();
75
76 tbsp::evaluate(&cli.file(), &cli.program(), cli.language()).unwrap_or_else(|e| {
77 eprintln!("{e:?}");
78 std::process::exit(-1);
79 });
80}