-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathlib.rs
More file actions
357 lines (317 loc) · 12.2 KB
/
lib.rs
File metadata and controls
357 lines (317 loc) · 12.2 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
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
use std::env;
use std::error::Error;
use std::fs;
use std::path::{Path, PathBuf};
/// Represents the version of Lua to build.
#[derive(Debug, PartialEq, Eq)]
pub enum Version {
Lua51,
Lua52,
Lua53,
Lua54,
Lua55,
}
pub use self::Version::*;
/// Represents the configuration for building Lua artifacts.
pub struct Build {
out_dir: Option<PathBuf>,
target: Option<String>,
host: Option<String>,
opt_level: Option<String>,
debug: Option<bool>,
}
/// Represents the artifacts produced by the build process.
#[derive(Clone, Debug)]
pub struct Artifacts {
root_dir: PathBuf,
include_dir: PathBuf,
lib_dir: PathBuf,
libs: Vec<String>,
}
impl Default for Build {
fn default() -> Build {
Build {
out_dir: env::var_os("OUT_DIR").map(PathBuf::from),
target: env::var("TARGET").ok(),
host: None,
opt_level: None,
debug: None,
}
}
}
impl Build {
/// Creates a new `Build` instance with default settings.
pub fn new() -> Build {
Build::default()
}
/// Sets the output directory for the build artifacts.
///
/// This is required if called outside of a build script.
pub fn out_dir<P: AsRef<Path>>(&mut self, path: P) -> &mut Build {
self.out_dir = Some(path.as_ref().to_path_buf());
self
}
/// Sets the target architecture for the build.
///
/// This is required if called outside of a build script.
pub fn target(&mut self, target: &str) -> &mut Build {
self.target = Some(target.to_string());
self
}
/// Sets the host architecture for the build.
///
/// This is optional and will default to the environment variable `HOST` if not set.
/// If called outside of a build script, it will default to the target architecture.
pub fn host(&mut self, host: &str) -> &mut Build {
self.host = Some(host.to_string());
self
}
/// Sets the optimization level for the build.
///
/// This is optional and will default to the environment variable `OPT_LEVEL` if not set.
/// If called outside of a build script, it will default to `0` in debug mode and `2` otherwise.
pub fn opt_level(&mut self, opt_level: &str) -> &mut Build {
self.opt_level = Some(opt_level.to_string());
self
}
/// Sets whether to build in debug mode.
///
/// This is optional and will default to the value of `cfg!(debug_assertions)`.
/// If set to `true`, it also enables Lua API checks.
pub fn debug(&mut self, debug: bool) -> &mut Build {
self.debug = Some(debug);
self
}
/// Builds the Lua artifacts for the specified version.
pub fn build(&self, version: Version) -> Artifacts {
match self.try_build(version) {
Ok(artifacts) => artifacts,
Err(err) => panic!("{err}"),
}
}
/// Attempts to build the Lua artifacts for the specified version.
///
/// Returns an error if the build fails.
pub fn try_build(&self, version: Version) -> Result<Artifacts, Box<dyn Error>> {
let target = self.target.as_ref().ok_or("TARGET is not set")?;
let out_dir = self.out_dir.as_ref().ok_or("OUT_DIR is not set")?;
let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
let mut source_dir = manifest_dir.join(version.source_dir());
let lib_dir = out_dir.join("lib");
let include_dir = out_dir.join("include");
if !include_dir.exists() {
fs::create_dir_all(&include_dir)
.context(|| format!("Cannot create '{}'", include_dir.display()))?;
}
let mut config = cc::Build::new();
config.warnings(false).cargo_metadata(false).target(target);
match &self.host {
Some(host) => {
config.host(host);
}
// Host will be taken from the environment variable
None if env::var("HOST").is_ok() => {}
None => {
// If called outside of build script, set default host
config.host(target);
}
}
let mut libs = vec![version.lib_name().to_string()];
match target {
_ if target.contains("linux") => {
config.define("LUA_USE_LINUX", None);
}
_ if target.ends_with("bsd") => {
config.define("LUA_USE_LINUX", None);
}
_ if target.contains("apple-darwin") => {
match version {
Lua51 => config.define("LUA_USE_LINUX", None),
_ => config.define("LUA_USE_MACOSX", None),
};
}
_ if target.contains("apple-ios") => {
match version {
Lua54 | Lua55 => config.define("LUA_USE_IOS", None),
_ => config.define("LUA_USE_POSIX", None),
};
}
_ if target.contains("windows") => {
// Defined in Lua >= 5.3
config.define("LUA_USE_WINDOWS", None);
}
_ if target.ends_with("emscripten") => {
config
.define("LUA_USE_POSIX", None)
.cpp(true)
.flag("-fexceptions")
.flag("-fwasm-exceptions"); // Enable exceptions to be caught
let cpp_source_dir = out_dir.join("cpp_source");
if cpp_source_dir.exists() {
fs::remove_dir_all(&cpp_source_dir)
.context(|| format!("Cannot remove '{}'", cpp_source_dir.display()))?;
}
fs::create_dir_all(&cpp_source_dir)
.context(|| format!("Cannot create '{}'", cpp_source_dir.display()))?;
for file in fs::read_dir(&source_dir)
.context(|| format!("Cannot read '{}'", source_dir.display()))?
{
let file = file?;
let filename = file.file_name();
let filename = &*filename.to_string_lossy();
let src_file = source_dir.join(file.file_name());
let dst_file = cpp_source_dir.join(file.file_name());
let mut content = fs::read(&src_file)
.context(|| format!("Cannot read '{}'", src_file.display()))?;
if ["lauxlib.h", "lua.h", "lualib.h"].contains(&filename) {
content.splice(0..0, b"extern \"C\" {\n".to_vec());
content.extend(b"\n}".to_vec())
}
fs::write(&dst_file, content)
.context(|| format!("Cannot write to '{}'", dst_file.display()))?;
}
source_dir = cpp_source_dir
}
_ if target.contains("wasi") => {
// WASI is posix-like, but further patches are needed to the Lua
// source to get it compiling.
config.define("LUA_USE_POSIX", None);
// Bring in just enough signal-handling support to get Lua at
// least compiling, but WASI in general does not support
// signals.
config.define("_WASI_EMULATED_SIGNAL", None);
libs.push("wasi-emulated-signal".to_string());
// https://github.com/WebAssembly/wasi-sdk/blob/main/SetjmpLongjmp.md
// for information about getting setjmp/longjmp working.
config.flag("-mllvm").flag("-wasm-enable-eh");
config.flag("-mllvm").flag("-wasm-use-legacy-eh=false");
config.flag("-mllvm").flag("-wasm-enable-sjlj");
libs.push("setjmp".to_string());
}
_ => Err(format!("don't know how to build Lua for {target}"))?,
}
if let Lua54 = version {
config.define("LUA_COMPAT_5_3", None);
}
#[cfg(feature = "ucid")]
if let Lua54 | Lua55 = version {
config.define("LUA_UCID", None);
}
let debug = self.debug.unwrap_or(cfg!(debug_assertions));
if debug {
config.define("LUA_USE_APICHECK", None);
config.debug(true);
}
match &self.opt_level {
Some(opt_level) => {
config.opt_level_str(opt_level);
}
// Opt level will be taken from the environment variable
None if env::var("OPT_LEVEL").is_ok() => {}
None => {
// If called outside of build script, set default opt level
config.opt_level(if debug { 0 } else { 2 });
}
}
config
.include(&source_dir)
.warnings(false) // Suppress all warnings
.flag_if_supported("-fno-common") // Compile common globals like normal definitions
.add_files_by_ext(&source_dir, "c")?
.out_dir(&lib_dir)
.try_compile(version.lib_name())?;
for f in &["lauxlib.h", "lua.h", "luaconf.h", "lualib.h"] {
let from = source_dir.join(f);
let to = include_dir.join(f);
fs::copy(&from, &to)
.context(|| format!("Cannot copy '{}' to '{}'", from.display(), to.display()))?;
}
Ok(Artifacts {
root_dir: out_dir.clone(),
include_dir,
lib_dir,
libs,
})
}
}
impl Version {
fn source_dir(&self) -> &'static str {
match self {
Lua51 => "lua-5.1.5",
Lua52 => "lua-5.2.4",
Lua53 => "lua-5.3.6",
Lua54 => "lua-5.4.8",
Lua55 => "lua-5.5.0",
}
}
fn lib_name(&self) -> &'static str {
match self {
Lua51 => "lua5.1",
Lua52 => "lua5.2",
Lua53 => "lua5.3",
Lua54 => "lua5.4",
Lua55 => "lua5.5",
}
}
}
impl Artifacts {
/// Returns the directory containing the `include` and `lib` directories.
pub fn root_dir(&self) -> &Path {
&self.root_dir
}
/// Returns the directory containing the Lua headers.
pub fn include_dir(&self) -> &Path {
&self.include_dir
}
/// Returns the directory containing the Lua libraries.
pub fn lib_dir(&self) -> &Path {
&self.lib_dir
}
/// Returns the names of the Lua libraries built.
pub fn libs(&self) -> &[String] {
&self.libs
}
/// Prints the necessary Cargo metadata for linking the Lua libraries.
///
/// This method is typically called in a build script to inform Cargo
/// about the location of the Lua libraries and how to link them.
pub fn print_cargo_metadata(&self) {
println!("cargo:rustc-link-search=native={}", self.lib_dir.display());
for lib in self.libs.iter() {
println!("cargo:rustc-link-lib=static:-bundle={lib}");
}
}
/// Prints the necessary Cargo metadata such that dependent build scripts
/// can find the Lua install root and include directories in their
/// `DEP_LUA_ROOT` and `DEP_LUA_INCLUDE` environment variables.
///
/// This method is typically called in a build script to inform Cargo
/// about the Lua install location.
pub fn print_cargo_root(&self) {
println!("cargo:root={}", self.root_dir().display());
println!("cargo:include={}", self.include_dir().display());
}
}
trait ErrorContext<T> {
fn context(self, f: impl FnOnce() -> String) -> Result<T, Box<dyn Error>>;
}
impl<T, E: Error> ErrorContext<T> for Result<T, E> {
fn context(self, f: impl FnOnce() -> String) -> Result<T, Box<dyn Error>> {
self.map_err(|e| format!("{}: {e}", f()).into())
}
}
trait AddFilesByExt {
fn add_files_by_ext(&mut self, dir: &Path, ext: &str) -> Result<&mut Self, Box<dyn Error>>;
}
impl AddFilesByExt for cc::Build {
fn add_files_by_ext(&mut self, dir: &Path, ext: &str) -> Result<&mut Self, Box<dyn Error>> {
for entry in fs::read_dir(dir)
.context(|| format!("Cannot read '{}'", dir.display()))?
.filter_map(|e| e.ok())
.filter(|e| e.path().extension() == Some(ext.as_ref()))
{
self.file(entry.path());
}
Ok(self)
}
}