foundry_common/preprocessor/
data.rs1use 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
15pub type PreprocessorData = BTreeMap<ContractId, ContractData>;
18
19#[derive(Debug)]
21pub struct ContractConstructorData {
22 pub abi_encode_args: String,
24 pub struct_fields: String,
26 pub helper_contract: String,
28 pub args_struct: String,
30 pub encode_function: String,
32 pub helper_path: PathBuf,
34}
35
36#[derive(Debug)]
38pub(crate) struct ContractData {
39 path: PathBuf,
41 name: String,
43 pub constructor_data: Option<ContractConstructorData>,
45 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 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 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 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
195pub(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
232pub(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 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
262pub(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 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
288const DEPLOY_HELPERS_DIR: &str = "foundry-pp";
290
291pub(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
305pub 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}