Skip to main content

offlineasm_backend/
driver.rs

1//! Compiles parsed offlineasm into emitted output.
2
3use crate::ast::Node;
4use crate::backends::text::TextTarget;
5use crate::backends::{lower_node, Backend, BackendSet, LowerCtx, WORKING_BACKENDS};
6use crate::parser::{parse_data, parse_file, parse_tokens, ParseSession, ParserOptions};
7use crate::settings::{
8    compute_settings_combinations, for_settings, is_ast_erroneous, non_backend_settings,
9    rust_cfg_predicate, SettingsMap,
10};
11use crate::transform::{fold, resolve_offsets, validate};
12use std::collections::HashMap;
13use std::path::Path;
14
15/// Returns the text target `backend` prints for, or `None` for the interpreter.
16fn text_target(backend: Backend) -> Option<TextTarget> {
17    match backend {
18        Backend::X86_64 => Some(TextTarget::X86_64),
19        Backend::Arm64 | Backend::Arm64e => Some(TextTarget::Aarch64),
20        Backend::Riscv64 => Some(TextTarget::Riscv64),
21        Backend::RLoop => None,
22    }
23}
24
25#[derive(Debug, Default)]
26pub struct AsmEmitter {
27    pub lines: Vec<String>,
28    pub rust_lines: Vec<String>,
29    comment: Option<String>,
30    annotation: Option<String>,
31    code_origin: Option<String>,
32    internal_comment: Option<String>,
33    pub num_local_labels: usize,
34    pub num_global_labels: usize,
35    pub enable_label_count_comments: bool,
36    pub enable_code_origin_comments: bool,
37    pub enable_instr_annotations: bool,
38    pub emit_elf_debug_directives: bool,
39    comment_column: usize,
40    uid_counter: usize,
41}
42
43impl AsmEmitter {
44    pub fn new() -> Self {
45        Self {
46            comment_column: 40,
47            enable_code_origin_comments: true,
48            ..Default::default()
49        }
50    }
51
52    fn last_comment(&mut self) -> String {
53        let mut result = String::new();
54        if let Some(c) = self.comment.take() {
55            result = c;
56        }
57        if self.enable_instr_annotations {
58            if let Some(a) = self.annotation.take() {
59                if !result.is_empty() {
60                    result.push(' ');
61                }
62                result.push_str(&a);
63            } else {
64                self.annotation = None;
65            }
66        } else {
67            self.annotation = None;
68        }
69        if let Some(ic) = self.internal_comment.take() {
70            if !result.is_empty() {
71                result.push(' ');
72            }
73            result.push_str(&ic);
74        }
75        if self.enable_code_origin_comments {
76            if let Some(co) = self.code_origin.take() {
77                if !result.is_empty() {
78                    result.push(' ');
79                }
80                result.push_str(&co);
81            }
82        }
83        self.comment = None;
84        self.code_origin = None;
85        if result.is_empty() {
86            result
87        } else {
88            format!("// {}", result)
89        }
90    }
91
92    fn format_dump(&self, dump: &str, comment: &str) -> String {
93        if comment.is_empty() {
94            dump.to_string()
95        } else {
96            format!("{:<width$} {}", dump, comment, width = self.comment_column)
97        }
98    }
99
100    pub fn puts(&mut self, line: &str) {
101        let comment = self.last_comment();
102        self.lines
103            .push(self.format_dump(&format!("\t{}", line), &comment));
104    }
105
106    pub fn put_str(&mut self, line: &str) {
107        let _ = self.last_comment();
108        self.lines.push(line.to_string());
109    }
110
111    pub fn put_rust(&mut self, line: &str) {
112        let comment = self.last_comment();
113        self.rust_lines
114            .push(self.format_dump(&format!("    {}", line), &comment));
115    }
116
117    pub fn rust_source(&self) -> String {
118        self.rust_lines.join("\n")
119    }
120
121    pub fn puts_label(
122        &mut self,
123        label: &str,
124        is_global: bool,
125        is_export: bool,
126        is_aligned: bool,
127        align_to: Option<String>,
128    ) {
129        self.num_global_labels += 1;
130        if self.enable_label_count_comments {
131            self.internal_comment = Some(format!("Global Label {}", self.num_global_labels));
132        }
133        let comment = self.last_comment();
134        let mut emit = |line: String| {
135            if comment.is_empty() {
136                self.lines.push(line);
137            } else {
138                self.lines.push(format!(
139                    "{:<width$} {}",
140                    line,
141                    comment,
142                    width = self.comment_column
143                ));
144            }
145        };
146        if is_global {
147            if !is_aligned {
148                let _ = is_export;
149                emit(format!(".globl {}", label));
150                if let Some(a) = align_to {
151                    emit(format!(".p2align {}", a));
152                }
153                emit(format!("{}:", label));
154            } else if let Some(a) = align_to {
155                emit(format!(".globl {}", label));
156                emit(format!(".p2align {}", a));
157                emit(format!("{}:", label));
158            } else {
159                emit(format!(".globl {}", label));
160                emit(format!("{}:", label));
161            }
162            if is_export {
163                // todo
164            }
165            if self.emit_elf_debug_directives {
166                emit(format!(".type {}, @function", label));
167                emit(format!(".size {}, . - {}", label, label));
168            }
169        } else {
170            if let Some(a) = align_to {
171                emit(format!(".p2align {}", a));
172            }
173            emit(format!("{}:", label));
174        }
175    }
176
177    pub fn puts_local_label(&mut self, label: &str) {
178        self.num_local_labels += 1;
179        if self.enable_label_count_comments {
180            self.internal_comment = Some(format!("Local Label {}", self.num_local_labels));
181        }
182        let comment = self.last_comment();
183        self.lines.push(String::new());
184        let line = format!("  {}:", label);
185        if comment.is_empty() {
186            self.lines.push(line);
187        } else {
188            self.lines.push(format!(
189                "{:<width$} {}",
190                line,
191                comment,
192                width = self.comment_column
193            ));
194        }
195    }
196
197    pub fn code_origin(&mut self, text: String) {
198        self.code_origin = Some(text);
199    }
200
201    pub fn comment(&mut self, text: String) {
202        self.comment = Some(text);
203    }
204
205    pub fn annotation(&mut self, text: String) {
206        self.annotation = Some(text);
207    }
208
209    pub fn put_local_annotation(&mut self) {
210        if self.enable_instr_annotations {
211            if let Some(a) = self.annotation.take() {
212                self.lines.push(format!("    // {}", a));
213            }
214        } else {
215            self.annotation = None;
216        }
217    }
218
219    pub fn put_global_annotation(&mut self) {
220        if self.enable_instr_annotations {
221            if let Some(a) = self.annotation.take() {
222                self.lines.push(String::new());
223                self.lines.push(format!("// {}", a));
224            }
225        } else {
226            self.annotation = None;
227        }
228    }
229
230    pub fn new_uid(&mut self) -> usize {
231        self.uid_counter += 1;
232        self.uid_counter
233    }
234
235    pub fn template(&self) -> String {
236        self.lines.join("\n")
237    }
238}
239
240pub const MACHO: &str = "Mach-O";
241
242#[derive(Clone, Debug, Default)]
243pub struct CompileOptions {
244    pub backend: Option<Backend>,
245    pub platform: Option<String>,
246    pub binary_format: Option<String>,
247    pub globals: Vec<String>,
248    pub global_exports: Vec<String>,
249    pub integer_offsets: HashMap<String, i64>,
250    pub auto_rust_offsets: bool,
251    pub settings_overrides: HashMap<String, bool>,
252}
253
254impl CompileOptions {
255    pub fn with_auto_rust_offsets(mut self, v: bool) -> Self {
256        self.auto_rust_offsets = v;
257        self
258    }
259}
260
261#[derive(Clone, Debug)]
262pub struct CompiledAsm {
263    pub template: String,
264    pub const_args: Vec<(String, String)>,
265    pub referenced_externs: Vec<String>,
266    pub backend: Backend,
267    pub rust_lines: Vec<String>,
268}
269
270/// Compiles offlineasm source text to a `global_asm!` template.
271///
272/// # Errors
273///
274/// - Returns an error if `src` fails to parse.
275/// - Returns an error if `options.globals` or `options.global_exports`
276///   conflict with declared labels.
277/// - Returns an error if no valid settings combination selects the backend.
278/// - Returns an error if lowering the resolved tree fails.
279pub fn compile_str(
280    src: &str,
281    file_name: &str,
282    options: &CompileOptions,
283    parser_options: &ParserOptions,
284) -> Result<CompiledAsm, String> {
285    let mut session = ParseSession::new(parser_options.clone());
286    let ast = parse_data(src, file_name, &mut session).map_err(|e| e.to_string())?;
287    compile_ast(&ast, &mut session, options)
288}
289
290/// Compiles offlineasm source already tokenized as a
291/// [`proc_macro2::TokenStream`] (the inline `offlineasm!{ ... }` macro
292/// form) to a `global_asm!` template.
293///
294/// # Errors
295///
296/// Same conditions as [`compile_str`].
297pub fn compile_tokens(
298    tokens: proc_macro2::TokenStream,
299    file_name: &str,
300    options: &CompileOptions,
301    parser_options: &ParserOptions,
302) -> Result<CompiledAsm, String> {
303    let mut session = ParseSession::new(parser_options.clone());
304    let ast = parse_tokens(tokens, file_name, &mut session).map_err(|e| e.to_string())?;
305    compile_ast(&ast, &mut session, options)
306}
307
308/// Compiles an offlineasm file, tracking includes relative to it.
309///
310/// # Errors
311///
312/// - Returns an error if the file or one of its `include`s cannot be read
313///   or parsed.
314/// - Returns an error if `options.globals` or `options.global_exports`
315///   conflict with declared labels.
316/// - Returns an error if no valid settings combination selects the backend.
317/// - Returns an error if lowering the resolved tree fails.
318pub fn compile_file(
319    path: &Path,
320    options: &CompileOptions,
321    parser_options: &ParserOptions,
322) -> Result<CompiledAsm, String> {
323    let mut session = ParseSession::new(parser_options.clone());
324    let ast = parse_file(path, &mut session).map_err(|e| e.to_string())?;
325    compile_ast(&ast, &mut session, options)
326}
327
328fn compile_ast(
329    ast: &Node,
330    session: &mut ParseSession,
331    options: &CompileOptions,
332) -> Result<CompiledAsm, String> {
333    for g in &options.globals {
334        session
335            .labels
336            .set_as_global(g)
337            .map_err(|e| format!("globals: {}", e))?;
338    }
339    for g in &options.global_exports {
340        session
341            .labels
342            .set_as_global_export(g)
343            .map_err(|e| format!("exports: {}", e))?;
344    }
345    let backend = options.backend.unwrap_or(Backend::X86_64);
346    let mut combinations = compute_settings_combinations(ast);
347
348    let undeclared: Vec<(String, bool)> = options
349        .settings_overrides
350        .iter()
351        .filter(|(k, _)| !combinations.iter().any(|c| c.contains_key(*k)))
352        .map(|(k, v)| (k.clone(), *v))
353        .collect();
354    if !undeclared.is_empty() {
355        for combination in &mut combinations {
356            for (k, v) in &undeclared {
357                combination.insert(k.clone(), *v);
358            }
359        }
360    }
361
362    let mut chosen: Option<(SettingsMap, Node)> = None;
363    for settings in &combinations {
364        if settings.get(backend.name()) != Some(&true) {
365            continue;
366        }
367        let mut ok = true;
368        for (k, v) in &options.settings_overrides {
369            if settings.get(k) != Some(v) {
370                ok = false;
371                break;
372            }
373        }
374        if !ok {
375            continue;
376        }
377        if let Some(resolved) = for_settings(settings, ast)? {
378            // Default overrides imply all non-backend settings false.
379            if options.settings_overrides.is_empty() {
380                let non_backend_set = resolved
381                    .settings
382                    .iter()
383                    .any(|(k, v)| *k != backend.name() && !crate::backends::is_backend(k) && *v);
384                if non_backend_set {
385                    continue;
386                }
387            }
388            chosen = Some((resolved.settings, resolved.low_level_ast));
389            break;
390        }
391    }
392    let (chosen_settings, low_level) = chosen.ok_or_else(|| {
393        format!(
394            "no valid settings combination for backend {}",
395            backend.name()
396        )
397    })?;
398    compile_resolved(&low_level, backend, session, options, &chosen_settings)
399}
400
401fn compile_resolved(
402    low_level: &Node,
403    backend: Backend,
404    session: &mut ParseSession,
405    options: &CompileOptions,
406    settings: &SettingsMap,
407) -> Result<CompiledAsm, String> {
408    let (demacroed, label_renames) = crate::transform::demacroify_recording(low_level)?;
409
410    for (old, new) in &label_renames {
411        session.labels.apply_substituted_label_flags(old, new);
412    }
413
414    let (with_offsets, mut const_args) = resolve_offsets_ergo(&demacroed, options)?;
415    let folded = fold(&with_offsets);
416
417    for (ident, expr) in collect_rust_consts(&folded) {
418        if !const_args.iter().any(|(existing, _)| *existing == ident) {
419            const_args.push((ident, expr));
420        }
421    }
422    validate(&folded)?;
423    let mut emitter = AsmEmitter::new();
424    emitter.emit_elf_debug_directives =
425        options.binary_format.as_deref() == Some("ELF") && backend != Backend::RLoop;
426    if let Some(target) = text_target(backend) {
427        // x86-64 output is Intel syntax (the dialect is destination-first).
428        let mut prologue_ctx = LowerCtx::new(backend, &mut emitter);
429        target.prologue(&mut prologue_ctx);
430    }
431    let label_snapshot = session.labels.clone();
432    let label_flags = |name: &str| -> (bool, bool, bool, bool, Option<String>) {
433        match label_snapshot.label_flags(name) {
434            Some(fl) => (
435                fl.global,
436                fl.export,
437                fl.aligned,
438                fl.is_extern,
439                fl.align_to.as_ref().map(|n| n.dump()),
440            ),
441            None => (false, false, true, true, None),
442        }
443    };
444    let referenced;
445    {
446        let mut ctx = LowerCtx::new(backend, &mut emitter);
447        ctx.is_win = options.platform.as_deref() == Some("Windows");
448        ctx.macho = options.binary_format.as_deref() == Some(MACHO);
449        ctx.set_settings(settings.clone());
450        ctx.declared_externs = session.labels.declared_externs.clone();
451
452        for (name, string) in &session.labels.local_strings {
453            ctx.local_strings.insert(name.clone(), string.clone());
454            ctx.known_labels.insert(name.clone());
455        }
456        collect_label_info(&folded, &mut ctx);
457        lower_node(&folded, &mut ctx, &label_flags).map_err(|e| e.to_string())?;
458        referenced = ctx.referenced_extern.clone();
459    }
460    Ok(CompiledAsm {
461        template: emitter.template(),
462        const_args,
463        referenced_externs: referenced,
464        backend,
465        rust_lines: emitter.rust_lines.clone(),
466    })
467}
468
469/// Holds one compiled settings configuration.
470#[derive(Clone, Debug)]
471pub struct ConfiguredAsm {
472    /// Holds the `cfg` predicate selecting this configuration.
473    pub cfg_predicate: String,
474    /// Holds the resolved settings.
475    pub settings: SettingsMap,
476    /// Names the backend used.
477    pub backend: Backend,
478    /// Holds the compiled output.
479    pub compiled: CompiledAsm,
480}
481
482/// Compiles source text once per valid settings combination.
483///
484/// # Errors
485///
486/// - Returns an error if `src` fails to parse.
487/// - Returns an error if `options.globals` or `options.global_exports` name
488///   a label already declared incompatibly.
489/// - Returns an error if lowering a combination's resolved tree fails.
490pub fn compile_all_configurations(
491    src: &str,
492    file_name: &str,
493    options: &CompileOptions,
494    parser_options: &ParserOptions,
495) -> Result<Vec<ConfiguredAsm>, String> {
496    let mut session = ParseSession::new(parser_options.clone());
497    let ast = parse_data(src, file_name, &mut session).map_err(|e| e.to_string())?;
498    compile_all_configurations_ast(&ast, &mut session, options)
499}
500
501/// Compiles already-tokenized offlineasm source (the inline
502/// `offlineasm!{ ... }` macro form) once per valid settings combination.
503///
504/// # Errors
505///
506/// Same conditions as [`compile_all_configurations`].
507pub fn compile_all_configurations_tokens(
508    tokens: proc_macro2::TokenStream,
509    file_name: &str,
510    options: &CompileOptions,
511    parser_options: &ParserOptions,
512) -> Result<Vec<ConfiguredAsm>, String> {
513    let mut session = ParseSession::new(parser_options.clone());
514    let ast = parse_tokens(tokens, file_name, &mut session).map_err(|e| e.to_string())?;
515    compile_all_configurations_ast(&ast, &mut session, options)
516}
517
518/// Compiles a file via [`compile_all_configurations`].
519///
520/// Tracks includes relative to the file.
521///
522/// # Errors
523///
524/// - Returns an error if the file or one of its `include`s cannot be read
525///   or parsed.
526/// - Returns an error if `options.globals` or `options.global_exports` name
527///   a label already declared incompatibly.
528/// - Returns an error if lowering a combination's resolved tree fails.
529pub fn compile_all_configurations_file(
530    path: &Path,
531    options: &CompileOptions,
532    parser_options: &ParserOptions,
533) -> Result<Vec<ConfiguredAsm>, String> {
534    let mut session = ParseSession::new(parser_options.clone());
535    let ast = parse_file(path, &mut session).map_err(|e| e.to_string())?;
536    compile_all_configurations_ast(&ast, &mut session, options)
537}
538
539fn compile_all_configurations_ast(
540    ast: &Node,
541    session: &mut ParseSession,
542    options: &CompileOptions,
543) -> Result<Vec<ConfiguredAsm>, String> {
544    for g in &options.globals {
545        session
546            .labels
547            .set_as_global(g)
548            .map_err(|e| format!("globals: {}", e))?;
549    }
550    for g in &options.global_exports {
551        session
552            .labels
553            .set_as_global_export(g)
554            .map_err(|e| format!("exports: {}", e))?;
555    }
556    let non_backend_order = non_backend_settings(ast);
557    let combinations = compute_settings_combinations(ast);
558    let mut out = Vec::new();
559    for settings in &combinations {
560        let resolved = match for_settings(settings, ast)? {
561            Some(r) => r,
562            None => continue,
563        };
564
565        if is_ast_erroneous(&resolved.low_level_ast)? {
566            eprintln!(
567                "offlineasm: skipping configuration {}: invalid configuration (error node present)",
568                crate::settings::cpp_settings_test(&resolved.settings)
569            );
570            continue;
571        }
572
573        if !WORKING_BACKENDS.contains(&resolved.backend.as_str()) {
574            eprintln!(
575                "offlineasm: skipping configuration {}: backend {} is not supported yet",
576                crate::settings::cpp_settings_test(&resolved.settings),
577                resolved.backend
578            );
579            continue;
580        }
581        let backend = Backend::parse(&resolved.backend)?;
582        let cfg_predicate = rust_cfg_predicate(&resolved.settings, &non_backend_order);
583        let compiled = compile_resolved(
584            &resolved.low_level_ast,
585            backend,
586            session,
587            options,
588            &resolved.settings,
589        )?;
590        out.push(ConfiguredAsm {
591            cfg_predicate,
592            settings: resolved.settings,
593            backend,
594            compiled,
595        });
596    }
597    Ok(out)
598}
599
600fn resolve_offsets_ergo(
601    ast: &Node,
602    options: &CompileOptions,
603) -> Result<(Node, Vec<(String, String)>), String> {
604    // Collect keys in order: sorted offsets, sizes, consts.
605    let offsets = crate::offsets::offsets_list(ast);
606    let sizes = crate::offsets::sizes_list(ast);
607    let consts = crate::offsets::consts_list(ast);
608    let mut map: HashMap<String, i64> = HashMap::new();
609    let mut const_args: Vec<(String, String)> = Vec::new();
610    let mut symbolic: HashMap<String, (String, String)> = HashMap::new();
611    let mut counter = 0usize;
612
613    let mut rust_expr_for = |key: &str| -> (String, String) {
614        counter += 1;
615        let ident = format!("OFFLINE_ASM_CONST_{}", counter);
616        let expr = rust_expr_for_key(key);
617        (ident, expr)
618    };
619
620    for key in offsets.iter().chain(sizes.iter()).chain(consts.iter()) {
621        if let Some(v) = options.integer_offsets.get(key) {
622            map.insert(key.clone(), *v);
623        } else if options.auto_rust_offsets {
624            let (ident, expr) = rust_expr_for(key);
625            symbolic.insert(key.clone(), (ident.clone(), expr.clone()));
626            const_args.push((ident, expr));
627        } else {
628            return Err(format!("Could not find {} in offsets map", key));
629        }
630    }
631    if symbolic.is_empty() {
632        let resolved = resolve_offsets(ast, &map)?;
633        return Ok((resolved, vec![]));
634    }
635
636    let with_symbols = replace_with_symbols(ast, &symbolic)?;
637    let resolved = resolve_offsets_partial(&with_symbols, &map)?;
638    Ok((resolved, const_args))
639}
640
641/// Maps an offset key to its Rust const expression.
642///
643/// `sizeof T` becomes `size_of::<T>()`, `Struct::field` becomes
644/// `offset_of!(Struct, field)`, and const forms pass their expr as is.
645pub fn rust_expr_for_key(key: &str) -> String {
646    if let Some(rest) = key.strip_prefix("sizeof ") {
647        return format!("::core::mem::size_of::<{}>()", rest.trim());
648    }
649    if let Some(rest) = key
650        .strip_prefix("const { ")
651        .and_then(|s| s.strip_suffix(" }"))
652    {
653        return rest.trim().to_string();
654    }
655    if let Some(rest) = key
656        .strip_prefix("constexpr (")
657        .and_then(|s| s.strip_suffix(')'))
658    {
659        return rest.trim().to_string();
660    }
661    if let Some(pos) = key.rfind("::") {
662        let (s, f) = key.split_at(pos);
663        let field = &f[2..];
664        return format!("::core::mem::offset_of!({}, {})", s, field);
665    }
666    key.to_string()
667}
668
669fn replace_with_symbols(
670    ast: &Node,
671    symbolic: &HashMap<String, (String, String)>,
672) -> Result<Node, String> {
673    match ast {
674        Node::StructOffset { .. } | Node::Sizeof { .. } | Node::ConstExpr { .. } => {
675            let key = ast.dump();
676            if let Some((ident, expr)) = symbolic.get(&key) {
677                let expr = syn::parse_str::<syn::Expr>(expr).map_err(|e| e.to_string())?;
678                Ok(Node::RustConst {
679                    origin: ast
680                        .origin()
681                        .cloned()
682                        .unwrap_or_else(crate::ast::builtin_origin),
683                    ident: ident.clone(),
684                    expr,
685                })
686            } else {
687                Ok(ast.clone())
688            }
689        }
690        _ => {
691            let res: Result<Node, String> = (|| match ast {
692                Node::Add {
693                    origin,
694                    left,
695                    right,
696                } => Ok(Node::Add {
697                    origin: origin.clone(),
698                    left: Box::new(replace_with_symbols(left, symbolic)?),
699                    right: Box::new(replace_with_symbols(right, symbolic)?),
700                }),
701                Node::Sub {
702                    origin,
703                    left,
704                    right,
705                } => Ok(Node::Sub {
706                    origin: origin.clone(),
707                    left: Box::new(replace_with_symbols(left, symbolic)?),
708                    right: Box::new(replace_with_symbols(right, symbolic)?),
709                }),
710                Node::Mul {
711                    origin,
712                    left,
713                    right,
714                } => Ok(Node::Mul {
715                    origin: origin.clone(),
716                    left: Box::new(replace_with_symbols(left, symbolic)?),
717                    right: Box::new(replace_with_symbols(right, symbolic)?),
718                }),
719                Node::Neg { origin, child } => Ok(Node::Neg {
720                    origin: origin.clone(),
721                    child: Box::new(replace_with_symbols(child, symbolic)?),
722                }),
723                Node::Or {
724                    origin,
725                    left,
726                    right,
727                } => Ok(Node::Or {
728                    origin: origin.clone(),
729                    left: Box::new(replace_with_symbols(left, symbolic)?),
730                    right: Box::new(replace_with_symbols(right, symbolic)?),
731                }),
732                Node::And {
733                    origin,
734                    left,
735                    right,
736                } => Ok(Node::And {
737                    origin: origin.clone(),
738                    left: Box::new(replace_with_symbols(left, symbolic)?),
739                    right: Box::new(replace_with_symbols(right, symbolic)?),
740                }),
741                Node::Xor {
742                    origin,
743                    left,
744                    right,
745                } => Ok(Node::Xor {
746                    origin: origin.clone(),
747                    left: Box::new(replace_with_symbols(left, symbolic)?),
748                    right: Box::new(replace_with_symbols(right, symbolic)?),
749                }),
750                Node::Bitnot { origin, child } => Ok(Node::Bitnot {
751                    origin: origin.clone(),
752                    child: Box::new(replace_with_symbols(child, symbolic)?),
753                }),
754                Node::Address {
755                    origin,
756                    base,
757                    offset,
758                } => Ok(Node::Address {
759                    origin: origin.clone(),
760                    base: Box::new(replace_with_symbols(base, symbolic)?),
761                    offset: Box::new(replace_with_symbols(offset, symbolic)?),
762                }),
763                Node::BaseIndex {
764                    origin,
765                    base,
766                    index,
767                    scale,
768                    offset,
769                } => Ok(Node::BaseIndex {
770                    origin: origin.clone(),
771                    base: Box::new(replace_with_symbols(base, symbolic)?),
772                    index: Box::new(replace_with_symbols(index, symbolic)?),
773                    scale: Box::new(replace_with_symbols(scale, symbolic)?),
774                    offset: Box::new(replace_with_symbols(offset, symbolic)?),
775                }),
776                Node::AbsoluteAddress { origin, address } => Ok(Node::AbsoluteAddress {
777                    origin: origin.clone(),
778                    address: Box::new(replace_with_symbols(address, symbolic)?),
779                }),
780                Node::Instruction {
781                    origin,
782                    opcode,
783                    operands,
784                    annotation,
785                } => Ok(Node::Instruction {
786                    origin: origin.clone(),
787                    opcode: opcode.clone(),
788                    operands: operands
789                        .iter()
790                        .map(|o| replace_with_symbols(o, symbolic))
791                        .collect::<Result<Vec<_>, _>>()?,
792                    annotation: annotation.clone(),
793                }),
794                Node::Sequence { origin, list } => Ok(Node::Sequence {
795                    origin: origin.clone(),
796                    list: list
797                        .iter()
798                        .map(|n| replace_with_symbols(n, symbolic))
799                        .collect::<Result<Vec<_>, _>>()?,
800                }),
801                Node::ConstDecl {
802                    origin,
803                    variable,
804                    value,
805                } => Ok(Node::ConstDecl {
806                    origin: origin.clone(),
807                    variable: variable.clone(),
808                    value: Box::new(replace_with_symbols(value, symbolic)?),
809                }),
810                _ => Ok(ast.clone()),
811            })();
812            res
813        }
814    }
815}
816
817fn resolve_offsets_partial(ast: &Node, map: &HashMap<String, i64>) -> Result<Node, String> {
818    match ast {
819        Node::RustConst { .. } => Ok(ast.clone()),
820        Node::StructOffset { .. } | Node::Sizeof { .. } | Node::ConstExpr { .. } => {
821            let key = ast.dump();
822            match map.get(&key) {
823                Some(v) => Ok(Node::Immediate {
824                    origin: ast
825                        .origin()
826                        .cloned()
827                        .unwrap_or_else(crate::ast::builtin_origin),
828                    value: *v as i128,
829                }),
830                None => Err(format!("Could not find {} in offsets map", key)),
831            }
832        }
833        Node::Add {
834            origin,
835            left,
836            right,
837        } => Ok(Node::Add {
838            origin: origin.clone(),
839            left: Box::new(resolve_offsets_partial(left, map)?),
840            right: Box::new(resolve_offsets_partial(right, map)?),
841        }),
842        Node::Sub {
843            origin,
844            left,
845            right,
846        } => Ok(Node::Sub {
847            origin: origin.clone(),
848            left: Box::new(resolve_offsets_partial(left, map)?),
849            right: Box::new(resolve_offsets_partial(right, map)?),
850        }),
851        Node::Mul {
852            origin,
853            left,
854            right,
855        } => Ok(Node::Mul {
856            origin: origin.clone(),
857            left: Box::new(resolve_offsets_partial(left, map)?),
858            right: Box::new(resolve_offsets_partial(right, map)?),
859        }),
860        Node::Neg { origin, child } => Ok(Node::Neg {
861            origin: origin.clone(),
862            child: Box::new(resolve_offsets_partial(child, map)?),
863        }),
864        Node::Or {
865            origin,
866            left,
867            right,
868        } => Ok(Node::Or {
869            origin: origin.clone(),
870            left: Box::new(resolve_offsets_partial(left, map)?),
871            right: Box::new(resolve_offsets_partial(right, map)?),
872        }),
873        Node::And {
874            origin,
875            left,
876            right,
877        } => Ok(Node::And {
878            origin: origin.clone(),
879            left: Box::new(resolve_offsets_partial(left, map)?),
880            right: Box::new(resolve_offsets_partial(right, map)?),
881        }),
882        Node::Xor {
883            origin,
884            left,
885            right,
886        } => Ok(Node::Xor {
887            origin: origin.clone(),
888            left: Box::new(resolve_offsets_partial(left, map)?),
889            right: Box::new(resolve_offsets_partial(right, map)?),
890        }),
891        Node::Bitnot { origin, child } => Ok(Node::Bitnot {
892            origin: origin.clone(),
893            child: Box::new(resolve_offsets_partial(child, map)?),
894        }),
895        Node::Address {
896            origin,
897            base,
898            offset,
899        } => Ok(Node::Address {
900            origin: origin.clone(),
901            base: Box::new(resolve_offsets_partial(base, map)?),
902            offset: Box::new(resolve_offsets_partial(offset, map)?),
903        }),
904        Node::BaseIndex {
905            origin,
906            base,
907            index,
908            scale,
909            offset,
910        } => Ok(Node::BaseIndex {
911            origin: origin.clone(),
912            base: Box::new(resolve_offsets_partial(base, map)?),
913            index: Box::new(resolve_offsets_partial(index, map)?),
914            scale: Box::new(resolve_offsets_partial(scale, map)?),
915            offset: Box::new(resolve_offsets_partial(offset, map)?),
916        }),
917        Node::Instruction {
918            origin,
919            opcode,
920            operands,
921            annotation,
922        } => Ok(Node::Instruction {
923            origin: origin.clone(),
924            opcode: opcode.clone(),
925            operands: operands
926                .iter()
927                .map(|o| resolve_offsets_partial(o, map))
928                .collect::<Result<Vec<_>, _>>()?,
929            annotation: annotation.clone(),
930        }),
931        Node::Sequence { origin, list } => Ok(Node::Sequence {
932            origin: origin.clone(),
933            list: list
934                .iter()
935                .map(|n| resolve_offsets_partial(n, map))
936                .collect::<Result<Vec<_>, _>>()?,
937        }),
938        _ => Ok(ast.clone()),
939    }
940}
941
942/// Registers every label `ast` defines in `ctx`.
943pub fn collect_label_info(ast: &Node, ctx: &mut crate::backends::LowerCtx) {
944    match ast {
945        Node::Label { name, .. } => {
946            ctx.known_labels.insert(name.clone());
947        }
948        Node::LocalLabel { name, origin } => {
949            ctx.known_labels.insert(name.clone());
950
951            ctx.local_strings
952                .entry(name.clone())
953                .or_insert_with(|| crate::backends::LowerCtx::local_label_string(name, origin));
954        }
955        _ => {}
956    }
957    for child in ast.children() {
958        collect_label_info(child, ctx);
959    }
960}
961
962fn collect_rust_consts(node: &Node) -> Vec<(String, String)> {
963    let mut out = Vec::new();
964    collect_rust_consts_into(node, &mut out);
965    out
966}
967
968fn collect_rust_consts_into(node: &Node, out: &mut Vec<(String, String)>) {
969    if let Node::RustConst { ident, expr, .. } = node {
970        out.push((ident.clone(), quote::quote!(#expr).to_string()));
971    }
972    for child in node.children() {
973        collect_rust_consts_into(child, out);
974    }
975}
976
977#[allow(dead_code)]
978fn backend_set() -> BackendSet {
979    BackendSet::new()
980}