1use crate::manifest::GenericManifestFile;
2use crate::{
3 lock::Lock,
4 manifest::{Dependency, ManifestFile, MemberManifestFiles, PackageManifestFile},
5 source::{self, IPFSNode, Source},
6 BuildProfile,
7};
8use anyhow::{anyhow, bail, Context, Error, Result};
9use byte_unit::{Byte, UnitType};
10use forc_tracing::{println_action_green, println_warning};
11use forc_util::{
12 default_output_directory, find_file_name, kebab_to_snake_case, print_compiling, print_infos,
13 print_on_failure, print_warnings,
14};
15use petgraph::{
16 self, dot,
17 visit::{Bfs, Dfs, EdgeRef, Walker},
18 Directed, Direction,
19};
20use serde::{Deserialize, Serialize};
21use std::{
22 collections::{hash_map, BTreeSet, HashMap, HashSet},
23 fmt,
24 fs::{self, File},
25 hash::{Hash, Hasher},
26 io::Write,
27 path::{Path, PathBuf},
28 str::FromStr,
29 sync::{atomic::AtomicBool, Arc},
30};
31use sway_core::transform::AttributeArg;
32pub use sway_core::Programs;
33use sway_core::{
34 abi_generation::{
35 evm_abi,
36 fuel_abi::{self, AbiContext},
37 },
38 asm_generation::ProgramABI,
39 decl_engine::DeclRefFunction,
40 fuel_prelude::{
41 fuel_crypto,
42 fuel_tx::{self, Contract, ContractId, StorageSlot},
43 },
44 language::parsed::TreeType,
45 semantic_analysis::namespace,
46 source_map::SourceMap,
47 write_dwarf, BuildTarget, Engines, FinalizedEntry, LspConfig,
48};
49use sway_core::{namespace::Package, Observer};
50use sway_core::{set_bytecode_configurables_offset, DbgGeneration, IrCli, PrintAsm};
51use sway_error::{error::CompileError, handler::Handler, warning::CompileWarning};
52use sway_features::ExperimentalFeatures;
53use sway_types::{Ident, ProgramId, Span, Spanned};
54use sway_utils::{constants, time_expr, CompilationPhaseMetrics, PerformanceMetrics};
55use tracing::{debug, info};
56
57type GraphIx = u32;
58type Node = Pinned;
59#[derive(PartialEq, Eq, Clone, Debug)]
60pub struct Edge {
61 pub name: String,
80 pub kind: DepKind,
81}
82
83#[derive(PartialEq, Eq, Clone, Debug)]
84pub enum DepKind {
85 Library,
87 Contract { salt: fuel_tx::Salt },
89}
90
91pub type Graph = petgraph::stable_graph::StableGraph<Node, Edge, Directed, GraphIx>;
92pub type EdgeIx = petgraph::graph::EdgeIndex<GraphIx>;
93pub type NodeIx = petgraph::graph::NodeIndex<GraphIx>;
94pub type ManifestMap = HashMap<PinnedId, PackageManifestFile>;
95
96#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
100pub struct PinnedId(u64);
101
102#[derive(Debug, Clone)]
104pub struct BuiltPackage {
105 pub descriptor: PackageDescriptor,
106 pub program_abi: ProgramABI,
107 pub storage_slots: Vec<StorageSlot>,
108 pub warnings: Vec<CompileWarning>,
109 pub source_map: SourceMap,
110 pub tree_type: TreeType,
111 pub bytecode: BuiltPackageBytecode,
112 pub bytecode_without_tests: Option<BuiltPackageBytecode>,
118}
119
120#[derive(Debug, Clone)]
123pub struct PackageDescriptor {
124 pub name: String,
125 pub target: BuildTarget,
126 pub manifest_file: PackageManifestFile,
127 pub pinned: Pinned,
128}
129
130#[derive(Debug, Clone)]
132pub struct BuiltPackageBytecode {
133 pub bytes: Vec<u8>,
134 pub entries: Vec<PkgEntry>,
135}
136
137#[derive(Debug, Clone)]
139pub struct PkgEntry {
140 pub finalized: FinalizedEntry,
141 pub kind: PkgEntryKind,
142}
143
144#[derive(Debug, Clone)]
146pub enum PkgEntryKind {
147 Main,
148 Test(PkgTestEntry),
149}
150
151#[derive(Debug, Clone)]
153pub enum TestPassCondition {
154 ShouldRevert(Option<u64>),
155 ShouldNotRevert,
156}
157
158#[derive(Debug, Clone)]
160pub struct PkgTestEntry {
161 pub pass_condition: TestPassCondition,
162 pub span: Span,
163 pub file_path: Arc<PathBuf>,
164}
165
166pub type BuiltWorkspace = Vec<Arc<BuiltPackage>>;
168
169#[derive(Debug, Clone)]
170pub enum Built {
171 Package(Arc<BuiltPackage>),
173 Workspace(BuiltWorkspace),
175}
176
177pub struct CompiledPackage {
179 pub source_map: SourceMap,
180 pub tree_type: TreeType,
181 pub program_abi: ProgramABI,
182 pub storage_slots: Vec<StorageSlot>,
183 pub bytecode: BuiltPackageBytecode,
184 pub namespace: namespace::Package,
185 pub warnings: Vec<CompileWarning>,
186 pub metrics: PerformanceMetrics,
187}
188
189pub struct CompiledContractDependency {
191 pub bytecode: Vec<u8>,
192 pub storage_slots: Vec<StorageSlot>,
193}
194
195pub type CompiledContractDeps = HashMap<NodeIx, CompiledContractDependency>;
197
198#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Deserialize, Serialize)]
200pub struct Pkg {
201 pub name: String,
203 pub source: Source,
205}
206
207#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
209pub struct Pinned {
210 pub name: String,
211 pub source: source::Pinned,
212}
213
214#[derive(Clone, Debug)]
216pub struct BuildPlan {
217 graph: Graph,
218 manifest_map: ManifestMap,
219 compilation_order: Vec<NodeIx>,
220}
221
222#[derive(Clone, Debug)]
224pub struct PinnedIdParseError;
225
226#[derive(Default, Clone)]
227pub struct PkgOpts {
228 pub path: Option<String>,
230 pub offline: bool,
233 pub terse: bool,
235 pub locked: bool,
238 pub output_directory: Option<String>,
242 pub ipfs_node: IPFSNode,
244}
245
246#[derive(Default, Clone)]
247pub struct PrintOpts {
248 pub ast: bool,
250 pub dca_graph: Option<String>,
253 pub dca_graph_url_format: Option<String>,
257 pub asm: PrintAsm,
259 pub bytecode: bool,
261 pub bytecode_spans: bool,
263 pub ir: IrCli,
265 pub reverse_order: bool,
267}
268
269#[derive(Default, Clone)]
270pub struct MinifyOpts {
271 pub json_abi: bool,
274 pub json_storage_slots: bool,
277}
278
279type ContractIdConst = String;
281
282#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)]
283pub struct DumpOpts {
284 pub dump_impls: Option<String>,
286}
287
288#[derive(Default, Clone)]
290pub struct BuildOpts {
291 pub pkg: PkgOpts,
292 pub print: PrintOpts,
293 pub minify: MinifyOpts,
294 pub dump: DumpOpts,
295 pub hex_outfile: Option<String>,
297 pub binary_outfile: Option<String>,
299 pub debug_outfile: Option<String>,
303 pub build_target: BuildTarget,
305 pub build_profile: String,
307 pub release: bool,
310 pub time_phases: bool,
312 pub profile: bool,
314 pub metrics_outfile: Option<String>,
316 pub error_on_warnings: bool,
318 pub tests: bool,
320 pub member_filter: MemberFilter,
322 pub experimental: Vec<sway_features::Feature>,
324 pub no_experimental: Vec<sway_features::Feature>,
326 pub no_output: bool,
328}
329
330#[derive(Clone)]
332pub struct MemberFilter {
333 pub build_contracts: bool,
334 pub build_scripts: bool,
335 pub build_predicates: bool,
336 pub build_libraries: bool,
337}
338
339impl Default for MemberFilter {
340 fn default() -> Self {
341 Self {
342 build_contracts: true,
343 build_scripts: true,
344 build_predicates: true,
345 build_libraries: true,
346 }
347 }
348}
349
350impl MemberFilter {
351 pub fn only_scripts() -> Self {
353 Self {
354 build_contracts: false,
355 build_scripts: true,
356 build_predicates: false,
357 build_libraries: false,
358 }
359 }
360
361 pub fn only_contracts() -> Self {
363 Self {
364 build_contracts: true,
365 build_scripts: false,
366 build_predicates: false,
367 build_libraries: false,
368 }
369 }
370
371 pub fn only_predicates() -> Self {
373 Self {
374 build_contracts: false,
375 build_scripts: false,
376 build_predicates: true,
377 build_libraries: false,
378 }
379 }
380
381 pub fn filter_outputs(
383 &self,
384 build_plan: &BuildPlan,
385 outputs: HashSet<NodeIx>,
386 ) -> HashSet<NodeIx> {
387 let graph = build_plan.graph();
388 let manifest_map = build_plan.manifest_map();
389 outputs
390 .into_iter()
391 .filter(|&node_ix| {
392 let pkg = &graph[node_ix];
393 let pkg_manifest = &manifest_map[&pkg.id()];
394 let program_type = pkg_manifest.program_type();
395 match program_type {
405 Ok(program_type) => match program_type {
406 TreeType::Predicate => self.build_predicates,
407 TreeType::Script => self.build_scripts,
408 TreeType::Contract => self.build_contracts,
409 TreeType::Library => self.build_libraries,
410 },
411 Err(_) => true,
412 }
413 })
414 .collect()
415 }
416}
417
418impl BuildOpts {
419 pub fn include_tests(self, include_tests: bool) -> Self {
421 Self {
422 tests: include_tests,
423 ..self
424 }
425 }
426}
427
428impl Edge {
429 pub fn new(name: String, kind: DepKind) -> Edge {
430 Edge { name, kind }
431 }
432}
433
434impl BuiltPackage {
435 pub fn write_bytecode(&self, path: &Path) -> Result<()> {
437 fs::write(path, &self.bytecode.bytes)?;
438 Ok(())
439 }
440
441 pub fn write_hexcode(&self, path: &Path) -> Result<()> {
442 let hex_file = serde_json::json!({
443 "hex": format!("0x{}", hex::encode(&self.bytecode.bytes)),
444 });
445
446 fs::write(path, hex_file.to_string())?;
447 Ok(())
448 }
449
450 pub fn write_debug_info(&self, out_file: &Path) -> Result<()> {
452 if matches!(out_file.extension(), Some(ext) if ext == "json") {
453 let source_map_json =
454 serde_json::to_vec(&self.source_map).expect("JSON serialization failed");
455 fs::write(out_file, source_map_json)?;
456 } else {
457 let primary_dir = self.descriptor.manifest_file.dir();
458 let primary_src = self.descriptor.manifest_file.entry_path();
459 write_dwarf(&self.source_map, primary_dir, &primary_src, out_file)?;
460 }
461 Ok(())
462 }
463
464 pub fn json_abi_string(&self, minify_json_abi: bool) -> Result<Option<String>> {
465 match &self.program_abi {
466 ProgramABI::Fuel(program_abi) => {
467 if !program_abi.functions.is_empty() {
468 let json_string = if minify_json_abi {
469 serde_json::to_string(&program_abi)
470 } else {
471 serde_json::to_string_pretty(&program_abi)
472 }?;
473 Ok(Some(json_string))
474 } else {
475 Ok(None)
476 }
477 }
478 ProgramABI::Evm(program_abi) => {
479 if !program_abi.is_empty() {
480 let json_string = if minify_json_abi {
481 serde_json::to_string(&program_abi)
482 } else {
483 serde_json::to_string_pretty(&program_abi)
484 }?;
485 Ok(Some(json_string))
486 } else {
487 Ok(None)
488 }
489 }
490 ProgramABI::MidenVM(()) => Ok(None),
492 }
493 }
494
495 pub fn write_json_abi(&self, path: &Path, minify: &MinifyOpts) -> Result<()> {
497 if let Some(json_abi_string) = self.json_abi_string(minify.json_abi)? {
498 let mut file = File::create(path)?;
499 file.write_all(json_abi_string.as_bytes())?;
500 }
501 Ok(())
502 }
503
504 pub fn write_output(
506 &self,
507 minify: &MinifyOpts,
508 pkg_name: &str,
509 output_dir: &Path,
510 ) -> Result<()> {
511 if !output_dir.exists() {
512 fs::create_dir_all(output_dir)?;
513 }
514 let bin_path = output_dir.join(pkg_name).with_extension("bin");
516
517 self.write_bytecode(&bin_path)?;
518
519 let program_abi_stem = format!("{pkg_name}-abi");
520 let json_abi_path = output_dir.join(program_abi_stem).with_extension("json");
521 self.write_json_abi(&json_abi_path, minify)?;
522
523 debug!(
524 " Bytecode size: {} bytes ({})",
525 self.bytecode.bytes.len(),
526 format_bytecode_size(self.bytecode.bytes.len())
527 );
528
529 match self.tree_type {
531 TreeType::Contract => {
532 let storage_slots_stem = format!("{pkg_name}-storage_slots");
534 let storage_slots_path = output_dir.join(storage_slots_stem).with_extension("json");
535 let storage_slots_file = File::create(storage_slots_path)?;
536 let res = if minify.json_storage_slots {
537 serde_json::to_writer(&storage_slots_file, &self.storage_slots)
538 } else {
539 serde_json::to_writer_pretty(&storage_slots_file, &self.storage_slots)
540 };
541
542 res?;
543 }
544 TreeType::Predicate => {
545 let root = format!(
547 "0x{}",
548 fuel_tx::Input::predicate_owner(&self.bytecode.bytes)
549 );
550 let root_file_name = format!("{}{}", &pkg_name, SWAY_BIN_ROOT_SUFFIX);
551 let root_path = output_dir.join(root_file_name);
552 fs::write(root_path, &root)?;
553 info!(" Predicate root [{}]: {}", pkg_name, root);
554 }
555 TreeType::Script => {
556 let bytecode_hash =
558 format!("0x{}", fuel_crypto::Hasher::hash(&self.bytecode.bytes));
559 let hash_file_name = format!("{}{}", &pkg_name, SWAY_BIN_HASH_SUFFIX);
560 let hash_path = output_dir.join(hash_file_name);
561 fs::write(hash_path, &bytecode_hash)?;
562 debug!(" Bytecode hash: {}", bytecode_hash);
563 }
564 _ => (),
565 }
566
567 Ok(())
568 }
569}
570
571impl Built {
572 pub fn into_members<'a>(
574 &'a self,
575 ) -> Box<dyn Iterator<Item = (&'a Pinned, Arc<BuiltPackage>)> + 'a> {
576 match self {
579 Built::Package(pkg) => {
580 let pinned = &pkg.as_ref().descriptor.pinned;
581 let pkg = pkg.clone();
582 Box::new(std::iter::once((pinned, pkg)))
583 }
584 Built::Workspace(workspace) => Box::new(
585 workspace
586 .iter()
587 .map(|pkg| (&pkg.descriptor.pinned, pkg.clone())),
588 ),
589 }
590 }
591
592 pub fn expect_pkg(self) -> Result<Arc<BuiltPackage>> {
594 match self {
595 Built::Package(built_pkg) => Ok(built_pkg),
596 Built::Workspace(_) => bail!("expected `Built` to be `Built::Package`"),
597 }
598 }
599}
600
601impl BuildPlan {
602 pub fn from_pkg_opts(pkg_options: &PkgOpts) -> Result<Self> {
607 let path = &pkg_options.path;
608
609 let manifest_dir = if let Some(ref path) = path {
610 PathBuf::from(path)
611 } else {
612 std::env::current_dir()?
613 };
614
615 let manifest_file = ManifestFile::from_dir(manifest_dir)?;
616 let member_manifests = manifest_file.member_manifests()?;
617 if member_manifests.is_empty() {
619 bail!("No member found to build")
620 }
621 let lock_path = manifest_file.lock_path()?;
622 Self::from_lock_and_manifests(
623 &lock_path,
624 &member_manifests,
625 pkg_options.locked,
626 pkg_options.offline,
627 &pkg_options.ipfs_node,
628 )
629 }
630
631 pub fn from_manifests(
635 manifests: &MemberManifestFiles,
636 offline: bool,
637 ipfs_node: &IPFSNode,
638 ) -> Result<Self> {
639 validate_version(manifests)?;
641 let mut graph = Graph::default();
642 let mut manifest_map = ManifestMap::default();
643 fetch_graph(manifests, offline, ipfs_node, &mut graph, &mut manifest_map)?;
644 validate_graph(&graph, manifests)?;
647 let compilation_order = compilation_order(&graph)?;
648 Ok(Self {
649 graph,
650 manifest_map,
651 compilation_order,
652 })
653 }
654
655 pub fn from_lock_and_manifests(
672 lock_path: &Path,
673 manifests: &MemberManifestFiles,
674 locked: bool,
675 offline: bool,
676 ipfs_node: &IPFSNode,
677 ) -> Result<Self> {
678 validate_version(manifests)?;
680 let mut new_lock_cause = None;
682
683 let lock = Lock::from_path(lock_path).unwrap_or_else(|e| {
685 new_lock_cause = if e.to_string().contains("No such file or directory") {
686 Some(anyhow!("lock file did not exist"))
687 } else {
688 Some(e)
689 };
690 Lock::default()
691 });
692
693 let mut graph = lock.to_graph().unwrap_or_else(|e| {
695 new_lock_cause = Some(anyhow!("Invalid lock: {}", e));
696 Graph::default()
697 });
698
699 let invalid_deps = validate_graph(&graph, manifests)?;
705 let members: HashSet<String> = manifests.keys().cloned().collect();
706 remove_deps(&mut graph, &members, &invalid_deps);
707
708 let mut manifest_map = graph_to_manifest_map(manifests, &graph)?;
711
712 let _added = fetch_graph(manifests, offline, ipfs_node, &mut graph, &mut manifest_map)?;
714
715 let compilation_order = compilation_order(&graph)?;
717
718 let plan = Self {
719 graph,
720 manifest_map,
721 compilation_order,
722 };
723
724 let new_lock = Lock::from_graph(plan.graph());
726 let lock_diff = new_lock.diff(&lock);
727 if !lock_diff.removed.is_empty() || !lock_diff.added.is_empty() {
728 new_lock_cause.get_or_insert(anyhow!("lock file did not match manifest"));
729 }
730
731 if let Some(cause) = new_lock_cause {
733 if locked {
734 bail!(
735 "The lock file {} needs to be updated (Cause: {}) \
736 but --locked was passed to prevent this.",
737 lock_path.to_string_lossy(),
738 cause,
739 );
740 }
741 println_action_green(
742 "Creating",
743 &format!("a new `Forc.lock` file. (Cause: {cause})"),
744 );
745 let member_names = manifests
746 .values()
747 .map(|manifest| manifest.project.name.to_string())
748 .collect();
749 crate::lock::print_diff(&member_names, &lock_diff);
750 let string = toml::ser::to_string_pretty(&new_lock)
751 .map_err(|e| anyhow!("failed to serialize lock file: {}", e))?;
752 fs::write(lock_path, string)
753 .map_err(|e| anyhow!("failed to write lock file: {}", e))?;
754 debug!(" Created new lock file at {}", lock_path.display());
755 }
756
757 Ok(plan)
758 }
759
760 pub fn contract_dependencies(&self, node: NodeIx) -> impl Iterator<Item = NodeIx> + '_ {
763 let graph = self.graph();
764 let connected: HashSet<_> = Dfs::new(graph, node).iter(graph).collect();
765 self.compilation_order()
766 .iter()
767 .cloned()
768 .filter(move |&n| n != node)
769 .filter(|&n| {
770 graph
771 .edges_directed(n, Direction::Incoming)
772 .any(|edge| matches!(edge.weight().kind, DepKind::Contract { .. }))
773 })
774 .filter(move |&n| connected.contains(&n))
775 }
776
777 pub fn member_nodes(&self) -> impl Iterator<Item = NodeIx> + '_ {
782 self.compilation_order()
783 .iter()
784 .copied()
785 .filter(|&n| self.graph[n].source == source::Pinned::MEMBER)
786 }
787
788 pub fn member_pinned_pkgs(&self) -> impl Iterator<Item = Pinned> + '_ {
793 let graph = self.graph();
794 self.member_nodes().map(|node| &graph[node]).cloned()
795 }
796
797 pub fn graph(&self) -> &Graph {
799 &self.graph
800 }
801
802 pub fn manifest_map(&self) -> &ManifestMap {
804 &self.manifest_map
805 }
806
807 pub fn compilation_order(&self) -> &[NodeIx] {
809 &self.compilation_order
810 }
811
812 pub fn find_member_index(&self, member_name: &str) -> Option<NodeIx> {
814 self.member_nodes()
815 .find(|node_ix| self.graph[*node_ix].name == member_name)
816 }
817
818 pub fn node_deps(&self, n: NodeIx) -> impl '_ + Iterator<Item = NodeIx> {
820 let bfs = Bfs::new(&self.graph, n);
821 bfs.iter(&self.graph)
823 }
824
825 pub fn build_profiles(&self) -> impl '_ + Iterator<Item = (String, BuildProfile)> {
827 let manifest_map = &self.manifest_map;
828 let graph = &self.graph;
829 self.member_nodes().flat_map(|member_node| {
830 manifest_map[&graph[member_node].id()]
831 .build_profiles()
832 .map(|(n, p)| (n.clone(), p.clone()))
833 })
834 }
835
836 pub fn salt(&self, pinned: &Pinned) -> Option<fuel_tx::Salt> {
838 let graph = self.graph();
839 let node_ix = graph
840 .node_indices()
841 .find(|node_ix| graph[*node_ix] == *pinned);
842 node_ix.and_then(|node| {
843 graph
844 .edges_directed(node, Direction::Incoming)
845 .map(|e| match e.weight().kind {
846 DepKind::Library => None,
847 DepKind::Contract { salt } => Some(salt),
848 })
849 .next()
850 .flatten()
851 })
852 }
853
854 pub fn visualize(&self, url_file_prefix: Option<String>) -> String {
856 format!(
857 "{:?}",
858 dot::Dot::with_attr_getters(
859 &self.graph,
860 &[dot::Config::NodeNoLabel, dot::Config::EdgeNoLabel],
861 &|_, _| String::new(),
862 &|_, nr| {
863 let url = url_file_prefix.clone().map_or(String::new(), |prefix| {
864 self.manifest_map
865 .get(&nr.1.id())
866 .map_or(String::new(), |manifest| {
867 format!("URL = \"{}{}\"", prefix, manifest.path().to_string_lossy())
868 })
869 });
870 format!("label = \"{}\" shape = box {url}", nr.1.name)
871 },
872 )
873 )
874 }
875}
876
877fn potential_proj_nodes<'a>(g: &'a Graph, proj_name: &'a str) -> impl 'a + Iterator<Item = NodeIx> {
880 member_nodes(g).filter(move |&n| g[n].name == proj_name)
881}
882
883fn find_proj_node(graph: &Graph, proj_name: &str) -> Result<NodeIx> {
890 let mut potentials = potential_proj_nodes(graph, proj_name);
891 let proj_node = potentials
892 .next()
893 .ok_or_else(|| anyhow!("graph contains no project node"))?;
894 match potentials.next() {
895 None => Ok(proj_node),
896 Some(_) => Err(anyhow!("graph contains more than one project node")),
897 }
898}
899
900fn validate_version(member_manifests: &MemberManifestFiles) -> Result<()> {
905 for member_pkg_manifest in member_manifests.values() {
906 validate_pkg_version(member_pkg_manifest)?;
907 }
908 Ok(())
909}
910
911fn validate_pkg_version(pkg_manifest: &PackageManifestFile) -> Result<()> {
916 if let Some(min_forc_version) = &pkg_manifest.project.forc_version {
917 let crate_version = env!("CARGO_PKG_VERSION");
919 let toolchain_version = semver::Version::parse(crate_version)?;
920 if toolchain_version < *min_forc_version {
921 bail!(
922 "{:?} requires forc version {} but current forc version is {}\nUpdate the toolchain by following: https://fuellabs.github.io/sway/v{}/introduction/installation.html",
923 pkg_manifest.project.name,
924 min_forc_version,
925 crate_version,
926 crate_version
927 );
928 }
929 };
930 Ok(())
931}
932
933fn member_nodes(g: &Graph) -> impl Iterator<Item = NodeIx> + '_ {
934 g.node_indices()
935 .filter(|&n| g[n].source == source::Pinned::MEMBER)
936}
937
938fn validate_graph(graph: &Graph, manifests: &MemberManifestFiles) -> Result<BTreeSet<EdgeIx>> {
942 let mut member_pkgs: HashMap<&String, &PackageManifestFile> = manifests.iter().collect();
943 let member_nodes: Vec<_> = member_nodes(graph)
944 .filter_map(|n| {
945 member_pkgs
946 .remove(&graph[n].name.to_string())
947 .map(|pkg| (n, pkg))
948 })
949 .collect();
950
951 if member_nodes.is_empty() {
953 return Ok(graph.edge_indices().collect());
954 }
955
956 let mut visited = HashSet::new();
957 let edges = member_nodes
958 .into_iter()
959 .flat_map(move |(n, _)| validate_deps(graph, n, manifests, &mut visited))
960 .collect();
961
962 Ok(edges)
963}
964
965fn validate_deps(
969 graph: &Graph,
970 node: NodeIx,
971 manifests: &MemberManifestFiles,
972 visited: &mut HashSet<NodeIx>,
973) -> BTreeSet<EdgeIx> {
974 let mut remove = BTreeSet::default();
975 for edge in graph.edges_directed(node, Direction::Outgoing) {
976 let dep_name = edge.weight();
977 let dep_node = edge.target();
978 match validate_dep(graph, manifests, dep_name, dep_node) {
979 Err(_) => {
980 remove.insert(edge.id());
981 }
982 Ok(_) => {
983 if visited.insert(dep_node) {
984 let rm = validate_deps(graph, dep_node, manifests, visited);
985 remove.extend(rm);
986 }
987 continue;
988 }
989 }
990 }
991 remove
992}
993
994fn validate_dep(
998 graph: &Graph,
999 manifests: &MemberManifestFiles,
1000 dep_edge: &Edge,
1001 dep_node: NodeIx,
1002) -> Result<PackageManifestFile> {
1003 let dep_name = &dep_edge.name;
1004 let node_manifest = manifests
1005 .get(dep_name)
1006 .ok_or_else(|| anyhow!("Couldn't find manifest file for {}", dep_name))?;
1007 let dep_path = dep_path(graph, node_manifest, dep_node, manifests).map_err(|e| {
1009 anyhow!(
1010 "failed to construct path for dependency {:?}: {}",
1011 dep_name,
1012 e
1013 )
1014 })?;
1015
1016 let dep_manifest = PackageManifestFile::from_dir(&dep_path)?;
1018
1019 let dep_entry = node_manifest
1021 .dep(dep_name)
1022 .ok_or_else(|| anyhow!("no entry in parent manifest"))?;
1023 let dep_source =
1024 Source::from_manifest_dep_patched(node_manifest, dep_name, dep_entry, manifests)?;
1025 let dep_pkg = graph[dep_node].unpinned(&dep_path);
1026 if dep_pkg.source != dep_source {
1027 bail!("dependency node's source does not match manifest entry");
1028 }
1029
1030 validate_dep_manifest(&graph[dep_node], &dep_manifest, dep_edge)?;
1031
1032 Ok(dep_manifest)
1033}
1034fn validate_dep_manifest(
1036 dep: &Pinned,
1037 dep_manifest: &PackageManifestFile,
1038 dep_edge: &Edge,
1039) -> Result<()> {
1040 let dep_program_type = dep_manifest.program_type()?;
1041 match (&dep_program_type, &dep_edge.kind) {
1043 (TreeType::Contract, DepKind::Contract { salt: _ })
1044 | (TreeType::Library, DepKind::Library) => {}
1045 _ => bail!(
1046 "\"{}\" is declared as a {} dependency, but is actually a {}",
1047 dep.name,
1048 dep_edge.kind,
1049 dep_program_type
1050 ),
1051 }
1052 if dep.name != dep_manifest.project.name {
1054 bail!(
1055 "dependency name {:?} must match the manifest project name {:?} \
1056 unless `package = {:?}` is specified in the dependency declaration",
1057 dep.name,
1058 dep_manifest.project.name,
1059 dep_manifest.project.name,
1060 );
1061 }
1062 validate_pkg_version(dep_manifest)?;
1063 Ok(())
1064}
1065
1066fn dep_path(
1071 graph: &Graph,
1072 node_manifest: &PackageManifestFile,
1073 dep_node: NodeIx,
1074 manifests: &MemberManifestFiles,
1075) -> Result<PathBuf> {
1076 let dep = &graph[dep_node];
1077 let dep_name = &dep.name;
1078 match dep.source.dep_path(&dep.name)? {
1079 source::DependencyPath::ManifestPath(path) => Ok(path),
1080 source::DependencyPath::Root(path_root) => {
1081 validate_path_root(graph, dep_node, path_root)?;
1082
1083 if let Some(path) = node_manifest.dep_path(dep_name) {
1085 if path.exists() {
1086 return Ok(path);
1087 }
1088 }
1089
1090 for (_, patch_map) in node_manifest.patches() {
1092 if let Some(Dependency::Detailed(details)) = patch_map.get(&dep_name.to_string()) {
1093 if let Some(ref rel_path) = details.path {
1094 if let Ok(path) = node_manifest.dir().join(rel_path).canonicalize() {
1095 if path.exists() {
1096 return Ok(path);
1097 }
1098 }
1099 }
1100 }
1101 }
1102
1103 bail!(
1104 "no dependency or patch with name {:?} in manifest of {:?}",
1105 dep_name,
1106 node_manifest.project.name
1107 )
1108 }
1109 source::DependencyPath::Member => {
1110 manifests
1112 .values()
1113 .find(|manifest| manifest.project.name == *dep_name)
1114 .map(|manifest| manifest.path().to_path_buf())
1115 .ok_or_else(|| anyhow!("cannot find dependency in the workspace"))
1116 }
1117 }
1118}
1119
1120fn remove_deps(
1124 graph: &mut Graph,
1125 member_names: &HashSet<String>,
1126 edges_to_remove: &BTreeSet<EdgeIx>,
1127) {
1128 let member_nodes: HashSet<_> = member_nodes(graph)
1130 .filter(|&n| member_names.contains(&graph[n].name.to_string()))
1131 .collect();
1132
1133 let node_removal_order = if let Ok(nodes) = petgraph::algo::toposort(&*graph, None) {
1135 nodes
1136 } else {
1137 graph.clear();
1139 return;
1140 };
1141
1142 for &edge in edges_to_remove {
1144 graph.remove_edge(edge);
1145 }
1146
1147 let nodes = node_removal_order.into_iter();
1149 for node in nodes {
1150 if !has_parent(graph, node) && !member_nodes.contains(&node) {
1151 graph.remove_node(node);
1152 }
1153 }
1154}
1155
1156fn has_parent(graph: &Graph, node: NodeIx) -> bool {
1157 graph
1158 .edges_directed(node, Direction::Incoming)
1159 .next()
1160 .is_some()
1161}
1162
1163impl Pinned {
1164 pub fn id(&self) -> PinnedId {
1168 PinnedId::new(&self.name, &self.source)
1169 }
1170
1171 pub fn unpinned(&self, path: &Path) -> Pkg {
1173 let source = self.source.unpinned(path);
1174 let name = self.name.clone();
1175 Pkg { name, source }
1176 }
1177}
1178
1179impl PinnedId {
1180 pub fn new(name: &str, source: &source::Pinned) -> Self {
1182 let mut hasher = hash_map::DefaultHasher::default();
1183 name.hash(&mut hasher);
1184 source.hash(&mut hasher);
1185 Self(hasher.finish())
1186 }
1187}
1188
1189impl fmt::Display for DepKind {
1190 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1191 match self {
1192 DepKind::Library => write!(f, "library"),
1193 DepKind::Contract { .. } => write!(f, "contract"),
1194 }
1195 }
1196}
1197
1198impl fmt::Display for PinnedId {
1199 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1200 write!(f, "{:016X}", self.0)
1202 }
1203}
1204
1205impl FromStr for PinnedId {
1206 type Err = PinnedIdParseError;
1207 fn from_str(s: &str) -> Result<Self, Self::Err> {
1208 Ok(Self(
1209 u64::from_str_radix(s, 16).map_err(|_| PinnedIdParseError)?,
1210 ))
1211 }
1212}
1213
1214pub fn compilation_order(graph: &Graph) -> Result<Vec<NodeIx>> {
1218 let rev_pkg_graph = petgraph::visit::Reversed(&graph);
1219 petgraph::algo::toposort(rev_pkg_graph, None).map_err(|_| {
1220 let scc = petgraph::algo::kosaraju_scc(&graph);
1223 let mut path = String::new();
1224 scc.iter()
1225 .filter(|path| path.len() > 1)
1226 .for_each(|cyclic_path| {
1227 let starting_node = &graph[*cyclic_path.last().unwrap()];
1229
1230 path.push_str(&starting_node.name.to_string());
1232 path.push_str(" -> ");
1233
1234 for (node_index, node) in cyclic_path.iter().enumerate() {
1235 path.push_str(&graph[*node].name.to_string());
1236 if node_index != cyclic_path.len() - 1 {
1237 path.push_str(" -> ");
1238 }
1239 }
1240 path.push('\n');
1241 });
1242 anyhow!("dependency cycle detected: {}", path)
1243 })
1244}
1245
1246fn graph_to_manifest_map(manifests: &MemberManifestFiles, graph: &Graph) -> Result<ManifestMap> {
1250 let mut manifest_map = HashMap::new();
1251 for pkg_manifest in manifests.values() {
1252 let pkg_name = &pkg_manifest.project.name;
1253 manifest_map.extend(pkg_graph_to_manifest_map(manifests, pkg_name, graph)?);
1254 }
1255 Ok(manifest_map)
1256}
1257
1258fn pkg_graph_to_manifest_map(
1266 manifests: &MemberManifestFiles,
1267 pkg_name: &str,
1268 graph: &Graph,
1269) -> Result<ManifestMap> {
1270 let proj_manifest = manifests
1271 .get(pkg_name)
1272 .ok_or_else(|| anyhow!("Cannot find manifest for {}", pkg_name))?;
1273 let mut manifest_map = ManifestMap::new();
1274
1275 let Ok(proj_node) = find_proj_node(graph, &proj_manifest.project.name) else {
1277 return Ok(manifest_map);
1278 };
1279 let proj_id = graph[proj_node].id();
1280 manifest_map.insert(proj_id, proj_manifest.clone());
1281
1282 let mut bfs = Bfs::new(graph, proj_node);
1285 bfs.next(graph);
1286 while let Some(dep_node) = bfs.next(graph) {
1287 let (parent_manifest, dep_name) = graph
1289 .edges_directed(dep_node, Direction::Incoming)
1290 .find_map(|edge| {
1291 let parent_node = edge.source();
1292 let dep_name = &edge.weight().name;
1293 let parent = &graph[parent_node];
1294 let parent_manifest = manifest_map.get(&parent.id())?;
1295 Some((parent_manifest, dep_name))
1296 })
1297 .ok_or_else(|| anyhow!("more than one root package detected in graph"))?;
1298 let dep_path = dep_path(graph, parent_manifest, dep_node, manifests).map_err(|e| {
1299 anyhow!(
1300 "failed to construct path for dependency {:?}: {}",
1301 dep_name,
1302 e
1303 )
1304 })?;
1305 let dep_manifest = PackageManifestFile::from_dir(&dep_path)?;
1306 let dep = &graph[dep_node];
1307 manifest_map.insert(dep.id(), dep_manifest);
1308 }
1309
1310 Ok(manifest_map)
1311}
1312
1313fn validate_path_root(graph: &Graph, path_dep: NodeIx, path_root: PinnedId) -> Result<()> {
1318 let path_root_node = find_path_root(graph, path_dep)?;
1319 if graph[path_root_node].id() != path_root {
1320 bail!(
1321 "invalid `path_root` for path dependency package {:?}",
1322 &graph[path_dep].name
1323 )
1324 }
1325 Ok(())
1326}
1327
1328fn find_path_root(graph: &Graph, mut node: NodeIx) -> Result<NodeIx> {
1330 loop {
1331 let pkg = &graph[node];
1332 match pkg.source {
1333 source::Pinned::Path(ref src) => {
1334 let parent = graph
1335 .edges_directed(node, Direction::Incoming)
1336 .next()
1337 .map(|edge| edge.source())
1338 .ok_or_else(|| {
1339 anyhow!(
1340 "Failed to find path root: `path` dependency \"{}\" has no parent",
1341 src
1342 )
1343 })?;
1344 node = parent;
1345 }
1346 source::Pinned::Git(_)
1347 | source::Pinned::Ipfs(_)
1348 | source::Pinned::Member(_)
1349 | source::Pinned::Registry(_) => {
1350 return Ok(node);
1351 }
1352 }
1353 }
1354}
1355
1356fn fetch_graph(
1364 member_manifests: &MemberManifestFiles,
1365 offline: bool,
1366 ipfs_node: &IPFSNode,
1367 graph: &mut Graph,
1368 manifest_map: &mut ManifestMap,
1369) -> Result<HashSet<NodeIx>> {
1370 let mut added_nodes = HashSet::default();
1371 for member_pkg_manifest in member_manifests.values() {
1372 added_nodes.extend(&fetch_pkg_graph(
1373 member_pkg_manifest,
1374 offline,
1375 ipfs_node,
1376 graph,
1377 manifest_map,
1378 member_manifests,
1379 )?);
1380 }
1381 validate_contract_deps(graph)?;
1382 Ok(added_nodes)
1383}
1384
1385fn fetch_pkg_graph(
1399 proj_manifest: &PackageManifestFile,
1400 offline: bool,
1401 ipfs_node: &IPFSNode,
1402 graph: &mut Graph,
1403 manifest_map: &mut ManifestMap,
1404 member_manifests: &MemberManifestFiles,
1405) -> Result<HashSet<NodeIx>> {
1406 let proj_node = if let Ok(proj_node) = find_proj_node(graph, &proj_manifest.project.name) {
1408 proj_node
1409 } else {
1410 let name = proj_manifest.project.name.clone();
1411 let source = source::Pinned::MEMBER;
1412 let pkg = Pinned { name, source };
1413 let pkg_id = pkg.id();
1414 manifest_map.insert(pkg_id, proj_manifest.clone());
1415 graph.add_node(pkg)
1416 };
1417
1418 let fetch_ts = std::time::Instant::now();
1420 let fetch_id = source::fetch_id(proj_manifest.dir(), fetch_ts);
1421 let path_root = graph[proj_node].id();
1422 let mut fetched = graph
1423 .node_indices()
1424 .map(|n| {
1425 let pinned = &graph[n];
1426 let manifest = &manifest_map[&pinned.id()];
1427 let pkg = pinned.unpinned(manifest.dir());
1428 (pkg, n)
1429 })
1430 .collect();
1431 let mut visited = HashSet::default();
1432 fetch_deps(
1433 fetch_id,
1434 offline,
1435 ipfs_node,
1436 proj_node,
1437 path_root,
1438 graph,
1439 manifest_map,
1440 &mut fetched,
1441 &mut visited,
1442 member_manifests,
1443 )
1444}
1445
1446#[allow(clippy::too_many_arguments)]
1450fn fetch_deps(
1451 fetch_id: u64,
1452 offline: bool,
1453 ipfs_node: &IPFSNode,
1454 node: NodeIx,
1455 path_root: PinnedId,
1456 graph: &mut Graph,
1457 manifest_map: &mut ManifestMap,
1458 fetched: &mut HashMap<Pkg, NodeIx>,
1459 visited: &mut HashSet<NodeIx>,
1460 member_manifests: &MemberManifestFiles,
1461) -> Result<HashSet<NodeIx>> {
1462 let mut added = HashSet::default();
1463 let parent_id = graph[node].id();
1464 let package_manifest = &manifest_map[&parent_id];
1465 let deps: Vec<(String, Dependency, DepKind)> = package_manifest
1467 .contract_deps()
1468 .map(|(n, d)| {
1469 (
1470 n.clone(),
1471 d.dependency.clone(),
1472 DepKind::Contract { salt: d.salt.0 },
1473 )
1474 })
1475 .chain(
1476 package_manifest
1477 .deps()
1478 .map(|(n, d)| (n.clone(), d.clone(), DepKind::Library)),
1479 )
1480 .collect();
1481 for (dep_name, dep, dep_kind) in deps {
1482 let name = dep.package().unwrap_or(&dep_name);
1483 let parent_manifest = &manifest_map[&parent_id];
1484 let source =
1485 Source::from_manifest_dep_patched(parent_manifest, name, &dep, member_manifests)
1486 .context(format!("Failed to source dependency: {dep_name}"))?;
1487
1488 let dep_pkg = Pkg {
1490 name: name.to_string(),
1491 source,
1492 };
1493 let dep_node = match fetched.entry(dep_pkg) {
1494 hash_map::Entry::Occupied(entry) => *entry.get(),
1495 hash_map::Entry::Vacant(entry) => {
1496 let pkg = entry.key();
1497 let ctx = source::PinCtx {
1498 fetch_id,
1499 path_root,
1500 name: &pkg.name,
1501 offline,
1502 ipfs_node,
1503 };
1504 let source = pkg.source.pin(ctx, manifest_map)?;
1505 let name = pkg.name.clone();
1506 let dep_pinned = Pinned { name, source };
1507 let dep_node = graph.add_node(dep_pinned);
1508 added.insert(dep_node);
1509 *entry.insert(dep_node)
1510 }
1511 };
1512
1513 let dep_edge = Edge::new(dep_name.to_string(), dep_kind.clone());
1514 graph.update_edge(node, dep_node, dep_edge.clone());
1516
1517 if !visited.insert(dep_node) {
1519 continue;
1520 }
1521
1522 let dep_pinned = &graph[dep_node];
1523 let dep_pkg_id = dep_pinned.id();
1524 validate_dep_manifest(dep_pinned, &manifest_map[&dep_pkg_id], &dep_edge).map_err(|e| {
1525 let parent = &graph[node];
1526 anyhow!(
1527 "dependency of {:?} named {:?} is invalid: {}",
1528 parent.name,
1529 dep_name,
1530 e
1531 )
1532 })?;
1533
1534 let path_root = match dep_pinned.source {
1535 source::Pinned::Member(_)
1536 | source::Pinned::Git(_)
1537 | source::Pinned::Ipfs(_)
1538 | source::Pinned::Registry(_) => dep_pkg_id,
1539 source::Pinned::Path(_) => path_root,
1540 };
1541
1542 added.extend(fetch_deps(
1544 fetch_id,
1545 offline,
1546 ipfs_node,
1547 dep_node,
1548 path_root,
1549 graph,
1550 manifest_map,
1551 fetched,
1552 visited,
1553 member_manifests,
1554 )?);
1555 }
1556 Ok(added)
1557}
1558
1559pub fn sway_build_config(
1562 manifest_dir: &Path,
1563 entry_path: &Path,
1564 build_target: BuildTarget,
1565 build_profile: &BuildProfile,
1566 dbg_generation: sway_core::DbgGeneration,
1567) -> Result<sway_core::BuildConfig> {
1568 let file_name = find_file_name(manifest_dir, entry_path)?;
1570 let build_config = sway_core::BuildConfig::root_from_file_name_and_manifest_path(
1571 file_name.to_path_buf(),
1572 manifest_dir.to_path_buf(),
1573 build_target,
1574 dbg_generation,
1575 )
1576 .with_print_dca_graph(build_profile.print_dca_graph.clone())
1577 .with_print_dca_graph_url_format(build_profile.print_dca_graph_url_format.clone())
1578 .with_print_asm(build_profile.print_asm)
1579 .with_print_bytecode(
1580 build_profile.print_bytecode,
1581 build_profile.print_bytecode_spans,
1582 )
1583 .with_print_ir(build_profile.print_ir.clone())
1584 .with_include_tests(build_profile.include_tests)
1585 .with_time_phases(build_profile.time_phases)
1586 .with_profile(build_profile.profile)
1587 .with_metrics(build_profile.metrics_outfile.clone())
1588 .with_optimization_level(build_profile.optimization_level)
1589 .with_backtrace(build_profile.backtrace);
1590 Ok(build_config)
1591}
1592
1593#[allow(clippy::too_many_arguments)]
1606pub fn dependency_namespace(
1607 lib_namespace_map: &HashMap<NodeIx, namespace::Package>,
1608 compiled_contract_deps: &CompiledContractDeps,
1609 graph: &Graph,
1610 node: NodeIx,
1611 engines: &Engines,
1612 contract_id_value: Option<ContractIdConst>,
1613 program_id: ProgramId,
1614 experimental: ExperimentalFeatures,
1615 dbg_generation: sway_core::DbgGeneration,
1616) -> Result<namespace::Package, vec1::Vec1<CompileError>> {
1617 let node_idx = &graph[node];
1619 let name = Ident::new_no_span(node_idx.name.clone());
1620 let mut namespace = if let Some(contract_id_value) = contract_id_value {
1621 namespace::package_with_contract_id(
1622 engines,
1623 name.clone(),
1624 program_id,
1625 contract_id_value,
1626 experimental,
1627 dbg_generation,
1628 )?
1629 } else {
1630 Package::new(name.clone(), None, program_id, false)
1631 };
1632
1633 for edge in graph.edges_directed(node, Direction::Outgoing) {
1635 let dep_node = edge.target();
1636 let dep_name = kebab_to_snake_case(&edge.weight().name);
1637 let dep_edge = edge.weight();
1638 let dep_namespace = match dep_edge.kind {
1639 DepKind::Library => lib_namespace_map
1640 .get(&dep_node)
1641 .cloned()
1642 .expect("no root namespace module")
1643 .clone(),
1644 DepKind::Contract { salt } => {
1645 let dep_contract_id = compiled_contract_deps
1646 .get(&dep_node)
1647 .map(|dep| contract_id(&dep.bytecode, dep.storage_slots.clone(), &salt))
1648 .unwrap_or_default();
1650 let contract_id_value = format!("0x{dep_contract_id}");
1652 let node_idx = &graph[dep_node];
1653 let name = Ident::new_no_span(node_idx.name.clone());
1654 namespace::package_with_contract_id(
1655 engines,
1656 name.clone(),
1657 program_id,
1658 contract_id_value,
1659 experimental,
1660 dbg_generation,
1661 )?
1662 }
1663 };
1664 namespace.add_external(dep_name, dep_namespace);
1665 }
1666
1667 Ok(namespace)
1668}
1669
1670pub fn compile(
1689 pkg: &PackageDescriptor,
1690 profile: &BuildProfile,
1691 engines: &Engines,
1692 namespace: namespace::Package,
1693 source_map: &mut SourceMap,
1694 experimental: ExperimentalFeatures,
1695 dbg_generation: DbgGeneration,
1696) -> Result<CompiledPackage> {
1697 let mut metrics = PerformanceMetrics::default();
1698
1699 let entry_path = pkg.manifest_file.entry_path();
1700 let sway_build_config = sway_build_config(
1701 pkg.manifest_file.dir(),
1702 &entry_path,
1703 pkg.target,
1704 profile,
1705 dbg_generation,
1706 )?;
1707 let terse_mode = profile.terse;
1708 let reverse_results = profile.reverse_results;
1709 let fail = |handler: Handler| {
1710 let (errors, warnings, infos) = handler.consume();
1711 print_on_failure(
1712 engines.se(),
1713 terse_mode,
1714 &infos,
1715 &warnings,
1716 &errors,
1717 reverse_results,
1718 );
1719 bail!("Failed to compile {}", pkg.name);
1720 };
1721 let source = pkg.manifest_file.entry_string()?;
1722
1723 let handler = Handler::default();
1724
1725 let ast_res = time_expr!(
1727 pkg.name,
1728 "compile to ast",
1729 "compile_to_ast",
1730 sway_core::compile_to_ast(
1731 &handler,
1732 engines,
1733 source,
1734 namespace.clone(),
1735 Some(&sway_build_config),
1736 &pkg.name,
1737 None,
1738 experimental
1739 ),
1740 Some(sway_build_config.clone()),
1741 metrics
1742 );
1743
1744 let programs = match ast_res {
1745 Err(_) => return fail(handler),
1746 Ok(programs) => programs,
1747 };
1748 let typed_program = match programs.typed.as_ref() {
1749 Err(_) => return fail(handler),
1750 Ok(typed_program) => typed_program,
1751 };
1752
1753 if profile.print_ast {
1754 tracing::info!("{:#?}", typed_program);
1755 }
1756
1757 let storage_slots = typed_program.storage_slots.clone();
1758 let tree_type = typed_program.kind.tree_type();
1759
1760 if handler.has_errors() {
1761 return fail(handler);
1762 }
1763
1764 if let Some(typename) = &profile.dump.dump_impls {
1765 let _ = sway_core::dump_trait_impls_for_typename(
1766 &handler,
1767 engines,
1768 &typed_program.namespace,
1769 typename,
1770 );
1771 }
1772
1773 let asm_res = time_expr!(
1774 pkg.name,
1775 "compile ast to asm",
1776 "compile_ast_to_asm",
1777 sway_core::ast_to_asm(
1778 &handler,
1779 engines,
1780 &programs,
1781 &sway_build_config,
1782 experimental
1783 ),
1784 Some(sway_build_config.clone()),
1785 metrics
1786 );
1787
1788 let mut asm = match asm_res {
1789 Err(_) => return fail(handler),
1790 Ok(asm) => asm,
1791 };
1792
1793 const ENCODING_V0: &str = "0";
1794 const ENCODING_V1: &str = "1";
1795 const SPEC_VERSION: &str = "1.2";
1796
1797 let mut program_abi = match pkg.target {
1798 BuildTarget::Fuel => {
1799 let program_abi_res = time_expr!(
1800 pkg.name,
1801 "generate JSON ABI program",
1802 "generate_json_abi",
1803 fuel_abi::generate_program_abi(
1804 &handler,
1805 &mut AbiContext {
1806 program: typed_program,
1807 panic_occurrences: &asm.panic_occurrences,
1808 panicking_call_occurrences: &asm.panicking_call_occurrences,
1809 abi_with_callpaths: true,
1810 type_ids_to_full_type_str: HashMap::<String, String>::new(),
1811 unique_names: HashMap::new(),
1812 },
1813 engines,
1814 if experimental.new_encoding {
1815 ENCODING_V1.into()
1816 } else {
1817 ENCODING_V0.into()
1818 },
1819 SPEC_VERSION.into()
1820 ),
1821 Some(sway_build_config.clone()),
1822 metrics
1823 );
1824 let program_abi = match program_abi_res {
1825 Err(_) => return fail(handler),
1826 Ok(program_abi) => program_abi,
1827 };
1828 ProgramABI::Fuel(program_abi)
1829 }
1830 BuildTarget::EVM => {
1831 let mut ops = match &asm.finalized_asm.abi {
1834 Some(ProgramABI::Evm(ops)) => ops.clone(),
1835 _ => vec![],
1836 };
1837
1838 let abi = time_expr!(
1839 pkg.name,
1840 "generate JSON ABI program",
1841 "generate_json_abi",
1842 evm_abi::generate_abi_program(typed_program, engines),
1843 Some(sway_build_config.clone()),
1844 metrics
1845 );
1846
1847 ops.extend(abi);
1848
1849 ProgramABI::Evm(ops)
1850 }
1851 };
1852
1853 let entries = asm
1854 .finalized_asm
1855 .entries
1856 .iter()
1857 .map(|finalized_entry| PkgEntry::from_finalized_entry(finalized_entry, engines))
1858 .collect::<anyhow::Result<_>>()?;
1859
1860 let bc_res = time_expr!(
1861 pkg.name,
1862 "compile asm to bytecode",
1863 "compile_asm_to_bytecode",
1864 sway_core::asm_to_bytecode(
1865 &handler,
1866 &mut asm,
1867 source_map,
1868 engines.se(),
1869 &sway_build_config
1870 ),
1871 Some(sway_build_config.clone()),
1872 metrics
1873 );
1874
1875 let errored = handler.has_errors() || (handler.has_warnings() && profile.error_on_warnings);
1876
1877 let mut compiled = match bc_res {
1878 Ok(compiled) if !errored => compiled,
1879 _ => return fail(handler),
1880 };
1881
1882 let (_, warnings, infos) = handler.consume();
1883
1884 print_infos(engines.se(), terse_mode, &infos);
1885 print_warnings(engines.se(), terse_mode, &pkg.name, &warnings, &tree_type);
1886
1887 let mut md = [0u8, 0, 0, 0, 0, 0, 0, 0];
1889 if let ProgramABI::Fuel(ref mut program_abi) = program_abi {
1892 let mut configurables_offset = compiled.bytecode.len() as u64;
1893 if let Some(ref mut configurables) = program_abi.configurables {
1894 configurables.retain(|c| {
1896 compiled
1897 .named_data_section_entries_offsets
1898 .contains_key(&c.name)
1899 });
1900 for (config, offset) in &compiled.named_data_section_entries_offsets {
1902 if *offset < configurables_offset {
1903 configurables_offset = *offset;
1904 }
1905 if let Some(idx) = configurables.iter().position(|c| &c.name == config) {
1906 configurables[idx].offset = *offset;
1907 }
1908 }
1909 }
1910
1911 md = configurables_offset.to_be_bytes();
1912 }
1913
1914 if let BuildTarget::Fuel = pkg.target {
1916 set_bytecode_configurables_offset(&mut compiled, &md);
1917 }
1918
1919 metrics.bytecode_size = compiled.bytecode.len();
1920 metrics.decl_engine = engines.de().metrics();
1921
1922 let bytecode = BuiltPackageBytecode {
1923 bytes: compiled.bytecode,
1924 entries,
1925 };
1926
1927 let compiled_package = CompiledPackage {
1928 source_map: source_map.clone(),
1929 program_abi,
1930 storage_slots,
1931 tree_type,
1932 bytecode,
1933 namespace: typed_program.namespace.current_package_ref().clone(),
1934 warnings,
1935 metrics,
1936 };
1937
1938 if sway_build_config.profile {
1939 report_assembly_information(&asm, &compiled_package);
1940 }
1941
1942 Ok(compiled_package)
1943}
1944
1945fn report_assembly_information(
1947 compiled_asm: &sway_core::CompiledAsm,
1948 compiled_package: &CompiledPackage,
1949) {
1950 let mut bytes = compiled_package.bytecode.bytes.clone();
1952
1953 let data_offset = u64::from_be_bytes(
1955 bytes
1956 .iter()
1957 .skip(8)
1958 .take(8)
1959 .cloned()
1960 .collect::<Vec<_>>()
1961 .try_into()
1962 .unwrap(),
1963 );
1964 let data_section_size = bytes.len() as u64 - data_offset;
1965
1966 bytes.truncate(data_offset as usize);
1968
1969 fn calculate_entry_size(entry: &sway_core::asm_generation::Entry) -> u64 {
1973 match &entry.value {
1974 sway_core::asm_generation::Datum::Byte(value) => std::mem::size_of_val(value) as u64,
1975
1976 sway_core::asm_generation::Datum::Word(value) => std::mem::size_of_val(value) as u64,
1977
1978 sway_core::asm_generation::Datum::ByteArray(bytes)
1979 | sway_core::asm_generation::Datum::Slice(bytes) => {
1980 if bytes.len() % 8 == 0 {
1981 bytes.len() as u64
1982 } else {
1983 ((bytes.len() + 7) & 0xfffffff8_usize) as u64
1984 }
1985 }
1986
1987 sway_core::asm_generation::Datum::Collection(items) => {
1988 items.iter().map(calculate_entry_size).sum()
1989 }
1990 }
1991 }
1992
1993 let asm_information = sway_core::asm_generation::AsmInformation {
1995 bytecode_size: bytes.len() as _,
1996 data_section: sway_core::asm_generation::DataSectionInformation {
1997 size: data_section_size,
1998 used: compiled_asm
1999 .finalized_asm
2000 .data_section
2001 .iter_all_entries()
2002 .map(|entry| calculate_entry_size(&entry))
2003 .sum(),
2004 value_pairs: compiled_asm
2005 .finalized_asm
2006 .data_section
2007 .iter_all_entries()
2008 .collect(),
2009 },
2010 };
2011
2012 println!(
2014 "/dyno info {}",
2015 serde_json::to_string(&asm_information).unwrap()
2016 );
2017}
2018
2019impl PkgEntry {
2020 pub fn is_test(&self) -> bool {
2022 self.kind.test().is_some()
2023 }
2024
2025 fn from_finalized_entry(finalized_entry: &FinalizedEntry, engines: &Engines) -> Result<Self> {
2026 let pkg_entry_kind = match &finalized_entry.test_decl_ref {
2027 Some(test_decl_ref) => {
2028 let pkg_test_entry = PkgTestEntry::from_decl(test_decl_ref, engines)?;
2029 PkgEntryKind::Test(pkg_test_entry)
2030 }
2031 None => PkgEntryKind::Main,
2032 };
2033
2034 Ok(Self {
2035 finalized: finalized_entry.clone(),
2036 kind: pkg_entry_kind,
2037 })
2038 }
2039}
2040
2041impl PkgEntryKind {
2042 pub fn test(&self) -> Option<&PkgTestEntry> {
2044 match self {
2045 PkgEntryKind::Test(test) => Some(test),
2046 _ => None,
2047 }
2048 }
2049}
2050
2051impl PkgTestEntry {
2052 fn from_decl(decl_ref: &DeclRefFunction, engines: &Engines) -> Result<Self> {
2053 fn get_invalid_revert_code_error_msg(
2054 test_function_name: &Ident,
2055 should_revert_arg: &AttributeArg,
2056 ) -> String {
2057 format!("Invalid revert code for test \"{}\".\nA revert code must be a string containing a \"u64\", e.g.: \"42\".\nThe invalid revert code was: {}.",
2058 test_function_name,
2059 should_revert_arg.value.as_ref().expect("`get_string_opt` returned either a value or an error, which means that the invalid value must exist").span().as_str(),
2060 )
2061 }
2062
2063 let span = decl_ref.span();
2064 let test_function_decl = engines.de().get_function(decl_ref);
2065
2066 let Some(test_attr) = test_function_decl.attributes.test() else {
2067 unreachable!("`test_function_decl` is guaranteed to be a test function and it must have a `#[test]` attribute");
2068 };
2069
2070 let pass_condition = match test_attr
2071 .args
2072 .iter()
2073 .rfind(|arg| arg.is_test_should_revert())
2075 {
2076 Some(should_revert_arg) => {
2077 match should_revert_arg.get_string_opt(&Handler::default()) {
2078 Ok(should_revert_arg_value) => TestPassCondition::ShouldRevert(
2079 should_revert_arg_value
2080 .map(|val| val.parse::<u64>())
2081 .transpose()
2082 .map_err(|_| {
2083 anyhow!(get_invalid_revert_code_error_msg(
2084 &test_function_decl.name,
2085 should_revert_arg
2086 ))
2087 })?,
2088 ),
2089 Err(_) => bail!(get_invalid_revert_code_error_msg(
2090 &test_function_decl.name,
2091 should_revert_arg
2092 )),
2093 }
2094 }
2095 None => TestPassCondition::ShouldNotRevert,
2096 };
2097
2098 let file_path =
2099 Arc::new(engines.se().get_path(span.source_id().ok_or_else(|| {
2100 anyhow!("Missing span for test \"{}\".", test_function_decl.name)
2101 })?));
2102 Ok(Self {
2103 pass_condition,
2104 span,
2105 file_path,
2106 })
2107 }
2108}
2109
2110pub const SWAY_BIN_HASH_SUFFIX: &str = "-bin-hash";
2113
2114pub const SWAY_BIN_ROOT_SUFFIX: &str = "-bin-root";
2117
2118fn build_profile_from_opts(
2120 build_profiles: &HashMap<String, BuildProfile>,
2121 build_options: &BuildOpts,
2122) -> Result<BuildProfile> {
2123 let BuildOpts {
2124 pkg,
2125 print,
2126 time_phases,
2127 profile: profile_opt,
2128 build_profile,
2129 release,
2130 metrics_outfile,
2131 tests,
2132 error_on_warnings,
2133 dump,
2134 ..
2135 } = build_options;
2136
2137 let selected_profile_name = match release {
2138 true => BuildProfile::RELEASE,
2139 false => build_profile,
2140 };
2141
2142 let mut profile = build_profiles
2144 .get(selected_profile_name)
2145 .cloned()
2146 .unwrap_or_else(|| {
2147 println_warning(&format!(
2148 "The provided profile option {selected_profile_name} is not present in the manifest file. \
2149 Using default profile."
2150 ));
2151 BuildProfile::default()
2152 });
2153 profile.name = selected_profile_name.into();
2154 profile.dump = dump.clone();
2155 profile.print_ast |= print.ast;
2156 if profile.print_dca_graph.is_none() {
2157 profile.print_dca_graph.clone_from(&print.dca_graph);
2158 }
2159 if profile.print_dca_graph_url_format.is_none() {
2160 profile
2161 .print_dca_graph_url_format
2162 .clone_from(&print.dca_graph_url_format);
2163 }
2164 profile.print_ir |= print.ir.clone();
2165 profile.print_asm |= print.asm;
2166 profile.print_bytecode |= print.bytecode;
2167 profile.print_bytecode_spans |= print.bytecode_spans;
2168 profile.terse |= pkg.terse;
2169 profile.time_phases |= time_phases;
2170 profile.profile |= profile_opt;
2171 if profile.metrics_outfile.is_none() {
2172 profile.metrics_outfile.clone_from(metrics_outfile);
2173 }
2174 profile.include_tests |= tests;
2175 profile.error_on_warnings |= error_on_warnings;
2176
2177 Ok(profile)
2178}
2179
2180fn profile_target_string(profile_name: &str, build_target: &BuildTarget) -> String {
2182 let mut targets = vec![format!("{build_target}")];
2183 match profile_name {
2184 BuildProfile::DEBUG => targets.insert(0, "unoptimized".into()),
2185 BuildProfile::RELEASE => targets.insert(0, "optimized".into()),
2186 _ => {}
2187 };
2188 format!("{profile_name} [{}] target(s)", targets.join(" + "))
2189}
2190pub fn format_bytecode_size(bytes_len: usize) -> String {
2192 let size = Byte::from_u64(bytes_len as u64);
2193 let adjusted_byte = size.get_appropriate_unit(UnitType::Decimal);
2194 adjusted_byte.to_string()
2195}
2196
2197fn is_contract_dependency(graph: &Graph, node: NodeIx) -> bool {
2199 graph
2200 .edges_directed(node, Direction::Incoming)
2201 .any(|e| matches!(e.weight().kind, DepKind::Contract { .. }))
2202}
2203
2204pub fn build_with_options(
2206 build_options: &BuildOpts,
2207 callback_handler: Option<Box<dyn Observer>>,
2208) -> Result<Built> {
2209 let BuildOpts {
2210 hex_outfile,
2211 minify,
2212 binary_outfile,
2213 debug_outfile,
2214 pkg,
2215 build_target,
2216 member_filter,
2217 experimental,
2218 no_experimental,
2219 no_output,
2220 ..
2221 } = &build_options;
2222
2223 let current_dir = std::env::current_dir()?;
2224 let path = &build_options
2225 .pkg
2226 .path
2227 .as_ref()
2228 .map_or_else(|| current_dir, PathBuf::from);
2229
2230 println_action_green("Building", &path.display().to_string());
2231
2232 let build_plan = BuildPlan::from_pkg_opts(&build_options.pkg)?;
2233 let graph = build_plan.graph();
2234 let manifest_map = build_plan.manifest_map();
2235
2236 let curr_manifest = manifest_map
2239 .values()
2240 .find(|&pkg_manifest| pkg_manifest.dir() == path);
2241 let build_profiles: HashMap<String, BuildProfile> = build_plan.build_profiles().collect();
2242 let build_profile = build_profile_from_opts(&build_profiles, build_options)?;
2244 let outputs = match curr_manifest {
2246 Some(pkg_manifest) => std::iter::once(
2247 build_plan
2248 .find_member_index(&pkg_manifest.project.name)
2249 .ok_or_else(|| anyhow!("Cannot found project node in the graph"))?,
2250 )
2251 .collect(),
2252 None => build_plan.member_nodes().collect(),
2253 };
2254
2255 let outputs = member_filter.filter_outputs(&build_plan, outputs);
2256
2257 let mut built_workspace = Vec::new();
2259 let build_start = std::time::Instant::now();
2260 let built_packages = build(
2261 &build_plan,
2262 *build_target,
2263 &build_profile,
2264 &outputs,
2265 experimental,
2266 no_experimental,
2267 callback_handler,
2268 )?;
2269 let output_dir = pkg.output_directory.as_ref().map(PathBuf::from);
2270 let total_size = built_packages
2271 .iter()
2272 .map(|(_, pkg)| pkg.bytecode.bytes.len())
2273 .sum::<usize>();
2274
2275 println_action_green(
2276 "Finished",
2277 &format!(
2278 "{} [{}] in {:.2}s",
2279 profile_target_string(&build_profile.name, build_target),
2280 format_bytecode_size(total_size),
2281 build_start.elapsed().as_secs_f32()
2282 ),
2283 );
2284 for (node_ix, built_package) in built_packages {
2285 print_pkg_summary_header(&built_package);
2286 let pinned = &graph[node_ix];
2287 let pkg_manifest = manifest_map
2288 .get(&pinned.id())
2289 .ok_or_else(|| anyhow!("Couldn't find member manifest for {}", pinned.name))?;
2290 let output_dir = output_dir.clone().unwrap_or_else(|| {
2291 default_output_directory(pkg_manifest.dir()).join(&build_profile.name)
2292 });
2293 if let Some(outfile) = &binary_outfile {
2295 built_package.write_bytecode(outfile.as_ref())?;
2296 }
2297 if debug_outfile.is_some() || build_profile.name == BuildProfile::DEBUG {
2299 let debug_path = debug_outfile
2300 .as_ref()
2301 .map(|p| output_dir.join(p))
2302 .unwrap_or_else(|| output_dir.join("debug_symbols.obj"));
2303 built_package.write_debug_info(&debug_path)?;
2304 }
2305
2306 if let Some(hex_path) = hex_outfile {
2307 let hexfile_path = output_dir.join(hex_path);
2308 built_package.write_hexcode(&hexfile_path)?;
2309 }
2310
2311 if !no_output {
2312 built_package.write_output(minify, &pkg_manifest.project.name, &output_dir)?;
2313 }
2314
2315 built_workspace.push(Arc::new(built_package));
2316 }
2317
2318 match curr_manifest {
2319 Some(pkg_manifest) => {
2320 let built_pkg = built_workspace
2321 .into_iter()
2322 .find(|pkg| pkg.descriptor.manifest_file == *pkg_manifest)
2323 .expect("package didn't exist in workspace");
2324 Ok(Built::Package(built_pkg))
2325 }
2326 None => Ok(Built::Workspace(built_workspace)),
2327 }
2328}
2329
2330fn print_pkg_summary_header(built_pkg: &BuiltPackage) {
2331 let prog_ty_str = forc_util::program_type_str(&built_pkg.tree_type);
2332 let padded_ty_str = format!("{prog_ty_str:>10}");
2336 let padding = &padded_ty_str[..padded_ty_str.len() - prog_ty_str.len()];
2337 let ty_ansi = ansiterm::Colour::Green.bold().paint(prog_ty_str);
2338 let name_ansi = ansiterm::Style::new()
2339 .bold()
2340 .paint(&built_pkg.descriptor.name);
2341 debug!("{padding}{ty_ansi} {name_ansi}");
2342}
2343
2344pub fn contract_id(
2346 bytecode: &[u8],
2347 mut storage_slots: Vec<StorageSlot>,
2348 salt: &fuel_tx::Salt,
2349) -> ContractId {
2350 let contract = Contract::from(bytecode);
2352 storage_slots.sort();
2353 let state_root = Contract::initial_state_root(storage_slots.iter());
2354 Contract::id(salt, &contract.root(), &state_root)
2355}
2356
2357fn validate_contract_deps(graph: &Graph) -> Result<()> {
2359 for node in graph.node_indices() {
2362 let pkg = &graph[node];
2363 let name = pkg.name.clone();
2364 let salt_declarations: HashSet<fuel_tx::Salt> = graph
2365 .edges_directed(node, Direction::Incoming)
2366 .filter_map(|e| match e.weight().kind {
2367 DepKind::Library => None,
2368 DepKind::Contract { salt } => Some(salt),
2369 })
2370 .collect();
2371 if salt_declarations.len() > 1 {
2372 bail!(
2373 "There are conflicting salt declarations for contract dependency named: {}\nDeclared salts: {:?}",
2374 name,
2375 salt_declarations,
2376 )
2377 }
2378 }
2379 Ok(())
2380}
2381
2382pub fn build(
2388 plan: &BuildPlan,
2389 target: BuildTarget,
2390 profile: &BuildProfile,
2391 outputs: &HashSet<NodeIx>,
2392 experimental: &[sway_features::Feature],
2393 no_experimental: &[sway_features::Feature],
2394 callback_handler: Option<Box<dyn Observer>>,
2395) -> anyhow::Result<Vec<(NodeIx, BuiltPackage)>> {
2396 let mut built_packages = Vec::new();
2397
2398 let required: HashSet<NodeIx> = outputs
2399 .iter()
2400 .flat_map(|output_node| plan.node_deps(*output_node))
2401 .collect();
2402
2403 let engines = Engines::default();
2404 if let Some(callbacks) = callback_handler {
2405 engines.obs().set_observer(callbacks);
2406 }
2407
2408 let include_tests = profile.include_tests;
2409
2410 let mut contract_id_value: Option<ContractIdConst> = None;
2413
2414 let mut lib_namespace_map = HashMap::default();
2415 let mut compiled_contract_deps = HashMap::new();
2416
2417 for &node in plan
2418 .compilation_order
2419 .iter()
2420 .filter(|node| required.contains(node))
2421 {
2422 let mut source_map = SourceMap::new();
2423 let pkg = &plan.graph()[node];
2424 let manifest = &plan.manifest_map()[&pkg.id()];
2425 let program_ty = manifest.program_type().ok();
2426 let dbg_generation = match (profile.is_release(), manifest.project.force_dbg_in_release) {
2427 (true, Some(true)) | (false, _) => DbgGeneration::Full,
2428 (true, _) => DbgGeneration::None,
2429 };
2430
2431 print_compiling(
2432 program_ty.as_ref(),
2433 &pkg.name,
2434 &pkg.source.display_compiling(manifest.dir()),
2435 );
2436
2437 let experimental = ExperimentalFeatures::new(
2438 &manifest.project.experimental,
2439 experimental,
2440 no_experimental,
2441 )
2442 .map_err(|err| anyhow!("{err}"))?;
2443
2444 let descriptor = PackageDescriptor {
2445 name: pkg.name.clone(),
2446 target,
2447 pinned: pkg.clone(),
2448 manifest_file: manifest.clone(),
2449 };
2450
2451 let fail = |infos, warnings, errors| {
2452 print_on_failure(
2453 engines.se(),
2454 profile.terse,
2455 infos,
2456 warnings,
2457 errors,
2458 profile.reverse_results,
2459 );
2460 bail!("Failed to compile {}", pkg.name);
2461 };
2462
2463 let is_contract_dependency = is_contract_dependency(plan.graph(), node);
2464 let bytecode_without_tests = if (include_tests
2467 && matches!(manifest.program_type(), Ok(TreeType::Contract)))
2468 || is_contract_dependency
2469 {
2470 let profile = BuildProfile {
2477 include_tests: false,
2478 ..profile.clone()
2479 };
2480
2481 let program_id = engines
2482 .se()
2483 .get_or_create_program_id_from_manifest_path(&manifest.entry_path());
2484
2485 let dep_namespace = match dependency_namespace(
2488 &lib_namespace_map,
2489 &compiled_contract_deps,
2490 plan.graph(),
2491 node,
2492 &engines,
2493 None,
2494 program_id,
2495 experimental,
2496 dbg_generation,
2497 ) {
2498 Ok(o) => o,
2499 Err(errs) => return fail(&[], &[], &errs),
2500 };
2501
2502 let compiled_without_tests = compile(
2503 &descriptor,
2504 &profile,
2505 &engines,
2506 dep_namespace,
2507 &mut source_map,
2508 experimental,
2509 dbg_generation,
2510 )?;
2511
2512 if let Some(outfile) = profile.metrics_outfile {
2513 let path = Path::new(&outfile);
2514 let metrics_json = serde_json::to_string_pretty(&compiled_without_tests.metrics)
2515 .expect("JSON serialization failed");
2516 fs::write(path, metrics_json)?;
2517 }
2518
2519 if is_contract_dependency {
2524 let compiled_contract_dep = CompiledContractDependency {
2525 bytecode: compiled_without_tests.bytecode.bytes.clone(),
2526 storage_slots: compiled_without_tests.storage_slots.clone(),
2527 };
2528 compiled_contract_deps.insert(node, compiled_contract_dep);
2529 } else {
2530 let contract_id = contract_id(
2532 &compiled_without_tests.bytecode.bytes,
2533 compiled_without_tests.storage_slots.clone(),
2534 &fuel_tx::Salt::zeroed(),
2535 );
2536 contract_id_value = Some(format!("0x{contract_id}"));
2538 }
2539 Some(compiled_without_tests.bytecode)
2540 } else {
2541 None
2542 };
2543
2544 let profile = if !plan.member_nodes().any(|member| member == node) {
2546 BuildProfile {
2547 include_tests: false,
2548 ..profile.clone()
2549 }
2550 } else {
2551 profile.clone()
2552 };
2553
2554 let program_id = engines
2555 .se()
2556 .get_or_create_program_id_from_manifest_path(&manifest.entry_path());
2557
2558 let dep_namespace = match dependency_namespace(
2560 &lib_namespace_map,
2561 &compiled_contract_deps,
2562 plan.graph(),
2563 node,
2564 &engines,
2565 contract_id_value.clone(),
2566 program_id,
2567 experimental,
2568 dbg_generation,
2569 ) {
2570 Ok(o) => o,
2571 Err(errs) => {
2572 print_on_failure(
2573 engines.se(),
2574 profile.terse,
2575 &[],
2576 &[],
2577 &errs,
2578 profile.reverse_results,
2579 );
2580 bail!("Failed to compile {}", pkg.name);
2581 }
2582 };
2583
2584 let compiled = compile(
2585 &descriptor,
2586 &profile,
2587 &engines,
2588 dep_namespace,
2589 &mut source_map,
2590 experimental,
2591 dbg_generation,
2592 )?;
2593
2594 if let Some(outfile) = profile.metrics_outfile {
2595 let path = Path::new(&outfile);
2596 let metrics_json =
2597 serde_json::to_string_pretty(&compiled.metrics).expect("JSON serialization failed");
2598 fs::write(path, metrics_json)?;
2599 }
2600
2601 if let TreeType::Library = compiled.tree_type {
2602 lib_namespace_map.insert(node, compiled.namespace);
2603 }
2604 source_map.insert_dependency(descriptor.manifest_file.dir());
2605
2606 let built_pkg = BuiltPackage {
2607 descriptor,
2608 program_abi: compiled.program_abi,
2609 storage_slots: compiled.storage_slots,
2610 source_map: compiled.source_map,
2611 tree_type: compiled.tree_type,
2612 bytecode: compiled.bytecode,
2613 warnings: compiled.warnings,
2614 bytecode_without_tests,
2615 };
2616
2617 if outputs.contains(&node) {
2618 built_packages.push((node, built_pkg));
2619 }
2620 }
2621
2622 Ok(built_packages)
2623}
2624
2625#[allow(clippy::too_many_arguments)]
2629pub fn check(
2630 plan: &BuildPlan,
2631 build_target: BuildTarget,
2632 terse_mode: bool,
2633 lsp_mode: Option<LspConfig>,
2634 include_tests: bool,
2635 engines: &Engines,
2636 retrigger_compilation: Option<Arc<AtomicBool>>,
2637 experimental: &[sway_features::Feature],
2638 no_experimental: &[sway_features::Feature],
2639 dbg_generation: sway_core::DbgGeneration,
2640) -> anyhow::Result<Vec<(Option<Programs>, Handler)>> {
2641 let mut lib_namespace_map = HashMap::default();
2642 let mut source_map = SourceMap::new();
2643 let compiled_contract_deps = HashMap::new();
2645
2646 let mut results = vec![];
2647 for (idx, &node) in plan.compilation_order.iter().enumerate() {
2648 let pkg = &plan.graph[node];
2649 let manifest = &plan.manifest_map()[&pkg.id()];
2650
2651 let experimental = ExperimentalFeatures::new(
2652 &manifest.project.experimental,
2653 experimental,
2654 no_experimental,
2655 )
2656 .map_err(|err| anyhow!("{err}"))?;
2657
2658 let contract_id_value = if lsp_mode.is_some() && (idx == plan.compilation_order.len() - 1) {
2661 const DUMMY_CONTRACT_ID: &str =
2669 "0x0000000000000000000000000000000000000000000000000000000000000000";
2670 Some(DUMMY_CONTRACT_ID.to_string())
2671 } else {
2672 None
2673 };
2674
2675 let program_id = engines
2676 .se()
2677 .get_or_create_program_id_from_manifest_path(&manifest.entry_path());
2678
2679 let dep_namespace = dependency_namespace(
2680 &lib_namespace_map,
2681 &compiled_contract_deps,
2682 &plan.graph,
2683 node,
2684 engines,
2685 contract_id_value,
2686 program_id,
2687 experimental,
2688 dbg_generation,
2689 )
2690 .expect("failed to create dependency namespace");
2691
2692 let profile = BuildProfile {
2693 terse: terse_mode,
2694 ..BuildProfile::debug()
2695 };
2696
2697 let build_config = sway_build_config(
2698 manifest.dir(),
2699 &manifest.entry_path(),
2700 build_target,
2701 &profile,
2702 dbg_generation,
2703 )?
2704 .with_include_tests(include_tests)
2705 .with_lsp_mode(lsp_mode.clone());
2706
2707 let input = manifest.entry_string()?;
2708 let handler = Handler::default();
2709 let programs_res = sway_core::compile_to_ast(
2710 &handler,
2711 engines,
2712 input,
2713 dep_namespace,
2714 Some(&build_config),
2715 &pkg.name,
2716 retrigger_compilation.clone(),
2717 experimental,
2718 );
2719
2720 if retrigger_compilation
2721 .as_ref()
2722 .is_some_and(|b| b.load(std::sync::atomic::Ordering::SeqCst))
2723 {
2724 bail!("compilation was retriggered")
2725 }
2726
2727 let programs = match programs_res.as_ref() {
2728 Ok(programs) => programs,
2729 _ => {
2730 results.push((programs_res.ok(), handler));
2731 return Ok(results);
2732 }
2733 };
2734
2735 if let Ok(typed_program) = programs.typed.as_ref() {
2736 if let TreeType::Library = typed_program.kind.tree_type() {
2737 let mut lib_namespace = typed_program.namespace.current_package_ref().clone();
2738 lib_namespace.root_module_mut().set_span(
2739 Span::new(
2740 manifest.entry_string()?,
2741 0,
2742 0,
2743 Some(engines.se().get_source_id(&manifest.entry_path())),
2744 )
2745 .unwrap(),
2746 );
2747 lib_namespace_map.insert(node, lib_namespace);
2748 }
2749 source_map.insert_dependency(manifest.dir());
2750 } else {
2751 results.push((programs_res.ok(), handler));
2752 return Ok(results);
2753 }
2754 results.push((programs_res.ok(), handler));
2755 }
2756
2757 if results.is_empty() {
2758 bail!("unable to check sway program: build plan contains no packages")
2759 }
2760
2761 Ok(results)
2762}
2763
2764pub fn manifest_file_missing<P: AsRef<Path>>(dir: P) -> anyhow::Error {
2766 let message = format!(
2767 "could not find `{}` in `{}` or any parent directory",
2768 constants::MANIFEST_FILE_NAME,
2769 dir.as_ref().display()
2770 );
2771 Error::msg(message)
2772}
2773
2774pub fn parsing_failed(project_name: &str, errors: &[CompileError]) -> anyhow::Error {
2776 let error = errors
2777 .iter()
2778 .map(|e| format!("{e}"))
2779 .collect::<Vec<String>>()
2780 .join("\n");
2781 let message = format!("Parsing {project_name} failed: \n{error}");
2782 Error::msg(message)
2783}
2784
2785pub fn wrong_program_type(
2787 project_name: &str,
2788 expected_types: &[TreeType],
2789 parse_type: TreeType,
2790) -> anyhow::Error {
2791 let message = format!("{project_name} is not a '{expected_types:?}' it is a '{parse_type:?}'");
2792 Error::msg(message)
2793}
2794
2795pub fn fuel_core_not_running(node_url: &str) -> anyhow::Error {
2797 let message = format!("could not get a response from node at the URL {node_url}. Start a node with `fuel-core`. See https://github.com/FuelLabs/fuel-core#running for more information");
2798 Error::msg(message)
2799}
2800
2801#[cfg(test)]
2802mod test {
2803 use super::*;
2804 use regex::Regex;
2805 use tempfile::NamedTempFile;
2806
2807 fn setup_build_plan() -> BuildPlan {
2808 let current_dir = env!("CARGO_MANIFEST_DIR");
2809 let manifest_dir = PathBuf::from(current_dir)
2810 .parent()
2811 .unwrap()
2812 .join("test/src/e2e_vm_tests/test_programs/should_pass/forc/workspace_building/");
2813 let manifest_file = ManifestFile::from_dir(manifest_dir).unwrap();
2814 let member_manifests = manifest_file.member_manifests().unwrap();
2815 let lock_path = manifest_file.lock_path().unwrap();
2816 BuildPlan::from_lock_and_manifests(
2817 &lock_path,
2818 &member_manifests,
2819 false,
2820 false,
2821 &IPFSNode::default(),
2822 )
2823 .unwrap()
2824 }
2825
2826 #[test]
2827 fn test_root_pkg_order() {
2828 let build_plan = setup_build_plan();
2829 let graph = build_plan.graph();
2830 let order: Vec<String> = build_plan
2831 .member_nodes()
2832 .map(|order| graph[order].name.clone())
2833 .collect();
2834 assert_eq!(order, vec!["test_lib", "test_contract", "test_script"])
2835 }
2836
2837 #[test]
2838 fn test_visualize_with_url_prefix() {
2839 let build_plan = setup_build_plan();
2840 let result = build_plan.visualize(Some("some-prefix::".to_string()));
2841 let re = Regex::new(r#"digraph \{
2842 0 \[ label = "std" shape = box URL = "some-prefix::[[:ascii:]]+/sway-lib-std/Forc.toml"\]
2843 1 \[ label = "test_contract" shape = box URL = "some-prefix::/[[:ascii:]]+/test_contract/Forc.toml"\]
2844 2 \[ label = "test_lib" shape = box URL = "some-prefix::/[[:ascii:]]+/test_lib/Forc.toml"\]
2845 3 \[ label = "test_script" shape = box URL = "some-prefix::/[[:ascii:]]+/test_script/Forc.toml"\]
2846 3 -> 2 \[ \]
2847 3 -> 0 \[ \]
2848 3 -> 1 \[ \]
2849 1 -> 2 \[ \]
2850 1 -> 0 \[ \]
2851\}
2852"#).unwrap();
2853 dbg!(&result);
2854 assert!(!re.find(result.as_str()).unwrap().is_empty());
2855 }
2856
2857 #[test]
2858 fn test_visualize_without_prefix() {
2859 let build_plan = setup_build_plan();
2860 let result = build_plan.visualize(None);
2861 let expected = r#"digraph {
2862 0 [ label = "std" shape = box ]
2863 1 [ label = "test_contract" shape = box ]
2864 2 [ label = "test_lib" shape = box ]
2865 3 [ label = "test_script" shape = box ]
2866 3 -> 2 [ ]
2867 3 -> 0 [ ]
2868 3 -> 1 [ ]
2869 1 -> 2 [ ]
2870 1 -> 0 [ ]
2871}
2872"#;
2873 assert_eq!(expected, result);
2874 }
2875
2876 #[test]
2877 fn test_write_hexcode() -> Result<()> {
2878 let temp_file = NamedTempFile::new()?;
2880 let path = temp_file.path();
2881
2882 let current_dir = env!("CARGO_MANIFEST_DIR");
2883 let manifest_dir = PathBuf::from(current_dir).parent().unwrap().join(
2884 "test/src/e2e_vm_tests/test_programs/should_pass/forc/workspace_building/test_contract",
2885 );
2886
2887 let test_bytecode = vec![0x01, 0x02, 0x03, 0x04];
2889 let built_package = BuiltPackage {
2890 descriptor: PackageDescriptor {
2891 name: "test_package".to_string(),
2892 target: BuildTarget::Fuel,
2893 pinned: Pinned {
2894 name: "built_test".to_owned(),
2895 source: source::Pinned::MEMBER,
2896 },
2897 manifest_file: PackageManifestFile::from_dir(manifest_dir)?,
2898 },
2899 program_abi: ProgramABI::Fuel(fuel_abi_types::abi::program::ProgramABI {
2900 program_type: "".to_owned(),
2901 spec_version: "".into(),
2902 encoding_version: "".into(),
2903 concrete_types: vec![],
2904 metadata_types: vec![],
2905 functions: vec![],
2906 configurables: None,
2907 logged_types: None,
2908 messages_types: None,
2909 error_codes: None,
2910 panicking_calls: None,
2911 }),
2912 storage_slots: vec![],
2913 warnings: vec![],
2914 source_map: SourceMap::new(),
2915 tree_type: TreeType::Script,
2916 bytecode: BuiltPackageBytecode {
2917 bytes: test_bytecode,
2918 entries: vec![],
2919 },
2920 bytecode_without_tests: None,
2921 };
2922
2923 built_package.write_hexcode(path)?;
2925
2926 let contents = fs::read_to_string(path)?;
2928 let expected = r#"{"hex":"0x01020304"}"#;
2929 assert_eq!(contents, expected);
2930
2931 Ok(())
2932 }
2933}