1use super::{
2 data::{ContractData, PreprocessorData, deploy_helper_path, reserved_identifiers},
3 span_to_range,
4};
5use crate::fs::{canonicalize_path, normalize_path};
6use alloy_primitives::keccak256;
7use foundry_compilers::{
8 ProjectPathsConfig, Updates,
9 artifacts::{SolcLanguage, remappings::Remapping},
10 project::{NativeDependencies, NativeDependencyState, PreprocessorState},
11};
12use itertools::Itertools;
13use path_slash::PathExt;
14use solar::{
15 ast::{ItemKind, UserDefinableOperator},
16 sema::{
17 Gcx, Hir,
18 builtins::Builtin,
19 hir::{
20 CallArgs, CallArgsKind, CallOptions, Contract, ContractId, ContractKind, Expr,
21 ExprKind, Function, FunctionId, FunctionKind, Modifier, Res, SourceId, StateMutability,
22 Stmt, StmtKind, TypeKind, UsingDirective, UsingEntryKind, Variable, VariableId,
23 Visibility, Visit,
24 },
25 interface::{SourceMap, Symbol, data_structures::Never, source_map::FileName},
26 },
27};
28use std::{
29 collections::{BTreeMap, BTreeSet, HashSet},
30 ops::{ControlFlow, Range},
31 path::{Path, PathBuf},
32};
33
34#[derive(Clone, Copy)]
36pub(super) struct ConstructorContext {
37 pub abi_coder_v2: bool,
38 pub supports_create2: bool,
39}
40
41impl ConstructorContext {
42 pub(super) fn for_source(mut self, gcx: Gcx<'_>, source: SourceId) -> Self {
43 let ast = gcx
44 .sources
45 .get_file(&gcx.hir.source(source).file)
46 .and_then(|(_, source)| source.ast.as_ref());
47 let Some(ast) = ast else {
48 self.abi_coder_v2 = false;
49 return self;
50 };
51 for item in ast.items.iter() {
52 if let ItemKind::Pragma(pragma) = &item.kind
53 && let Some((name, Some(value))) = pragma.tokens.as_name_and_value()
54 {
55 match (name.as_str(), value.as_str()) {
56 ("abicoder", "v1") => {
57 self.abi_coder_v2 = false;
58 return self;
59 }
60 ("abicoder", "v2") | ("experimental", "ABIEncoderV2") => {
61 self.abi_coder_v2 = true;
62 }
63 _ => {}
64 }
65 }
66 }
67 self
68 }
69}
70
71pub(crate) struct PreprocessorDependencies {
73 pub preprocessed_contracts: BTreeMap<ContractId, Vec<BytecodeDependency>>,
75 pub referenced_contracts: HashSet<ContractId>,
77}
78
79impl PreprocessorDependencies {
80 #[allow(clippy::too_many_arguments)]
81 pub fn new(
82 gcx: Gcx<'_>,
83 constructor_context: ConstructorContext,
84 paths: &[PathBuf],
85 script_paths: &HashSet<PathBuf>,
86 project_paths: &ProjectPathsConfig<SolcLanguage>,
87 source_units: &[PathBuf],
88 mocks: &mut HashSet<PathBuf>,
89 preprocessor_state: &mut PreprocessorState,
90 ) -> Self {
91 let relative_paths = project_paths.paths_relative();
92 let src_dir = &relative_paths.sources;
93 let root_dir = &project_paths.root;
94 let remappings = &project_paths.remappings;
95 let mut preprocessed_contracts = BTreeMap::new();
96 let mut referenced_contracts = HashSet::new();
97 let mut current_mocks = HashSet::new();
98 let mut current_native_dependencies = NativeDependencies::new();
99 let candidate_files =
100 paths.iter().map(|path| normalize_path(&root_dir.join(path))).collect::<HashSet<_>>();
101 let mut conservative_files = HashSet::new();
102 let global_using_dependencies = using_dependency_sources(
103 gcx,
104 gcx.hir
105 .source_ids()
106 .flat_map(|id| gcx.hir.source(id).usings)
107 .filter(|directive| directive.global),
108 );
109
110 let candidate_contracts = || {
112 gcx.hir.contract_ids().filter_map(|id| {
113 let contract = gcx.hir.contract(id);
114 let source = gcx.hir.source(contract.source);
115 let FileName::Real(path) = &source.file.name else {
116 return None;
117 };
118
119 if !paths.contains(path) {
120 trace!("{} is not test or script", path.display());
121 return None;
122 }
123
124 Some((id, contract, source, path))
125 })
126 };
127
128 let mut native_return_data_contracts = HashSet::new();
131 for (id, _, _, _) in candidate_contracts() {
132 let mut observer = ReturnDataObserver::new(gcx);
133 let _ = observer.visit_nested_contract(id);
134 if observer.observes_return_data {
135 native_return_data_contracts.insert(id);
136 native_return_data_contracts.extend(observer.contracts);
137 }
138 }
139
140 for (_, contract, _, path) in candidate_contracts() {
142 let full_path = normalize_path(&root_dir.join(path));
143 let mut inherited_dependencies = BTreeSet::new();
144 let mut inherits_source_contract = false;
145 for base_id in contract.linearized_bases {
146 let base = gcx.hir.contract(*base_id);
147 if let FileName::Real(base_path) = &gcx.hir.source(base.source).file.name {
148 let base_path = normalize_path(&root_dir.join(base_path));
149 let is_source_contract = is_path_in_dir(&base_path, src_dir, root_dir);
150 inherits_source_contract |= is_source_contract;
151 if base_path != full_path {
152 inherited_dependencies.insert(base_path);
153 }
154 }
155 }
156 if inherits_source_contract {
157 trace!("found mock contract {}", full_path.display());
158 current_mocks.insert(full_path.clone());
159 }
160 if !inherited_dependencies.is_empty() {
161 add_native_dependencies(
162 &mut current_native_dependencies,
163 full_path,
164 inherited_dependencies,
165 );
166 }
167 }
168
169 for (contract_id, contract, source, path) in candidate_contracts() {
171 let full_path = normalize_path(&root_dir.join(path));
172
173 if current_mocks.contains(&full_path) {
174 trace!("{} is a mock, skipping", path.display());
175 continue;
176 }
177
178 let is_script = script_paths.contains(path)
182 || contract
183 .linearized_bases
184 .iter()
185 .skip(1)
186 .any(|base_id| gcx.hir.contract(*base_id).name.as_str() == "Script");
187 let mut deps_collector = BytecodeDependencyCollector::new(
188 gcx,
189 contract_id,
190 path,
191 src_dir,
192 root_dir,
193 is_script,
194 constructor_context.for_source(gcx, contract.source),
195 );
196 deps_collector.preserve_native_bytecode =
197 native_return_data_contracts.contains(&contract_id);
198 let mut using_dependencies = global_using_dependencies.clone();
199 using_dependencies.extend(using_dependency_sources(
200 gcx,
201 source.usings.iter().chain(
202 contract
203 .linearized_bases
204 .iter()
205 .flat_map(|base_id| gcx.hir.contract(*base_id).usings),
206 ),
207 ));
208 for source_id in using_dependencies {
209 deps_collector.collect_source_dependencies(source_id);
210 }
211 let _ = deps_collector.walk_contract(contract);
213 if deps_collector.has_unresolved_native_dependency {
214 conservative_files.insert(full_path.clone());
215 }
216 if !deps_collector.native_dependencies.is_empty() {
217 add_native_dependencies(
218 &mut current_native_dependencies,
219 full_path.clone(),
220 deps_collector.native_dependencies,
221 );
222 }
223 deps_collector.dependencies.retain(|dependency| {
224 let dependency_id = dependency.referenced_contract;
225 let dependency = gcx.hir.contract(dependency_id);
226 let dependency_source = gcx.hir.source(dependency.source);
227 let FileName::Real(dependency_path) = &dependency_source.file.name else {
228 conservative_files.insert(full_path.clone());
229 return false;
230 };
231 let has_constructor_args = dependency
232 .ctor
233 .is_some_and(|ctor_id| !gcx.hir.function(ctor_id).parameters.is_empty());
234 if can_rewrite(
235 dependency_path,
236 path,
237 root_dir,
238 source_units,
239 remappings,
240 has_constructor_args,
241 dependency.name.as_str(),
242 ) {
243 true
244 } else {
245 add_native_dependencies(
246 &mut current_native_dependencies,
247 full_path.clone(),
248 [normalize_path(&root_dir.join(dependency_path))],
249 );
250 false
251 }
252 });
253 if !deps_collector.dependencies.is_empty() {
255 preprocessed_contracts.insert(contract_id, deps_collector.dependencies);
256 }
257 }
258
259 for file in conservative_files {
260 current_native_dependencies.insert(file, NativeDependencyState::Conservative);
261 }
262
263 for file in candidate_files {
266 let state = current_native_dependencies.remove(&file);
267 if preprocessor_state.update(file.clone(), state) {
268 mocks.remove(&file);
269 }
270 }
271 mocks.extend(current_mocks);
272
273 for dependencies in preprocessed_contracts.values() {
274 referenced_contracts.extend(dependencies.iter().map(|dep| dep.referenced_contract));
275 }
276
277 Self { preprocessed_contracts, referenced_contracts }
278 }
279}
280
281fn add_native_dependencies(
283 dependencies: &mut NativeDependencies,
284 file: PathBuf,
285 incoming: impl IntoIterator<Item = PathBuf>,
286) {
287 match dependencies.entry(file) {
288 std::collections::btree_map::Entry::Vacant(entry) => {
289 entry.insert(NativeDependencyState::Known(incoming.into_iter().collect()));
290 }
291 std::collections::btree_map::Entry::Occupied(entry) => {
292 if let NativeDependencyState::Known(dependencies) = entry.into_mut() {
293 dependencies.extend(incoming);
294 }
295 }
296 }
297}
298
299fn using_dependency_sources<'gcx>(
301 gcx: Gcx<'gcx>,
302 directives: impl IntoIterator<Item = &'gcx UsingDirective<'gcx>>,
303) -> HashSet<SourceId> {
304 directives
305 .into_iter()
306 .flat_map(|directive| directive.entries)
307 .flat_map(|entry| match entry.kind {
308 UsingEntryKind::Library(contract_id) => vec![gcx.hir.contract(contract_id).source],
309 UsingEntryKind::Functions(function_ids) => function_ids
310 .iter()
311 .map(|function_id| gcx.hir.function(*function_id).source)
312 .collect(),
313 UsingEntryKind::Err(_) => Vec::new(),
314 })
315 .collect()
316}
317
318#[derive(Debug)]
320enum BytecodeDependencyKind {
321 CreationCode,
323 RuntimeCode,
325 New {
327 name: String,
329 args_length: usize,
331 call_args_offset: usize,
333 value: Option<String>,
335 salt: Option<String>,
337 },
338}
339
340#[derive(Debug)]
342pub(crate) struct BytecodeDependency {
343 kind: BytecodeDependencyKind,
345 loc: Range<usize>,
347 referenced_contract: ContractId,
349 preserve_native: bool,
351}
352
353struct BytecodeDependencyCollector<'gcx, 'src> {
355 gcx: Gcx<'gcx>,
357 owner_contract: ContractId,
359 constructor_context: ConstructorContext,
361 source_path: PathBuf,
363 src_dir: &'src Path,
365 root_dir: &'src Path,
367 is_script: bool,
372 preserve_native_creation_code: bool,
374 preserve_native_bytecode: bool,
376 dependencies: Vec<BytecodeDependency>,
378 native_dependencies: BTreeSet<PathBuf>,
380 has_unresolved_native_dependency: bool,
382 visited_functions: HashSet<FunctionId>,
384 visited_sources: HashSet<SourceId>,
386 visited_variables: HashSet<VariableId>,
388}
389
390impl<'gcx, 'src> BytecodeDependencyCollector<'gcx, 'src> {
391 fn new(
392 gcx: Gcx<'gcx>,
393 owner_contract: ContractId,
394 source_path: &Path,
395 src_dir: &'src Path,
396 root_dir: &'src Path,
397 is_script: bool,
398 constructor_context: ConstructorContext,
399 ) -> Self {
400 Self {
401 gcx,
402 owner_contract,
403 constructor_context,
404 source_path: normalize_path(&root_dir.join(source_path)),
405 src_dir,
406 root_dir,
407 is_script,
408 preserve_native_creation_code: false,
409 preserve_native_bytecode: false,
410 dependencies: vec![],
411 native_dependencies: BTreeSet::new(),
412 has_unresolved_native_dependency: false,
413 visited_functions: HashSet::new(),
414 visited_sources: HashSet::new(),
415 visited_variables: HashSet::new(),
416 }
417 }
418
419 fn collect_function_dependency(&mut self, function_id: FunctionId) {
421 let function = self.gcx.hir.function(function_id);
422 if function.contract == Some(self.owner_contract)
423 || !self.visited_functions.insert(function_id)
424 {
425 return;
426 }
427
428 let source = self.gcx.hir.source(function.source);
429 if let FileName::Real(path) = &source.file.name {
430 let path = normalize_path(&self.root_dir.join(path));
431 if path != self.source_path {
432 self.native_dependencies.insert(path);
433 }
434 } else {
435 self.has_unresolved_native_dependency = true;
436 }
437
438 let previous = self.preserve_native_bytecode;
439 self.preserve_native_bytecode = true;
440 let _ = self.visit_function(function);
441 self.preserve_native_bytecode = previous;
442 }
443
444 fn collect_native_expr(&mut self, expr: &'gcx Expr<'gcx>) {
446 let previous = self.preserve_native_bytecode;
447 self.preserve_native_bytecode = true;
448 let _ = self.visit_expr(expr);
449 self.preserve_native_bytecode = previous;
450 }
451
452 fn collect_source_dependencies(&mut self, source_id: SourceId) {
454 if !self.visited_sources.insert(source_id) {
455 return;
456 }
457 let source = self.gcx.hir.source(source_id);
458 if let FileName::Real(path) = &source.file.name {
459 let path = normalize_path(&self.root_dir.join(path));
460 if path != self.source_path {
461 self.native_dependencies.insert(path);
462 }
463 } else {
464 self.has_unresolved_native_dependency = true;
465 }
466 for &(_, imported_source) in source.imports {
467 self.collect_source_dependencies(imported_source);
468 }
469 }
470
471 fn collect_dependency(&mut self, dependency: BytecodeDependency) {
473 let contract = self.gcx.hir.contract(dependency.referenced_contract);
474 let source = self.gcx.hir.source(contract.source);
475 let FileName::Real(path) = &source.file.name else {
476 self.has_unresolved_native_dependency = true;
477 return;
478 };
479 let native_path = normalize_path(&self.root_dir.join(path));
480
481 if self.preserve_native_bytecode || dependency.preserve_native {
482 self.native_dependencies.insert(native_path);
483 return;
484 }
485
486 if matches!(&dependency.kind, BytecodeDependencyKind::RuntimeCode) {
487 self.native_dependencies.insert(native_path);
488 return;
489 }
490
491 if self.is_script {
493 match &dependency.kind {
494 BytecodeDependencyKind::CreationCode | BytecodeDependencyKind::RuntimeCode => {
495 trace!("skip creationCode in script");
496 self.native_dependencies.insert(native_path);
497 return;
498 }
499 BytecodeDependencyKind::New { .. } => {
500 trace!("skip new-expression in script");
501 self.native_dependencies.insert(native_path);
502 return;
503 }
504 }
505 }
506
507 if self.preserve_native_creation_code
510 && matches!(&dependency.kind, BytecodeDependencyKind::CreationCode)
511 {
512 trace!("skip creationCode in native creationCode context");
513 self.native_dependencies.insert(native_path);
514 return;
515 }
516
517 let has_constructor_args = contract
518 .ctor
519 .is_some_and(|ctor_id| !self.gcx.hir.function(ctor_id).parameters.is_empty());
520 if contract.layout.is_some() && has_constructor_args {
524 trace!("skip dependency on custom-layout contract");
525 self.native_dependencies.insert(native_path);
526 return;
527 }
528
529 if constructor_uses_private_constants(self.gcx, contract) {
532 self.native_dependencies.insert(native_path);
533 return;
534 }
535
536 if !is_path_in_dir(path, self.src_dir, self.root_dir) {
539 let path = path.display();
540 trace!("keep external dependency {path} native");
541 self.native_dependencies.insert(native_path);
542 return;
543 }
544
545 self.dependencies.push(dependency);
546 }
547
548 fn collect_variable_dependency(&mut self, id: VariableId) {
550 let variable = self.gcx.hir.variable(id);
551 if !variable.is_constant() || !self.visited_variables.insert(id) {
552 return;
553 }
554 if let FileName::Real(path) = &self.gcx.hir.source(variable.source).file.name {
555 let path = normalize_path(&self.root_dir.join(path));
556 if path != self.source_path {
557 self.native_dependencies.insert(path);
558 }
559 } else {
560 self.has_unresolved_native_dependency = true;
561 }
562 if let Some(initializer) = variable.initializer {
563 self.collect_native_expr(initializer);
564 }
565 }
566}
567
568fn constructor_uses_private_constants(gcx: Gcx<'_>, contract: &Contract<'_>) -> bool {
570 contract.ctor.is_some_and(|ctor| {
571 gcx.hir.function(ctor).parameters.iter().any(|¶m| {
572 gcx.hir
573 .variable(param)
574 .ty
575 .visit(&gcx.hir, &mut |ty| {
576 if let TypeKind::Array(array) = &ty.kind
577 && let Some(size) = array.size
578 {
579 size.visit(&mut |expr| {
580 if gcx.resolved_variable(expr).is_some_and(|var| {
581 gcx.hir.variable(var).visibility == Some(Visibility::Private)
582 }) {
583 return ControlFlow::Break(());
584 }
585 ControlFlow::Continue(())
586 })?;
587 }
588 ControlFlow::Continue(())
589 })
590 .is_break()
591 })
592 })
593}
594
595fn can_rewrite(
599 path: &Path,
600 source_path: &Path,
601 root_dir: &Path,
602 source_units: &[PathBuf],
603 remappings: &[Remapping],
604 has_constructor_args: bool,
605 contract_name: &str,
606) -> bool {
607 let generated_path = path.strip_prefix(root_dir).unwrap_or(path);
608 if !source_units.iter().any(|source_unit| source_unit == generated_path)
609 || source_units.iter().filter(|source_unit| source_unit.ends_with(generated_path)).count()
610 != 1
611 {
612 return false;
613 }
614
615 if remappings.iter().any(|remapping| remapping_matches_path(remapping, generated_path)) {
619 return false;
620 }
621
622 if !has_constructor_args {
623 return true;
624 }
625
626 let identifier = keccak256(format!("{}:{contract_name}", generated_path.to_slash_lossy()));
627 let helper_path = deploy_helper_path(&format!("{identifier:x}"), source_units);
628 !remappings.iter().any(|remapping| {
629 remapping_applies(remapping, &helper_path, source_path, root_dir)
631 || remapping_applies(remapping, generated_path, &helper_path, root_dir)
632 })
633}
634
635fn is_path_in_dir(path: &Path, dir: &Path, root_dir: &Path) -> bool {
637 let path = normalize_path(&root_dir.join(path));
638 let dir = normalize_path(&root_dir.join(dir));
639 path.starts_with(&dir)
640 || canonicalize_path(path)
641 .is_ok_and(|path| canonicalize_path(dir).is_ok_and(|dir| path.starts_with(dir)))
642}
643
644fn remapping_applies(
646 remapping: &Remapping,
647 import_path: &Path,
648 source_unit: &Path,
649 root_dir: &Path,
650) -> bool {
651 let source_unit = source_unit.strip_prefix(root_dir).unwrap_or(source_unit).to_slash_lossy();
652 remapping
653 .context
654 .as_ref()
655 .is_none_or(|context| source_unit.starts_with(Path::new(context).to_slash_lossy().as_ref()))
656 && remapping_matches_path(remapping, import_path)
657}
658
659fn remapping_matches_path(remapping: &Remapping, path: &Path) -> bool {
661 path.to_slash_lossy().starts_with(&remapping.name)
662}
663
664impl<'gcx> Visit<'gcx> for BytecodeDependencyCollector<'gcx, '_> {
665 type BreakValue = Never;
666
667 fn hir(&self) -> &'gcx Hir<'gcx> {
668 &self.gcx.hir
669 }
670
671 fn visit_function(&mut self, func: &'gcx Function<'gcx>) -> ControlFlow<Self::BreakValue> {
672 let previous = self.preserve_native_creation_code;
673 self.preserve_native_creation_code = previous
674 || func.state_mutability == StateMutability::Pure
675 || matches!(func.kind, FunctionKind::Modifier);
676 self.walk_function(func)?;
677 self.preserve_native_creation_code = previous;
678 ControlFlow::Continue(())
679 }
680
681 fn visit_var(&mut self, var: &'gcx Variable<'gcx>) -> ControlFlow<Self::BreakValue> {
682 let previous = self.preserve_native_creation_code;
683 self.preserve_native_creation_code |= var.is_constant();
684 self.walk_var(var)?;
685 self.preserve_native_creation_code = previous;
686 ControlFlow::Continue(())
687 }
688
689 fn visit_expr(&mut self, expr: &'gcx Expr<'gcx>) -> ControlFlow<Self::BreakValue> {
690 #[allow(clippy::collapsible_match)]
691 match &expr.kind {
692 ExprKind::Ident(resolutions) => {
693 for &resolution in *resolutions {
694 match resolution {
695 Res::Namespace(source_id) => {
696 self.collect_source_dependencies(source_id);
697 }
698 Res::Item(item) => {
699 if let Some(function_id) = item.as_function() {
700 self.collect_function_dependency(function_id);
701 } else if let Some(variable_id) = item.as_variable() {
702 self.collect_variable_dependency(variable_id);
703 }
704 }
705 _ => {}
706 }
707 }
708 }
709 ExprKind::Call(callee, call_args) => {
710 let (call_expr, named_args) = callee.split_call_options();
711 if let Some(dependency) = handle_call_expr(
712 self.gcx,
713 self.constructor_context,
714 expr,
715 call_expr,
716 call_args,
717 &named_args,
718 ) {
719 self.collect_dependency(dependency);
720 self.visit_expr(call_expr)?;
723 if let Some(call_options) = named_args {
724 for arg in call_options.args {
725 self.collect_native_expr(&arg.value);
726 }
727 }
728 self.visit_call_args(call_args)?;
729 return ControlFlow::Continue(());
730 }
731 if let Some(function_id) = self.gcx.resolved_function(call_expr) {
732 self.collect_function_dependency(function_id);
733 }
734 }
735 ExprKind::Member(member_expr, ident) => {
736 if let ExprKind::Ident(resolutions) = member_expr.kind {
740 for resolution in resolutions {
741 if let Res::Item(item) = resolution
742 && let Some(contract_id) = item.as_contract()
743 {
744 let contract = self.gcx.hir.contract(contract_id);
745 if contract.kind == ContractKind::Library {
746 self.collect_source_dependencies(contract.source);
747 }
748 }
749 }
750 }
751 if let ExprKind::TypeCall(ty) = &member_expr.kind
752 && let TypeKind::Custom(contract_id) = &ty.kind
753 && let Some(contract_id) = contract_id.as_contract()
754 && let kind = match ident.name.as_str() {
755 "creationCode" => BytecodeDependencyKind::CreationCode,
756 "runtimeCode" => BytecodeDependencyKind::RuntimeCode,
757 _ => return self.walk_expr(expr),
758 }
759 {
760 self.collect_dependency(BytecodeDependency {
761 kind,
762 loc: span_to_range(self.gcx.sess.source_map(), expr.span),
763 referenced_contract: contract_id,
764 preserve_native: false,
765 });
766 }
767 }
768 _ => {}
769 }
770 self.walk_expr(expr)
771 }
772
773 fn visit_stmt(&mut self, stmt: &'gcx Stmt<'gcx>) -> ControlFlow<Self::BreakValue> {
774 if let StmtKind::Try(stmt_try) = stmt.kind
775 && let ExprKind::Call(callee, ..) = &stmt_try.expr.kind
776 && let (call_expr, _) = callee.split_call_options()
777 && matches!(call_expr.kind, ExprKind::New(_))
778 {
779 self.collect_native_expr(&stmt_try.expr);
783
784 for clause in stmt_try.clauses {
785 for &var in clause.args {
786 self.visit_nested_var(var)?;
787 }
788 for stmt in clause.block.stmts {
789 self.visit_stmt(stmt)?;
790 }
791 }
792 return ControlFlow::Continue(());
793 }
794 self.walk_stmt(stmt)
795 }
796}
797
798fn handle_call_expr(
800 gcx: Gcx<'_>,
801 context: ConstructorContext,
802 parent_expr: &Expr<'_>,
803 call_expr: &Expr<'_>,
804 call_args: &CallArgs<'_>,
805 call_options: &Option<&CallOptions<'_>>,
806) -> Option<BytecodeDependency> {
807 if let ExprKind::New(ty_new) = &call_expr.kind
808 && let TypeKind::Custom(item_id) = ty_new.kind
809 && let Some(contract_id) = item_id.as_contract()
810 {
811 let source_map = gcx.sess.source_map();
812 let name = source_map.span_to_snippet(ty_new.span).ok()?;
813
814 let call_args_offset = if call_args.is_empty() {
819 0
820 } else {
821 (call_args.span.lo() - ty_new.span.hi()).to_usize()
822 };
823
824 let args_len = parent_expr.span.hi() - ty_new.span.hi();
825 return Some(BytecodeDependency {
826 kind: BytecodeDependencyKind::New {
827 name,
828 args_length: args_len.to_usize(),
829 call_args_offset,
830 value: named_arg(call_options, "value", source_map),
831 salt: named_arg(call_options, "salt", source_map),
832 },
833 loc: span_to_range(source_map, parent_expr.span.with_hi(call_expr.span.hi())),
835 referenced_contract: contract_id,
836 preserve_native: !valid_constructor_call(
837 gcx,
838 context,
839 contract_id,
840 call_args,
841 call_options,
842 ),
843 });
844 }
845 None
846}
847
848fn named_arg(
850 call_options: &Option<&CallOptions<'_>>,
851 arg: &str,
852 source_map: &SourceMap,
853) -> Option<String> {
854 call_options
855 .map(|options| options.args)
856 .unwrap_or_default()
857 .iter()
858 .find(|named_arg| named_arg.name.as_str() == arg)
859 .and_then(|named_arg| source_map.span_to_snippet(named_arg.value.span).ok())
860}
861
862pub(crate) fn remove_bytecode_dependencies(
867 gcx: Gcx<'_>,
868 deps: &PreprocessorDependencies,
869 data: &PreprocessorData,
870 root_dir: &Path,
871 use_uint160_return: bool,
872) -> Updates {
873 let mut updates = Updates::default();
874 for (contract_id, deps) in &deps.preprocessed_contracts {
875 let contract = gcx.hir.contract(*contract_id);
876 let source = gcx.hir.source(contract.source);
877 let FileName::Real(path) = &source.file.name else {
878 continue;
879 };
880
881 let reserved_identifiers = reserved_identifiers(gcx, contract.source);
882 let identifier = keccak256(format!(
883 "{}:{}",
884 path.strip_prefix(root_dir).unwrap_or(path).to_slash_lossy(),
885 contract.name,
886 ));
887 let updates = updates.entry(path.clone()).or_default();
888 let mut used_helpers = BTreeSet::new();
889
890 let vm_interface_name =
891 unique_identifier(&reserved_identifiers, format!("VmContractHelper{identifier:x}"));
892 let vm = format!("{vm_interface_name}(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D)");
894 for dep in deps {
895 let Some(ContractData { artifact, constructor_data, .. }) =
896 data.get(&dep.referenced_contract)
897 else {
898 continue;
899 };
900
901 match &dep.kind {
902 BytecodeDependencyKind::CreationCode => {
903 updates.insert((
905 dep.loc.start,
906 dep.loc.end,
907 format!("{vm}.getCode(\"{artifact}\")"),
908 ));
909 }
910 BytecodeDependencyKind::RuntimeCode => {
911 unreachable!("runtimeCode is never rewritten")
912 }
913 BytecodeDependencyKind::New {
914 name,
915 args_length,
916 call_args_offset,
917 value,
918 salt,
919 } => {
920 let mut update = format!("{name}(payable(");
921 if use_uint160_return {
922 update.push_str("address(");
923 }
924 let closing_seq = if use_uint160_return { "}))))" } else { "})))" };
925 update.push_str(&format!("{vm}.deployCode({{"));
926 update.push_str(&format!("_artifact: \"{artifact}\""));
927
928 if let Some(value) = value {
929 update.push_str(", ");
930 update.push_str(&format!("_value: {value}"));
931 }
932
933 if let Some(salt) = salt {
934 update.push_str(", ");
935 update.push_str(&format!("_salt: {salt}"));
936 }
937
938 if let Some(constructor_data) = constructor_data {
939 used_helpers.insert(dep.referenced_contract);
941 let helper_contract = unique_identifier(
942 &reserved_identifiers,
943 constructor_data.helper_contract.clone(),
944 );
945 let encode_function = unique_identifier(
946 &reserved_identifiers,
947 constructor_data.encode_function.clone(),
948 );
949
950 update.push_str(", ");
951 update.push_str(&format!(
952 "_args: {}({}.{}",
953 encode_function, helper_contract, constructor_data.args_struct,
954 ));
955 updates.insert((dep.loc.start, dep.loc.end + call_args_offset, update));
956
957 updates.insert((
958 dep.loc.end + args_length,
959 dep.loc.end + args_length,
960 format!("){closing_seq}"),
961 ));
962 } else {
963 update.push_str(closing_seq);
964 updates.insert((dep.loc.start, dep.loc.end + args_length, update));
965 }
966 }
967 };
968 }
969
970 let helper_imports = used_helpers
971 .into_iter()
972 .map(|id| {
973 let constructor = data[&id].constructor_data.as_ref().unwrap();
974 let helper_contract = &constructor.helper_contract;
975 let encode_function = &constructor.encode_function;
976 let local_helper =
977 unique_identifier(&reserved_identifiers, helper_contract.clone());
978 let local_encoder =
979 unique_identifier(&reserved_identifiers, encode_function.clone());
980 let helper_import = import_alias(helper_contract, &local_helper);
981 let encoder_import = import_alias(encode_function, &local_encoder);
982 let helper_path = constructor.helper_path.to_slash_lossy();
983 format!("import {{{helper_import}, {encoder_import}}} from \"{helper_path}\";",)
984 })
985 .sorted()
986 .join("\n");
987 let deployment_return_type = if use_uint160_return { "uint160" } else { "address" };
988 updates.insert((
989 source.file.src.len(),
990 source.file.src.len(),
991 format!(
992 r#"
993{helper_imports}
994
995interface {vm_interface_name} {{
996 function deployCode(string memory _artifact) external returns ({deployment_return_type});
997 function deployCode(string memory _artifact, bytes32 _salt) external returns ({deployment_return_type});
998 function deployCode(string memory _artifact, bytes memory _args) external returns ({deployment_return_type});
999 function deployCode(string memory _artifact, bytes memory _args, bytes32 _salt) external returns ({deployment_return_type});
1000 function deployCode(string memory _artifact, uint256 _value) external returns ({deployment_return_type});
1001 function deployCode(string memory _artifact, uint256 _value, bytes32 _salt) external returns ({deployment_return_type});
1002 function deployCode(string memory _artifact, bytes memory _args, uint256 _value) external returns ({deployment_return_type});
1003 function deployCode(string memory _artifact, bytes memory _args, uint256 _value, bytes32 _salt) external returns ({deployment_return_type});
1004 function getCode(string memory _artifact) external view returns (bytes memory);
1005}}"#
1006 ),
1007 ));
1008 }
1009 updates
1010}
1011
1012fn unique_identifier(source: &str, mut identifier: String) -> String {
1014 while source.contains(&identifier) {
1015 identifier.push('_');
1016 }
1017 identifier
1018}
1019
1020fn import_alias(identifier: &str, local: &str) -> String {
1021 if identifier == local { identifier.to_string() } else { format!("{identifier} as {local}") }
1022}
1023
1024fn valid_constructor_call(
1028 gcx: Gcx<'_>,
1029 context: ConstructorContext,
1030 id: ContractId,
1031 args: &CallArgs<'_>,
1032 options: &Option<&CallOptions<'_>>,
1033) -> bool {
1034 let contract = gcx.hir.contract(id);
1035 if contract.kind != ContractKind::Contract {
1036 return false;
1037 }
1038 let constructor = contract.ctor.map(|id| gcx.hir.function(id));
1039 let parameters = constructor.map_or(&[][..], |ctor| ctor.parameters);
1040 if args.len() != parameters.len() || (!parameters.is_empty() && !context.abi_coder_v2) {
1041 return false;
1042 }
1043 if let CallArgsKind::Named(args) = args.kind {
1044 let mut names = HashSet::new();
1045 if args.iter().any(|arg| {
1046 !names.insert(arg.name.name)
1047 || !parameters.iter().any(|id| {
1048 gcx.hir.variable(*id).name.is_some_and(|name| name.name == arg.name.name)
1049 })
1050 }) {
1051 return false;
1052 }
1053 }
1054 if let Some(options) = options {
1055 let mut names = HashSet::new();
1056 if options.args.iter().any(|arg| {
1057 !names.insert(arg.name.name)
1058 || match arg.name.as_str() {
1059 "salt" => !context.supports_create2,
1060 "value" => constructor
1061 .is_none_or(|ctor| ctor.state_mutability != StateMutability::Payable),
1062 _ => true,
1063 }
1064 }) {
1065 return false;
1066 }
1067 }
1068 true
1069}
1070
1071struct ReturnDataObserver<'gcx> {
1073 gcx: Gcx<'gcx>,
1074 observes_return_data: bool,
1075 functions: HashSet<FunctionId>,
1076 contracts: HashSet<ContractId>,
1077 visited_contracts: HashSet<ContractId>,
1078 member_functions: HashSet<(FunctionId, Symbol)>,
1079 sources: HashSet<SourceId>,
1080 operator_functions: HashSet<(FunctionId, UserDefinableOperator)>,
1081}
1082
1083impl<'gcx> ReturnDataObserver<'gcx> {
1084 fn new(gcx: Gcx<'gcx>) -> Self {
1085 Self {
1086 gcx,
1087 observes_return_data: false,
1088 functions: HashSet::new(),
1089 contracts: HashSet::new(),
1090 visited_contracts: HashSet::new(),
1091 member_functions: HashSet::new(),
1092 sources: HashSet::new(),
1093 operator_functions: HashSet::new(),
1094 }
1095 }
1096
1097 fn collect_member_functions(&mut self, source: SourceId, contract: Option<ContractId>) {
1098 let bases = contract
1099 .into_iter()
1100 .flat_map(|id| self.gcx.hir.contract(id).linearized_bases)
1101 .copied()
1102 .collect::<Vec<_>>();
1103 for &id in &bases {
1104 self.member_functions.extend(
1105 self.gcx
1106 .hir
1107 .contract(id)
1108 .functions()
1109 .filter_map(|id| self.gcx.hir.function(id).name.map(|name| (id, name.name))),
1110 );
1111 }
1112 let directives = self
1113 .gcx
1114 .hir
1115 .source(source)
1116 .usings
1117 .iter()
1118 .chain(bases.iter().flat_map(|&id| self.gcx.hir.contract(id).usings))
1119 .chain(
1120 self.gcx
1121 .hir
1122 .source_ids()
1123 .flat_map(|id| self.gcx.hir.source(id).usings)
1124 .filter(|directive| directive.global),
1125 );
1126 for directive in directives {
1127 for entry in directive.entries {
1128 match entry.kind {
1129 UsingEntryKind::Library(id) => self.member_functions.extend(
1130 self.gcx.hir.contract(id).functions().filter_map(|id| {
1131 self.gcx.hir.function(id).name.map(|name| (id, name.name))
1132 }),
1133 ),
1134 UsingEntryKind::Functions(ids) => {
1135 if let Some(operator) = entry.operator {
1136 self.operator_functions.extend(ids.iter().map(|&id| (id, operator)));
1137 }
1138 self.member_functions.extend(ids.iter().copied().filter_map(|id| {
1139 entry
1140 .name
1141 .or_else(|| self.gcx.hir.function(id).name.map(|name| name.name))
1142 .map(|name| (id, name))
1143 }))
1144 }
1145 UsingEntryKind::Err(_) => {}
1146 }
1147 }
1148 }
1149 }
1150}
1151
1152impl<'gcx> Visit<'gcx> for ReturnDataObserver<'gcx> {
1153 type BreakValue = Never;
1154
1155 fn hir(&self) -> &'gcx Hir<'gcx> {
1156 &self.gcx.hir
1157 }
1158
1159 fn visit_nested_source(&mut self, id: SourceId) -> ControlFlow<Self::BreakValue> {
1160 if self.sources.insert(id) {
1161 let source = self.gcx.hir.source(id);
1162 self.walk_nested_source(id)?;
1163 for &(_, id) in source.imports {
1164 self.visit_nested_source(id)?;
1165 }
1166 }
1167 ControlFlow::Continue(())
1168 }
1169
1170 fn visit_nested_contract(&mut self, id: ContractId) -> ControlFlow<Self::BreakValue> {
1171 if self.visited_contracts.insert(id) {
1172 let contract = self.gcx.hir.contract(id);
1173 self.contracts.insert(id);
1174 self.collect_member_functions(contract.source, Some(id));
1177 for &base in contract.linearized_bases {
1180 if base != id {
1181 self.visit_nested_contract(base)?;
1182 }
1183 }
1184 self.walk_contract(contract)?;
1185 }
1186 ControlFlow::Continue(())
1187 }
1188
1189 fn visit_nested_function(&mut self, id: FunctionId) -> ControlFlow<Self::BreakValue> {
1190 if self.functions.insert(id) {
1191 let function = self.gcx.hir.function(id);
1192 self.collect_member_functions(function.source, function.contract);
1193 if let Some(id) = function.contract {
1194 self.contracts.insert(id);
1195 }
1196 self.walk_function(function)?;
1197 }
1198 ControlFlow::Continue(())
1199 }
1200
1201 fn visit_modifier(&mut self, modifier: &'gcx Modifier<'gcx>) -> ControlFlow<Self::BreakValue> {
1202 if let Some(id) = modifier.id.as_function() {
1203 self.visit_nested_function(id)?;
1204 }
1205 self.walk_modifier(modifier)
1206 }
1207
1208 fn visit_expr(&mut self, expr: &'gcx Expr<'gcx>) -> ControlFlow<Self::BreakValue> {
1209 let operator = match &expr.kind {
1210 ExprKind::Unary(op, _) => UserDefinableOperator::from_unop(op.kind),
1211 ExprKind::Binary(_, op, _) => UserDefinableOperator::from_binop(op.kind),
1212 _ => None,
1213 };
1214 if let Some(operator) = operator {
1215 let functions = self
1217 .operator_functions
1218 .iter()
1219 .filter_map(|&(id, bound)| (bound == operator).then_some(id))
1220 .collect::<Vec<_>>();
1221 for id in functions {
1222 self.visit_nested_function(id)?;
1223 }
1224 }
1225 match &expr.kind {
1226 ExprKind::Ident(resolutions) => {
1227 for resolution in *resolutions {
1228 match resolution {
1229 Res::Builtin(Builtin::YulReturndatasize | Builtin::YulReturndatacopy) => {
1230 self.observes_return_data = true;
1231 }
1232 Res::Item(item) => {
1233 if let Some(id) = item.as_function() {
1234 self.visit_nested_function(id)?;
1235 }
1236 }
1237 _ => {}
1238 }
1239 }
1240 }
1241 ExprKind::Call(callee, _) => {
1242 let (callee, _) = callee.split_call_options();
1243 if let Some(id) = self.gcx.resolved_function(callee) {
1244 self.visit_nested_function(id)?;
1245 }
1246 }
1247 ExprKind::Member(member, name) => {
1248 let mut names = vec![*name];
1251 let mut root = member.peel_parens();
1252 while let ExprKind::Member(parent, name) = &root.kind {
1253 names.push(*name);
1254 root = parent.peel_parens();
1255 }
1256 if let ExprKind::Ident(resolutions) = &root.kind {
1257 names.reverse();
1258 for resolution in *resolutions {
1259 if let Res::Namespace(source) = resolution {
1260 if let Some(resolutions) =
1261 self.gcx.source_path_resolutions(&names, *source, None)
1262 && let Some(targets) = resolutions.last()
1263 {
1264 for target in targets {
1265 if let Res::Item(item) = target {
1266 if let Some(id) = item.as_function() {
1267 self.visit_nested_function(id)?;
1268 } else if let Some(id) = item.as_variable() {
1269 self.visit_nested_var(id)?;
1270 }
1271 }
1272 }
1273 } else {
1274 self.visit_nested_source(*source)?;
1277 }
1278 }
1279 }
1280 }
1281 let functions = self
1284 .member_functions
1285 .iter()
1286 .copied()
1287 .filter_map(|(id, attached_name)| (attached_name == name.name).then_some(id))
1288 .collect::<Vec<_>>();
1289 for id in functions {
1290 self.visit_nested_function(id)?;
1291 }
1292 if let ExprKind::Ident(resolutions) = member.peel_parens().kind {
1293 for resolution in resolutions {
1294 if let Res::Item(item) = resolution
1295 && let Some(id) = item.as_contract()
1296 && self.gcx.hir.contract(id).kind == ContractKind::Library
1297 {
1298 for id in self.gcx.hir.contract(id).functions() {
1299 if self
1300 .gcx
1301 .hir
1302 .function(id)
1303 .name
1304 .is_some_and(|ident| ident.name == name.name)
1305 {
1306 self.visit_nested_function(id)?;
1307 }
1308 }
1309 }
1310 }
1311 }
1312 }
1313 _ => {}
1314 }
1315 self.walk_expr(expr)
1316 }
1317}