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