1use std::{
2 env,
3 io::{self, Cursor},
4 path::Path,
5 process::{ExitStatus, Stdio},
6};
7
8use crate::{
9 build::{command, compile::CCExt},
10 config::Config,
11 fs,
12 hash::HasIntegrity,
13 lua,
14 operations::unpack,
15};
16use bon::Builder;
17use bytes::Bytes;
18use git2::{build::RepoBuilder, FetchOptions};
19use miette::Diagnostic;
20use path_slash::PathExt;
21use ssri::Integrity;
22use target_lexicon::Triple;
23use thiserror::Error;
24use tokio::process::Command;
25use tracing::{info_span, span, Instrument};
26use url::Url;
27
28const LUA51_VERSION: &str = "5.1.5";
29const LUA51_HASH: &str = "sha256-JkD8VqeV8p0o7xXhPDSkfiI5YLAkDoywqC2bBzhpUzM=";
30const LUA52_VERSION: &str = "5.2.4";
31const LUA52_HASH: &str = "sha256-ueLkqtZ4mztjoFbUQveznw7Pyjrg8fwK5OlhRAG2n0s=";
32const LUA53_VERSION: &str = "5.3.6";
33const LUA53_HASH: &str = "sha256-/F/Wm7hzYyPwJmcrG3I12mE9cXfnJViJOgvc0yBGbWA=";
34const LUA54_VERSION: &str = "5.4.9";
35const LUA54_HASH: &str = "sha256-IzW2xYKlJlT5RhK/ENL0ZygF0FMpqmVosdjNnlxvuOY=";
36const LUA55_VERSION: &str = "5.5.1";
37const LUA55_HASH: &str = "sha256-HEtAaNZwYfKiIxrStUIud6zqFIfqmJD2Mgr2FPQ3Pc4=";
38const LUAJIT_MM_VERSION: &str = "2.1";
41const LUAU_VERSION: &str = "0.747";
42
43#[derive(Builder)]
44#[builder(start_fn = new, finish_fn(name = _build, vis = ""))]
45pub struct BuildLua<'a> {
46 lua_version: &'a lua::Version,
47 install_dir: &'a Path,
48 config: &'a Config,
49}
50
51#[derive(Debug, Error, Diagnostic)]
52pub enum Error {
53 #[error(transparent)]
54 Request(#[from] crate::reqwest::Error),
55 #[error(transparent)]
56 Io(#[from] io::Error),
57 #[error(transparent)]
58 #[diagnostic(transparent)]
59 Fs(#[from] fs::Error),
60 #[error(transparent)]
61 #[diagnostic(transparent)]
62 Unpack(#[from] unpack::Error),
63 #[error(transparent)]
64 Git(#[from] git2::Error),
65 #[error(transparent)]
66 CC(#[from] cc::Error),
67 #[error("no Lua source mirrors are configured")]
68 #[diagnostic(help("add at least one URL to `lua_mirrors` in your Lux config."))]
69 NoLuaMirrors,
70 #[error("could not download the Lua sources from any configured mirror")]
71 #[diagnostic(help(
72 "check your network connection, or configure additional `lua_mirrors` in your Lux config."
73 ))]
74 SourceMirrors {
75 #[source]
76 source: crate::reqwest::Error,
77 #[related]
78 related: Vec<crate::reqwest::Error>,
79 },
80 #[error("failed to construct a Lua source URL: {0}")]
81 #[diagnostic(help("check the `lua_mirrors` URLs in your Lux config."))]
82 Url(#[from] url::ParseError),
83 #[error("failed to find cl.exe")]
84 ClNotFound,
85 #[error("expected `{name}` in the Luau build output")]
86 #[diagnostic(help("this usually indicates a broken or incomplete Luau source build"))]
87 LuauBinaryNotFound { name: String },
88 #[error("failed to run `{cmd}`")]
89 CmakeSpawn { cmd: String, source: io::Error },
90 #[error("failed to find LINK.exe")]
91 LinkNotFound,
92 #[error(
93 r#"source integrity mismatch.
94- source: {src}
95- expected: {expected}
96- got: {actual}"#
97 )]
98 #[diagnostic(help(
99 r#"the source may have been modified or a tag may have been moved.
100check the source, then rerun the command with `--no-lock` to update the hash."#
101 ))]
102 SourceIntegrityMismatch {
103 src: String,
104 expected: Integrity,
105 actual: Integrity,
106 },
107 #[error("{name} failed.\n\n{status}\n\nstdout:\n{stdout}\n\nstderr:\n{stderr}")]
108 CommandFailure {
109 name: String,
110 status: ExitStatus,
111 stdout: String,
112 stderr: String,
113 },
114}
115
116impl<State: build_lua_builder::State + build_lua_builder::IsComplete> BuildLuaBuilder<'_, State> {
117 pub async fn build(self) -> Result<(), Error> {
118 let args = self._build();
119 let lua_version = args.lua_version;
120 match lua_version {
121 lua::Version::Lua51
122 | lua::Version::Lua52
123 | lua::Version::Lua53
124 | lua::Version::Lua54
125 | lua::Version::Lua55 => do_build_lua(args).await,
126 lua::Version::LuaJIT | lua::Version::LuaJIT52 => do_build_luajit(args).await,
127 lua::Version::Luau => do_build_luau(args).await,
128 }
129 }
130}
131
132#[tracing::instrument(
133 name = "Building LuaJIT",
134 level = "info",
135 skip_all,
136 fields(version = LUAJIT_MM_VERSION),
137)]
138async fn do_build_luajit(args: BuildLua<'_>) -> Result<(), Error> {
139 let build_dir = fs::tempfile::tempdir()?;
140 let luajit_url = "https://github.com/LuaJIT/LuaJIT.git";
143
144 {
145 let span = span!(
146 tracing::Level::INFO,
147 "Cloning LuaJIT sources",
148 url = luajit_url,
149 );
150 let _enter = span.enter(); let mut fetch_options = FetchOptions::new();
154 fetch_options.update_fetchhead(false);
155 let mut repo_builder = RepoBuilder::new();
156 repo_builder.fetch_options(fetch_options);
157 let repo = repo_builder.clone(luajit_url, build_dir.path())?;
158 let (object, _) = repo.revparse_ext(&format!("v{LUAJIT_MM_VERSION}"))?;
159 repo.checkout_tree(&object, None)?;
160 }
161 if cfg!(target_env = "msvc") {
162 do_build_luajit_msvc(args, build_dir.path()).await
163 } else {
164 do_build_luajit_unix(args, build_dir.path()).await
165 }
166}
167
168#[tracing::instrument(name = "Compiling LuaJIT", skip_all)]
169async fn do_build_luajit_unix(args: BuildLua<'_>, build_dir: &Path) -> Result<(), Error> {
170 let lua_version = args.lua_version;
171 let config = args.config;
172 let install_dir = args.install_dir;
173
174 let host = Triple::host();
175
176 let mut cc = cc::Build::new();
177 cc.cargo_output(false)
178 .cargo_metadata(false)
179 .cargo_warnings(false)
180 .warnings(config.verbose())
181 .opt_level(3)
182 .host(&host.to_string())
183 .target(&host.to_string());
184 let compiler = cc.try_get_compiler()?;
185 let compiler_path = compiler.path().to_slash_lossy().to_string();
186 let mut make_cmd = Command::new(config.make_cmd());
187 make_cmd.current_dir(build_dir.join("src"));
188 make_cmd.arg("-e");
189 make_cmd.stdout(Stdio::piped());
190 make_cmd.stderr(Stdio::piped());
191 let target = host.to_string();
192 match target.as_str() {
193 "x86_64-apple-darwin" if env::var_os("MACOSX_DEPLOYMENT_TARGET").is_none() => {
194 make_cmd.env("MACOSX_DEPLOYMENT_TARGET", "10.11");
195 }
196 "aarch64-apple-darwin" if env::var_os("MACOSX_DEPLOYMENT_TARGET").is_none() => {
197 make_cmd.env("MACOSX_DEPLOYMENT_TARGET", "11.0");
198 }
199 _ if target.contains("linux") => {
200 make_cmd.env("TARGET_SYS", "Linux");
201 }
202 _ => {}
203 }
204 let compiler_path = which::which(&compiler_path)
205 .map_err(|err| io::Error::other(format!("cannot find {}:\n{}", compiler_path, err)))?;
206 let compiler_path = compiler_path.to_slash_lossy().to_string();
207 let compiler_args = compiler.cflags_env();
208 let compiler_args = compiler_args.to_string_lossy();
209 if env::var_os("STATIC_CC").is_none() {
210 make_cmd.env("STATIC_CC", format!("{compiler_path} {compiler_args}"));
211 }
212 if env::var_os("TARGET_LD").is_none() {
213 make_cmd.env("TARGET_LD", format!("{compiler_path} {compiler_args}"));
214 }
215 let mut xcflags = vec!["-fPIC"];
216 if lua_version == &lua::Version::LuaJIT52 {
217 xcflags.push("-DLUAJIT_ENABLE_LUA52COMPAT");
218 }
219 if cfg!(debug_assertions) {
220 xcflags.push("-DLUA_USE_ASSERT");
221 xcflags.push("-DLUA_USE_APICHECK");
222 }
223 make_cmd.env("BUILDMODE", "static");
224 make_cmd.env("XCFLAGS", xcflags.join(" "));
225
226 match make_cmd.output().await {
227 Ok(output) if output.status.success() => command::trace_output(&output),
228 Ok(output) => {
229 return Err(Error::CommandFailure {
230 name: "build".into(),
231 status: output.status,
232 stdout: String::from_utf8_lossy(&output.stdout).into(),
233 stderr: String::from_utf8_lossy(&output.stderr).into(),
234 });
235 }
236 Err(err) => {
237 return Err(Error::Io(io::Error::other(format!(
238 "Failed to run `{} build`:\n{}",
239 config.make_cmd(),
240 err
241 ))));
242 }
243 };
244
245 match Command::new(config.make_cmd())
246 .current_dir(build_dir)
247 .stdout(Stdio::piped())
248 .stderr(Stdio::piped())
249 .arg("install")
250 .arg(format!(r#"PREFIX="{}""#, install_dir.display()))
251 .output()
252 .await
253 {
254 Ok(output) if output.status.success() => command::trace_output(&output),
255 Ok(output) => {
256 return Err(Error::CommandFailure {
257 name: "install".into(),
258 status: output.status,
259 stdout: String::from_utf8_lossy(&output.stdout).into(),
260 stderr: String::from_utf8_lossy(&output.stderr).into(),
261 });
262 }
263 Err(err) => {
264 return Err(Error::Io(io::Error::other(format!(
265 "Failed to run `{} install`:\n{}",
266 config.make_cmd(),
267 err
268 ))));
269 }
270 };
271 move_luajit_includes(install_dir).await?;
272 Ok(())
273}
274
275async fn move_luajit_includes(install_dir: &Path) -> io::Result<()> {
278 let include_dir = install_dir.join("include");
279 let include_subdir = include_dir.join(format!("luajit-{LUAJIT_MM_VERSION}"));
280 if !include_subdir.is_dir() {
281 return Ok(());
282 }
283 let mut dir = fs::tokio::read_dir(&include_subdir)
284 .await
285 .map_err(|err| io::Error::other(err.to_string()))?;
286 while let Some(entry) = dir.next_entry().await? {
287 let file_name = entry.file_name();
288 let src_path = entry.path();
289 let dest_path = include_dir.join(&file_name);
290 fs::tokio::copy(&src_path, &dest_path)
291 .await
292 .map_err(|err| io::Error::other(err.to_string()))?;
293 }
294 fs::tokio::remove_dir_all(&include_subdir)
295 .await
296 .map_err(|err| io::Error::other(err.to_string()))?;
297 Ok(())
298}
299
300#[tracing::instrument(name = "Compiling LuaJIT", skip_all)]
304async fn do_build_luajit_msvc(args: BuildLua<'_>, build_dir: &Path) -> Result<(), Error> {
305 let lua_version = args.lua_version;
306 let install_dir = args.install_dir;
307 let lib_dir = install_dir.join("lib");
308 fs::tokio::create_dir_all(&lib_dir)
309 .await
310 .map_err(|err| io::Error::other(err.to_string()))?;
311 let include_dir = install_dir.join("include");
312 fs::tokio::create_dir_all(&include_dir)
313 .await
314 .map_err(|err| io::Error::other(err.to_string()))?;
315 let bin_dir = install_dir.join("bin");
316 fs::tokio::create_dir_all(&bin_dir)
317 .await
318 .map_err(|err| io::Error::other(err.to_string()))?;
319
320 let src_dir = build_dir.join("src");
321 let mut msvcbuild = Command::new(src_dir.join("msvcbuild.bat"));
322 msvcbuild.current_dir(&src_dir);
323 if lua_version == &lua::Version::LuaJIT52 {
324 msvcbuild.arg("lua52compat");
325 }
326 let host = Triple::host();
327 let target = host.to_string();
328 let cl = cc::windows_registry::find_tool(&target, "cl.exe").ok_or(Error::ClNotFound)?;
329 for (k, v) in cl.get_envs() {
330 msvcbuild.env(k, v);
331 }
332 fs::tokio::create_dir_all(&install_dir)
333 .await
334 .map_err(|err| io::Error::other(err.to_string()))?;
335 match msvcbuild.output().await {
336 Ok(output) if output.status.success() => command::trace_output(&output),
337 Ok(output) => {
338 return Err(Error::CommandFailure {
339 name: "build".into(),
340 status: output.status,
341 stdout: String::from_utf8_lossy(&output.stdout).into(),
342 stderr: String::from_utf8_lossy(&output.stderr).into(),
343 });
344 }
345 Err(err) => {
346 return Err(Error::Io(io::Error::other(format!(
347 "Failed to run msvcbuild.bat:\n{}",
348 err
349 ))))
350 }
351 };
352
353 copy_includes(&src_dir, &include_dir).await?;
354 fs::tokio::copy(src_dir.join("lua51.lib"), lib_dir.join("luajit.lib"))
355 .await
356 .map_err(|err| io::Error::other(err.to_string()))?;
357 fs::tokio::copy(src_dir.join("luajit.exe"), bin_dir.join("luajit.exe"))
358 .await
359 .map_err(|err| io::Error::other(err.to_string()))?;
360 fs::tokio::copy(src_dir.join("lua51.dll"), bin_dir.join("lua51.dll"))
361 .await
362 .map_err(|err| io::Error::other(err.to_string()))?;
363 fs::tokio::copy(src_dir.join("lua51.dll"), lib_dir.join("lua51.dll"))
364 .await
365 .map_err(|err| io::Error::other(err.to_string()))?;
366 Ok(())
367}
368
369async fn do_build_luau(args: BuildLua<'_>) -> Result<(), Error> {
370 let install_dir = args.install_dir;
371 let build_dir = fs::tempfile::tempdir()?;
372
373 let luau_url = "https://github.com/luau-lang/luau.git";
374 {
375 let span = info_span!("Cloning Luau sources", url = luau_url);
376 let _enter = span.enter(); let mut fetch_options = FetchOptions::new();
379 fetch_options.update_fetchhead(false);
380 let mut repo_builder = RepoBuilder::new();
381 repo_builder.fetch_options(fetch_options);
382 let repo = repo_builder.clone(luau_url, build_dir.path())?;
383 let (object, _) = repo.revparse_ext(LUAU_VERSION)?;
384 repo.checkout_tree(&object, None)?;
385 }
386
387 let cmake_build_dir = build_dir.path().join("build");
388 fs::tokio::create_dir_all(&cmake_build_dir).await?;
389
390 let src_dir_arg = build_dir.path().to_slash_lossy().to_string();
391 let build_dir_arg = cmake_build_dir.to_slash_lossy().to_string();
392 let build_type = if cfg!(debug_assertions) {
393 "Debug"
395 } else {
396 "Release"
397 };
398 run_cmake(
399 build_dir.path(),
400 &[
401 "-S".into(),
402 src_dir_arg,
403 "-B".into(),
404 build_dir_arg.clone(),
405 format!("-DCMAKE_BUILD_TYPE={build_type}"),
406 "-DLUAU_BUILD_TESTS=OFF".into(),
407 "-DLUAU_BUILD_WEB=OFF".into(),
408 ],
409 args.config,
410 )
411 .await?;
412 run_cmake(
413 build_dir.path(),
414 &[
415 "--build".into(),
416 build_dir_arg,
417 "--config".into(),
418 build_type.into(),
419 "--parallel".into(),
420 "--target".into(),
421 "Luau.Repl.CLI".into(),
422 "Luau.Analyze.CLI".into(),
423 ],
424 args.config,
425 )
426 .await?;
427
428 let bin_candidates = [cmake_build_dir.join(build_type), cmake_build_dir];
431 let bin_dir = install_dir.join("bin");
432 fs::tokio::create_dir_all(&bin_dir).await?;
433
434 #[cfg(windows)]
435 const CLI_BINARIES: [&str; 2] = ["luau.exe", "luau-analyze.exe"];
436 #[cfg(not(windows))]
437 const CLI_BINARIES: [&str; 2] = ["luau", "luau-analyze"];
438
439 for name in CLI_BINARIES {
440 let src = bin_candidates
441 .iter()
442 .map(|dir| dir.join(name))
443 .find(|path| path.is_file())
444 .ok_or(Error::LuauBinaryNotFound {
445 name: name.to_string(),
446 })?;
447 fs::tokio::copy(&src, bin_dir.join(name)).await?;
448 }
449 Ok(())
450}
451
452async fn run_cmake(cwd: &Path, args: &[String], config: &Config) -> Result<(), Error> {
453 let mut cmd = Command::new(config.cmake_cmd());
454 cmd.current_dir(cwd);
455 cmd.args(args);
456 cmd.stdout(Stdio::piped());
457 cmd.stderr(Stdio::piped());
458 match cmd.output().await {
459 Ok(output) if output.status.success() => {
460 command::trace_output(&output);
461 Ok(())
462 }
463 Ok(output) => Err(Error::CommandFailure {
464 name: config.cmake_cmd(),
465 status: output.status,
466 stdout: String::from_utf8_lossy(&output.stdout).into(),
467 stderr: String::from_utf8_lossy(&output.stderr).into(),
468 }),
469 Err(err) => Err(Error::CmakeSpawn {
470 cmd: config.cmake_cmd(),
471 source: err,
472 }),
473 }
474}
475
476#[tracing::instrument(
477 name = "Building Lua",
478 level = "info",
479 skip_all,
480 fields(version = args.lua_version.to_string()),
481)]
482async fn do_build_lua(args: BuildLua<'_>) -> Result<(), Error> {
483 let lua_version = args.lua_version;
484 let build_dir = fs::tempfile::tempdir()?;
485
486 let (source_integrity, pkg_version): (Integrity, &str) = unsafe {
487 match lua_version {
488 lua::Version::Lua51 => (LUA51_HASH.parse().unwrap_unchecked(), LUA51_VERSION),
489 lua::Version::Lua52 => (LUA52_HASH.parse().unwrap_unchecked(), LUA52_VERSION),
490 lua::Version::Lua53 => (LUA53_HASH.parse().unwrap_unchecked(), LUA53_VERSION),
491 lua::Version::Lua54 => (LUA54_HASH.parse().unwrap_unchecked(), LUA54_VERSION),
492 lua::Version::Lua55 => (LUA55_HASH.parse().unwrap_unchecked(), LUA55_VERSION),
493 lua::Version::LuaJIT | lua::Version::LuaJIT52 | lua::Version::Luau => unreachable!(),
494 }
495 };
496
497 let file_name = format!("lua-{pkg_version}.tar.gz");
498 let (source_url, response) = download_source(&file_name, args.config).await?;
499
500 let hash = response.hash().await?;
501
502 if hash.matches(&source_integrity).is_none() {
503 return Err(Error::SourceIntegrityMismatch {
504 src: source_url.to_string(),
505 expected: source_integrity,
506 actual: hash,
507 });
508 }
509
510 let cursor = Cursor::new(response);
511 let mime_type = infer::get(cursor.get_ref()).map(|file_type| file_type.mime_type());
512 unpack::extract(mime_type, cursor, true, file_name, build_dir.path()).await?;
513
514 if cfg!(target_env = "msvc") {
515 do_build_lua_msvc(args, build_dir.path(), lua_version, pkg_version).await
516 } else {
517 do_build_lua_unix(args, build_dir.path(), lua_version, pkg_version).await
518 }
519}
520
521async fn download_source(file_name: &str, config: &Config) -> Result<(Url, Bytes), Error> {
522 let client = config.https_client()?;
523 let mut errors = Vec::new();
524 for base in config.lua_mirrors() {
525 let url = base.join(file_name)?;
526 let response = client
527 .get(url.clone())
528 .send()
529 .instrument(tracing::info_span!("Downloading Lua"))
530 .await
531 .and_then(reqwest::Response::error_for_status);
532 match response {
533 Ok(response) => {
534 let bytes = response
535 .bytes()
536 .instrument(tracing::trace_span!("getting response body"))
537 .await?;
538 return Ok((url, bytes));
539 }
540 Err(err) => {
541 tracing::warn!(message = format!("failed to download {url}: {err}").as_str());
542 errors.push(crate::reqwest::Error::from(err));
543 }
544 }
545 }
546 let mut errors = errors.into_iter();
547 match errors.next() {
548 None => Err(Error::NoLuaMirrors),
549 Some(source) => Err(Error::SourceMirrors {
550 source,
551 related: errors.collect(),
552 }),
553 }
554}
555
556#[tracing::instrument(name = "Compiling Lua", skip_all)]
557async fn do_build_lua_unix(
558 args: BuildLua<'_>,
559 build_dir: &Path,
560 lua_version: &lua::Version,
561 _pkg_version: &str,
562) -> Result<(), Error> {
563 tracing::debug!(message = "Compiling Lua (Unix)...");
564 let config = args.config;
565 let install_dir = args.install_dir;
566
567 let build_target = if cfg!(target_os = "linux") {
568 if matches!(&lua_version, lua::Version::Lua54) {
570 "linux-readline"
571 } else {
572 "linux"
573 }
574 } else if cfg!(target_os = "macos") {
575 "macosx"
576 } else if cfg!(target_os = "freebsd") {
577 "freebsd"
578 } else {
579 "generic"
580 };
581 match Command::new(config.make_cmd())
582 .current_dir(build_dir)
583 .stdout(Stdio::piped())
584 .stderr(Stdio::piped())
585 .arg(build_target)
586 .output()
587 .await
588 {
589 Ok(output) if !output.status.success() && build_target != "generic" => {
593 let fallback_output = Command::new(config.make_cmd())
594 .current_dir(build_dir)
595 .stdout(Stdio::piped())
596 .stderr(Stdio::piped())
597 .arg("generic")
598 .output()
599 .await;
600 guard_success(fallback_output, config, "build (generic)")?;
601 }
602 output => guard_success(output, config, &format!("build ({build_target})"))?,
603 };
604
605 match Command::new(config.make_cmd())
606 .current_dir(build_dir)
607 .stdout(Stdio::piped())
608 .stderr(Stdio::piped())
609 .arg("install")
610 .arg(format!(r#"INSTALL_TOP="{}""#, install_dir.display()))
611 .output()
612 .await
613 {
614 Ok(output) if output.status.success() => command::trace_output(&output),
615 Ok(output) => {
616 return Err(Error::CommandFailure {
617 name: "install".into(),
618 status: output.status,
619 stdout: String::from_utf8_lossy(&output.stdout).into(),
620 stderr: String::from_utf8_lossy(&output.stderr).into(),
621 });
622 }
623 Err(err) => {
624 return Err(Error::Io(io::Error::other(format!(
625 "Failed to run `{} install`:\n{}",
626 config.make_cmd(),
627 err
628 ))))
629 }
630 };
631
632 Ok(())
633}
634
635#[tracing::instrument(name = "Compiling Lua", skip_all)]
636async fn do_build_lua_msvc(
637 args: BuildLua<'_>,
638 build_dir: &Path,
639 lua_version: &lua::Version,
640 _pkg_version: &str,
641) -> Result<(), Error> {
642 tracing::debug!(message = "Compiling Lua (MSVC)...");
643 let config = args.config;
644 let install_dir = args.install_dir;
645
646 let lib_dir = install_dir.join("lib");
647 fs::tokio::create_dir_all(&lib_dir)
648 .await
649 .map_err(|err| io::Error::other(err.to_string()))?;
650 let include_dir = install_dir.join("include");
651 fs::tokio::create_dir_all(&include_dir)
652 .await
653 .map_err(|err| io::Error::other(err.to_string()))?;
654 let bin_dir = install_dir.join("bin");
655 fs::tokio::create_dir_all(&bin_dir)
656 .await
657 .map_err(|err| io::Error::other(err.to_string()))?;
658
659 let src_dir = build_dir.join("src");
660
661 let lua_bin_name = "lua";
662 let lua_c_bin_name = "luac";
663
664 let dll_name = match lua_version {
665 lua::Version::Lua51 => "lua51",
666 lua::Version::Lua52 => "lua52",
667 lua::Version::Lua53 => "lua53",
668 lua::Version::Lua54 => "lua54",
669 lua::Version::Lua55 => "lua55",
670 lua::Version::LuaJIT | lua::Version::LuaJIT52 | lua::Version::Luau => unreachable!(),
671 };
672
673 let lib_name = match lua_version {
674 lua::Version::Lua51 => "lua5.1",
675 lua::Version::Lua52 => "lua5.2",
676 lua::Version::Lua53 => "lua5.3",
677 lua::Version::Lua54 => "lua5.4",
678 lua::Version::Lua55 => "lua5.5",
679 lua::Version::LuaJIT | lua::Version::LuaJIT52 | lua::Version::Luau => unreachable!(),
680 };
681
682 let host = Triple::host();
683 let mut cc = cc::Build::new();
684 cc.cargo_output(false)
685 .cargo_metadata(false)
686 .cargo_warnings(false)
687 .warnings(config.verbose())
688 .opt_level(3)
689 .host(&host.to_string())
690 .target(&host.to_string());
691
692 cc.define("LUA_USE_WINDOWS", None);
693 cc.define("LUA_BUILD_AS_DLL", None);
694
695 let mut lib_c_files = Vec::new();
696 let mut read_dir = fs::tokio::read_dir(&src_dir)
697 .await
698 .map_err(|err| io::Error::other(err.to_string()))?;
699 while let Some(entry) = read_dir.next_entry().await? {
700 let path = entry.path();
701 if path.extension().is_some_and(|ext| ext == "c")
702 && path
703 .with_extension("")
704 .file_name()
705 .is_some_and(|name| name != "lua" && name != "luac")
706 {
707 lib_c_files.push(path);
708 }
709 }
710
711 let lib_objects = cc
712 .include(&src_dir)
713 .files(lib_c_files)
714 .out_dir(&lib_dir)
715 .try_compile_objects(config)?;
716
717 let bin_objects = cc
718 .include(&src_dir)
719 .file(src_dir.join(format!("{lua_bin_name}.c")))
720 .file(src_dir.join(format!("{lua_c_bin_name}.c")))
721 .out_dir(&src_dir)
722 .try_compile_objects(config)?;
723
724 let lua_bin_objects = bin_objects.iter().filter(|file| {
725 file.file_stem().is_some_and(|fname| {
726 fname
727 .to_string_lossy()
728 .ends_with(&format!("-{lua_bin_name}"))
729 })
730 });
731
732 let lua_c_bin_objects = bin_objects.iter().filter(|file| {
733 file.file_stem().is_some_and(|fname| {
734 fname
735 .to_string_lossy()
736 .ends_with(&format!("-{lua_c_bin_name}"))
737 })
738 });
739
740 let target = host.to_string();
741 let link = cc::windows_registry::find_tool(&target, "link.exe").ok_or(Error::LinkNotFound)?;
742
743 let dll_path = bin_dir.join(format!("{dll_name}.dll"));
744 let lua_bin_path = bin_dir.join(format!("{lua_bin_name}.exe"));
745 let lua_c_bin_path = bin_dir.join(format!("{lua_c_bin_name}.exe"));
746
747 let implib_path = lib_dir.join(format!("{lib_name}.lib"));
748
749 guard_success(
751 Command::new(link.path())
752 .arg("/DLL")
753 .arg(format!("/OUT:{}", dll_path.display()))
754 .arg(format!("/IMPLIB:{}", implib_path.display()))
755 .args(&lib_objects)
756 .output()
757 .await,
758 config,
759 &format!("link {dll_name}.dll"),
760 )?;
761
762 guard_success(
764 Command::new(link.path())
765 .arg(format!("/OUT:{}", lua_bin_path.display()))
766 .arg(&implib_path)
767 .args(lua_bin_objects)
768 .output()
769 .await,
770 config,
771 &format!("link {}", lua_bin_path.display()),
772 )?;
773
774 guard_success(
776 Command::new(link.path())
777 .arg(format!("/OUT:{}", lua_c_bin_path.display()))
778 .args(&lib_objects)
779 .args(lua_c_bin_objects)
780 .output()
781 .await,
782 config,
783 &format!("link {}", lua_c_bin_path.display()),
784 )?;
785
786 copy_includes(&src_dir, &include_dir).await?;
787
788 Ok(())
789}
790
791fn guard_success(
792 output: io::Result<std::process::Output>,
793 config: &Config,
794 cmd_name: &str,
795) -> Result<(), Error> {
796 match output {
797 Ok(output) if output.status.success() => {
798 command::trace_output(&output);
799 Ok(())
800 }
801 Ok(output) => Err(Error::CommandFailure {
802 name: cmd_name.to_string(),
803 status: output.status,
804 stdout: String::from_utf8_lossy(&output.stdout).into(),
805 stderr: String::from_utf8_lossy(&output.stderr).into(),
806 }),
807 Err(err) => Err(Error::Io(io::Error::other(format!(
808 "Failed to run `{} build`:\n{}",
809 config.make_cmd(),
810 err
811 )))),
812 }
813}
814
815async fn copy_includes(src_dir: &Path, include_dir: &Path) -> Result<(), io::Error> {
816 for f in &[
817 "lauxlib.h",
818 "lua.h",
819 "luaconf.h",
820 "luajit.h",
821 "lualib.h",
822 "lua.hpp",
823 ] {
824 let src_file = src_dir.join(f);
825 if src_file.is_file() {
826 fs::tokio::copy(&src_file, include_dir.join(f))
827 .await
828 .map_err(|err| io::Error::other(err.to_string()))?;
829 }
830 }
831 Ok(())
832}
833
834impl From<reqwest::Error> for Error {
835 fn from(err: reqwest::Error) -> Self {
836 Self::Request(err.into())
837 }
838}