Skip to main content

sbpf_assembler/
lib.rs

1use {anyhow::Result, codespan::Files};
2
3// Parser
4pub mod parser;
5
6// Preprocessor (include + macro expansion)
7pub mod preprocessor;
8
9// Error handling and diagnostics
10pub mod errors;
11pub mod macros;
12
13// Intermediate Representation
14pub mod ast;
15pub mod astnode;
16pub mod dynsym;
17pub mod optimizer;
18
19// ELF header, program, section
20pub mod header;
21pub mod program;
22pub mod section;
23
24// Debug info
25pub mod debug;
26
27// WASM bindings
28#[cfg(target_arch = "wasm32")]
29pub mod wasm;
30
31pub use self::{
32    ast::OptimizationConfig,
33    astnode::ASTNode,
34    debug::DebugData,
35    errors::CompileError,
36    parser::{ProgramLayout, Token, parse, parse_with_optimization},
37    preprocessor::{
38        FileResolver, FsFileResolver, MockFileResolver, PreprocessResult, preprocess,
39        source_map::{FileRegistry, SourceMap, SourceOrigin},
40    },
41    program::Program,
42};
43
44/// sBPF target architecture
45#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
46pub enum SbpfArch {
47    V0,
48    #[default]
49    V3,
50}
51
52impl SbpfArch {
53    pub fn is_v3(&self) -> bool {
54        matches!(self, SbpfArch::V3)
55    }
56
57    pub fn e_flags(&self) -> u32 {
58        match self {
59            SbpfArch::V0 => 0,
60            SbpfArch::V3 => 3,
61        }
62    }
63}
64
65/// Debug mode configuration for the assembler
66#[derive(Debug, Clone)]
67pub struct DebugMode {
68    /// Source filename for debug info
69    pub filename: String,
70    /// Source directory for debug info
71    pub directory: String,
72}
73
74/// Options for the assembler
75#[derive(Debug, Clone, Default)]
76pub struct AssemblerOption {
77    /// sBPF target architecture
78    pub arch: SbpfArch,
79    /// Optional debug mode configuration
80    pub debug_mode: Option<DebugMode>,
81    /// Optional optimization and CFG diagnostic configuration
82    pub optimization: OptimizationConfig,
83}
84
85impl AssemblerOption {
86    /// Set the target architecture
87    pub fn with_arch(mut self, arch: SbpfArch) -> Self {
88        self.arch = arch;
89        self
90    }
91
92    /// Enable debug mode with the given config
93    pub fn with_debug_mode(mut self, debug_mode: DebugMode) -> Self {
94        self.debug_mode = Some(debug_mode);
95        self
96    }
97}
98
99/// An error enriched with source location information from preprocessing.
100/// Wraps a `CompileError` with the resolved original source location.
101#[derive(Debug)]
102pub struct AssemblerError {
103    pub error: CompileError,
104    pub origin: Option<SourceOrigin>,
105    /// Column offset (0-based) within the original line, if known.
106    pub column: Option<usize>,
107}
108
109impl std::fmt::Display for AssemblerError {
110    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111        write!(f, "{}", self.error)
112    }
113}
114
115impl std::error::Error for AssemblerError {
116    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
117        Some(&self.error)
118    }
119}
120
121/// Returned when assembly with preprocessing fails.
122/// Contains the errors and the file registry so callers can render
123/// diagnostics against the original source files.
124#[derive(Debug)]
125pub struct AssembleErrors {
126    pub errors: Vec<AssemblerError>,
127    pub file_registry: FileRegistry,
128}
129
130/// Assembler for SBPF assembly code
131#[derive(Debug, Clone)]
132pub struct Assembler {
133    options: AssemblerOption,
134}
135
136impl Assembler {
137    /// Create a new Assembler with the given options
138    pub fn new(options: AssemblerOption) -> Self {
139        Self { options }
140    }
141
142    /// Assemble source code directly (no preprocessing).
143    /// This is the original API -- macros and includes are not supported.
144    pub fn assemble(&self, source: &str) -> Result<Vec<u8>, Vec<CompileError>> {
145        let parse_result = match parse_with_optimization(
146            source,
147            self.options.arch,
148            self.options.optimization.clone(),
149        ) {
150            Ok(result) => result,
151            Err(errors) => {
152                return Err(errors);
153            }
154        };
155
156        // Build debug data if debug mode is enabled
157        let debug_data = if let Some(ref debug_mode) = self.options.debug_mode {
158            let (lines, labels) = collect_line_and_label_entries(source, &parse_result);
159            let code_end = parse_result.code_section.get_size();
160
161            Some(DebugData {
162                filename: debug_mode.filename.clone(),
163                directory: debug_mode.directory.clone(),
164                lines,
165                labels,
166                code_start: 0,
167                code_end,
168            })
169        } else {
170            None
171        };
172
173        let program = Program::from_parse_result(parse_result, debug_data);
174        let bytecode = program.emit_bytecode();
175        Ok(bytecode)
176    }
177
178    /// Assemble with preprocessing: resolves `.include` and expands `.macro` directives
179    /// before parsing. Errors include source location information from the source map,
180    /// and the file registry is returned so callers can render diagnostics against
181    /// original source files.
182    pub fn assemble_with_preprocess(
183        &self,
184        source: &str,
185        source_path: &str,
186        resolver: Option<&dyn FileResolver>,
187    ) -> Result<Vec<u8>, AssembleErrors> {
188        // Run preprocessor
189        let preprocess_result =
190            preprocess(source, source_path, resolver).map_err(|failure| AssembleErrors {
191                errors: failure
192                    .errors
193                    .into_iter()
194                    .map(|e| AssemblerError {
195                        error: e.error,
196                        origin: e.origin,
197                        column: None,
198                    })
199                    .collect(),
200                file_registry: failure.file_registry,
201            })?;
202
203        let expanded = &preprocess_result.expanded_source;
204        let source_map = &preprocess_result.source_map;
205
206        // Parse the expanded source
207        let parse_result = match parse_with_optimization(
208            expanded,
209            self.options.arch,
210            self.options.optimization.clone(),
211        ) {
212            Ok(result) => result,
213            Err(errors) => {
214                // Extract file registry from source map before moving errors
215                let file_registry = source_map.file_registry.clone();
216                return Err(AssembleErrors {
217                    errors: errors
218                        .into_iter()
219                        .map(|e| {
220                            let span = e.span();
221                            let origin = source_map.resolve_span(span, expanded).clone();
222                            // Compute column offset within the line from the
223                            // expanded source so we can highlight the right token.
224                            let col = expanded[..span.start]
225                                .rfind('\n')
226                                .map(|nl| span.start - nl - 1)
227                                .unwrap_or(span.start);
228                            AssemblerError {
229                                error: e,
230                                column: Some(col),
231                                origin: Some(origin),
232                            }
233                        })
234                        .collect(),
235                    file_registry,
236                });
237            }
238        };
239
240        // Build debug data if debug mode is enabled
241        let debug_data = if let Some(ref debug_mode) = self.options.debug_mode {
242            let (lines, labels) = collect_line_and_label_entries(expanded, &parse_result);
243            let code_end = parse_result.code_section.get_size();
244
245            Some(DebugData {
246                filename: debug_mode.filename.clone(),
247                directory: debug_mode.directory.clone(),
248                lines,
249                labels,
250                code_start: 0,
251                code_end,
252            })
253        } else {
254            None
255        };
256
257        let program = Program::from_parse_result(parse_result, debug_data);
258        let bytecode = program.emit_bytecode();
259        Ok(bytecode)
260    }
261
262    /// Convenience method: read a file from disk and assemble with full preprocessing.
263    pub fn assemble_file(&self, path: &std::path::Path) -> Result<Vec<u8>, AssembleErrors> {
264        let source = std::fs::read_to_string(path).map_err(|e| AssembleErrors {
265            errors: vec![AssemblerError {
266                error: CompileError::IncludeReadError {
267                    path: path.display().to_string(),
268                    reason: e.to_string(),
269                    span: 0..0,
270                    custom_label: Some("Failed to read source file".to_string()),
271                },
272                origin: None,
273                column: None,
274            }],
275            file_registry: FileRegistry::new(),
276        })?;
277
278        let source_path = path.to_string_lossy();
279        let resolver = FsFileResolver::new();
280        self.assemble_with_preprocess(&source, &source_path, Some(&resolver))
281    }
282}
283
284type LineEntry = (u64, u32); // (offset, line)
285type LabelEntry = (String, u64, u32); // (label, offset, line)
286
287/// Helper function to collect line and label entries
288fn collect_line_and_label_entries(
289    source: &str,
290    parse_result: &ProgramLayout,
291) -> (Vec<LineEntry>, Vec<LabelEntry>) {
292    let mut files: Files<&str> = Files::new();
293    let file_id = files.add("source", source);
294
295    let mut line_entries = Vec::new();
296    let mut label_entries = Vec::new();
297
298    for node in parse_result.code_section.get_nodes() {
299        match node {
300            ASTNode::Instruction {
301                instruction,
302                offset,
303            } => {
304                let line_index = files.line_index(file_id, instruction.span.start as u32);
305                let line_number = (line_index.to_usize() + 1) as u32;
306                line_entries.push((*offset, line_number));
307            }
308            ASTNode::Label { label, offset } => {
309                let line_index = files.line_index(file_id, label.span.start as u32);
310                let line_number = (line_index.to_usize() + 1) as u32;
311                label_entries.push((label.name.clone(), *offset, line_number));
312            }
313            _ => {}
314        }
315    }
316
317    for node in parse_result.data_section.get_nodes() {
318        if let ASTNode::ROData { rodata, offset } = node {
319            let line_index = files.line_index(file_id, rodata.span.start as u32);
320            let line_number = (line_index.to_usize() + 1) as u32;
321            label_entries.push((rodata.name.clone(), *offset, line_number));
322        }
323    }
324
325    (line_entries, label_entries)
326}
327
328#[cfg(test)]
329pub fn assemble(source: &str) -> Result<Vec<u8>, Vec<CompileError>> {
330    let options = AssemblerOption::default();
331    let assembler = Assembler::new(options);
332    assembler.assemble(source)
333}
334
335#[cfg(test)]
336pub fn assemble_with_debug_data(
337    source: &str,
338    filename: &str,
339    directory: &str,
340) -> Result<Vec<u8>, Vec<CompileError>> {
341    let options = AssemblerOption::default().with_debug_mode(DebugMode {
342        filename: filename.to_string(),
343        directory: directory.to_string(),
344    });
345    let assembler = Assembler::new(options);
346    assembler.assemble(source)
347}
348
349#[cfg(test)]
350mod tests {
351    use super::*;
352
353    #[test]
354    fn test_assemble_success() {
355        let source = "exit";
356        let result = assemble(source);
357        assert!(result.is_ok());
358        let bytecode = result.unwrap();
359        assert!(!bytecode.is_empty());
360    }
361
362    #[test]
363    fn test_assemble_parse_error() {
364        let source = "invalid_xyz";
365        let result = assemble(source);
366        assert!(result.is_err());
367    }
368
369    #[test]
370    fn test_parse_error_has_correct_span() {
371        // Verify parse errors point to the actual error position,
372        // not span 0..len (which would lose position info for source maps).
373        let source = ".rodata\n    thing2: .bogus 5\n.text\nentrypoint:\n    exit\n";
374        let result = assemble(source);
375        assert!(result.is_err());
376        let errors = result.unwrap_err();
377        let span = errors[0].span();
378        // The error should point somewhere near ".bogus" (byte ~20), NOT 0..len
379        assert!(
380            span.start > 0,
381            "Error span should not start at 0, got {:?}",
382            span
383        );
384        assert!(
385            span.end < source.len(),
386            "Error span should not cover entire source, got {:?}",
387            span
388        );
389        // Verify the span actually points at ".bogus", not at "thing2"
390        let error_text = &source[span.start..span.end.min(source.len())];
391        assert!(
392            error_text.starts_with('.'),
393            "Error should point at '.bogus', but points at: '{}'",
394            &source[span.start..span.start + 10.min(source.len() - span.start)]
395        );
396    }
397
398    #[test]
399    fn test_assemble_with_equ_directive() {
400        let source = r#"
401        .globl entrypoint
402        .equ MY_CONST, 42
403        entrypoint:
404            mov64 r1, MY_CONST
405            exit
406        "#;
407        let result = assemble(source);
408        assert!(result.is_ok());
409    }
410
411    #[test]
412    fn test_assemble_const_expr_overflow_errors() {
413        for expr in ["BIG + 1", "BIG * 2"] {
414            let source = format!(
415                r#"
416                .globl entrypoint
417                .equ BIG, 0x7FFFFFFFFFFFFFFF
418                entrypoint:
419                    lddw r1, {expr}
420                    exit
421                "#
422            );
423            let result = assemble(&source);
424            assert!(result.is_err(), "expected error for '{expr}'");
425            assert!(matches!(
426                result.unwrap_err().first(),
427                Some(CompileError::ArithmeticError { .. })
428            ));
429        }
430    }
431
432    #[test]
433    fn test_assemble_const_expr_div_by_zero_errors() {
434        let source = r#"
435        .globl entrypoint
436        entrypoint:
437            lddw r1, 8 / 0
438            exit
439        "#;
440        let result = assemble(source);
441        assert!(result.is_err());
442        let errors = result.unwrap_err();
443        assert!(matches!(
444            errors.first(),
445            Some(CompileError::ArithmeticError { .. })
446        ));
447        // The diagnostic must point at the offending expression, not 0..len.
448        assert!(errors[0].span().start > 0);
449    }
450
451    #[test]
452    fn test_assemble_const_expr_overflow_in_directive_errors() {
453        // The directive-value evaluator must also be overflow-safe.
454        let source = r#"
455        .globl entrypoint
456        .equ BAD, 0x7FFFFFFFFFFFFFFF + 1
457        entrypoint:
458            lddw r1, BAD
459            exit
460        "#;
461        let result = assemble(source);
462        assert!(result.is_err());
463        assert!(matches!(
464            result.unwrap_err().first(),
465            Some(CompileError::ArithmeticError { .. })
466        ));
467    }
468
469    #[test]
470    fn test_assemble_valid_const_expr_still_folds() {
471        // Regression: in-range arithmetic must keep folding correctly.
472        let source = r#"
473        .globl entrypoint
474        .equ A, 0x10
475        .equ B, 0x20
476        entrypoint:
477            lddw r1, A * 4 + B
478            exit
479        "#;
480        assert!(assemble(source).is_ok());
481    }
482
483    #[test]
484    fn test_assemble_const_expr_precedence() {
485        // `*` and `/` bind tighter than `+` and `-`, and equal precedence folds
486        // left to right, both in `.equ` and in operands.
487        let program = |expr: &str| {
488            let source = format!(
489                r#"
490        .globl entrypoint
491        .equ C, {expr}
492        entrypoint:
493            mov64 r1, C
494            mov64 r2, {expr}
495            exit
496        "#
497            );
498            assemble(&source).unwrap()
499        };
500        for (expr, value) in [
501            ("10 - 3 - 2", "5"),
502            ("100 / 10 / 5", "2"),
503            ("2 * 3 + 4", "10"),
504            ("2 + 3 * 4", "14"),
505            ("20 - 6 / 2", "17"),
506            ("(2 + 3) * 4", "20"),
507        ] {
508            assert_eq!(
509                program(expr),
510                program(value),
511                "{expr} should fold to {value}"
512            );
513        }
514    }
515
516    #[test]
517    fn test_assemble_duplicate_label_error() {
518        let source = r#"
519        .globl entrypoint
520        entrypoint:
521            mov64 r1, 1
522        entrypoint:
523            exit
524        "#;
525        let result = assemble(source);
526        assert!(result.is_err());
527        let errors = result.unwrap_err();
528        assert!(!errors.is_empty());
529    }
530
531    #[test]
532    fn test_assemble_undefined_label_error() {
533        let instructions = [
534            "mov64 r1, UNDEF",
535            "jeq r1, UNDEF, done",
536            "jeq32 r1, UNDEF, done",
537            "stb [r1+0], UNDEF",
538            "stb [r1+UNDEF], 0x1",
539            "stxb [r1+UNDEF], r2",
540            "ldxb r1, [r2+UNDEF]",
541            "call UNDEF",
542            "lddw r1, UNDEF",
543            "ja UNDEF",
544            "jeq r1, 0x1, UNDEF",
545            "jeq r1, r2, UNDEF",
546            "jeq32 r1, 0x1, UNDEF",
547            "jeq32 r1, r2, UNDEF",
548        ];
549
550        for instruction in instructions {
551            let source = format!(
552                r#"
553                .globl e
554                e:
555                    {instruction}
556                    exit
557                done:
558                    exit
559                "#
560            );
561            let instruction_start = source.find(instruction).unwrap();
562            let instruction_end = instruction_start + instruction.len();
563            let errors = assemble(&source).unwrap_err();
564
565            assert_eq!(errors.len(), 1, "unexpected errors for `{instruction}`");
566            match &errors[0] {
567                CompileError::UndefinedLabel { label, span, .. } => {
568                    assert_eq!(label, "UNDEF", "unexpected label for `{instruction}`");
569                    assert_eq!(
570                        span,
571                        &(instruction_start..instruction_end),
572                        "unexpected span for `{instruction}`"
573                    );
574                }
575                error => {
576                    panic!("unexpected error for `{instruction}`: {error:?}")
577                }
578            }
579        }
580    }
581
582    #[test]
583    fn test_assemble_extern_directive() {
584        let source = r#"
585        .globl entrypoint
586        .extern my_extern_symbol
587        entrypoint:
588            exit
589        "#;
590        let result = assemble(source);
591        assert!(result.is_ok());
592    }
593
594    #[test]
595    fn test_assemble_rodata_section() {
596        let source = r#"
597        .globl entrypoint
598        .rodata
599        my_data: .ascii "hello"
600        .text
601        entrypoint:
602            exit
603        "#;
604        let result = assemble(source);
605        assert!(result.is_ok());
606    }
607
608    #[test]
609    fn test_assemble_rodata_byte() {
610        let source = r#"
611        .globl entrypoint
612        .rodata
613        my_byte: .byte 0x42
614        .text
615        entrypoint:
616            exit
617        "#;
618        let result = assemble(source);
619        assert!(result.is_ok());
620    }
621
622    #[test]
623    fn test_assemble_rodata_multiple_bytes() {
624        let source = r#"
625        .globl entrypoint
626        .rodata
627        my_bytes: .byte 0x01, 0x02, 0x03, 0x04
628        .text
629        entrypoint:
630            exit
631        "#;
632        let result = assemble(source);
633        assert!(result.is_ok());
634    }
635
636    #[test]
637    fn test_assemble_rodata_mixed() {
638        let source = r#"
639        .globl entrypoint
640        .rodata
641        data1: .byte 0x42
642        data2: .ascii "test"
643        .text
644        entrypoint:
645            exit
646        "#;
647        let result = assemble(source);
648        assert!(result.is_ok());
649    }
650
651    #[test]
652    fn test_assemble_rodata_out_of_range_errors() {
653        for data in [
654            "data: .byte 256",
655            "data: .byte -129",
656            "data: .short 0x10000",
657            "data: .int 0x100000000",
658            "data:\n.byte 0x1ff",
659        ] {
660            let source = format!(".globl entrypoint\nentrypoint:\n    exit\n.rodata\n{data}\n");
661            let result = assemble(&source);
662            assert!(
663                matches!(
664                    result.as_ref().map_err(|e| e.first()),
665                    Err(Some(CompileError::OutOfRangeLiteral { .. }))
666                ),
667                "expected out of range error for '{data}', got {:?}",
668                result.err()
669            );
670        }
671    }
672
673    #[test]
674    fn test_assemble_most_negative_offset_and_imm() {
675        // Negating 0x8000 or 0x8000000000000000 doesn't fit, so these must match the
676        // forms that never negate.
677        let assemble_ix = |ix: &str| {
678            let source = format!(".equ MIN, -32768\n.equ OFF, 0x8000\nentrypoint:\n{ix}\nexit\n");
679            assemble(&source)
680        };
681        for (ix, same_as) in [
682            ("ldxdw r2, [r1-32768]", "ldxdw r2, [r1+MIN]"),
683            ("ldxdw r2, [r1-0x8000]", "ldxdw r2, [r1+MIN]"),
684            ("ldxdw r2, [r1-OFF]", "ldxdw r2, [r1+MIN]"),
685            ("stxdw [r1-32768], r2", "stxdw [r1+MIN], r2"),
686            (
687                "lddw r1, -0x8000000000000000",
688                "lddw r1, -9223372036854775808",
689            ),
690        ] {
691            assert_eq!(
692                assemble_ix(ix).unwrap(),
693                assemble_ix(same_as).unwrap(),
694                "{ix}"
695            );
696        }
697    }
698
699    #[test]
700    fn test_assemble_jump_operations() {
701        let source = r#"
702        .globl entrypoint
703        entrypoint:
704            jeq r1, 0, +1
705            ja +2
706        target:
707            jne r1, r2, target
708            exit
709        "#;
710        let result = assemble(source);
711        assert!(result.is_ok());
712    }
713
714    #[test]
715    fn test_assemble_jump32_v3() {
716        let source = r#"
717        .globl entrypoint
718        entrypoint:
719            jeq32 r1, 0, +1
720            jset32 r1, r2, +1
721            exit
722        "#;
723        let assembler = Assembler::new(AssemblerOption::default());
724        let result = assembler.assemble(source);
725        assert!(result.is_ok());
726    }
727
728    #[test]
729    fn test_assemble_jump32_v0() {
730        let source = r#"
731        .globl entrypoint
732        entrypoint:
733            jeq32 r1, 0, +1
734            exit
735        "#;
736        let assembler = Assembler::new(AssemblerOption::default().with_arch(SbpfArch::V0));
737        let result = assembler.assemble(source);
738        // jmp32 operations should not work in v0
739        assert!(result.is_err());
740    }
741
742    #[test]
743    fn test_assemble_llvm_jump32_v3() {
744        let source = r#"
745        .globl entrypoint
746        entrypoint:
747            if w1 == 0 goto +1
748            if w1 & w2 goto +1
749            exit
750        "#;
751        let assembler = Assembler::new(AssemblerOption::default());
752        let result = assembler.assemble(source);
753        assert!(result.is_ok(),);
754    }
755
756    #[test]
757    fn test_assemble_llvm_jump32_v0() {
758        let source = r#"
759        .globl entrypoint
760        entrypoint:
761            if w1 == 0 goto +1
762            exit
763        "#;
764        let assembler = Assembler::new(AssemblerOption::default().with_arch(SbpfArch::V0));
765        let result = assembler.assemble(source);
766        // jmp32 operations should not work in v0
767        assert!(result.is_err());
768    }
769
770    #[test]
771    fn test_assemble_offset_expression() {
772        let source = r#"
773        .globl entrypoint
774        .equ BASE, 100
775        entrypoint:
776            mov64 r1, BASE+10
777            exit
778        "#;
779        let result = assemble(source);
780        assert!(result.is_ok());
781    }
782
783    #[test]
784    fn test_assemble_equ_expression() {
785        let source = r#"
786        .globl entrypoint
787        .equ BASE, 100
788        .equ OFFSET, 20
789        .equ COMPUTED, BASE
790        entrypoint:
791            mov64 r1, BASE
792            mov64 r2, OFFSET
793            mov64 r3, COMPUTED
794            exit
795        "#;
796        let result = assemble(source);
797        assert!(result.is_ok());
798    }
799
800    #[test]
801    fn test_assemble_label_arithmetic_rodata_length() {
802        // The primary use case: compute string length via label subtraction
803        let source = r#"
804        .globl entrypoint
805        .rodata
806        msg: .ascii "Hello"
807        msg_end:
808        .text
809        entrypoint:
810            lddw r1, msg
811            mov64 r2, msg_end - msg
812            exit
813        "#;
814        let result = assemble(source);
815        assert!(result.is_ok(), "Failed: {:?}", result.err());
816    }
817
818    #[test]
819    fn test_assemble_label_arithmetic_with_offset() {
820        // Label arithmetic with additional constant offset
821        let source = r#"
822        .globl entrypoint
823        .rodata
824        msg: .ascii "Hello!"
825        msg_end:
826        .text
827        entrypoint:
828            lddw r1, msg
829            mov64 r2, msg_end - msg - 1
830            exit
831        "#;
832        let result = assemble(source);
833        assert!(result.is_ok(), "Failed: {:?}", result.err());
834    }
835
836    #[test]
837    fn test_assemble_label_arithmetic_text_section() {
838        // Label arithmetic works in the text section too
839        let source = r#"
840        .globl entrypoint
841        entrypoint:
842            mov64 r1, 1
843        middle:
844            mov64 r2, 2
845        end:
846            mov64 r3, end - entrypoint
847            exit
848        "#;
849        let result = assemble(source);
850        assert!(result.is_ok(), "Failed: {:?}", result.err());
851    }
852
853    #[test]
854    fn test_assemble_label_arithmetic_forward_reference() {
855        // Text section before rodata — forward references to rodata labels
856        let source = r#"
857        .globl entrypoint
858        entrypoint:
859            lddw r1, message
860            mov64 r2, message_end - message
861            call sol_log_
862            exit
863            lddw r10, 1
864        .rodata
865            message: .ascii "Hello, Solana!"
866            message_end:
867        "#;
868        let result = assemble(source);
869        assert!(
870            result.is_ok(),
871            "Forward reference failed: {:?}",
872            result.err()
873        );
874    }
875
876    #[test]
877    fn test_assemble_label_arithmetic_multiline_rodata() {
878        // Rodata label and directive on separate lines (as from macro expansion)
879        let source = r#"
880        .globl entrypoint
881        entrypoint:
882            lddw r1, message
883            mov64 r2, message_end - message
884            call sol_log_
885            exit
886        .rodata
887        message:
888            .ascii "Hello, Solana!"
889        message_end:
890        "#;
891        let result = assemble(source);
892        assert!(
893            result.is_ok(),
894            "Multi-line rodata failed: {:?}",
895            result.err()
896        );
897    }
898
899    #[test]
900    fn test_assemble_label_arithmetic_macro_e2e() {
901        // Full end-to-end test with macro expansion + label arithmetic
902        let source = r#"
903.macro DEF_STR name, text
904\name:
905    .ascii \text
906\name\()_end:
907.endm
908
909.macro SOL_LOG name
910    lddw r1, \name
911    mov64 r2, \name\()_end - \name
912    call sol_log_
913.endm
914
915.globl entrypoint
916entrypoint:
917    SOL_LOG message
918    exit
919.rodata
920    DEF_STR message, "Hello, Solana!"
921"#;
922        let assembler = Assembler::new(AssemblerOption::default());
923        let result = assembler.assemble_with_preprocess(source, "test.s", None);
924        assert!(result.is_ok(), "Macro e2e failed: {:?}", result.err());
925    }
926
927    #[test]
928    fn test_assemble_macro_call_with_trailing_comment() {
929        // The comment must not become part of the last argument: `\b - \a`
930        // would expand to `4 ; r2 = 3 - 1` and assemble as `mov64 r2, 4`.
931        let source = r#"
932.macro SUB_LEN a, b
933    mov64 r2, \b - \a
934.endm
935.globl entrypoint
936entrypoint:
937    SUB_LEN 1, 4 ; r2 = 3
938    exit
939"#;
940        let assembler = Assembler::new(AssemblerOption::default());
941        let result = assembler.assemble_with_preprocess(source, "test.s", None);
942        let expected = assemble(".globl entrypoint\nentrypoint:\n    mov64 r2, 3\n    exit\n");
943        assert_eq!(result.unwrap(), expected.unwrap());
944    }
945
946    #[test]
947    fn test_assemble_directives_with_trailing_comments() {
948        let source = r#"
949.macro TWICE x # repeats x
950.rept 2 // twice
951    mov64 r1, \x
952.endr ; rept
953.endm # TWICE
954.globl entrypoint
955entrypoint:
956.if 1 # always
957    TWICE 7
958.endif ; if
959.if 0 // never
960    mov64 r0, 1
961.else # otherwise
962.irp reg, r3, r4 ; each
963    mov64 \reg, 2
964.endr // irp
965.endif # if/else
966    exit
967"#;
968        let assembler = Assembler::new(AssemblerOption::default());
969        let result = assembler.assemble_with_preprocess(source, "test.s", None);
970        let expected = assemble(
971            r#"
972.globl entrypoint
973entrypoint:
974    mov64 r1, 7
975    mov64 r1, 7
976    mov64 r3, 2
977    mov64 r4, 2
978    exit
979"#,
980        );
981        assert_eq!(result.unwrap(), expected.unwrap());
982    }
983
984    #[test]
985    fn test_assemble_label_arithmetic_cross_section_error() {
986        // Cross-section arithmetic should fail
987        let source = r#"
988        .globl entrypoint
989        .rodata
990        msg: .ascii "Hello"
991        .text
992        entrypoint:
993            mov64 r1, msg - entrypoint
994            exit
995        "#;
996        let result = assemble(source);
997        assert!(result.is_err(), "Cross-section arithmetic should fail");
998    }
999
1000    #[test]
1001    fn test_assemble_label_arithmetic_complex_expression() {
1002        // More complex expression with multiple rodata entries
1003        let source = r#"
1004        .globl entrypoint
1005        .rodata
1006        str1: .ascii "Hello"
1007        str2: .ascii " World"
1008        str2_end:
1009        .text
1010        entrypoint:
1011            lddw r1, str2
1012            mov64 r2, str2_end - str2
1013            exit
1014        "#;
1015        let result = assemble(source);
1016        assert!(result.is_ok(), "Failed: {:?}", result.err());
1017    }
1018
1019    #[test]
1020    fn test_parse_error_column_through_preprocess() {
1021        // Verify the column offset is correctly computed through the
1022        // preprocessing pipeline so errors point at the invalid token,
1023        // not at the label before it.
1024        let source = ".globl e\ne:\n    exit\n.rodata\n    thing1: .bogus 5\n";
1025        let assembler = Assembler::new(AssemblerOption::default());
1026        let result = assembler.assemble_with_preprocess(source, "test.s", None);
1027        assert!(result.is_err());
1028        let errors = result.unwrap_err();
1029        let err = &errors.errors[0];
1030        let origin = err.origin.as_ref().expect("Expected origin");
1031        let registry = &errors.file_registry;
1032
1033        // Verify the column points at ".bogus", not "thing1"
1034        let col = err.column.expect("Expected column info");
1035        let line_start = registry.line_byte_offset(origin.file_id, origin.line);
1036        let content = registry.content(origin.file_id);
1037        let at_col = &content[line_start + col..];
1038        assert!(
1039            at_col.starts_with(".bogus"),
1040            "Expected column to point at '.bogus', but points at: '{}'",
1041            &at_col[..at_col.len().min(20)]
1042        );
1043    }
1044
1045    #[test]
1046    fn test_parse_error_column_with_include_and_macros() {
1047        // Simulate the user's actual scenario: .include with macros,
1048        // then an invalid directive on a later line.
1049        use std::collections::HashMap;
1050
1051        struct TestResolver {
1052            files: HashMap<String, String>,
1053        }
1054        impl FileResolver for TestResolver {
1055            fn resolve(&self, path: &str, _base: &str) -> Result<String, std::io::Error> {
1056                self.files.get(path).cloned().ok_or_else(|| {
1057                    std::io::Error::new(
1058                        std::io::ErrorKind::NotFound,
1059                        format!("not found: {}", path),
1060                    )
1061                })
1062            }
1063        }
1064
1065        let mut files = HashMap::new();
1066        files.insert(
1067            "syscalls/sol_log.s".to_string(),
1068            r#".macro SOL_LOG name
1069    lddw r1, \name
1070    mov64 r2, \name\()_end - \name
1071    call sol_log_
1072.endm
1073
1074.macro DEF_STR name, text
1075\name:
1076    .ascii \text
1077\name\()_end:
1078.endm
1079"#
1080            .to_string(),
1081        );
1082
1083        let source = r#".include "syscalls/sol_log.s"
1084.globl e
1085e:
1086    SOL_LOG message
1087.rodata
1088    DEF_STR message, "TEST"
1089    thing2: .int 1
1090    thing1: .bogus "text"
1091"#;
1092        let resolver = TestResolver { files };
1093        let assembler = Assembler::new(AssemblerOption::default());
1094        let result = assembler.assemble_with_preprocess(source, "main.s", Some(&resolver));
1095        assert!(result.is_err());
1096        let errors = result.unwrap_err();
1097        let err = &errors.errors[0];
1098        let origin = err.origin.as_ref().expect("Expected origin");
1099        let registry = &errors.file_registry;
1100
1101        // Verify origin points to main.s, not the included file
1102        assert_eq!(registry.path(origin.file_id), "main.s");
1103
1104        // Verify the column points at ".bogus"
1105        let col = err.column.expect("Expected column info");
1106        let line_start = registry.line_byte_offset(origin.file_id, origin.line);
1107        let content = registry.content(origin.file_id);
1108        let at_col = &content[line_start + col..];
1109        assert!(
1110            at_col.starts_with(".bogus"),
1111            "Expected column to point at '.bogus', but at line {} col {}, points at: '{}'",
1112            origin.line,
1113            col,
1114            &at_col[..at_col.len().min(20)]
1115        );
1116    }
1117
1118    #[test]
1119    fn test_assemble_with_debug_data() {
1120        let source = r#".equ MSG_LEN, 14
1121
1122.globl entrypoint
1123entrypoint:
1124  lddw r1, message
1125  mov64 r2, MSG_LEN
1126  call sol_log_
1127  exit
1128.rodata
1129  message: .ascii "Hello, Solana!"
1130"#;
1131        let result = assemble_with_debug_data(source, "hello_solana.s", "/tmp");
1132        assert!(result.is_ok());
1133        let bytecode = result.unwrap();
1134
1135        // Verify the ELF has all debug sections.
1136        let bytecode_str = String::from_utf8_lossy(&bytecode);
1137        assert!(
1138            bytecode_str.contains(".debug_abbrev"),
1139            "Missing .debug_abbrev section"
1140        );
1141        assert!(
1142            bytecode_str.contains(".debug_info"),
1143            "Missing .debug_info section"
1144        );
1145        assert!(
1146            bytecode_str.contains(".debug_line"),
1147            "Missing .debug_line section"
1148        );
1149        assert!(
1150            bytecode_str.contains(".debug_line_str"),
1151            "Missing .debug_line_str section"
1152        );
1153    }
1154}