1use itertools::{Either, 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 #[error(transparent)]
68 #[diagnostic(transparent)]
69 Teal(#[from] compile::teal::Error),
70}
71
72impl BuildBackend for rockspec::build::backend::Builtin {
73 type Err = Error;
74
75 #[tracing::instrument(name = "builtin::run", skip_all, level = "debug")]
76 async fn run<T>(self, args: RunBuildArgs<'_, T>) -> Result<BuildInfo, Self::Err>
77 where
78 T: InstallTree + Sync,
79 {
80 let package = args.package;
81 let lua = args.lua;
82 let external_dependencies = args.external_dependencies;
83 let config = args.config;
84 let tree = args.tree;
85 let layout = tree.layout_for(package);
86 let build_dir = args.build_dir;
87 let build_dependencies = args.build_dependencies;
88 let dependency_layouts = args.dependency_layouts;
89
90 let (detected_modules, teal_files) =
91 autodetect_modules(build_dir, source_paths(build_dir, &self.modules))?;
92 let modules = detected_modules
93 .into_iter()
94 .chain(self.modules)
95 .collect::<HashMap<_, _>>();
96
97 if lua.version.is_luau() {
98 let has_native_modules = modules.values().any(|spec| match spec {
99 rockspec::build::backend::ModuleSpec::SourcePath(source) => {
100 source.extension().is_some_and(|ext| ext == "c")
101 }
102 rockspec::build::backend::ModuleSpec::SourcePaths(_)
103 | rockspec::build::backend::ModuleSpec::ModulePaths(_) => true,
104 });
105 if has_native_modules {
106 return Err(Error::LuauNativeDepsUnsupported);
107 }
108 }
109
110 for (destination_path, module_type) in modules.iter() {
111 match module_type {
112 rockspec::build::backend::ModuleSpec::SourcePath(source) => {
113 if source.extension().map(|ext| ext == "c").unwrap_or(false) {
114 let absolute_source_paths = vec![build_dir.join(source)];
115 c_files::Compiler::new()
116 .files(&absolute_source_paths)
117 .target_module(destination_path)
118 .target_dir(&layout.lib)
119 .lua(lua)
120 .external_dependencies(external_dependencies)
121 .config(config)
122 .compile()
123 .await?;
124 } else if source.extension().is_some_and(|ext| ext == "luau")
125 && !lua.version.is_luau()
126 {
127 #[cfg(feature = "luau-transpile")]
128 {
129 let absolute_source_path = build_dir.join(source);
130 super::luau::transpile_luau_to_lua_module(
131 &absolute_source_path,
132 destination_path,
133 &layout.src,
134 )
135 .await?;
136 }
137 #[cfg(not(feature = "luau-transpile"))]
138 return Err(Error::LuauTranspileDisabled {
139 module: destination_path.to_string(),
140 lua_version: lua.version.clone(),
141 });
142 } else {
143 let absolute_source_path = build_dir.join(source);
144 install::lua_module(&absolute_source_path, destination_path, &layout.src)?;
145 }
146 }
147 rockspec::build::backend::ModuleSpec::SourcePaths(files) => {
148 let absolute_source_paths: Vec<PathBuf> =
149 files.iter().map(|file| build_dir.join(file)).collect();
150 c_files::Compiler::new()
151 .files(&absolute_source_paths)
152 .target_module(destination_path)
153 .target_dir(&layout.lib)
154 .lua(lua)
155 .external_dependencies(external_dependencies)
156 .config(config)
157 .compile()
158 .await?
159 }
160 rockspec::build::backend::ModuleSpec::ModulePaths(data) => {
161 c_modules::Compiler::new()
162 .data(data)
163 .source_dir(build_dir)
164 .target_module(destination_path)
165 .target_dir(&layout.lib)
166 .lua(lua)
167 .external_dependencies(external_dependencies)
168 .dependency_layouts(dependency_layouts)
169 .config(config)
170 .compile()
171 .await?
172 }
173 }
174 }
175
176 if !teal_files.is_empty() {
177 install::sources(build_dir, &layout.src, &teal_files)?;
178 if build_dependencies
179 .iter()
180 .any(|dep| dep.name().to_string() == "tl")
181 {
182 compile::teal::compile(build_dir, &layout.src, &teal_files, lua, tree, config)
183 .await?;
184 }
185 }
186
187 let mut binaries = Vec::new();
188 for bin_script in install::detect_binaries(build_dir) {
189 if let Some(target) = bin_script.file_name() {
190 let file_name = target.to_string_lossy().to_string();
191 let installed_bin_script =
192 install::binary(&bin_script, &file_name, tree, lua, args.deploy, config)
193 .await
194 .map_err(|err| Error::InstallBinary {
195 file_name: file_name.clone(),
196 source: err,
197 })?;
198 if let Some(bin_script_file_name) = installed_bin_script.file_name() {
199 binaries.push(bin_script_file_name.into());
200 }
201 }
202 }
203
204 Ok(BuildInfo { binaries })
205 }
206}
207
208fn source_paths(
209 build_dir: &Path,
210 modules: &HashMap<rockspec::build::backend::Module, rockspec::build::backend::ModuleSpec>,
211) -> HashSet<PathBuf> {
212 modules
213 .values()
214 .flat_map(|spec| match spec {
215 rockspec::build::backend::ModuleSpec::SourcePath(path_buf) => vec![path_buf],
216 rockspec::build::backend::ModuleSpec::SourcePaths(vec) => vec.iter().collect_vec(),
217 rockspec::build::backend::ModuleSpec::ModulePaths(module_paths) => {
218 module_paths.sources.iter().collect_vec()
219 }
220 })
221 .map(|path| build_dir.join(path))
222 .collect()
223}
224
225#[derive(Error, Debug, Diagnostic)]
226#[non_exhaustive]
227pub enum AutoDetectModulesError {
228 #[error(transparent)]
229 #[diagnostic(transparent)]
230 ParseLuaModule(#[from] rockspec::build::backend::ParseLuaModuleError),
231}
232
233#[tracing::instrument(level = "trace")]
234pub(crate) fn autodetect_modules(
235 build_dir: &Path,
236 exclude: HashSet<PathBuf>,
237) -> Result<
238 (
239 HashMap<rockspec::build::backend::Module, rockspec::build::backend::ModuleSpec>,
240 Vec<PathBuf>,
241 ),
242 AutoDetectModulesError,
243> {
244 let (modules, teal_files): (Vec<_>, Vec<_>) = WalkDir::new(build_dir.join("src"))
245 .into_iter()
246 .chain(WalkDir::new(build_dir.join("lua")))
247 .chain(WalkDir::new(build_dir.join("lib")))
248 .filter_map(|file| {
249 file.ok().and_then(|file| {
250 let is_source = PathBuf::from(file.file_name())
251 .extension()
252 .is_some_and(|ext| matches!(ext.to_str(), Some("lua" | "luau" | "tl")));
253 if is_source
254 && file.file_type().is_file()
255 && !exclude.contains(&file.clone().into_path())
256 {
257 Some(file)
258 } else {
259 None
260 }
261 })
262 })
263 .map(|file| {
264 let diff: PathBuf = unsafe {
265 pathdiff::diff_paths(build_dir.join(file.clone().into_path()), build_dir)
266 .unwrap_unchecked()
267 };
268 if diff.extension().is_some_and(|ext| ext == "tl") {
269 return Ok::<_, AutoDetectModulesError>(Either::Right(diff));
270 }
271
272 let mut pathbuf = diff.components().skip(1).collect::<PathBuf>();
279 let lua_module = if pathbuf
280 .parent()
281 .is_none_or(|parent| parent.as_os_str().is_empty())
282 {
283 pathbuf.set_extension("");
284 rockspec::build::backend::Module::from_pathbuf(pathbuf)?
285 } else {
286 let mut lua_module = rockspec::build::backend::Module::from_pathbuf(pathbuf)?;
287 if matches!(
290 file.file_name().to_string_lossy().as_bytes(),
291 b"init.lua" | b"init.luau"
292 ) {
293 unsafe {
294 lua_module = lua_module.join(
295 &rockspec::build::backend::Module::from_str("init").unwrap_unchecked(),
296 );
297 }
298 }
299 lua_module
300 };
301 Ok::<_, AutoDetectModulesError>(Either::Left((
302 lua_module,
303 rockspec::build::backend::ModuleSpec::SourcePath(diff),
304 )))
305 })
306 .try_collect::<_, Vec<_>, _>()?
307 .into_iter()
308 .partition_map(|detected| detected);
309 Ok((modules.into_iter().collect(), teal_files))
310}
311
312#[cfg(test)]
313mod tests {
314 use super::*;
315
316 fn write_file(path: &Path) {
317 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
318 std::fs::write(path, b"return {}").unwrap();
319 }
320
321 #[tokio::test]
322 async fn test_auto_detect_modules() {
323 let build_dir = tempfile::tempdir().unwrap();
324 let root = build_dir.path();
325 write_file(&root.join("src").join("foo.luau"));
326 write_file(&root.join("src").join("bar").join("baz.luau"));
327 write_file(&root.join("src").join("baz").join("init.luau"));
328 write_file(&root.join("lua").join("legacy.lua"));
329 write_file(&root.join("src").join("teal").join("mod.tl"));
330 write_file(&root.join("src").join("teal.d.tl"));
331
332 let (modules, teal_files) = autodetect_modules(root, Default::default()).unwrap();
333
334 let names = modules.keys().map(|m| m.to_string()).collect_vec();
335 assert!(names.contains(&"foo".to_string()), "{names:?}");
336 assert!(names.contains(&"bar.baz".to_string()), "{names:?}");
337 assert!(names.contains(&"baz.init".to_string()), "{names:?}");
338 assert!(names.contains(&"legacy".to_string()), "{names:?}");
339
340 let foo_spec = &modules[&"foo".parse().unwrap()];
341 match foo_spec {
342 rockspec::build::backend::ModuleSpec::SourcePath(path) => {
343 assert_eq!(path.extension().unwrap(), "luau");
344 }
345 _ => panic!("expected SourcePath for foo.luau"),
346 }
347
348 let mut teal_files = teal_files
349 .iter()
350 .map(|path| path.to_string_lossy().into_owned())
351 .collect_vec();
352 teal_files.sort();
353 assert_eq!(teal_files, vec!["src/teal.d.tl", "src/teal/mod.tl"]);
354 }
355}