Skip to main content

lua_src/
lib.rs

1use std::env;
2use std::error::Error;
3use std::fs;
4use std::path::{Path, PathBuf};
5
6/// Represents the version of Lua to build.
7#[derive(Debug, PartialEq, Eq)]
8pub enum Version {
9    Lua51,
10    Lua52,
11    Lua53,
12    Lua54,
13    Lua55,
14}
15pub use self::Version::*;
16
17/// Represents the configuration for building Lua artifacts.
18pub struct Build {
19    out_dir: Option<PathBuf>,
20    target: Option<String>,
21    host: Option<String>,
22    opt_level: Option<String>,
23    debug: Option<bool>,
24}
25
26/// Represents the artifacts produced by the build process.
27#[derive(Clone, Debug)]
28pub struct Artifacts {
29    include_dir: PathBuf,
30    lib_dir: PathBuf,
31    libs: Vec<String>,
32}
33
34impl Default for Build {
35    fn default() -> Build {
36        Build {
37            out_dir: env::var_os("OUT_DIR").map(PathBuf::from),
38            target: env::var("TARGET").ok(),
39            host: None,
40            opt_level: None,
41            debug: None,
42        }
43    }
44}
45
46impl Build {
47    /// Creates a new `Build` instance with default settings.
48    pub fn new() -> Build {
49        Build::default()
50    }
51
52    /// Sets the output directory for the build artifacts.
53    ///
54    /// This is required if called outside of a build script.
55    pub fn out_dir<P: AsRef<Path>>(&mut self, path: P) -> &mut Build {
56        self.out_dir = Some(path.as_ref().to_path_buf());
57        self
58    }
59
60    /// Sets the target architecture for the build.
61    ///
62    /// This is required if called outside of a build script.
63    pub fn target(&mut self, target: &str) -> &mut Build {
64        self.target = Some(target.to_string());
65        self
66    }
67
68    /// Sets the host architecture for the build.
69    ///
70    /// This is optional and will default to the environment variable `HOST` if not set.
71    /// If called outside of a build script, it will default to the target architecture.
72    pub fn host(&mut self, host: &str) -> &mut Build {
73        self.host = Some(host.to_string());
74        self
75    }
76
77    /// Sets the optimization level for the build.
78    ///
79    /// This is optional and will default to the environment variable `OPT_LEVEL` if not set.
80    /// If called outside of a build script, it will default to `0` in debug mode and `2` otherwise.
81    pub fn opt_level(&mut self, opt_level: &str) -> &mut Build {
82        self.opt_level = Some(opt_level.to_string());
83        self
84    }
85
86    /// Sets whether to build in debug mode.
87    ///
88    /// This is optional and will default to the value of `cfg!(debug_assertions)`.
89    /// If set to `true`, it also enables Lua API checks.
90    pub fn debug(&mut self, debug: bool) -> &mut Build {
91        self.debug = Some(debug);
92        self
93    }
94
95    /// Builds the Lua artifacts for the specified version.
96    pub fn build(&self, version: Version) -> Artifacts {
97        match self.try_build(version) {
98            Ok(artifacts) => artifacts,
99            Err(err) => panic!("{err}"),
100        }
101    }
102
103    /// Attempts to build the Lua artifacts for the specified version.
104    ///
105    /// Returns an error if the build fails.
106    pub fn try_build(&self, version: Version) -> Result<Artifacts, Box<dyn Error>> {
107        let target = self.target.as_ref().ok_or("TARGET is not set")?;
108        let out_dir = self.out_dir.as_ref().ok_or("OUT_DIR is not set")?;
109        let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
110        let source_dir = manifest_dir.join(version.source_dir());
111        let lib_dir = out_dir.join("lib");
112        let include_dir = out_dir.join("include");
113
114        if !include_dir.exists() {
115            fs::create_dir_all(&include_dir)
116                .context(|| format!("Cannot create '{}'", include_dir.display()))?;
117        }
118
119        let mut config = cc::Build::new();
120        config.warnings(false).cargo_metadata(false).target(target);
121
122        match &self.host {
123            Some(host) => {
124                config.host(host);
125            }
126            // Host will be taken from the environment variable
127            None if env::var("HOST").is_ok() => {}
128            None => {
129                // If called outside of build script, set default host
130                config.host(target);
131            }
132        }
133
134        let mut libs = vec![version.lib_name().to_string()];
135        match target {
136            _ if target.contains("linux") => {
137                config.define("LUA_USE_LINUX", None);
138            }
139            _ if target.ends_with("bsd")
140                || target.contains("netbsd")
141                || target.contains("dragonfly") =>
142            {
143                config.define("LUA_USE_LINUX", None);
144            }
145            _ if target.ends_with("illumos") => {
146                config.define("LUA_USE_POSIX", None);
147            }
148            _ if target.ends_with("solaris") => {
149                config.define("LUA_USE_POSIX", None);
150            }
151            _ if target.contains("apple-darwin") => {
152                match version {
153                    Lua51 => config.define("LUA_USE_LINUX", None),
154                    _ => config.define("LUA_USE_MACOSX", None),
155                };
156            }
157            _ if target.contains("apple-ios") => {
158                match version {
159                    Lua54 | Lua55 => config.define("LUA_USE_IOS", None),
160                    _ => config.define("LUA_USE_POSIX", None),
161                };
162            }
163            _ if target.contains("windows") => {
164                // Defined in Lua >= 5.3
165                config.define("LUA_USE_WINDOWS", None);
166            }
167            _ if target.ends_with("emscripten") => {
168                config
169                    .define("LUA_USE_POSIX", None)
170                    .flag("-sSUPPORT_LONGJMP=wasm"); // Enable setjmp/longjmp support (WASM-specific)
171            }
172            _ if target.contains("wasi") => {
173                // WASI is posix-like, but further patches are needed to the Lua
174                // source to get it compiling.
175                config.define("LUA_USE_POSIX", None);
176
177                // Bring in just enough signal-handling support to get Lua at
178                // least compiling, but WASI in general does not support
179                // signals.
180                config.define("_WASI_EMULATED_SIGNAL", None);
181                libs.push("wasi-emulated-signal".to_string());
182
183                // https://github.com/WebAssembly/wasi-sdk/blob/main/SetjmpLongjmp.md
184                // for information about getting setjmp/longjmp working.
185                config.flag("-mllvm").flag("-wasm-enable-eh");
186                config.flag("-mllvm").flag("-wasm-use-legacy-eh=false");
187                config.flag("-mllvm").flag("-wasm-enable-sjlj");
188                libs.push("setjmp".to_string());
189            }
190            _ => Err(format!("don't know how to build Lua for {target}"))?,
191        }
192
193        if let Lua54 = version {
194            config.define("LUA_COMPAT_5_3", None);
195        }
196
197        #[cfg(feature = "ucid")]
198        if let Lua54 | Lua55 = version {
199            config.define("LUA_UCID", None);
200        }
201
202        let debug = self.debug.unwrap_or(cfg!(debug_assertions));
203        if debug {
204            config.define("LUA_USE_APICHECK", None);
205            config.debug(true);
206        }
207
208        match &self.opt_level {
209            Some(opt_level) => {
210                config.opt_level_str(opt_level);
211            }
212            // Opt level will be taken from the environment variable
213            None if env::var("OPT_LEVEL").is_ok() => {}
214            None => {
215                // If called outside of build script, set default opt level
216                config.opt_level(if debug { 0 } else { 2 });
217            }
218        }
219
220        config
221            .include(&source_dir)
222            .warnings(false) // Suppress all warnings
223            .flag_if_supported("-fno-common") // Compile common globals like normal definitions
224            .add_files_by_ext(&source_dir, "c")?
225            .out_dir(&lib_dir)
226            .try_compile(version.lib_name())?;
227
228        for f in &["lauxlib.h", "lua.h", "luaconf.h", "lualib.h"] {
229            let from = source_dir.join(f);
230            let to = include_dir.join(f);
231            fs::copy(&from, &to)
232                .context(|| format!("Cannot copy '{}' to '{}'", from.display(), to.display()))?;
233        }
234
235        Ok(Artifacts {
236            include_dir,
237            lib_dir,
238            libs,
239        })
240    }
241}
242
243impl Version {
244    fn source_dir(&self) -> &'static str {
245        match self {
246            Lua51 => "lua-5.1.5",
247            Lua52 => "lua-5.2.4",
248            Lua53 => "lua-5.3.6",
249            Lua54 => "lua-5.4.8",
250            Lua55 => "lua-5.5.0",
251        }
252    }
253
254    fn lib_name(&self) -> &'static str {
255        match self {
256            Lua51 => "lua5.1",
257            Lua52 => "lua5.2",
258            Lua53 => "lua5.3",
259            Lua54 => "lua5.4",
260            Lua55 => "lua5.5",
261        }
262    }
263}
264
265impl Artifacts {
266    /// Returns the directory containing the Lua headers.
267    pub fn include_dir(&self) -> &Path {
268        &self.include_dir
269    }
270
271    /// Returns the directory containing the Lua libraries.
272    pub fn lib_dir(&self) -> &Path {
273        &self.lib_dir
274    }
275
276    /// Returns the names of the Lua libraries built.
277    pub fn libs(&self) -> &[String] {
278        &self.libs
279    }
280
281    /// Prints the necessary Cargo metadata for linking the Lua libraries.
282    ///
283    /// This method is typically called in a build script to inform Cargo
284    /// about the location of the Lua libraries and how to link them.
285    pub fn print_cargo_metadata(&self) {
286        println!("cargo:rustc-link-search=native={}", self.lib_dir.display());
287        for lib in self.libs.iter() {
288            println!("cargo:rustc-link-lib=static:-bundle={lib}");
289        }
290        println!("cargo:include={}", self.include_dir.display());
291        println!("cargo:lib={}", self.lib_dir.display());
292    }
293}
294
295trait ErrorContext<T> {
296    fn context(self, f: impl FnOnce() -> String) -> Result<T, Box<dyn Error>>;
297}
298
299impl<T, E: Error> ErrorContext<T> for Result<T, E> {
300    fn context(self, f: impl FnOnce() -> String) -> Result<T, Box<dyn Error>> {
301        self.map_err(|e| format!("{}: {e}", f()).into())
302    }
303}
304
305trait AddFilesByExt {
306    fn add_files_by_ext(&mut self, dir: &Path, ext: &str) -> Result<&mut Self, Box<dyn Error>>;
307}
308
309impl AddFilesByExt for cc::Build {
310    fn add_files_by_ext(&mut self, dir: &Path, ext: &str) -> Result<&mut Self, Box<dyn Error>> {
311        for entry in fs::read_dir(dir)
312            .context(|| format!("Cannot read '{}'", dir.display()))?
313            .filter_map(|e| e.ok())
314            .filter(|e| e.path().extension() == Some(ext.as_ref()))
315        {
316            self.file(entry.path());
317        }
318        Ok(self)
319    }
320}