Skip to main content

foundry_common/preprocessor/
data.rs

1use super::{deps::ConstructorContext, span_to_range};
2use alloy_primitives::keccak256;
3use foundry_compilers::artifacts::{Source, Sources};
4use path_slash::PathExt;
5use solar::sema::{
6    Gcx,
7    hir::{ContractId, SourceId},
8    interface::source_map::FileName,
9};
10use std::{
11    collections::{BTreeMap, HashSet},
12    path::{Path, PathBuf},
13};
14
15/// Keeps data about project contracts definitions referenced from tests and scripts.
16/// Contract id -> Contract data definition mapping.
17pub type PreprocessorData = BTreeMap<ContractId, ContractData>;
18
19/// Keeps data about a contract constructor.
20#[derive(Debug)]
21pub struct ContractConstructorData {
22    /// ABI encoded args.
23    pub abi_encode_args: String,
24    /// Constructor struct fields.
25    pub struct_fields: String,
26    /// Generated helper contract identifier.
27    pub helper_contract: String,
28    /// Generated constructor argument struct identifier.
29    pub args_struct: String,
30    /// Generated ABI encoding function identifier.
31    pub encode_function: String,
32    /// Generated helper source-unit path.
33    pub helper_path: PathBuf,
34}
35
36/// Keeps data about a single contract definition.
37#[derive(Debug)]
38pub(crate) struct ContractData {
39    /// Path of the source file.
40    path: PathBuf,
41    /// Name of the contract
42    name: String,
43    /// Constructor parameters, if any.
44    pub constructor_data: Option<ContractConstructorData>,
45    /// Artifact string to pass into cheatcodes.
46    pub artifact: String,
47}
48
49impl ContractData {
50    fn new(
51        gcx: Gcx<'_>,
52        contract_id: ContractId,
53        path: &Path,
54        reserved_identifiers: &str,
55        source_units: &[PathBuf],
56    ) -> Self {
57        let contract = gcx.hir.contract(contract_id);
58        let source = gcx.hir.source(contract.source);
59        let artifact =
60            solidity_string_content(&format!("{}:{}", path.to_slash_lossy(), contract.name));
61
62        // Process data for contracts with constructor and parameters.
63        let constructor_data = contract
64            .ctor
65            .map(|ctor_id| gcx.hir.function(ctor_id))
66            .filter(|ctor| !ctor.parameters.is_empty())
67            .map(|ctor| {
68                let contract_id = keccak256(format!("{}:{}", path.to_slash_lossy(), contract.name));
69                let mut abi_encode_args = vec![];
70                let mut struct_fields = vec![];
71                let mut arg_index = 0;
72                for param_id in ctor.parameters {
73                    let param = gcx.hir.variable(*param_id);
74                    let loc = span_to_range(gcx.sess.source_map(), param.ty.span);
75                    let ty = &source.file.src[loc];
76                    let name = if let Some(ident) = param.name {
77                        ident.name.to_string()
78                    } else {
79                        // Generate a unique name if the constructor arg does not have one.
80                        arg_index += 1;
81                        unique_identifier(
82                            reserved_identifiers,
83                            format!("foundry_pp_ctor_arg{arg_index}"),
84                        )
85                    };
86                    abi_encode_args.push(format!("args.{name}"));
87                    struct_fields.push(format!("{ty} {name}"));
88                }
89
90                ContractConstructorData {
91                    abi_encode_args: abi_encode_args.join(", "),
92                    struct_fields: struct_fields.join("; "),
93                    helper_contract: unique_identifier(
94                        reserved_identifiers,
95                        format!("DeployHelper{contract_id:x}"),
96                    ),
97                    args_struct: unique_identifier(
98                        reserved_identifiers,
99                        "FoundryPpConstructorArgs".to_string(),
100                    ),
101                    encode_function: unique_identifier(
102                        reserved_identifiers,
103                        format!("encodeArgs{contract_id:x}"),
104                    ),
105                    helper_path: deploy_helper_path(&format!("{contract_id:x}"), source_units),
106                }
107            });
108
109        Self {
110            path: path.to_path_buf(),
111            name: contract.name.to_string(),
112            constructor_data,
113            artifact,
114        }
115    }
116
117    /// If contract has a non-empty constructor, generates a helper source file for it containing a
118    /// helper to encode constructor arguments.
119    ///
120    /// This is needed because current preprocessing wraps the arguments, leaving them unchanged.
121    /// This allows us to handle nested new expressions correctly. However, this requires us to have
122    /// a way to wrap both named and unnamed arguments. i.e you can't do abi.encode({arg: val}).
123    ///
124    /// This function produces a helper struct + a helper function to encode the arguments. The
125    /// struct is defined in scope of an abstract contract inheriting the contract containing the
126    /// constructor. This is done as a hack to allow us to inherit the same scope of definitions.
127    ///
128    /// The resulted helper looks like this:
129    /// ```solidity
130    /// import "lib/openzeppelin-contracts/contracts/token/ERC20.sol";
131    ///
132    /// abstract contract DeployHelper335 is ERC20 {
133    ///     struct FoundryPpConstructorArgs {
134    ///         string name;
135    ///         string symbol;
136    ///     }
137    /// }
138    ///
139    /// function encodeArgs335(DeployHelper335.FoundryPpConstructorArgs memory args) pure returns (bytes memory) {
140    ///     return abi.encode(args.name, args.symbol);
141    /// }
142    /// ```
143    ///
144    /// Example usage:
145    /// ```solidity
146    /// new ERC20(name, symbol)
147    /// ```
148    /// becomes
149    /// ```solidity
150    /// vm.deployCode("artifact path", encodeArgs335(DeployHelper335.FoundryPpConstructorArgs(name, symbol)))
151    /// ```
152    /// With named arguments:
153    /// ```solidity
154    /// new ERC20({name: name, symbol: symbol})
155    /// ```
156    /// becomes
157    /// ```solidity
158    /// vm.deployCode("artifact path", encodeArgs335(DeployHelper335.FoundryPpConstructorArgs({name: name, symbol: symbol})))
159    /// ```
160    pub fn build_helper(&self, abi_pragma: &str) -> Option<String> {
161        let Self { path, name, constructor_data, artifact: _ } = self;
162
163        let Some(constructor_details) = constructor_data else { return None };
164        let struct_fields = &constructor_details.struct_fields;
165        let abi_encode_args = &constructor_details.abi_encode_args;
166        let helper_contract = &constructor_details.helper_contract;
167        let args_struct = &constructor_details.args_struct;
168        let encode_function = &constructor_details.encode_function;
169
170        let path = solidity_string_content(path.to_slash_lossy().as_ref());
171        let helper = format!(
172            r#"
173// SPDX-License-Identifier: MIT
174pragma solidity >=0.4.0;
175{abi_pragma}
176
177import "{path}";
178
179abstract contract {helper_contract} is {name} {{
180    struct {args_struct} {{
181        {struct_fields};
182    }}
183}}
184
185function {encode_function}({helper_contract}.{args_struct} memory args) pure returns (bytes memory) {{
186    return abi.encode({abi_encode_args});
187}}
188        "#,
189        );
190
191        Some(helper)
192    }
193}
194
195/// Reserves names only in the source's import closure, which is stable across compiler jobs.
196pub(super) fn reserved_identifiers(gcx: Gcx<'_>, source: SourceId) -> String {
197    let mut visited = HashSet::new();
198    let mut pending = vec![source];
199    let mut identifiers = String::new();
200    while let Some(id) = pending.pop() {
201        if visited.insert(id) {
202            let source = gcx.hir.source(id);
203            identifiers.push_str(source.file.src.as_str());
204            identifiers.push('\n');
205            pending.extend(source.imports.iter().map(|(_, id)| *id));
206        }
207    }
208    identifiers
209}
210
211fn unique_identifier(source: &str, mut identifier: String) -> String {
212    while source.contains(&identifier) {
213        identifier.push('_');
214    }
215    identifier
216}
217
218fn solidity_string_content(value: &str) -> String {
219    value.chars().fold(String::new(), |mut escaped, char| {
220        match char {
221            '\\' => escaped.push_str("\\\\"),
222            '"' => escaped.push_str("\\\""),
223            '\n' => escaped.push_str("\\n"),
224            '\r' => escaped.push_str("\\r"),
225            '\t' => escaped.push_str("\\t"),
226            char => escaped.push(char),
227        }
228        escaped
229    })
230}
231
232/// Collects preprocessor data from referenced contracts.
233pub(crate) fn collect_preprocessor_data(
234    gcx: Gcx<'_>,
235    referenced_contracts: &HashSet<ContractId>,
236    root_dir: &Path,
237    source_units: &[PathBuf],
238) -> PreprocessorData {
239    let mut data = PreprocessorData::default();
240    for contract_id in referenced_contracts {
241        let contract = gcx.hir.contract(*contract_id);
242        let source = gcx.hir.source(contract.source);
243
244        let FileName::Real(path) = &source.file.name else {
245            continue;
246        };
247
248        // Match the compiler input paths in generated imports and artifact references.
249        let path = path.strip_prefix(root_dir).unwrap_or(path);
250        let contract_data = ContractData::new(
251            gcx,
252            *contract_id,
253            path,
254            &reserved_identifiers(gcx, contract.source),
255            source_units,
256        );
257        data.insert(*contract_id, contract_data);
258    }
259    data
260}
261
262/// Creates helper libraries for contracts with a non-empty constructor.
263///
264/// See [`ContractData::build_helper`] for more details.
265pub(crate) fn create_deploy_helpers(
266    gcx: Gcx<'_>,
267    constructor_context: ConstructorContext,
268    data: &BTreeMap<ContractId, ContractData>,
269) -> Sources {
270    let mut deploy_helpers = Sources::new();
271    for (id, contract) in data {
272        // Helpers need their own pragma only when the compiler defaults to ABI coder v1.
273        let abi_pragma = if !constructor_context.abi_coder_v2
274            && constructor_context.for_source(gcx, gcx.hir.contract(*id).source).abi_coder_v2
275        {
276            "pragma experimental ABIEncoderV2;"
277        } else {
278            ""
279        };
280        if let Some(code) = contract.build_helper(abi_pragma) {
281            let path = contract.constructor_data.as_ref().unwrap().helper_path.clone();
282            deploy_helpers.insert(path, Source::new(code));
283        }
284    }
285    deploy_helpers
286}
287
288/// Directory of the deploy helper sources generated by the preprocessor.
289const DEPLOY_HELPERS_DIR: &str = "foundry-pp";
290
291/// Returns a generated helper path that cannot overwrite an existing source unit.
292///
293/// Keep `is_source_context_change_relevant` in sync with how this reads `source_units`.
294pub(crate) fn deploy_helper_path(contract_id: &str, source_units: &[PathBuf]) -> PathBuf {
295    let mut stem = format!("DeployHelper{contract_id}");
296    loop {
297        let path = PathBuf::from(format!("{DEPLOY_HELPERS_DIR}/{stem}.sol"));
298        if !source_units.iter().any(|source_unit| source_unit == &path) {
299            return path;
300        }
301        stem.push('_');
302    }
303}
304
305/// Returns whether the path points to a deploy helper source generated by the preprocessor.
306///
307/// These sources only exist in the compiler input and are never written to disk.
308pub fn is_deploy_helper_path(path: &Path) -> bool {
309    path.parent().and_then(Path::file_name).is_some_and(|dir| dir == DEPLOY_HELPERS_DIR)
310        && path
311            .file_stem()
312            .and_then(|stem| stem.to_str())
313            .is_some_and(|stem| stem.starts_with("DeployHelper"))
314}
315
316#[cfg(test)]
317mod tests {
318    use super::*;
319
320    #[test]
321    fn deploy_helper_path_does_not_replace_source_units() {
322        let source_units = [
323            PathBuf::from("foundry-pp/DeployHelper7.sol"),
324            PathBuf::from("foundry-pp/DeployHelper7_.sol"),
325        ];
326
327        assert_eq!(
328            deploy_helper_path("7", &source_units),
329            PathBuf::from("foundry-pp/DeployHelper7__.sol")
330        );
331    }
332
333    #[test]
334    fn is_deploy_helper_path_matches_generated_helpers() {
335        assert!(is_deploy_helper_path(Path::new("foundry-pp/DeployHelper7.sol")));
336        assert!(is_deploy_helper_path(Path::new("/project/foundry-pp/DeployHelper7_.sol")));
337        assert!(!is_deploy_helper_path(Path::new("/project/src/DeployHelper7.sol")));
338        assert!(!is_deploy_helper_path(Path::new("/project/foundry-pp/Counter.sol")));
339    }
340}