1use std::{
2 io,
3 path::{Path, PathBuf},
4 process::Stdio,
5};
6
7use miette::Diagnostic;
8use path_slash::PathExt as _;
9use thiserror::Error;
10
11use crate::{
12 config::Config,
13 fs, lua,
14 path::{self, Paths},
15 tree::{self, InstallTree},
16};
17
18#[derive(Error, Debug, Diagnostic)]
19#[non_exhaustive]
20pub enum Error {
21 #[error(transparent)]
22 #[diagnostic(transparent)]
23 Fs(#[from] fs::Error),
24 #[error(transparent)]
25 #[diagnostic(transparent)]
26 Tree(#[from] tree::Error),
27 #[error(transparent)]
28 #[diagnostic(transparent)]
29 Paths(#[from] path::Error),
30 #[error("the Teal compiler was not found in the build tree")]
31 #[diagnostic(help("add `tl` to `build_dependencies` and rerun the build"))]
32 NoTealCompiler,
33 #[error("failed to run the Teal compiler")]
34 #[diagnostic(help("ensure Lua is installed and executable, or run `lx install-lua`"))]
35 Run { source: io::Error },
36 #[error("no Lua executable found")]
37 NoLuaBinary {
38 #[help]
39 help: String,
40 },
41 #[error("failed to compile Teal module '{}':\n{stderr}", file.display())]
42 #[diagnostic(help(
43 "fix the Teal errors above, or verify `tl` supports the target Lua version"
44 ))]
45 Compile { file: PathBuf, stderr: String },
46}
47
48pub(crate) async fn compile<T: InstallTree>(
49 build_dir: &Path,
50 target_dir: &Path,
51 files: &[PathBuf],
52 lua: &lua::Installation,
53 tree: &T,
54 config: &Config,
55) -> Result<(), Error> {
56 let build_dir = fs::sync::absolute(build_dir)?;
57 let target_dir = fs::sync::absolute(target_dir)?;
58 let build_tree = tree.build_tree(config)?;
59 let script = teal_script(&build_tree).ok_or(Error::NoTealCompiler)?;
60 let build_paths = Paths::new(&build_tree)?;
61 let target_paths = Paths::new(tree)?;
62 let lua_path = lua_path(&build_dir, &build_paths, &target_paths);
63 let lua_cpath = [
64 build_paths.package_cpath().joined(),
65 target_paths.package_cpath().joined(),
66 ]
67 .into_iter()
68 .filter(|path| !path.is_empty())
69 .collect::<Vec<_>>()
70 .join(";");
71 let lua_bin = lua
72 .lua_binary_or_config_override(config)
73 .ok_or_else(|| Error::NoLuaBinary {
74 help: format!(
75 "make sure Lua {} is on the PATH or has been installed by Lux",
76 lua.version
77 ),
78 })?;
79 let version_suffix = lua.version.version_compatibility_str().replace('.', "_");
80 let (gen_target, gen_compat) = gen_options(&lua.version);
81 let compiler = Compiler {
82 script: &script,
83 working_dir: &build_dir,
84 lua_bin: &lua_bin,
85 config,
86 lua_path: &lua_path,
87 lua_cpath: &lua_cpath,
88 version_suffix: &version_suffix,
89 gen_target,
90 gen_compat,
91 };
92 for file in files.iter().filter(|file| !is_declaration(file)) {
93 let target = target_dir
94 .join(file.components().skip(1).collect::<PathBuf>())
95 .with_extension("lua");
96 compiler.compile(&build_dir.join(file), &target).await?;
97 }
98 Ok(())
99}
100
101struct Compiler<'a> {
102 script: &'a Path,
103 working_dir: &'a Path,
104 lua_bin: &'a str,
105 config: &'a Config,
106 lua_path: &'a str,
107 lua_cpath: &'a str,
108 version_suffix: &'a str,
109 gen_target: &'a str,
110 gen_compat: &'a str,
111}
112
113impl Compiler<'_> {
114 async fn compile(&self, source: &Path, target: &Path) -> Result<(), Error> {
115 if let Some(parent) = target.parent() {
116 fs::tokio::create_dir_all(parent).await?;
117 }
118 let args = vec![
119 self.script.as_os_str().to_owned(),
120 "-q".into(),
121 "--gen-target".into(),
122 self.gen_target.into(),
123 "--gen-compat".into(),
124 self.gen_compat.into(),
125 "gen".into(),
126 "--output".into(),
127 target.as_os_str().to_owned(),
128 source.as_os_str().to_owned(),
129 ];
130 let output = self
131 .config
132 .wrapped_command(self.lua_bin, args)
133 .current_dir(self.working_dir)
134 .env_remove("TL_PATH")
135 .env("LUA_PATH", self.lua_path)
136 .env(format!("LUA_PATH_{}", self.version_suffix), self.lua_path)
137 .env("LUA_CPATH", self.lua_cpath)
138 .env(format!("LUA_CPATH_{}", self.version_suffix), self.lua_cpath)
139 .stdin(Stdio::null())
140 .output()
141 .await
142 .map_err(|source| Error::Run { source })?;
143 if !output.status.success() {
144 return Err(Error::Compile {
145 file: source.to_path_buf(),
146 stderr: String::from_utf8_lossy(&output.stderr).trim().to_string(),
147 });
148 }
149 fs::make_writable(target).await?;
150 Ok(())
151 }
152}
153
154fn teal_script(build_tree: &tree::Tree) -> Option<PathBuf> {
155 [
156 build_tree.unwrapped_bin().join("tl"),
157 build_tree.bin().join("tl"),
158 ]
159 .into_iter()
160 .find(|path| path.is_file())
161}
162
163fn gen_options(target_version: &lua::Version) -> (&'static str, &'static str) {
164 match target_version {
165 lua::Version::Lua53 => ("5.3", "optional"),
166 lua::Version::Lua54 => ("5.4", "off"),
167 lua::Version::Lua55 => ("5.5", "off"),
168 _ => ("5.1", "optional"),
169 }
170}
171
172fn lua_path(build_dir: &Path, build_paths: &Paths, target_paths: &Paths) -> String {
173 let mut entries = vec![
174 build_paths.package_path().joined(),
175 target_paths.package_path().joined(),
176 ];
177 for root in ["src", "lua", "lib"] {
178 entries.push(
179 build_dir
180 .join(root)
181 .join("?.lua")
182 .to_slash_lossy()
183 .into_owned(),
184 );
185 entries.push(
186 build_dir
187 .join(root)
188 .join("?")
189 .join("init.lua")
190 .to_slash_lossy()
191 .into_owned(),
192 );
193 }
194 entries.retain(|entry| !entry.is_empty());
195 entries.join(";")
196}
197
198fn is_declaration(file: &Path) -> bool {
199 file.extension().is_some_and(|ext| ext == "tl")
200 && file
201 .file_stem()
202 .is_some_and(|stem| Path::new(stem).extension().is_some_and(|ext| ext == "d"))
203}
204
205#[cfg(test)]
206mod tests {
207 use super::*;
208
209 #[test]
210 fn detects_teal_declarations() {
211 assert!(is_declaration(Path::new("src/foo.d.tl")));
212 assert!(is_declaration(Path::new("src/foo/bar.d.tl")));
213 assert!(!is_declaration(Path::new("src/foo.tl")));
214 assert!(!is_declaration(Path::new("src/foo.d.lua")));
215 }
216}