fuels_code_gen/program_bindings/
abigen.rs

1use std::{collections::HashSet, path::PathBuf};
2
3pub use abigen_target::{Abi, AbigenTarget, ProgramType};
4use fuel_abi_types::abi::full_program::FullTypeDeclaration;
5use inflector::Inflector;
6use itertools::Itertools;
7use proc_macro2::TokenStream;
8use quote::quote;
9use regex::Regex;
10
11use crate::{
12    error::Result,
13    program_bindings::{
14        abigen::bindings::generate_bindings, custom_types::generate_types,
15        generated_code::GeneratedCode,
16    },
17    utils::ident,
18};
19
20mod abigen_target;
21mod bindings;
22mod configurables;
23mod logs;
24
25pub struct Abigen;
26
27impl Abigen {
28    /// Generate code which can be used to interact with the underlying
29    /// contract, script or predicate in a type-safe manner.
30    ///
31    /// # Arguments
32    ///
33    /// * `targets`: `AbigenTargets` detailing which ABI to generate bindings
34    ///   for, and of what nature (Contract, Script or Predicate).
35    /// * `no_std`: don't use the Rust std library.
36    pub fn generate(targets: Vec<AbigenTarget>, no_std: bool) -> Result<TokenStream> {
37        let generated_code = Self::generate_code(no_std, targets)?;
38
39        let use_statements = generated_code.use_statements_for_uniquely_named_types();
40
41        let code = if no_std {
42            Self::wasm_paths_hotfix(&generated_code.code())
43        } else {
44            generated_code.code()
45        };
46
47        Ok(quote! {
48            #code
49            #use_statements
50        })
51    }
52    fn wasm_paths_hotfix(code: &TokenStream) -> TokenStream {
53        [
54            (r"::\s*std\s*::\s*string", "::alloc::string"),
55            (r"::\s*std\s*::\s*format", "::alloc::format"),
56            (r"::\s*std\s*::\s*vec", "::alloc::vec"),
57            (r"::\s*std\s*::\s*boxed", "::alloc::boxed"),
58        ]
59        .map(|(reg_expr_str, substitute)| (Regex::new(reg_expr_str).unwrap(), substitute))
60        .into_iter()
61        .fold(code.to_string(), |code, (regex, wasm_include)| {
62            regex.replace_all(&code, wasm_include).to_string()
63        })
64        .parse()
65        .expect("Wasm hotfix failed!")
66    }
67
68    fn generate_code(no_std: bool, parsed_targets: Vec<AbigenTarget>) -> Result<GeneratedCode> {
69        let custom_types = Self::filter_custom_types(&parsed_targets);
70        let shared_types = Self::filter_shared_types(custom_types);
71
72        let bindings = Self::generate_all_bindings(parsed_targets, no_std, &shared_types)?;
73        let shared_types = Self::generate_shared_types(shared_types, no_std)?;
74
75        let mod_name = ident("abigen_bindings");
76        Ok(shared_types.merge(bindings).wrap_in_mod(mod_name))
77    }
78
79    fn generate_all_bindings(
80        targets: Vec<AbigenTarget>,
81        no_std: bool,
82        shared_types: &HashSet<FullTypeDeclaration>,
83    ) -> Result<GeneratedCode> {
84        targets
85            .into_iter()
86            .map(|target| Self::generate_binding(target, no_std, shared_types))
87            .fold_ok(GeneratedCode::default(), |acc, generated_code| {
88                acc.merge(generated_code)
89            })
90    }
91
92    fn generate_binding(
93        target: AbigenTarget,
94        no_std: bool,
95        shared_types: &HashSet<FullTypeDeclaration>,
96    ) -> Result<GeneratedCode> {
97        let mod_name = ident(&format!("{}_mod", &target.name.to_snake_case()));
98
99        let recompile_trigger =
100            Self::generate_macro_recompile_trigger(target.source.path.as_ref(), no_std);
101        let types = generate_types(&target.source.abi.types, shared_types, no_std)?;
102        let bindings = generate_bindings(target, no_std)?;
103        Ok(recompile_trigger
104            .merge(types)
105            .merge(bindings)
106            .wrap_in_mod(mod_name))
107    }
108
109    /// Any changes to the file pointed to by `path` will cause the reevaluation of the current
110    /// procedural macro. This is a hack until <https://github.com/rust-lang/rust/issues/99515>
111    /// lands.
112    fn generate_macro_recompile_trigger(path: Option<&PathBuf>, no_std: bool) -> GeneratedCode {
113        let code = path
114            .as_ref()
115            .map(|path| {
116                let stringified_path = path.display().to_string();
117                quote! {
118                    const _: &[u8] = include_bytes!(#stringified_path);
119                }
120            })
121            .unwrap_or_default();
122        GeneratedCode::new(code, Default::default(), no_std)
123    }
124
125    fn generate_shared_types(
126        shared_types: HashSet<FullTypeDeclaration>,
127        no_std: bool,
128    ) -> Result<GeneratedCode> {
129        let types = generate_types(&shared_types, &HashSet::default(), no_std)?;
130
131        if types.is_empty() {
132            Ok(Default::default())
133        } else {
134            let mod_name = ident("shared_types");
135            Ok(types.wrap_in_mod(mod_name))
136        }
137    }
138
139    fn filter_custom_types(
140        all_types: &[AbigenTarget],
141    ) -> impl Iterator<Item = &FullTypeDeclaration> {
142        all_types
143            .iter()
144            .flat_map(|target| &target.source.abi.types)
145            .filter(|ttype| ttype.is_custom_type())
146    }
147
148    /// A type is considered "shared" if it appears at least twice in
149    /// `all_custom_types`.
150    ///
151    /// # Arguments
152    ///
153    /// * `all_custom_types`: types from all ABIs whose bindings are being
154    ///   generated.
155    fn filter_shared_types<'a>(
156        all_custom_types: impl IntoIterator<Item = &'a FullTypeDeclaration>,
157    ) -> HashSet<FullTypeDeclaration> {
158        all_custom_types.into_iter().duplicates().cloned().collect()
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    #[test]
167    fn correctly_determines_shared_types() {
168        let types = ["type_0", "type_1", "type_0"].map(|type_field| FullTypeDeclaration {
169            type_field: type_field.to_string(),
170            components: vec![],
171            type_parameters: vec![],
172        });
173
174        let shared_types = Abigen::filter_shared_types(&types);
175
176        assert_eq!(shared_types, HashSet::from([types[0].clone()]))
177    }
178}