lib.rs

cdk-rsx/crates/cdk-rsx-store-derive/src/lib.rs

1//! Owner-private version declarations and their compiled catalog certificates.2use proc_macro::TokenStream;3use quote::{format_ident, quote};4use syn::{5    Expr, Fields, GenericParam, ItemStruct, LitStr, Path, Type, parse_macro_input, parse_quote,6    spanned::Spanned,7};89/// Package-owned source inputs for the Store kernel contract.10#[doc(hidden)]11#[proc_macro]12pub fn __package_policy(input: TokenStream) -> TokenStream {13    let _ = parse_macro_input!(input as syn::parse::Nothing);14    cdk_rsx_compat::emit_package_recipe(15        std::path::Path::new(env!("CARGO_MANIFEST_DIR")),16        env!("CARGO_PKG_NAME"),17        include_str!("../Cargo.toml"),18        include_bytes!("lib.rs"),19    )20}2122/// Declare one frozen module version. Data defaults to Data, Children to ().23/// Identity defaults to the module path plus marker name; source is the24/// declaration's source file. Generic markers require explicit semantic inputs.25#[proc_macro_attribute]26pub fn memory(attributes: TokenStream, input: TokenStream) -> TokenStream {27    expand(attributes.into(), parse_macro_input!(input as ItemStruct))28        .unwrap_or_else(syn::Error::into_compile_error)29        .into()30}3132fn expand(33    attributes: proc_macro2::TokenStream,34    input: ItemStruct,35) -> syn::Result<proc_macro2::TokenStream> {36    let mut owner: Option<Path> = None;37    let mut data: Type = parse_quote!(Data);38    let mut children: Type = parse_quote!(());39    let mut source: Option<LitStr> = None;40    let mut contract: Option<Expr> = None;41    let mut sources = Vec::<Expr>::new();42    let mut dependencies = Vec::<Expr>::new();43    let mut hylix = false;44    let mut key: Option<syn::Ident> = None;45    let parser = syn::meta::parser(|meta| {46        if meta.path.is_ident("owner") {47            owner = Some(meta.value()?.parse()?);48        } else if meta.path.is_ident("data") {49            data = meta.value()?.parse()?;50        } else if meta.path.is_ident("children") {51            children = meta.value()?.parse()?;52        } else if meta.path.is_ident("source") {53            source = Some(meta.value()?.parse()?);54        } else if meta.path.is_ident("contract") {55            contract = Some(meta.value()?.parse()?);56        } else if meta.path.is_ident("hylix") {57            hylix = true;58        } else if meta.path.is_ident("key") {59            key = Some(meta.value()?.parse()?);60        } else if meta.path.is_ident("sources") {61            let values: syn::ExprArray = meta.value()?.parse()?;62            sources = values.elems.into_iter().collect();63        } else if meta.path.is_ident("dependencies") {64            let values: syn::ExprArray = meta.value()?.parse()?;65            dependencies = values.elems.into_iter().collect();66        } else {67            return Err(meta.error(68                "expected owner, data, children, hylix, key, source, sources, contract or dependencies",69            ));70        }71        Ok(())72    });73    syn::parse::Parser::parse2(parser, attributes)?;74    if !matches!(input.fields, Fields::Unit) {75        return Err(syn::Error::new(76            input.span(),77            "memory expects a unit marker; persisted fields belong to Data",78        ));79    }80    for parameter in &input.generics.params {81        if let GenericParam::Lifetime(parameter) = parameter {82            return Err(syn::Error::new(83                parameter.span(),84                "memory markers are static; use owned type/const parameters rather than lifetimes",85            ));86        }87    }88    let generic = !input.generics.params.is_empty();89    if generic && key.as_ref().is_some_and(|key| key != "associated") {90        return Err(syn::Error::new(91            key.as_ref().unwrap().span(),92            "generic memory uses an owner-private associated KEY; named module keys require a concrete marker",93        ));94    }95    if generic && dependencies.is_empty() {96        return Err(syn::Error::new(97            input.ident.span(),98            "generic memory requires explicit semantic dependencies = [..]; qualify saved type/const interpretation without relying on type names",99        ));100    }101    let owner = owner.ok_or_else(|| {102        syn::Error::new(103            input.ident.span(),104            "memory requires owner = crate::owner to keep KEY private",105        )106    })?;107    let source = match source {108        Some(source) => source,109        None => {110            let path = input.ident.span().unwrap().local_file().ok_or_else(|| {111                syn::Error::new(112                    input.ident.span(),113                    "source file unavailable; specify source = \"vN.rs\"",114                )115            })?;116            let filename = path.file_name().ok_or_else(|| {117                syn::Error::new(118                    input.ident.span(),119                    "source filename unavailable; specify source explicitly",120                )121            })?;122            LitStr::new(&filename.to_string_lossy(), input.ident.span())123        }124    };125    let name = &input.ident;126    let identity = contract127        .map(|v| quote!(#v))128        .unwrap_or_else(|| quote!(concat!(module_path!(), "::", stringify!(#name))));129    let visibility = &input.vis;130    let attributes = &input.attrs;131    let generics = &input.generics;132    let (implementation, arguments, predicates) = generics.split_for_impl();133    let parameters = generics134        .type_params()135        .map(|parameter| &parameter.ident)136        .collect::<Vec<_>>();137    let witness = quote!((#(::core::marker::PhantomData<#parameters>,)*));138    let associated_key = generic || key.as_ref().is_some_and(|key| key == "associated");139    let private_key = if associated_key {140        quote!(pub(in #owner) const KEY: ::cdk_rsx_store::MemoryKey<Self> = unsafe { ::cdk_rsx_store::MemoryKey::new() };)141    } else {142        quote!()143    };144    let module_key = if associated_key {145        quote!()146    } else {147        let key = key.unwrap_or_else(|| format_ident!("KEY"));148        quote!(pub(in #owner) const #key: ::cdk_rsx_store::MemoryKey<#name> = unsafe { ::cdk_rsx_store::MemoryKey::new() };)149    };150    let cache = format_ident!("__CDK_RSX_PHYSICAL_{}", name);151    let native = if hylix {152        quote!(::cdk_rsx_store::hylix::Record<#data>)153    } else {154        quote!(#data)155    };156    let hylix_impl = if hylix {157        quote! {158            unsafe impl #implementation ::cdk_rsx_store::hylix::ModuleMemory for #name #arguments #predicates { type HylixData = #data; }159        }160    } else {161        quote!()162    };163    let hylix_policy = if hylix {164        quote!(::cdk_rsx_store::__private::HYLIX_POLICY,)165    } else {166        quote!()167    };168    let hylix_size = if hylix {169        quote!(Some(<#data as ::cdk_rsx_store::__private::Codec>::SIZE as u64))170    } else {171        quote!(None)172    };173    let cache_declaration = if generic {174        quote!()175    } else {176        quote! {177            ::std::thread_local! {178                #[allow(non_upper_case_globals)]179                static #cache: ::std::cell::Cell<Option<[u8; 32]>> = const { ::std::cell::Cell::new(None) };180            }181        }182    };183    let physical_digest = if generic {184        quote!(Self::__CDK_RSX_ABI.digest())185    } else {186        quote! {187            #cache.with(|cache| match cache.get() {188                Some(digest) => digest,189                None => { let digest = Self::__CDK_RSX_ABI.digest(); cache.set(Some(digest)); digest }190            })191        }192    };193    Ok(quote! {194        #(#attributes)*195        #visibility struct #name #generics (::cdk_rsx_store::__private::Declaration<#native, #children, #witness>) #predicates;196        impl #implementation #name #arguments #predicates {197            #private_key198            const __CDK_RSX_ABI: ::cdk_rsx_store::__private::Physical =199                ::cdk_rsx_store::__private::physical::<::cdk_rsx_store::PhysicalModule<Self>>();200        }201        #cache_declaration202        // SAFETY: the actual Data/Children bounds and full cell certificate are203        // checked by the compiler; KEY is visible only within the owner.204        unsafe impl #implementation ::cdk_rsx_store::ModuleMemory for #name #arguments #predicates {205            type Data = #native;206            type Children = #children;207            const CONTRACT: [u8; 32] = ::cdk_rsx_store::__private::semantic_contract(208                #identity, &[include_str!(#source), #(#sources),*], &[#hylix_policy #(#dependencies),*]209            );210            fn physical_contract() -> [u8; 32] {211                #physical_digest212            }213        }214        #hylix_impl215        // SAFETY: the marker's sole field is the generated declaration witness;216        // these metadata methods never read a marker or retained pointer.217        unsafe impl #implementation ::cdk_rsx_store::__private::CatalogSpec for #name #arguments #predicates {218            const PHYSICAL: &'static ::cdk_rsx_store::__private::Physical = &Self::__CDK_RSX_ABI;219            const SEMANTIC: [u8; 32] = <Self as ::cdk_rsx_store::ModuleMemory>::CONTRACT;220            const HYLIX_SIZE: Option<u64> = #hylix_size;221        }222        #module_key223    })224}