ink_codegen/generator/macros.rs
1// Copyright (C) Use Ink (UK) Ltd.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15/// Returns the "default" ABI for calls.
16///
17/// # Note
18///
19/// The "default" ABI for calls is "ink", unless the ABI is set to "sol"
20/// in the ink! project's manifest file (i.e. `Cargo.toml`).
21macro_rules! default_abi {
22 () => {{
23 if cfg!(ink_abi = "sol") {
24 quote!(::ink::abi::Sol)
25 } else {
26 quote!(::ink::abi::Ink)
27 }
28 }};
29}
30
31/// Calls the given callback function once for each enabled ABI.
32///
33/// # Note
34///
35/// The ABI is passed to the callback function as an argument.
36/// The argument value can be either as an `ink_primitives::abi::Abi` variant,
37/// or tokens for `::ink::abi::Ink` or `::ink::abi::Sol`.
38#[macro_export]
39macro_rules! for_each_abi {
40 ($callback: expr, $ink_abi: expr, $sol_abi: expr) => {{
41 #[cfg(not(ink_abi = "sol"))]
42 $callback($ink_abi);
43
44 #[cfg(any(ink_abi = "sol", ink_abi = "all"))]
45 $callback($sol_abi);
46 }};
47 (@tokens $callback: expr) => {
48 for_each_abi!($callback, quote!(::ink::abi::Ink), quote!(::ink::abi::Sol))
49 };
50 (@type $callback: expr) => {
51 for_each_abi!(
52 $callback,
53 ink_primitives::abi::Abi::Ink,
54 ink_primitives::abi::Abi::Sol
55 )
56 };
57}
58
59/// Generates code for all enabled ABIs by calling the given generator function for each
60/// enabled ABI, and returns a `TokenStream` combining all generated ABI specific code.
61/// with the ABI as an argument.
62///
63/// # Note
64///
65/// The ABI is passed to the generator function as an argument.
66/// The argument value can be either as an `ink_primitives::abi::Abi` variant,
67/// or tokens for `::ink::abi::Ink` or `::ink::abi::Sol`.
68#[macro_export]
69macro_rules! generate_abi_impls {
70 ($generator: expr, $ink_abi: expr, $sol_abi: expr) => {{
71 let mut abi_impls = Vec::new();
72 $crate::for_each_abi!(@type |abi| {
73 match abi {
74 ink_primitives::abi::Abi::Ink => {
75 abi_impls.push($generator($ink_abi));
76 },
77 ink_primitives::abi::Abi::Sol => {
78 abi_impls.push($generator($sol_abi));
79 },
80 }
81 });
82 quote! {
83 #( #abi_impls )*
84 }
85 }};
86 (@tokens $callback: expr) => {
87 generate_abi_impls!(
88 $callback,
89 quote!(::ink::abi::Ink),
90 quote!(::ink::abi::Sol)
91 )
92 };
93 (@type $callback: expr) => {
94 generate_abi_impls!(
95 $callback,
96 ink_primitives::abi::Abi::Ink,
97 ink_primitives::abi::Abi::Sol
98 )
99 };
100}