lux_lib/build/compile/
c_files.rs1use std::{
2 collections::HashMap,
3 path::{Path, PathBuf},
4};
5
6use miette::Diagnostic;
7use target_lexicon::Triple;
8use thiserror::Error;
9
10use crate::{
11 build::external_dependency::ExternalDependencyInfo, config::Config, fs, lua, rockspec,
12};
13
14use super::{c_link, CCExt};
15
16#[derive(Error, Debug, Diagnostic)]
17#[non_exhaustive]
18pub enum Error {
19 #[error(transparent)]
20 #[diagnostic(transparent)]
21 Fs(#[from] fs::Error),
22 #[error("failed to compile intermediates from C files")]
23 #[diagnostic(help(
24 r#"check the compiler output above for missing headers or syntax errors.
25ensure the C compiler has access to the required include paths."#
26 ))]
27 CompileIntermediates { source: cc::Error },
28 #[error("error compiling C files (compilation failed):")]
29 #[diagnostic(help(
30 r#"check the compiler output above for details.
31if no C compiler was found, run `lx debug toolchains` to verify your build tools."#
32 ))]
33 Compilation(#[from] cc::Error),
34 #[error("error compiling C files (linking failed)")]
35 #[diagnostic(forward(0))]
36 Link(#[from] c_link::Error),
37}
38
39#[derive(bon::Builder)]
43#[builder(start_fn = new, finish_fn(name = _build, vis = ""))]
44pub(crate) struct Compiler<'a> {
45 files: &'a [PathBuf],
46 target_module: &'a rockspec::build::backend::Module,
47 target_dir: &'a Path,
48 lua: &'a lua::Installation,
49 external_dependencies: &'a HashMap<String, ExternalDependencyInfo>,
50 config: &'a Config,
51}
52
53impl<'a, State> CompilerBuilder<'a, State>
54where
55 State: compiler_builder::State + compiler_builder::IsComplete,
56{
57 #[tracing::instrument(name = "Compiling C files", level = "info", skip_all)]
58 pub(crate) async fn compile(self) -> Result<(), Error> {
59 let compiler = self._build();
60 let target = compiler
61 .target_dir
62 .join(compiler.target_module.to_lib_path());
63 let target_parent_dir = target.parent().unwrap_or_else(|| {
64 unreachable!(
65 "couldn't determine build target parent directory:\n{}",
66 target.display()
67 )
68 });
69 let target_file_name = target
70 .file_name()
71 .unwrap_or_default()
72 .to_string_lossy()
73 .to_string();
74
75 fs::sync::create_dir_all(target_parent_dir)?;
76
77 let host = Triple::host();
78
79 let mut build = cc::Build::new();
82 let intermediate_dir = fs::tempfile::tempdir()?;
83 let build = build
84 .cargo_output(compiler.config.verbose())
85 .cargo_debug(compiler.config.verbose())
86 .cargo_metadata(compiler.config.verbose())
87 .cargo_warnings(compiler.config.verbose())
88 .warnings(compiler.config.verbose())
89 .files(compiler.files)
90 .host(&host.to_string())
91 .target(&host.to_string())
92 .includes(compiler.lua.includes())
93 .includes(
94 compiler
95 .external_dependencies
96 .values()
97 .filter_map(|dep| dep.include_dir.as_ref()),
98 )
99 .opt_level(compiler.config.build_profile().opt_level())
100 .out_dir(intermediate_dir);
101
102 let cc_tool = build.try_get_compiler()?;
103 if cc_tool.is_like_msvc() {
105 build.flag("-W0");
106 } else {
107 build.flag("-w");
108 }
109 for arg in compiler.lua.define_flags() {
110 build.flag(&arg);
111 }
112
113 let objects = build
114 .try_compile_objects(compiler.config)
115 .map_err(|source| Error::CompileIntermediates { source })?;
116
117 c_link::Linker::new()
118 .cc_build(build)
119 .lua(compiler.lua)
120 .external_dependencies(compiler.external_dependencies)
121 .target_file_name(&target_file_name)
122 .libdir_args(Vec::new())
123 .library_args(Vec::new())
124 .target_module(compiler.target_module)
125 .target_parent_dir(target_parent_dir)
126 .objects(objects)
127 .config(compiler.config)
128 .link()
129 .await?;
130 Ok(())
131 }
132}