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::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#[tracing::instrument(
50    name = "Compiling C modules",
51    level = "info",
52    skip_all,
53    fields(profile = config.build_profile().to_string()),
54)]
55pub(crate) async fn compile(
56    data: &rockspec::build::backend::ModulePaths,
57    source_dir: &Path,
58    target_module: &rockspec::build::backend::Module,
59    target_dir: &Path,
60    lua: &lua::Installation,
61    external_dependencies: &HashMap<String, ExternalDependencyInfo>,
62    config: &Config,
63) -> Result<(), Error> {
64    let target = target_dir.join(target_module.to_lib_path());
65
66    let target_parent_dir = target.parent().unwrap_or_else(|| {
67        unreachable!(
68            "couldn't determine build target parent directory:\n{}",
69            target.display()
70        )
71    });
72
73    fs::tokio::create_dir_all(target_parent_dir).await?;
74
75    let host = Triple::host();
76
77    let mut build = cc::Build::new();
78    let source_files = data
79        .sources
80        .iter()
81        .map(|dir| {
82            variables::substitute(
83                &[lua, external_dependencies, &Environment {}, config],
84                &dir.to_slash_lossy(),
85            )
86        })
87        .map(|dir| dir.map(|dir| source_dir.join(dir)))
88        .try_collect::<_, Vec<_>, _>()?;
89    let include_dirs = data
90        .incdirs
91        .iter()
92        .map(|dir| {
93            variables::substitute(
94                &[lua, external_dependencies, &Environment {}, config],
95                &dir.to_slash_lossy(),
96            )
97        })
98        .map(|dir| dir.map(|dir| source_dir.join(dir)))
99        .chain(
100            external_dependencies
101                .values()
102                .filter_map(|dep| dep.include_dir.clone())
103                .map(Result::Ok),
104        )
105        .try_collect::<_, Vec<_>, _>()?
106        .into_iter()
107        .unique() // Some rocks specify the include dirs via variable substitution.
108        .collect_vec();
109
110    let intermediate_dir = fs::tempfile::tempdir()?;
111    let build = build
112        .cargo_output(config.verbose())
113        .cargo_debug(config.verbose())
114        .cargo_metadata(config.verbose())
115        .cargo_warnings(config.verbose())
116        .warnings(config.verbose())
117        .files(source_files)
118        .host(&host.to_string())
119        .target(&host.to_string())
120        .includes(&include_dirs)
121        .includes(lua.includes())
122        .includes(
123            external_dependencies
124                .values()
125                .filter_map(|dep| dep.include_dir.as_ref()),
126        )
127        .opt_level(config.build_profile().opt_level())
128        .out_dir(intermediate_dir);
129
130    let compiler = build.try_get_compiler()?;
131    let is_msvc = compiler.is_like_msvc();
132    // Suppress all warnings
133    if is_msvc {
134        build.flag("-W0");
135    } else {
136        build.flag("-w");
137    }
138    for arg in lua.define_flags() {
139        build.flag(&arg);
140    }
141
142    // `cc::Build` has no `defines()` function, so we manually feed in the
143    // definitions in a verbose loop
144    for (name, value) in &data.defines {
145        build.define(name, value.as_deref());
146    }
147
148    let target_file_name = target
149        .file_name()
150        .unwrap_or_default()
151        .to_string_lossy()
152        .to_string();
153    // See https://github.com/rust-lang/cc-rs/issues/594#issuecomment-2110551057
154    let objects = build
155        .try_compile_objects(config)
156        .map_err(Error::CompileIntermediates)?;
157
158    let libdir_args = data
159        .libdirs
160        .iter()
161        .map(|dir| {
162            variables::substitute(
163                &[lua, external_dependencies, &Environment {}, config],
164                &dir.to_slash_lossy(),
165            )
166        })
167        .map(|libdir| {
168            libdir.map(|libdir| {
169                if is_msvc {
170                    format!("/LIBPATH:{}", source_dir.join(libdir).display())
171                } else {
172                    format!("-L{}", source_dir.join(libdir).display())
173                }
174            })
175        })
176        .try_collect::<_, Vec<_>, _>()?;
177
178    let library_args = data
179        .libraries
180        .iter()
181        .map(|dir| {
182            variables::substitute(
183                &[lua, external_dependencies, &Environment {}, config],
184                &dir.to_slash_lossy(),
185            )
186        })
187        .map(|library| {
188            library.map(|library| {
189                if is_msvc {
190                    format!("{}.lib", library)
191                } else {
192                    format!("-l{}", library)
193                }
194            })
195        })
196        .try_collect::<_, Vec<_>, _>()?;
197
198    c_link::artifacts(
199        build,
200        lua,
201        external_dependencies,
202        &target_file_name,
203        libdir_args,
204        library_args,
205        target_module,
206        target_parent_dir,
207        objects,
208        config,
209    )
210    .await?;
211    Ok(())
212}