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