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 solc = svm::version_binary(&version.to_string());
219 if !solc.is_file() {
220 return Ok(None);
221 }
222 Ok(Some(Self::new_with_version(&solc, version.clone())))
223 }
224
225 #[cfg(feature = "svm-solc")]
231 pub fn svm_home() -> Option<PathBuf> {
232 Some(svm::data_dir().to_path_buf())
233 }
234
235 #[cfg(feature = "svm-solc")]
241 pub fn svm_global_version() -> Option<Version> {
242 svm::get_global_version().ok().flatten()
243 }
244
245 #[cfg(feature = "svm-solc")]
247 pub fn installed_versions() -> Vec<Version> {
248 svm::installed_versions().unwrap_or_default()
249 }
250
251 #[cfg(feature = "svm-solc")]
253 pub fn released_versions() -> Vec<Version> {
254 RELEASES.1.clone()
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 trace!("blocking installing solc version \"{}\"", version);
297 crate::report::solc_installation_start(version);
298 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 #[cfg(feature = "svm-solc")]
316 #[instrument(name = "Solc::verify_checksum", skip_all)]
317 pub fn verify_checksum(&self) -> Result<()> {
318 let version = self.version_short();
319 let mut version_path = svm::version_path(version.to_string().as_str());
320 version_path.push(format!("solc-{}", version.to_string().as_str()));
321 trace!(target:"solc", "reading solc binary for checksum {:?}", version_path);
322 let content =
323 std::fs::read(&version_path).map_err(|err| SolcError::io(err, version_path.clone()))?;
324
325 if !RELEASES.2 {
326 return Ok(());
329 }
330
331 #[cfg(windows)]
332 {
333 const V0_7_2: Version = Version::new(0, 7, 2);
336 if version < V0_7_2 {
337 return Ok(());
338 }
339 }
340
341 use sha2::Digest;
342 let mut hasher = sha2::Sha256::new();
343 hasher.update(content);
344 let checksum_calc = &hasher.finalize()[..];
345
346 let checksum_found = &RELEASES
347 .0
348 .get_checksum(&version)
349 .ok_or_else(|| SolcError::ChecksumNotFound { version: version.clone() })?;
350
351 if checksum_calc == checksum_found {
352 Ok(())
353 } else {
354 use alloy_primitives::hex;
355 let expected = hex::encode(checksum_found);
356 let detected = hex::encode(checksum_calc);
357 warn!(target: "solc", "checksum mismatch for {:?}, expected {}, but found {} for file {:?}", version, expected, detected, version_path);
358 Err(SolcError::ChecksumMismatch { version, expected, detected, file: version_path })
359 }
360 }
361
362 pub fn compile_source(&self, path: &Path) -> Result<CompilerOutput> {
364 let mut res: CompilerOutput = Default::default();
365 for input in
366 SolcInput::resolve_and_build(Source::read_sol_yul_from(path)?, Default::default())
367 {
368 let input = input.sanitized(&self.version);
369 let output = self.compile(&input)?;
370 res.merge(output)
371 }
372
373 Ok(res)
374 }
375
376 pub fn compile_exact(&self, input: &SolcInput) -> Result<CompilerOutput> {
384 let mut out = self.compile(input)?;
385 out.retain_files(input.sources.keys().map(|p| p.as_path()));
386 Ok(out)
387 }
388
389 pub fn compile<T: Serialize>(&self, input: &T) -> Result<CompilerOutput> {
409 self.compile_as(input)
410 }
411
412 #[instrument(name = "Solc::compile", skip_all)]
414 pub fn compile_as<T: Serialize, D: DeserializeOwned>(&self, input: &T) -> Result<D> {
415 let output = self.compile_output(input)?;
416
417 let output = std::str::from_utf8(&output).map_err(|_| SolcError::InvalidUtf8)?;
419
420 Ok(serde_json::from_str(output)?)
421 }
422
423 #[instrument(name = "Solc::compile_raw", skip_all)]
425 pub fn compile_output<T: Serialize>(&self, input: &T) -> Result<Vec<u8>> {
426 let mut cmd = self.configure_cmd();
427
428 trace!(input=%serde_json::to_string(input).unwrap_or_else(|e| e.to_string()));
429 debug!(?cmd, "compiling");
430
431 let mut child = cmd.spawn().map_err(self.map_io_err())?;
432 debug!("spawned");
433
434 {
435 let mut stdin = io::BufWriter::new(child.stdin.take().unwrap());
436 serde_json::to_writer(&mut stdin, input)?;
437 stdin.flush().map_err(self.map_io_err())?;
438 }
439 debug!("wrote JSON input to stdin");
440
441 let output = child.wait_with_output().map_err(self.map_io_err())?;
442 debug!(%output.status, output.stderr = ?String::from_utf8_lossy(&output.stderr), "finished");
443
444 compile_output(output)
445 }
446
447 pub fn version_short(&self) -> Version {
449 Version::new(self.version.major, self.version.minor, self.version.patch)
450 }
451
452 pub fn version(solc: impl Into<PathBuf>) -> Result<Version> {
454 Self::version_with_args(solc, &[])
455 }
456
457 pub fn version_with_args(solc: impl Into<PathBuf>, args: &[String]) -> Result<Version> {
459 crate::cache_version(solc.into(), args, |solc| Self::version_impl(solc, args))
460 }
461
462 fn version_impl(solc: &Path, args: &[String]) -> Result<Version> {
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 fn map_io_err(&self) -> impl FnOnce(std::io::Error) -> SolcError + '_ {
478 move |err| SolcError::io(err, &self.solc)
479 }
480
481 pub fn configure_cmd(&self) -> Command {
485 let mut cmd = Command::new(&self.solc);
486 cmd.stdin(Stdio::piped()).stderr(Stdio::piped()).stdout(Stdio::piped());
487 cmd.args(&self.extra_args);
488
489 if !self.allow_paths.is_empty() {
490 cmd.arg("--allow-paths");
491 cmd.arg(self.allow_paths.iter().map(|p| p.display()).join(","));
492 }
493 if let Some(base_path) = &self.base_path {
494 if SUPPORTS_BASE_PATH.matches(&self.version) {
495 if SUPPORTS_INCLUDE_PATH.matches(&self.version) {
496 for path in
500 self.include_paths.iter().filter(|p| p.as_path() != base_path.as_path())
501 {
502 cmd.arg("--include-path").arg(path);
503 }
504 }
505
506 cmd.arg("--base-path").arg(base_path);
507 }
508
509 cmd.current_dir(base_path);
510 }
511
512 cmd.arg("--standard-json");
513
514 cmd
515 }
516
517 #[cfg(feature = "svm-solc")]
519 pub fn find_or_install(version: &Version) -> Result<Self> {
520 let solc = if let Some(solc) = Self::find_svm_installed_version(version)? {
521 solc
522 } else {
523 Self::blocking_install(version)?
524 };
525
526 Ok(solc)
527 }
528}
529
530#[cfg(feature = "async")]
531impl Solc {
532 pub async fn async_compile_source(&self, path: &Path) -> Result<CompilerOutput> {
534 self.async_compile(&SolcInput::resolve_and_build(
535 Source::async_read_all_from(path, SOLC_EXTENSIONS).await?,
536 Default::default(),
537 ))
538 .await
539 }
540
541 pub async fn async_compile<T: Serialize>(&self, input: &T) -> Result<CompilerOutput> {
544 self.async_compile_as(input).await
545 }
546
547 pub async fn async_compile_as<T: Serialize, D: DeserializeOwned>(
550 &self,
551 input: &T,
552 ) -> Result<D> {
553 let output = self.async_compile_output(input).await?;
554 Ok(serde_json::from_slice(&output)?)
555 }
556
557 pub async fn async_compile_output<T: Serialize>(&self, input: &T) -> Result<Vec<u8>> {
558 use tokio::{io::AsyncWriteExt, process::Command};
559
560 let mut cmd: Command = self.configure_cmd().into();
561 let mut child = cmd.spawn().map_err(self.map_io_err())?;
562 let stdin = child.stdin.as_mut().unwrap();
563
564 let content = serde_json::to_vec(input)?;
565
566 stdin.write_all(&content).await.map_err(self.map_io_err())?;
567 stdin.flush().await.map_err(self.map_io_err())?;
568
569 compile_output(child.wait_with_output().await.map_err(self.map_io_err())?)
570 }
571
572 pub async fn async_version(solc: &Path) -> Result<Version> {
573 let mut cmd = tokio::process::Command::new(solc);
574 cmd.arg("--version").stdin(Stdio::piped()).stderr(Stdio::piped()).stdout(Stdio::piped());
575 debug!(?cmd, "getting version");
576 let output = cmd.output().await.map_err(|e| SolcError::io(e, solc))?;
577 let version = version_from_output(output)?;
578 debug!(%version);
579 Ok(version)
580 }
581
582 pub async fn compile_many<I>(jobs: I, n: usize) -> crate::many::CompiledMany
588 where
589 I: IntoIterator<Item = (Self, SolcInput)>,
590 {
591 use futures_util::stream::StreamExt;
592
593 let outputs = futures_util::stream::iter(
594 jobs.into_iter()
595 .map(|(solc, input)| async { (solc.async_compile(&input).await, solc, input) }),
596 )
597 .buffer_unordered(n)
598 .collect::<Vec<_>>()
599 .await;
600
601 crate::many::CompiledMany::new(outputs)
602 }
603}
604
605fn compile_output(output: Output) -> Result<Vec<u8>> {
606 if output.status.success() {
607 Ok(output.stdout)
608 } else {
609 Err(SolcError::solc_output(&output))
610 }
611}
612
613fn version_from_output(output: Output) -> Result<Version> {
614 if output.status.success() {
615 let stdout = String::from_utf8_lossy(&output.stdout);
616 let version = stdout
617 .lines()
618 .rfind(|l| !l.trim().is_empty())
619 .ok_or_else(|| SolcError::msg("Version not found in Solc output"))?;
620 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 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 take_solc_installer_lock!(_lock);
759 let version = Version::new(0, 8, 6);
760 if svm::installed_versions()
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}