lux_lib/lua_installation/
mod.rs

1use is_executable::IsExecutable;
2use itertools::Itertools;
3use path_slash::PathBufExt;
4use std::fmt;
5use std::fmt::Display;
6use std::io;
7use std::path::Path;
8use std::path::PathBuf;
9use target_lexicon::Triple;
10use tempdir::TempDir;
11use thiserror::Error;
12use which::which;
13
14use crate::build::external_dependency::to_lib_name;
15use crate::build::external_dependency::ExternalDependencyInfo;
16use crate::build::utils::recursive_copy_dir;
17use crate::build::utils::{c_lib_extension, format_path};
18use crate::config::external_deps::ExternalDependencySearchConfig;
19use crate::lua_rockspec::ExternalDependencySpec;
20use crate::{
21    config::{Config, LuaVersion},
22    package::PackageVersion,
23    variables::HasVariables,
24};
25use lazy_static::lazy_static;
26use tokio::sync::Mutex;
27
28// Because installing lua is not thread-safe, we have to synchronize with a global Mutex
29lazy_static! {
30    static ref NEW_MUTEX: Mutex<i32> = Mutex::new(0i32);
31    static ref INSTALL_MUTEX: Mutex<i32> = Mutex::new(0i32);
32}
33
34#[derive(Debug)]
35pub struct LuaInstallation {
36    pub version: LuaVersion,
37    dependency_info: ExternalDependencyInfo,
38    /// Binary to the Lua executable, if present
39    pub(crate) bin: Option<PathBuf>,
40}
41
42#[derive(Debug, Error)]
43pub enum LuaBinaryError {
44    #[error("neither `lua` nor `luajit` found on the PATH")]
45    LuaBinaryNotFound,
46    #[error(transparent)]
47    DetectLuaVersion(#[from] DetectLuaVersionError),
48    #[error(
49        "{} -v (= {}) does not match expected Lua version {}",
50        lua_cmd,
51        installed_version,
52        lua_version
53    )]
54    LuaVersionMismatch {
55        lua_cmd: String,
56        installed_version: PackageVersion,
57        lua_version: LuaVersion,
58    },
59    #[error("{0} not found on the PATH")]
60    CustomBinaryNotFound(String),
61}
62
63#[derive(Error, Debug)]
64pub enum DetectLuaVersionError {
65    #[error("failed to run {0}: {1}")]
66    RunLuaCommand(String, io::Error),
67    #[error("failed to parse Lua version from output: {0}")]
68    ParseLuaVersion(String),
69    #[error(transparent)]
70    PackageVersionParse(#[from] crate::package::PackageVersionParseError),
71    #[error(transparent)]
72    LuaVersion(#[from] crate::config::LuaVersionError),
73}
74
75#[derive(Error, Debug)]
76pub enum LuaInstallationError {
77    #[error("error building Lua from source:\n{0}")]
78    Build(String),
79}
80
81impl LuaInstallation {
82    pub async fn new(version: &LuaVersion, config: &Config) -> Result<Self, LuaInstallationError> {
83        let _lock = NEW_MUTEX.lock().await;
84        if let Some(lua_intallation) = Self::probe(version, config.external_deps()) {
85            return Ok(lua_intallation);
86        }
87        let output = Self::root_dir(version, config);
88        let include_dir = output.join("include");
89        let lib_dir = output.join("lib");
90        let lua_lib_name = get_lua_lib_name(&lib_dir, version);
91        if include_dir.is_dir() && lua_lib_name.is_some() {
92            let bin_dir = Some(output.join("bin")).filter(|bin_path| bin_path.is_dir());
93            let bin = bin_dir
94                .as_ref()
95                .and_then(|bin_path| find_lua_executable(bin_path));
96            let lib_dir = output.join("lib");
97            let lua_lib_name = get_lua_lib_name(&lib_dir, version);
98            let include_dir = Some(output.join("include"));
99            Ok(LuaInstallation {
100                version: version.clone(),
101                dependency_info: ExternalDependencyInfo {
102                    include_dir,
103                    lib_dir: Some(lib_dir),
104                    bin_dir,
105                    lib_info: None,
106                    lib_name: lua_lib_name,
107                },
108                bin,
109            })
110        } else {
111            Self::install(version, config).await
112        }
113    }
114
115    pub(crate) fn probe(
116        version: &LuaVersion,
117        search_config: &ExternalDependencySearchConfig,
118    ) -> Option<Self> {
119        let pkg_name = match version {
120            LuaVersion::Lua51 => "lua5.1",
121            LuaVersion::Lua52 => "lua5.2",
122            LuaVersion::Lua53 => "lua5.3",
123            LuaVersion::Lua54 => "lua5.4",
124            LuaVersion::LuaJIT | LuaVersion::LuaJIT52 => "luajit",
125        };
126
127        let mut dependency_info = ExternalDependencyInfo::probe(
128            pkg_name,
129            &ExternalDependencySpec::default(),
130            search_config,
131        );
132
133        if let Ok(info) = &mut dependency_info {
134            let bin = info.lib_dir.as_ref().and_then(|lib_dir| {
135                lib_dir
136                    .parent()
137                    .map(|parent| parent.join("bin"))
138                    .filter(|dir| dir.is_dir())
139                    .and_then(|bin_path| find_lua_executable(&bin_path))
140            });
141            let lua_lib_name = info
142                .lib_dir
143                .as_ref()
144                .and_then(|lib_dir| get_lua_lib_name(lib_dir, version));
145            info.lib_name = lua_lib_name;
146            Some(Self {
147                version: version.clone(),
148                dependency_info: dependency_info.unwrap(),
149                bin,
150            })
151        } else {
152            None
153        }
154    }
155
156    // XXX: lua_src and luajit_src panic on failure, so we just unwrap errors here.
157    pub async fn install(
158        version: &LuaVersion,
159        config: &Config,
160    ) -> Result<Self, LuaInstallationError> {
161        let _lock = INSTALL_MUTEX.lock().await;
162        let host = Triple::host();
163        let target = &host.to_string();
164        let host_operating_system = &host.operating_system.to_string();
165
166        let output = TempDir::new("lux_lua_installation")
167            .expect("failed to create lua_installation temp directory");
168
169        let (include_dir, lib_dir) = match version {
170            LuaVersion::LuaJIT | LuaVersion::LuaJIT52 => {
171                // XXX: luajit_src panics if this is not set.
172                let target_pointer_width =
173                    std::env::var("CARGO_CFG_TARGET_POINTER_WIDTH").unwrap_or("64".into());
174                std::env::set_var("CARGO_CFG_TARGET_POINTER_WIDTH", target_pointer_width);
175                let build = luajit_src::Build::new()
176                    .target(target)
177                    .host(host_operating_system)
178                    .out_dir(&output)
179                    .lua52compat(matches!(version, LuaVersion::LuaJIT52))
180                    .build();
181
182                (
183                    build.include_dir().to_path_buf(),
184                    build.lib_dir().to_path_buf(),
185                )
186            }
187            _ => {
188                let build = lua_src::Build::new()
189                    .target(target)
190                    .host(host_operating_system)
191                    .out_dir(&output)
192                    .try_build(match version {
193                        LuaVersion::Lua51 => lua_src::Version::Lua51,
194                        LuaVersion::Lua52 => lua_src::Version::Lua52,
195                        LuaVersion::Lua53 => lua_src::Version::Lua53,
196                        LuaVersion::Lua54 => lua_src::Version::Lua54,
197                        _ => unreachable!(),
198                    })
199                    .map_err(|err| LuaInstallationError::Build(err.to_string()))?;
200
201                (
202                    build.include_dir().to_path_buf(),
203                    build.lib_dir().to_path_buf(),
204                )
205            }
206        };
207
208        let target = Self::root_dir(version, config);
209        recursive_copy_dir(&output.into_path(), &target)
210            .await
211            .expect("error copying lua installation");
212
213        let bin_dir = Some(target.join("bin")).filter(|bin_path| bin_path.is_dir());
214        let bin = bin_dir
215            .as_ref()
216            .and_then(|bin_path| find_lua_executable(bin_path));
217        let lua_lib_name = get_lua_lib_name(&lib_dir, version);
218        Ok(LuaInstallation {
219            version: version.clone(),
220            dependency_info: ExternalDependencyInfo {
221                include_dir: Some(include_dir),
222                lib_dir: Some(lib_dir),
223                bin_dir,
224                lib_info: None,
225                lib_name: lua_lib_name,
226            },
227            bin,
228        })
229    }
230
231    pub fn includes(&self) -> Vec<&PathBuf> {
232        self.dependency_info.include_dir.iter().collect_vec()
233    }
234
235    fn root_dir(version: &LuaVersion, config: &Config) -> PathBuf {
236        if let Some(lua_dir) = config.lua_dir() {
237            return lua_dir.clone();
238        } else if let Ok(tree) = config.user_tree(version.clone()) {
239            return tree.root().join(".lua");
240        }
241        config.data_dir().join(".lua").join(version.to_string())
242    }
243
244    #[cfg(not(target_env = "msvc"))]
245    fn lua_lib(&self) -> Option<String> {
246        self.dependency_info
247            .lib_name
248            .as_ref()
249            .map(|name| format!("{}.{}", name, c_lib_extension()))
250    }
251
252    #[cfg(target_env = "msvc")]
253    fn lua_lib(&self) -> Option<String> {
254        self.dependency_info.lib_name.clone()
255    }
256
257    pub(crate) fn define_flags(&self) -> Vec<String> {
258        self.dependency_info.define_flags()
259    }
260
261    /// NOTE: In luarocks, these are behind a link_lua_explicity config option
262    pub(crate) fn lib_link_args(&self, compiler: &cc::Tool) -> Vec<String> {
263        self.dependency_info.lib_link_args(compiler)
264    }
265
266    /// Get the Lua binary (if present), prioritising
267    /// a potentially overridden value in the config.
268    pub(crate) fn lua_binary_or_config_override(&self, config: &Config) -> Option<String> {
269        config.variables().get("LUA").cloned().or(self
270            .bin
271            .clone()
272            .or(LuaBinary::new(self.version.clone(), config).try_into().ok())
273            .map(|bin| bin.to_slash_lossy().to_string()))
274    }
275}
276
277impl HasVariables for LuaInstallation {
278    fn get_variable(&self, input: &str) -> Option<String> {
279        let result = match input {
280            "LUA_INCDIR" => self
281                .dependency_info
282                .include_dir
283                .as_ref()
284                .map(|dir| format_path(dir)),
285            "LUA_LIBDIR" => self
286                .dependency_info
287                .lib_dir
288                .as_ref()
289                .map(|dir| format_path(dir)),
290            "LUA_BINDIR" => self
291                .bin
292                .as_ref()
293                .and_then(|bin| bin.parent().map(format_path)),
294            "LUA" => self
295                .bin
296                .clone()
297                .or(LuaBinary::Lua {
298                    lua_version: self.version.clone(),
299                }
300                .try_into()
301                .ok())
302                .map(|lua| format_path(&lua)),
303            "LUALIB" => self.lua_lib().or(Some("".into())),
304            _ => None,
305        }?;
306        Some(result)
307    }
308}
309
310#[derive(Clone)]
311pub enum LuaBinary {
312    /// The regular Lua interpreter.
313    Lua { lua_version: LuaVersion },
314    /// Custom Lua interpreter.
315    Custom(String),
316}
317
318impl Display for LuaBinary {
319    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
320        match self {
321            LuaBinary::Lua { lua_version } => write!(f, "lua {lua_version}"),
322            LuaBinary::Custom(cmd) => write!(f, "{cmd}"),
323        }
324    }
325}
326
327impl LuaBinary {
328    /// Construct a new `LuaBinary` for the given `LuaVersion`,
329    /// potentially prioritising an overridden value in the config.
330    pub fn new(lua_version: LuaVersion, config: &Config) -> Self {
331        match config.variables().get("LUA").cloned() {
332            Some(lua) => Self::Custom(lua),
333            None => Self::Lua { lua_version },
334        }
335    }
336}
337
338impl From<PathBuf> for LuaBinary {
339    fn from(value: PathBuf) -> Self {
340        Self::Custom(value.to_string_lossy().to_string())
341    }
342}
343
344impl TryFrom<LuaBinary> for PathBuf {
345    type Error = LuaBinaryError;
346
347    fn try_from(value: LuaBinary) -> Result<Self, Self::Error> {
348        match value {
349            LuaBinary::Lua { lua_version } => {
350                if let Some(lua_binary) =
351                    LuaInstallation::probe(&lua_version, &ExternalDependencySearchConfig::default())
352                        .and_then(|lua_installation| lua_installation.bin)
353                {
354                    return Ok(lua_binary);
355                }
356                if lua_version.is_luajit() {
357                    if let Ok(path) = which("luajit") {
358                        return Ok(path);
359                    }
360                }
361                match which("lua") {
362                    Ok(path) => {
363                        let installed_version = detect_installed_lua_version_from_path(&path)?;
364                        if lua_version
365                            .clone()
366                            .as_version_req()
367                            .matches(&installed_version)
368                        {
369                            Ok(path)
370                        } else {
371                            Err(Self::Error::LuaVersionMismatch {
372                                lua_cmd: path.to_slash_lossy().to_string(),
373                                installed_version,
374                                lua_version,
375                            })?
376                        }
377                    }
378                    Err(_) => Err(LuaBinaryError::LuaBinaryNotFound),
379                }
380            }
381            LuaBinary::Custom(bin) => match which(&bin) {
382                Ok(path) => Ok(path),
383                Err(_) => Err(LuaBinaryError::CustomBinaryNotFound(bin)),
384            },
385        }
386    }
387}
388
389pub fn detect_installed_lua_version() -> Option<LuaVersion> {
390    which("lua")
391        .ok()
392        .or(which("luajit").ok())
393        .and_then(|lua_cmd| {
394            detect_installed_lua_version_from_path(&lua_cmd)
395                .ok()
396                .and_then(|version| LuaVersion::from_version(version).ok())
397        })
398}
399
400fn find_lua_executable(bin_path: &Path) -> Option<PathBuf> {
401    std::fs::read_dir(bin_path).ok().and_then(|entries| {
402        entries
403            .filter_map(Result::ok)
404            .map(|entry| entry.path().to_path_buf())
405            .filter(|file| {
406                file.is_executable()
407                    && file.file_name().is_some_and(|name| {
408                        matches!(
409                            name.to_string_lossy().to_string().as_str(),
410                            "lua" | "luajit"
411                        )
412                    })
413            })
414            .collect_vec()
415            .first()
416            .cloned()
417    })
418}
419
420fn is_lua_lib_name(name: &str, lua_version: &LuaVersion) -> bool {
421    let prefixes = match lua_version {
422        LuaVersion::LuaJIT | LuaVersion::LuaJIT52 => vec!["luajit", "lua"],
423        _ => vec!["lua"],
424    };
425    let version_str = lua_version.version_compatibility_str();
426    let version_suffix = version_str.replace(".", "");
427    #[cfg(target_family = "unix")]
428    let name = name.trim_start_matches("lib");
429    prefixes
430        .iter()
431        .any(|prefix| name == format!("{}.{}", *prefix, c_lib_extension()))
432        || prefixes.iter().any(|prefix| name.starts_with(*prefix))
433            && (name.contains(&version_str) || name.contains(&version_suffix))
434}
435
436fn get_lua_lib_name(lib_dir: &Path, lua_version: &LuaVersion) -> Option<String> {
437    std::fs::read_dir(lib_dir)
438        .ok()
439        .and_then(|entries| {
440            entries
441                .filter_map(Result::ok)
442                .map(|entry| entry.path().to_path_buf())
443                .filter(|file| file.extension().is_some_and(|ext| ext == c_lib_extension()))
444                .filter(|file| {
445                    file.file_name()
446                        .is_some_and(|name| is_lua_lib_name(&name.to_string_lossy(), lua_version))
447                })
448                .collect_vec()
449                .first()
450                .cloned()
451        })
452        .map(|file| to_lib_name(&file))
453}
454
455fn detect_installed_lua_version_from_path(
456    lua_cmd: &Path,
457) -> Result<PackageVersion, DetectLuaVersionError> {
458    let output = match std::process::Command::new(lua_cmd).arg("-v").output() {
459        Ok(output) => Ok(output),
460        Err(err) => Err(DetectLuaVersionError::RunLuaCommand(
461            lua_cmd.to_string_lossy().to_string(),
462            err,
463        )),
464    }?;
465    let output_vec = if output.stderr.is_empty() {
466        output.stdout
467    } else {
468        // Yes, Lua 5.1 prints to stderr (-‸ლ)
469        output.stderr
470    };
471    let lua_output = String::from_utf8_lossy(&output_vec).to_string();
472    parse_lua_version_from_output(&lua_output)
473}
474
475fn parse_lua_version_from_output(
476    lua_output: &str,
477) -> Result<PackageVersion, DetectLuaVersionError> {
478    let lua_version_str = lua_output
479        .trim_start_matches("Lua")
480        .trim_start_matches("JIT")
481        .split_whitespace()
482        .next()
483        .map(|s| s.to_string())
484        .ok_or(DetectLuaVersionError::ParseLuaVersion(
485            lua_output.to_string(),
486        ))?;
487    Ok(PackageVersion::parse(&lua_version_str)?)
488}
489
490#[cfg(test)]
491mod test {
492    use crate::config::ConfigBuilder;
493
494    use super::*;
495
496    #[tokio::test]
497    async fn parse_luajit_version() {
498        let luajit_output =
499            "LuaJIT 2.1.1713773202 -- Copyright (C) 2005-2023 Mike Pall. https://luajit.org/";
500        parse_lua_version_from_output(luajit_output).unwrap();
501    }
502
503    #[tokio::test]
504    async fn parse_lua_51_version() {
505        let lua_output = "Lua 5.1.5  Copyright (C) 1994-2012 Lua.org, PUC-Rio";
506        parse_lua_version_from_output(lua_output).unwrap();
507    }
508
509    #[tokio::test]
510    async fn lua_installation_bin() {
511        if std::env::var("LUX_SKIP_IMPURE_TESTS").unwrap_or("0".into()) == "1" {
512            println!("Skipping impure test");
513            return;
514        }
515        let config = ConfigBuilder::new().unwrap().build().unwrap();
516        let lua_version = config.lua_version().unwrap();
517        let lua_installation = LuaInstallation::new(lua_version, &config).await.unwrap();
518        // FIXME: This fails when run in the nix checkPhase
519        assert!(lua_installation.bin.is_some());
520        let lua_binary: LuaBinary = lua_installation.bin.unwrap().into();
521        let lua_bin_path: PathBuf = lua_binary.try_into().unwrap();
522        let pkg_version = detect_installed_lua_version_from_path(&lua_bin_path).unwrap();
523        assert_eq!(&LuaVersion::from_version(pkg_version).unwrap(), lua_version);
524    }
525
526    #[cfg(not(target_env = "msvc"))]
527    #[tokio::test]
528    async fn test_is_lua_lib_name() {
529        assert!(is_lua_lib_name("lua.a", &LuaVersion::Lua51));
530        assert!(is_lua_lib_name("lua-5.1.a", &LuaVersion::Lua51));
531        assert!(is_lua_lib_name("lua5.1.a", &LuaVersion::Lua51));
532        assert!(is_lua_lib_name("lua51.a", &LuaVersion::Lua51));
533        assert!(!is_lua_lib_name("lua-5.2.a", &LuaVersion::Lua51));
534        assert!(is_lua_lib_name("luajit-5.2.a", &LuaVersion::LuaJIT52));
535        assert!(is_lua_lib_name("lua-5.2.a", &LuaVersion::LuaJIT52));
536        assert!(is_lua_lib_name("liblua.a", &LuaVersion::Lua51));
537        assert!(is_lua_lib_name("liblua-5.1.a", &LuaVersion::Lua51));
538        assert!(is_lua_lib_name("liblua53.a", &LuaVersion::Lua53));
539        assert!(is_lua_lib_name("liblua-54.a", &LuaVersion::Lua54));
540    }
541
542    #[cfg(target_env = "msvc")]
543    #[tokio::test]
544    async fn test_is_lua_lib_name() {
545        assert!(is_lua_lib_name("lua.lib", &LuaVersion::Lua51));
546        assert!(is_lua_lib_name("lua-5.1.lib", &LuaVersion::Lua51));
547        assert!(!is_lua_lib_name("lua-5.2.lib", &LuaVersion::Lua51));
548        assert!(!is_lua_lib_name("lua53.lib", &LuaVersion::Lua53));
549        assert!(!is_lua_lib_name("lua53.lib", &LuaVersion::Lua53));
550        assert!(is_lua_lib_name("luajit-5.2.lib", &LuaVersion::LuaJIT52));
551        assert!(is_lua_lib_name("lua-5.2.lib", &LuaVersion::LuaJIT52));
552    }
553}