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