1use crate::{
49 compilers::{Compiler, CompilerVersion, Language, ParsedSource},
50 project::VersionedSources,
51 ArtifactOutput, CompilerSettings, Project, ProjectPathsConfig,
52};
53use core::fmt;
54use foundry_compilers_artifacts::sources::{Source, Sources};
55use foundry_compilers_core::{
56 error::{Result, SolcError},
57 utils::{self, find_case_sensitive_existing_file},
58};
59use parse::SolData;
60use rayon::prelude::*;
61use semver::{Version, VersionReq};
62use std::{
63 collections::{BTreeSet, HashMap, HashSet, VecDeque},
64 io,
65 path::{Path, PathBuf},
66};
67use yansi::{Color, Paint};
68
69pub mod parse;
70mod tree;
71
72pub use parse::SolImportAlias;
73pub use tree::{print, Charset, TreeOptions};
74
75#[derive(Debug)]
77pub struct ResolvedSources<'a, C: Compiler> {
78 pub sources: VersionedSources<'a, C::Language, C::Settings>,
83 pub primary_profiles: HashMap<PathBuf, &'a str>,
91 pub edges: GraphEdges<C::ParsedSource>,
93}
94
95#[derive(Debug)]
100pub struct GraphEdges<D> {
101 edges: Vec<Vec<usize>>,
104 rev_edges: Vec<Vec<usize>>,
106 indices: HashMap<PathBuf, usize>,
108 rev_indices: HashMap<usize, PathBuf>,
110 versions: HashMap<usize, Option<VersionReq>>,
112 data: HashMap<usize, D>,
114 num_input_files: usize,
120 unresolved_imports: HashSet<(PathBuf, PathBuf)>,
122 resolved_solc_include_paths: BTreeSet<PathBuf>,
128}
129
130impl<D> GraphEdges<D> {
131 pub fn num_source_files(&self) -> usize {
133 self.num_input_files
134 }
135
136 pub fn files(&self) -> impl Iterator<Item = usize> + '_ {
138 0..self.edges.len()
139 }
140
141 pub fn source_files(&self) -> impl Iterator<Item = usize> + '_ {
143 0..self.num_input_files
144 }
145
146 pub fn library_files(&self) -> impl Iterator<Item = usize> + '_ {
148 self.files().skip(self.num_input_files)
149 }
150
151 pub fn include_paths(&self) -> &BTreeSet<PathBuf> {
153 &self.resolved_solc_include_paths
154 }
155
156 pub fn unresolved_imports(&self) -> &HashSet<(PathBuf, PathBuf)> {
158 &self.unresolved_imports
159 }
160
161 pub fn imported_nodes(&self, from: usize) -> &[usize] {
163 &self.edges[from]
164 }
165
166 pub fn all_imported_nodes(&self, from: usize) -> impl Iterator<Item = usize> + '_ {
168 NodesIter::new(from, self).skip(1)
169 }
170
171 pub fn imports(&self, file: &Path) -> HashSet<&Path> {
173 if let Some(start) = self.indices.get(file).copied() {
174 NodesIter::new(start, self).skip(1).map(move |idx| &*self.rev_indices[&idx]).collect()
175 } else {
176 HashSet::new()
177 }
178 }
179
180 pub fn importers(&self, file: &Path) -> HashSet<&Path> {
182 if let Some(start) = self.indices.get(file).copied() {
183 self.rev_edges[start].iter().map(move |idx| &*self.rev_indices[idx]).collect()
184 } else {
185 HashSet::new()
186 }
187 }
188
189 pub fn node_id(&self, file: &Path) -> usize {
191 self.indices[file]
192 }
193
194 pub fn node_path(&self, id: usize) -> &Path {
196 &self.rev_indices[&id]
197 }
198
199 pub fn is_input_file(&self, file: &Path) -> bool {
202 if let Some(idx) = self.indices.get(file).copied() {
203 idx < self.num_input_files
204 } else {
205 false
206 }
207 }
208
209 pub fn version_requirement(&self, file: &Path) -> Option<&VersionReq> {
211 self.indices.get(file).and_then(|idx| self.versions.get(idx)).and_then(Option::as_ref)
212 }
213
214 pub fn get_parsed_source(&self, file: &Path) -> Option<&D> {
216 self.indices.get(file).and_then(|idx| self.data.get(idx))
217 }
218}
219
220#[derive(Debug)]
226pub struct Graph<D = SolData> {
227 pub nodes: Vec<Node<D>>,
229 edges: GraphEdges<D>,
231 root: PathBuf,
233}
234
235impl<L: Language, D: ParsedSource<Language = L>> Graph<D> {
236 pub fn print(&self) {
238 self.print_with_options(Default::default())
239 }
240
241 pub fn print_with_options(&self, opts: TreeOptions) {
243 let stdout = io::stdout();
244 let mut out = stdout.lock();
245 tree::print(self, &opts, &mut out).expect("failed to write to stdout.")
246 }
247
248 pub fn imported_nodes(&self, from: usize) -> &[usize] {
250 self.edges.imported_nodes(from)
251 }
252
253 pub fn all_imported_nodes(&self, from: usize) -> impl Iterator<Item = usize> + '_ {
255 self.edges.all_imported_nodes(from)
256 }
257
258 pub(crate) fn has_outgoing_edges(&self, index: usize) -> bool {
260 !self.edges.edges[index].is_empty()
261 }
262
263 pub fn files(&self) -> &HashMap<PathBuf, usize> {
265 &self.edges.indices
266 }
267
268 pub fn is_empty(&self) -> bool {
270 self.nodes.is_empty()
271 }
272
273 pub fn node(&self, index: usize) -> &Node<D> {
279 &self.nodes[index]
280 }
281
282 pub(crate) fn display_node(&self, index: usize) -> DisplayNode<'_, D> {
283 DisplayNode { node: self.node(index), root: &self.root }
284 }
285
286 pub fn node_ids(&self, start: usize) -> impl Iterator<Item = usize> + '_ {
293 NodesIter::new(start, &self.edges)
294 }
295
296 pub fn nodes(&self, start: usize) -> impl Iterator<Item = &Node<D>> + '_ {
298 self.node_ids(start).map(move |idx| self.node(idx))
299 }
300
301 fn split(self) -> (Vec<(PathBuf, Source)>, GraphEdges<D>) {
302 let Self { nodes, mut edges, .. } = self;
303 let mut sources = Vec::new();
306 for (idx, node) in nodes.into_iter().enumerate() {
307 let Node { path, source, data } = node;
308 sources.push((path, source));
309 edges.data.insert(idx, data);
310 }
311
312 (sources, edges)
313 }
314
315 pub fn into_sources(self) -> (Sources, GraphEdges<D>) {
318 let (sources, edges) = self.split();
319 (sources.into_iter().collect(), edges)
320 }
321
322 pub fn input_nodes(&self) -> impl Iterator<Item = &Node<D>> {
326 self.nodes.iter().take(self.edges.num_input_files)
327 }
328
329 pub fn imports(&self, path: &Path) -> HashSet<&Path> {
331 self.edges.imports(path)
332 }
333
334 #[instrument(name = "Graph::resolve_sources", skip_all)]
336 pub fn resolve_sources(
337 paths: &ProjectPathsConfig<D::Language>,
338 sources: Sources,
339 ) -> Result<Self> {
340 fn add_node<D: ParsedSource>(
344 unresolved: &mut VecDeque<(PathBuf, Node<D>)>,
345 index: &mut HashMap<PathBuf, usize>,
346 resolved_imports: &mut Vec<usize>,
347 target: PathBuf,
348 ) -> Result<()> {
349 if let Some(idx) = index.get(&target).copied() {
350 resolved_imports.push(idx);
351 } else {
352 let node = Node::read(&target)?;
354 unresolved.push_back((target.clone(), node));
355 let idx = index.len();
356 index.insert(target, idx);
357 resolved_imports.push(idx);
358 }
359 Ok(())
360 }
361
362 let mut unresolved: VecDeque<_> = sources
365 .0
366 .into_par_iter()
367 .map(|(path, source)| {
368 let data = D::parse(source.as_ref(), &path)?;
369 Ok((path.clone(), Node { path, source, data }))
370 })
371 .collect::<Result<_>>()?;
372
373 let mut index: HashMap<_, _> =
375 unresolved.iter().enumerate().map(|(idx, (p, _))| (p.clone(), idx)).collect();
376
377 let num_input_files = unresolved.len();
378
379 let mut nodes = Vec::with_capacity(unresolved.len());
381 let mut edges = Vec::with_capacity(unresolved.len());
382 let mut rev_edges = Vec::with_capacity(unresolved.len());
383
384 let mut resolved_solc_include_paths = BTreeSet::new();
387 resolved_solc_include_paths.insert(paths.root.clone());
388
389 let mut unresolved_imports = HashSet::new();
392
393 while let Some((path, node)) = unresolved.pop_front() {
396 let mut resolved_imports = Vec::new();
397 let cwd = match path.parent() {
399 Some(inner) => inner,
400 None => continue,
401 };
402
403 for import_path in node.data.resolve_imports(paths, &mut resolved_solc_include_paths)? {
404 if let Some(err) = match paths.resolve_import_and_include_paths(
405 cwd,
406 &import_path,
407 &mut resolved_solc_include_paths,
408 ) {
409 Ok(import) => {
410 add_node(&mut unresolved, &mut index, &mut resolved_imports, import).err()
411 }
412 Err(err) => Some(err),
413 } {
414 unresolved_imports.insert((import_path.to_path_buf(), node.path.clone()));
415 trace!("failed to resolve import component \"{:?}\" for {:?}", err, node.path)
416 }
417 }
418
419 nodes.push(node);
420 edges.push(resolved_imports);
421 rev_edges.push(Vec::new());
423 }
424
425 for (idx, edges) in edges.iter().enumerate() {
427 for &edge in edges.iter() {
428 rev_edges[edge].push(idx);
429 }
430 }
431
432 if !unresolved_imports.is_empty() {
433 crate::report::unresolved_imports(
435 &unresolved_imports
436 .iter()
437 .map(|(i, f)| (i.as_path(), f.as_path()))
438 .collect::<Vec<_>>(),
439 &paths.remappings,
440 );
441 }
442
443 let edges = GraphEdges {
444 edges,
445 rev_edges,
446 rev_indices: index.iter().map(|(k, v)| (*v, k.clone())).collect(),
447 indices: index,
448 num_input_files,
449 versions: nodes
450 .iter()
451 .enumerate()
452 .map(|(idx, node)| (idx, node.data.version_req().cloned()))
453 .collect(),
454 data: Default::default(),
455 unresolved_imports,
456 resolved_solc_include_paths,
457 };
458 Ok(Self { nodes, edges, root: paths.root.clone() })
459 }
460
461 pub fn resolve(paths: &ProjectPathsConfig<D::Language>) -> Result<Self> {
463 Self::resolve_sources(paths, paths.read_input_files()?)
464 }
465}
466
467impl<L: Language, D: ParsedSource<Language = L>> Graph<D> {
468 pub fn into_sources_by_version<C, T>(
474 self,
475 project: &Project<C, T>,
476 ) -> Result<ResolvedSources<'_, C>>
477 where
478 T: ArtifactOutput<CompilerContract = C::CompilerContract>,
479 C: Compiler<ParsedSource = D, Language = L>,
480 {
481 fn insert_imports(
489 idx: usize,
490 all_nodes: &mut HashMap<usize, (PathBuf, Source)>,
491 sources: &mut Sources,
492 edges: &[Vec<usize>],
493 processed_sources: &mut HashSet<usize>,
494 ) {
495 for dep in edges[idx].iter().copied() {
497 if !processed_sources.insert(dep) {
500 continue;
501 }
502
503 if let Some((path, source)) = all_nodes.get(&dep).cloned() {
505 sources.insert(path, source);
506 insert_imports(dep, all_nodes, sources, edges, processed_sources);
507 }
508 }
509 }
510
511 let versioned_nodes = self.get_input_node_versions(project)?;
512 let versioned_nodes = self.resolve_settings(project, versioned_nodes)?;
513 let (nodes, edges) = self.split();
514
515 let mut all_nodes = nodes.into_iter().enumerate().collect::<HashMap<_, _>>();
516
517 let mut resulted_sources = HashMap::new();
518 let mut default_profiles = HashMap::new();
519
520 let profiles = project.settings_profiles().collect::<Vec<_>>();
521
522 for (language, versioned_nodes) in versioned_nodes {
524 let mut versioned_sources = Vec::with_capacity(versioned_nodes.len());
525
526 for (version, profile_to_nodes) in versioned_nodes {
527 for (profile_idx, input_node_indixies) in profile_to_nodes {
528 let mut sources = Sources::new();
529
530 let mut processed_sources = input_node_indixies.iter().copied().collect();
532
533 for idx in input_node_indixies {
535 let (path, source) =
538 all_nodes.get(&idx).cloned().expect("node is preset. qed");
539
540 default_profiles.insert(path.clone(), profiles[profile_idx].0);
541 sources.insert(path, source);
542 insert_imports(
543 idx,
544 &mut all_nodes,
545 &mut sources,
546 &edges.edges,
547 &mut processed_sources,
548 );
549 }
550 versioned_sources.push((version.clone(), sources, profiles[profile_idx]));
551 }
552 }
553
554 resulted_sources.insert(language, versioned_sources);
555 }
556
557 Ok(ResolvedSources { sources: resulted_sources, primary_profiles: default_profiles, edges })
558 }
559
560 fn format_imports_list<
569 C: Compiler,
570 T: ArtifactOutput<CompilerContract = C::CompilerContract>,
571 W: std::fmt::Write,
572 >(
573 &self,
574 idx: usize,
575 incompatible: HashSet<usize>,
576 project: &Project<C, T>,
577 f: &mut W,
578 ) -> std::result::Result<(), std::fmt::Error> {
579 let format_node = |idx, f: &mut W| {
580 let node = self.node(idx);
581 let color = if incompatible.contains(&idx) { Color::Red } else { Color::White };
582
583 let mut line = utils::source_name(&node.path, &self.root).display().to_string();
584 if let Some(req) = self.version_requirement(idx, project) {
585 line.push_str(&format!(" {req}"));
586 }
587
588 write!(f, "{}", line.paint(color))
589 };
590 format_node(idx, f)?;
591 write!(f, " imports:")?;
592 for dep in self.node_ids(idx).skip(1) {
593 write!(f, "\n ")?;
594 format_node(dep, f)?;
595 }
596
597 Ok(())
598 }
599
600 fn version_requirement<
602 C: Compiler,
603 T: ArtifactOutput<CompilerContract = C::CompilerContract>,
604 >(
605 &self,
606 idx: usize,
607 project: &Project<C, T>,
608 ) -> Option<VersionReq> {
609 let node = self.node(idx);
610 let parsed_req = node.data.version_req();
611 let other_req = project.restrictions.get(&node.path).and_then(|r| r.version.as_ref());
612
613 match (parsed_req, other_req) {
614 (Some(parsed_req), Some(other_req)) => {
615 let mut req = parsed_req.clone();
616 req.comparators.extend(other_req.comparators.clone());
617 Some(req)
618 }
619 (Some(parsed_req), None) => Some(parsed_req.clone()),
620 (None, Some(other_req)) => Some(other_req.clone()),
621 _ => None,
622 }
623 }
624
625 fn check_available_version<
630 C: Compiler,
631 T: ArtifactOutput<CompilerContract = C::CompilerContract>,
632 >(
633 &self,
634 idx: usize,
635 all_versions: &[&CompilerVersion],
636 project: &Project<C, T>,
637 ) -> std::result::Result<(), SourceVersionError> {
638 let Some(req) = self.version_requirement(idx, project) else { return Ok(()) };
639
640 if !all_versions.iter().any(|v| req.matches(v.as_ref())) {
641 return if project.offline {
642 Err(SourceVersionError::NoMatchingVersionOffline(req))
643 } else {
644 Err(SourceVersionError::NoMatchingVersion(req))
645 };
646 }
647
648 Ok(())
649 }
650
651 fn retain_compatible_versions<
654 C: Compiler,
655 T: ArtifactOutput<CompilerContract = C::CompilerContract>,
656 >(
657 &self,
658 idx: usize,
659 candidates: &mut Vec<&CompilerVersion>,
660 project: &Project<C, T>,
661 ) -> Result<(), String> {
662 let mut all_versions = candidates.clone();
663
664 let nodes: Vec<_> = self.node_ids(idx).collect();
665 let mut failed_node_idx = None;
666 for node in nodes.iter() {
667 if let Some(req) = self.version_requirement(*node, project) {
668 candidates.retain(|v| req.matches(v.as_ref()));
669
670 if candidates.is_empty() {
671 failed_node_idx = Some(*node);
672 break;
673 }
674 }
675 }
676
677 let Some(failed_node_idx) = failed_node_idx else {
678 return Ok(());
680 };
681
682 let failed_node = self.node(failed_node_idx);
686
687 if let Err(version_err) =
688 self.check_available_version(failed_node_idx, &all_versions, project)
689 {
690 let f = utils::source_name(&failed_node.path, &self.root).display();
692 return Err(format!("Encountered invalid solc version in {f}: {version_err}"));
693 } else {
694 if let Some(req) = self.version_requirement(failed_node_idx, project) {
699 all_versions.retain(|v| req.matches(v.as_ref()));
700 }
701
702 for node in &nodes {
704 if self.check_available_version(*node, &all_versions, project).is_err() {
705 let mut msg = "Found incompatible versions:\n".white().to_string();
706
707 self.format_imports_list(
708 idx,
709 [*node, failed_node_idx].into(),
710 project,
711 &mut msg,
712 )
713 .unwrap();
714 return Err(msg);
715 }
716 }
717 }
718
719 let mut msg = "Found incompatible versions:\n".white().to_string();
720 self.format_imports_list(idx, nodes.into_iter().collect(), project, &mut msg).unwrap();
721 Err(msg)
722 }
723
724 fn retain_compatible_profiles<
726 C: Compiler,
727 T: ArtifactOutput<CompilerContract = C::CompilerContract>,
728 >(
729 &self,
730 idx: usize,
731 project: &Project<C, T>,
732 candidates: &mut Vec<(usize, (&str, &C::Settings))>,
733 ) -> Result<(), String> {
734 let mut all_profiles = candidates.clone();
735
736 let nodes: Vec<_> = self.node_ids(idx).collect();
737 let mut failed_node_idx = None;
738 for node in nodes.iter() {
739 if let Some(req) = project.restrictions.get(&self.node(*node).path) {
740 candidates.retain(|(_, (_, settings))| settings.satisfies_restrictions(&**req));
741 if candidates.is_empty() {
742 failed_node_idx = Some(*node);
743 break;
744 }
745 }
746 }
747
748 let Some(failed_node_idx) = failed_node_idx else {
749 return Ok(());
751 };
752
753 let failed_node = self.node(failed_node_idx);
754
755 if let Some(req) = project.restrictions.get(&failed_node.path) {
757 all_profiles.retain(|(_, (_, settings))| settings.satisfies_restrictions(&**req));
758 }
759
760 if all_profiles.is_empty() {
761 let f = utils::source_name(&failed_node.path, &self.root).display();
762 return Err(format!("Missing profile satisfying settings restrictions for {f}"));
763 }
764
765 for node in &nodes {
767 if let Some(req) = project.restrictions.get(&self.node(*node).path) {
768 if !all_profiles
769 .iter()
770 .any(|(_, (_, settings))| settings.satisfies_restrictions(&**req))
771 {
772 let mut msg = "Found incompatible settings restrictions:\n".white().to_string();
773
774 self.format_imports_list(
775 idx,
776 [*node, failed_node_idx].into(),
777 project,
778 &mut msg,
779 )
780 .unwrap();
781 return Err(msg);
782 }
783 }
784 }
785
786 let mut msg = "Found incompatible settings restrictions:\n".white().to_string();
787 self.format_imports_list(idx, nodes.into_iter().collect(), project, &mut msg).unwrap();
788 Err(msg)
789 }
790
791 fn input_nodes_by_language(&self) -> HashMap<D::Language, Vec<usize>> {
792 let mut nodes = HashMap::new();
793
794 for idx in 0..self.edges.num_input_files {
795 nodes.entry(self.nodes[idx].data.language()).or_insert_with(Vec::new).push(idx);
796 }
797
798 nodes
799 }
800
801 fn get_input_node_versions<
812 C: Compiler<Language = L>,
813 T: ArtifactOutput<CompilerContract = C::CompilerContract>,
814 >(
815 &self,
816 project: &Project<C, T>,
817 ) -> Result<HashMap<L, HashMap<Version, Vec<usize>>>> {
818 trace!("resolving input node versions");
819
820 let mut resulted_nodes = HashMap::new();
821
822 for (language, nodes) in self.input_nodes_by_language() {
823 let mut errors = Vec::new();
827
828 let all_versions = if project.offline {
830 project
831 .compiler
832 .available_versions(&language)
833 .into_iter()
834 .filter(|v| v.is_installed())
835 .collect()
836 } else {
837 project.compiler.available_versions(&language)
838 };
839
840 if all_versions.is_empty() && !nodes.is_empty() {
841 return Err(SolcError::msg(format!(
842 "Found {language} sources, but no compiler versions are available for it"
843 )));
844 }
845
846 let mut versioned_nodes = HashMap::new();
848
849 let mut all_candidates = Vec::with_capacity(self.edges.num_input_files);
851 for idx in nodes {
853 let mut candidates = all_versions.iter().collect::<Vec<_>>();
854 if let Err(err) = self.retain_compatible_versions(idx, &mut candidates, project) {
857 errors.push(err);
858 } else {
859 let candidate =
862 if let Some(pos) = candidates.iter().rposition(|v| v.is_installed()) {
863 candidates[pos]
864 } else {
865 candidates.last().expect("not empty; qed.")
866 }
867 .clone();
868
869 all_candidates.push((idx, candidates.into_iter().collect::<HashSet<_>>()));
871
872 versioned_nodes
873 .entry(candidate)
874 .or_insert_with(|| Vec::with_capacity(1))
875 .push(idx);
876 }
877 }
878
879 if versioned_nodes.len() > 1 {
882 versioned_nodes = Self::resolve_multiple_versions(all_candidates);
883 }
884
885 if versioned_nodes.len() == 1 {
886 trace!(
887 "found exact solc version for all sources \"{}\"",
888 versioned_nodes.keys().next().unwrap()
889 );
890 }
891
892 if errors.is_empty() {
893 trace!("resolved {} versions {:?}", versioned_nodes.len(), versioned_nodes.keys());
894 resulted_nodes.insert(
895 language,
896 versioned_nodes
897 .into_iter()
898 .map(|(v, nodes)| (Version::from(v), nodes))
899 .collect(),
900 );
901 } else {
902 let s = errors.join("\n");
903 debug!("failed to resolve versions: {s}");
904 return Err(SolcError::msg(s));
905 }
906 }
907
908 Ok(resulted_nodes)
909 }
910
911 #[allow(clippy::complexity)]
912 fn resolve_settings<
913 C: Compiler<Language = L>,
914 T: ArtifactOutput<CompilerContract = C::CompilerContract>,
915 >(
916 &self,
917 project: &Project<C, T>,
918 input_nodes_versions: HashMap<L, HashMap<Version, Vec<usize>>>,
919 ) -> Result<HashMap<L, HashMap<Version, HashMap<usize, Vec<usize>>>>> {
920 let mut resulted_sources = HashMap::new();
921 let mut errors = Vec::new();
922 for (language, versions) in input_nodes_versions {
923 let mut versioned_sources = HashMap::new();
924 for (version, nodes) in versions {
925 let mut profile_to_nodes = HashMap::new();
926 for idx in nodes {
927 let mut profile_candidates =
928 project.settings_profiles().enumerate().collect::<Vec<_>>();
929 if let Err(err) =
930 self.retain_compatible_profiles(idx, project, &mut profile_candidates)
931 {
932 errors.push(err);
933 } else {
934 let (profile_idx, _) = profile_candidates.first().expect("exists");
935 profile_to_nodes.entry(*profile_idx).or_insert_with(Vec::new).push(idx);
936 }
937 }
938 versioned_sources.insert(version, profile_to_nodes);
939 }
940 resulted_sources.insert(language, versioned_sources);
941 }
942
943 if errors.is_empty() {
944 Ok(resulted_sources)
945 } else {
946 let s = errors.join("\n");
947 debug!("failed to resolve settings: {s}");
948 Err(SolcError::msg(s))
949 }
950 }
951
952 fn resolve_multiple_versions(
958 all_candidates: Vec<(usize, HashSet<&CompilerVersion>)>,
959 ) -> HashMap<CompilerVersion, Vec<usize>> {
960 fn intersection<'a>(
962 mut sets: Vec<&HashSet<&'a CompilerVersion>>,
963 ) -> Vec<&'a CompilerVersion> {
964 if sets.is_empty() {
965 return Vec::new();
966 }
967
968 let mut result = sets.pop().cloned().expect("not empty; qed.");
969 if !sets.is_empty() {
970 result.retain(|item| sets.iter().all(|set| set.contains(item)));
971 }
972
973 let mut v = result.into_iter().collect::<Vec<_>>();
974 v.sort_unstable();
975 v
976 }
977
978 fn remove_candidate(candidates: &mut Vec<&CompilerVersion>) -> CompilerVersion {
982 debug_assert!(!candidates.is_empty());
983
984 if let Some(pos) = candidates.iter().rposition(|v| v.is_installed()) {
985 candidates.remove(pos)
986 } else {
987 candidates.pop().expect("not empty; qed.")
988 }
989 .clone()
990 }
991
992 let all_sets = all_candidates.iter().map(|(_, versions)| versions).collect();
993
994 let mut intersection = intersection(all_sets);
996 if !intersection.is_empty() {
997 let exact_version = remove_candidate(&mut intersection);
998 let all_nodes = all_candidates.into_iter().map(|(node, _)| node).collect();
999 trace!("resolved solc version compatible with all sources \"{}\"", exact_version);
1000 return HashMap::from([(exact_version, all_nodes)]);
1001 }
1002
1003 let mut versioned_nodes: HashMap<_, _> = HashMap::new();
1005
1006 for (node, versions) in all_candidates {
1009 let mut versions = versions.into_iter().collect::<Vec<_>>();
1011 versions.sort_unstable();
1012
1013 let candidate = if let Some(idx) =
1014 versions.iter().rposition(|v| versioned_nodes.contains_key(*v))
1015 {
1016 versions.remove(idx).clone()
1018 } else {
1019 remove_candidate(&mut versions)
1021 };
1022
1023 versioned_nodes.entry(candidate).or_insert_with(|| Vec::with_capacity(1)).push(node);
1024 }
1025
1026 trace!(
1027 "no solc version can satisfy all source files, resolved multiple versions \"{:?}\"",
1028 versioned_nodes.keys()
1029 );
1030
1031 versioned_nodes
1032 }
1033}
1034
1035#[derive(Debug)]
1037pub struct NodesIter<'a, D> {
1038 stack: VecDeque<usize>,
1040 visited: HashSet<usize>,
1041 graph: &'a GraphEdges<D>,
1042}
1043
1044impl<'a, D> NodesIter<'a, D> {
1045 fn new(start: usize, graph: &'a GraphEdges<D>) -> Self {
1046 Self { stack: VecDeque::from([start]), visited: HashSet::new(), graph }
1047 }
1048}
1049
1050impl<D> Iterator for NodesIter<'_, D> {
1051 type Item = usize;
1052 fn next(&mut self) -> Option<Self::Item> {
1053 let node = self.stack.pop_front()?;
1054
1055 if self.visited.insert(node) {
1056 self.stack.extend(self.graph.imported_nodes(node).iter().copied());
1058 }
1059 Some(node)
1060 }
1061}
1062
1063#[derive(Debug)]
1064pub struct Node<D> {
1065 path: PathBuf,
1067 source: Source,
1069 pub data: D,
1071}
1072
1073impl<D: ParsedSource> Node<D> {
1074 pub fn read(file: &Path) -> Result<Self> {
1076 let source = Source::read(file).map_err(|err| {
1077 let exists = err.path().exists();
1078 if !exists && err.path().is_symlink() {
1079 SolcError::ResolveBadSymlink(err)
1080 } else {
1081 if !exists {
1083 if let Some(existing_file) = find_case_sensitive_existing_file(file) {
1085 SolcError::ResolveCaseSensitiveFileName { error: err, existing_file }
1086 } else {
1087 SolcError::Resolve(err)
1088 }
1089 } else {
1090 SolcError::Resolve(err)
1091 }
1092 }
1093 })?;
1094 let data = D::parse(source.as_ref(), file)?;
1095 Ok(Self { path: file.to_path_buf(), source, data })
1096 }
1097
1098 pub fn path(&self) -> &Path {
1100 &self.path
1101 }
1102
1103 pub fn content(&self) -> &str {
1105 &self.source.content
1106 }
1107
1108 pub fn unpack(&self) -> (&Path, &Source) {
1109 (&self.path, &self.source)
1110 }
1111}
1112
1113pub(crate) struct DisplayNode<'a, D> {
1115 node: &'a Node<D>,
1116 root: &'a PathBuf,
1117}
1118
1119impl<D: ParsedSource> fmt::Display for DisplayNode<'_, D> {
1120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1121 let path = utils::source_name(&self.node.path, self.root);
1122 write!(f, "{}", path.display())?;
1123 if let Some(v) = self.node.data.version_req() {
1124 write!(f, " {v}")?;
1125 }
1126 Ok(())
1127 }
1128}
1129
1130#[derive(Debug, thiserror::Error)]
1132#[allow(dead_code)]
1133enum SourceVersionError {
1134 #[error("Failed to parse solidity version {0}: {1}")]
1135 InvalidVersion(String, SolcError),
1136 #[error("No solc version exists that matches the version requirement: {0}")]
1137 NoMatchingVersion(VersionReq),
1138 #[error("No solc version installed that matches the version requirement: {0}")]
1139 NoMatchingVersionOffline(VersionReq),
1140}
1141
1142#[cfg(test)]
1143mod tests {
1144 use super::*;
1145
1146 #[test]
1147 fn can_resolve_hardhat_dependency_graph() {
1148 let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test-data/hardhat-sample");
1149 let paths = ProjectPathsConfig::hardhat(&root).unwrap();
1150
1151 let graph = Graph::<SolData>::resolve(&paths).unwrap();
1152
1153 assert_eq!(graph.edges.num_input_files, 1);
1154 assert_eq!(graph.files().len(), 2);
1155
1156 assert_eq!(
1157 graph.files().clone(),
1158 HashMap::from([
1159 (paths.sources.join("Greeter.sol"), 0),
1160 (paths.root.join("node_modules/hardhat/console.sol"), 1),
1161 ])
1162 );
1163 }
1164
1165 #[test]
1166 fn can_resolve_dapp_dependency_graph() {
1167 let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test-data/dapp-sample");
1168 let paths = ProjectPathsConfig::dapptools(&root).unwrap();
1169
1170 let graph = Graph::<SolData>::resolve(&paths).unwrap();
1171
1172 assert_eq!(graph.edges.num_input_files, 2);
1173 assert_eq!(graph.files().len(), 3);
1174 assert_eq!(
1175 graph.files().clone(),
1176 HashMap::from([
1177 (paths.sources.join("Dapp.sol"), 0),
1178 (paths.sources.join("Dapp.t.sol"), 1),
1179 (paths.root.join("lib/ds-test/src/test.sol"), 2),
1180 ])
1181 );
1182
1183 let dapp_test = graph.node(1);
1184 assert_eq!(dapp_test.path, paths.sources.join("Dapp.t.sol"));
1185 assert_eq!(
1186 dapp_test.data.imports.iter().map(|i| i.data().path()).collect::<Vec<&Path>>(),
1187 vec![Path::new("ds-test/test.sol"), Path::new("./Dapp.sol")]
1188 );
1189 assert_eq!(graph.imported_nodes(1).to_vec(), vec![2, 0]);
1190 }
1191
1192 #[test]
1193 #[cfg(not(target_os = "windows"))]
1194 fn can_print_dapp_sample_graph() {
1195 let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test-data/dapp-sample");
1196 let paths = ProjectPathsConfig::dapptools(&root).unwrap();
1197 let graph = Graph::<SolData>::resolve(&paths).unwrap();
1198 let mut out = Vec::<u8>::new();
1199 tree::print(&graph, &Default::default(), &mut out).unwrap();
1200
1201 assert_eq!(
1202 "
1203src/Dapp.sol >=0.6.6
1204src/Dapp.t.sol >=0.6.6
1205├── lib/ds-test/src/test.sol >=0.4.23
1206└── src/Dapp.sol >=0.6.6
1207"
1208 .trim_start()
1209 .as_bytes()
1210 .to_vec(),
1211 out
1212 );
1213 }
1214
1215 #[test]
1216 #[cfg(not(target_os = "windows"))]
1217 fn can_print_hardhat_sample_graph() {
1218 let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test-data/hardhat-sample");
1219 let paths = ProjectPathsConfig::hardhat(&root).unwrap();
1220 let graph = Graph::<SolData>::resolve(&paths).unwrap();
1221 let mut out = Vec::<u8>::new();
1222 tree::print(&graph, &Default::default(), &mut out).unwrap();
1223 assert_eq!(
1224 "contracts/Greeter.sol >=0.6.0
1225└── node_modules/hardhat/console.sol >=0.4.22, <0.9.0
1226",
1227 String::from_utf8(out).unwrap()
1228 );
1229 }
1230
1231 #[test]
1232 #[cfg(feature = "svm-solc")]
1233 fn test_print_unresolved() {
1234 use crate::{solc::SolcCompiler, ProjectBuilder};
1235
1236 let root =
1237 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test-data/incompatible-pragmas");
1238 let paths = ProjectPathsConfig::dapptools(&root).unwrap();
1239 let graph = Graph::<SolData>::resolve(&paths).unwrap();
1240 let Err(SolcError::Message(err)) = graph.get_input_node_versions(
1241 &ProjectBuilder::<SolcCompiler>::default()
1242 .paths(paths)
1243 .build(SolcCompiler::AutoDetect)
1244 .unwrap(),
1245 ) else {
1246 panic!("expected error");
1247 };
1248
1249 snapbox::assert_data_eq!(
1250 err,
1251 snapbox::str![[r#"
1252[37mFound incompatible versions:
1253[0m[31msrc/A.sol =0.8.25[0m imports:
1254 [37msrc/B.sol[0m
1255 [31msrc/C.sol =0.7.0[0m
1256"#]]
1257 );
1258 }
1259
1260 #[cfg(target_os = "linux")]
1261 #[test]
1262 fn can_read_different_case() {
1263 use crate::resolver::parse::SolData;
1264 use std::fs::{self, create_dir_all};
1265 use utils::tempdir;
1266
1267 let tmp_dir = tempdir("out").unwrap();
1268 let path = tmp_dir.path().join("forge-std");
1269 create_dir_all(&path).unwrap();
1270 let existing = path.join("Test.sol");
1271 let non_existing = path.join("test.sol");
1272 fs::write(
1273 existing,
1274 "
1275pragma solidity ^0.8.10;
1276contract A {}
1277 ",
1278 )
1279 .unwrap();
1280
1281 assert!(!non_existing.exists());
1282
1283 let found = crate::resolver::Node::<SolData>::read(&non_existing).unwrap_err();
1284 matches!(found, SolcError::ResolveCaseSensitiveFileName { .. });
1285 }
1286}