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