1#![forbid(unsafe_code)]
2mod enumeration;
8mod field;
9mod insert;
10mod map;
11mod ownership;
12mod record;
13mod set;
14#[cfg(test)]
15mod tests;
16mod unique;
17mod wrapped;
18
19use proc_macro::TokenStream;
20use proc_macro2::TokenStream as Tokens;
21use quote::quote;
22use std::collections::BTreeSet;
23use syn::{Expr, ItemStruct, Lit, Meta, Token, parse::Parser, punctuated::Punctuated};
24
25use field::Field;
26
27#[proc_macro_attribute]
58pub fn entity(args: TokenStream, item: TokenStream) -> TokenStream {
59 expand(args.into(), item.into())
60 .unwrap_or_else(syn::Error::into_compile_error)
61 .into()
62}
63
64#[proc_macro_attribute]
71pub fn enum_(args: TokenStream, item: TokenStream) -> TokenStream {
72 enumeration::expand(args.into(), item.into())
73 .unwrap_or_else(syn::Error::into_compile_error)
74 .into()
75}
76
77#[proc_macro_attribute]
79pub fn list(args: TokenStream, item: TokenStream) -> TokenStream {
80 wrapped::expand(args.into(), item.into(), true)
81 .unwrap_or_else(syn::Error::into_compile_error)
82 .into()
83}
84
85#[proc_macro_attribute]
87pub fn newtype(args: TokenStream, item: TokenStream) -> TokenStream {
88 wrapped::expand(args.into(), item.into(), false)
89 .unwrap_or_else(syn::Error::into_compile_error)
90 .into()
91}
92
93#[proc_macro_attribute]
97pub fn set(args: TokenStream, item: TokenStream) -> TokenStream {
98 set::expand(args.into(), item.into())
99 .unwrap_or_else(syn::Error::into_compile_error)
100 .into()
101}
102
103#[proc_macro_attribute]
107pub fn map(args: TokenStream, item: TokenStream) -> TokenStream {
108 map::expand(args.into(), item.into())
109 .unwrap_or_else(syn::Error::into_compile_error)
110 .into()
111}
112
113#[proc_macro_attribute]
115pub fn record(args: TokenStream, item: TokenStream) -> TokenStream {
116 record::expand(args.into(), item.into())
117 .unwrap_or_else(syn::Error::into_compile_error)
118 .into()
119}
120
121#[proc_macro_attribute]
123pub fn canister(args: TokenStream, item: TokenStream) -> TokenStream {
124 ownership::expand(args.into(), item.into(), false)
125 .unwrap_or_else(syn::Error::into_compile_error)
126 .into()
127}
128
129#[proc_macro_attribute]
131pub fn store(args: TokenStream, item: TokenStream) -> TokenStream {
132 ownership::expand(args.into(), item.into(), true)
133 .unwrap_or_else(syn::Error::into_compile_error)
134 .into()
135}
136
137fn membership(name: &syn::Ident) -> Tokens {
138 quote! {
139 const _: () = {
140 if let ::std::option::Option::Some(root) = ::std::option_env!("IC_DB_SCHEMA_ROOT") {
141 const PATH: &str = ::std::concat!(::std::module_path!(), "::", ::std::stringify!(#name));
142 ::std::assert!(
143 ::ic_db::__private::check_schema_member(
144 PATH, root,
145 ::std::option_env!(::std::concat!("IC_DB_SCHEMA_MEMBER_", ::std::stringify!(#name))),
146 ),
147 ::std::concat!("declaration missing from host schema: ", ::std::module_path!(), "::", ::std::stringify!(#name)),
148 );
149 }
150 };
151 }
152}
153
154fn owner_path(meta: &Meta) -> syn::Result<syn::Path> {
155 if let Meta::NameValue(pair) = meta
156 && let Expr::Path(path) = &pair.value
157 {
158 return Ok(path.path.clone());
159 }
160 Err(syn::Error::new_spanned(meta, "expected a Rust type path"))
161}
162
163struct Index {
164 name: String,
165 fields: Vec<String>,
166 unique: bool,
167 present_only: bool,
168}
169
170fn schema_attrs(attrs: &[syn::Attribute]) -> syn::Result<Tokens> {
172 let mut serialize = true;
173 let mut deserialize = true;
174 let mut supply_crate = true;
175 for attr in attrs {
176 if attr.path().is_ident("derive") {
177 for path in
178 attr.parse_args_with(Punctuated::<syn::Path, Token![,]>::parse_terminated)?
179 {
180 if let Some(name) = path.segments.last() {
181 serialize &= name.ident != "Serialize";
182 deserialize &= name.ident != "Deserialize";
183 }
184 }
185 } else if attr.path().is_ident("serde") {
186 supply_crate &= !meta_items(&attr.meta)?
187 .iter()
188 .any(|m| m.path().is_ident("crate"));
189 }
190 }
191 let ser = serialize.then(|| quote!(#[derive(::ic_db::__private::serde::Serialize)]));
192 let de = deserialize.then(|| quote!(#[derive(::ic_db::__private::serde::Deserialize)]));
193 let path = (supply_crate && (serialize || deserialize))
194 .then(|| quote!(#[serde(crate = "::ic_db::__private::serde")]));
195
196 Ok(quote!(#ser #de #(#attrs)* #path))
197}
198
199fn metas(tokens: Tokens) -> syn::Result<Vec<Meta>> {
200 Ok(Punctuated::<Meta, Token![,]>::parse_terminated
201 .parse2(tokens)?
202 .into_iter()
203 .collect())
204}
205
206fn meta_items(meta: &Meta) -> syn::Result<Vec<Meta>> {
207 match meta {
208 Meta::List(value) => metas(value.tokens.clone()),
209 _ => Err(syn::Error::new_spanned(meta, "expected attribute list")),
210 }
211}
212
213fn literal(meta: &Meta) -> syn::Result<&Lit> {
214 if let Meta::NameValue(value) = meta
215 && let Expr::Lit(value) = &value.value
216 {
217 return Ok(&value.lit);
218 }
219
220 Err(syn::Error::new_spanned(meta, "expected literal value"))
221}
222
223fn text(meta: &Meta) -> syn::Result<String> {
224 if let Lit::Str(value) = literal(meta)? {
225 return Ok(value.value());
226 }
227
228 Err(syn::Error::new_spanned(meta, "expected a string"))
229}
230
231fn once<T>(slot: &mut Option<T>, value: T, meta: &Meta) -> syn::Result<()> {
232 if slot.replace(value).is_some() {
233 return Err(syn::Error::new_spanned(meta, "duplicate attribute"));
234 }
235
236 Ok(())
237}
238
239fn fields(meta: &Meta) -> syn::Result<Vec<String>> {
240 if let Meta::NameValue(value) = meta
241 && let Expr::Array(values) = &value.value
242 {
243 return values
244 .elems
245 .iter()
246 .map(|value| {
247 if let Expr::Lit(value) = value
248 && let Lit::Str(value) = &value.lit
249 {
250 return Ok(value.value());
251 }
252
253 Err(syn::Error::new_spanned(value, "expected field name"))
254 })
255 .collect();
256 }
257
258 Err(syn::Error::new_spanned(
259 meta,
260 "expected an array of field names",
261 ))
262}
263
264fn declaration_name(name: Option<String>, ident: &syn::Ident, kind: &str) -> syn::Result<String> {
265 let name = name.unwrap_or_else(|| ident.to_string());
266 if !(1..=64).contains(&name.len()) {
267 return Err(syn::Error::new_spanned(
268 ident,
269 format!("{kind} name must contain 1..64 UTF-8 bytes"),
270 ));
271 }
272
273 Ok(name)
274}
275
276fn declaration(item: Tokens, kind: &str) -> syn::Result<ItemStruct> {
277 let item: ItemStruct = syn::parse2(item)?;
278 if !matches!(&item.fields, syn::Fields::Named(fields) if fields.named.is_empty())
279 || !item.generics.params.is_empty()
280 || item.generics.where_clause.is_some()
281 {
282 return Err(syn::Error::new_spanned(
283 &item,
284 format!("{kind} requires an empty, nongeneric struct body without a where clause"),
285 ));
286 }
287
288 Ok(item)
289}
290
291fn field_constants(fields: &[Field], owner: &syn::Ident) -> syn::Result<Vec<Tokens>> {
292 let mut constant_names = BTreeSet::new();
293 let mut field_constants = Vec::with_capacity(fields.len());
294 for field in fields {
295 let source = &field.name;
296 let constant = source
297 .strip_prefix("r#")
298 .unwrap_or(source)
299 .to_ascii_uppercase();
300 if !constant_names.insert(constant.clone()) {
301 return Err(syn::Error::new_spanned(
302 owner,
303 format!("fields generate the same associated constant `{constant}`"),
304 ));
305 }
306 let ident = syn::parse_str::<syn::Ident>(&constant)?;
307 let doc = format!("Logical field name `{source}` for fluent queries.");
308 field_constants.push(quote! { #[doc = #doc] pub const #ident: &'static str = #source; });
309 }
310 Ok(field_constants)
311}
312
313fn expand(args: Tokens, item: Tokens) -> syn::Result<Tokens> {
314 let item = declaration(item, "entity")?;
315 let mut logical_name = None;
316 let mut primary = None;
317 let mut store = None;
318 let mut authored = None;
319 let mut timestamps = None;
320 let mut indexes = Vec::new();
321 for meta in metas(args)? {
322 if meta.path().is_ident("name") {
323 once(&mut logical_name, text(&meta)?, &meta)?;
324 } else if meta.path().is_ident("store") {
325 once(&mut store, owner_path(&meta)?, &meta)?;
326 } else if matches!(&meta, Meta::Path(path) if path.is_ident("timestamps")) {
327 once(&mut timestamps, (), &meta)?;
328 } else if meta.path().is_ident("pk") {
329 let mut key = None;
330 for part in meta_items(&meta)? {
331 if part.path().is_ident("field") {
332 once(&mut key, text(&part)?, &part)?;
333 } else {
334 return Err(syn::Error::new_spanned(
335 part,
336 "pk accepts only field = \"name\"",
337 ));
338 }
339 }
340 let key = key.ok_or_else(|| syn::Error::new_spanned(&meta, "pk requires field"))?;
341 once(&mut primary, key, &meta)?;
342 } else if meta.path().is_ident("fields") {
343 let values = meta_items(&meta)?
344 .iter()
345 .map(Field::parse)
346 .collect::<syn::Result<Vec<_>>>()?;
347 once(&mut authored, values, &meta)?;
348 } else if meta.path().is_ident("index") {
349 let mut index_name = None;
350 let mut names = None;
351 let mut unique = false;
352 let mut present_only = false;
353 for part in meta_items(&meta)? {
354 if part.path().is_ident("name") {
355 once(&mut index_name, text(&part)?, &part)?;
356 } else if part.path().is_ident("fields") {
357 once(&mut names, fields(&part)?, &part)?;
358 } else if part.path().is_ident("field") {
359 once(&mut names, vec![text(&part)?], &part)?;
360 } else if matches!(&part, Meta::Path(path) if path.is_ident("unique")) && !unique {
361 unique = true;
362 } else if matches!(&part, Meta::Path(path) if path.is_ident("present_only"))
363 && !present_only
364 {
365 present_only = true;
366 } else {
367 return Err(syn::Error::new_spanned(
368 part,
369 "unsupported or duplicate index option",
370 ));
371 }
372 }
373 let fields =
374 names.ok_or_else(|| syn::Error::new_spanned(&meta, "index requires fields"))?;
375 indexes.push(Index {
376 name: index_name.unwrap_or_else(|| fields.join(",")),
377 fields,
378 unique,
379 present_only,
380 });
381 } else {
382 return Err(syn::Error::new_spanned(meta, "unsupported entity option"));
383 }
384 }
385 let fail = |message| syn::Error::new_spanned(&item.ident, message);
386 let logical_name = declaration_name(logical_name, &item.ident, "entity")?;
387 let store = store.ok_or_else(|| fail("entity requires store = StoreType"))?;
388 let primary = primary.ok_or_else(|| fail("entity requires pk"))?;
389 let mut authored = authored.ok_or_else(|| fail("entity requires fields"))?;
390 if timestamps.is_some() {
391 for (name, role) in [
392 ("created_at", field::Management::CreatedAt),
393 ("updated_at", field::Management::UpdatedAt),
394 ] {
395 authored.push(Field {
396 managed: Some(role),
397 ..Field::nested(name, field::Kind::Timestamp, false, None)
398 });
399 }
400 }
401 let names: BTreeSet<_> = authored.iter().map(|field| &field.name).collect();
402 if names.len() != authored.len()
403 || authored.is_empty()
404 || authored.len() > 16
405 || !names.contains(&primary)
406 || authored.iter().any(|field| field.name.len() > 64)
407 {
408 return Err(fail(
409 "invalid, duplicate or excessive fields/primary key (1..16 fields)",
410 ));
411 }
412 let field_ids: Vec<syn::Ident> = authored
413 .iter()
414 .map(|field| syn::parse_str(&field.name))
415 .collect::<syn::Result<_>>()?;
416 let field_constants = field_constants(&authored, &item.ident)?;
417 let key_type = authored
418 .iter()
419 .find(|field| field.name == primary && field.required_key())
420 .ok_or_else(|| {
421 fail("primary key currently requires a non-optional integer, U256, Ulid, Principal, Account or Subaccount")
422 })?
423 .rust_type();
424 let key_id: syn::Ident = syn::parse_str(&primary)?;
425 indexes.sort_by(|left, right| left.name.cmp(&right.name));
426 if indexes.len() > 8
427 || indexes.windows(2).any(|pair| pair[0].name == pair[1].name)
428 || indexes
429 .iter()
430 .any(|index| index.name.is_empty() || index.name.len() > 64)
431 {
432 return Err(fail(
433 "indexes require distinct names of 1..64 bytes (maximum eight); use name to disambiguate",
434 ));
435 }
436 let mut descriptions = Vec::new();
437 let mut encoded_indexes = Vec::new();
438 for field in &mut authored {
439 if let Some((_, selected)) = &mut field.reference {
440 let candidates: Vec<_> = indexes
441 .iter()
442 .filter(|index| !index.present_only && index.fields.first() == Some(&field.name))
443 .map(|index| index.name.as_str())
444 .collect();
445 match (selected.as_deref(), candidates.as_slice()) {
446 (Some(name), _) if candidates.contains(&name) => {}
447 (None, [name]) => *selected = Some((*name).to_owned()),
448 (requested, eligible) => {
449 let reason = match requested {
450 Some(name) => format!("cannot use index {name:?}"),
451 None => "requires one matching index".to_owned(),
452 };
453 let hint = if eligible.is_empty() {
454 format!(
455 "declare an unfiltered index beginning with {:?}",
456 field.name
457 )
458 } else {
459 format!("select one with `index = ...` from {eligible:?}")
460 };
461 return Err(fail(&format!(
462 "reference {}.{} {reason}; {hint}",
463 item.ident, field.name
464 )));
465 }
466 }
467 }
468 }
469 let mut unique_keys = unique::Keys::default();
470 for index in indexes {
471 let index_name = &index.name;
472 let unique = index.unique;
473 let present_only = index.present_only;
474 let names = &index.fields;
475 descriptions.push(quote! { ::ic_db::IndexSchema { id: ::ic_db::__private::handle(#index_name), name: #index_name, fields: &[#(#names),*], unique: #unique, present_only: #present_only } });
476 if let [path] = index.fields.as_slice()
477 && let Some((parent, member)) = path.split_once('.')
478 {
479 if index.unique
480 || index.present_only
481 || !authored.iter().any(|f| f.name == parent && !f.optional)
482 {
483 return Err(fail(
484 "a record-member index requires a single required indexable scalar member on a required record and cannot be unique",
485 ));
486 }
487 let parent: syn::Ident = syn::parse_str(parent)?;
488 let member: syn::Ident = syn::parse_str(member)?;
489 encoded_indexes.push(quote! {{
490 use ::ic_db::__private::MemberOperand as _;
491 ::ic_db::__private::encode_index(&[(row.#parent.#member.__ic_db_member_operand(), false)], false)
492 }});
493 continue;
494 }
495 let unique_fields: BTreeSet<_> = index.fields.iter().collect();
496 if index.fields.is_empty()
497 || index.fields.len() > 4
498 || unique_fields.len() != index.fields.len()
499 || index.fields.iter().any(|name| {
500 !authored
501 .iter()
502 .any(|field| &field.name == name && field.indexable())
503 })
504 {
505 return Err(fail(
506 "index requires 1..4 distinct supported scalar or unit-enum fields",
507 ));
508 }
509 let fields: Vec<syn::Ident> = index
510 .fields
511 .iter()
512 .map(|name| syn::parse_str(name))
513 .collect::<syn::Result<_>>()?;
514 let has_optional = index.fields.iter().any(|name| {
515 authored
516 .iter()
517 .any(|field| &field.name == name && field.optional)
518 });
519 if (unique && has_optional && !present_only) || (present_only && (!unique || !has_optional))
520 {
521 return Err(fail(
522 "optional unique indexes require present_only; present_only requires uniqueness and an optional component",
523 ));
524 }
525 let operands: Vec<_> = index
526 .fields
527 .iter()
528 .zip(&fields)
529 .map(|(name, ident)| {
530 let field = authored
531 .iter()
532 .find(|field| &field.name == name)
533 .expect("admitted index field");
534 let value = field.index_value(ident);
535 let optional = field.optional;
536
537 quote!((#value, #optional))
538 })
539 .collect();
540 if unique {
541 unique_keys.add(&item, index_name, &fields, &authored, &index.fields);
542 }
543 encoded_indexes
544 .push(quote! { ::ic_db::__private::encode_index(&[#(#operands),*], #present_only) });
545 }
546 let lookup_keys = unique_keys.declarations;
547 let name = &item.ident;
548 let attrs = crate::schema_attrs(&item.attrs)?;
549 let visibility = &item.vis;
550 let mut ordered: Vec<_> = authored.iter().collect();
551 ordered.sort_by_key(|field| &field.name);
552 let ordered_ids: Vec<syn::Ident> = ordered
553 .iter()
554 .map(|field| syn::parse_str(&field.name))
555 .collect::<syn::Result<_>>()?;
556 let nested_writes: Vec<_> = ordered
557 .iter()
558 .zip(&ordered_ids)
559 .filter(|(f, _)| f.many.is_some() || matches!(f.kind, field::Kind::Named(..)))
560 .map(|(f, id)| f.encode(id))
561 .collect();
562 let nested_validation = if nested_writes.is_empty() {
563 quote!()
564 } else {
565 quote! { let mut writer = ::ic_db::__private::Encoder::new(); #(#nested_writes)* }
566 };
567 let writes: Vec<_> = ordered
568 .iter()
569 .zip(&ordered_ids)
570 .map(|(field, id)| field.encode(id))
571 .collect();
572 let reads: Vec<_> = ordered
573 .iter()
574 .zip(&ordered_ids)
575 .map(|(field, id)| field.decode(id))
576 .collect();
577 let authored_types: Vec<_> = authored.iter().map(Field::rust_type).collect();
578 let descriptions_fields: Vec<_> = ordered.iter().map(|field| field.description()).collect();
579 let validations: Vec<_> = authored
580 .iter()
581 .zip(&field_ids)
582 .map(|(field, id)| field.validation(id))
583 .collect();
584 if authored
585 .iter()
586 .any(|field| field.name == primary && field.default.is_some())
587 {
588 return Err(syn::Error::new_spanned(
589 &item.ident,
590 "supplied primary keys cannot declare an insert default",
591 ));
592 }
593 let insert_input = insert::emit(&item, &authored)?;
594 let mut managed_fields = [None, None];
595 for (field, id) in authored.iter().zip(&field_ids) {
596 if let Some(policy) = field.managed {
597 let slot = usize::from(policy == field::Management::UpdatedAt);
598 let timestamp = if matches!(field.kind, field::Kind::Named(..)) {
599 quote!(#id.0)
600 } else {
601 quote!(#id)
602 };
603 if managed_fields[slot].replace(timestamp).is_some() {
604 return Err(syn::Error::new_spanned(
605 id,
606 "each managed timestamp role may appear once per entity",
607 ));
608 }
609 }
610 }
611 let managed_check = |owner: Tokens| {
612 if managed_fields.iter().all(Option::is_none) {
613 return quote!();
614 }
615 let values = managed_fields.iter().map(|field| {
616 field
617 .as_ref()
618 .map_or_else(|| quote!(None), |field| quote!(Some(#owner.#field)))
619 });
620
621 quote!(::ic_db::__private::validate_managed_order([#(#values),*])?;)
622 };
623 let membership = membership(name);
624 let reference_checks = authored.iter().filter_map(|field| field.reference.as_ref()).map(|(target,_)| quote! {
625 { fn same_store<T: ::ic_db::Entity<Store = #store>>() {} let _ = same_store::<#target>; }
626 });
627 let validate_managed = managed_check(quote!(self));
628 let decode_managed = managed_check(quote!(row));
629
630 Ok(quote! {
631 #insert_input
632 #(#lookup_keys)*
633 #attrs
634 #[derive(Clone, Debug, PartialEq, Eq)]
635 #visibility struct #name { #(#[doc = "Authored stored field."] pub #field_ids: #authored_types,)* }
636
637 impl #name { #(#field_constants)* }
638
639 impl ::ic_db::Entity for #name {
640 type Store = #store;
641 type Key = #key_type;
642 fn declaration_path() -> &'static str { #(#reference_checks)* concat!(module_path!(), "::", stringify!(#name)) }
643 const SCHEMA: &'static ::ic_db::EntitySchema = &::ic_db::EntitySchema {
644 id: ::ic_db::__private::handle(#logical_name), name: #logical_name, fields: &[#(#descriptions_fields),*], primary_key: #primary,
645 indexes: &[#(#descriptions),*],
646 };
647 fn key(&self) -> Self::Key { self.#key_id }
648
649 fn __row_info(&self) -> ::ic_db::__private::RowInfo {
650 let row = self;
651
652 ::ic_db::__private::RowInfo {
653 key: ::ic_db::PrimaryKey::into_row_key(<Self as ::ic_db::Entity>::key(row)),
654 indexes: ::std::vec![#(#encoded_indexes),*]
655 }
656 }
657
658 fn validate(&self) -> Result<(), ::ic_db::Error> {
659 #validate_managed
660 #(#validations)*
661 #nested_validation
662
663 Ok(())
664 }
665
666 fn encode(&self) -> Result<::std::vec::Vec<u8>, ::ic_db::Error> {
667 #validate_managed
668 let mut writer = ::ic_db::__private::Encoder::new();
669 #(#writes)*
670
671 Ok(writer.finish())
672 }
673
674 fn decode(bytes: &[u8]) -> Result<Self, ::ic_db::Error> {
675 let mut reader = ::ic_db::__private::Decoder::new(bytes)?;
676 let row = Self { #(#reads)* };
677 reader.finish()?;
678 #decode_managed
679
680 Ok(row)
681 }
682 }
683
684 impl ::ic_db::__private::ReferenceTarget for #name {
685 const NAME: &'static str = #logical_name;
686 }
687
688 #membership
689 ::ic_db::__register_schema!(#name);
690 })
691}