Skip to main content

cargo_kcfg_macros/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use cargo_kcfg::{Pipeline, ProjectLocator};
4use proc_macro::TokenStream;
5use quote::quote;
6use std::env;
7use std::path::{Path, PathBuf};
8
9/// Expand the evaluated `config.rs` into the calling module.
10///
11/// Takes no arguments. Discovers `Kconfig` from `CARGO_MANIFEST_DIR` (walking
12/// up to a workspace root) and the unique `*_defconfig` or `KCONFIG_DEFCONFIG`.
13///
14/// # Errors
15///
16/// Expansion becomes `compile_error!` when:
17///
18/// - the macro is invoked with arguments
19/// - `CARGO_MANIFEST_DIR` is unset
20/// - `Kconfig` or a unique defconfig cannot be found
21/// - the definition file cannot be parsed
22/// - evaluation is incoherent (unmet `depends on`, bad `select`, and so on)
23/// - generated Rust is not valid tokens
24#[proc_macro]
25pub fn include_config(input: TokenStream) -> TokenStream {
26    if !input.is_empty() {
27        return compile_error("include_config! takes no arguments");
28    }
29    match expand() {
30        Ok(tokens) => tokens,
31        Err(message) => compile_error(&message),
32    }
33}
34
35fn compile_error(message: &str) -> TokenStream {
36    let lit = proc_macro2::Literal::string(message);
37    quote! { compile_error!(#lit); }.into()
38}
39
40fn expand() -> Result<TokenStream, String> {
41    let manifest = env::var("CARGO_MANIFEST_DIR").map_err(|_| {
42        "CARGO_MANIFEST_DIR is not set. include_config! is for Cargo crates".to_string()
43    })?;
44    let locator =
45        ProjectLocator::discover(PathBuf::from(manifest)).map_err(|err| err.to_string())?;
46    let request = locator.resolve(None, None).map_err(|err| err.to_string())?;
47    let result = Pipeline::new()
48        .run(&request)
49        .map_err(|err| err.to_string())?;
50
51    let body: proc_macro2::TokenStream = result
52        .generated
53        .config_rs
54        .parse()
55        .map_err(|err| format!("generated config.rs is not valid Rust: {err}"))?;
56
57    let mut files = Vec::new();
58    push_tracked(&mut files, &request.kconfig);
59    push_tracked(&mut files, &request.defconfig);
60    for loaded in &result.loaded_files {
61        push_tracked(&mut files, loaded);
62    }
63    files.sort();
64    files.dedup();
65    let file_lits = files
66        .iter()
67        .map(|p| proc_macro2::Literal::string(p))
68        .collect::<Vec<_>>();
69
70    Ok(quote! {
71        #body
72        const _: &[&str] = &[#(include_str!(#file_lits)),*];
73        const _: Option<&str> = option_env!("KCONFIG_DEFCONFIG");
74    }
75    .into())
76}
77
78fn push_tracked(files: &mut Vec<String>, path: &Path) {
79    let abs = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
80    if let Some(text) = abs.to_str() {
81        files.push(text.to_string());
82    }
83}