Skip to main content

sbpf_common_tablegen/
lib.rs

1pub mod error;
2pub mod expand;
3pub mod ir;
4pub mod parse;
5pub mod validate;
6
7pub use {
8    expand::{expand_opcode_group, expand_opcode_table},
9    ir::{GroupDef, HandlerTypePaths, OpcodeArch, OpcodeDef, OpcodeGroupDef, OpcodeTableDef},
10    parse::{parse_opcode_group, parse_opcode_table},
11    validate::{validate_opcode_group, validate_opcode_table},
12};
13
14/// Trait for OpcodeTable metadata, group membership, and byte conversions.
15pub trait OpcodeTable: Copy + Sized + 'static {
16    type Group: OpcodeGroup;
17
18    fn to_str(&self) -> &'static str;
19    fn to_operator(&self) -> Option<&'static str>;
20    fn to_size(&self) -> Option<&'static str>;
21    fn from_size(size: &str, group: Self::Group) -> Option<Self>;
22    fn is_32bit(&self) -> bool;
23    fn group(self) -> Self::Group;
24    fn by_group(group: Self::Group) -> &'static [Self];
25    fn try_from_sbpf_v3(opcode: u8) -> Result<Self, OpcodeError>;
26    fn all() -> &'static [Self];
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30pub enum OpcodeError {
31    InvalidOpcode { byte: u8 },
32}
33
34impl core::fmt::Display for OpcodeError {
35    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
36        match self {
37            OpcodeError::InvalidOpcode { byte } => {
38                write!(f, "invalid opcode: 0x{byte:02x}")
39            }
40        }
41    }
42}
43
44impl std::error::Error for OpcodeError {}
45
46/// Trait for OpcodeGroup metadata and decode/validate/execute handler routing.
47pub trait OpcodeGroup: HandlerTypes + Copy + Sized + 'static {
48    fn title(self) -> &'static str;
49    fn description(self) -> &'static str;
50    fn decode_fn(self) -> Self::DecodeFn;
51    fn validate_fn(self) -> Self::ValidateFn;
52    fn execute_fn(self) -> Self::ExecuteFn;
53    fn all() -> &'static [Self];
54}
55
56/// Handler types for an `OpcodeGroup`.
57pub trait HandlerTypes {
58    type DecodeFn: Copy;
59    type ValidateFn: Copy;
60    type ExecuteFn: Copy;
61}
62
63/// Parse, validate and expand an `OpcodeTable`.
64pub fn derive_opcode_table(input: &syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
65    let table = parse_opcode_table(input)?;
66    validate_opcode_table(&table)?;
67    Ok(expand_opcode_table(&table))
68}
69
70/// Parse, validate and expand an `OpcodeGroup`.
71pub fn derive_opcode_group(input: &syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
72    let table = parse_opcode_group(input)?;
73    validate_opcode_group(&table)?;
74    Ok(expand_opcode_group(&table))
75}
76
77#[cfg(test)]
78mod tests;