foundry_compilers/compilers/solc/
compiler.rs

1use crate::resolver::parse::SolData;
2use foundry_compilers_artifacts::{sources::Source, CompilerOutput, SolcInput};
3use foundry_compilers_core::{
4    error::{Result, SolcError},
5    utils::{SUPPORTS_BASE_PATH, SUPPORTS_INCLUDE_PATH},
6};
7use itertools::Itertools;
8use semver::{Version, VersionReq};
9use serde::{de::DeserializeOwned, Deserialize, Serialize};
10use std::{
11    collections::BTreeSet,
12    io::{self, Write},
13    path::{Path, PathBuf},
14    process::{Command, Output, Stdio},
15    str::FromStr,
16};
17
18/// Extensions acceptable by solc compiler.
19pub const SOLC_EXTENSIONS: &[&str] = &["sol", "yul"];
20
21/// take the lock in tests, we use this to enforce that
22/// a test does not run while a compiler version is being installed
23///
24/// This ensures that only one thread installs a missing `solc` exe.
25/// Instead of taking this lock in `Solc::blocking_install`, the lock should be taken before
26/// installation is detected.
27#[cfg(feature = "svm-solc")]
28#[cfg(any(test, feature = "test-utils"))]
29#[macro_export]
30macro_rules! take_solc_installer_lock {
31    ($lock:ident) => {
32        let lock_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(".lock");
33        let lock_file = std::fs::OpenOptions::new()
34            .read(true)
35            .write(true)
36            .create(true)
37            .truncate(false)
38            .open(lock_path)
39            .unwrap();
40        let mut lock = fd_lock::RwLock::new(lock_file);
41        let $lock = lock.write().unwrap();
42    };
43}
44
45/// A list of upstream Solc releases, used to check which version
46/// we should download.
47/// The boolean value marks whether there was an error accessing the release list
48#[cfg(feature = "svm-solc")]
49pub static RELEASES: std::sync::LazyLock<(svm::Releases, Vec<Version>, bool)> =
50    std::sync::LazyLock::new(|| {
51        match serde_json::from_str::<svm::Releases>(svm_builds::RELEASE_LIST_JSON) {
52            Ok(releases) => {
53                let sorted_versions = releases.clone().into_versions();
54                (releases, sorted_versions, true)
55            }
56            Err(err) => {
57                error!("failed to deserialize SVM static RELEASES JSON: {err}");
58                Default::default()
59            }
60        }
61    });
62
63/// Abstraction over `solc` command line utility
64///
65/// Supports sync and async functions.
66///
67/// By default the solc path is configured as follows, with descending priority:
68///   1. `SOLC_PATH` environment variable
69///   2. [svm](https://github.com/roynalnaruto/svm-rs)'s  `global_version` (set via `svm use
70///      <version>`), stored at `<svm_home>/.global_version`
71///   3. `solc` otherwise
72#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
73pub struct Solc {
74    /// Path to the `solc` executable
75    pub solc: PathBuf,
76    /// Compiler version.
77    pub version: Version,
78    /// Value for --base-path arg.
79    pub base_path: Option<PathBuf>,
80    /// Value for --allow-paths arg.
81    pub allow_paths: BTreeSet<PathBuf>,
82    /// Value for --include-paths arg.
83    pub include_paths: BTreeSet<PathBuf>,
84    /// Additional arbitrary arguments.
85    pub extra_args: Vec<String>,
86}
87
88impl Solc {
89    /// A new instance which points to `solc`. Invokes `solc --version` to determine the version.
90    ///
91    /// Returns error if `solc` is not found in the system or if the version cannot be retrieved.
92    #[instrument(name = "Solc::new", skip_all)]
93    pub fn new(path: impl Into<PathBuf>) -> Result<Self> {
94        Self::new_with_args(path, Vec::<String>::new())
95    }
96
97    /// A new instance which points to `solc` with additional cli arguments. Invokes `solc
98    /// --version` to determine the version.
99    ///
100    /// Returns error if `solc` is not found in the system or if the version cannot be retrieved.
101    pub fn new_with_args(
102        path: impl Into<PathBuf>,
103        extra_args: impl IntoIterator<Item: Into<String>>,
104    ) -> Result<Self> {
105        let path = path.into();
106        let extra_args = extra_args.into_iter().map(Into::into).collect::<Vec<_>>();
107        let version = Self::version_with_args(path.clone(), &extra_args)?;
108        Ok(Self::_new(path, version, extra_args))
109    }
110
111    /// A new instance which points to `solc` with the given version
112    pub fn new_with_version(path: impl Into<PathBuf>, version: Version) -> Self {
113        Self::_new(path.into(), version, Default::default())
114    }
115
116    fn _new(path: PathBuf, version: Version, extra_args: Vec<String>) -> Self {
117        let this = Self {
118            solc: path,
119            version,
120            base_path: None,
121            allow_paths: Default::default(),
122            include_paths: Default::default(),
123            extra_args,
124        };
125        this.debug_assert();
126        this
127    }
128
129    fn debug_assert(&self) {
130        if !cfg!(debug_assertions) {
131            return;
132        }
133        assert_eq!(self.version_short(), self.version);
134        if let Ok(v) = Self::version_with_args(&self.solc, &self.extra_args) {
135            assert_eq!(v.major, self.version.major);
136            assert_eq!(v.minor, self.version.minor);
137            assert_eq!(v.patch, self.version.patch);
138        }
139    }
140
141    /// Parses the given source looking for the `pragma` definition and
142    /// returns the corresponding SemVer version requirement.
143    pub fn source_version_req(source: &Source) -> Result<VersionReq> {
144        Ok(SolData::parse_version_pragma(&source.content).ok_or(SolcError::PragmaNotFound)??)
145    }
146
147    /// Given a Solidity source, it detects the latest compiler version which can be used
148    /// to build it, and returns it.
149    ///
150    /// If the required compiler version is not installed, it also proceeds to install it.
151    #[cfg(feature = "svm-solc")]
152    pub fn detect_version(source: &Source) -> Result<Version> {
153        // detects the required solc version
154        let sol_version = Self::source_version_req(source)?;
155        Self::ensure_installed(&sol_version)
156    }
157
158    /// Given a Solidity version requirement, it detects the latest compiler version which can be
159    /// used to build it, and returns it.
160    ///
161    /// If the required compiler version is not installed, it also proceeds to install it.
162    #[cfg(feature = "svm-solc")]
163    pub fn ensure_installed(sol_version: &VersionReq) -> Result<Version> {
164        #[cfg(test)]
165        take_solc_installer_lock!(_lock);
166
167        // load the local / remote versions
168        let versions = Self::installed_versions();
169
170        let local_versions = Self::find_matching_installation(&versions, sol_version);
171        let remote_versions = Self::find_matching_installation(&RELEASES.1, sol_version);
172
173        // if there's a better upstream version than the one we have, install it
174        Ok(match (local_versions, remote_versions) {
175            (Some(local), None) => local,
176            (Some(local), Some(remote)) => {
177                if remote > local {
178                    Self::blocking_install(&remote)?;
179                    remote
180                } else {
181                    local
182                }
183            }
184            (None, Some(version)) => {
185                Self::blocking_install(&version)?;
186                version
187            }
188            // do nothing otherwise
189            _ => return Err(SolcError::VersionNotFound),
190        })
191    }
192
193    /// Assuming the `versions` array is sorted, it returns the first element which satisfies
194    /// the provided [`VersionReq`]
195    pub fn find_matching_installation(
196        versions: &[Version],
197        required_version: &VersionReq,
198    ) -> Option<Version> {
199        // iterate in reverse to find the last match
200        versions.iter().rev().find(|version| required_version.matches(version)).cloned()
201    }
202
203    /// Returns the path for a [svm](https://github.com/roynalnaruto/svm-rs) installed version.
204    ///
205    /// # Examples
206    ///
207    /// ```no_run
208    /// use foundry_compilers::solc::Solc;
209    /// use semver::Version;
210    ///
211    /// let solc = Solc::find_svm_installed_version(&Version::new(0, 8, 9))?;
212    /// assert_eq!(solc, Some(Solc::new("~/.svm/0.8.9/solc-0.8.9")?));
213    ///
214    /// Ok::<_, Box<dyn std::error::Error>>(())
215    /// ```
216    #[instrument(skip_all)]
217    #[cfg(feature = "svm-solc")]
218    pub fn find_svm_installed_version(version: &Version) -> Result<Option<Self>> {
219        let version = Version::new(version.major, version.minor, version.patch);
220        let solc = svm::version_binary(&version.to_string());
221        if !solc.is_file() {
222            return Ok(None);
223        }
224        Ok(Some(Self::new_with_version(&solc, version)))
225    }
226
227    /// Returns the directory in which [svm](https://github.com/roynalnaruto/svm-rs) stores all versions
228    ///
229    /// This will be:
230    /// - `~/.svm` on unix, if it exists
231    /// - $XDG_DATA_HOME (~/.local/share/svm) if the svm folder does not exist.
232    #[cfg(feature = "svm-solc")]
233    pub fn svm_home() -> Option<PathBuf> {
234        Some(svm::data_dir().to_path_buf())
235    }
236
237    /// Returns the `semver::Version` [svm](https://github.com/roynalnaruto/svm-rs)'s `.global_version` is currently set to.
238    ///  `global_version` is configured with (`svm use <version>`)
239    ///
240    /// This will read the version string (eg: "0.8.9") that the  `~/.svm/.global_version` file
241    /// contains
242    #[cfg(feature = "svm-solc")]
243    pub fn svm_global_version() -> Option<Version> {
244        svm::get_global_version().ok().flatten()
245    }
246
247    /// Returns the list of all solc instances installed at `SVM_HOME`
248    #[cfg(feature = "svm-solc")]
249    pub fn installed_versions() -> Vec<Version> {
250        svm::installed_versions().unwrap_or_default()
251    }
252
253    /// Returns the list of all versions that are available to download
254    #[cfg(feature = "svm-solc")]
255    pub fn released_versions() -> Vec<Version> {
256        RELEASES.1.clone()
257    }
258
259    /// Installs the provided version of Solc in the machine under the svm dir and returns the
260    /// [Solc] instance pointing to the installation.
261    ///
262    /// # Examples
263    ///
264    /// ```no_run
265    /// use foundry_compilers::{solc::Solc, utils::ISTANBUL_SOLC};
266    ///
267    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
268    /// let solc = Solc::install(&ISTANBUL_SOLC).await?;
269    /// # Ok(())
270    /// # }
271    /// ```
272    #[cfg(feature = "svm-solc")]
273    #[instrument(name = "Solc::install", skip_all)]
274    pub async fn install(version: &Version) -> std::result::Result<Self, svm::SvmError> {
275        trace!("installing solc version \"{}\"", version);
276        crate::report::solc_installation_start(version);
277        match svm::install(version).await {
278            Ok(path) => {
279                crate::report::solc_installation_success(version);
280                Ok(Self::new_with_version(path, version.clone()))
281            }
282            Err(err) => {
283                crate::report::solc_installation_error(version, &err.to_string());
284                Err(err)
285            }
286        }
287    }
288
289    /// Blocking version of `Self::install`
290    #[cfg(feature = "svm-solc")]
291    #[instrument(name = "Solc::blocking_install", skip_all)]
292    pub fn blocking_install(version: &Version) -> std::result::Result<Self, svm::SvmError> {
293        use foundry_compilers_core::utils::RuntimeOrHandle;
294
295        #[cfg(test)]
296        crate::take_solc_installer_lock!(_lock);
297
298        let version = Version::new(version.major, version.minor, version.patch);
299
300        trace!("blocking installing solc version \"{}\"", version);
301        crate::report::solc_installation_start(&version);
302        // The async version `svm::install` is used instead of `svm::blocking_install`
303        // because the underlying `reqwest::blocking::Client` does not behave well
304        // inside of a Tokio runtime. See: https://github.com/seanmonstar/reqwest/issues/1017
305        match RuntimeOrHandle::new().block_on(svm::install(&version)) {
306            Ok(path) => {
307                crate::report::solc_installation_success(&version);
308                Ok(Self::new_with_version(path, version.clone()))
309            }
310            Err(err) => {
311                crate::report::solc_installation_error(&version, &err.to_string());
312                Err(err)
313            }
314        }
315    }
316
317    /// Verify that the checksum for this version of solc is correct. We check against the SHA256
318    /// checksum from the build information published by [binaries.soliditylang.org](https://binaries.soliditylang.org/)
319    #[cfg(feature = "svm-solc")]
320    #[instrument(name = "Solc::verify_checksum", skip_all)]
321    pub fn verify_checksum(&self) -> Result<()> {
322        let version = self.version_short();
323        let mut version_path = svm::version_path(version.to_string().as_str());
324        version_path.push(format!("solc-{}", version.to_string().as_str()));
325        trace!(target:"solc", "reading solc binary for checksum {:?}", version_path);
326        let content =
327            std::fs::read(&version_path).map_err(|err| SolcError::io(err, version_path.clone()))?;
328
329        if !RELEASES.2 {
330            // we skip checksum verification because the underlying request to fetch release info
331            // failed so we have nothing to compare against
332            return Ok(());
333        }
334
335        #[cfg(windows)]
336        {
337            // Prior to 0.7.2, binaries are released as exe files which are hard to verify: <https://github.com/foundry-rs/foundry/issues/5601>
338            // <https://binaries.soliditylang.org/windows-amd64/list.json>
339            const V0_7_2: Version = Version::new(0, 7, 2);
340            if version < V0_7_2 {
341                return Ok(());
342            }
343        }
344
345        use sha2::Digest;
346        let mut hasher = sha2::Sha256::new();
347        hasher.update(content);
348        let checksum_calc = &hasher.finalize()[..];
349
350        let checksum_found = &RELEASES
351            .0
352            .get_checksum(&version)
353            .ok_or_else(|| SolcError::ChecksumNotFound { version: version.clone() })?;
354
355        if checksum_calc == checksum_found {
356            Ok(())
357        } else {
358            use alloy_primitives::hex;
359            let expected = hex::encode(checksum_found);
360            let detected = hex::encode(checksum_calc);
361            warn!(target: "solc", "checksum mismatch for {:?}, expected {}, but found {} for file {:?}", version, expected, detected, version_path);
362            Err(SolcError::ChecksumMismatch { version, expected, detected, file: version_path })
363        }
364    }
365
366    /// Convenience function for compiling all sources under the given path
367    pub fn compile_source(&self, path: &Path) -> Result<CompilerOutput> {
368        let mut res: CompilerOutput = Default::default();
369        for input in
370            SolcInput::resolve_and_build(Source::read_sol_yul_from(path)?, Default::default())
371        {
372            let input = input.sanitized(&self.version);
373            let output = self.compile(&input)?;
374            res.merge(output)
375        }
376
377        Ok(res)
378    }
379
380    /// Same as [`Self::compile()`], but only returns those files which are included in the
381    /// `CompilerInput`.
382    ///
383    /// In other words, this removes those files from the `CompilerOutput` that are __not__ included
384    /// in the provided `CompilerInput`.
385    ///
386    /// # Examples
387    pub fn compile_exact(&self, input: &SolcInput) -> Result<CompilerOutput> {
388        let mut out = self.compile(input)?;
389        out.retain_files(input.sources.keys().map(|p| p.as_path()));
390        Ok(out)
391    }
392
393    /// Compiles with `--standard-json` and deserializes the output as [`CompilerOutput`].
394    ///
395    /// # Examples
396    ///
397    /// ```no_run
398    /// use foundry_compilers::{
399    ///     artifacts::{SolcInput, Source},
400    ///     compilers::{Compiler, CompilerInput},
401    ///     solc::Solc,
402    /// };
403    ///
404    /// let solc = Solc::new("solc")?;
405    /// let input = SolcInput::resolve_and_build(
406    ///     Source::read_sol_yul_from("./contracts".as_ref()).unwrap(),
407    ///     Default::default(),
408    /// );
409    /// let output = solc.compile(&input)?;
410    /// # Ok::<_, Box<dyn std::error::Error>>(())
411    /// ```
412    pub fn compile<T: Serialize>(&self, input: &T) -> Result<CompilerOutput> {
413        self.compile_as(input)
414    }
415
416    /// Compiles with `--standard-json` and deserializes the output as the given `D`.
417    #[instrument(name = "Solc::compile", skip_all)]
418    pub fn compile_as<T: Serialize, D: DeserializeOwned>(&self, input: &T) -> Result<D> {
419        let output = self.compile_output(input)?;
420
421        // Only run UTF-8 validation once.
422        let output = std::str::from_utf8(&output).map_err(|_| SolcError::InvalidUtf8)?;
423
424        Ok(serde_json::from_str(output)?)
425    }
426
427    /// Compiles with `--standard-json` and returns the raw `stdout` output.
428    #[instrument(name = "Solc::compile_raw", skip_all)]
429    pub fn compile_output<T: Serialize>(&self, input: &T) -> Result<Vec<u8>> {
430        let mut cmd = self.configure_cmd();
431
432        trace!(input=%serde_json::to_string(input).unwrap_or_else(|e| e.to_string()));
433        debug!(?cmd, "compiling");
434
435        let mut child = cmd.spawn().map_err(self.map_io_err())?;
436        debug!("spawned");
437
438        {
439            let mut stdin = io::BufWriter::new(child.stdin.take().unwrap());
440            serde_json::to_writer(&mut stdin, input)?;
441            stdin.flush().map_err(self.map_io_err())?;
442        }
443        debug!("wrote JSON input to stdin");
444
445        let output = child.wait_with_output().map_err(self.map_io_err())?;
446        debug!(%output.status, output.stderr = ?String::from_utf8_lossy(&output.stderr), "finished");
447
448        compile_output(output)
449    }
450
451    /// Returns the SemVer [`Version`], stripping the pre-release and build metadata.
452    pub fn version_short(&self) -> Version {
453        Version::new(self.version.major, self.version.minor, self.version.patch)
454    }
455
456    /// Invokes `solc --version` and parses the output as a SemVer [`Version`].
457    pub fn version(solc: impl Into<PathBuf>) -> Result<Version> {
458        Self::version_with_args(solc, &[])
459    }
460
461    /// Invokes `solc --version` and parses the output as a SemVer [`Version`].
462    pub fn version_with_args(solc: impl Into<PathBuf>, args: &[String]) -> Result<Version> {
463        crate::cache_version(solc.into(), args, |solc| Self::version_impl(solc, args))
464    }
465
466    fn version_impl(solc: &Path, args: &[String]) -> Result<Version> {
467        let mut cmd = Command::new(solc);
468        cmd.args(args)
469            .arg("--version")
470            .stdin(Stdio::piped())
471            .stderr(Stdio::piped())
472            .stdout(Stdio::piped());
473        debug!(?cmd, "getting Solc version");
474        let output = cmd.output().map_err(|e| SolcError::io(e, solc))?;
475        trace!(?output);
476        let version = version_from_output(output)?;
477        debug!(%version);
478        Ok(version)
479    }
480
481    fn map_io_err(&self) -> impl FnOnce(std::io::Error) -> SolcError + '_ {
482        move |err| SolcError::io(err, &self.solc)
483    }
484
485    /// Configures [Command] object depending on settings and solc version used.
486    /// Some features are only supported by newer versions of solc, so we have to disable them for
487    /// older ones.
488    pub fn configure_cmd(&self) -> Command {
489        let mut cmd = Command::new(&self.solc);
490        cmd.stdin(Stdio::piped()).stderr(Stdio::piped()).stdout(Stdio::piped());
491        cmd.args(&self.extra_args);
492
493        if !self.allow_paths.is_empty() {
494            cmd.arg("--allow-paths");
495            cmd.arg(self.allow_paths.iter().map(|p| p.display()).join(","));
496        }
497        if let Some(base_path) = &self.base_path {
498            if SUPPORTS_BASE_PATH.matches(&self.version) {
499                if SUPPORTS_INCLUDE_PATH.matches(&self.version) {
500                    // `--base-path` and `--include-path` conflict if set to the same path, so
501                    // as a precaution, we ensure here that the `--base-path` is not also used
502                    // for `--include-path`
503                    for path in
504                        self.include_paths.iter().filter(|p| p.as_path() != base_path.as_path())
505                    {
506                        cmd.arg("--include-path").arg(path);
507                    }
508                }
509
510                cmd.arg("--base-path").arg(base_path);
511            }
512
513            cmd.current_dir(base_path);
514        }
515
516        cmd.arg("--standard-json");
517
518        cmd
519    }
520
521    /// Either finds an installed Solc version or installs it if it's not found.
522    #[cfg(feature = "svm-solc")]
523    pub fn find_or_install(version: &Version) -> Result<Self> {
524        let solc = if let Some(solc) = Self::find_svm_installed_version(version)? {
525            solc
526        } else {
527            Self::blocking_install(version)?
528        };
529
530        Ok(solc)
531    }
532}
533
534#[cfg(feature = "async")]
535impl Solc {
536    /// Convenience function for compiling all sources under the given path
537    pub async fn async_compile_source(&self, path: &Path) -> Result<CompilerOutput> {
538        self.async_compile(&SolcInput::resolve_and_build(
539            Source::async_read_all_from(path, SOLC_EXTENSIONS).await?,
540            Default::default(),
541        ))
542        .await
543    }
544
545    /// Run `solc --stand-json` and return the `solc`'s output as
546    /// `CompilerOutput`
547    pub async fn async_compile<T: Serialize>(&self, input: &T) -> Result<CompilerOutput> {
548        self.async_compile_as(input).await
549    }
550
551    /// Run `solc --stand-json` and return the `solc`'s output as the given json
552    /// output
553    pub async fn async_compile_as<T: Serialize, D: DeserializeOwned>(
554        &self,
555        input: &T,
556    ) -> Result<D> {
557        let output = self.async_compile_output(input).await?;
558        Ok(serde_json::from_slice(&output)?)
559    }
560
561    pub async fn async_compile_output<T: Serialize>(&self, input: &T) -> Result<Vec<u8>> {
562        use tokio::{io::AsyncWriteExt, process::Command};
563
564        let mut cmd: Command = self.configure_cmd().into();
565        let mut child = cmd.spawn().map_err(self.map_io_err())?;
566        let stdin = child.stdin.as_mut().unwrap();
567
568        let content = serde_json::to_vec(input)?;
569
570        stdin.write_all(&content).await.map_err(self.map_io_err())?;
571        stdin.flush().await.map_err(self.map_io_err())?;
572
573        compile_output(child.wait_with_output().await.map_err(self.map_io_err())?)
574    }
575
576    pub async fn async_version(solc: &Path) -> Result<Version> {
577        let mut cmd = tokio::process::Command::new(solc);
578        cmd.arg("--version").stdin(Stdio::piped()).stderr(Stdio::piped()).stdout(Stdio::piped());
579        debug!(?cmd, "getting version");
580        let output = cmd.output().await.map_err(|e| SolcError::io(e, solc))?;
581        let version = version_from_output(output)?;
582        debug!(%version);
583        Ok(version)
584    }
585
586    /// Compiles all `CompilerInput`s with their associated `Solc`.
587    ///
588    /// This will buffer up to `n` `solc` processes and then return the `CompilerOutput`s in the
589    /// order in which they complete. No more than `n` futures will be buffered at any point in
590    /// time, and less than `n` may also be buffered depending on the state of each future.
591    pub async fn compile_many<I>(jobs: I, n: usize) -> crate::many::CompiledMany
592    where
593        I: IntoIterator<Item = (Self, SolcInput)>,
594    {
595        use futures_util::stream::StreamExt;
596
597        let outputs = futures_util::stream::iter(
598            jobs.into_iter()
599                .map(|(solc, input)| async { (solc.async_compile(&input).await, solc, input) }),
600        )
601        .buffer_unordered(n)
602        .collect::<Vec<_>>()
603        .await;
604
605        crate::many::CompiledMany::new(outputs)
606    }
607}
608
609fn compile_output(output: Output) -> Result<Vec<u8>> {
610    if output.status.success() {
611        Ok(output.stdout)
612    } else {
613        Err(SolcError::solc_output(&output))
614    }
615}
616
617fn version_from_output(output: Output) -> Result<Version> {
618    if output.status.success() {
619        let stdout = String::from_utf8_lossy(&output.stdout);
620        let version = stdout
621            .lines()
622            .filter(|l| !l.trim().is_empty())
623            .next_back()
624            .ok_or_else(|| SolcError::msg("Version not found in Solc output"))?;
625        // NOTE: semver doesn't like `+` in g++ in build metadata which is invalid semver
626        Ok(Version::from_str(&version.trim_start_matches("Version: ").replace(".g++", ".gcc"))?)
627    } else {
628        Err(SolcError::solc_output(&output))
629    }
630}
631
632impl AsRef<Path> for Solc {
633    fn as_ref(&self) -> &Path {
634        &self.solc
635    }
636}
637
638#[cfg(test)]
639#[cfg(feature = "svm-solc")]
640mod tests {
641    use super::*;
642    use crate::{resolver::parse::SolData, Artifact};
643
644    #[test]
645    fn test_version_parse() {
646        let req = SolData::parse_version_req(">=0.6.2 <0.8.21").unwrap();
647        let semver_req: VersionReq = ">=0.6.2,<0.8.21".parse().unwrap();
648        assert_eq!(req, semver_req);
649    }
650
651    fn solc() -> Solc {
652        if let Some(solc) = Solc::find_svm_installed_version(&Version::new(0, 8, 18)).unwrap() {
653            solc
654        } else {
655            Solc::blocking_install(&Version::new(0, 8, 18)).unwrap()
656        }
657    }
658
659    #[test]
660    fn solc_version_works() {
661        Solc::version(solc().solc).unwrap();
662    }
663
664    #[test]
665    fn can_parse_version_metadata() {
666        let _version = Version::from_str("0.6.6+commit.6c089d02.Linux.gcc").unwrap();
667    }
668
669    #[cfg(feature = "async")]
670    #[tokio::test(flavor = "multi_thread")]
671    async fn async_solc_version_works() {
672        Solc::async_version(&solc().solc).await.unwrap();
673    }
674
675    #[test]
676    fn solc_compile_works() {
677        let input = include_str!("../../../../../test-data/in/compiler-in-1.json");
678        let input: SolcInput = serde_json::from_str(input).unwrap();
679        let out = solc().compile(&input).unwrap();
680        let other = solc().compile(&serde_json::json!(input)).unwrap();
681        assert_eq!(out, other);
682    }
683
684    #[test]
685    fn solc_metadata_works() {
686        let input = include_str!("../../../../../test-data/in/compiler-in-1.json");
687        let mut input: SolcInput = serde_json::from_str(input).unwrap();
688        input.settings.push_output_selection("metadata");
689        let out = solc().compile(&input).unwrap();
690        for (_, c) in out.split().1.contracts_iter() {
691            assert!(c.metadata.is_some());
692        }
693    }
694
695    #[test]
696    fn can_compile_with_remapped_links() {
697        let input: SolcInput = serde_json::from_str(include_str!(
698            "../../../../../test-data/library-remapping-in.json"
699        ))
700        .unwrap();
701        let out = solc().compile(&input).unwrap();
702        let (_, mut contracts) = out.split();
703        let contract = contracts.remove("LinkTest").unwrap();
704        let bytecode = &contract.get_bytecode().unwrap().object;
705        assert!(!bytecode.is_unlinked());
706    }
707
708    #[test]
709    fn can_compile_with_remapped_links_temp_dir() {
710        let input: SolcInput = serde_json::from_str(include_str!(
711            "../../../../../test-data/library-remapping-in-2.json"
712        ))
713        .unwrap();
714        let out = solc().compile(&input).unwrap();
715        let (_, mut contracts) = out.split();
716        let contract = contracts.remove("LinkTest").unwrap();
717        let bytecode = &contract.get_bytecode().unwrap().object;
718        assert!(!bytecode.is_unlinked());
719    }
720
721    #[cfg(feature = "async")]
722    #[tokio::test(flavor = "multi_thread")]
723    async fn async_solc_compile_works() {
724        let input = include_str!("../../../../../test-data/in/compiler-in-1.json");
725        let input: SolcInput = serde_json::from_str(input).unwrap();
726        let out = solc().async_compile(&input).await.unwrap();
727        let other = solc().async_compile(&serde_json::json!(input)).await.unwrap();
728        assert_eq!(out, other);
729    }
730
731    #[cfg(feature = "async")]
732    #[tokio::test(flavor = "multi_thread")]
733    async fn async_solc_compile_works2() {
734        let input = include_str!("../../../../../test-data/in/compiler-in-2.json");
735        let input: SolcInput = serde_json::from_str(input).unwrap();
736        let out = solc().async_compile(&input).await.unwrap();
737        let other = solc().async_compile(&serde_json::json!(input)).await.unwrap();
738        assert_eq!(out, other);
739        let sync_out = solc().compile(&input).unwrap();
740        assert_eq!(out, sync_out);
741    }
742
743    #[test]
744    fn test_version_req() {
745        let versions = ["=0.1.2", "^0.5.6", ">=0.7.1", ">0.8.0"];
746
747        versions.iter().for_each(|version| {
748            let version_req = SolData::parse_version_req(version).unwrap();
749            assert_eq!(version_req, VersionReq::from_str(version).unwrap());
750        });
751
752        // Solidity defines version ranges with a space, whereas the semver package
753        // requires them to be separated with a comma
754        let version_range = ">=0.8.0 <0.9.0";
755        let version_req = SolData::parse_version_req(version_range).unwrap();
756        assert_eq!(version_req, VersionReq::from_str(">=0.8.0,<0.9.0").unwrap());
757    }
758
759    #[test]
760    #[cfg(feature = "full")]
761    fn test_find_installed_version_path() {
762        // This test does not take the lock by default, so we need to manually add it here.
763        take_solc_installer_lock!(_lock);
764        let version = Version::new(0, 8, 6);
765        if svm::installed_versions()
766            .map(|versions| !versions.contains(&version))
767            .unwrap_or_default()
768        {
769            Solc::blocking_install(&version).unwrap();
770        }
771        drop(_lock);
772        let res = Solc::find_svm_installed_version(&version).unwrap().unwrap();
773        let expected = svm::data_dir().join(version.to_string()).join(format!("solc-{version}"));
774        assert_eq!(res.solc, expected);
775    }
776
777    #[test]
778    #[cfg(feature = "svm-solc")]
779    fn can_install_solc_in_tokio_rt() {
780        let version = Version::from_str("0.8.6").unwrap();
781        let rt = tokio::runtime::Runtime::new().unwrap();
782        let result = rt.block_on(async { Solc::blocking_install(&version) });
783        assert!(result.is_ok());
784    }
785
786    #[test]
787    fn does_not_find_not_installed_version() {
788        let ver = Version::new(1, 1, 1);
789        let res = Solc::find_svm_installed_version(&ver).unwrap();
790        assert!(res.is_none());
791    }
792}