foundry_compilers/compilers/solc/
compiler.rs1use 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
18pub const SOLC_EXTENSIONS: &[&str] = &["sol", "yul"];
20
21#[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#[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#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
73pub struct Solc {
74 pub solc: PathBuf,
76 pub version: Version,
78 pub base_path: Option<PathBuf>,
80 pub allow_paths: BTreeSet<PathBuf>,
82 pub include_paths: BTreeSet<PathBuf>,
84 pub extra_args: Vec<String>,
86}
87
88impl Solc {
89 #[instrument(name = "Solc::new", skip_all)]
93 pub fn new(path: impl Into<PathBuf>) -> Result<Self> {
94 let path = path.into();
95 let version = Self::version(path.clone())?;
96 Ok(Self::new_with_version(path, version))
97 }
98
99 pub fn new_with_args(
104 path: impl Into<PathBuf>,
105 extra_args: impl IntoIterator<Item: Into<String>>,
106 ) -> Result<Self> {
107 let args = extra_args.into_iter().map(Into::into).collect::<Vec<_>>();
108 let path = path.into();
109 let version = Self::version_with_args(path.clone(), &args)?;
110
111 let mut solc = Self::new_with_version(path, version);
112 solc.extra_args = args;
113
114 Ok(solc)
115 }
116
117 pub fn new_with_version(path: impl Into<PathBuf>, version: Version) -> Self {
119 Self {
120 solc: path.into(),
121 version,
122 base_path: None,
123 allow_paths: Default::default(),
124 include_paths: Default::default(),
125 extra_args: Default::default(),
126 }
127 }
128
129 pub fn source_version_req(source: &Source) -> Result<VersionReq> {
132 Ok(SolData::parse_version_pragma(&source.content).ok_or(SolcError::PragmaNotFound)??)
133 }
134
135 #[cfg(feature = "svm-solc")]
140 pub fn detect_version(source: &Source) -> Result<Version> {
141 let sol_version = Self::source_version_req(source)?;
143 Self::ensure_installed(&sol_version)
144 }
145
146 #[cfg(feature = "svm-solc")]
151 pub fn ensure_installed(sol_version: &VersionReq) -> Result<Version> {
152 #[cfg(test)]
153 take_solc_installer_lock!(_lock);
154
155 let versions = Self::installed_versions();
157
158 let local_versions = Self::find_matching_installation(&versions, sol_version);
159 let remote_versions = Self::find_matching_installation(&RELEASES.1, sol_version);
160
161 Ok(match (local_versions, remote_versions) {
163 (Some(local), None) => local,
164 (Some(local), Some(remote)) => {
165 if remote > local {
166 Self::blocking_install(&remote)?;
167 remote
168 } else {
169 local
170 }
171 }
172 (None, Some(version)) => {
173 Self::blocking_install(&version)?;
174 version
175 }
176 _ => return Err(SolcError::VersionNotFound),
178 })
179 }
180
181 pub fn find_matching_installation(
184 versions: &[Version],
185 required_version: &VersionReq,
186 ) -> Option<Version> {
187 versions.iter().rev().find(|version| required_version.matches(version)).cloned()
189 }
190
191 #[instrument(skip_all)]
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 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 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 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 #[cfg(feature = "svm-solc")]
253 pub fn released_versions() -> Vec<Version> {
254 RELEASES.1.clone().into_iter().collect()
255 }
256
257 #[cfg(feature = "svm-solc")]
271 #[instrument(name = "Solc::install", skip_all)]
272 pub async fn install(version: &Version) -> std::result::Result<Self, svm::SvmError> {
273 trace!("installing solc version \"{}\"", version);
274 crate::report::solc_installation_start(version);
275 match svm::install(version).await {
276 Ok(path) => {
277 crate::report::solc_installation_success(version);
278 Ok(Self::new_with_version(path, version.clone()))
279 }
280 Err(err) => {
281 crate::report::solc_installation_error(version, &err.to_string());
282 Err(err)
283 }
284 }
285 }
286
287 #[cfg(feature = "svm-solc")]
289 #[instrument(name = "Solc::blocking_install", skip_all)]
290 pub fn blocking_install(version: &Version) -> std::result::Result<Self, svm::SvmError> {
291 use foundry_compilers_core::utils::RuntimeOrHandle;
292
293 #[cfg(test)]
294 crate::take_solc_installer_lock!(_lock);
295
296 let version = Version::new(version.major, version.minor, version.patch);
297
298 trace!("blocking installing solc version \"{}\"", version);
299 crate::report::solc_installation_start(&version);
300 match RuntimeOrHandle::new().block_on(svm::install(&version)) {
304 Ok(path) => {
305 crate::report::solc_installation_success(&version);
306 Ok(Self::new_with_version(path, version.clone()))
307 }
308 Err(err) => {
309 crate::report::solc_installation_error(&version, &err.to_string());
310 Err(err)
311 }
312 }
313 }
314
315 #[cfg(feature = "svm-solc")]
318 #[instrument(name = "Solc::verify_checksum", skip_all)]
319 pub fn verify_checksum(&self) -> Result<()> {
320 let version = self.version_short();
321 let mut version_path = svm::version_path(version.to_string().as_str());
322 version_path.push(format!("solc-{}", version.to_string().as_str()));
323 trace!(target:"solc", "reading solc binary for checksum {:?}", version_path);
324 let content =
325 std::fs::read(&version_path).map_err(|err| SolcError::io(err, version_path.clone()))?;
326
327 if !RELEASES.2 {
328 return Ok(());
331 }
332
333 #[cfg(windows)]
334 {
335 const V0_7_2: Version = Version::new(0, 7, 2);
338 if version < V0_7_2 {
339 return Ok(());
340 }
341 }
342
343 use sha2::Digest;
344 let mut hasher = sha2::Sha256::new();
345 hasher.update(content);
346 let checksum_calc = &hasher.finalize()[..];
347
348 let checksum_found = &RELEASES
349 .0
350 .get_checksum(&version)
351 .ok_or_else(|| SolcError::ChecksumNotFound { version: version.clone() })?;
352
353 if checksum_calc == checksum_found {
354 Ok(())
355 } else {
356 use alloy_primitives::hex;
357 let expected = hex::encode(checksum_found);
358 let detected = hex::encode(checksum_calc);
359 warn!(target: "solc", "checksum mismatch for {:?}, expected {}, but found {} for file {:?}", version, expected, detected, version_path);
360 Err(SolcError::ChecksumMismatch { version, expected, detected, file: version_path })
361 }
362 }
363
364 pub fn compile_source(&self, path: &Path) -> Result<CompilerOutput> {
366 let mut res: CompilerOutput = Default::default();
367 for input in
368 SolcInput::resolve_and_build(Source::read_sol_yul_from(path)?, Default::default())
369 {
370 let input = input.sanitized(&self.version);
371 let output = self.compile(&input)?;
372 res.merge(output)
373 }
374
375 Ok(res)
376 }
377
378 pub fn compile_exact(&self, input: &SolcInput) -> Result<CompilerOutput> {
386 let mut out = self.compile(input)?;
387 out.retain_files(input.sources.keys().map(|p| p.as_path()));
388 Ok(out)
389 }
390
391 pub fn compile<T: Serialize>(&self, input: &T) -> Result<CompilerOutput> {
411 self.compile_as(input)
412 }
413
414 #[instrument(name = "Solc::compile", skip_all)]
416 pub fn compile_as<T: Serialize, D: DeserializeOwned>(&self, input: &T) -> Result<D> {
417 let output = self.compile_output(input)?;
418
419 let output = std::str::from_utf8(&output).map_err(|_| SolcError::InvalidUtf8)?;
421
422 Ok(serde_json::from_str(output)?)
423 }
424
425 #[instrument(name = "Solc::compile_raw", skip_all)]
427 pub fn compile_output<T: Serialize>(&self, input: &T) -> Result<Vec<u8>> {
428 let mut cmd = self.configure_cmd();
429
430 trace!(input=%serde_json::to_string(input).unwrap_or_else(|e| e.to_string()));
431 debug!(?cmd, "compiling");
432
433 let mut child = cmd.spawn().map_err(self.map_io_err())?;
434 debug!("spawned");
435
436 {
437 let mut stdin = io::BufWriter::new(child.stdin.take().unwrap());
438 serde_json::to_writer(&mut stdin, input)?;
439 stdin.flush().map_err(self.map_io_err())?;
440 }
441 debug!("wrote JSON input to stdin");
442
443 let output = child.wait_with_output().map_err(self.map_io_err())?;
444 debug!(%output.status, output.stderr = ?String::from_utf8_lossy(&output.stderr), "finished");
445
446 compile_output(output)
447 }
448
449 pub fn version_short(&self) -> Version {
452 Version::new(self.version.major, self.version.minor, self.version.patch)
453 }
454
455 pub fn version(solc: impl Into<PathBuf>) -> Result<Version> {
457 Self::version_with_args(solc, &[])
458 }
459
460 pub fn version_with_args(solc: impl Into<PathBuf>, args: &[String]) -> Result<Version> {
462 crate::cache_version(solc.into(), args, |solc| {
463 let mut cmd = Command::new(solc);
464 cmd.args(args)
465 .arg("--version")
466 .stdin(Stdio::piped())
467 .stderr(Stdio::piped())
468 .stdout(Stdio::piped());
469 debug!(?cmd, "getting Solc version");
470 let output = cmd.output().map_err(|e| SolcError::io(e, solc))?;
471 trace!(?output);
472 let version = version_from_output(output)?;
473 debug!(%version);
474 Ok(version)
475 })
476 }
477
478 fn map_io_err(&self) -> impl FnOnce(std::io::Error) -> SolcError + '_ {
479 move |err| SolcError::io(err, &self.solc)
480 }
481
482 pub fn configure_cmd(&self) -> Command {
486 let mut cmd = Command::new(&self.solc);
487 cmd.stdin(Stdio::piped()).stderr(Stdio::piped()).stdout(Stdio::piped());
488 cmd.args(&self.extra_args);
489
490 if !self.allow_paths.is_empty() {
491 cmd.arg("--allow-paths");
492 cmd.arg(self.allow_paths.iter().map(|p| p.display()).join(","));
493 }
494 if let Some(base_path) = &self.base_path {
495 if SUPPORTS_BASE_PATH.matches(&self.version) {
496 if SUPPORTS_INCLUDE_PATH.matches(&self.version) {
497 for path in
501 self.include_paths.iter().filter(|p| p.as_path() != base_path.as_path())
502 {
503 cmd.arg("--include-path").arg(path);
504 }
505 }
506
507 cmd.arg("--base-path").arg(base_path);
508 }
509
510 cmd.current_dir(base_path);
511 }
512
513 cmd.arg("--standard-json");
514
515 cmd
516 }
517
518 #[cfg(feature = "svm-solc")]
520 pub fn find_or_install(version: &Version) -> Result<Self> {
521 let solc = if let Some(solc) = Self::find_svm_installed_version(version)? {
522 solc
523 } else {
524 Self::blocking_install(version)?
525 };
526
527 Ok(solc)
528 }
529}
530
531#[cfg(feature = "async")]
532impl Solc {
533 pub async fn async_compile_source(&self, path: &Path) -> Result<CompilerOutput> {
535 self.async_compile(&SolcInput::resolve_and_build(
536 Source::async_read_all_from(path, SOLC_EXTENSIONS).await?,
537 Default::default(),
538 ))
539 .await
540 }
541
542 pub async fn async_compile<T: Serialize>(&self, input: &T) -> Result<CompilerOutput> {
545 self.async_compile_as(input).await
546 }
547
548 pub async fn async_compile_as<T: Serialize, D: DeserializeOwned>(
551 &self,
552 input: &T,
553 ) -> Result<D> {
554 let output = self.async_compile_output(input).await?;
555 Ok(serde_json::from_slice(&output)?)
556 }
557
558 pub async fn async_compile_output<T: Serialize>(&self, input: &T) -> Result<Vec<u8>> {
559 use tokio::{io::AsyncWriteExt, process::Command};
560
561 let mut cmd: Command = self.configure_cmd().into();
562 let mut child = cmd.spawn().map_err(self.map_io_err())?;
563 let stdin = child.stdin.as_mut().unwrap();
564
565 let content = serde_json::to_vec(input)?;
566
567 stdin.write_all(&content).await.map_err(self.map_io_err())?;
568 stdin.flush().await.map_err(self.map_io_err())?;
569
570 compile_output(child.wait_with_output().await.map_err(self.map_io_err())?)
571 }
572
573 pub async fn async_version(solc: &Path) -> Result<Version> {
574 let mut cmd = tokio::process::Command::new(solc);
575 cmd.arg("--version").stdin(Stdio::piped()).stderr(Stdio::piped()).stdout(Stdio::piped());
576 debug!(?cmd, "getting version");
577 let output = cmd.output().await.map_err(|e| SolcError::io(e, solc))?;
578 let version = version_from_output(output)?;
579 debug!(%version);
580 Ok(version)
581 }
582
583 pub async fn compile_many<I>(jobs: I, n: usize) -> crate::many::CompiledMany
589 where
590 I: IntoIterator<Item = (Self, SolcInput)>,
591 {
592 use futures_util::stream::StreamExt;
593
594 let outputs = futures_util::stream::iter(
595 jobs.into_iter()
596 .map(|(solc, input)| async { (solc.async_compile(&input).await, solc, input) }),
597 )
598 .buffer_unordered(n)
599 .collect::<Vec<_>>()
600 .await;
601
602 crate::many::CompiledMany::new(outputs)
603 }
604}
605
606fn compile_output(output: Output) -> Result<Vec<u8>> {
607 if output.status.success() {
608 Ok(output.stdout)
609 } else {
610 Err(SolcError::solc_output(&output))
611 }
612}
613
614fn version_from_output(output: Output) -> Result<Version> {
615 if output.status.success() {
616 let stdout = String::from_utf8_lossy(&output.stdout);
617 let version = stdout
618 .lines()
619 .filter(|l| !l.trim().is_empty())
620 .next_back()
621 .ok_or_else(|| SolcError::msg("Version not found in Solc output"))?;
622 Ok(Version::from_str(&version.trim_start_matches("Version: ").replace(".g++", ".gcc"))?)
624 } else {
625 Err(SolcError::solc_output(&output))
626 }
627}
628
629impl AsRef<Path> for Solc {
630 fn as_ref(&self) -> &Path {
631 &self.solc
632 }
633}
634
635#[cfg(test)]
636#[cfg(feature = "svm-solc")]
637mod tests {
638 use super::*;
639 use crate::{resolver::parse::SolData, Artifact};
640
641 #[test]
642 fn test_version_parse() {
643 let req = SolData::parse_version_req(">=0.6.2 <0.8.21").unwrap();
644 let semver_req: VersionReq = ">=0.6.2,<0.8.21".parse().unwrap();
645 assert_eq!(req, semver_req);
646 }
647
648 fn solc() -> Solc {
649 if let Some(solc) = Solc::find_svm_installed_version(&Version::new(0, 8, 18)).unwrap() {
650 solc
651 } else {
652 Solc::blocking_install(&Version::new(0, 8, 18)).unwrap()
653 }
654 }
655
656 #[test]
657 fn solc_version_works() {
658 Solc::version(solc().solc).unwrap();
659 }
660
661 #[test]
662 fn can_parse_version_metadata() {
663 let _version = Version::from_str("0.6.6+commit.6c089d02.Linux.gcc").unwrap();
664 }
665
666 #[cfg(feature = "async")]
667 #[tokio::test(flavor = "multi_thread")]
668 async fn async_solc_version_works() {
669 Solc::async_version(&solc().solc).await.unwrap();
670 }
671
672 #[test]
673 fn solc_compile_works() {
674 let input = include_str!("../../../../../test-data/in/compiler-in-1.json");
675 let input: SolcInput = serde_json::from_str(input).unwrap();
676 let out = solc().compile(&input).unwrap();
677 let other = solc().compile(&serde_json::json!(input)).unwrap();
678 assert_eq!(out, other);
679 }
680
681 #[test]
682 fn solc_metadata_works() {
683 let input = include_str!("../../../../../test-data/in/compiler-in-1.json");
684 let mut input: SolcInput = serde_json::from_str(input).unwrap();
685 input.settings.push_output_selection("metadata");
686 let out = solc().compile(&input).unwrap();
687 for (_, c) in out.split().1.contracts_iter() {
688 assert!(c.metadata.is_some());
689 }
690 }
691
692 #[test]
693 fn can_compile_with_remapped_links() {
694 let input: SolcInput = serde_json::from_str(include_str!(
695 "../../../../../test-data/library-remapping-in.json"
696 ))
697 .unwrap();
698 let out = solc().compile(&input).unwrap();
699 let (_, mut contracts) = out.split();
700 let contract = contracts.remove("LinkTest").unwrap();
701 let bytecode = &contract.get_bytecode().unwrap().object;
702 assert!(!bytecode.is_unlinked());
703 }
704
705 #[test]
706 fn can_compile_with_remapped_links_temp_dir() {
707 let input: SolcInput = serde_json::from_str(include_str!(
708 "../../../../../test-data/library-remapping-in-2.json"
709 ))
710 .unwrap();
711 let out = solc().compile(&input).unwrap();
712 let (_, mut contracts) = out.split();
713 let contract = contracts.remove("LinkTest").unwrap();
714 let bytecode = &contract.get_bytecode().unwrap().object;
715 assert!(!bytecode.is_unlinked());
716 }
717
718 #[cfg(feature = "async")]
719 #[tokio::test(flavor = "multi_thread")]
720 async fn async_solc_compile_works() {
721 let input = include_str!("../../../../../test-data/in/compiler-in-1.json");
722 let input: SolcInput = serde_json::from_str(input).unwrap();
723 let out = solc().async_compile(&input).await.unwrap();
724 let other = solc().async_compile(&serde_json::json!(input)).await.unwrap();
725 assert_eq!(out, other);
726 }
727
728 #[cfg(feature = "async")]
729 #[tokio::test(flavor = "multi_thread")]
730 async fn async_solc_compile_works2() {
731 let input = include_str!("../../../../../test-data/in/compiler-in-2.json");
732 let input: SolcInput = serde_json::from_str(input).unwrap();
733 let out = solc().async_compile(&input).await.unwrap();
734 let other = solc().async_compile(&serde_json::json!(input)).await.unwrap();
735 assert_eq!(out, other);
736 let sync_out = solc().compile(&input).unwrap();
737 assert_eq!(out, sync_out);
738 }
739
740 #[test]
741 fn test_version_req() {
742 let versions = ["=0.1.2", "^0.5.6", ">=0.7.1", ">0.8.0"];
743
744 versions.iter().for_each(|version| {
745 let version_req = SolData::parse_version_req(version).unwrap();
746 assert_eq!(version_req, VersionReq::from_str(version).unwrap());
747 });
748
749 let version_range = ">=0.8.0 <0.9.0";
752 let version_req = SolData::parse_version_req(version_range).unwrap();
753 assert_eq!(version_req, VersionReq::from_str(">=0.8.0,<0.9.0").unwrap());
754 }
755
756 #[test]
757 #[cfg(feature = "full")]
758 fn test_find_installed_version_path() {
759 take_solc_installer_lock!(_lock);
761 let version = Version::new(0, 8, 6);
762 if utils::installed_versions(svm::data_dir())
763 .map(|versions| !versions.contains(&version))
764 .unwrap_or_default()
765 {
766 Solc::blocking_install(&version).unwrap();
767 }
768 drop(_lock);
769 let res = Solc::find_svm_installed_version(&version).unwrap().unwrap();
770 let expected = svm::data_dir().join(version.to_string()).join(format!("solc-{version}"));
771 assert_eq!(res.solc, expected);
772 }
773
774 #[test]
775 #[cfg(feature = "svm-solc")]
776 fn can_install_solc_in_tokio_rt() {
777 let version = Version::from_str("0.8.6").unwrap();
778 let rt = tokio::runtime::Runtime::new().unwrap();
779 let result = rt.block_on(async { Solc::blocking_install(&version) });
780 assert!(result.is_ok());
781 }
782
783 #[test]
784 fn does_not_find_not_installed_version() {
785 let ver = Version::new(1, 1, 1);
786 let res = Solc::find_svm_installed_version(&ver).unwrap();
787 assert!(res.is_none());
788 }
789}