Skip to main content

sbpf_assembler/parser/
common.rs

1use {
2    super::{Rule, Section},
3    crate::{SbpfArch, errors::CompileError},
4    either::Either,
5    pest::iterators::Pair,
6    sbpf_common::{
7        inst_param::{Number, Register},
8        instruction::Instruction,
9        opcode::Opcode,
10    },
11    std::{collections::HashMap, ops::Range},
12};
13
14// Shared parse functions.
15
16pub fn parse_register(pair: Pair<Rule>) -> Result<Register, CompileError> {
17    let reg_str = pair.as_str();
18    let span = pair.as_span();
19
20    if let Ok(n) = reg_str[1..].parse::<u8>() {
21        Ok(Register { n })
22    } else {
23        Err(CompileError::InvalidRegister {
24            register: reg_str.to_string(),
25            span: span.start()..span.end(),
26            custom_label: None,
27        })
28    }
29}
30
31pub(crate) fn parse_operand(
32    pair: Pair<Rule>,
33    const_map: &HashMap<String, Number>,
34    label_offset_map: &HashMap<String, (Number, Section)>,
35) -> Result<Either<String, Number>, CompileError> {
36    let span = pair.as_span();
37    let span_range = span.start()..span.end();
38
39    // operand = { expression }, so unwrap the inner expression
40    let expr = pair
41        .into_inner()
42        .next()
43        .ok_or_else(|| CompileError::ParseError {
44            error: "Invalid operand".to_string(),
45            span: span_range.clone(),
46            custom_label: None,
47        })?;
48
49    eval_operand_expression(expr, const_map, label_offset_map)
50}
51
52/// Evaluate an expression used as an instruction operand.
53///
54/// - A bare symbol not found in const_map or label_offset_map is returned as
55///   `Either::Left` for deferred resolution (e.g. `lddw r1, label`).
56/// - Multi-term expressions (arithmetic) resolve all symbols immediately from
57///   const_map and label_offset_map. Labels must be in the same section.
58fn eval_operand_expression(
59    pair: Pair<Rule>,
60    const_map: &HashMap<String, Number>,
61    label_offset_map: &HashMap<String, (Number, Section)>,
62) -> Result<Either<String, Number>, CompileError> {
63    let span = pair.as_span();
64    let span_range = span.start()..span.end();
65
66    let mut terms: Vec<Number> = Vec::new();
67    let mut ops: Vec<&str> = Vec::new();
68    let mut is_single_symbol = false;
69    let mut single_symbol_name = String::new();
70    let mut label_sections: Vec<(String, Section)> = Vec::new();
71
72    let inner_pairs: Vec<_> = pair.into_inner().collect();
73
74    // Check if this is a single bare symbol (no operators)
75    if inner_pairs.len() == 1 && inner_pairs[0].as_rule() == Rule::term {
76        let term_inners: Vec<_> = inner_pairs[0].clone().into_inner().collect();
77        if term_inners.len() == 1 && term_inners[0].as_rule() == Rule::symbol {
78            is_single_symbol = true;
79            single_symbol_name = term_inners[0].as_str().to_string();
80        }
81    }
82
83    // For a bare symbol not in const_map, defer resolution
84    if is_single_symbol {
85        if let Some(value) = const_map.get(&single_symbol_name) {
86            return Ok(Either::Right(value.clone()));
87        }
88        // Not in const_map — return as unresolved for build_program to handle
89        return Ok(Either::Left(single_symbol_name));
90    }
91
92    // Multi-term expression: resolve everything now
93    for inner in inner_pairs {
94        match inner.as_rule() {
95            Rule::term => {
96                let val =
97                    eval_operand_term(inner, const_map, label_offset_map, &mut label_sections)?;
98                terms.push(val);
99            }
100            Rule::bin_op => {
101                ops.push(match inner.as_str() {
102                    "+" => "+",
103                    "-" => "-",
104                    "*" => "*",
105                    "/" => "/",
106                    _ => "+",
107                });
108            }
109            _ => {}
110        }
111    }
112
113    // Bounds check: all labels in the expression must be from the same section
114    if label_sections.len() > 1 {
115        let first_section = label_sections[0].1;
116        for (name, section) in &label_sections[1..] {
117            if *section != first_section {
118                return Err(CompileError::CrossSectionArithmetic {
119                    label1: label_sections[0].0.clone(),
120                    label2: name.clone(),
121                    span: span_range,
122                    custom_label: None,
123                });
124            }
125        }
126    }
127
128    if terms.is_empty() {
129        return Err(CompileError::ParseError {
130            error: "Invalid operand expression".to_string(),
131            span: span_range,
132            custom_label: None,
133        });
134    }
135
136    fold_binary_ops(terms, &ops, span_range).map(Either::Right)
137}
138
139/// Fold `terms[0] ops[0] terms[1] ...` into one value. `*` and `/` bind tighter
140/// than `+` and `-`, and operators of equal precedence fold left to right.
141pub(crate) fn fold_binary_ops(
142    terms: Vec<Number>,
143    ops: &[&str],
144    span: Range<usize>,
145) -> Result<Number, CompileError> {
146    let mut terms = terms.into_iter();
147    let mut product = terms.next().ok_or_else(|| CompileError::ParseError {
148        error: "Invalid expression".to_string(),
149        span: span.clone(),
150        custom_label: None,
151    })?;
152    // The left side of a pending `+` or `-`, folded once the `*`/`/` run on its
153    // right side is done.
154    let mut sum: Option<(Number, &str)> = None;
155
156    for (op, rhs) in ops.iter().copied().zip(terms) {
157        if matches!(op, "*" | "/") {
158            product = apply_binary_op(op, &product, &rhs, &span)?;
159        } else {
160            let lhs = match sum.take() {
161                Some((lhs, sum_op)) => apply_binary_op(sum_op, &lhs, &product, &span)?,
162                None => product,
163            };
164            sum = Some((lhs, op));
165            product = rhs;
166        }
167    }
168
169    match sum {
170        Some((lhs, op)) => apply_binary_op(op, &lhs, &product, &span),
171        None => Ok(product),
172    }
173}
174
175fn apply_binary_op(
176    op: &str,
177    lhs: &Number,
178    rhs: &Number,
179    span: &Range<usize>,
180) -> Result<Number, CompileError> {
181    let folded = match op {
182        "+" => lhs.checked_add(rhs),
183        "-" => lhs.checked_sub(rhs),
184        "*" => lhs.checked_mul(rhs),
185        "/" => lhs.checked_div(rhs),
186        _ => Some(lhs.clone()),
187    };
188    folded.ok_or_else(|| {
189        let detail = if op == "/" && rhs.to_i64() == 0 {
190            "division by zero in constant expression".to_string()
191        } else {
192            format!("arithmetic overflow in constant expression ('{op}')")
193        };
194        CompileError::ArithmeticError {
195            error: detail,
196            span: span.clone(),
197            custom_label: None,
198        }
199    })
200}
201
202fn eval_operand_term(
203    pair: Pair<Rule>,
204    const_map: &HashMap<String, Number>,
205    label_offset_map: &HashMap<String, (Number, Section)>,
206    label_sections: &mut Vec<(String, Section)>,
207) -> Result<Number, CompileError> {
208    let span = pair.as_span();
209    let span_range = span.start()..span.end();
210
211    for inner in pair.into_inner() {
212        match inner.as_rule() {
213            Rule::expression => {
214                // Parenthesized sub-expression — recurse, but must fully resolve
215                let result = eval_operand_expression(inner, const_map, label_offset_map)?;
216                return match result {
217                    Either::Right(val) => Ok(val),
218                    Either::Left(name) => Err(CompileError::ParseError {
219                        error: format!(
220                            "Cannot use unresolved symbol '{}' in arithmetic expression",
221                            name
222                        ),
223                        span: span_range,
224                        custom_label: None,
225                    }),
226                };
227            }
228            Rule::number => {
229                return parse_number(inner);
230            }
231            Rule::symbol => {
232                let name = inner.as_str().to_string();
233                if let Some(value) = const_map.get(&name) {
234                    return Ok(value.clone());
235                }
236                if let Some((value, section)) = label_offset_map.get(&name) {
237                    label_sections.push((name, *section));
238                    return Ok(value.clone());
239                }
240                return Err(CompileError::ParseError {
241                    error: format!("Undefined symbol '{}' in arithmetic expression", name),
242                    span: inner.as_span().start()..inner.as_span().end(),
243                    custom_label: None,
244                });
245            }
246            _ => {}
247        }
248    }
249
250    Err(CompileError::ParseError {
251        error: "Invalid term in expression".to_string(),
252        span: span_range,
253        custom_label: None,
254    })
255}
256
257pub fn parse_jump_target(
258    pair: Pair<Rule>,
259    _const_map: &HashMap<String, Number>,
260) -> Result<Either<String, i16>, CompileError> {
261    let span = pair.as_span();
262    let span_range = span.start()..span.end();
263
264    for inner in pair.into_inner() {
265        match inner.as_rule() {
266            Rule::symbol | Rule::numeric_label_ref => {
267                return Ok(Either::Left(inner.as_str().to_string()));
268            }
269            Rule::number | Rule::signed_number => {
270                let num = parse_number(inner)?;
271                return Ok(Either::Right(num.to_i16()));
272            }
273            _ => {}
274        }
275    }
276
277    Err(CompileError::ParseError {
278        error: "Invalid jump target".to_string(),
279        span: span_range,
280        custom_label: None,
281    })
282}
283
284pub fn parse_memory_ref(
285    pair: Pair<Rule>,
286    const_map: &HashMap<String, Number>,
287) -> Result<(Register, Either<String, i16>), CompileError> {
288    let mut reg = None;
289    let mut accumulated_offset: i16 = 0;
290    let mut unresolved_symbol: Option<String> = None;
291    let mut sign: i16 = 1;
292
293    for inner in pair.into_inner() {
294        match inner.as_rule() {
295            Rule::register => {
296                reg = Some(parse_register(inner)?);
297            }
298            Rule::memory_op => {
299                sign = if inner.as_str() == "+" { 1 } else { -1 };
300            }
301            Rule::memory_offset => {
302                for offset_inner in inner.into_inner() {
303                    match offset_inner.as_rule() {
304                        Rule::number => {
305                            let num = parse_number(offset_inner)?;
306                            accumulated_offset =
307                                accumulated_offset.wrapping_add(sign.wrapping_mul(num.to_i16()));
308                        }
309                        Rule::symbol => {
310                            let name = offset_inner.as_str().to_string();
311                            if let Some(value) = const_map.get(&name) {
312                                accumulated_offset = accumulated_offset
313                                    .wrapping_add(sign.wrapping_mul(value.to_i16()));
314                            } else if unresolved_symbol.is_none() {
315                                unresolved_symbol = Some(name);
316                            }
317                        }
318                        _ => {}
319                    }
320                }
321            }
322            _ => {}
323        }
324    }
325
326    let offset = if let Some(sym) = unresolved_symbol {
327        Either::Left(sym)
328    } else {
329        Either::Right(accumulated_offset)
330    };
331
332    Ok((reg.unwrap_or(Register { n: 0 }), offset))
333}
334
335pub fn parse_number(pair: Pair<Rule>) -> Result<Number, CompileError> {
336    let span = pair.as_span();
337    let span_range = span.start()..span.end();
338    let raw = pair.as_str();
339    let number_str = raw.strip_prefix('+').unwrap_or(raw).replace('_', "");
340
341    // Try parsing as i64 first
342    if let Ok(value) = number_str.parse::<i64>() {
343        return Ok(Number::Int(value));
344    }
345
346    let mut sign: i64 = 1;
347    let value = if number_str.starts_with('-') {
348        sign = -1;
349        number_str.strip_prefix('-').unwrap()
350    } else {
351        number_str.as_str()
352    };
353
354    if value.starts_with("0x") {
355        let hex_str = value.trim_start_matches("0x");
356        if let Ok(value) = u64::from_str_radix(hex_str, 16) {
357            return Ok(Number::Addr(sign.wrapping_mul(value as i64)));
358        }
359    }
360
361    Err(CompileError::InvalidNumber {
362        number: number_str,
363        span: span_range,
364        custom_label: None,
365    })
366}
367
368// Shared process functions.
369
370pub fn process_exit(span: std::ops::Range<usize>) -> Result<Instruction, CompileError> {
371    Ok(Instruction {
372        opcode: Opcode::Exit,
373        dst: None,
374        src: None,
375        off: None,
376        imm: None,
377        span,
378    })
379}
380
381pub(crate) fn process_lddw(
382    pair: Pair<Rule>,
383    const_map: &HashMap<String, Number>,
384    label_offset_map: &HashMap<String, (Number, Section)>,
385    span: std::ops::Range<usize>,
386) -> Result<Instruction, CompileError> {
387    let mut dst = None;
388    let mut imm = None;
389
390    for inner in pair.into_inner() {
391        match inner.as_rule() {
392            Rule::register => dst = Some(parse_register(inner)?),
393            Rule::operand => imm = Some(parse_operand(inner, const_map, label_offset_map)?),
394            _ => {}
395        }
396    }
397
398    Ok(Instruction {
399        opcode: Opcode::Lddw,
400        dst,
401        src: None,
402        off: None,
403        imm,
404        span,
405    })
406}
407
408pub fn process_endian(
409    pair: Pair<Rule>,
410    span: std::ops::Range<usize>,
411) -> Result<Instruction, CompileError> {
412    let mut opcode = None;
413    let mut dst = None;
414    let mut imm = None;
415
416    for inner in pair.into_inner() {
417        match inner.as_rule() {
418            Rule::endian_op => {
419                let op_str = inner.as_str();
420                let inner_span = inner.as_span();
421                // Extract opcode and size from instruction (example: "be16" = be opcode, 16 bits)
422                let (opc, size) = if let Some(size_str) = op_str.strip_prefix("be") {
423                    let size = size_str
424                        .parse::<i64>()
425                        .map_err(|_| CompileError::ParseError {
426                            error: format!("Invalid endian size in '{}'", op_str),
427                            span: inner_span.start()..inner_span.end(),
428                            custom_label: None,
429                        })?;
430                    (Opcode::Be, size)
431                } else if let Some(size_str) = op_str.strip_prefix("le") {
432                    let size = size_str
433                        .parse::<i64>()
434                        .map_err(|_| CompileError::ParseError {
435                            error: format!("Invalid endian size in '{}'", op_str),
436                            span: inner_span.start()..inner_span.end(),
437                            custom_label: None,
438                        })?;
439                    (Opcode::Le, size)
440                } else {
441                    return Err(CompileError::ParseError {
442                        error: format!("Invalid endian operation '{}'", op_str),
443                        span: inner_span.start()..inner_span.end(),
444                        custom_label: None,
445                    });
446                };
447                opcode = Some(opc);
448                imm = Some(Either::Right(Number::Int(size)));
449            }
450            Rule::register => dst = Some(parse_register(inner)?),
451            _ => {}
452        }
453    }
454
455    Ok(Instruction {
456        opcode: opcode.unwrap_or(Opcode::Exit),
457        dst,
458        src: None,
459        off: None,
460        imm,
461        span,
462    })
463}
464
465pub fn process_call(
466    pair: Pair<Rule>,
467    const_map: &HashMap<String, Number>,
468    span: std::ops::Range<usize>,
469) -> Result<Instruction, CompileError> {
470    let mut imm = None;
471
472    for inner in pair.into_inner() {
473        if inner.as_rule() == Rule::symbol {
474            if let Some(symbol) = const_map.get(inner.as_str()) {
475                imm = Some(Either::Right(symbol.to_owned()));
476            } else {
477                imm = Some(Either::Left(inner.as_str().to_string()));
478            }
479        }
480    }
481
482    Ok(Instruction {
483        opcode: Opcode::Call,
484        dst: None,
485        src: None,
486        off: None,
487        imm,
488        span,
489    })
490}
491
492pub fn process_callx(
493    pair: Pair<Rule>,
494    span: std::ops::Range<usize>,
495) -> Result<Instruction, CompileError> {
496    let mut dst = None;
497
498    for inner in pair.into_inner() {
499        if inner.as_rule() == Rule::register {
500            dst = Some(parse_register(inner)?);
501        }
502    }
503
504    Ok(Instruction {
505        opcode: Opcode::Callx,
506        dst,
507        src: None,
508        off: None,
509        imm: None,
510        span,
511    })
512}
513
514pub(crate) fn check_arch_v3(pair: &Pair<Rule>, arch: SbpfArch) -> Result<(), CompileError> {
515    if arch.is_v3() {
516        return Ok(());
517    }
518
519    if let Some(inner) = pair.clone().into_inner().next() {
520        let span = inner.as_span();
521        return Err(CompileError::ParseError {
522            error: format!("instruction '{}' requires arch v3", inner.as_str()),
523            span: span.start()..span.end(),
524            custom_label: None,
525        });
526    }
527
528    Ok(())
529}