Skip to main content

offlineasm_backend/
settings.rs

1//! Enumerates and resolves offlineasm setting combinations.
2//!
3//! [`compute_settings_combinations`] lists every backend crossed with every
4//! non-backend setting the source uses. [`for_settings`] resolves one
5//! combination against the tree.
6
7use crate::ast::Node;
8use crate::backends::{is_backend, is_valid_backend, BACKENDS};
9use crate::transform::resolve_settings;
10use std::collections::HashMap;
11
12/// Maps every setting to its concrete `true` or `false` value.
13pub type SettingsMap = HashMap<String, bool>;
14
15/// Lists the non-backend settings `ast` mentions, in first-use order.
16pub fn non_backend_settings(ast: &Node) -> Vec<String> {
17    let mut seen = Vec::new();
18    collect_settings(ast, &mut seen);
19    seen.into_iter().filter(|s| !is_backend(s)).collect()
20}
21
22fn collect_settings(node: &Node, out: &mut Vec<String>) {
23    if let Node::Setting { name, .. } = node {
24        if !out.contains(name) {
25            out.push(name.clone());
26        }
27    }
28    for child in node.children() {
29        collect_settings(child, out);
30    }
31}
32
33/// Lists every backend crossed with every true/false assignment of the
34/// non-backend settings.
35pub fn compute_settings_combinations(ast: &Node) -> Vec<SettingsMap> {
36    let non_backend = non_backend_settings(ast);
37    let mut out = Vec::new();
38    for backend in BACKENDS {
39        let mut base: SettingsMap = HashMap::new();
40        for b in BACKENDS {
41            base.insert(b.to_string(), *b == *backend);
42        }
43        combinator(&mut out, base, &non_backend);
44    }
45    out
46}
47
48fn combinator(out: &mut Vec<SettingsMap>, so_far: SettingsMap, remaining: &[String]) {
49    if remaining.is_empty() {
50        out.push(so_far);
51        return;
52    }
53    let mut with_true = so_far.clone();
54    with_true.insert(remaining[0].clone(), true);
55    combinator(out, with_true, &remaining[1..]);
56    let mut with_false = so_far;
57    with_false.insert(remaining[0].clone(), false);
58    combinator(out, with_false, &remaining[1..]);
59}
60
61/// Holds one resolved settings combination.
62#[derive(Clone, Debug)]
63pub struct ResolvedConfig {
64    /// Holds the combination that produced this config.
65    pub settings: SettingsMap,
66    /// Holds the tree with settings resolved.
67    pub low_level_ast: Node,
68    /// Names the selected backend.
69    pub backend: String,
70}
71
72/// Resolves `ast` under one concrete `settings` assignment.
73///
74/// Returns `None` when `settings` selects no backend or an unsupported one.
75/// Not every enumerated combination is meant to compile.
76///
77/// # Errors
78///
79/// - Returns an error if `settings` selects more than one backend.
80/// - Returns an error if settings resolution against `ast` fails.
81pub fn for_settings(settings: &SettingsMap, ast: &Node) -> Result<Option<ResolvedConfig>, String> {
82    let mut selected: Option<String> = None;
83    for backend in BACKENDS {
84        if settings.get(*backend) == Some(&true) {
85            if selected.is_some() {
86                return Err("multiple backends selected".to_string());
87            }
88            selected = Some(backend.to_string());
89        }
90    }
91    let backend = match selected {
92        Some(b) => b,
93        None => return Ok(None),
94    };
95    if !is_valid_backend(&backend) {
96        return Ok(None);
97    }
98    let low_level_ast = resolve_settings(ast, settings)?;
99    Ok(Some(ResolvedConfig {
100        settings: settings.clone(),
101        low_level_ast,
102        backend,
103    }))
104}
105
106/// Resolves `ast` under each valid combination, calling `f` per combination.
107///
108/// Uses `combinations` when given, else [`compute_settings_combinations`].
109/// `f` receives the settings, the resolved tree, the backend name, and the
110/// combination index.
111///
112/// # Errors
113///
114/// Returns an error if [`for_settings`] fails for a combination.
115pub fn for_each_valid_settings_combination(
116    ast: &Node,
117    combinations: Option<&[SettingsMap]>,
118    mut f: impl FnMut(&SettingsMap, &Node, &str, usize),
119) -> Result<(), String> {
120    let owned;
121    let combos: &[SettingsMap] = match combinations {
122        Some(c) => c,
123        None => {
124            owned = compute_settings_combinations(ast);
125            // Borrow dance: call with owned value via recursion-free loop.
126            for (index, settings) in owned.iter().enumerate() {
127                if let Some(resolved) = for_settings(settings, ast)? {
128                    f(
129                        &resolved.settings,
130                        &resolved.low_level_ast,
131                        &resolved.backend,
132                        index,
133                    );
134                }
135            }
136            return Ok(());
137        }
138    };
139    for (index, settings) in combos.iter().enumerate() {
140        if let Some(resolved) = for_settings(settings, ast)? {
141            f(
142                &resolved.settings,
143                &resolved.low_level_ast,
144                &resolved.backend,
145                index,
146            );
147        }
148    }
149    Ok(())
150}
151
152/// Renders `settings` as a C preprocessor `#if` test.
153pub fn cpp_settings_test(settings: &SettingsMap) -> String {
154    let mut pairs: Vec<(&String, &bool)> = settings.iter().collect();
155    pairs.sort_by(|a, b| a.0.cmp(b.0));
156    let parts: Vec<String> = pairs
157        .iter()
158        .map(|(k, v)| {
159            if **v {
160                format!("OFFLINE_ASM_{}", k)
161            } else {
162                format!("!OFFLINE_ASM_{}", k)
163            }
164        })
165        .collect();
166    format!("#if {}", parts.join(" && "))
167}
168
169/// Renders `settings` as a Rust `cfg` predicate.
170///
171/// Terms follow `non_backend_order` after the backend terms.
172pub fn rust_cfg_predicate(settings: &SettingsMap, non_backend_order: &[String]) -> String {
173    let mut terms: Vec<String> = Vec::new();
174    for backend in BACKENDS {
175        if let Some(v) = settings.get(*backend) {
176            terms.push(cfg_term(backend, *v));
177        }
178    }
179    for name in non_backend_order {
180        if is_backend(name) {
181            continue;
182        }
183        if let Some(v) = settings.get(name) {
184            terms.push(cfg_term(name, *v));
185        }
186    }
187    format!("all({})", terms.join(", "))
188}
189
190fn cfg_term(name: &str, value: bool) -> String {
191    let ident = format!("offline_asm_{}", name.to_lowercase());
192    if value {
193        ident
194    } else {
195        format!("not({})", ident)
196    }
197}
198
199/// Reports whether `ast` holds a `Node::Error` after macro expansion.
200///
201/// # Errors
202///
203/// Returns an error if macro expansion fails.
204pub fn is_ast_erroneous(ast: &Node) -> Result<bool, String> {
205    let demacroed = crate::transform::demacroify(ast)?;
206    Ok(contains_error(&demacroed))
207}
208
209fn contains_error(node: &Node) -> bool {
210    if matches!(node, Node::Error { .. }) {
211        return true;
212    }
213    node.children().iter().any(|c| contains_error(c))
214}