1mod common;
2mod init;
3mod method;
4mod update;
5mod view;
6
7use crate::contract::common::{
8 derive_ident_metadata, extract_ident_from_type, max_depth_assertion,
9};
10use crate::contract::init::process_init_fn;
11use crate::contract::method::{ExtTraitComponents, MethodDetails};
12use crate::contract::update::{process_update_fn, process_update_fn_definition};
13use crate::contract::view::{process_view_fn, process_view_fn_definition};
14use ab_contracts_common::METADATA_STATIC_NAME_PREFIX;
15use heck::ToSnakeCase;
16use proc_macro2::{Ident, Literal, Span, TokenStream};
17use quote::{format_ident, quote};
18use std::collections::HashMap;
19use syn::spanned::Spanned;
20use syn::{
21 Error, ImplItem, ImplItemFn, ItemImpl, ItemTrait, Meta, TraitItem, TraitItemConst, TraitItemFn,
22 Type, Visibility, parse_quote, parse2,
23};
24
25#[derive(Default)]
26struct MethodOutput {
27 guest_ffi: TokenStream,
28 trait_ext_components: ExtTraitComponents,
29}
30
31struct Method {
32 original_ident: Ident,
34 methods_details: MethodDetails,
35}
36
37#[derive(Default)]
38struct ContractDetails {
39 methods: Vec<Method>,
40}
41
42pub(super) fn contract(item: TokenStream) -> Result<TokenStream, Error> {
43 if let Ok(item_trait) = parse2::<ItemTrait>(item.clone()) {
44 return process_trait_definition(item_trait);
46 }
47
48 let error_message = "`#[contract]` must be applied to struct implementation, trait definition or trait \
49 implementation";
50
51 let item_impl =
52 parse2::<ItemImpl>(item).map_err(|error| Error::new(error.span(), error_message))?;
53
54 if !item_impl.generics.params.is_empty() {
55 return Err(Error::new(
56 item_impl.generics.span(),
57 "`#[contract]` does not support generics",
58 ));
59 }
60
61 if extract_ident_from_type(&item_impl.self_ty).is_none() {
63 return Err(Error::new(
64 item_impl.self_ty.span(),
65 "`#[contract]` must be applied to an implementation for a simple struct without \
66 generics",
67 ));
68 }
69
70 if let Some((path, _for)) = &item_impl.trait_ {
71 let trait_name = path
72 .get_ident()
73 .ok_or_else(|| {
74 if path.leading_colon.is_some() || path.segments.len() > 1 {
75 Error::new(
76 path.span(),
77 "`#[contract]` requires the implemented trait to be named by a simple \
78 identifier, import it with `use` instead of using a path",
79 )
80 } else {
81 Error::new(path.span(), "`#[contract]` does not support generics")
82 }
83 })?
84 .clone();
85 process_trait_impl(item_impl, &trait_name)
87 } else {
88 process_struct_impl(item_impl)
90 }
91}
92
93fn process_trait_definition(mut item_trait: ItemTrait) -> Result<TokenStream, Error> {
94 let trait_name = &item_trait.ident;
95
96 if !item_trait.generics.params.is_empty() {
97 return Err(Error::new(
98 item_trait.generics.span(),
99 "`#[contract]` does not support generics",
100 ));
101 }
102
103 let mut guest_ffis = Vec::with_capacity(item_trait.items.len());
104 let mut trait_ext_components = Vec::with_capacity(item_trait.items.len());
105 let mut contract_details = ContractDetails::default();
106
107 for item in &mut item_trait.items {
108 if let TraitItem::Fn(trait_item_fn) = item {
109 let method_output =
110 process_fn_definition(trait_name, trait_item_fn, &mut contract_details)?;
111 guest_ffis.push(method_output.guest_ffi);
112 trait_ext_components.push(method_output.trait_ext_components);
113
114 if let Some(where_clause) = &mut trait_item_fn.sig.generics.where_clause {
117 where_clause.predicates.push(parse_quote! {
118 Self: ::core::marker::Sized
119 });
120 } else {
121 trait_item_fn
122 .sig
123 .generics
124 .where_clause
125 .replace(parse_quote! {
126 where
127 Self: ::core::marker::Sized
128 });
129 }
130 }
131 }
132
133 let metadata_const = generate_trait_metadata(&contract_details, trait_name, item_trait.span())?;
134 let ext_trait = generate_extension_trait(trait_name, &trait_ext_components);
135
136 Ok(quote! {
137 #item_trait
138
139 impl ::ab_contracts_macros::__private::ContractTraitDefinition for dyn #trait_name {
144 #[cfg(feature = "guest")]
145 #[doc(hidden)]
146 const GUEST_FEATURE_ENABLED: () = ();
147 #metadata_const
148 }
149
150 #ext_trait
151
152 #[expect(clippy::inline_modules, reason = "Macro-generated")]
154 #[expect(clippy::wildcard_imports, reason = "Macro-generated")]
155 pub mod ffi {
156 use super::*;
157
158 #( #guest_ffis )*
159 }
160 })
161}
162
163fn process_trait_impl(mut item_impl: ItemImpl, trait_name: &Ident) -> Result<TokenStream, Error> {
164 let struct_name = item_impl.self_ty.as_ref();
165
166 let mut guest_ffis = Vec::with_capacity(item_impl.items.len());
167 let mut contract_details = ContractDetails::default();
168
169 for item in &mut item_impl.items {
170 if let ImplItem::Fn(impl_item_fn) = item {
171 let method_output = process_fn(
172 struct_name.clone(),
173 Some(trait_name),
174 impl_item_fn,
175 &mut contract_details,
176 )?;
177 guest_ffis.push(method_output.guest_ffi);
178
179 if let Some(where_clause) = &mut impl_item_fn.sig.generics.where_clause {
180 where_clause.predicates.push(parse_quote! {
181 Self: ::core::marker::Sized
182 });
183 } else {
184 impl_item_fn
185 .sig
186 .generics
187 .where_clause
188 .replace(parse_quote! {
189 where
190 Self: ::core::marker::Sized
191 });
192 }
193 }
194 }
195
196 let static_name = format_ident!("{METADATA_STATIC_NAME_PREFIX}{}", trait_name);
197 let ffi_mod_ident = format_ident!("{}_ffi", trait_name.to_string().to_snake_case());
198 let metadata_const = generate_trait_metadata(&contract_details, trait_name, item_impl.span())?;
199 let method_fn_pointers_const = {
200 let methods = contract_details
201 .methods
202 .iter()
203 .map(|method| &method.original_ident);
204
205 quote! {
206 #[doc(hidden)]
207 const NATIVE_EXECUTOR_METHODS: &[::ab_contracts_macros::__private::NativeExecutorContactMethod] = &[
208 #( #ffi_mod_ident::#methods::fn_pointer::METHOD_FN_POINTER, )*
209 ];
210 }
211 };
212
213 Ok(quote! {
214 #[cfg(feature = "guest")]
216 #[allow(
217 unexpected_cfgs,
218 reason = "`abundance` is only a known `target_env` value when compiling for contracts"
219 )]
220 const _: () = {
221 #[used]
229 #[unsafe(no_mangle)]
230 #[cfg_attr(
231 target_env = "abundance",
232 unsafe(link_section = "ab-contract-metadata")
233 )]
234 static #static_name: [::core::primitive::u8; <dyn #trait_name as ::ab_contracts_macros::__private::ContractTraitDefinition>::METADATA.len()] = unsafe {
235 *<dyn #trait_name as ::ab_contracts_macros::__private::ContractTraitDefinition>::METADATA.as_ptr().cast()
236 };
237 };
238
239 const _: () = {
241 use #ffi_mod_ident as ffi;
243 #metadata_const
244
245 let (impl_compact_metadata, impl_compact_metadata_size) =
249 ::ab_contracts_macros::__private::ContractMetadataKind::compact(METADATA)
250 .expect(
251 "Generated metadata is correct unless a type in it is nested deeper than \
252 `MAX_METADATA_DEPTH`, which is reported by a separate error; qed"
253 );
254 let (def_compact_metadata, def_compact_metadata_size) =
255 ::ab_contracts_macros::__private::ContractMetadataKind::compact(
256 <dyn #trait_name as ::ab_contracts_macros::__private::ContractTraitDefinition>::METADATA,
257 )
258 .expect(
259 "Generated metadata is correct unless a type in it is nested deeper than \
260 `MAX_METADATA_DEPTH`, which is reported by a separate error; qed"
261 );
262 ::core::assert!(
263 impl_compact_metadata_size == def_compact_metadata_size,
264 "Trait implementation must match trait definition exactly"
265 );
266 let mut i = 0;
267 while impl_compact_metadata_size > i {
268 ::core::assert!(
269 impl_compact_metadata[i] == def_compact_metadata[i],
270 "Trait implementation must match trait definition exactly"
271 );
272 i += 1;
273 }
274 };
275
276 #[cfg(feature = "guest")]
278 const _: () = <dyn #trait_name as ::ab_contracts_macros::__private::ContractTraitDefinition>::GUEST_FEATURE_ENABLED;
279
280 #item_impl
281
282 unsafe impl ::ab_contracts_macros::__private::ContractTrait<dyn #trait_name> for #struct_name {
285 #method_fn_pointers_const
286 }
287
288 #[expect(clippy::inline_modules, reason = "Macro-generated")]
290 #[expect(clippy::wildcard_imports, reason = "Macro-generated")]
291 pub mod #ffi_mod_ident {
292 use super::*;
293
294 #( #guest_ffis )*
295 }
296 })
297}
298
299fn generate_trait_metadata(
300 contract_details: &ContractDetails,
301 trait_name: &Ident,
302 span: Span,
303) -> Result<TraitItemConst, Error> {
304 let num_methods = u8::try_from(contract_details.methods.len()).map_err(|_error| {
305 Error::new(
306 span,
307 format!("Trait can't have more than {} methods", u8::MAX),
308 )
309 })?;
310 let num_methods = Literal::u8_unsuffixed(num_methods);
311 let methods = contract_details
312 .methods
313 .iter()
314 .map(|method| &method.original_ident);
315 let trait_name_metadata = derive_ident_metadata(trait_name)?;
316
317 Ok(parse_quote! {
324 const METADATA: &[::core::primitive::u8] = {
328 const fn metadata()
329 -> ([::core::primitive::u8; ::ab_contracts_macros::__private::MAX_METADATA_CAPACITY], ::core::primitive::usize)
330 {
331 ::ab_contracts_macros::__private::concat_metadata_sources(&[
332 &[::ab_contracts_macros::__private::ContractMetadataKind::Trait as ::core::primitive::u8],
333 #trait_name_metadata,
334 &[#num_methods],
335 #( ffi::#methods::METADATA, )*
336 ])
337 }
338
339 let (metadata_scratch, metadata_size) = &metadata();
341 <[_]>::split_at(metadata_scratch, *metadata_size).0
342 };
343 })
344}
345
346fn process_struct_impl(mut item_impl: ItemImpl) -> Result<TokenStream, Error> {
347 let struct_name = item_impl.self_ty.as_ref();
348
349 item_impl.attrs.extend([
351 parse_quote! { #[expect(clippy::allow_attributes, reason = "Attribute below")] },
352 parse_quote! { #[allow(clippy::trivially_copy_pass_by_ref, reason = "API requirement")] },
353 ]);
354
355 let mut guest_ffis = Vec::with_capacity(item_impl.items.len());
356 let mut trait_ext_components = Vec::with_capacity(item_impl.items.len());
357 let mut contract_details = ContractDetails::default();
358
359 for item in &mut item_impl.items {
360 if let ImplItem::Fn(impl_item_fn) = item {
361 let method_output = process_fn(
362 struct_name.clone(),
363 None,
364 impl_item_fn,
365 &mut contract_details,
366 )?;
367 guest_ffis.push(method_output.guest_ffi);
368 trait_ext_components.push(method_output.trait_ext_components);
369 }
370 }
371
372 let slot_type = MethodDetails::slot_type(
373 contract_details
374 .methods
375 .iter()
376 .map(|method| &method.methods_details),
377 )?;
378 let tmp_type = MethodDetails::tmp_type(
379 contract_details
380 .methods
381 .iter()
382 .map(|method| &method.methods_details),
383 )?;
384
385 let max_depth_assertions = [
386 max_depth_assertion(
387 struct_name,
388 "State type must not be nested deeper than `MAX_METADATA_DEPTH`",
389 ),
390 max_depth_assertion(
391 &slot_type,
392 "`#[slot]` type must not be nested deeper than `MAX_METADATA_DEPTH`",
393 ),
394 max_depth_assertion(
395 &tmp_type,
396 "`#[tmp]` type must not be nested deeper than `MAX_METADATA_DEPTH`",
397 ),
398 ];
399
400 let metadata_const = {
401 let num_methods = u8::try_from(contract_details.methods.len()).map_err(|_error| {
402 Error::new(
403 item_impl.span(),
404 format!("Struct can't have more than {} methods", u8::MAX),
405 )
406 })?;
407 let num_methods = Literal::u8_unsuffixed(num_methods);
408 let methods = contract_details
409 .methods
410 .iter()
411 .map(|method| &method.original_ident);
412
413 quote! {
419 const MAIN_CONTRACT_METADATA: &[::core::primitive::u8] = {
420 const fn metadata()
421 -> ([::core::primitive::u8; ::ab_contracts_macros::__private::MAX_METADATA_CAPACITY], ::core::primitive::usize)
422 {
423 ::ab_contracts_macros::__private::concat_metadata_sources(&[
424 &[::ab_contracts_macros::__private::ContractMetadataKind::Contract as ::core::primitive::u8],
425 <#struct_name as ::ab_contracts_macros::__private::IoType>::METADATA,
426 <#slot_type as ::ab_contracts_macros::__private::IoType>::METADATA,
427 <#tmp_type as ::ab_contracts_macros::__private::IoType>::METADATA,
428 &[#num_methods],
429 #( ffi::#methods::METADATA, )*
430 ])
431 }
432
433 let (metadata_scratch, metadata_size) = &metadata();
435 <[_]>::split_at(metadata_scratch, *metadata_size).0
436 };
437 }
438 };
439 let method_fn_pointers_const = {
440 let methods = contract_details
441 .methods
442 .iter()
443 .map(|method| &method.original_ident);
444
445 quote! {
446 #[doc(hidden)]
447 const NATIVE_EXECUTOR_METHODS: &[::ab_contracts_macros::__private::NativeExecutorContactMethod] = &[
448 #( ffi::#methods::fn_pointer::METHOD_FN_POINTER, )*
449 ];
450 }
451 };
452
453 let struct_name_ident = extract_ident_from_type(struct_name)
454 .expect("Checked in `contract()` before processing the implementation; qed");
455
456 let ext_trait = generate_extension_trait(struct_name_ident, &trait_ext_components);
457
458 let struct_name_str = struct_name_ident.to_string();
459 let static_name = format_ident!("{METADATA_STATIC_NAME_PREFIX}{}", struct_name_str);
460 Ok(quote! {
461 #[cfg(feature = "guest")]
463 #[allow(
464 unexpected_cfgs,
465 reason = "`abundance` is only a known `target_env` value when compiling for contracts"
466 )]
467 const _: () = {
468 #[used]
478 #[unsafe(no_mangle)]
479 #[cfg_attr(
480 target_env = "abundance",
481 unsafe(link_section = "ab-contract-metadata")
482 )]
483 static #static_name: [
484 ::core::primitive::u8;
485 <#struct_name as ::ab_contracts_macros::__private::Contract>::MAIN_CONTRACT_METADATA
486 .len()
487 ] = unsafe {
488 *<#struct_name as ::ab_contracts_macros::__private::Contract>::MAIN_CONTRACT_METADATA
489 .as_ptr()
490 .cast()
491 };
492 };
493
494 const _: () = {
497 #( #max_depth_assertions )*
498 };
499
500 unsafe impl ::ab_contracts_macros::__private::Contract for #struct_name {
501 #metadata_const
502 #method_fn_pointers_const
503 #[doc(hidden)]
504 const CODE: &::core::primitive::str = ::ab_contracts_macros::__private::concatcp!(
505 #struct_name_str,
506 '[',
507 ::core::env!("CARGO_PKG_NAME"),
508 '/',
509 ::core::file!(),
510 ':',
511 ::core::line!(),
512 ':',
513 ::core::column!(),
514 ']',
515 );
516 #[cfg(feature = "guest")]
518 #[doc(hidden)]
519 const GUEST_FEATURE_ENABLED: () = ();
520 type Slot = #slot_type;
521 type Tmp = #tmp_type;
522
523 fn code() -> impl ::core::ops::Deref<
524 Target = ::ab_contracts_macros::__private::VariableBytes<
525 'static,
526 { ::ab_contracts_macros::__private::MAX_CODE_SIZE },
527 >,
528 > {
529 const fn code_bytes() -> &'static [::core::primitive::u8] {
530 <#struct_name as ::ab_contracts_macros::__private::Contract>::CODE.as_bytes()
531 }
532
533 const fn code_size() -> ::core::primitive::u32 {
534 code_bytes().len() as ::core::primitive::u32
535 }
536
537 static CODE_SIZE: ::core::primitive::u32 = code_size();
538
539 ::ab_contracts_macros::__private::VariableBytes::from_buffer(
540 code_bytes(),
541 &CODE_SIZE
542 )
543 .expect("Size is the length of the code, which is a short string; qed")
544 }
545 }
546
547 #item_impl
548
549 #ext_trait
550
551 #[expect(clippy::inline_modules, reason = "Macro-generated")]
553 #[expect(clippy::wildcard_imports, reason = "Macro-generated")]
554 pub mod ffi {
555 use super::*;
556
557 #( #guest_ffis )*
558 }
559 })
560}
561
562fn process_fn_definition(
563 trait_name: &Ident,
564 trait_item_fn: &mut TraitItemFn,
565 contract_details: &mut ContractDetails,
566) -> Result<MethodOutput, Error> {
567 if let Some(init_attr) = trait_item_fn
568 .attrs
569 .iter()
570 .find(|attr| attr.path().is_ident("init"))
571 {
572 return Err(Error::new(
573 init_attr.span(),
574 "`#[init]` is not supported in trait definitions, since the initial state is specific \
575 to each contract that implements the trait",
576 ));
577 }
578
579 let supported_attrs = HashMap::<_, fn(_, _, _, _) -> _>::from_iter([
580 (format_ident!("update"), process_update_fn_definition as _),
581 (format_ident!("view"), process_view_fn_definition as _),
582 ]);
583 let mut attrs = trait_item_fn.attrs.extract_if(.., |attr| match &attr.meta {
584 Meta::Path(path) => {
585 path.leading_colon.is_none()
586 && path.segments.len() == 1
587 && supported_attrs.contains_key(&path.segments[0].ident)
588 }
589 Meta::List(_meta_list) => false,
590 Meta::NameValue(_meta_name_value) => false,
591 });
592
593 let Some(attr) = attrs.next() else {
594 drop(attrs);
595
596 return Ok(MethodOutput::default());
598 };
599
600 if let Some(next_attr) = attrs.take(1).next() {
601 return Err(Error::new(
602 next_attr.span(),
603 format!(
604 "The method `{}` can only have one of `#[update]` or `#[view]` attributes specified",
605 trait_item_fn.sig.ident
606 ),
607 ));
608 }
609
610 if let Some(abi) = &trait_item_fn.sig.abi {
612 return Err(Error::new(
613 abi.span(),
614 format!(
615 "The method `{}` with `#[{}]` attribute must have default ABI",
616 trait_item_fn.sig.ident,
617 attr.meta.path().segments[0].ident
618 ),
619 ));
620 }
621
622 if trait_item_fn.default.is_some() {
623 return Err(Error::new(
624 trait_item_fn.span(),
625 "`#[contract]` does not support `#[update]` or `#[view]` methods with default implementation \
626 in trait definition",
627 ));
628 }
629
630 let processor = supported_attrs
631 .get(&attr.path().segments[0].ident)
632 .expect("Matched above to be one of the supported attributes; qed");
633 processor(
634 trait_name,
635 &mut trait_item_fn.sig,
636 trait_item_fn.attrs.as_slice(),
637 contract_details,
638 )
639}
640
641fn process_fn(
642 struct_name: Type,
643 trait_name: Option<&Ident>,
644 impl_item_fn: &mut ImplItemFn,
645 contract_details: &mut ContractDetails,
646) -> Result<MethodOutput, Error> {
647 let supported_attrs = HashMap::<_, fn(_, _, _, _, _) -> _>::from_iter([
648 (format_ident!("init"), process_init_fn as _),
649 (format_ident!("update"), process_update_fn as _),
650 (format_ident!("view"), process_view_fn as _),
651 ]);
652 let mut attrs = impl_item_fn.attrs.extract_if(.., |attr| match &attr.meta {
653 Meta::Path(path) => {
654 path.leading_colon.is_none()
655 && path.segments.len() == 1
656 && supported_attrs.contains_key(&path.segments[0].ident)
657 }
658 Meta::List(_meta_list) => false,
659 Meta::NameValue(_meta_name_value) => false,
660 });
661
662 let Some(attr) = attrs.next() else {
663 drop(attrs);
664
665 return Ok(MethodOutput::default());
667 };
668
669 if let Some(next_attr) = attrs.take(1).next() {
670 return Err(Error::new(
671 next_attr.span(),
672 format!(
673 "The method `{}` can only have one of `#[init]`, `#[update]` or `#[view]` attributes specified",
674 impl_item_fn.sig.ident
675 ),
676 ));
677 }
678
679 if !(matches!(impl_item_fn.vis, Visibility::Public(_)) || trait_name.is_some()) {
681 return Err(Error::new(
682 impl_item_fn.sig.span(),
683 format!(
684 "The method `{}` with `#[{}]` attribute must be public",
685 impl_item_fn.sig.ident,
686 attr.meta.path().segments[0].ident
687 ),
688 ));
689 }
690
691 if let Some(abi) = &impl_item_fn.sig.abi {
693 return Err(Error::new(
694 abi.span(),
695 format!(
696 "The method `{}` with `#[{}]` attribute must have default ABI",
697 impl_item_fn.sig.ident,
698 attr.meta.path().segments[0].ident
699 ),
700 ));
701 }
702
703 let processor = supported_attrs
704 .get(&attr.path().segments[0].ident)
705 .expect("Matched above to be one of the supported attributes; qed");
706 processor(
707 struct_name,
708 trait_name,
709 &mut impl_item_fn.sig,
710 impl_item_fn.attrs.as_slice(),
711 contract_details,
712 )
713}
714
715fn generate_extension_trait(
716 ident: &Ident,
717 trait_ext_components: &[ExtTraitComponents],
718) -> TokenStream {
719 let trait_name = format_ident!("{ident}Ext");
720 let trait_doc = format!(
721 "Extension trait that provides helper methods for calling [`{ident}`]'s methods on \
722 [`Env`](::ab_contracts_macros::__private::Env) for convenience purposes"
723 );
724 let definitions = trait_ext_components
725 .iter()
726 .map(|components| &components.definition);
727 let impls = trait_ext_components
728 .iter()
729 .map(|components| &components.r#impl);
730
731 quote! {
732 #[expect(clippy::wildcard_imports, reason = "Macro-generated")]
733 use ffi::*;
734
735 #[doc = #trait_doc]
736 #[automatically_derived]
737 #[expect(clippy::allow_attributes, reason = "Attribute below")]
738 #[allow(clippy::trivially_copy_pass_by_ref, reason = "API requirement")]
739 #[allow(rustdoc::redundant_explicit_links, reason = "Macro-generated")]
740 pub trait #trait_name {
741 #( #definitions )*
742 }
743
744 #[automatically_derived]
745 impl #trait_name for ::ab_contracts_macros::__private::Env<'_> {
746 #( #impls )*
747 }
748 }
749}