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 mut candidates = indexes.iter().filter(|index| {
419 !index.present_only
420 && index.fields.first() == Some(&field.name)
421 && selected.as_ref().is_none_or(|name| *name == index.name)
422 });
423 let Some(index) = candidates.next() else {
424 return Err(fail(
425 "reference requires an unfiltered declared index beginning with its field",
426 ));
427 };
428 if candidates.next().is_some() {
429 return Err(fail(
430 "ambiguous reference access path; select an index by name",
431 ));
432 }
433 *selected = Some(index.name.clone());
434 }
435 }
436 let mut unique_keys = unique::Keys::default();
437 for index in indexes {
438 let unique_fields: BTreeSet<_> = index.fields.iter().collect();
439 if index.fields.is_empty()
440 || index.fields.len() > 4
441 || unique_fields.len() != index.fields.len()
442 || index.fields.iter().any(|name| {
443 !authored
444 .iter()
445 .any(|field| &field.name == name && field.indexable())
446 })
447 {
448 return Err(fail(
449 "index requires 1..4 distinct supported scalar or unit-enum fields",
450 ));
451 }
452 let fields: Vec<syn::Ident> = index
453 .fields
454 .iter()
455 .map(|name| syn::parse_str(name))
456 .collect::<syn::Result<_>>()?;
457 let index_name = index.name;
458 let unique = index.unique;
459 let present_only = index.present_only;
460 let has_optional = index.fields.iter().any(|name| {
461 authored
462 .iter()
463 .any(|field| &field.name == name && field.optional)
464 });
465 if (unique && has_optional && !present_only) || (present_only && (!unique || !has_optional))
466 {
467 return Err(fail(
468 "optional unique indexes require present_only; present_only requires uniqueness and an optional component",
469 ));
470 }
471 let operands: Vec<_> = index
472 .fields
473 .iter()
474 .zip(&fields)
475 .map(|(name, ident)| {
476 let field = authored
477 .iter()
478 .find(|field| &field.name == name)
479 .expect("admitted index field");
480 let value = field.index_value(ident);
481 let optional = field.optional;
482
483 quote!((#value, #optional))
484 })
485 .collect();
486 if unique {
487 unique_keys.add(&item, &index_name, &fields, &authored, &index.fields);
488 }
489 let names = index.fields;
490 descriptions.push(quote! { ::ic_db::IndexSchema { id: ::ic_db::__private::handle(#index_name), name: #index_name, fields: &[#(#names),*], unique: #unique, present_only: #present_only } });
491 encoded_indexes
492 .push(quote! { ::ic_db::__private::encode_index(&[#(#operands),*], #present_only) });
493 }
494 let lookup_keys = unique_keys.declarations;
495 let name = &item.ident;
496 let attrs = crate::schema_attrs(&item.attrs)?;
497 let visibility = &item.vis;
498 let mut ordered: Vec<_> = authored.iter().collect();
499 ordered.sort_by_key(|field| &field.name);
500 let ordered_ids: Vec<syn::Ident> = ordered
501 .iter()
502 .map(|field| syn::parse_str(&field.name))
503 .collect::<syn::Result<_>>()?;
504 let nested_writes: Vec<_> = ordered
505 .iter()
506 .zip(&ordered_ids)
507 .filter(|(f, _)| f.many.is_some() || matches!(f.kind, field::Kind::Named(..)))
508 .map(|(f, id)| f.encode(id))
509 .collect();
510 let nested_validation = if nested_writes.is_empty() {
511 quote!()
512 } else {
513 quote! { let mut writer = ::ic_db::__private::Encoder::new(); #(#nested_writes)* }
514 };
515 let writes: Vec<_> = ordered
516 .iter()
517 .zip(&ordered_ids)
518 .map(|(field, id)| field.encode(id))
519 .collect();
520 let reads: Vec<_> = ordered
521 .iter()
522 .zip(&ordered_ids)
523 .map(|(field, id)| field.decode(id))
524 .collect();
525 let authored_types: Vec<_> = authored.iter().map(Field::rust_type).collect();
526 let descriptions_fields: Vec<_> = ordered.iter().map(|field| field.description()).collect();
527 let validations: Vec<_> = authored
528 .iter()
529 .zip(&field_ids)
530 .map(|(field, id)| field.validation(id))
531 .collect();
532 if authored
533 .iter()
534 .any(|field| field.name == primary && field.default.is_some())
535 {
536 return Err(syn::Error::new_spanned(
537 &item.ident,
538 "supplied primary keys cannot declare an insert default",
539 ));
540 }
541 let insert_input = insert::emit(&item, &authored)?;
542 let mut managed_fields = [None, None];
543 for (field, id) in authored.iter().zip(&field_ids) {
544 if let Some(policy) = field.managed {
545 let slot = usize::from(policy == field::Management::UpdatedAt);
546 let timestamp = if matches!(field.kind, field::Kind::Named(..)) {
547 quote!(#id.0)
548 } else {
549 quote!(#id)
550 };
551 if managed_fields[slot].replace(timestamp).is_some() {
552 return Err(syn::Error::new_spanned(
553 id,
554 "each managed timestamp role may appear once per entity",
555 ));
556 }
557 }
558 }
559 let managed_check = |owner: Tokens| {
560 if managed_fields.iter().all(Option::is_none) {
561 return quote!();
562 }
563 let values = managed_fields.iter().map(|field| {
564 field
565 .as_ref()
566 .map_or_else(|| quote!(None), |field| quote!(Some(#owner.#field)))
567 });
568
569 quote!(::ic_db::__private::validate_managed_order([#(#values),*])?;)
570 };
571 let membership = membership(name);
572 let reference_checks = authored.iter().filter_map(|field| field.reference.as_ref()).map(|(target,_)| quote! {
573 { fn same_store<T: ::ic_db::Entity<Store = #store>>() {} let _ = same_store::<#target>; }
574 });
575 let validate_managed = managed_check(quote!(self));
576 let decode_managed = managed_check(quote!(row));
577
578 Ok(quote! {
579 #insert_input
580 #(#lookup_keys)*
581 #attrs
582 #[derive(Clone, Debug, PartialEq, Eq)]
583 #visibility struct #name { #(#[doc = "Authored stored field."] pub #field_ids: #authored_types,)* }
584
585 impl #name { #(#field_constants)* }
586
587 impl ::ic_db::Entity for #name {
588 type Store = #store;
589 type Key = #key_type;
590 fn declaration_path() -> &'static str { #(#reference_checks)* concat!(module_path!(), "::", stringify!(#name)) }
591 const SCHEMA: &'static ::ic_db::EntitySchema = &::ic_db::EntitySchema {
592 id: ::ic_db::__private::handle(#logical_name), name: #logical_name, fields: &[#(#descriptions_fields),*], primary_key: #primary,
593 indexes: &[#(#descriptions),*],
594 };
595 fn key(&self) -> Self::Key { self.#key_id }
596
597 fn __row_info(&self) -> ::ic_db::__private::RowInfo {
598 let row = self;
599
600 ::ic_db::__private::RowInfo {
601 key: ::ic_db::PrimaryKey::into_row_key(<Self as ::ic_db::Entity>::key(row)),
602 indexes: ::std::vec![#(#encoded_indexes),*]
603 }
604 }
605
606 fn validate(&self) -> Result<(), ::ic_db::Error> {
607 #validate_managed
608 #(#validations)*
609 #nested_validation
610
611 Ok(())
612 }
613
614 fn encode(&self) -> Result<::std::vec::Vec<u8>, ::ic_db::Error> {
615 #validate_managed
616 let mut writer = ::ic_db::__private::Encoder::new();
617 #(#writes)*
618
619 Ok(writer.finish())
620 }
621
622 fn decode(bytes: &[u8]) -> Result<Self, ::ic_db::Error> {
623 let mut reader = ::ic_db::__private::Decoder::new(bytes)?;
624 let row = Self { #(#reads)* };
625 reader.finish()?;
626 #decode_managed
627
628 Ok(row)
629 }
630 }
631
632 impl ::ic_db::__private::ReferenceTarget for #name {
633 const NAME: &'static str = #logical_name;
634 }
635
636 #membership
637 ::ic_db::__register_schema!(#name);
638 })
639}