Skip to main content

ic_db_macros/
lib.rs

1#![forbid(unsafe_code)]
2//! Attribute macros for IC DB schema declarations.
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
125// Supply Serde through ic-db even in schema crates without a direct serde dependency.
126fn schema_attrs(attrs: &[syn::Attribute]) -> syn::Result<Tokens> {
127    let mut serialize = true;
128    let mut deserialize = true;
129    let mut supply_crate = true;
130    for attr in attrs {
131        if attr.path().is_ident("derive") {
132            for path in
133                attr.parse_args_with(Punctuated::<syn::Path, Token![,]>::parse_terminated)?
134            {
135                if let Some(name) = path.segments.last() {
136                    serialize &= name.ident != "Serialize";
137                    deserialize &= name.ident != "Deserialize";
138                }
139            }
140        } else if attr.path().is_ident("serde") {
141            supply_crate &= !meta_items(&attr.meta)?
142                .iter()
143                .any(|m| m.path().is_ident("crate"));
144        }
145    }
146    let ser = serialize.then(|| quote!(#[derive(::ic_db::__private::serde::Serialize)]));
147    let de = deserialize.then(|| quote!(#[derive(::ic_db::__private::serde::Deserialize)]));
148    let path = (supply_crate && (serialize || deserialize))
149        .then(|| quote!(#[serde(crate = "::ic_db::__private::serde")]));
150
151    Ok(quote!(#ser #de #(#attrs)* #path))
152}
153
154fn metas(tokens: Tokens) -> syn::Result<Vec<Meta>> {
155    Ok(Punctuated::<Meta, Token![,]>::parse_terminated
156        .parse2(tokens)?
157        .into_iter()
158        .collect())
159}
160
161fn meta_items(meta: &Meta) -> syn::Result<Vec<Meta>> {
162    match meta {
163        Meta::List(value) => metas(value.tokens.clone()),
164        _ => Err(syn::Error::new_spanned(meta, "expected attribute list")),
165    }
166}
167
168fn literal(meta: &Meta) -> syn::Result<&Lit> {
169    if let Meta::NameValue(value) = meta
170        && let Expr::Lit(value) = &value.value
171    {
172        return Ok(&value.lit);
173    }
174
175    Err(syn::Error::new_spanned(meta, "expected literal value"))
176}
177
178fn text(meta: &Meta) -> syn::Result<String> {
179    if let Lit::Str(value) = literal(meta)? {
180        return Ok(value.value());
181    }
182
183    Err(syn::Error::new_spanned(meta, "expected a string"))
184}
185
186fn once<T>(slot: &mut Option<T>, value: T, meta: &Meta) -> syn::Result<()> {
187    if slot.replace(value).is_some() {
188        return Err(syn::Error::new_spanned(meta, "duplicate attribute"));
189    }
190
191    Ok(())
192}
193
194fn fields(meta: &Meta) -> syn::Result<Vec<String>> {
195    if let Meta::NameValue(value) = meta
196        && let Expr::Array(values) = &value.value
197    {
198        return values
199            .elems
200            .iter()
201            .map(|value| {
202                if let Expr::Lit(value) = value
203                    && let Lit::Str(value) = &value.lit
204                {
205                    return Ok(value.value());
206                }
207
208                Err(syn::Error::new_spanned(value, "expected field name"))
209            })
210            .collect();
211    }
212
213    Err(syn::Error::new_spanned(
214        meta,
215        "expected an array of field names",
216    ))
217}
218
219fn declaration_name(name: Option<String>, ident: &syn::Ident, kind: &str) -> syn::Result<String> {
220    let name = name.unwrap_or_else(|| ident.to_string());
221    if !(1..=64).contains(&name.len()) {
222        return Err(syn::Error::new_spanned(
223            ident,
224            format!("{kind} name must contain 1..64 UTF-8 bytes"),
225        ));
226    }
227
228    Ok(name)
229}
230
231fn declaration(item: Tokens, kind: &str) -> syn::Result<ItemStruct> {
232    let item: ItemStruct = syn::parse2(item)?;
233    if !matches!(&item.fields, syn::Fields::Named(fields) if fields.named.is_empty())
234        || !item.generics.params.is_empty()
235        || item.generics.where_clause.is_some()
236    {
237        return Err(syn::Error::new_spanned(
238            &item,
239            format!("{kind} requires an empty, nongeneric struct body without a where clause"),
240        ));
241    }
242
243    Ok(item)
244}
245
246fn expand(args: Tokens, item: Tokens) -> syn::Result<Tokens> {
247    let item = declaration(item, "entity")?;
248    let mut logical_name = None;
249    let mut primary = None;
250    let mut authored = None;
251    let mut indexes = Vec::new();
252    for meta in metas(args)? {
253        if meta.path().is_ident("name") {
254            once(&mut logical_name, text(&meta)?, &meta)?;
255        } else if meta.path().is_ident("pk") {
256            let mut key = None;
257            for part in meta_items(&meta)? {
258                if part.path().is_ident("field") {
259                    once(&mut key, text(&part)?, &part)?;
260                } else {
261                    return Err(syn::Error::new_spanned(
262                        part,
263                        "pk accepts only field = \"name\"",
264                    ));
265                }
266            }
267            let key = key.ok_or_else(|| syn::Error::new_spanned(&meta, "pk requires field"))?;
268            once(&mut primary, key, &meta)?;
269        } else if meta.path().is_ident("fields") {
270            let values = meta_items(&meta)?
271                .iter()
272                .map(Field::parse)
273                .collect::<syn::Result<Vec<_>>>()?;
274            once(&mut authored, values, &meta)?;
275        } else if meta.path().is_ident("index") {
276            let mut index_name = None;
277            let mut names = None;
278            let mut unique = false;
279            let mut present_only = false;
280            for part in meta_items(&meta)? {
281                if part.path().is_ident("name") {
282                    once(&mut index_name, text(&part)?, &part)?;
283                } else if part.path().is_ident("fields") {
284                    once(&mut names, fields(&part)?, &part)?;
285                } else if part.path().is_ident("field") {
286                    once(&mut names, vec![text(&part)?], &part)?;
287                } else if matches!(&part, Meta::Path(path) if path.is_ident("unique")) && !unique {
288                    unique = true;
289                } else if matches!(&part, Meta::Path(path) if path.is_ident("present_only"))
290                    && !present_only
291                {
292                    present_only = true;
293                } else {
294                    return Err(syn::Error::new_spanned(
295                        part,
296                        "unsupported or duplicate index option",
297                    ));
298                }
299            }
300            let fields =
301                names.ok_or_else(|| syn::Error::new_spanned(&meta, "index requires fields"))?;
302            indexes.push(Index {
303                name: index_name.unwrap_or_else(|| fields.join(",")),
304                fields,
305                unique,
306                present_only,
307            });
308        } else {
309            return Err(syn::Error::new_spanned(meta, "unsupported entity option"));
310        }
311    }
312    let fail = |message| syn::Error::new_spanned(&item.ident, message);
313    let logical_name = declaration_name(logical_name, &item.ident, "entity")?;
314    let primary = primary.ok_or_else(|| fail("entity requires pk"))?;
315    let mut authored = authored.ok_or_else(|| fail("entity requires fields"))?;
316    let names: BTreeSet<_> = authored.iter().map(|field| &field.name).collect();
317    if names.len() != authored.len()
318        || authored.is_empty()
319        || authored.len() > 16
320        || !names.contains(&primary)
321        || authored.iter().any(|field| field.name.len() > 64)
322    {
323        return Err(fail(
324            "invalid, duplicate or excessive fields/primary key (1..16 fields)",
325        ));
326    }
327    let field_ids: Vec<syn::Ident> = authored
328        .iter()
329        .map(|field| syn::parse_str(&field.name))
330        .collect::<syn::Result<_>>()?;
331    let mut constant_names = BTreeSet::new();
332    let mut field_constants = Vec::with_capacity(authored.len());
333    for field in &authored {
334        let source = &field.name;
335        let constant = source
336            .strip_prefix("r#")
337            .unwrap_or(source)
338            .to_ascii_uppercase();
339        if !constant_names.insert(constant.clone()) {
340            return Err(fail(&format!(
341                "fields generate the same associated constant `{constant}`"
342            )));
343        }
344        let ident = syn::parse_str::<syn::Ident>(&constant)?;
345        let doc = format!("Logical field name `{source}` for fluent queries.");
346        field_constants.push(quote! { #[doc = #doc] pub const #ident: &'static str = #source; });
347    }
348    let key_type = authored
349        .iter()
350        .find(|field| field.name == primary && field.required_key())
351        .ok_or_else(|| {
352            fail("primary key currently requires a non-optional integer, U256, Ulid, Principal, Account or Subaccount")
353        })?
354        .rust_type();
355    let key_id: syn::Ident = syn::parse_str(&primary)?;
356    indexes.sort_by(|left, right| left.name.cmp(&right.name));
357    if indexes.len() > 8
358        || indexes.windows(2).any(|pair| pair[0].name == pair[1].name)
359        || indexes
360            .iter()
361            .any(|index| index.name.is_empty() || index.name.len() > 64)
362    {
363        return Err(fail(
364            "indexes require distinct names of 1..64 bytes (maximum eight); use name to disambiguate",
365        ));
366    }
367    let mut descriptions = Vec::new();
368    let mut encoded_indexes = Vec::new();
369    for field in &mut authored {
370        if let Some((_, selected)) = &mut field.reference {
371            let mut candidates = indexes.iter().filter(|index| {
372                !index.present_only
373                    && index.fields.first() == Some(&field.name)
374                    && selected.as_ref().is_none_or(|name| *name == index.name)
375            });
376            let Some(index) = candidates.next() else {
377                return Err(fail(
378                    "reference requires an unfiltered declared index beginning with its field",
379                ));
380            };
381            if candidates.next().is_some() {
382                return Err(fail(
383                    "ambiguous reference access path; select an index by name",
384                ));
385            }
386            *selected = Some(index.name.clone());
387        }
388    }
389    let mut unique_keys = unique::Keys::default();
390    for index in indexes {
391        let unique_fields: BTreeSet<_> = index.fields.iter().collect();
392        if index.fields.is_empty()
393            || index.fields.len() > 4
394            || unique_fields.len() != index.fields.len()
395            || index.fields.iter().any(|name| {
396                !authored
397                    .iter()
398                    .any(|field| &field.name == name && field.indexable())
399            })
400        {
401            return Err(fail(
402                "index requires 1..4 distinct supported scalar or unit-enum fields",
403            ));
404        }
405        let fields: Vec<syn::Ident> = index
406            .fields
407            .iter()
408            .map(|name| syn::parse_str(name))
409            .collect::<syn::Result<_>>()?;
410        let index_name = index.name;
411        let unique = index.unique;
412        let present_only = index.present_only;
413        let has_optional = index.fields.iter().any(|name| {
414            authored
415                .iter()
416                .any(|field| &field.name == name && field.optional)
417        });
418        if (unique && has_optional && !present_only) || (present_only && (!unique || !has_optional))
419        {
420            return Err(fail(
421                "optional unique indexes require present_only; present_only requires uniqueness and an optional component",
422            ));
423        }
424        let operands: Vec<_> = index
425            .fields
426            .iter()
427            .zip(&fields)
428            .map(|(name, ident)| {
429                let field = authored
430                    .iter()
431                    .find(|field| &field.name == name)
432                    .expect("admitted index field");
433                let value = field.index_value(ident);
434                let optional = field.optional;
435
436                quote!((#value, #optional))
437            })
438            .collect();
439        if unique {
440            unique_keys.add(&item, &index_name, &fields, &authored, &index.fields);
441        }
442        let names = index.fields;
443        descriptions.push(quote! { ::ic_db::IndexSchema { id: ::ic_db::__private::handle(#index_name), name: #index_name, fields: &[#(#names),*], unique: #unique, present_only: #present_only } });
444        encoded_indexes
445            .push(quote! { ::ic_db::__private::encode_index(&[#(#operands),*], #present_only) });
446    }
447    let lookup_keys = unique_keys.declarations;
448    let name = &item.ident;
449    let attrs = crate::schema_attrs(&item.attrs)?;
450    let visibility = &item.vis;
451    let mut ordered: Vec<_> = authored.iter().collect();
452    ordered.sort_by_key(|field| &field.name);
453    let ordered_ids: Vec<syn::Ident> = ordered
454        .iter()
455        .map(|field| syn::parse_str(&field.name))
456        .collect::<syn::Result<_>>()?;
457    let nested_writes: Vec<_> = ordered
458        .iter()
459        .zip(&ordered_ids)
460        .filter(|(f, _)| f.many.is_some() || matches!(f.kind, field::Kind::Named(..)))
461        .map(|(f, id)| f.encode(id))
462        .collect();
463    let nested_validation = if nested_writes.is_empty() {
464        quote!()
465    } else {
466        quote! { let mut writer = ::ic_db::__private::Encoder::new(); #(#nested_writes)* }
467    };
468    let writes: Vec<_> = ordered
469        .iter()
470        .zip(&ordered_ids)
471        .map(|(field, id)| field.encode(id))
472        .collect();
473    let reads: Vec<_> = ordered
474        .iter()
475        .zip(&ordered_ids)
476        .map(|(field, id)| field.decode(id))
477        .collect();
478    let authored_types: Vec<_> = authored.iter().map(Field::rust_type).collect();
479    let descriptions_fields: Vec<_> = ordered.iter().map(|field| field.description()).collect();
480    let validations: Vec<_> = authored
481        .iter()
482        .zip(&field_ids)
483        .map(|(field, id)| field.validation(id))
484        .collect();
485    if authored
486        .iter()
487        .any(|field| field.name == primary && field.default.is_some())
488    {
489        return Err(syn::Error::new_spanned(
490            &item.ident,
491            "supplied primary keys cannot declare an insert default",
492        ));
493    }
494    let insert_input = insert::emit(&item, &authored)?;
495    let mut managed_fields = [None, None];
496    for (field, id) in authored.iter().zip(&field_ids) {
497        if let Some(policy) = field.managed {
498            let slot = usize::from(policy == field::Management::UpdatedAt);
499            let timestamp = if matches!(field.kind, field::Kind::Named(..)) {
500                quote!(#id.0)
501            } else {
502                quote!(#id)
503            };
504            if managed_fields[slot].replace(timestamp).is_some() {
505                return Err(syn::Error::new_spanned(
506                    id,
507                    "each managed timestamp role may appear once per entity",
508                ));
509            }
510        }
511    }
512    let managed_check = |owner: Tokens| {
513        if managed_fields.iter().all(Option::is_none) {
514            return quote!();
515        }
516        let values = managed_fields.iter().map(|field| {
517            field
518                .as_ref()
519                .map_or_else(|| quote!(None), |field| quote!(Some(#owner.#field)))
520        });
521
522        quote!(::ic_db::__private::validate_managed_order([#(#values),*])?;)
523    };
524    let validate_managed = managed_check(quote!(self));
525    let decode_managed = managed_check(quote!(row));
526
527    Ok(quote! {
528        #insert_input
529        #(#lookup_keys)*
530        #attrs
531        #[derive(Clone, Debug, PartialEq, Eq)]
532        #visibility struct #name { #(#[doc = "Authored stored field."] pub #field_ids: #authored_types,)* }
533
534        impl #name { #(#field_constants)* }
535
536        impl ::ic_db::Entity for #name {
537            type Key = #key_type;
538            fn declaration_path() -> &'static str { concat!(module_path!(), "::", stringify!(#name)) }
539            const SCHEMA: &'static ::ic_db::EntitySchema = &::ic_db::EntitySchema {
540                id: ::ic_db::__private::handle(#logical_name), name: #logical_name, fields: &[#(#descriptions_fields),*], primary_key: #primary,
541                indexes: &[#(#descriptions),*],
542            };
543            fn key(&self) -> Self::Key { self.#key_id }
544
545            fn __row_info(&self) -> ::ic_db::__private::RowInfo {
546                let row = self;
547
548                ::ic_db::__private::RowInfo {
549                    key: ::ic_db::PrimaryKey::into_row_key(<Self as ::ic_db::Entity>::key(row)),
550                    indexes: ::std::vec![#(#encoded_indexes),*]
551                }
552            }
553
554            fn validate(&self) -> Result<(), ::ic_db::Error> {
555                #validate_managed
556                #(#validations)*
557                #nested_validation
558
559                Ok(())
560            }
561
562            fn encode(&self) -> Result<::std::vec::Vec<u8>, ::ic_db::Error> {
563                #validate_managed
564                let mut writer = ::ic_db::__private::Encoder::new();
565                #(#writes)*
566
567                Ok(writer.finish())
568            }
569
570            fn decode(bytes: &[u8]) -> Result<Self, ::ic_db::Error> {
571                let mut reader = ::ic_db::__private::Decoder::new(bytes)?;
572                let row = Self { #(#reads)* };
573                reader.finish()?;
574                #decode_managed
575
576                Ok(row)
577            }
578        }
579
580        impl ::ic_db::__private::ReferenceTarget for #name {
581            const NAME: &'static str = #logical_name;
582        }
583
584        const _: () = {
585            if let ::std::option::Option::Some(root) = ::std::option_env!("IC_DB_SCHEMA_ROOT") {
586                const PATH: &str = ::std::concat!(::std::module_path!(), "::", ::std::stringify!(#name));
587                ::std::assert!(
588                    ::ic_db::__private::check_schema_member(
589                        PATH, root,
590                        ::std::option_env!(::std::concat!("IC_DB_SCHEMA_MEMBER_", ::std::stringify!(#name))),
591                    ),
592                    ::std::concat!("entity missing from host schema: ", ::std::module_path!(), "::", ::std::stringify!(#name)),
593                );
594            }
595        };
596        ::ic_db::__register_schema!(#name);
597    })
598}