Skip to main content

lux_lib/build/
builtin.rs

1use itertools::Itertools;
2use miette::Diagnostic;
3use std::{
4    collections::{HashMap, HashSet},
5    path::{Path, PathBuf},
6    str::FromStr,
7};
8use thiserror::Error;
9use walkdir::WalkDir;
10
11use crate::{
12    build::{
13        backend::{BuildBackend, BuildInfo, RunBuildArgs},
14        compile::{c_files, c_modules},
15    },
16    fs, rockspec,
17    tree::{self, InstallTree},
18};
19
20#[cfg(not(feature = "luau-transpile"))]
21use crate::lua;
22
23use super::{compile, install};
24
25#[derive(Error, Debug, Diagnostic)]
26#[non_exhaustive]
27pub enum Error {
28    #[error(transparent)]
29    #[diagnostic(transparent)]
30    CompileCFiles(#[from] compile::c_files::Error),
31    #[error(transparent)]
32    #[diagnostic(transparent)]
33    CompileCModules(#[from] compile::c_modules::Error),
34    #[error("failed to install binary '{file_name}'")]
35    InstallBinary {
36        file_name: String,
37        #[diagnostic_source]
38        source: install::Error,
39    },
40    #[error(transparent)]
41    #[diagnostic(transparent)]
42    Fs(#[from] fs::Error),
43    #[error(transparent)]
44    #[diagnostic(transparent)]
45    Tree(#[from] tree::Error),
46    #[error("module auto-detection failed")]
47    #[diagnostic(transparent)]
48    AutoDetectModules(#[from] AutoDetectModulesError),
49    #[error("luau does not support native dependencies")]
50    #[diagnostic(help(
51        "the luau runtime cannot load native libraries. use pure-Luau packages or Lua"
52    ))]
53    LuauNativeDepsUnsupported,
54    #[cfg(feature = "luau-transpile")]
55    #[error(transparent)]
56    #[diagnostic(transparent)]
57    LuauTranspile(#[from] super::luau::Error),
58    #[cfg(not(feature = "luau-transpile"))]
59    #[error("cannot install Luau module `{module}` on {lua_version}")]
60    #[diagnostic(help(
61        "this build of Lux was compiled without support for transpiling Luau to Lua"
62    ))]
63    LuauTranspileDisabled {
64        module: String,
65        lua_version: lua::Version,
66    },
67}
68
69impl BuildBackend for rockspec::build::backend::Builtin {
70    type Err = Error;
71
72    #[tracing::instrument(name = "builtin::run", skip_all, level = "debug")]
73    async fn run<T>(self, args: RunBuildArgs<'_, T>) -> Result<BuildInfo, Self::Err>
74    where
75        T: InstallTree + Sync,
76    {
77        let package = args.package;
78        let lua = args.lua;
79        let external_dependencies = args.external_dependencies;
80        let config = args.config;
81        let tree = args.tree;
82        let layout = tree.layout_for(package);
83        let build_dir = args.build_dir;
84
85        // Detect all Lua modules
86        let modules = autodetect_modules(build_dir, source_paths(build_dir, &self.modules))?
87            .into_iter()
88            .chain(self.modules)
89            .collect::<HashMap<_, _>>();
90
91        if lua.version.is_luau() {
92            let has_native_modules = modules.values().any(|spec| match spec {
93                rockspec::build::backend::ModuleSpec::SourcePath(source) => {
94                    source.extension().is_some_and(|ext| ext == "c")
95                }
96                rockspec::build::backend::ModuleSpec::SourcePaths(_)
97                | rockspec::build::backend::ModuleSpec::ModulePaths(_) => true,
98            });
99            if has_native_modules {
100                return Err(Error::LuauNativeDepsUnsupported);
101            }
102        }
103
104        for (destination_path, module_type) in modules.iter() {
105            match module_type {
106                rockspec::build::backend::ModuleSpec::SourcePath(source) => {
107                    if source.extension().map(|ext| ext == "c").unwrap_or(false) {
108                        let absolute_source_paths = vec![build_dir.join(source)];
109                        c_files::compile(
110                            &absolute_source_paths,
111                            destination_path,
112                            &layout.lib,
113                            lua,
114                            external_dependencies,
115                            config,
116                        )
117                        .await?;
118                    } else if source.extension().is_some_and(|ext| ext == "luau")
119                        && !lua.version.is_luau()
120                    {
121                        #[cfg(feature = "luau-transpile")]
122                        {
123                            let absolute_source_path = build_dir.join(source);
124                            super::luau::transpile_luau_to_lua_module(
125                                &absolute_source_path,
126                                destination_path,
127                                &layout.src,
128                            )
129                            .await?;
130                        }
131                        #[cfg(not(feature = "luau-transpile"))]
132                        return Err(Error::LuauTranspileDisabled {
133                            module: destination_path.to_string(),
134                            lua_version: lua.version.clone(),
135                        });
136                    } else {
137                        let absolute_source_path = build_dir.join(source);
138                        install::lua_module(&absolute_source_path, destination_path, &layout.src)?;
139                    }
140                }
141                rockspec::build::backend::ModuleSpec::SourcePaths(files) => {
142                    let absolute_source_paths =
143                        files.iter().map(|file| build_dir.join(file)).collect();
144                    c_files::compile(
145                        &absolute_source_paths,
146                        destination_path,
147                        &layout.lib,
148                        lua,
149                        external_dependencies,
150                        config,
151                    )
152                    .await?
153                }
154                rockspec::build::backend::ModuleSpec::ModulePaths(data) => {
155                    c_modules::compile(
156                        data,
157                        build_dir,
158                        destination_path,
159                        &layout.lib,
160                        lua,
161                        external_dependencies,
162                        config,
163                    )
164                    .await?
165                }
166            }
167        }
168
169        let mut binaries = Vec::new();
170        for bin_script in install::detect_binaries(build_dir) {
171            if let Some(target) = bin_script.file_name() {
172                let file_name = target.to_string_lossy().to_string();
173                let installed_bin_script =
174                    install::binary(&bin_script, &file_name, tree, lua, args.deploy, config)
175                        .await
176                        .map_err(|err| Error::InstallBinary {
177                            file_name: file_name.clone(),
178                            source: err,
179                        })?;
180                if let Some(bin_script_file_name) = installed_bin_script.file_name() {
181                    binaries.push(bin_script_file_name.into());
182                }
183            }
184        }
185
186        Ok(BuildInfo { binaries })
187    }
188}
189
190fn source_paths(
191    build_dir: &Path,
192    modules: &HashMap<rockspec::build::backend::Module, rockspec::build::backend::ModuleSpec>,
193) -> HashSet<PathBuf> {
194    modules
195        .values()
196        .flat_map(|spec| match spec {
197            rockspec::build::backend::ModuleSpec::SourcePath(path_buf) => vec![path_buf],
198            rockspec::build::backend::ModuleSpec::SourcePaths(vec) => vec.iter().collect_vec(),
199            rockspec::build::backend::ModuleSpec::ModulePaths(module_paths) => {
200                module_paths.sources.iter().collect_vec()
201            }
202        })
203        .map(|path| build_dir.join(path))
204        .collect()
205}
206
207#[derive(Error, Debug, Diagnostic)]
208#[non_exhaustive]
209pub enum AutoDetectModulesError {
210    #[error(transparent)]
211    #[diagnostic(transparent)]
212    ParseLuaModule(#[from] rockspec::build::backend::ParseLuaModuleError),
213}
214
215#[tracing::instrument(level = "trace")]
216pub(crate) fn autodetect_modules(
217    build_dir: &Path,
218    exclude: HashSet<PathBuf>,
219) -> Result<
220    HashMap<rockspec::build::backend::Module, rockspec::build::backend::ModuleSpec>,
221    AutoDetectModulesError,
222> {
223    WalkDir::new(build_dir.join("src"))
224        .into_iter()
225        .chain(WalkDir::new(build_dir.join("lua")))
226        .chain(WalkDir::new(build_dir.join("lib")))
227        .filter_map(|file| {
228            file.ok().and_then(|file| {
229                let is_lua_file = PathBuf::from(file.file_name())
230                    .extension()
231                    .is_some_and(|ext| ext == "lua" || ext == "luau");
232                if is_lua_file && !exclude.contains(&file.clone().into_path()) {
233                    Some(file)
234                } else {
235                    None
236                }
237            })
238        })
239        .map(|file| {
240            let diff: PathBuf = unsafe {
241                pathdiff::diff_paths(build_dir.join(file.clone().into_path()), build_dir)
242                    .unwrap_unchecked()
243            };
244
245            // NOTE(vhyrro): You may ask why we convert all paths to Lua module paths
246            // just to convert them back later in the `run()` stage.
247            //
248            // The rockspec requires the format to be like this, and representing our
249            // data in this form allows us to respect any overrides made by the user (which follow
250            // the `module.name` format, not our internal one).
251            let mut pathbuf = diff.components().skip(1).collect::<PathBuf>();
252            let lua_module = if pathbuf
253                .parent()
254                .is_none_or(|parent| parent.as_os_str().is_empty())
255            {
256                pathbuf.set_extension("");
257                Ok(rockspec::build::backend::Module::from_pathbuf(pathbuf)?)
258            } else {
259                let mut lua_module = rockspec::build::backend::Module::from_pathbuf(pathbuf)?;
260                // NOTE(mrcjkb): `build::backend::Module` does not parse as "<module>.init" from files named "init.lua"
261                // To make sure we don't change the file structure when installing, we append it here.
262                if matches!(
263                    file.file_name().to_string_lossy().as_bytes(),
264                    b"init.lua" | b"init.luau"
265                ) {
266                    unsafe {
267                        lua_module = lua_module.join(
268                            &rockspec::build::backend::Module::from_str("init").unwrap_unchecked(),
269                        )
270                    }
271                }
272                Ok(lua_module)
273            };
274            lua_module.map(|lua_module| {
275                (
276                    lua_module,
277                    rockspec::build::backend::ModuleSpec::SourcePath(diff),
278                )
279            })
280        })
281        .try_collect()
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287
288    fn write_file(path: &Path) {
289        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
290        std::fs::write(path, b"return {}").unwrap();
291    }
292
293    #[tokio::test]
294    async fn test_auto_detect_modules() {
295        let build_dir = tempfile::tempdir().unwrap();
296        let root = build_dir.path();
297        write_file(&root.join("src").join("foo.luau"));
298        write_file(&root.join("src").join("bar").join("baz.luau"));
299        write_file(&root.join("src").join("baz").join("init.luau"));
300        write_file(&root.join("lua").join("legacy.lua"));
301
302        let modules = autodetect_modules(root, Default::default()).unwrap();
303
304        let names = modules.keys().map(|m| m.to_string()).collect_vec();
305        assert!(names.contains(&"foo".to_string()), "{names:?}");
306        assert!(names.contains(&"bar.baz".to_string()), "{names:?}");
307        assert!(names.contains(&"baz.init".to_string()), "{names:?}");
308        assert!(names.contains(&"legacy".to_string()), "{names:?}");
309
310        let foo_spec = &modules[&"foo".parse().unwrap()];
311        match foo_spec {
312            rockspec::build::backend::ModuleSpec::SourcePath(path) => {
313                assert_eq!(path.extension().unwrap(), "luau");
314            }
315            _ => panic!("expected SourcePath for foo.luau"),
316        }
317    }
318}