Skip to main content

lux_lib/build/compile/
c_modules.rs

1use std::{collections::HashMap, path::Path};
2
3use itertools::Itertools;
4use miette::Diagnostic;
5use path_slash::PathExt;
6use target_lexicon::Triple;
7use thiserror::Error;
8
9use crate::{
10    build::{dependency, external_dependency::ExternalDependencyInfo},
11    config::Config,
12    fs, lua, rockspec,
13    variables::{self, Environment},
14};
15
16use super::{c_link, CCExt};
17
18// TODO: (#261): special cases for mingw/cygwin?
19
20#[derive(Error, Debug, Diagnostic)]
21#[non_exhaustive]
22pub enum Error {
23    #[error(transparent)]
24    #[diagnostic(transparent)]
25    Fs(#[from] fs::Error),
26    #[error("failed to compile intermediates from C modules")]
27    #[diagnostic(help(
28        r#"check the compiler output above for missing headers or syntax errors.
29ensure the C compiler has access to the required include paths."#
30    ))]
31    CompileIntermediates(#[source] cc::Error),
32    #[error("error compiling C modules (compilation failed)")]
33    #[diagnostic(help(
34        r#"check the compiler output above for details.
35if no C compiler was found, run `lx debug toolchains` to verify your build tools."#
36    ))]
37    Compilation(#[from] cc::Error),
38    #[error("error compiling C modules (linking failed)")]
39    #[diagnostic(forward(0))]
40    Link(#[from] c_link::Error),
41    #[error(transparent)]
42    #[diagnostic(transparent)]
43    VariableSubstitution(#[from] variables::Error),
44}
45
46/// Compiles a set of C files (with extra metadata) to a given destination.
47/// # Panics
48/// Panics if no filename for the target path can be determined.
49#[derive(bon::Builder)]
50#[builder(start_fn = new, finish_fn(name = _build, vis = ""))]
51pub(crate) struct Compiler<'a> {
52    data: &'a rockspec::build::backend::ModulePaths,
53    source_dir: &'a Path,
54    target_module: &'a rockspec::build::backend::Module,
55    target_dir: &'a Path,
56    lua: &'a lua::Installation,
57    external_dependencies: &'a HashMap<String, ExternalDependencyInfo>,
58    dependency_layouts: &'a dependency::Layouts,
59    config: &'a Config,
60}
61
62impl<'a, State> CompilerBuilder<'a, State>
63where
64    State: compiler_builder::State + compiler_builder::IsComplete,
65{
66    #[tracing::instrument(name = "Compiling C modules", level = "info", skip_all)]
67    pub(crate) async fn compile(self) -> Result<(), Error> {
68        let compiler = self._build();
69        let target = compiler
70            .target_dir
71            .join(compiler.target_module.to_lib_path());
72
73        let target_parent_dir = target.parent().unwrap_or_else(|| {
74            unreachable!(
75                "couldn't determine build target parent directory:\n{}",
76                target.display()
77            )
78        });
79
80        fs::tokio::create_dir_all(target_parent_dir).await?;
81
82        let host = Triple::host();
83
84        let mut build = cc::Build::new();
85        let source_files = compiler
86            .data
87            .sources
88            .iter()
89            .map(|dir| {
90                variables::substitute(
91                    &[
92                        compiler.lua,
93                        compiler.external_dependencies,
94                        compiler.dependency_layouts,
95                        &Environment {},
96                        compiler.config,
97                    ],
98                    &dir.to_slash_lossy(),
99                )
100            })
101            .map(|dir| dir.map(|dir| compiler.source_dir.join(dir)))
102            .try_collect::<_, Vec<_>, _>()?;
103        let include_dirs = compiler
104            .data
105            .incdirs
106            .iter()
107            .map(|dir| {
108                variables::substitute(
109                    &[
110                        compiler.lua,
111                        compiler.external_dependencies,
112                        compiler.dependency_layouts,
113                        &Environment {},
114                        compiler.config,
115                    ],
116                    &dir.to_slash_lossy(),
117                )
118            })
119            .map(|dir| dir.map(|dir| compiler.source_dir.join(dir)))
120            .chain(
121                compiler
122                    .external_dependencies
123                    .values()
124                    .filter_map(|dep| dep.include_dir.clone())
125                    .map(Result::Ok),
126            )
127            .try_collect::<_, Vec<_>, _>()?
128            .into_iter()
129            .unique() // Some rocks specify the include dirs via variable substitution.
130            .collect_vec();
131
132        let intermediate_dir = fs::tempfile::tempdir()?;
133        let build = build
134            .cargo_output(compiler.config.verbose())
135            .cargo_debug(compiler.config.verbose())
136            .cargo_metadata(compiler.config.verbose())
137            .cargo_warnings(compiler.config.verbose())
138            .warnings(compiler.config.verbose())
139            .files(source_files)
140            .host(&host.to_string())
141            .target(&host.to_string())
142            .includes(&include_dirs)
143            .includes(compiler.lua.includes())
144            .includes(
145                compiler
146                    .external_dependencies
147                    .values()
148                    .filter_map(|dep| dep.include_dir.as_ref()),
149            )
150            .opt_level(compiler.config.build_profile().opt_level())
151            .out_dir(intermediate_dir);
152
153        let cc_tool = build.try_get_compiler()?;
154        let is_msvc = cc_tool.is_like_msvc();
155        // Suppress all warnings
156        if is_msvc {
157            build.flag("-W0");
158        } else {
159            build.flag("-w");
160        }
161        for arg in compiler.lua.define_flags() {
162            build.flag(&arg);
163        }
164
165        // `cc::Build` has no `defines()` function, so we manually feed in the
166        // definitions in a verbose loop
167        for (name, value) in &compiler.data.defines {
168            build.define(name, value.as_deref());
169        }
170
171        let target_file_name = target
172            .file_name()
173            .unwrap_or_default()
174            .to_string_lossy()
175            .to_string();
176        // See https://github.com/rust-lang/cc-rs/issues/594#issuecomment-2110551057
177        let objects = build
178            .try_compile_objects(compiler.config)
179            .map_err(Error::CompileIntermediates)?;
180
181        let libdir_args = compiler
182            .data
183            .libdirs
184            .iter()
185            .map(|dir| {
186                variables::substitute(
187                    &[
188                        compiler.lua,
189                        compiler.external_dependencies,
190                        compiler.dependency_layouts,
191                        &Environment {},
192                        compiler.config,
193                    ],
194                    &dir.to_slash_lossy(),
195                )
196            })
197            .map(|libdir| {
198                libdir.map(|libdir| {
199                    if is_msvc {
200                        format!("/LIBPATH:{}", compiler.source_dir.join(libdir).display())
201                    } else {
202                        format!("-L{}", compiler.source_dir.join(libdir).display())
203                    }
204                })
205            })
206            .try_collect::<_, Vec<_>, _>()?;
207
208        let library_args = compiler
209            .data
210            .libraries
211            .iter()
212            .map(|dir| {
213                variables::substitute(
214                    &[
215                        compiler.lua,
216                        compiler.external_dependencies,
217                        compiler.dependency_layouts,
218                        &Environment {},
219                        compiler.config,
220                    ],
221                    &dir.to_slash_lossy(),
222                )
223            })
224            .map(|library| {
225                library.map(|library| {
226                    if is_msvc {
227                        format!("{}.lib", library)
228                    } else {
229                        format!("-l{}", library)
230                    }
231                })
232            })
233            .try_collect::<_, Vec<_>, _>()?;
234
235        c_link::Linker::new()
236            .cc_build(build)
237            .lua(compiler.lua)
238            .external_dependencies(compiler.external_dependencies)
239            .target_file_name(&target_file_name)
240            .libdir_args(libdir_args)
241            .library_args(library_args)
242            .target_module(compiler.target_module)
243            .target_parent_dir(target_parent_dir)
244            .objects(objects)
245            .config(compiler.config)
246            .link()
247            .await?;
248        Ok(())
249    }
250}