-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.rs
217 lines (184 loc) · 5.63 KB
/
main.rs
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
#![warn(clippy::all, clippy::nursery)]
use clap::Parser;
use std::io::Write;
use std::process::Command;
fn main() -> Result<(), Box<dyn std::error::Error>> {
pretty_env_logger::init();
let opts: Opts = Opts::parse();
match opts.subcmd {
SubCommand::Ast(cmd) => ast(cmd),
SubCommand::Build(cmd) => build(cmd),
SubCommand::Run(cmd) => run(cmd),
SubCommand::Tokens(cmd) => tokens(cmd),
}
}
#[derive(Parser)]
#[clap(
version = "1.0",
name = "gors",
author = "Aymeric Beaumet <hi@aymericbeaumet.com>",
about = "gors is a go toolbelt written in rust; providing a parser and rust transpiler"
)]
struct Opts {
#[clap(subcommand)]
subcmd: SubCommand,
}
#[derive(Parser)]
enum SubCommand {
#[clap(about = "Parse the named Go file and print the AST")]
Ast(Ast),
#[clap(about = "Compile the named Go file")]
Build(Build),
#[clap(about = "Compile and run the named Go file")]
Run(Run),
#[clap(about = "Scan the named Go file and print the tokens")]
Tokens(Tokens),
}
#[derive(Parser)]
struct Ast {
#[clap(name = "file", help = "The file to parse")]
file: String,
}
#[derive(Parser)]
struct Build {
#[clap(name = "file", help = "The file to build")]
file: String,
#[clap(
long,
name = "release",
help = "Build in release mode, with optimizations"
)]
release: bool,
#[clap(
long,
name = "emit",
help = "Type of output for the compiler to emit:\nrust|asm|llvm-bc|llvm-ir|obj|metadata|link|dep-info|mir"
)]
emit: Option<String>,
}
#[derive(Parser)]
struct Run {
#[clap(name = "file", help = "The file to run")]
file: String,
#[clap(
long,
name = "release",
help = "Build in release mode, with optimizations"
)]
release: bool,
}
#[derive(Parser)]
struct Tokens {
#[clap(name = "file", help = "The file to lex")]
file: String,
}
fn ast(cmd: Ast) -> Result<(), Box<dyn std::error::Error>> {
let stdout = std::io::stdout();
let mut w = std::io::BufWriter::with_capacity(8192, stdout.lock());
let buffer = std::fs::read_to_string(&cmd.file)?;
let ast = gors::parser::parse_file(&cmd.file, &buffer)?;
gors::ast::fprint(&mut w, ast)?;
w.flush()?;
Ok(())
}
fn build(cmd: Build) -> Result<(), Box<dyn std::error::Error>> {
let buffer = std::fs::read_to_string(&cmd.file)?;
let ast = gors::parser::parse_file(&cmd.file, &buffer)?;
let compiled = gors::compiler::compile(ast)?;
// shortcut when rust code is to be emitted
if matches!(cmd.emit.as_deref(), Some("rust")) {
let mut w = std::fs::File::create("main.rs")?;
gors::codegen::fprint(&mut w, compiled)?;
return Ok(());
}
let tmp_dir = tempdir::TempDir::new("gors")?;
let source_file = tmp_dir.path().join("main.rs");
let mut w = std::fs::File::create(&source_file)?;
gors::codegen::fprint(&mut w, compiled)?;
w.sync_all()?;
let rustc = Command::new("rustc")
.args(RustcArgs {
src: source_file.to_str().unwrap(),
out: None,
emit: cmd.emit.as_deref(),
release: cmd.release,
})
.output()?;
if !rustc.status.success() {
print!("{}", String::from_utf8_lossy(&rustc.stdout));
eprint!("{}", String::from_utf8_lossy(&rustc.stderr));
return Ok(());
}
Ok(())
}
fn run(cmd: Run) -> Result<(), Box<dyn std::error::Error>> {
let tmp_dir = tempdir::TempDir::new("gors")?;
let out_rust = tmp_dir.path().join("main.rs");
let out_bin = tmp_dir.path().join("main");
let mut w = std::fs::File::create(&out_rust)?;
let buffer = std::fs::read_to_string(&cmd.file)?;
let ast = gors::parser::parse_file(&cmd.file, &buffer)?;
let compiled = gors::compiler::compile(ast)?;
gors::codegen::fprint(&mut w, compiled)?;
w.sync_all()?;
let rustc = Command::new("rustc")
.args(RustcArgs {
src: out_rust.to_str().unwrap(),
out: Some(out_bin.to_str().unwrap()),
emit: None,
release: cmd.release,
})
.output()?;
if !rustc.status.success() {
print!("{}", String::from_utf8_lossy(&rustc.stdout));
eprint!("{}", String::from_utf8_lossy(&rustc.stderr));
return Ok(());
}
let mut cmd = Command::new(&out_bin).spawn()?;
cmd.wait()?;
Ok(())
}
fn tokens(cmd: Tokens) -> Result<(), Box<dyn std::error::Error>> {
let stdout = std::io::stdout();
let mut w = std::io::BufWriter::with_capacity(8192, stdout.lock());
let buffer = std::fs::read_to_string(&cmd.file)?;
for step in gors::scanner::Scanner::new(&cmd.file, &buffer) {
serde_json::to_writer(&mut w, &step?)?;
w.write_all(b"\n")?;
}
w.flush()?;
Ok(())
}
struct RustcArgs<'a> {
src: &'a str,
out: Option<&'a str>,
emit: Option<&'a str>,
release: bool,
}
impl<'a> From<RustcArgs<'a>> for Vec<&'a str> {
fn from(args: RustcArgs<'a>) -> Self {
let mut flags = vec![args.src, "--edition=2021"];
if let Some(emit) = args.emit {
flags.extend(["--emit", emit]);
}
if let Some(out) = args.out {
flags.extend(["-o", out]);
}
if args.release {
flags.extend([
"-Ccodegen-units=1",
"-Clto=fat",
"-Copt-level=3",
"-Ctarget-cpu=native",
]);
}
flags
}
}
impl<'a> IntoIterator for RustcArgs<'a> {
type Item = &'a str;
type IntoIter = std::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
Vec::from(self).into_iter()
}
}