foundry_cli/opts/build/
utils.rs

1use eyre::Result;
2use foundry_compilers::{
3    CompilerInput, Graph, Project, ProjectCompileOutput, ProjectPathsConfig,
4    artifacts::{Source, Sources},
5    multi::{MultiCompilerLanguage, MultiCompilerParser},
6    solc::{SOLC_EXTENSIONS, SolcLanguage, SolcVersionedInput},
7};
8use foundry_config::Config;
9use rayon::prelude::*;
10use solar::{interface::MIN_SOLIDITY_VERSION, sema::ParsingContext};
11use std::{
12    collections::{HashSet, VecDeque},
13    path::{Path, PathBuf},
14};
15
16/// Configures a [`ParsingContext`] from [`Config`].
17///
18/// - Configures include paths, remappings
19/// - Source files are added if `add_source_file` is set
20/// - If no `project` is provided, it will spin up a new ephemeral project.
21/// - If no `target_paths` are provided, all project files are processed.
22/// - Only processes the subset of sources with the most up-to-date Solidity version.
23pub fn configure_pcx(
24    pcx: &mut ParsingContext<'_>,
25    config: &Config,
26    project: Option<&Project>,
27    target_paths: Option<&[PathBuf]>,
28) -> Result<()> {
29    // Process build options
30    let project = match project {
31        Some(project) => project,
32        None => &config.ephemeral_project()?,
33    };
34
35    let sources = match target_paths {
36        // If target files are provided, only process those sources
37        Some(targets) => {
38            let mut sources = Sources::new();
39            for t in targets {
40                let path = dunce::canonicalize(t)?;
41                let source = Source::read(&path)?;
42                sources.insert(path, source);
43            }
44            sources
45        }
46        // Otherwise, process all project files
47        None => project.paths.read_input_files()?,
48    };
49
50    // Only process sources with latest Solidity version to avoid conflicts.
51    let graph = Graph::<MultiCompilerParser>::resolve_sources(&project.paths, sources)?;
52    let (version, sources) = graph
53        // Resolve graph into mapping language -> version -> sources
54        .into_sources_by_version(project)?
55        .sources
56        .into_iter()
57        // Only interested in Solidity sources
58        .find(|(lang, _)| *lang == MultiCompilerLanguage::Solc(SolcLanguage::Solidity))
59        .ok_or_else(|| eyre::eyre!("no Solidity sources"))?
60        .1
61        .into_iter()
62        // Filter unsupported versions
63        .filter(|(v, _, _)| v >= &MIN_SOLIDITY_VERSION)
64        // Always pick the latest version
65        .max_by(|(v1, _, _), (v2, _, _)| v1.cmp(v2))
66        .map_or((MIN_SOLIDITY_VERSION, Sources::default()), |(v, s, _)| (v, s));
67
68    if sources.is_empty() {
69        sh_warn!("no files found. Solar doesn't support Solidity versions prior to 0.8.0")?;
70    }
71
72    let solc = SolcVersionedInput::build(
73        sources,
74        config.solc_settings()?,
75        SolcLanguage::Solidity,
76        version,
77    );
78
79    configure_pcx_from_solc(pcx, &project.paths, &solc, true);
80
81    Ok(())
82}
83
84/// Extracts Solar-compatible sources from a [`ProjectCompileOutput`].
85///
86/// # Note:
87/// uses `output.graph().source_files()` and `output.artifact_ids()` rather than `output.sources()`
88/// because sources aren't populated when build is skipped when there are no changes in the source
89/// code. <https://github.com/foundry-rs/foundry/issues/12018>
90pub fn get_solar_sources_from_compile_output(
91    config: &Config,
92    output: &ProjectCompileOutput,
93    target_paths: Option<&[PathBuf]>,
94) -> Result<SolcVersionedInput> {
95    let is_solidity_file = |path: &Path| -> bool {
96        path.extension().and_then(|s| s.to_str()).is_some_and(|ext| SOLC_EXTENSIONS.contains(&ext))
97    };
98
99    // Collect source path targets
100    let mut source_paths: HashSet<PathBuf> = if let Some(targets) = target_paths
101        && !targets.is_empty()
102    {
103        let mut source_paths = HashSet::new();
104        let mut queue: VecDeque<PathBuf> = targets
105            .iter()
106            .filter_map(|path| {
107                is_solidity_file(path).then(|| dunce::canonicalize(path).ok()).flatten()
108            })
109            .collect();
110
111        while let Some(path) = queue.pop_front() {
112            if source_paths.insert(path.clone()) {
113                for import in output.graph().imports(path.as_path()) {
114                    queue.push_back(import.to_path_buf());
115                }
116            }
117        }
118
119        source_paths
120    } else {
121        output
122            .graph()
123            .source_files()
124            .filter_map(|idx| {
125                let path = output.graph().node_path(idx).to_path_buf();
126                is_solidity_file(&path).then_some(path)
127            })
128            .collect()
129    };
130
131    // Read all sources and find the latest version.
132    let (version, sources) = {
133        let (mut max_version, mut sources) = (MIN_SOLIDITY_VERSION, Sources::new());
134        for (id, _) in output.artifact_ids() {
135            if let Ok(path) = dunce::canonicalize(&id.source)
136                && source_paths.remove(&path)
137            {
138                if id.version < MIN_SOLIDITY_VERSION {
139                    continue;
140                } else if max_version < id.version {
141                    max_version = id.version;
142                };
143
144                let source = Source::read(&path)?;
145                sources.insert(path, source);
146            }
147        }
148
149        (max_version, sources)
150    };
151
152    let solc = SolcVersionedInput::build(
153        sources,
154        config.solc_settings()?,
155        SolcLanguage::Solidity,
156        version,
157    );
158
159    Ok(solc)
160}
161
162/// Configures a [`ParsingContext`] from a [`ProjectCompileOutput`].
163pub fn configure_pcx_from_compile_output(
164    pcx: &mut ParsingContext<'_>,
165    config: &Config,
166    output: &ProjectCompileOutput,
167    target_paths: Option<&[PathBuf]>,
168) -> Result<()> {
169    let solc = get_solar_sources_from_compile_output(config, output, target_paths)?;
170    configure_pcx_from_solc(pcx, &config.project_paths(), &solc, true);
171    Ok(())
172}
173
174/// Configures a [`ParsingContext`] from [`ProjectPathsConfig`] and [`SolcVersionedInput`].
175///
176/// - Configures include paths, remappings.
177/// - Source files are added if `add_source_file` is set
178pub fn configure_pcx_from_solc(
179    pcx: &mut ParsingContext<'_>,
180    project_paths: &ProjectPathsConfig,
181    vinput: &SolcVersionedInput,
182    add_source_files: bool,
183) {
184    configure_pcx_from_solc_cli(pcx, project_paths, &vinput.cli_settings);
185    if add_source_files {
186        let sources = vinput
187            .input
188            .sources
189            .par_iter()
190            .filter_map(|(path, source)| {
191                pcx.sess.source_map().new_source_file(path.clone(), source.content.as_str()).ok()
192            })
193            .collect::<Vec<_>>();
194        pcx.add_files(sources);
195    }
196}
197
198fn configure_pcx_from_solc_cli(
199    pcx: &mut ParsingContext<'_>,
200    project_paths: &ProjectPathsConfig,
201    cli_settings: &foundry_compilers::solc::CliSettings,
202) {
203    pcx.file_resolver
204        .set_current_dir(cli_settings.base_path.as_ref().unwrap_or(&project_paths.root));
205    for remapping in &project_paths.remappings {
206        pcx.file_resolver.add_import_remapping(solar::sema::interface::config::ImportRemapping {
207            context: remapping.context.clone().unwrap_or_default(),
208            prefix: remapping.name.clone(),
209            path: remapping.path.clone(),
210        });
211    }
212    pcx.file_resolver.add_include_paths(cli_settings.include_paths.iter().cloned());
213}