foundry_common/preprocessor/
mod.rs

1use crate::errors::convert_solar_errors;
2use foundry_compilers::{
3    Compiler, ProjectPathsConfig, SourceParser, apply_updates,
4    artifacts::SolcLanguage,
5    error::Result,
6    multi::{MultiCompiler, MultiCompilerInput, MultiCompilerLanguage},
7    project::Preprocessor,
8    solc::{SolcCompiler, SolcVersionedInput},
9};
10use solar::parse::{ast::Span, interface::SourceMap};
11use std::{
12    collections::HashSet,
13    ops::{ControlFlow, Range},
14    path::PathBuf,
15};
16
17mod data;
18use data::{collect_preprocessor_data, create_deploy_helpers};
19
20mod deps;
21use deps::{PreprocessorDependencies, remove_bytecode_dependencies};
22
23/// Returns the range of the given span in the source map.
24#[track_caller]
25fn span_to_range(source_map: &SourceMap, span: Span) -> Range<usize> {
26    source_map.span_to_range(span).unwrap()
27}
28
29/// Preprocessor that replaces static bytecode linking in tests and scripts (`new Contract`) with
30/// dynamic linkage through (`Vm.create*`).
31///
32/// This allows for more efficient caching when iterating on tests.
33///
34/// See <https://github.com/foundry-rs/foundry/pull/10010>.
35#[derive(Debug)]
36pub struct DynamicTestLinkingPreprocessor;
37
38impl Preprocessor<SolcCompiler> for DynamicTestLinkingPreprocessor {
39    #[instrument(name = "DynamicTestLinkingPreprocessor::preprocess", skip_all)]
40    fn preprocess(
41        &self,
42        _solc: &SolcCompiler,
43        input: &mut SolcVersionedInput,
44        paths: &ProjectPathsConfig<SolcLanguage>,
45        mocks: &mut HashSet<PathBuf>,
46    ) -> Result<()> {
47        // Skip if we are not preprocessing any tests or scripts. Avoids unnecessary AST parsing.
48        if !input.input.sources.iter().any(|(path, _)| paths.is_test_or_script(path)) {
49            trace!("no tests or sources to preprocess");
50            return Ok(());
51        }
52
53        let mut compiler =
54            foundry_compilers::resolver::parse::SolParser::new(paths.with_language_ref())
55                .into_compiler();
56        let _ = compiler.enter_mut(|compiler| -> solar::interface::Result {
57            let mut pcx = compiler.parse();
58
59            // Add the sources into the context.
60            // Include all sources in the source map so as to not re-load them from disk, but only
61            // parse and preprocess tests and scripts.
62            let mut preprocessed_paths = vec![];
63            let sources = &mut input.input.sources;
64            for (path, source) in sources.iter() {
65                if let Ok(src_file) = compiler
66                    .sess()
67                    .source_map()
68                    .new_source_file(path.clone(), source.content.as_str())
69                    && paths.is_test_or_script(path)
70                {
71                    pcx.add_file(src_file);
72                    preprocessed_paths.push(path.clone());
73                }
74            }
75
76            // Parse and preprocess.
77            pcx.parse();
78            let ControlFlow::Continue(()) = compiler.lower_asts()? else { return Ok(()) };
79            let gcx = compiler.gcx();
80            // Collect tests and scripts dependencies and identify mock contracts.
81            let deps = PreprocessorDependencies::new(
82                gcx,
83                &preprocessed_paths,
84                &paths.paths_relative().sources,
85                &paths.root,
86                mocks,
87            );
88            // Collect data of source contracts referenced in tests and scripts.
89            let data = collect_preprocessor_data(gcx, &deps.referenced_contracts);
90
91            // Extend existing sources with preprocessor deploy helper sources.
92            sources.extend(create_deploy_helpers(&data));
93
94            // Generate and apply preprocessor source updates.
95            apply_updates(sources, remove_bytecode_dependencies(gcx, &deps, &data));
96
97            Ok(())
98        });
99
100        // Warn if any diagnostics emitted during content parsing.
101        if let Err(err) = convert_solar_errors(compiler.dcx()) {
102            warn!(%err, "failed preprocessing");
103        }
104
105        Ok(())
106    }
107}
108
109impl Preprocessor<MultiCompiler> for DynamicTestLinkingPreprocessor {
110    fn preprocess(
111        &self,
112        compiler: &MultiCompiler,
113        input: &mut <MultiCompiler as Compiler>::Input,
114        paths: &ProjectPathsConfig<MultiCompilerLanguage>,
115        mocks: &mut HashSet<PathBuf>,
116    ) -> Result<()> {
117        // Preprocess only Solc compilers.
118        let MultiCompilerInput::Solc(input) = input else { return Ok(()) };
119
120        let Some(solc) = &compiler.solc else { return Ok(()) };
121
122        let paths = paths.clone().with_language::<SolcLanguage>();
123        self.preprocess(solc, input, &paths, mocks)
124    }
125}