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
use std::{
io::{self, Read, Write},
process,
};
use molecule_codegen::IntermediateFormat;
mod codegen;
use codegen::Generator;
pub(crate) enum AppAction {
DisplayFormat,
ProcessIntermediate(Vec<u8>),
}
pub struct AppConfig {
action: AppAction,
format: IntermediateFormat,
}
type RawAppConfig<'a> = (IntermediateFormat, &'a clap::ArgMatches<'a>);
pub fn build_commandline(format: IntermediateFormat) -> AppConfig {
let yaml = clap::load_yaml!("cli/go-plugin.yaml");
let matches = clap::App::from_yaml(yaml)
.name("Moleculec Go Plugin")
.about("Compiler plugin for molecule to generate code.")
.version(clap::crate_version!())
.get_matches();
AppConfig::from(&(format, &matches))
}
impl<'a> From<&'a RawAppConfig<'a>> for AppConfig {
fn from(input: &'a RawAppConfig<'a>) -> Self {
let (format, matches) = input;
let action = if matches.is_present("format") {
AppAction::DisplayFormat
} else {
let mut input = Vec::new();
if io::stdin().read_to_end(&mut input).is_err() {
eprintln!("Error: failed to read data from stdin)");
process::exit(1);
};
AppAction::ProcessIntermediate(input)
};
Self {
action,
format: *format,
}
}
}
impl AppConfig {
pub fn execute(self) {
match self.action {
AppAction::DisplayFormat => {
println!("{}", self.format);
}
AppAction::ProcessIntermediate(input) => {
let ast = self.format.recover(&input).unwrap();
let mut output_data = Vec::<u8>::new();
if let Err(err) = Generator::generate(&mut output_data, &ast) {
eprintln!("failed to write data by generator: {}", err)
}
let stdout = io::stdout();
let mut stdout_handle = stdout.lock();
stdout_handle.write_all(&output_data).unwrap();
stdout_handle.flush().unwrap();
}
}
}
}