Skip to main content

foundry_common/
compile.rs

1//! Support for compiling [foundry_compilers::Project]
2
3use crate::{
4    TestFunctionExt,
5    external_compiler::{ExternalCompilation, is_builtin_compiler_source},
6    fs::canonicalize_path,
7    preprocessor::DynamicTestLinkingPreprocessor,
8    shell,
9    term::SpinnerReporter,
10};
11use alloy_json_abi::JsonAbi;
12use comfy_table::{
13    Cell, Color, Table,
14    presets::{ASCII_FULL, ASCII_MARKDOWN},
15};
16use evm2::{
17    SpecId,
18    constants::{
19        MAX_CODE_SIZE, MAX_CODE_SIZE_AMSTERDAM, MAX_INITCODE_SIZE, MAX_INITCODE_SIZE_AMSTERDAM,
20    },
21};
22use eyre::{OptionExt, Result};
23use foundry_block_explorers::contract::Metadata;
24use foundry_compilers::{
25    Artifact, Project, ProjectBuilder, ProjectCompileOutput, ProjectPathsConfig, SolcConfig,
26    artifacts::{
27        BytecodeObject, Contract, Error as SolcError, SecondarySourceLocation, Severity, Source,
28        output_selection::OutputSelection,
29        remappings::{RelativeRemapping, Remapping},
30    },
31    compilers::{
32        CompilationError, Compiler,
33        solc::{Solc, SolcCompiler},
34    },
35    info::ContractInfo as CompilerContractInfo,
36    multi::{MultiCompiler, MultiCompilerError, MultiCompilerSettings},
37    project::Preprocessor,
38    report::{BasicStdoutReporter, NoReporter, Report},
39    solc::SolcSettings,
40};
41use foundry_config::{Config, providers::dependency_library_paths};
42use itertools::Itertools;
43use num_format::{Locale, ToFormattedString};
44use path_slash::PathExt;
45use solar::{
46    ast::{Arena, ContractKind, ItemKind},
47    interface::{Session, source_map::FileName},
48    parse::Parser,
49};
50use std::{
51    any::Any,
52    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
53    fmt::Display,
54    io::IsTerminal,
55    path::{Component, Path, PathBuf},
56    str::FromStr,
57    sync::Arc,
58    time::Instant,
59};
60
61/// A Solar compiler instance, to grant syntactic and semantic analysis capabilities.
62pub type Analysis = Arc<solar::sema::Compiler>;
63
64/// Builder type to configure how to compile a project.
65///
66/// This is merely a wrapper for [`Project::compile()`] which also prints to stdout depending on its
67/// settings.
68#[must_use = "ProjectCompiler does nothing unless you call a `compile*` method"]
69pub struct ProjectCompiler {
70    /// The root of the project.
71    project_root: PathBuf,
72
73    /// Whether to also print contract names.
74    print_names: Option<bool>,
75
76    /// Whether to also print contract sizes.
77    print_sizes: Option<bool>,
78
79    /// Whether to print anything at all. Overrides other `print` options.
80    quiet: Option<bool>,
81
82    /// Whether to print the resolved settings for each compiler invocation.
83    print_compiler_settings: bool,
84
85    /// Whether to bail on compiler errors.
86    bail: Option<bool>,
87
88    /// Whether to ignore the contract initcode size limit introduced by EIP-3860.
89    ignore_eip_3860: bool,
90
91    /// Contract size limits used when reporting compiled contract sizes.
92    size_limits: ContractSizeLimits,
93
94    /// Extra files to include, that are not necessarily in the project's source directory.
95    files: Vec<PathBuf>,
96
97    /// Complete source roots to retry if filtering changed Solidity's inheritance ordering.
98    source_order_fallback: Vec<PathBuf>,
99
100    /// Paths used by external adapters to select compiler-native build units.
101    selected_paths: Vec<PathBuf>,
102
103    /// Whether to compile with dynamic linking tests and scripts.
104    dynamic_test_linking: bool,
105
106    /// Whether compiled contracts may depend on externally linked Solidity libraries.
107    allow_linked_libraries: bool,
108
109    /// Whether ABI acquisition may consult the compiler-owned ABI cache.
110    abi_cache: bool,
111
112    /// External compiler configuration.
113    external_compilers: Option<Config>,
114
115    /// Preserves the caller's artifact policy when ABI caching enables artifacts on a cloned
116    /// project.
117    external_writes: bool,
118}
119
120impl Default for ProjectCompiler {
121    #[inline]
122    fn default() -> Self {
123        Self::new()
124    }
125}
126
127impl ProjectCompiler {
128    /// Create a new builder with the default settings.
129    #[inline]
130    pub fn new() -> Self {
131        Self {
132            project_root: PathBuf::new(),
133            print_names: None,
134            print_sizes: None,
135            quiet: Some(crate::shell::is_quiet()),
136            print_compiler_settings: false,
137            bail: None,
138            ignore_eip_3860: false,
139            size_limits: ContractSizeLimits::default(),
140            files: Vec::new(),
141            source_order_fallback: Vec::new(),
142            selected_paths: Vec::new(),
143            dynamic_test_linking: false,
144            allow_linked_libraries: true,
145            abi_cache: false,
146            external_compilers: None,
147            external_writes: true,
148        }
149    }
150
151    /// Sets whether to print contract names.
152    #[inline]
153    pub const fn print_names(mut self, yes: bool) -> Self {
154        self.print_names = Some(yes);
155        self
156    }
157
158    /// Sets whether to print contract sizes.
159    #[inline]
160    pub const fn print_sizes(mut self, yes: bool) -> Self {
161        self.print_sizes = Some(yes);
162        self
163    }
164
165    /// Sets whether to print anything at all. Overrides other `print` options.
166    #[inline]
167    #[doc(alias = "silent")]
168    pub const fn quiet(mut self, yes: bool) -> Self {
169        self.quiet = Some(yes);
170        self
171    }
172
173    /// Sets whether to print the resolved settings for each compiler invocation.
174    #[inline]
175    pub const fn print_compiler_settings(mut self, yes: bool) -> Self {
176        self.print_compiler_settings = yes;
177        self
178    }
179
180    /// Sets whether to bail on compiler errors.
181    #[inline]
182    pub const fn bail(mut self, yes: bool) -> Self {
183        self.bail = Some(yes);
184        self
185    }
186
187    /// Sets whether to ignore EIP-3860 initcode size limits.
188    #[inline]
189    pub const fn ignore_eip_3860(mut self, yes: bool) -> Self {
190        self.ignore_eip_3860 = yes;
191        self
192    }
193
194    /// Sets the contract size limits for size reports.
195    #[inline]
196    pub const fn size_limits(mut self, limits: ContractSizeLimits) -> Self {
197        self.size_limits = limits;
198        self
199    }
200
201    /// Sets extra files to include, that are not necessarily in the project's source dir.
202    #[inline]
203    pub fn files(mut self, files: impl IntoIterator<Item = PathBuf>) -> Self {
204        self.files.extend(files);
205        self
206    }
207
208    /// Sets paths used by external adapters to select compiler-native build units.
209    pub fn selected_paths(mut self, paths: impl IntoIterator<Item = PathBuf>) -> Self {
210        self.selected_paths.extend(paths);
211        self
212    }
213
214    /// Selects targets for external adapters and built-in sources where applicable.
215    pub fn target_files(mut self, paths: impl IntoIterator<Item = PathBuf>) -> Self {
216        for path in paths {
217            if is_builtin_compiler_source(&path) {
218                self.files.push(path.clone());
219            }
220            self.selected_paths.push(path);
221        }
222        self
223    }
224
225    /// Sets if tests should be dynamically linked.
226    #[inline]
227    pub const fn dynamic_test_linking(mut self, preprocess: bool) -> Self {
228        self.dynamic_test_linking = preprocess;
229        self
230    }
231
232    /// Enables explicitly configured external compilers for this build.
233    pub fn external_compilers(mut self, config: &Config) -> Self {
234        self.external_compilers = Some(config.clone());
235        self
236    }
237
238    /// Controls whether external artifacts and their cache may be published.
239    pub const fn external_artifacts(mut self, write: bool) -> Self {
240        self.external_writes = write;
241        self
242    }
243
244    /// Reuses normal artifacts before consulting the compiler-owned ABI cache.
245    ///
246    /// The project must request ABI output and may include other contract outputs.
247    /// The project's artifact policy controls writes to the secondary cache.
248    pub const fn cache_abi(mut self) -> Self {
249        self.abi_cache = true;
250        self
251    }
252
253    /// Retries once with these roots if compilation fails because a base contract is defined
254    /// after its derived contract. Removing roots can change traversal order in import cycles.
255    pub fn source_order_fallback(mut self, files: impl IntoIterator<Item = PathBuf>) -> Self {
256        self.source_order_fallback.extend(files);
257        self
258    }
259
260    /// Sets whether compiled contracts may depend on externally linked Solidity libraries.
261    ///
262    /// This does not disable dynamic test linking. With `bail(false)`, violations are reported as
263    /// compiler errors in the returned output.
264    pub const fn allow_linked_libraries(mut self, allow: bool) -> Self {
265        self.allow_linked_libraries = allow;
266        self
267    }
268
269    /// Compiles the project.
270    #[instrument(target = "forge::compile", skip_all)]
271    pub fn compile<C: Compiler<CompilerContract = Contract>>(
272        mut self,
273        project: &Project<C>,
274    ) -> Result<ProjectCompileOutput<C>>
275    where
276        DynamicTestLinkingPreprocessor: Preprocessor<C>,
277    {
278        self.project_root = project.root().to_path_buf();
279
280        // TODO: Avoid using std::process::exit(0).
281        // Replacing this with a return (e.g., Ok(ProjectCompileOutput::default())) would be more
282        // idiomatic, but it currently requires a `Default` bound on `C::Language`, which
283        // breaks compatibility with downstream crates like `foundry-cli`. This would need a
284        // broader refactor across the call chain. Leaving it as-is for now until a larger
285        // refactor is feasible.
286        if !project.paths.has_input_files()
287            && self.files.is_empty()
288            && self.selected_paths.is_empty()
289            && self
290                .external_compilers
291                .as_ref()
292                .is_none_or(|config| config.external_compilers.is_empty())
293        {
294            sh_println!("Nothing to compile")?;
295            std::process::exit(0);
296        }
297
298        // Taking is fine since we don't need these in `compile_with`.
299        let files = std::mem::take(&mut self.files);
300        let fallback_files = std::mem::take(&mut self.source_order_fallback);
301        let explicit_selection = !files.is_empty() || !self.selected_paths.is_empty();
302        let selected_paths = std::mem::take(&mut self.selected_paths);
303        let preprocess = self.dynamic_test_linking;
304        let abi_cache = self.abi_cache;
305        let external_compilers = self.external_compilers.take();
306        let external_writes = self.external_writes && !project.no_artifacts;
307        self.compile_with(|| {
308            let external = external_compilers
309                .as_ref()
310                .map(|config| {
311                    ExternalCompilation::compile(config, &selected_paths, external_writes)
312                })
313                .transpose()?;
314            let sources = if explicit_selection {
315                Source::read_all(files)?
316            } else {
317                project.paths.read_input_files()?
318            };
319
320            let preprocessor = DynamicTestLinkingPreprocessor::default();
321            let compile = |preprocess| -> Result<ProjectCompileOutput<C>> {
322                let compile_sources = |sources| {
323                    let mut compiler = foundry_compilers::project::ProjectCompiler::with_sources(
324                        project, sources,
325                    )?;
326                    if preprocess {
327                        compiler = compiler.with_preprocessor(preprocessor.clone());
328                    }
329                    if abi_cache { compiler.compile_abi_cached() } else { compiler.compile() }
330                };
331                let mut output = compile_sources(sources.clone())?;
332                // Solc error 2449 can be introduced by filtering compilation roots in an import
333                // cycle. Retry before reporting diagnostics or bailing on the filtered output.
334                if !fallback_files.is_empty()
335                    && output.output().errors.iter().any(|error| error.error_code() == Some(2449))
336                {
337                    output = compile_sources(Source::read_all(&fallback_files)?)?;
338                }
339                Ok(output)
340            };
341            let mut output = compile(preprocess)?;
342            // A retry can only help if DTL changed the compiler input.
343            if preprocessor.rewrote_sources()
344                && let Some(reason) = dynamic_test_linking_failure(&output.output().errors)
345            {
346                sh_warn!(
347                    "dynamic test linking failed ({reason}); retrying with native test linking. \
348                     Use --no-dynamic-test-linking to skip the failed attempt."
349                )?;
350                // The preprocessor is part of the cache identity: native compilation cannot
351                // reuse DTL artifacts. Return only this attempt, including any compiler errors.
352                output = compile(false)?;
353            }
354            // Drop deferred DTL-disable warnings on failure; solc's error already explains it.
355            let disable_warnings = preprocessor.take_disable_warnings();
356            if !output.has_compiler_errors() {
357                for warning in disable_warnings {
358                    sh_warn!("{warning}")?;
359                }
360            }
361            if !output.has_compiler_errors()
362                && let Some(external) = external
363            {
364                external.merge(&mut output)?;
365            }
366            add_scoped_alias_diagnostics(&mut output, &project.paths);
367            Ok(output)
368        })
369    }
370
371    /// Compiles the project with the given closure
372    fn compile_with<C: Compiler<CompilerContract = Contract>, F>(
373        self,
374        f: F,
375    ) -> Result<ProjectCompileOutput<C>>
376    where
377        F: FnOnce() -> Result<ProjectCompileOutput<C>>,
378    {
379        let quiet = self.quiet.unwrap_or(false);
380        let bail = self.bail.unwrap_or(true);
381
382        let mut output = with_compilation_reporter_and_settings(
383            quiet,
384            Some(self.project_root.clone()),
385            self.print_compiler_settings,
386            || {
387                tracing::debug!("compiling project");
388
389                let timer = Instant::now();
390                let r = f();
391                let elapsed = timer.elapsed();
392
393                tracing::debug!("finished compiling in {:.3}s", elapsed.as_secs_f64());
394                r
395            },
396        )?;
397
398        if bail && output.has_compiler_errors() {
399            eyre::bail!("{output}");
400        }
401
402        let mut linking_error = (!self.allow_linked_libraries && !output.has_compiler_errors())
403            .then(|| linked_libraries_error(&output, &self.project_root))
404            .flatten();
405        if !bail && let Some(message) = linking_error.take() {
406            push_linked_libraries_error(&mut output, message);
407        }
408
409        if !quiet && !shell::is_json() {
410            if output.is_unchanged() {
411                sh_println!("No files changed, compilation skipped")?;
412            } else {
413                // print the compiler output / warnings
414                sh_println!("{output}")?;
415            }
416        }
417
418        // Report compiler warnings before the policy failure.
419        if let Some(message) = linking_error {
420            eyre::bail!("{message}");
421        }
422
423        // Quiet mode suppresses reports, but size limits still apply.
424        if !(shell::is_json() && output.has_compiler_errors()) {
425            self.handle_output(&output)?;
426        }
427
428        Ok(output)
429    }
430
431    /// Prints requested reports and checks contract size limits.
432    fn handle_output<C: Compiler<CompilerContract = Contract>>(
433        &self,
434        output: &ProjectCompileOutput<C>,
435    ) -> Result<()> {
436        let quiet = self.quiet.unwrap_or(false);
437        let print_names = self.print_names.unwrap_or(false) && !quiet;
438        let print_sizes = self.print_sizes.unwrap_or(false);
439
440        // print any sizes or names
441        if print_names {
442            let mut artifacts: BTreeMap<_, Vec<_>> = BTreeMap::new();
443            for (name, (_, version)) in output.versioned_artifacts() {
444                artifacts.entry(version).or_default().push(name);
445            }
446
447            if shell::is_json() {
448                sh_println!("{}", serde_json::to_string(&artifacts).unwrap())?;
449            } else {
450                for (version, names) in artifacts {
451                    sh_println!(
452                        "  compiler version: {}.{}.{}",
453                        version.major,
454                        version.minor,
455                        version.patch
456                    )?;
457                    for name in names {
458                        sh_println!("    - {name}")?;
459                    }
460                }
461            }
462        }
463
464        if print_sizes {
465            // add extra newline if names were already printed
466            if print_names && !shell::is_json() {
467                sh_println!()?;
468            }
469
470            let mut size_report =
471                SizeReport { contracts: BTreeMap::new(), limits: self.size_limits };
472
473            let mut artifacts: BTreeMap<String, Vec<_>> = BTreeMap::new();
474            for (id, artifact) in output.artifact_ids().filter(|(id, _)| {
475                // filter out forge-std specific contracts
476                !id.source.to_string_lossy().contains("/forge-std/src/")
477            }) {
478                artifacts.entry(id.name.clone()).or_default().push((id.source, artifact));
479            }
480
481            // Internal libraries are inlined into consumers and never deployed; skip them.
482            // Only artifacts whose ABI has no functions can be internal libraries, so restrict the
483            // solar parse to those sources to avoid a second full parse pass.
484            let abs_source = |path: &Path| -> PathBuf {
485                if path.is_absolute() { path.to_path_buf() } else { self.project_root.join(path) }
486            };
487            let source_paths = artifacts
488                .values()
489                .flatten()
490                .filter(|(_, artifact)| {
491                    artifact.abi.as_ref().is_some_and(|abi| abi.functions().next().is_none())
492                })
493                .map(|(path, _)| abs_source(path))
494                .collect::<BTreeSet<_>>();
495            let libraries = collect_libraries(&source_paths);
496
497            for (name, artifact_list) in artifacts {
498                // A library with no functions in its ABI is internal-only; fail open if the ABI is
499                // missing. Filter first so the duplicate-name suffix below reflects kept contracts.
500                let kept = artifact_list
501                    .iter()
502                    .filter(|(path, artifact)| {
503                        let is_library = libraries
504                            .get(&abs_source(path))
505                            .is_some_and(|libs| libs.contains(&name));
506                        let has_no_abi_functions = artifact
507                            .abi
508                            .as_ref()
509                            .is_some_and(|abi| abi.functions().next().is_none());
510                        !(is_library && has_no_abi_functions)
511                    })
512                    .collect::<Vec<_>>();
513
514                for (path, artifact) in &kept {
515                    let runtime_size = contract_size(*artifact, false).unwrap_or_default();
516                    let init_size = contract_size(*artifact, true).unwrap_or_default();
517
518                    let is_dev_contract = artifact.abi.as_ref().is_some_and(|abi| {
519                        abi.functions().any(|f| {
520                            f.test_function_kind().is_known()
521                                || matches!(f.name.as_str(), "IS_TEST" | "IS_SCRIPT")
522                        })
523                    });
524
525                    let unique_name = if kept.len() > 1 {
526                        format!(
527                            "{} ({})",
528                            name,
529                            path.strip_prefix(&self.project_root).unwrap_or(path).display()
530                        )
531                    } else {
532                        name.clone()
533                    };
534
535                    size_report.contracts.insert(
536                        unique_name,
537                        ContractInfo { runtime_size, init_size, is_dev_contract },
538                    );
539                }
540            }
541
542            if !quiet {
543                sh_println!("{size_report}")?;
544            }
545
546            let runtime_eip = match size_report.limits.runtime {
547                CONTRACT_RUNTIME_SIZE_LIMIT => "EIP-170: ",
548                AMSTERDAM_CONTRACT_RUNTIME_SIZE_LIMIT => "EIP-7954: ",
549                _ => "",
550            };
551            eyre::ensure!(
552                !size_report.exceeds_runtime_size_limit(),
553                "some contracts exceed the runtime size limit ({runtime_eip}{} bytes)",
554                size_report.limits.runtime
555            );
556            // Check size limits only if not ignoring EIP-3860
557            let initcode_eip = match size_report.limits.initcode {
558                CONTRACT_INITCODE_SIZE_LIMIT => "EIP-3860: ",
559                AMSTERDAM_CONTRACT_INITCODE_SIZE_LIMIT => "EIP-7954: ",
560                _ => "",
561            };
562            eyre::ensure!(
563                self.ignore_eip_3860 || !size_report.exceeds_initcode_size_limit(),
564                "some contracts exceed the initcode size limit ({initcode_eip}{} bytes)",
565                size_report.limits.initcode
566            );
567        }
568
569        Ok(())
570    }
571}
572
573// https://eips.ethereum.org/EIPS/eip-170
574const CONTRACT_RUNTIME_SIZE_LIMIT: usize = MAX_CODE_SIZE;
575
576// https://eips.ethereum.org/EIPS/eip-3860
577const CONTRACT_INITCODE_SIZE_LIMIT: usize = MAX_INITCODE_SIZE;
578
579// https://eips.ethereum.org/EIPS/eip-7954
580const AMSTERDAM_CONTRACT_RUNTIME_SIZE_LIMIT: usize = MAX_CODE_SIZE_AMSTERDAM;
581const AMSTERDAM_CONTRACT_INITCODE_SIZE_LIMIT: usize = MAX_INITCODE_SIZE_AMSTERDAM;
582
583const CONTRACT_RUNTIME_SIZE_WARN_THRESHOLD: usize = 18_000;
584const CONTRACT_INITCODE_SIZE_WARN_THRESHOLD: usize = 36_000;
585
586/// Runtime and initcode byte-size limits for compiled contract size reports.
587#[derive(Clone, Copy, Debug, PartialEq, Eq)]
588pub struct ContractSizeLimits {
589    /// Maximum deployed runtime bytecode size.
590    pub runtime: usize,
591    /// Maximum initcode bytecode size.
592    pub initcode: usize,
593}
594
595impl ContractSizeLimits {
596    /// Creates a new set of contract size limits.
597    pub const fn new(runtime: usize, initcode: usize) -> Self {
598        Self { runtime, initcode }
599    }
600
601    /// Creates limits from a runtime code-size limit, using the EIP-3860 2x initcode ratio.
602    pub const fn with_runtime_limit(runtime: usize) -> Self {
603        Self { runtime, initcode: runtime.saturating_mul(2) }
604    }
605
606    /// Returns the protocol limits active for an EVM specification.
607    pub const fn for_spec_id(spec_id: SpecId) -> Self {
608        if spec_id.enables(SpecId::AMSTERDAM) {
609            Self::new(AMSTERDAM_CONTRACT_RUNTIME_SIZE_LIMIT, AMSTERDAM_CONTRACT_INITCODE_SIZE_LIMIT)
610        } else {
611            Self::new(CONTRACT_RUNTIME_SIZE_LIMIT, CONTRACT_INITCODE_SIZE_LIMIT)
612        }
613    }
614
615    const fn runtime_warning_threshold(self) -> usize {
616        scaled_threshold(
617            self.runtime,
618            CONTRACT_RUNTIME_SIZE_WARN_THRESHOLD,
619            CONTRACT_RUNTIME_SIZE_LIMIT,
620        )
621    }
622
623    const fn initcode_warning_threshold(self) -> usize {
624        scaled_threshold(
625            self.initcode,
626            CONTRACT_INITCODE_SIZE_WARN_THRESHOLD,
627            CONTRACT_INITCODE_SIZE_LIMIT,
628        )
629    }
630}
631
632impl Default for ContractSizeLimits {
633    fn default() -> Self {
634        Self::new(CONTRACT_RUNTIME_SIZE_LIMIT, CONTRACT_INITCODE_SIZE_LIMIT)
635    }
636}
637
638const fn scaled_threshold(limit: usize, threshold: usize, default_limit: usize) -> usize {
639    limit.saturating_mul(threshold) / default_limit
640}
641
642/// Contracts with info about their size
643pub struct SizeReport {
644    /// `contract name -> info`
645    pub contracts: BTreeMap<String, ContractInfo>,
646    /// Size limits used to calculate margins and failures.
647    pub limits: ContractSizeLimits,
648}
649
650impl SizeReport {
651    /// Returns the maximum runtime code size, excluding dev contracts.
652    pub fn max_runtime_size(&self) -> usize {
653        self.contracts
654            .values()
655            .filter(|c| !c.is_dev_contract)
656            .map(|c| c.runtime_size)
657            .max()
658            .unwrap_or(0)
659    }
660
661    /// Returns the maximum initcode size, excluding dev contracts.
662    pub fn max_init_size(&self) -> usize {
663        self.contracts
664            .values()
665            .filter(|c| !c.is_dev_contract)
666            .map(|c| c.init_size)
667            .max()
668            .unwrap_or(0)
669    }
670
671    /// Returns true if any contract exceeds the runtime size limit, excluding dev contracts.
672    pub fn exceeds_runtime_size_limit(&self) -> bool {
673        self.max_runtime_size() > self.limits.runtime
674    }
675
676    /// Returns true if any contract exceeds the initcode size limit, excluding dev contracts.
677    pub fn exceeds_initcode_size_limit(&self) -> bool {
678        self.max_init_size() > self.limits.initcode
679    }
680}
681
682impl Display for SizeReport {
683    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
684        if shell::is_json() {
685            writeln!(f, "{}", self.format_json_output())?;
686        } else {
687            writeln!(f, "\n{}", self.format_table_output())?;
688        }
689        Ok(())
690    }
691}
692
693impl SizeReport {
694    fn format_json_output(&self) -> String {
695        let contracts = self
696            .contracts
697            .iter()
698            .filter(|(_, c)| !c.is_dev_contract && (c.runtime_size > 0 || c.init_size > 0))
699            .map(|(name, contract)| {
700                (
701                    name.clone(),
702                    serde_json::json!({
703                        "runtime_size": contract.runtime_size,
704                        "init_size": contract.init_size,
705                        "runtime_margin": self.limits.runtime as isize - contract.runtime_size as isize,
706                        "init_margin": self.limits.initcode as isize - contract.init_size as isize,
707                    }),
708                )
709            })
710            .collect::<serde_json::Map<_, _>>();
711
712        serde_json::to_string(&contracts).unwrap()
713    }
714
715    fn format_table_output(&self) -> Table {
716        let mut table = Table::new();
717        if shell::is_markdown() {
718            table.load_style(ASCII_MARKDOWN);
719        } else {
720            table.load_style(ASCII_FULL.with_rounded_corners());
721        }
722
723        table.set_header(vec![
724            Cell::new("Contract"),
725            Cell::new("Runtime Size (B)"),
726            Cell::new("Initcode Size (B)"),
727            Cell::new("Runtime Margin (B)"),
728            Cell::new("Initcode Margin (B)"),
729        ]);
730
731        // Filters out dev contracts (Test or Script)
732        let contracts = self
733            .contracts
734            .iter()
735            .filter(|(_, c)| !c.is_dev_contract && (c.runtime_size > 0 || c.init_size > 0));
736        let runtime_warning_threshold = self.limits.runtime_warning_threshold();
737        let initcode_warning_threshold = self.limits.initcode_warning_threshold();
738        for (name, contract) in contracts {
739            let runtime_margin = self.limits.runtime as isize - contract.runtime_size as isize;
740            let init_margin = self.limits.initcode as isize - contract.init_size as isize;
741
742            let runtime_color = if contract.runtime_size < runtime_warning_threshold {
743                Color::Reset
744            } else if contract.runtime_size <= self.limits.runtime {
745                Color::Yellow
746            } else {
747                Color::Red
748            };
749
750            let init_color = if contract.init_size < initcode_warning_threshold {
751                Color::Reset
752            } else if contract.init_size <= self.limits.initcode {
753                Color::Yellow
754            } else {
755                Color::Red
756            };
757
758            let locale = &Locale::en;
759            table.add_row([
760                Cell::new(name),
761                Cell::new(contract.runtime_size.to_formatted_string(locale)).fg(runtime_color),
762                Cell::new(contract.init_size.to_formatted_string(locale)).fg(init_color),
763                Cell::new(runtime_margin.to_formatted_string(locale)).fg(runtime_color),
764                Cell::new(init_margin.to_formatted_string(locale)).fg(init_color),
765            ]);
766        }
767
768        table
769    }
770}
771
772/// Parses each source file with solar and returns the library names declared in it.
773///
774/// Files that fail to parse are skipped, so a missing entry means "unknown", not "no libraries".
775fn collect_libraries(sources: &BTreeSet<PathBuf>) -> HashMap<PathBuf, HashSet<String>> {
776    let mut result: HashMap<PathBuf, HashSet<String>> = HashMap::new();
777    let sess = Session::builder().with_silent_emitter(None).build();
778    let _ = sess.enter(|| -> solar::interface::Result<()> {
779        for path in sources {
780            let arena = Arena::new();
781            let mut parser = match Parser::from_lazy_source_code(
782                &sess,
783                &arena,
784                FileName::from(path.clone()),
785                || std::fs::read_to_string(path),
786            ) {
787                Ok(parser) => parser,
788                Err(_) => continue,
789            };
790            let Ok(ast) = parser.parse_file() else { continue };
791            let libs = ast
792                .items
793                .iter()
794                .filter_map(|item| match &item.kind {
795                    ItemKind::Contract(c) if c.kind == ContractKind::Library => {
796                        Some(c.name.as_str().to_string())
797                    }
798                    _ => None,
799                })
800                .collect::<HashSet<_>>();
801            if !libs.is_empty() {
802                result.insert(path.clone(), libs);
803            }
804        }
805        Ok(())
806    });
807    result
808}
809
810/// Returns the deployed or init size of the contract.
811fn contract_size<T: Artifact>(artifact: &T, initcode: bool) -> Option<usize> {
812    let bytecode = if initcode {
813        artifact.get_bytecode_object()?
814    } else {
815        artifact.get_deployed_bytecode_object()?
816    };
817
818    let size = match bytecode.as_ref() {
819        BytecodeObject::Bytecode(bytes) => bytes.len(),
820        BytecodeObject::Unlinked(unlinked) => {
821            // we don't need to account for placeholders here, because library placeholders take up
822            // 40 characters: `__$<library hash>$__` which is the same as a 20byte address in hex.
823            let mut size = unlinked.len();
824            if unlinked.starts_with("0x") {
825                size -= 2;
826            }
827            // hex -> bytes
828            size / 2
829        }
830    };
831
832    Some(size)
833}
834
835/// How big the contract is and whether it is a dev contract where size limits can be neglected
836#[derive(Clone, Copy, Debug)]
837pub struct ContractInfo {
838    /// Size of the runtime code in bytes
839    pub runtime_size: usize,
840    /// Size of the initcode in bytes
841    pub init_size: usize,
842    /// A development contract is either a Script or a Test contract.
843    pub is_dev_contract: bool,
844}
845
846/// Compiles target file path.
847///
848/// If `quiet` is set, the compilation reporter's progress/status output is suppressed.
849/// (When not suppressed, that output is emitted to stderr; see `with_compilation_reporter`.)
850///
851/// **Note:** this expects the `target_path` to be absolute
852pub fn compile_target<C: Compiler<CompilerContract = Contract>>(
853    target_path: &Path,
854    project: &Project<C>,
855    quiet: bool,
856) -> Result<ProjectCompileOutput<C>>
857where
858    DynamicTestLinkingPreprocessor: Preprocessor<C>,
859{
860    ProjectCompiler::new().quiet(quiet).files([target_path.into()]).compile(project)
861}
862
863/// Compiles the project requesting only ABI output.
864pub fn compile_abi_project<C: Compiler<CompilerContract = Contract>>(
865    project: &mut Project<C>,
866    mut compiler: ProjectCompiler,
867) -> Result<ProjectCompileOutput<C>>
868where
869    DynamicTestLinkingPreprocessor: Preprocessor<C>,
870{
871    project.update_output_selection(|selection| {
872        // Request ABI so compilers populate `contracts` without producing bytecode outputs.
873        *selection = OutputSelection::common_output_selection(["abi".to_string()]);
874    });
875    // Cached ABI artifacts do not retain compiler diagnostics.
876    compiler.abi_cache = (compiler.abi_cache || project.no_artifacts)
877        && project.compiler_severity_filter == Severity::Error;
878    compiler.compile(project)
879}
880
881/// Acquires ABI output with compiler-owned persistence separate from normal artifacts.
882///
883/// Requests for additional files or full build info retain their existing output behavior.
884pub fn compile_abi_project_cached<C: Compiler<CompilerContract = Contract>>(
885    project: &mut Project<C>,
886    mut compiler: ProjectCompiler,
887) -> Result<ProjectCompileOutput<C>>
888where
889    DynamicTestLinkingPreprocessor: Preprocessor<C>,
890{
891    if !project.cached
892        || project.build_info
893        || project.artifacts.additional_files != Default::default()
894        || project.compiler_severity_filter != Severity::Error
895    {
896        return compile_abi_project(project, compiler);
897    }
898    let mut cached_project = project.clone();
899    cached_project.no_artifacts = false;
900    compiler.abi_cache = true;
901    compiler.external_writes &= !project.no_artifacts;
902    compile_abi_project(&mut cached_project, compiler)
903}
904
905/// Compiles the target contract requesting only ABI output and returns its ABI.
906pub fn compile_target_abi(
907    project: &mut Project<MultiCompiler>,
908    target_path: &Path,
909    target_name: &str,
910) -> Result<JsonAbi> {
911    let target_path = canonicalize_path(target_path)?;
912    let output = compile_abi_project(
913        project,
914        ProjectCompiler::new().quiet(true).files([target_path.clone()]),
915    )?;
916
917    let artifact = output
918        .find(&target_path, target_name)
919        .ok_or_eyre("failed to find target artifact when compiling for abi")?;
920    artifact.abi.clone().ok_or_eyre("target artifact does not have an ABI")
921}
922
923/// Creates a [Project] from an Etherscan source.
924pub fn etherscan_project(metadata: &Metadata, target_path: &Path) -> Result<Project> {
925    let target_path = canonicalize_path(target_path)?;
926    let sources_path = target_path.join(&metadata.contract_name);
927    metadata.source_tree()?.write_to(&target_path)?;
928
929    let mut settings = metadata.settings()?;
930
931    // make remappings absolute with our root
932    //
933    // The remappings come from the explorer's copy of the contract's compiler settings, which is
934    // attacker controlled: a target of `../../..` would otherwise point the compiler at sources
935    // outside the checkout and let a verified contract pull arbitrary local files into the build.
936    for remapping in &mut settings.remappings {
937        let new_path = sources_path.join(sanitize_relative_path(remapping.path.as_ref()));
938        remapping.path = new_path.display().to_string();
939    }
940
941    // add missing remappings
942    if !settings.remappings.iter().any(|remapping| remapping.name.starts_with("@openzeppelin/")) {
943        let oz = Remapping {
944            context: None,
945            name: "@openzeppelin/".into(),
946            path: sources_path.join("@openzeppelin").display().to_string(),
947        };
948        settings.remappings.push(oz);
949    }
950
951    // root/
952    //   ContractName/
953    //     [source code]
954    let paths = ProjectPathsConfig::builder()
955        .sources(sources_path.clone())
956        .remappings(settings.remappings.clone())
957        .build_with_root(sources_path);
958
959    // TODO: detect vyper
960    let v = metadata.compiler_version()?;
961    let solc = Solc::find_or_install(&v)?;
962
963    let compiler = MultiCompiler { solc: Some(SolcCompiler::Specific(solc)), vyper: None };
964
965    Ok(ProjectBuilder::<MultiCompiler>::default()
966        .settings(MultiCompilerSettings {
967            solc: SolcSettings {
968                settings: SolcConfig::builder().settings(settings).build(),
969                ..Default::default()
970            },
971            ..Default::default()
972        })
973        .paths(paths)
974        .ephemeral()
975        .no_artifacts()
976        .build(compiler)?)
977}
978
979/// Normalizes an untrusted path relative to the source root, discarding leading separators,
980/// drive prefixes, and parent components that would escape that root.
981fn sanitize_relative_path(path: &Path) -> PathBuf {
982    let mut normalized = PathBuf::new();
983    for component in path.components() {
984        match component {
985            Component::Normal(part) => normalized.push(part),
986            Component::ParentDir => {
987                normalized.pop();
988            }
989            _ => {}
990        }
991    }
992    normalized
993}
994
995/// Adds `storageLayout` to the compiler output selection for the given project.
996pub fn add_storage_layout_output<C: Compiler<CompilerContract = Contract>>(
997    project: &mut Project<C>,
998) {
999    project.artifacts.additional_values.storage_layout = true;
1000    project.update_output_selection(|selection| {
1001        for contract_selection in selection.0.values_mut() {
1002            for selection in contract_selection.values_mut() {
1003                selection.push("storageLayout".to_string());
1004            }
1005        }
1006    })
1007}
1008
1009/// Configures the reporter and runs the given closure.
1010///
1011/// In TTY mode, [`SpinnerReporter`] paints the progress to stderr. The non-TTY fallback
1012/// still writes to stdout via `BasicStdoutReporter`; migrating that path to stderr is
1013/// part of the per-command stdout migration tracked in `docs/dev/output-channels.md`
1014/// (it would shift many existing snapshot tests at once).
1015pub fn with_compilation_reporter<O>(
1016    quiet: bool,
1017    project_root: Option<PathBuf>,
1018    f: impl FnOnce() -> O,
1019) -> O {
1020    with_compilation_reporter_and_settings(quiet, project_root, false, f)
1021}
1022
1023fn with_compilation_reporter_and_settings<O>(
1024    quiet: bool,
1025    project_root: Option<PathBuf>,
1026    print_compiler_settings: bool,
1027    f: impl FnOnce() -> O,
1028) -> O {
1029    #[expect(clippy::collapsible_else_if)]
1030    let reporter = if quiet || shell::is_json() {
1031        Report::new(NoReporter::default())
1032    } else {
1033        if std::io::stderr().is_terminal() {
1034            Report::new(
1035                SpinnerReporter::spawn(project_root)
1036                    .with_compiler_settings(print_compiler_settings),
1037            )
1038        } else {
1039            Report::new(
1040                BasicStdoutReporter::default().with_compiler_settings(print_compiler_settings),
1041            )
1042        }
1043    };
1044
1045    foundry_compilers::report::with_scoped(&reporter, f)
1046}
1047
1048/// Container type for parsing contract identifiers from CLI.
1049///
1050/// Passed string can be of the following forms:
1051/// - `src/Counter.sol` - path to the contract file, in the case where it only contains one contract
1052/// - `src/Counter.sol:Counter` - path to the contract file and the contract name
1053/// - `Counter` - contract name only
1054#[derive(Clone, PartialEq, Eq)]
1055pub enum PathOrContractInfo {
1056    /// Non-canonicalized path provided via CLI.
1057    Path(PathBuf),
1058    /// Contract info provided via CLI.
1059    ContractInfo(CompilerContractInfo),
1060}
1061
1062impl PathOrContractInfo {
1063    /// Returns the path to the contract file if provided.
1064    pub fn path(&self) -> Option<PathBuf> {
1065        match self {
1066            Self::Path(path) => Some(path.clone()),
1067            Self::ContractInfo(info) => info.path.as_ref().map(PathBuf::from),
1068        }
1069    }
1070
1071    /// Returns the contract name if provided.
1072    pub fn name(&self) -> Option<&str> {
1073        match self {
1074            Self::Path(_) => None,
1075            Self::ContractInfo(info) => Some(&info.name),
1076        }
1077    }
1078}
1079
1080impl FromStr for PathOrContractInfo {
1081    type Err = eyre::Error;
1082
1083    fn from_str(s: &str) -> Result<Self> {
1084        if let Ok(contract) = CompilerContractInfo::from_str(s) {
1085            return Ok(Self::ContractInfo(contract));
1086        }
1087        let path = PathBuf::from(s);
1088        if path.extension().is_some_and(|ext| ext == "sol" || ext == "vy") {
1089            return Ok(Self::Path(path));
1090        }
1091        Err(eyre::eyre!("Invalid contract identifier, file is not *.sol or *.vy: {}", s))
1092    }
1093}
1094
1095impl std::fmt::Debug for PathOrContractInfo {
1096    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1097        match self {
1098            Self::Path(path) => write!(f, "Path({})", path.display()),
1099            Self::ContractInfo(info) => {
1100                write!(f, "ContractInfo({info})")
1101            }
1102        }
1103    }
1104}
1105
1106/// Describes the Solidity library dependencies in creation or runtime bytecode, if any.
1107///
1108/// Includes cached artifacts and permits internal libraries and dynamic test linking helpers.
1109fn linked_libraries_error<C: Compiler<CompilerContract = Contract>>(
1110    output: &ProjectCompileOutput<C>,
1111    root: &Path,
1112) -> Option<String> {
1113    let violations = output
1114        .artifact_ids()
1115        .flat_map(|(id, artifact)| {
1116            let contract = id.with_stripped_file_prefixes(root).identifier();
1117            artifact.all_link_references().into_iter().flat_map(move |(file, libs)| {
1118                let contract = contract.clone();
1119                libs.into_keys().map(move |lib| format!("{contract} links {file}:{lib}"))
1120            })
1121        })
1122        .collect::<BTreeSet<_>>();
1123    (!violations.is_empty()).then(|| {
1124        format!(
1125            "Linked libraries are not allowed (`allow_linked_libraries = false`):\n  {}\n\
1126             help: make the library functions `internal` to inline them, or set \
1127             `allow_linked_libraries = true`",
1128            violations.into_iter().collect::<Vec<_>>().join("\n  ")
1129        )
1130    })
1131}
1132
1133/// Appends a linked-library policy error to solc or multi-compiler diagnostics.
1134fn push_linked_libraries_error<C: Compiler<CompilerContract = Contract>>(
1135    output: &mut ProjectCompileOutput<C>,
1136    message: String,
1137) {
1138    let error = SolcError {
1139        source_location: None,
1140        secondary_source_locations: Vec::new(),
1141        r#type: "LinkedLibraryError".to_string(),
1142        component: "foundry".to_string(),
1143        severity: Severity::Error,
1144        error_code: None,
1145        message,
1146        formatted_message: None,
1147    };
1148    // CompilationError has no constructor; downcast to the concrete diagnostics instead.
1149    let errors = &mut output.output_mut().errors as &mut dyn Any;
1150    if let Some(errors) = errors.downcast_mut::<Vec<SolcError>>() {
1151        errors.push(error);
1152    } else if let Some(errors) = errors.downcast_mut::<Vec<MultiCompilerError>>() {
1153        errors.push(MultiCompilerError::Solc(error));
1154    }
1155}
1156
1157/// Recognizes only solc code-generation failures that DTL's source rewrites can introduce.
1158/// Unrelated errors (including other languages) must not trigger a retry.
1159fn dynamic_test_linking_failure<E: CompilationError>(errors: &[E]) -> Option<&'static str> {
1160    let mut reason = None;
1161    for error in errors.iter().filter(|error| error.is_error()) {
1162        // CompilationError has no structured message/type accessors. Inspect the concrete solc
1163        // diagnostic rather than its Display output, which can include source snippets.
1164        let error = error as &dyn Any;
1165        let error = if let Some(error) = error.downcast_ref::<SolcError>() {
1166            error
1167        } else if let Some(MultiCompilerError::Solc(error)) =
1168            error.downcast_ref::<MultiCompilerError>()
1169        {
1170            error
1171        } else {
1172            return None;
1173        };
1174        reason = Some(match error.r#type.as_str() {
1175            "YulException" if error.message.contains("too deep in the stack") => "stack too deep",
1176            "CompilerError" if error.message.contains("Stack too deep") => "stack too deep",
1177            "InternalCompilerError"
1178                if error.message.contains("Tag too large for reserved space") =>
1179            {
1180                "Tag too large for reserved space"
1181            }
1182            _ => return None,
1183        });
1184    }
1185    reason
1186}
1187
1188/// Returns the innermost dependency directory that contains `file`, relative to the root.
1189///
1190/// Nested dependencies live in the library directories their parent configures. An npm scope such
1191/// as `node_modules/@scope/` holds packages, so its owner is the package. Other `@` directories,
1192/// such as Soldeer's `dependencies/@name-version/`, are packages themselves.
1193fn dependency_owner<L>(paths: &ProjectPathsConfig<L>, file: &Path) -> Option<PathBuf> {
1194    let mut libs = paths.libraries.iter().map(|lib| paths.root.join(lib)).collect::<Vec<_>>();
1195    let mut owner = None;
1196    loop {
1197        let mut next = None;
1198        for lib in &libs {
1199            let Ok(rest) = file.strip_prefix(lib) else { continue };
1200            let mut parts = rest.iter();
1201            let Some(name) = parts.next() else { break };
1202            let mut package = lib.join(name);
1203            if lib.ends_with("node_modules") && name.to_string_lossy().starts_with('@') {
1204                let Some(name) = parts.next() else { break };
1205                package.push(name);
1206            }
1207            // A file directly in a library directory belongs to no package there.
1208            if parts.next().is_some() {
1209                next = Some(package);
1210            }
1211            break;
1212        }
1213        let Some(package) = next else { break };
1214        libs = dependency_library_paths(&package);
1215        owner = Some(package);
1216    }
1217    owner?.strip_prefix(&paths.root).ok().map(Path::to_path_buf)
1218}
1219
1220/// Finds aliases restricted to dependency contexts that would resolve an import.
1221///
1222/// Root files get root remappings. Dependency files get remappings scoped to their innermost
1223/// dependency, so the fix does not redirect the alias for the root or other dependencies.
1224fn remapping_candidates<L: Clone>(
1225    paths: &ProjectPathsConfig<L>,
1226    import: &Path,
1227    file: &Path,
1228) -> BTreeMap<String, BTreeSet<String>> {
1229    let file = paths.root.join(file);
1230    let mut candidates = BTreeMap::<_, BTreeSet<_>>::new();
1231    let Some(cwd) = file.parent() else { return candidates };
1232    let owner = dependency_owner(paths, &file);
1233    // Library directories are a fallback of the source graph that the compiler does not share.
1234    let mut candidate_paths = paths.clone();
1235    candidate_paths.libraries.clear();
1236    if !file.starts_with(&paths.root)
1237        || (owner.is_none()
1238            && paths.libraries.iter().any(|lib| file.starts_with(paths.root.join(lib))))
1239        // An applicable root or CLI mapping remains authoritative, even if its target is missing.
1240        || candidate_paths.resolve_library_import(cwd, import).is_some()
1241    {
1242        return candidates;
1243    }
1244    let scope = owner.map(|owner| format!("{}/:", owner.to_slash_lossy())).unwrap_or_default();
1245
1246    for remapping in &paths.remappings {
1247        if let Some(context) = &remapping.context
1248            && paths
1249                .libraries
1250                .iter()
1251                .any(|lib| paths.root.join(context).starts_with(paths.root.join(lib)))
1252        {
1253            let mut global = remapping.clone();
1254            global.context = None;
1255            candidate_paths.remappings = vec![global.clone()];
1256            if candidate_paths
1257                .resolve_library_import(cwd, import)
1258                .is_some_and(|target| target.is_file())
1259            {
1260                candidates.entry(global.name.clone()).or_default().insert(format!(
1261                    "{scope}{}",
1262                    RelativeRemapping::new(global, &paths.root).to_relative_remapping()
1263                ));
1264            }
1265        }
1266    }
1267    candidates
1268}
1269
1270/// Returns the import a compiler failed to find: solc reports it as 6275, Solar without a code.
1271fn missing_import(error: &SolcError) -> Option<&str> {
1272    let (import, _) = match error.error_code {
1273        Some(6275) => error.message.strip_prefix("Source \"")?.split_once("\" not found")?,
1274        None => error.message.strip_prefix("couldn't read ")?.split_once(": ")?,
1275        _ => return None,
1276    };
1277    Some(import)
1278}
1279
1280/// Adds actionable alias migration help to existing import errors, including JSON diagnostics.
1281fn add_scoped_alias_diagnostics<C: Compiler<CompilerContract = Contract>>(
1282    output: &mut ProjectCompileOutput<C>,
1283    paths: &ProjectPathsConfig<C::Language>,
1284) {
1285    for error in &mut output.output_mut().errors {
1286        // CompilationError has no mutable diagnostic accessors; reuse concrete solc errors.
1287        let error = error as &mut dyn Any;
1288        let error = if error.is::<SolcError>() {
1289            error.downcast_mut::<SolcError>().unwrap()
1290        } else if let Some(MultiCompilerError::Solc(error)) =
1291            error.downcast_mut::<MultiCompilerError>()
1292        {
1293            error
1294        } else {
1295            continue;
1296        };
1297        // The compiler may reject an import that the source graph resolved through a fallback, so
1298        // take the missing import from the error itself.
1299        if let Some(import) = missing_import(error).map(PathBuf::from)
1300            && let Some(location) = &error.source_location
1301            && let file = paths.root.join(&location.file)
1302            && let aliases = remapping_candidates(paths, &import, &file)
1303            && !aliases.is_empty()
1304        {
1305            let importer = dependency_owner(paths, &file).map_or_else(
1306                || "the root project".to_string(),
1307                |owner| format!("`{}/`", owner.to_slash_lossy()),
1308            );
1309            for (alias, mappings) in aliases {
1310                let action = if mappings.len() == 1 {
1311                    "add a remapping to foundry.toml or remappings.txt"
1312                } else {
1313                    "choose a remapping in foundry.toml or remappings.txt"
1314                };
1315                // Text rendering restyles later `note:message` lines, which would corrupt
1316                // remappings containing `:`, so list them on the help line.
1317                let help = format!(
1318                    "help: this file imports the alias {alias:?}, which is scoped to a dependency. \
1319                     To use it from {importer}, {action}: {}",
1320                    mappings.iter().map(|mapping| format!("`{mapping}`")).join(" or ")
1321                );
1322                error.secondary_source_locations.push(SecondarySourceLocation {
1323                    file: None,
1324                    start: None,
1325                    end: None,
1326                    message: Some(help.clone()),
1327                });
1328                // Keep the original message intact so text rendering does not print help twice.
1329                let message = error.formatted_message.as_mut().unwrap_or(&mut error.message);
1330                message.truncate(message.trim_end().len());
1331                message.push_str("\n\n");
1332                message.push_str(&help);
1333                message.push('\n');
1334            }
1335        }
1336    }
1337}
1338
1339#[cfg(test)]
1340mod tests {
1341    use super::*;
1342    use foundry_compilers::multi::MultiCompilerLanguage;
1343    use std::fs;
1344    use tempfile::tempdir;
1345
1346    #[test]
1347    fn parse_contract_identifiers() {
1348        let t = ["src/Counter.sol", "src/Counter.sol:Counter", "Counter"];
1349
1350        let i1 = PathOrContractInfo::from_str(t[0]).unwrap();
1351        assert_eq!(i1, PathOrContractInfo::Path(PathBuf::from(t[0])));
1352
1353        let i2 = PathOrContractInfo::from_str(t[1]).unwrap();
1354        assert_eq!(
1355            i2,
1356            PathOrContractInfo::ContractInfo(CompilerContractInfo {
1357                path: Some("src/Counter.sol".to_string()),
1358                name: "Counter".to_string()
1359            })
1360        );
1361
1362        let i3 = PathOrContractInfo::from_str(t[2]).unwrap();
1363        assert_eq!(
1364            i3,
1365            PathOrContractInfo::ContractInfo(CompilerContractInfo {
1366                path: None,
1367                name: "Counter".to_string()
1368            })
1369        );
1370    }
1371
1372    #[test]
1373    fn size_report_uses_configured_limits() {
1374        let mut contracts = BTreeMap::new();
1375        contracts.insert(
1376            "LargeContract".to_string(),
1377            ContractInfo { runtime_size: 30_000, init_size: 60_000, is_dev_contract: false },
1378        );
1379
1380        let default_report =
1381            SizeReport { contracts: contracts.clone(), limits: ContractSizeLimits::default() };
1382        assert!(default_report.exceeds_runtime_size_limit());
1383        assert!(default_report.exceeds_initcode_size_limit());
1384
1385        let custom_report =
1386            SizeReport { contracts, limits: ContractSizeLimits::new(131_072, 262_144) };
1387        assert!(!custom_report.exceeds_runtime_size_limit());
1388        assert!(!custom_report.exceeds_initcode_size_limit());
1389        let output: serde_json::Value =
1390            serde_json::from_str(&custom_report.format_json_output()).unwrap();
1391        assert_eq!(
1392            output,
1393            serde_json::json!({
1394                "LargeContract": {
1395                    "runtime_size": 30000,
1396                    "init_size": 60000,
1397                    "runtime_margin": 101072,
1398                    "init_margin": 202144,
1399                }
1400            })
1401        );
1402    }
1403
1404    #[test]
1405    fn contract_size_limits_derive_initcode_limit_from_runtime_limit() {
1406        assert_eq!(
1407            ContractSizeLimits::with_runtime_limit(50_000),
1408            ContractSizeLimits::new(50_000, 100_000)
1409        );
1410    }
1411
1412    #[test]
1413    fn contract_size_limits_follow_evm_spec() {
1414        assert_eq!(ContractSizeLimits::for_spec_id(SpecId::OSAKA), ContractSizeLimits::default());
1415        assert_eq!(
1416            ContractSizeLimits::for_spec_id(SpecId::AMSTERDAM),
1417            ContractSizeLimits::new(65_536, 131_072)
1418        );
1419    }
1420
1421    #[test]
1422    fn sanitized_remapping_paths_stay_inside_the_root() {
1423        let root = Path::new("/tmp/sources");
1424        for path in ["../../../etc", "a/../../../etc", "/etc", "./a/../b"] {
1425            let joined = root.join(sanitize_relative_path(Path::new(path)));
1426            assert!(
1427                joined.starts_with(root) && !joined.components().any(|c| c == Component::ParentDir),
1428                "{path} escaped the root: {}",
1429                joined.display()
1430            );
1431        }
1432
1433        for (path, expected) in [("src/../lib/", "lib"), ("./a/../b", "b"), ("a/../../lib", "lib")]
1434        {
1435            assert_eq!(sanitize_relative_path(Path::new(path)), Path::new(expected));
1436        }
1437
1438        // Ordinary relative paths are left alone.
1439        assert_eq!(
1440            sanitize_relative_path(Path::new("lib/openzeppelin")),
1441            Path::new("lib/openzeppelin")
1442        );
1443    }
1444
1445    #[test]
1446    fn remapping_candidates_respect_targets_choices_and_importers() {
1447        let temp = tempdir().unwrap();
1448        let root = temp.path().join("project");
1449        fs::create_dir_all(root.join("lib/a/src")).unwrap();
1450        fs::write(root.join("lib/a/src/Target.sol"), "contract Target {}\n").unwrap();
1451        // A dependency can keep its nested dependencies in a directory the root does not use.
1452        fs::create_dir_all(root.join("lib/d")).unwrap();
1453        fs::write(root.join("lib/d/foundry.toml"), "[profile.default]\nlibs = [\"./vendor\"]\n")
1454            .unwrap();
1455        // The source graph resolves `File.sol` to this loose copy, but the compiler does not.
1456        fs::write(root.join("lib/File.sol"), "contract Loose {}\n").unwrap();
1457        let root = dunce::canonicalize(root).unwrap();
1458        let paths = ProjectPathsConfig::builder()
1459            .root(&root)
1460            .lib(root.join("lib"))
1461            .lib(root.join("node_modules"))
1462            .remapping(Remapping::from_str("lib/a/:@alias/=lib/a/src/").unwrap())
1463            .remapping(Remapping::from_str("lib/a/:File.sol=lib/a/src/Target.sol").unwrap())
1464            .build::<MultiCompilerLanguage>()
1465            .unwrap();
1466        let file = root.join("src/Root.sol");
1467        let import = Path::new("@alias/Target.sol");
1468
1469        assert_eq!(
1470            remapping_candidates(&paths, Path::new("File.sol"), &file),
1471            BTreeMap::from([(
1472                "File.sol".to_string(),
1473                BTreeSet::from(["File.sol=lib/a/src/Target.sol".to_string()])
1474            )])
1475        );
1476
1477        // Dependency importers get a remapping scoped to their own innermost dependency.
1478        for (importer, scoped) in [
1479            ("lib/b/src/nested/Dep.sol", "lib/b/:@alias/=lib/a/src/"),
1480            // Nested dependencies own their files; a loose nested file belongs to its parent.
1481            ("lib/b/lib/c/src/C.sol", "lib/b/lib/c/:@alias/=lib/a/src/"),
1482            ("lib/b/lib/Loose.sol", "lib/b/:@alias/=lib/a/src/"),
1483            ("lib/d/vendor/c/src/C.sol", "lib/d/vendor/c/:@alias/=lib/a/src/"),
1484            ("lib/d/lib/c/src/C.sol", "lib/d/:@alias/=lib/a/src/"),
1485            ("node_modules/@scope/c/src/Dep.sol", "node_modules/@scope/c/:@alias/=lib/a/src/"),
1486            // Soldeer packages start with `@` but are not npm scopes.
1487            ("lib/@pkg-1.0.0/src/Dep.sol", "lib/@pkg-1.0.0/:@alias/=lib/a/src/"),
1488            ("lib/@pkg-1.0.0/Dep.sol", "lib/@pkg-1.0.0/:@alias/=lib/a/src/"),
1489        ] {
1490            fs::create_dir_all(root.join(importer).parent().unwrap()).unwrap();
1491            assert_eq!(
1492                remapping_candidates(&paths, import, &root.join(importer)),
1493                BTreeMap::from([("@alias/".to_string(), BTreeSet::from([scoped.to_string()]))])
1494            );
1495        }
1496
1497        for (import, file) in [
1498            (Path::new("@alias/Missing.sol"), file.clone()),
1499            (import, root.join("lib/Loose.sol")),
1500            (import, root.join("lib/a/src/Target.sol")),
1501            (import, temp.path().join("Outside.sol")),
1502        ] {
1503            assert_eq!(remapping_candidates(&paths, import, &file), BTreeMap::new());
1504        }
1505
1506        for explicit in ["@alias/=missing/", "src/:@alias/=missing/"] {
1507            let mut paths = paths.clone();
1508            paths.remappings.push(Remapping::from_str(explicit).unwrap());
1509            assert_eq!(remapping_candidates(&paths, import, &file), BTreeMap::new());
1510        }
1511    }
1512}