Skip to main content

lux_lib/lua/
installation.rs

1use is_executable::IsExecutable;
2use itertools::Itertools;
3use miette::Diagnostic;
4use path_slash::PathBufExt;
5use std::path::Path;
6use std::path::PathBuf;
7use thiserror::Error;
8use which::which;
9
10use super::binary::Binary;
11use super::detect;
12use super::version::{self, Version};
13use crate::build::external_dependency::to_lib_name;
14use crate::build::external_dependency::ExternalDependencyInfo;
15use crate::config::external_deps::ExternalDependencySearchConfig;
16use crate::fs;
17use crate::operations::build_lua;
18use crate::package;
19use crate::rockspec;
20use crate::tree::InstallTree;
21use crate::variables::GetVariableError;
22use crate::{config::Config, variables::HasVariables};
23use crate::{path, target};
24use lazy_static::lazy_static;
25use tokio::sync::Mutex;
26
27// Because installing lua is not thread-safe, we have to synchronize with a global Mutex
28lazy_static! {
29    static ref NEW_MUTEX: Mutex<i32> = Mutex::new(0i32);
30    static ref INSTALL_MUTEX: Mutex<i32> = Mutex::new(0i32);
31}
32
33#[derive(Debug)]
34pub struct Installation {
35    pub version: Version,
36    dependency_info: ExternalDependencyInfo,
37    /// Binary to the Lua executable, if present
38    pub(crate) bin: Option<PathBuf>,
39}
40
41#[derive(Error, Debug, Diagnostic)]
42#[non_exhaustive]
43pub enum Error {
44    #[error("could not find a Lua installation and failed to build Lua from source")]
45    #[diagnostic(forward(0))]
46    Build(#[from] build_lua::Error),
47    #[error(transparent)]
48    #[diagnostic(transparent)]
49    Version(#[from] version::Error),
50    #[error("`luau` binary not found after building Luau from source")]
51    #[diagnostic(help("this is probably a bug"))]
52    LuauBinaryNotFoundAfterBuild,
53    #[error("neither `lua` nor `luajit` found on the PATH")]
54    BinaryNotFound,
55    #[error("neither `luau` nor `lune` found on the PATH.")]
56    #[diagnostic(
57        help("ensure luau is installed or run `lx install-lua --lua-version luau`"),
58        url("https://github.com/luau-lang/luau/releases")
59    )]
60    LuauBinaryNotFound,
61    #[error(transparent)]
62    #[diagnostic(transparent)]
63    DetectVersion(#[from] detect::Error),
64    #[error(
65        r#"
66{} -v (= {}) does not match expected Lua version: {}.
67
68Try setting
69
70```toml
71[variables]
72LUA = "/path/to/lua_binary"
73```
74
75in your config, or use `-v LUA=/path/to/lua_binary`.
76    "#,
77        cmd,
78        installed_version,
79        required_version
80    )]
81    VersionMismatch {
82        cmd: String,
83        installed_version: package::Version,
84        required_version: Version,
85    },
86    #[error("{0} not found on the PATH")]
87    CustomBinaryNotFound(String),
88}
89
90impl Installation {
91    #[tracing::instrument(level = "trace", skip_all)]
92    pub async fn new_from_config(config: &Config) -> Result<Self, Error> {
93        Self::new(Version::from(config)?, config).await
94    }
95
96    #[tracing::instrument(level = "trace", skip(config))]
97    pub async fn new(version: &Version, config: &Config) -> Result<Self, Error> {
98        let _lock = NEW_MUTEX.lock().await;
99        if let Some(lua_intallation) = Self::probe(version, config.external_deps()) {
100            return Ok(lua_intallation);
101        }
102        if version.is_luau() {
103            if let Ok(bin) = PathBuf::try_from(Binary::new(version.clone(), config)) {
104                return Ok(Self::from_bin_path(version.clone(), bin));
105            }
106            return match Self::luau_from_root_dir(&Self::root_dir(version, config)) {
107                Some(lua_installation) => Ok(lua_installation),
108                None => Self::install(version, config).await,
109            };
110        }
111        let output = Self::root_dir(version, config);
112        let include_dir = output.join("include");
113        let lib_dir = output.join("lib");
114        let lua_lib_name = lib_name(&lib_dir, version);
115        if include_dir.is_dir() && lua_lib_name.is_some() {
116            let bin_dir = Some(output.join("bin")).filter(|bin_path| bin_path.is_dir());
117            let bin = bin_dir
118                .as_ref()
119                .and_then(|bin_path| find_executable(bin_path, version));
120            let lib_dir = output.join("lib");
121            let lua_lib_name = lib_name(&lib_dir, version);
122            let include_dir = Some(output.join("include"));
123            Ok(Installation {
124                version: version.clone(),
125                dependency_info: ExternalDependencyInfo {
126                    include_dir,
127                    lib_dir: Some(lib_dir),
128                    bin_dir,
129                    lib_info: None,
130                    lib_name: lua_lib_name,
131                },
132                bin,
133            })
134        } else {
135            Self::install(version, config).await
136        }
137    }
138
139    #[tracing::instrument(level = "trace")]
140    pub(crate) fn probe(
141        version: &Version,
142        search_config: &ExternalDependencySearchConfig,
143    ) -> Option<Self> {
144        let pkg_name_probes = match version {
145            Version::Lua51 => vec!["lua5.1", "lua-5.1"],
146            Version::Lua52 => vec!["lua5.2", "lua-5.2"],
147            Version::Lua53 => vec!["lua5.3", "lua-5.3"],
148            Version::Lua54 => vec!["lua5.4", "lua-5.4"],
149            Version::Lua55 => vec!["lua5.5", "lua-5.5"],
150            Version::LuaJIT | Version::LuaJIT52 => vec!["luajit"],
151            // NOTE: lune is a standalone binary with no pkg-config metadata or C API
152            Version::Luau => vec!["luau"],
153        };
154
155        let mut dependency_info = pkg_name_probes
156            .iter()
157            .map(|pkg_name| {
158                ExternalDependencyInfo::probe(
159                    pkg_name,
160                    &rockspec::external_dependency::Spec::default(),
161                    search_config,
162                )
163            })
164            .find_map(Result::ok);
165
166        if let Some(info) = &mut dependency_info {
167            if info.include_dir.is_none() || info.lib_dir.is_none() {
168                return None;
169            }
170            let bin = info.lib_dir.as_ref().and_then(|lib_dir| {
171                lib_dir
172                    .parent()
173                    .map(|parent| parent.join("bin"))
174                    .filter(|dir| dir.is_dir())
175                    .and_then(|bin_path| find_executable(&bin_path, version))
176            });
177            let lua_lib_name = info
178                .lib_dir
179                .as_ref()
180                .and_then(|lib_dir| lib_name(lib_dir, version));
181            info.lib_name = lua_lib_name;
182            dependency_info.map(|dependency_info| Self {
183                version: version.clone(),
184                dependency_info,
185                bin,
186            })
187        } else {
188            None
189        }
190    }
191
192    #[tracing::instrument(level = "trace", skip(config))]
193    pub async fn install(version: &Version, config: &Config) -> Result<Self, Error> {
194        let _lock = INSTALL_MUTEX.lock().await;
195
196        let target = Self::root_dir(version, config);
197
198        build_lua::BuildLua::new()
199            .lua_version(version)
200            .install_dir(&target)
201            .config(config)
202            .build()
203            .await?;
204
205        if version.is_luau() {
206            return Self::luau_from_root_dir(&target).ok_or(Error::LuauBinaryNotFoundAfterBuild);
207        }
208
209        let include_dir = target.join("include");
210        let lib_dir = target.join("lib");
211        let bin_dir = Some(target.join("bin")).filter(|bin_path| bin_path.is_dir());
212        let bin = bin_dir
213            .as_ref()
214            .and_then(|bin_path| find_executable(bin_path, version));
215        let lua_lib_name = lib_name(&lib_dir, version);
216        Ok(Installation {
217            version: version.clone(),
218            dependency_info: ExternalDependencyInfo {
219                include_dir: Some(include_dir),
220                lib_dir: Some(lib_dir),
221                bin_dir,
222                lib_info: None,
223                lib_name: lua_lib_name,
224            },
225            bin,
226        })
227    }
228
229    pub fn includes(&self) -> Vec<&PathBuf> {
230        self.dependency_info.include_dir.iter().collect_vec()
231    }
232
233    pub fn bin(&self) -> &Option<PathBuf> {
234        &self.bin
235    }
236
237    fn luau_from_root_dir(root: &Path) -> Option<Self> {
238        let bin_dir = root.join("bin");
239        let bin = find_executable(&bin_dir, &Version::Luau)?;
240        Some(Self {
241            version: Version::Luau,
242            dependency_info: ExternalDependencyInfo {
243                include_dir: None,
244                lib_dir: None,
245                bin_dir: bin.parent().map(Path::to_path_buf),
246                lib_info: None,
247                lib_name: None,
248            },
249            bin: Some(bin),
250        })
251    }
252
253    /// A Lua installation referencing a binary found on the PATH,
254    /// without probing for headers/libraries or building from source.
255    /// Used for installations that don't link against the Lua C API.
256    fn from_bin_path(version: Version, bin: PathBuf) -> Self {
257        Self {
258            version,
259            dependency_info: ExternalDependencyInfo {
260                include_dir: None,
261                lib_dir: None,
262                bin_dir: bin.parent().map(Path::to_path_buf),
263                lib_info: None,
264                lib_name: None,
265            },
266            bin: Some(bin),
267        }
268    }
269
270    fn root_dir(version: &Version, config: &Config) -> PathBuf {
271        if let Some(lua_dir) = config.lua_dir() {
272            return lua_dir.clone();
273        } else if let Ok(tree) = config.user_tree(version.clone()) {
274            return tree.root().join(".lua");
275        }
276        config.data_dir().join(".lua").join(version.to_string())
277    }
278
279    #[cfg(not(target_env = "msvc"))]
280    fn lua_lib(&self) -> Option<String> {
281        self.dependency_info
282            .lib_name
283            .as_ref()
284            .map(|name| format!("{}.{}", name, target::c_lib_extension()))
285    }
286
287    #[cfg(target_env = "msvc")]
288    fn lua_lib(&self) -> Option<String> {
289        self.dependency_info.lib_name.clone()
290    }
291
292    pub(crate) fn define_flags(&self) -> Vec<String> {
293        let mut defines = self.dependency_info.define_flags();
294        if self.version.is_luajit() {
295            defines.push("-DLUAJIT_VERSION".into());
296        }
297        defines
298    }
299
300    pub(crate) fn lib_link_args(&self, compiler: &cc::Tool) -> Vec<String> {
301        self.dependency_info.lib_link_args(compiler)
302    }
303
304    /// Get the Lua binary (if present), prioritising
305    /// a potentially overridden value in the config.
306    pub(crate) fn lua_binary_or_config_override(&self, config: &Config) -> Option<String> {
307        let variable = if self.version.is_luau() {
308            "LUAU"
309        } else {
310            "LUA"
311        };
312        config.variables().get(variable).cloned().or(self
313            .bin
314            .clone()
315            .or(Binary::new(self.version.clone(), config).try_into().ok())
316            .map(|bin| bin.to_slash_lossy().to_string()))
317    }
318}
319
320impl HasVariables for Installation {
321    #[tracing::instrument(level = "trace")]
322    fn get_variable(&self, input: &str) -> Result<Option<String>, GetVariableError> {
323        Ok(match input {
324            "LUA_INCDIR" => self
325                .dependency_info
326                .include_dir
327                .as_ref()
328                .map(|dir| path::quoted(dir)),
329            "LUA_LIBDIR" => self
330                .dependency_info
331                .lib_dir
332                .as_ref()
333                .map(|dir| path::quoted(dir)),
334            "LUA_BINDIR" => self
335                .bin
336                .as_ref()
337                .and_then(|bin| bin.parent().map(path::quoted)),
338            "LUA" => self
339                .bin
340                .clone()
341                .or(Binary::Lua {
342                    version: self.version.clone(),
343                }
344                .try_into()
345                .ok())
346                .map(|lua| path::quoted(&lua)),
347            "LUAU" if self.version.is_luau() => self.bin.as_ref().map(|bin| path::quoted(bin)),
348            "LUALIB" => self.lua_lib().or(Some("".into())),
349            _ => None,
350        })
351    }
352}
353
354impl TryFrom<Binary> for PathBuf {
355    type Error = Error;
356
357    fn try_from(value: Binary) -> Result<Self, Self::Error> {
358        match value {
359            Binary::Lua { version } => {
360                if version.is_luau() {
361                    return which("luau")
362                        .or_else(|_| which("lune"))
363                        .map_err(|_| Error::LuauBinaryNotFound);
364                }
365                if let Some(lua_binary) =
366                    Installation::probe(&version, &ExternalDependencySearchConfig::default())
367                        .and_then(|lua_installation| lua_installation.bin)
368                {
369                    return Ok(lua_binary);
370                }
371                if version.is_luajit() {
372                    if let Ok(path) = which("luajit") {
373                        return Ok(path);
374                    }
375                }
376                match which(format!("lua{}", version)) {
377                    Ok(path) => Ok(path),
378                    Err(_) => default_bin(version),
379                }
380            }
381            Binary::Custom(bin) => match which(&bin) {
382                Ok(path) => Ok(path),
383                Err(_) => Err(Error::CustomBinaryNotFound(bin)),
384            },
385        }
386    }
387}
388
389fn default_bin(version: Version) -> Result<PathBuf, Error> {
390    match which("lua") {
391        Ok(path) => {
392            let installed_version = detect::version_from_path(&path)?;
393            if version.clone().as_version_req().matches(&installed_version) {
394                Ok(path)
395            } else {
396                Err(Error::VersionMismatch {
397                    cmd: path.to_slash_lossy().to_string(),
398                    installed_version,
399                    required_version: version,
400                })?
401            }
402        }
403        Err(_) => Err(Error::BinaryNotFound),
404    }
405}
406
407/// Determine the Lua version to use with the `nvim` preset.
408/// Prefers LuaJIT if installed, falling back to Lua 5.1.
409pub fn version_for_neovim() -> Option<Version> {
410    if Installation::probe(&Version::LuaJIT, &Default::default()).is_some() {
411        Some(Version::LuaJIT)
412    } else if Installation::probe(&Version::Lua51, &Default::default()).is_some() {
413        Some(Version::Lua51)
414    } else {
415        None
416    }
417}
418
419fn find_executable(bin_path: &Path, version: &Version) -> Option<PathBuf> {
420    fs::sync::read_dir(bin_path).ok().and_then(|entries| {
421        let bin_files = entries
422            .filter_map(Result::ok)
423            .map(|entry| entry.path().to_path_buf())
424            .collect_vec();
425
426        #[cfg(windows)]
427        let ext = ".exe";
428
429        #[cfg(not(windows))]
430        let ext = "";
431
432        if version.is_luau() {
433            let luau_bin = format!("luau{ext}");
434            return bin_files
435                .into_iter()
436                .filter(|file| {
437                    file.is_executable()
438                        && file
439                            .file_name()
440                            .is_some_and(|name| name.to_string_lossy() == luau_bin)
441                })
442                .collect_vec()
443                .first()
444                .cloned();
445        }
446
447        // Prioritise Lua binaries with version suffix
448        // (see https://github.com/lumen-oss/lux/issues/1215)
449        let version_bin = format!("lua{}{}", version, ext);
450        if let Some(lua_bin) = bin_files
451            .iter()
452            .filter(|file| {
453                file.is_executable()
454                    && file
455                        .file_name()
456                        .is_some_and(|name| name.to_string_lossy() == version_bin)
457            })
458            .collect_vec()
459            .first()
460            .cloned()
461        {
462            Some(lua_bin.clone())
463        } else {
464            // Fall back to Lua binary without version suffix
465            bin_files
466                .into_iter()
467                .filter(|file| {
468                    file.is_executable()
469                        && file.file_name().is_some_and(|name| {
470                            matches!(
471                                name.to_string_lossy().to_string().as_str(),
472                                "lua" | "luajit" | "lua.exe" | "luajit.exe"
473                            )
474                        })
475                })
476                .collect_vec()
477                .first()
478                .cloned()
479        }
480    })
481}
482
483fn is_lib_name(name: &str, version: &Version) -> bool {
484    let prefixes = match version {
485        Version::LuaJIT | Version::LuaJIT52 => vec!["luajit", "lua"],
486        _ => vec!["lua"],
487    };
488    let version_str = version.version_compatibility_str();
489    let version_suffix = version_str.replace(".", "");
490    #[cfg(target_family = "unix")]
491    let name = name.trim_start_matches("lib");
492    prefixes
493        .iter()
494        .any(|prefix| name == format!("{}.{}", *prefix, target::c_lib_extension()))
495        || prefixes.iter().any(|prefix| name.starts_with(*prefix))
496            && (name.contains(&version_str) || name.contains(&version_suffix))
497}
498
499fn lib_name(lib_dir: &Path, version: &Version) -> Option<String> {
500    fs::sync::read_dir(lib_dir)
501        .ok()
502        .and_then(|entries| {
503            entries
504                .filter_map(Result::ok)
505                .map(|entry| entry.path().to_path_buf())
506                .filter(|file| {
507                    file.extension()
508                        .is_some_and(|ext| ext == target::c_lib_extension())
509                })
510                .filter(|file| {
511                    file.file_name()
512                        .is_some_and(|name| is_lib_name(&name.to_string_lossy(), version))
513                })
514                .collect_vec()
515                .first()
516                .cloned()
517        })
518        .map(|file| to_lib_name(&file))
519}
520
521#[cfg(test)]
522mod tests {
523    use super::*;
524    #[cfg(feature = "impure_tests")]
525    use flaky_test::flaky_test;
526
527    #[cfg(feature = "impure_tests")]
528    #[flaky_test(tokio, times = 5)]
529    async fn lua_installation_bin() {
530        let config = crate::config::Builder::new().unwrap().build().unwrap();
531        let lua_version = config.lua_version().unwrap();
532        let lua_installation = Installation::new(lua_version, &config).await.unwrap();
533        // FIXME: This fails when run in the nix checkPhase
534        assert!(lua_installation.bin.is_some());
535        let lua_binary: Binary = lua_installation.bin.unwrap().into();
536        let lua_bin_path: PathBuf = lua_binary.try_into().unwrap();
537        let pkg_version = detect::version_from_path(&lua_bin_path).unwrap();
538        assert_eq!(&Version::from_version(pkg_version).unwrap(), lua_version);
539    }
540
541    #[cfg(not(target_env = "msvc"))]
542    #[tokio::test]
543    async fn test_is_lib_name() {
544        assert!(is_lib_name("lua.a", &Version::Lua51));
545        assert!(is_lib_name("lua-5.1.a", &Version::Lua51));
546        assert!(is_lib_name("lua5.1.a", &Version::Lua51));
547        assert!(is_lib_name("lua51.a", &Version::Lua51));
548        assert!(!is_lib_name("lua-5.2.a", &Version::Lua51));
549        assert!(is_lib_name("luajit-5.2.a", &Version::LuaJIT52));
550        assert!(is_lib_name("lua-5.2.a", &Version::LuaJIT52));
551        assert!(is_lib_name("liblua.a", &Version::Lua51));
552        assert!(is_lib_name("liblua-5.1.a", &Version::Lua51));
553        assert!(is_lib_name("liblua53.a", &Version::Lua53));
554        assert!(is_lib_name("liblua-54.a", &Version::Lua54));
555        assert!(is_lib_name("liblua-55.a", &Version::Lua55));
556    }
557
558    #[cfg(target_env = "msvc")]
559    #[tokio::test]
560    async fn test_is_lib_name() {
561        assert!(is_lib_name("lua.lib", &Version::Lua51));
562        assert!(is_lib_name("lua-5.1.lib", &Version::Lua51));
563        assert!(!is_lib_name("lua-5.2.lib", &Version::Lua51));
564        assert!(!is_lib_name("lua53.lib", &Version::Lua53));
565        assert!(!is_lib_name("lua53.lib", &Version::Lua53));
566        assert!(is_lib_name("luajit-5.2.lib", &Version::LuaJIT52));
567        assert!(is_lib_name("lua-5.2.lib", &Version::LuaJIT52));
568    }
569}