Skip to main content

ic_db_macros/
lib.rs

1#![forbid(unsafe_code)]
2//! Small attribute authoring boundary for the first persistent-record slice.
3//! Generates typed records/codecs and metadata, never endpoints or executors.
4//! All declarations use empty, nongeneric struct bodies without `where` clauses;
5//! unsupported Rust constraints are rejected rather than discarded during expansion.
6
7mod enumeration;
8mod field;
9mod insert;
10mod map;
11mod record;
12mod set;
13#[cfg(test)]
14mod tests;
15mod unique;
16mod wrapped;
17
18use proc_macro::TokenStream;
19use proc_macro2::TokenStream as Tokens;
20use quote::quote;
21use std::collections::BTreeSet;
22use syn::{Expr, ItemStruct, Lit, Meta, Token, parse::Parser, punctuated::Punctuated};
23
24use field::Field;
25
26/// Author a typed record with named fields, a supplied scalar key and indexes.
27///
28/// Each field has an associated name constant, e.g. `User::NAME` for `name`.
29/// Field types follow the implemented `ic_db::FieldType` contract, with explicit
30/// bounds for variable-size values. Secondary indexes admit supported ordered
31/// scalar fields and unit enums, including optional forms. Optional unique indexes require
32/// `present_only`, omitting a row when any optional key component is absent. Unsupported shapes
33/// refuse explicitly; this is not a retirement of the broader planned type surface.
34/// Entity names default to the type name; `name = "StableName"` overrides it.
35/// Index names default to comma-separated ordered fields; `name` overrides them.
36/// A unique index on `User(issuer, subject)` generates `UserByIssuerAndSubject`
37/// with named fields for `session.get_unique(&key)`. A sparse unique key takes
38/// the present component types. Equivalent unique indexes share a key type.
39/// Required or optional supported key fields may declare `references(entity = "path::Target")`;
40/// select the sole unfiltered index leading with this field, or use `index = "name"`.
41/// `None` has no target; every `Some(id)` requires that target in the final batch state.
42/// `entity = "path::Target"` lets Rust resolve an entity type (including imports
43/// and `Self`) to its logical identity. Numeric authoring IDs are unsupported.
44/// With the host-only `ic-db/build` feature, declarations also register their
45/// full Rust paths for second-stage schema assembly.
46/// Fields may declare `default = LITERAL` for integers, Bool, bounded Text and Blob.
47/// Blob defaults use Rust byte strings, e.g. `default = b"\x00\xff"`, never text/hex coercion.
48/// `Entity::insert()` builds typed omission-aware input for `Batch::insert_input`;
49/// explicit optional `None` is never replaced by a default. Primary-key and nested
50/// record defaults are not implemented. Defaults never run on decode/replacement.
51/// Required Timestamp fields and their scalar newtypes may declare `managed = "created_at"` or
52/// `managed = "updated_at"`, once per role. These fields have no insert setters;
53/// use `Batch::at(time)` to supply one operation time for the entire batch.
54#[proc_macro_attribute]
55pub fn entity(args: TokenStream, item: TokenStream) -> TokenStream {
56    expand(args.into(), item.into())
57        .unwrap_or_else(syn::Error::into_compile_error)
58        .into()
59}
60
61/// Declare a named enum using an empty struct and `variant(name = "...")` attributes.
62/// Supports 1–64 unit or typed payload variants. Canonical name order determines
63/// stored ordinals; source declaration order does not. Use item(indirect, is = "Self")
64/// for boxed recursion, with a finite base alternative.
65/// All-unit enums also convert by reference into `ic_db::IndexValue`, using the
66/// same canonical order. Any payload variant excludes the whole enum from indexes.
67#[proc_macro_attribute]
68pub fn enum_(args: TokenStream, item: TokenStream) -> TokenStream {
69    enumeration::expand(args.into(), item.into())
70        .unwrap_or_else(syn::Error::into_compile_error)
71        .into()
72}
73
74/// Declare a reusable ordered list with an item type and a shared maximum length.
75#[proc_macro_attribute]
76pub fn list(args: TokenStream, item: TokenStream) -> TokenStream {
77    wrapped::expand(args.into(), item.into(), true)
78        .unwrap_or_else(syn::Error::into_compile_error)
79        .into()
80}
81
82/// Declare a distinct Rust and schema type around one primitive, including its bounds.
83#[proc_macro_attribute]
84pub fn newtype(args: TokenStream, item: TokenStream) -> TokenStream {
85    wrapped::expand(args.into(), item.into(), false)
86        .unwrap_or_else(syn::Error::into_compile_error)
87        .into()
88}
89
90/// Declare a bounded ordered set with `item(...)` and `max_items = N` (0..256).
91/// Elements can be primitives, scalar newtypes or unit enums. The generated
92/// wrapper contains a `BTreeSet<T>`. Decoding requires strictly increasing keys.
93#[proc_macro_attribute]
94pub fn set(args: TokenStream, item: TokenStream) -> TokenStream {
95    set::expand(args.into(), item.into())
96        .unwrap_or_else(syn::Error::into_compile_error)
97        .into()
98}
99
100/// Declare a named `BTreeMap` wrapper using `key(...)`, `value(...)` and
101/// `max_items = N` (0..256). Keys are primitives, scalar newtypes or unit enums. Values use the
102/// ordinary optional/list/named field rules; stored duplicate keys refuse.
103#[proc_macro_attribute]
104pub fn map(args: TokenStream, item: TokenStream) -> TokenStream {
105    map::expand(args.into(), item.into())
106        .unwrap_or_else(syn::Error::into_compile_error)
107        .into()
108}
109
110/// Declare a named stored record using attribute-owned fields and an empty struct.
111#[proc_macro_attribute]
112pub fn record(args: TokenStream, item: TokenStream) -> TokenStream {
113    record::expand(args.into(), item.into())
114        .unwrap_or_else(syn::Error::into_compile_error)
115        .into()
116}
117
118struct Index {
119    name: String,
120    fields: Vec<String>,
121    unique: bool,
122    present_only: bool,
123}
124
125fn metas(tokens: Tokens) -> syn::Result<Vec<Meta>> {
126    Ok(Punctuated::<Meta, Token![,]>::parse_terminated
127        .parse2(tokens)?
128        .into_iter()
129        .collect())
130}
131
132fn meta_items(meta: &Meta) -> syn::Result<Vec<Meta>> {
133    match meta {
134        Meta::List(value) => metas(value.tokens.clone()),
135        _ => Err(syn::Error::new_spanned(meta, "expected attribute list")),
136    }
137}
138
139fn literal(meta: &Meta) -> syn::Result<&Lit> {
140    if let Meta::NameValue(value) = meta
141        && let Expr::Lit(value) = &value.value
142    {
143        return Ok(&value.lit);
144    }
145    Err(syn::Error::new_spanned(meta, "expected literal value"))
146}
147
148fn text(meta: &Meta) -> syn::Result<String> {
149    if let Lit::Str(value) = literal(meta)? {
150        return Ok(value.value());
151    }
152    Err(syn::Error::new_spanned(meta, "expected a string"))
153}
154
155fn once<T>(slot: &mut Option<T>, value: T, meta: &Meta) -> syn::Result<()> {
156    if slot.replace(value).is_some() {
157        return Err(syn::Error::new_spanned(meta, "duplicate attribute"));
158    }
159    Ok(())
160}
161
162fn fields(meta: &Meta) -> syn::Result<Vec<String>> {
163    if let Meta::NameValue(value) = meta
164        && let Expr::Array(values) = &value.value
165    {
166        return values
167            .elems
168            .iter()
169            .map(|value| {
170                if let Expr::Lit(value) = value
171                    && let Lit::Str(value) = &value.lit
172                {
173                    return Ok(value.value());
174                }
175                Err(syn::Error::new_spanned(value, "expected field name"))
176            })
177            .collect();
178    }
179    Err(syn::Error::new_spanned(
180        meta,
181        "expected an array of field names",
182    ))
183}
184
185fn declaration(item: Tokens, kind: &str) -> syn::Result<ItemStruct> {
186    let item: ItemStruct = syn::parse2(item)?;
187    if !matches!(&item.fields, syn::Fields::Named(fields) if fields.named.is_empty())
188        || !item.generics.params.is_empty()
189        || item.generics.where_clause.is_some()
190    {
191        return Err(syn::Error::new_spanned(
192            &item,
193            format!("{kind} requires an empty, nongeneric struct body without a where clause"),
194        ));
195    }
196    Ok(item)
197}
198
199fn expand(args: Tokens, item: Tokens) -> syn::Result<Tokens> {
200    let item = declaration(item, "entity")?;
201    let mut logical_name = None;
202    let mut primary = None;
203    let mut authored = None;
204    let mut indexes = Vec::new();
205    for meta in metas(args)? {
206        if meta.path().is_ident("name") {
207            once(&mut logical_name, text(&meta)?, &meta)?;
208        } else if meta.path().is_ident("pk") {
209            let mut key = None;
210            for part in meta_items(&meta)? {
211                if part.path().is_ident("field") {
212                    once(&mut key, text(&part)?, &part)?;
213                } else {
214                    return Err(syn::Error::new_spanned(
215                        part,
216                        "pk accepts only field = \"name\"",
217                    ));
218                }
219            }
220            let key = key.ok_or_else(|| syn::Error::new_spanned(&meta, "pk requires field"))?;
221            once(&mut primary, key, &meta)?;
222        } else if meta.path().is_ident("fields") {
223            let values = meta_items(&meta)?
224                .iter()
225                .map(Field::parse)
226                .collect::<syn::Result<Vec<_>>>()?;
227            once(&mut authored, values, &meta)?;
228        } else if meta.path().is_ident("index") {
229            let mut index_name = None;
230            let mut names = None;
231            let mut unique = false;
232            let mut present_only = false;
233            for part in meta_items(&meta)? {
234                if part.path().is_ident("name") {
235                    once(&mut index_name, text(&part)?, &part)?;
236                } else if part.path().is_ident("fields") {
237                    once(&mut names, fields(&part)?, &part)?;
238                } else if part.path().is_ident("field") {
239                    once(&mut names, vec![text(&part)?], &part)?;
240                } else if matches!(&part, Meta::Path(path) if path.is_ident("unique")) && !unique {
241                    unique = true;
242                } else if matches!(&part, Meta::Path(path) if path.is_ident("present_only"))
243                    && !present_only
244                {
245                    present_only = true;
246                } else {
247                    return Err(syn::Error::new_spanned(
248                        part,
249                        "unsupported or duplicate index option",
250                    ));
251                }
252            }
253            let fields =
254                names.ok_or_else(|| syn::Error::new_spanned(&meta, "index requires fields"))?;
255            indexes.push(Index {
256                name: index_name.unwrap_or_else(|| fields.join(",")),
257                fields,
258                unique,
259                present_only,
260            });
261        } else {
262            return Err(syn::Error::new_spanned(meta, "unsupported entity option"));
263        }
264    }
265    let fail = |message| syn::Error::new_spanned(&item.ident, message);
266    let logical_name = logical_name.unwrap_or_else(|| item.ident.to_string());
267    if logical_name.is_empty() || logical_name.len() > 64 {
268        return Err(fail("entity name requires 1..64 UTF-8 bytes"));
269    }
270    let primary = primary.ok_or_else(|| fail("entity requires pk"))?;
271    let mut authored = authored.ok_or_else(|| fail("entity requires fields"))?;
272    let names: BTreeSet<_> = authored.iter().map(|field| &field.name).collect();
273    if names.len() != authored.len()
274        || authored.is_empty()
275        || authored.len() > 16
276        || !names.contains(&primary)
277        || authored.iter().any(|field| field.name.len() > 64)
278    {
279        return Err(fail(
280            "invalid, duplicate or excessive fields/primary key (1..16 fields)",
281        ));
282    }
283    let field_ids: Vec<syn::Ident> = authored
284        .iter()
285        .map(|field| syn::parse_str(&field.name))
286        .collect::<syn::Result<_>>()?;
287    let mut constant_names = BTreeSet::new();
288    let mut field_constants = Vec::with_capacity(authored.len());
289    for field in &authored {
290        let source = &field.name;
291        let constant = source
292            .strip_prefix("r#")
293            .unwrap_or(source)
294            .to_ascii_uppercase();
295        if !constant_names.insert(constant.clone()) {
296            return Err(fail(&format!(
297                "fields generate the same associated constant `{constant}`"
298            )));
299        }
300        let ident = syn::parse_str::<syn::Ident>(&constant)?;
301        let doc = format!("Logical field name `{source}` for fluent queries.");
302        field_constants.push(quote! { #[doc = #doc] pub const #ident: &'static str = #source; });
303    }
304    let key_type = authored
305        .iter()
306        .find(|field| field.name == primary && field.required_key())
307        .ok_or_else(|| {
308            fail("primary key currently requires a non-optional integer, U256, Ulid, Principal, Account or Subaccount")
309        })?
310        .rust_type();
311    let key_id: syn::Ident = syn::parse_str(&primary)?;
312    indexes.sort_by(|left, right| left.name.cmp(&right.name));
313    if indexes.len() > 8
314        || indexes.windows(2).any(|pair| pair[0].name == pair[1].name)
315        || indexes
316            .iter()
317            .any(|index| index.name.is_empty() || index.name.len() > 64)
318    {
319        return Err(fail(
320            "indexes require distinct names of 1..64 bytes (maximum eight); use name to disambiguate",
321        ));
322    }
323    let mut descriptions = Vec::new();
324    let mut encoded_indexes = Vec::new();
325    for field in &mut authored {
326        if let Some((_, selected)) = &mut field.reference {
327            let mut candidates = indexes.iter().filter(|index| {
328                !index.present_only
329                    && index.fields.first() == Some(&field.name)
330                    && selected.as_ref().is_none_or(|name| *name == index.name)
331            });
332            let Some(index) = candidates.next() else {
333                return Err(fail(
334                    "reference requires an unfiltered declared index beginning with its field",
335                ));
336            };
337            if candidates.next().is_some() {
338                return Err(fail(
339                    "ambiguous reference access path; select an index by name",
340                ));
341            }
342            *selected = Some(index.name.clone());
343        }
344    }
345    let mut unique_keys = unique::Keys::default();
346    for index in indexes {
347        let unique_fields: BTreeSet<_> = index.fields.iter().collect();
348        if index.fields.is_empty()
349            || index.fields.len() > 4
350            || unique_fields.len() != index.fields.len()
351            || index.fields.iter().any(|name| {
352                !authored
353                    .iter()
354                    .any(|field| &field.name == name && field.indexable())
355            })
356        {
357            return Err(fail(
358                "index requires 1..4 distinct supported scalar or unit-enum fields",
359            ));
360        }
361        let fields: Vec<syn::Ident> = index
362            .fields
363            .iter()
364            .map(|name| syn::parse_str(name))
365            .collect::<syn::Result<_>>()?;
366        let index_name = index.name;
367        let unique = index.unique;
368        let present_only = index.present_only;
369        let has_optional = index.fields.iter().any(|name| {
370            authored
371                .iter()
372                .any(|field| &field.name == name && field.optional)
373        });
374        if (unique && has_optional && !present_only) || (present_only && (!unique || !has_optional))
375        {
376            return Err(fail(
377                "optional unique indexes require present_only; present_only requires uniqueness and an optional component",
378            ));
379        }
380        let operands: Vec<_> = index
381            .fields
382            .iter()
383            .zip(&fields)
384            .map(|(name, ident)| {
385                let field = authored
386                    .iter()
387                    .find(|field| &field.name == name)
388                    .expect("admitted index field");
389                let value = field.index_value(ident);
390                let optional = field.optional;
391                quote!((#value, #optional))
392            })
393            .collect();
394        if unique {
395            unique_keys.add(&item, &index_name, &fields, &authored, &index.fields);
396        }
397        let names = index.fields;
398        descriptions.push(quote! { ::ic_db::IndexSchema { id: ::ic_db::__private::handle(#index_name), name: #index_name, fields: &[#(#names),*], unique: #unique, present_only: #present_only } });
399        encoded_indexes
400            .push(quote! { ::ic_db::__private::encode_index(&[#(#operands),*], #present_only) });
401    }
402    let lookup_keys = unique_keys.declarations;
403    let name = &item.ident;
404    let attrs = &item.attrs;
405    let visibility = &item.vis;
406    let mut ordered: Vec<_> = authored.iter().collect();
407    ordered.sort_by_key(|field| &field.name);
408    let ordered_ids: Vec<syn::Ident> = ordered
409        .iter()
410        .map(|field| syn::parse_str(&field.name))
411        .collect::<syn::Result<_>>()?;
412    let nested_writes: Vec<_> = ordered
413        .iter()
414        .zip(&ordered_ids)
415        .filter(|(f, _)| f.many.is_some() || matches!(f.kind, field::Kind::Named(..)))
416        .map(|(f, id)| f.encode(id))
417        .collect();
418    let nested_validation = if nested_writes.is_empty() {
419        quote!()
420    } else {
421        quote! { let mut writer = ::ic_db::__private::Encoder::new(); #(#nested_writes)* }
422    };
423    let writes: Vec<_> = ordered
424        .iter()
425        .zip(&ordered_ids)
426        .map(|(field, id)| field.encode(id))
427        .collect();
428    let reads: Vec<_> = ordered
429        .iter()
430        .zip(&ordered_ids)
431        .map(|(field, id)| field.decode(id))
432        .collect();
433    let authored_types: Vec<_> = authored.iter().map(Field::rust_type).collect();
434    let descriptions_fields: Vec<_> = ordered.iter().map(|field| field.description()).collect();
435    let validations: Vec<_> = authored
436        .iter()
437        .zip(&field_ids)
438        .map(|(field, id)| field.validation(id))
439        .collect();
440    if authored
441        .iter()
442        .any(|field| field.name == primary && field.default.is_some())
443    {
444        return Err(syn::Error::new_spanned(
445            &item.ident,
446            "supplied primary keys cannot declare an insert default",
447        ));
448    }
449    let insert_input = insert::emit(&item, &authored)?;
450    let mut managed_fields = [None, None];
451    for (field, id) in authored.iter().zip(&field_ids) {
452        if let Some(policy) = field.managed {
453            let slot = usize::from(policy == field::Management::UpdatedAt);
454            let timestamp = if matches!(field.kind, field::Kind::Named(..)) {
455                quote!(#id.0)
456            } else {
457                quote!(#id)
458            };
459            if managed_fields[slot].replace(timestamp).is_some() {
460                return Err(syn::Error::new_spanned(
461                    id,
462                    "each managed timestamp role may appear once per entity",
463                ));
464            }
465        }
466    }
467    let managed_check = |owner: Tokens| {
468        if managed_fields.iter().all(Option::is_none) {
469            return quote!();
470        }
471        let values = managed_fields.iter().map(|field| {
472            field
473                .as_ref()
474                .map_or_else(|| quote!(None), |field| quote!(Some(#owner.#field)))
475        });
476        quote!(::ic_db::__private::validate_managed_order([#(#values),*])?;)
477    };
478    let validate_managed = managed_check(quote!(self));
479    let decode_managed = managed_check(quote!(row));
480    Ok(quote! {
481        #insert_input
482        #(#lookup_keys)*
483        #(#attrs)*
484        #[derive(Clone, Debug, PartialEq, Eq)]
485        #visibility struct #name { #(#[doc = "Authored stored field."] pub #field_ids: #authored_types,)* }
486        impl #name { #(#field_constants)* }
487        impl ::ic_db::__private::ReferenceTarget for #name {
488            const NAME: &'static str = #logical_name;
489        }
490        impl ::ic_db::Entity for #name {
491            type Key = #key_type;
492            fn declaration_path() -> &'static str { concat!(module_path!(), "::", stringify!(#name)) }
493            const SCHEMA: &'static ::ic_db::EntitySchema = &::ic_db::EntitySchema {
494                id: ::ic_db::__private::handle(#logical_name), name: #logical_name, fields: &[#(#descriptions_fields),*], primary_key: #primary,
495                indexes: &[#(#descriptions),*],
496            };
497            fn key(&self) -> Self::Key { self.#key_id }
498
499            fn __row_info(&self) -> ::ic_db::__private::RowInfo {
500                let row = self;
501                ::ic_db::__private::RowInfo {
502                    key: ::ic_db::PrimaryKey::into_row_key(<Self as ::ic_db::Entity>::key(row)),
503                    indexes: ::std::vec![#(#encoded_indexes),*]
504                }
505            }
506
507            fn validate(&self) -> Result<(), ::ic_db::Error> {
508                #validate_managed
509                #(#validations)*
510                #nested_validation
511                Ok(())
512            }
513
514            fn encode(&self) -> Result<::std::vec::Vec<u8>, ::ic_db::Error> {
515                #validate_managed
516                let mut writer = ::ic_db::__private::Encoder::new();
517                #(#writes)*
518                Ok(writer.finish())
519            }
520
521            fn decode(bytes: &[u8]) -> Result<Self, ::ic_db::Error> {
522                let mut reader = ::ic_db::__private::Decoder::new(bytes)?;
523                let row = Self { #(#reads)* };
524                reader.finish()?;
525                #decode_managed
526                Ok(row)
527            }
528        }
529        ::ic_db::__register_schema!(#name);
530    })
531}