ic-db-macros 0.23.7

Attribute authoring for experimental IC DB records
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
#![forbid(unsafe_code)]
//! Small attribute authoring boundary for the first persistent-record slice.
//! Generates typed records/codecs and metadata, never endpoints or executors.
//! All declarations use empty, nongeneric struct bodies without `where` clauses;
//! unsupported Rust constraints are rejected rather than discarded during expansion.

use proc_macro::TokenStream;
use proc_macro2::TokenStream as Tokens;
use quote::quote;
use std::collections::BTreeSet;
use syn::{Expr, ItemStruct, Lit, Meta, Token, parse::Parser, punctuated::Punctuated};

mod enumeration;
mod field;
mod insert;
mod map;
mod record;
mod set;
mod wrapped;
use field::Field;

/// Author a typed record with named fields, a supplied scalar key and indexes.
///
/// Field types follow the implemented `ic_db::FieldType` contract, with explicit
/// bounds for variable-size values. Secondary indexes admit supported ordered
/// scalar fields and unit enums, including optional forms. Optional unique indexes require
/// `present_only`, omitting a row when any optional key component is absent. Unsupported shapes
/// refuse explicitly; this is not a retirement of the broader planned type surface.
/// Entity names default to the type name; `name = "StableName"` overrides it.
/// Index names default to comma-separated ordered fields; `name` overrides them.
/// Required or optional supported key fields may declare `references(entity = "path::Target")`;
/// select the sole unfiltered index leading with this field, or use `index = "name"`.
/// `None` has no target; every `Some(id)` requires that target in the final batch state.
/// `entity = "path::Target"` lets Rust resolve an entity type (including imports
/// and `Self`) to its logical identity. Numeric authoring IDs are unsupported.
/// With the host-only `ic-db/build` feature, declarations also register their
/// full Rust paths for second-stage schema assembly.
/// Fields may declare `default = LITERAL` for integers, Bool, bounded Text and Blob.
/// Blob defaults use Rust byte strings, e.g. `default = b"\x00\xff"`, never text/hex coercion.
/// `Entity::insert()` builds typed omission-aware input for `Batch::insert_input`;
/// explicit optional `None` is never replaced by a default. Primary-key and nested
/// record defaults are not implemented. Defaults never run on decode/replacement.
/// Required Timestamp fields and their scalar newtypes may declare `managed = "created_at"` or
/// `managed = "updated_at"`, once per role. These fields have no insert setters;
/// use `Batch::at(time)` to supply one operation time for the entire batch.
#[proc_macro_attribute]
pub fn entity(args: TokenStream, item: TokenStream) -> TokenStream {
    expand(args.into(), item.into())
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

/// Declare a named enum using an empty struct and `variant(name = "...")` attributes.
/// Supports 1–64 unit or typed payload variants. Canonical name order determines
/// stored ordinals; source declaration order does not. Use item(indirect, is = "Self")
/// for boxed recursion, with a finite base alternative.
/// All-unit enums also convert by reference into `ic_db::IndexValue`, using the
/// same canonical order. Any payload variant excludes the whole enum from indexes.
#[proc_macro_attribute]
pub fn enum_(args: TokenStream, item: TokenStream) -> TokenStream {
    enumeration::expand(args.into(), item.into())
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

/// Declare a reusable ordered list with an item type and a shared maximum length.
#[proc_macro_attribute]
pub fn list(args: TokenStream, item: TokenStream) -> TokenStream {
    wrapped::expand(args.into(), item.into(), true)
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

/// Declare a distinct Rust and schema type around one primitive, including its bounds.
#[proc_macro_attribute]
pub fn newtype(args: TokenStream, item: TokenStream) -> TokenStream {
    wrapped::expand(args.into(), item.into(), false)
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

/// Declare a bounded ordered set with `item(...)` and `max_items = N` (0..256).
/// Elements can be primitives, scalar newtypes or unit enums. The generated
/// wrapper contains a `BTreeSet<T>`. Decoding requires strictly increasing keys.
#[proc_macro_attribute]
pub fn set(args: TokenStream, item: TokenStream) -> TokenStream {
    set::expand(args.into(), item.into())
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

/// Declare a named `BTreeMap` wrapper using `key(...)`, `value(...)` and
/// `max_items = N` (0..256). Keys are primitives, scalar newtypes or unit enums. Values use the
/// ordinary optional/list/named field rules; stored duplicate keys refuse.
#[proc_macro_attribute]
pub fn map(args: TokenStream, item: TokenStream) -> TokenStream {
    map::expand(args.into(), item.into())
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

/// Declare a named stored record using attribute-owned fields and an empty struct.
#[proc_macro_attribute]
pub fn record(args: TokenStream, item: TokenStream) -> TokenStream {
    record::expand(args.into(), item.into())
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}

struct Index {
    name: String,
    fields: Vec<String>,
    unique: bool,
    present_only: bool,
}

fn metas(tokens: Tokens) -> syn::Result<Vec<Meta>> {
    Ok(Punctuated::<Meta, Token![,]>::parse_terminated
        .parse2(tokens)?
        .into_iter()
        .collect())
}
fn meta_items(meta: &Meta) -> syn::Result<Vec<Meta>> {
    match meta {
        Meta::List(value) => metas(value.tokens.clone()),
        _ => Err(syn::Error::new_spanned(meta, "expected attribute list")),
    }
}
fn literal(meta: &Meta) -> syn::Result<&Lit> {
    if let Meta::NameValue(value) = meta
        && let Expr::Lit(value) = &value.value
    {
        return Ok(&value.lit);
    }
    Err(syn::Error::new_spanned(meta, "expected literal value"))
}
fn text(meta: &Meta) -> syn::Result<String> {
    if let Lit::Str(value) = literal(meta)? {
        return Ok(value.value());
    }
    Err(syn::Error::new_spanned(meta, "expected a string"))
}
fn once<T>(slot: &mut Option<T>, value: T, meta: &Meta) -> syn::Result<()> {
    if slot.replace(value).is_some() {
        return Err(syn::Error::new_spanned(meta, "duplicate attribute"));
    }
    Ok(())
}
fn fields(meta: &Meta) -> syn::Result<Vec<String>> {
    if let Meta::NameValue(value) = meta
        && let Expr::Array(values) = &value.value
    {
        return values
            .elems
            .iter()
            .map(|value| {
                if let Expr::Lit(value) = value
                    && let Lit::Str(value) = &value.lit
                {
                    return Ok(value.value());
                }
                Err(syn::Error::new_spanned(value, "expected field name"))
            })
            .collect();
    }
    Err(syn::Error::new_spanned(
        meta,
        "expected an array of field names",
    ))
}

fn declaration(item: Tokens, kind: &str) -> syn::Result<ItemStruct> {
    let item: ItemStruct = syn::parse2(item)?;
    if !matches!(&item.fields, syn::Fields::Named(fields) if fields.named.is_empty())
        || !item.generics.params.is_empty()
        || item.generics.where_clause.is_some()
    {
        return Err(syn::Error::new_spanned(
            &item,
            format!("{kind} requires an empty, nongeneric struct body without a where clause"),
        ));
    }
    Ok(item)
}

fn expand(args: Tokens, item: Tokens) -> syn::Result<Tokens> {
    let item = declaration(item, "entity")?;
    let mut logical_name = None;
    let mut primary = None;
    let mut authored = None;
    let mut indexes = Vec::new();
    for meta in metas(args)? {
        if meta.path().is_ident("name") {
            once(&mut logical_name, text(&meta)?, &meta)?;
        } else if meta.path().is_ident("pk") {
            let mut key = None;
            let mut source = None;
            for part in meta_items(&meta)? {
                if part.path().is_ident("field") {
                    once(&mut key, text(&part)?, &part)?;
                } else if part.path().is_ident("source") {
                    once(&mut source, text(&part)?, &part)?;
                } else {
                    return Err(syn::Error::new_spanned(
                        part,
                        "unsupported primary-key option",
                    ));
                }
            }
            if source.as_deref().is_some_and(|source| source != "external") {
                return Err(syn::Error::new_spanned(
                    meta,
                    "this slice requires externally supplied keys",
                ));
            }
            let key = key.ok_or_else(|| syn::Error::new_spanned(&meta, "pk requires field"))?;
            once(&mut primary, key, &meta)?;
        } else if meta.path().is_ident("fields") {
            let values = meta_items(&meta)?
                .iter()
                .map(Field::parse)
                .collect::<syn::Result<Vec<_>>>()?;
            once(&mut authored, values, &meta)?;
        } else if meta.path().is_ident("index") {
            let mut index_name = None;
            let mut names = None;
            let mut unique = false;
            let mut present_only = false;
            for part in meta_items(&meta)? {
                if part.path().is_ident("name") {
                    once(&mut index_name, text(&part)?, &part)?;
                } else if part.path().is_ident("fields") {
                    once(&mut names, fields(&part)?, &part)?;
                } else if part.path().is_ident("field") {
                    once(&mut names, vec![text(&part)?], &part)?;
                } else if matches!(&part, Meta::Path(path) if path.is_ident("unique")) && !unique {
                    unique = true;
                } else if matches!(&part, Meta::Path(path) if path.is_ident("present_only"))
                    && !present_only
                {
                    present_only = true;
                } else {
                    return Err(syn::Error::new_spanned(
                        part,
                        "unsupported or duplicate index option",
                    ));
                }
            }
            let fields =
                names.ok_or_else(|| syn::Error::new_spanned(&meta, "index requires fields"))?;
            indexes.push(Index {
                name: index_name.unwrap_or_else(|| fields.join(",")),
                fields,
                unique,
                present_only,
            });
        } else {
            return Err(syn::Error::new_spanned(meta, "unsupported entity option"));
        }
    }
    let fail = |message| syn::Error::new_spanned(&item.ident, message);
    let logical_name = logical_name.unwrap_or_else(|| item.ident.to_string());
    if logical_name.is_empty() || logical_name.len() > 64 {
        return Err(fail("entity name requires 1..64 UTF-8 bytes"));
    }
    let primary = primary.ok_or_else(|| fail("entity requires pk"))?;
    let mut authored = authored.ok_or_else(|| fail("entity requires fields"))?;
    let names: BTreeSet<_> = authored.iter().map(|field| &field.name).collect();
    if names.len() != authored.len()
        || authored.is_empty()
        || authored.len() > 16
        || !names.contains(&primary)
        || authored.iter().any(|field| field.name.len() > 64)
    {
        return Err(fail(
            "invalid, duplicate or excessive fields/primary key (1..16 fields)",
        ));
    }
    let field_ids: Vec<syn::Ident> = authored
        .iter()
        .map(|field| syn::parse_str(&field.name))
        .collect::<syn::Result<_>>()?;
    let key_type = authored
        .iter()
        .find(|field| field.name == primary && field.required_key())
        .ok_or_else(|| {
            fail("primary key currently requires a non-optional integer, U256, Ulid, Principal, Account or Subaccount")
        })?
        .rust_type();
    let key_id: syn::Ident = syn::parse_str(&primary)?;
    indexes.sort_by(|left, right| left.name.cmp(&right.name));
    if indexes.len() > 8
        || indexes.windows(2).any(|pair| pair[0].name == pair[1].name)
        || indexes
            .iter()
            .any(|index| index.name.is_empty() || index.name.len() > 64)
    {
        return Err(fail(
            "indexes require distinct names of 1..64 bytes (maximum eight); use name to disambiguate",
        ));
    }
    let mut descriptions = Vec::new();
    let mut encoded_indexes = Vec::new();
    for field in &mut authored {
        if let Some((_, selected)) = &mut field.reference {
            let mut candidates = indexes.iter().filter(|index| {
                !index.present_only
                    && index.fields.first() == Some(&field.name)
                    && selected.as_ref().is_none_or(|name| *name == index.name)
            });
            let Some(index) = candidates.next() else {
                return Err(fail(
                    "reference requires an unfiltered declared index beginning with its field",
                ));
            };
            if candidates.next().is_some() {
                return Err(fail(
                    "ambiguous reference access path; select an index by name",
                ));
            }
            *selected = Some(index.name.clone());
        }
    }
    for index in indexes {
        let unique_fields: BTreeSet<_> = index.fields.iter().collect();
        if index.fields.is_empty()
            || index.fields.len() > 4
            || unique_fields.len() != index.fields.len()
            || index.fields.iter().any(|name| {
                !authored
                    .iter()
                    .any(|field| &field.name == name && field.indexable())
            })
        {
            return Err(fail(
                "index requires 1..4 distinct supported scalar or unit-enum fields",
            ));
        }
        let fields: Vec<syn::Ident> = index
            .fields
            .iter()
            .map(|name| syn::parse_str(name))
            .collect::<syn::Result<_>>()?;
        let index_name = index.name;
        let unique = index.unique;
        let present_only = index.present_only;
        let has_optional = index.fields.iter().any(|name| {
            authored
                .iter()
                .any(|field| &field.name == name && field.optional)
        });
        if (unique && has_optional && !present_only) || (present_only && (!unique || !has_optional))
        {
            return Err(fail(
                "optional unique indexes require present_only; present_only requires uniqueness and an optional component",
            ));
        }
        let operands: Vec<_> = index
            .fields
            .iter()
            .zip(&fields)
            .map(|(name, ident)| {
                let field = authored
                    .iter()
                    .find(|field| &field.name == name)
                    .expect("admitted index field");
                let value = field.index_value(ident);
                let optional = field.optional;
                quote!((#value, #optional))
            })
            .collect();
        let names = index.fields;
        descriptions.push(quote! { ::ic_db::IndexSchema { id: ::ic_db::__private::handle(#index_name), name: #index_name, fields: &[#(#names),*], unique: #unique, present_only: #present_only } });
        encoded_indexes
            .push(quote! { ::ic_db::__private::encode_index(&[#(#operands),*], #present_only) });
    }
    let name = &item.ident;
    let attrs = &item.attrs;
    let visibility = &item.vis;
    let mut ordered: Vec<_> = authored.iter().collect();
    ordered.sort_by_key(|field| &field.name);
    let ordered_ids: Vec<syn::Ident> = ordered
        .iter()
        .map(|field| syn::parse_str(&field.name))
        .collect::<syn::Result<_>>()?;
    let nested_writes: Vec<_> = ordered
        .iter()
        .zip(&ordered_ids)
        .filter(|(f, _)| f.many.is_some() || matches!(f.kind, field::Kind::Named(..)))
        .map(|(f, id)| f.encode(id))
        .collect();
    let nested_validation = if nested_writes.is_empty() {
        quote!()
    } else {
        quote! { let mut writer = ::ic_db::__private::Encoder::new(); #(#nested_writes)* }
    };
    let writes: Vec<_> = ordered
        .iter()
        .zip(&ordered_ids)
        .map(|(field, id)| field.encode(id))
        .collect();
    let reads: Vec<_> = ordered
        .iter()
        .zip(&ordered_ids)
        .map(|(field, id)| field.decode(id))
        .collect();
    let authored_types: Vec<_> = authored.iter().map(Field::rust_type).collect();
    let descriptions_fields: Vec<_> = ordered.iter().map(|field| field.description()).collect();
    let validations: Vec<_> = authored
        .iter()
        .zip(&field_ids)
        .map(|(field, id)| field.validation(id))
        .collect();
    if authored
        .iter()
        .any(|field| field.name == primary && field.default.is_some())
    {
        return Err(syn::Error::new_spanned(
            &item.ident,
            "supplied primary keys cannot declare an insert default",
        ));
    }
    let insert_input = insert::emit(&item, &authored)?;
    let mut managed_fields = [None, None];
    for (field, id) in authored.iter().zip(&field_ids) {
        if let Some(policy) = field.managed {
            let slot = usize::from(policy == field::Management::UpdatedAt);
            let timestamp = if matches!(field.kind, field::Kind::Named(..)) {
                quote!(#id.0)
            } else {
                quote!(#id)
            };
            if managed_fields[slot].replace(timestamp).is_some() {
                return Err(syn::Error::new_spanned(
                    id,
                    "each managed timestamp role may appear once per entity",
                ));
            }
        }
    }
    let managed_check = |owner: Tokens| {
        if managed_fields.iter().all(Option::is_none) {
            return quote!();
        }
        let values = managed_fields.iter().map(|field| {
            field
                .as_ref()
                .map_or_else(|| quote!(None), |field| quote!(Some(#owner.#field)))
        });
        quote!(::ic_db::__private::validate_managed_order([#(#values),*])?;)
    };
    let validate_managed = managed_check(quote!(self));
    let decode_managed = managed_check(quote!(row));
    Ok(quote! {
        #insert_input
        #(#attrs)*
        #[derive(Clone, Debug, PartialEq, Eq)]
        #visibility struct #name { #(#[doc = "Authored stored field."] pub #field_ids: #authored_types,)* }
        impl ::ic_db::Entity for #name {
            type Key = #key_type;
            const ID: u32 = ::ic_db::__private::handle(#logical_name);
            const NAME: &'static str = #logical_name;
            const PATH: &'static str = concat!(module_path!(), "::", stringify!(#name));
            const SCHEMA: &'static ::ic_db::EntitySchema = &::ic_db::EntitySchema {
                id: Self::ID, name: Self::NAME, fields: &[#(#descriptions_fields),*], primary_key: #primary,
                indexes: &[#(#descriptions),*],
            };
            fn key(&self) -> Self::Key { self.#key_id }
            fn __row_info(&self) -> ::ic_db::__private::RowInfo {
                let row = self;
                ::ic_db::__private::RowInfo {
                    key: ::ic_db::PrimaryKey::into_row_key(<Self as ::ic_db::Entity>::key(row)),
                    indexes: ::std::vec![#(#encoded_indexes),*]
                }
            }
            fn validate(&self) -> Result<(), ::ic_db::Error> {
                #validate_managed
                #(#validations)*
                #nested_validation
                Ok(())
            }
            fn encode(&self) -> Result<::std::vec::Vec<u8>, ::ic_db::Error> {
                #validate_managed
                let mut writer = ::ic_db::__private::Encoder::new();
                #(#writes)*
                Ok(writer.finish())
            }
            fn decode(bytes: &[u8]) -> Result<Self, ::ic_db::Error> {
                let mut reader = ::ic_db::__private::Decoder::new(bytes)?;
                let row = Self { #(#reads)* };
                reader.finish()?;
                #decode_managed
                Ok(row)
            }
        }
        ::ic_db::__register_schema! {
            const _: () = {
                #[::ic_db::build::__ctor::ctor(unsafe, anonymous, crate_path = ::ic_db::build::__ctor)]
                fn register() {
                    ::ic_db::build::__register(<#name as ::ic_db::Entity>::PATH, <#name as ::ic_db::Entity>::SCHEMA);
                }
            };
        }
    })
}

#[cfg(test)]
mod tests;