-
Notifications
You must be signed in to change notification settings - Fork 13
/
build.rs
213 lines (175 loc) · 6.15 KB
/
build.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
#![deny(warnings)]
extern crate cargo_metadata;
extern crate quote;
extern crate syn;
#[macro_use]
extern crate failure;
use std::env;
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
// Dummy declarations for RLS.
if std::env::var("CARGO").unwrap_or_default().ends_with("rls") {
llvm::Generator::default()
.write_declarations(&format!("{}/llvm_gen.rs", out_dir))
.expect("Unable to write generated LLVM declarations");
return;
}
println!("cargo:rerun-if-changed=build.rs");
llvm::Generator::default()
.parse_llvm_sys_crate()
.expect("Unable to parse 'llvm-sys' crate")
.write_declarations(&format!("{}/llvm_gen.rs", out_dir))
.expect("Unable to write generated LLVM declarations");
}
#[derive(Debug)]
struct Declaration {
name: String,
args: String,
ret_ty: String,
}
mod llvm {
use std::fs::File;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use cargo_metadata::MetadataCommand;
use failure::Error;
use quote::ToTokens;
use syn::{parse_file, Abi, ForeignItem, Item, ItemForeignMod, ReturnType};
use super::*;
const LLVM_SOURCES: &[&str] = &[
"core.rs",
"linker.rs",
"bit_reader.rs",
"bit_writer.rs",
"ir_reader.rs",
"disassembler.rs",
"error_handling.rs",
"initialization.rs",
"link_time_optimizer.rs",
"lto.rs",
"object.rs",
"orc.rs",
"support.rs",
"target.rs",
"target_machine.rs",
"transforms/ipo.rs",
"transforms/pass_manager_builder.rs",
"transforms/scalar.rs",
"transforms/vectorize.rs",
"debuginfo.rs",
"analysis.rs",
"execution_engine.rs",
];
const INIT_MACROS: &[&str] = &[
"LLVM_InitializeAllTargetInfos",
"LLVM_InitializeAllTargets",
"LLVM_InitializeAllTargetMCs",
"LLVM_InitializeAllAsmPrinters",
"LLVM_InitializeAllAsmParsers",
"LLVM_InitializeAllDisassemblers",
"LLVM_InitializeNativeTarget",
"LLVM_InitializeNativeAsmParser",
"LLVM_InitializeNativeAsmPrinter",
"LLVM_InitializeNativeDisassembler",
];
#[derive(Default)]
pub struct Generator {
declarations: Vec<Declaration>,
}
impl Generator {
pub fn parse_llvm_sys_crate(mut self) -> Result<Self, Error> {
let llvm_src_path = self.get_llvm_sys_crate_path()?;
for file in LLVM_SOURCES {
let path = llvm_src_path.join(file);
let mut declarations = self.extract_file_declarations(&path)?;
self.declarations.append(&mut declarations);
}
Ok(self)
}
pub fn write_declarations(self, path: &str) -> Result<(), Error> {
let mut file = File::create(path)?;
for decl in self.declarations {
if INIT_MACROS.contains(&decl.name.as_str()) {
// Skip target initialization wrappers
// (see llvm-sys/wrappers/target.c)
continue;
}
writeln!(
file,
"create_proxy!({}; {}; {});",
decl.name,
decl.ret_ty,
decl.args.trim_end_matches(",")
)?;
}
Ok(())
}
fn get_llvm_sys_crate_path(&self) -> Result<PathBuf, Error> {
let metadata = MetadataCommand::new()
.exec()
.map_err(|_| format_err!("Unable to get crate metadata"))?;
let llvm_dependency = metadata
.packages
.into_iter()
.find(|item| item.name == "llvm-sys")
.ok_or(format_err!(
"Unable to find 'llvm-sys' in the crate metadata"
))?;
let llvm_lib_rs_path = PathBuf::from(
llvm_dependency
.targets
.into_iter()
.find(|item| item.name == "llvm-sys")
.ok_or(format_err!(
"Unable to find lib target for 'llvm-sys' crate"
))?
.src_path,
);
Ok(llvm_lib_rs_path.parent().unwrap().into())
}
fn extract_file_declarations(&self, path: &Path) -> Result<Vec<Declaration>, Error> {
let mut file = File::open(path)
.map_err(|_| format_err!("Unable to open file: {}", path.to_str().unwrap()))?;
let mut content = String::new();
file.read_to_string(&mut content)?;
let ast = parse_file(&content).map_err(|e| failure::err_msg(e.to_string()))?;
Ok(ast.items.iter().fold(vec![], |mut list, item| match item {
Item::ForeignMod(ref item) if item.abi.is_c() => {
list.append(&mut self.extract_foreign_mod_declarations(item));
list
}
_ => list,
}))
}
fn extract_foreign_mod_declarations(&self, item: &ItemForeignMod) -> Vec<Declaration> {
item.items.iter().fold(vec![], |mut list, item| match item {
ForeignItem::Fn(ref item) => {
let ret_ty = match item.decl.output {
ReturnType::Default => "()".into(),
ReturnType::Type(_, ref ty) => ty.into_token_stream().to_string(),
};
list.push(Declaration {
name: item.ident.to_string(),
args: item.decl.inputs.clone().into_token_stream().to_string(),
ret_ty,
});
list
}
_ => list,
})
}
}
trait AbiExt {
fn is_c(&self) -> bool;
}
impl AbiExt for Abi {
fn is_c(&self) -> bool {
let abi_name = self
.name
.as_ref()
.map(|item| item.value())
.unwrap_or(String::new());
abi_name == "C"
}
}
}