Skip to main content

forc_pkg/
pkg.rs

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    /// The name specified on the left hand side of the `=` in a dependency declaration under
62    /// `[dependencies]` or `[contract-dependencies]` within a forc manifest.
63    ///
64    /// The name of a dependency may differ from the package name in the case that the dependency's
65    /// `package` field is specified.
66    ///
67    /// For example, in the following, `foo` is assumed to be both the package name and the dependency
68    /// name:
69    ///
70    /// ```toml
71    /// foo = { git = "https://github.com/owner/repo", branch = "master" }
72    /// ```
73    ///
74    /// In the following case however, `foo` is the package name, but the dependency name is `foo-alt`:
75    ///
76    /// ```toml
77    /// foo-alt = { git = "https://github.com/owner/repo", branch = "master", package = "foo" }
78    /// ```
79    pub name: String,
80    pub kind: DepKind,
81}
82
83#[derive(PartialEq, Eq, Clone, Debug)]
84pub enum DepKind {
85    /// The dependency is a library and declared under `[dependencies]`.
86    Library,
87    /// The dependency is a contract and declared under `[contract-dependencies]`.
88    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/// A unique ID for a pinned package.
97///
98/// The internal value is produced by hashing the package's name and `source::Pinned`.
99#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
100pub struct PinnedId(u64);
101
102/// The result of successfully compiling a package.
103#[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    /// `Some` for contract member builds where tests were included. This is
113    /// required so that we can deploy once instance of the contract (without
114    /// tests) with a valid contract ID before executing the tests as scripts.
115    ///
116    /// For non-contract members, this is always `None`.
117    pub bytecode_without_tests: Option<BuiltPackageBytecode>,
118}
119
120/// The package descriptors that a `BuiltPackage` holds so that the source used for building the
121/// package can be retrieved later on.
122#[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/// The bytecode associated with a built package along with its entry points.
131#[derive(Debug, Clone)]
132pub struct BuiltPackageBytecode {
133    pub bytes: Vec<u8>,
134    pub entries: Vec<PkgEntry>,
135}
136
137/// Represents a package entry point.
138#[derive(Debug, Clone)]
139pub struct PkgEntry {
140    pub finalized: FinalizedEntry,
141    pub kind: PkgEntryKind,
142}
143
144/// Data specific to each kind of package entry point.
145#[derive(Debug, Clone)]
146pub enum PkgEntryKind {
147    Main,
148    Test(PkgTestEntry),
149}
150
151/// The possible conditions for a test result to be considered "passing".
152#[derive(Debug, Clone)]
153pub enum TestPassCondition {
154    ShouldRevert(Option<u64>),
155    ShouldNotRevert,
156}
157
158/// Data specific to the test entry point.
159#[derive(Debug, Clone)]
160pub struct PkgTestEntry {
161    pub pass_condition: TestPassCondition,
162    pub span: Span,
163    pub file_path: Arc<PathBuf>,
164}
165
166/// The result of successfully compiling a workspace.
167pub type BuiltWorkspace = Vec<Arc<BuiltPackage>>;
168
169#[derive(Debug, Clone)]
170pub enum Built {
171    /// Represents a standalone package build.
172    Package(Arc<BuiltPackage>),
173    /// Represents a workspace build.
174    Workspace(BuiltWorkspace),
175}
176
177/// The result of the `compile` function, i.e. compiling a single package.
178pub 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
189/// Compiled contract dependency parts relevant to calculating a contract's ID.
190pub struct CompiledContractDependency {
191    pub bytecode: Vec<u8>,
192    pub storage_slots: Vec<StorageSlot>,
193}
194
195/// The set of compiled contract dependencies, provided to dependency namespace construction.
196pub type CompiledContractDeps = HashMap<NodeIx, CompiledContractDependency>;
197
198/// A package uniquely identified by name along with its source.
199#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Deserialize, Serialize)]
200pub struct Pkg {
201    /// The unique name of the package as declared in its manifest.
202    pub name: String,
203    /// Where the package is sourced from.
204    pub source: Source,
205}
206
207/// A package uniquely identified by name along with its pinned source.
208#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
209pub struct Pinned {
210    pub name: String,
211    pub source: source::Pinned,
212}
213
214/// Represents the full build plan for a project.
215#[derive(Clone, Debug)]
216pub struct BuildPlan {
217    graph: Graph,
218    manifest_map: ManifestMap,
219    compilation_order: Vec<NodeIx>,
220}
221
222/// Error returned upon failed parsing of `PinnedId::from_str`.
223#[derive(Clone, Debug)]
224pub struct PinnedIdParseError;
225
226#[derive(Default, Clone)]
227pub struct PkgOpts {
228    /// Path to the project, if not specified, current working directory will be used.
229    pub path: Option<String>,
230    /// Offline mode, prevents Forc from using the network when managing dependencies.
231    /// Meaning it will only try to use previously downloaded dependencies.
232    pub offline: bool,
233    /// Terse mode. Limited warning and error output.
234    pub terse: bool,
235    /// Requires that the Forc.lock file is up-to-date. If the lock file is missing, or it
236    /// needs to be updated, Forc will exit with an error
237    pub locked: bool,
238    /// The directory in which the sway compiler output artifacts are placed.
239    ///
240    /// By default, this is `<project-root>/out`.
241    pub output_directory: Option<String>,
242    /// The IPFS node to be used for fetching IPFS sources.
243    pub ipfs_node: IPFSNode,
244}
245
246#[derive(Default, Clone)]
247pub struct PrintOpts {
248    /// Print the generated Sway AST (Abstract Syntax Tree).
249    pub ast: bool,
250    /// Print the computed Sway DCA (Dead Code Analysis) graph to the specified path.
251    /// If not specified prints to stdout.
252    pub dca_graph: Option<String>,
253    /// Specifies the url format to be used in the generated dot file.
254    /// Variables {path}, {line} {col} can be used in the provided format.
255    /// An example for vscode would be: "vscode://file/{path}:{line}:{col}"
256    pub dca_graph_url_format: Option<String>,
257    /// Print the generated ASM.
258    pub asm: PrintAsm,
259    /// Print the bytecode. This is the final output of the compiler.
260    pub bytecode: bool,
261    /// Print the original source code together with bytecode.
262    pub bytecode_spans: bool,
263    /// Print the generated Sway IR (Intermediate Representation).
264    pub ir: IrCli,
265    /// Output build errors and warnings in reverse order.
266    pub reverse_order: bool,
267}
268
269#[derive(Default, Clone)]
270pub struct MinifyOpts {
271    /// By default the JSON for ABIs is formatted for human readability. By using this option JSON
272    /// output will be "minified", i.e. all on one line without whitespace.
273    pub json_abi: bool,
274    /// By default the JSON for initial storage slots is formatted for human readability. By using
275    /// this option JSON output will be "minified", i.e. all on one line without whitespace.
276    pub json_storage_slots: bool,
277}
278
279/// Represents a compiled contract ID as a pub const in a contract.
280type ContractIdConst = String;
281
282#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)]
283pub struct DumpOpts {
284    /// Dump all trait implementations for the given type name.
285    pub dump_impls: Option<String>,
286}
287
288/// The set of options provided to the `build` functions.
289#[derive(Default, Clone)]
290pub struct BuildOpts {
291    pub pkg: PkgOpts,
292    pub print: PrintOpts,
293    pub minify: MinifyOpts,
294    pub dump: DumpOpts,
295    /// If set, generates a JSON file containing the hex-encoded script binary.
296    pub hex_outfile: Option<String>,
297    /// If set, outputs a binary file representing the script bytes.
298    pub binary_outfile: Option<String>,
299    /// If set, outputs debug info to the provided file.
300    /// If the argument provided ends with .json, a JSON is emitted,
301    /// otherwise, an ELF file containing DWARF is emitted.
302    pub debug_outfile: Option<String>,
303    /// Build target to use.
304    pub build_target: BuildTarget,
305    /// Name of the build profile to use.
306    pub build_profile: String,
307    /// Use the release build profile.
308    /// The release profile can be customized in the manifest file.
309    pub release: bool,
310    /// Output the time elapsed over each part of the compilation process.
311    pub time_phases: bool,
312    /// Profile the build process.
313    pub profile: bool,
314    /// If set, outputs compilation metrics info in JSON format.
315    pub metrics_outfile: Option<String>,
316    /// Warnings must be treated as compiler errors.
317    pub error_on_warnings: bool,
318    /// Include all test functions within the build.
319    pub tests: bool,
320    /// The set of options to filter by member project kind.
321    pub member_filter: MemberFilter,
322    /// Set of enabled experimental flags
323    pub experimental: Vec<sway_features::Feature>,
324    /// Set of disabled experimental flags
325    pub no_experimental: Vec<sway_features::Feature>,
326    /// Do not output any build artifacts, e.g., bytecode, ABI JSON, etc.
327    pub no_output: bool,
328}
329
330/// The set of options to filter type of projects to build in a workspace.
331#[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    /// Returns a new `MemberFilter` that only builds scripts.
352    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    /// Returns a new `MemberFilter` that only builds contracts.
362    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    /// Returns a new `MemberFilter`, that only builds predicates.
372    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    /// Filter given target of output nodes according to the this `MemberFilter`.
382    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                // Since parser cannot recover for program type detection, for the scenarios that
396                // parser fails to parse the code, program type detection is not possible. So in
397                // failing to parse cases we should try to build at least until
398                // https://github.com/FuelLabs/sway/issues/3017 is fixed. Until then we should
399                // build those members because of two reasons:
400                //
401                // 1. The member could already be from the desired member type
402                // 2. If we do not try to build there is no way users can know there is a code
403                //    piece failing to be parsed in their workspace.
404                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    /// Return a `BuildOpts` with modified `tests` field.
420    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    /// Writes bytecode of the BuiltPackage to the given `path`.
436    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    /// Writes debug_info (source_map) of the BuiltPackage to the given `out_file`.
451    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            // TODO?
491            ProgramABI::MidenVM(()) => Ok(None),
492        }
493    }
494
495    /// Writes the ABI in JSON format to the given `path`.
496    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    /// Writes BuiltPackage to `output_dir`.
505    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        // Place build artifacts into the output directory.
515        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        // Additional ops required depending on the program type
530        match self.tree_type {
531            TreeType::Contract => {
532                // For contracts, emit a JSON file with all the initialized storage slots.
533                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                // Get the root hash of the bytecode for predicates and store the result in a file in the output directory
546                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                // hash the bytecode for scripts and store the result in a file in the output directory
557                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    /// Returns an iterator yielding all member built packages.
573    pub fn into_members<'a>(
574        &'a self,
575    ) -> Box<dyn Iterator<Item = (&'a Pinned, Arc<BuiltPackage>)> + 'a> {
576        // NOTE: Since pkg is a `Arc<_>`, pkg clones in this function are only reference
577        // increments. `BuiltPackage` struct does not get copied.`
578        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    /// Tries to retrieve the `Built` as a `BuiltPackage`.
593    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    /// Create a new build plan for the project from the build options provided.
603    ///
604    /// To do so, it tries to read the manifet file at the target path and creates the plan with
605    /// `BuildPlan::from_lock_and_manifest`.
606    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        // Check if we have members to build so that we are not trying to build an empty workspace.
618        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    /// Create a new build plan for the project by fetching and pinning all dependencies.
632    ///
633    /// To account for an existing lock file, use `from_lock_and_manifest` instead.
634    pub fn from_manifests(
635        manifests: &MemberManifestFiles,
636        offline: bool,
637        ipfs_node: &IPFSNode,
638    ) -> Result<Self> {
639        // Check toolchain version
640        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 the graph, since we constructed the graph from scratch the paths will not be a
645        // problem but the version check is still needed
646        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    /// Create a new build plan taking into account the state of both the PackageManifest and the existing
656    /// lock file if there is one.
657    ///
658    /// This will first attempt to load a build plan from the lock file and validate the resulting
659    /// graph using the current state of the PackageManifest.
660    ///
661    /// This includes checking if the [dependencies] or [patch] tables have changed and checking
662    /// the validity of the local path dependencies. If any changes are detected, the graph is
663    /// updated and any new packages that require fetching are fetched.
664    ///
665    /// The resulting build plan should always be in a valid state that is ready for building or
666    /// checking.
667    // TODO: Currently (if `--locked` isn't specified) this writes the updated lock directly. This
668    // probably should not be the role of the `BuildPlan` constructor - instead, we should return
669    // the manifest alongside some lock diff type that can be used to optionally write the updated
670    // lock file and print the diff.
671    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        // Check toolchain version
679        validate_version(manifests)?;
680        // Keep track of the cause for the new lock file if it turns out we need one.
681        let mut new_lock_cause = None;
682
683        // First, attempt to load the lock.
684        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        // Next, construct the package graph from the lock.
694        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        // Since the lock file was last created there are many ways in which it might have been
700        // invalidated. E.g. a package's manifest `[dependencies]` table might have changed, a user
701        // might have edited the `Forc.lock` file when they shouldn't have, a path dependency no
702        // longer exists at its specified location, etc. We must first remove all invalid nodes
703        // before we can determine what we need to fetch.
704        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        // We know that the remaining nodes have valid paths, otherwise they would have been
709        // removed. We can safely produce an initial `manifest_map`.
710        let mut manifest_map = graph_to_manifest_map(manifests, &graph)?;
711
712        // Attempt to fetch the remainder of the graph.
713        let _added = fetch_graph(manifests, offline, ipfs_node, &mut graph, &mut manifest_map)?;
714
715        // Determine the compilation order.
716        let compilation_order = compilation_order(&graph)?;
717
718        let plan = Self {
719            graph,
720            manifest_map,
721            compilation_order,
722        };
723
724        // Construct the new lock and check the diff.
725        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 there was some change in the lock file, write the new one and print the cause.
732        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    /// Produce an iterator yielding all contract dependencies of given node in the order of
761    /// compilation.
762    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    /// Produce an iterator yielding all workspace member nodes in order of compilation.
778    ///
779    /// In the case that this [BuildPlan] was constructed for a single package,
780    /// only that package's node will be yielded.
781    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    /// Produce an iterator yielding all workspace member pinned pkgs in order of compilation.
789    ///
790    /// In the case that this `BuildPlan` was constructed for a single package,
791    /// only that package's pinned pkg will be yielded.
792    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    /// View the build plan's compilation graph.
798    pub fn graph(&self) -> &Graph {
799        &self.graph
800    }
801
802    /// View the build plan's map of pinned package IDs to their associated manifest.
803    pub fn manifest_map(&self) -> &ManifestMap {
804        &self.manifest_map
805    }
806
807    /// The order in which nodes are compiled, determined via a toposort of the package graph.
808    pub fn compilation_order(&self) -> &[NodeIx] {
809        &self.compilation_order
810    }
811
812    /// Produce the node index of the member with the given name.
813    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    /// Produce an iterator yielding indices for the given node and its dependencies in BFS order.
819    pub fn node_deps(&self, n: NodeIx) -> impl '_ + Iterator<Item = NodeIx> {
820        let bfs = Bfs::new(&self.graph, n);
821        // Return an iterator yielding visitable nodes from the given node.
822        bfs.iter(&self.graph)
823    }
824
825    /// Produce an iterator yielding build profiles from the member nodes of this BuildPlan.
826    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    /// Returns a salt for the given pinned package if it is a contract and `None` for libraries.
837    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    /// Returns a [String] representing the build dependency graph in GraphViz DOT format.
855    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
877/// Given a graph and the known project name retrieved from the manifest, produce an iterator
878/// yielding any nodes from the graph that might potentially be a project node.
879fn 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
883/// Given a graph, find the project node.
884///
885/// This should be the only node that satisfies the following conditions:
886///
887/// - The package name matches `proj_name`
888/// - The node has no incoming edges, i.e. is not a dependency of another node.
889fn 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
900/// Checks if the toolchain version is in compliance with minimum implied by `manifest`.
901///
902/// If the `manifest` is a ManifestFile::Workspace, check all members of the workspace for version
903/// validation. Otherwise only the given package is checked.
904fn 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
911/// Check minimum forc version given in the package manifest file
912///
913/// If required minimum forc version is higher than current forc version return an error with
914/// upgrade instructions
915fn validate_pkg_version(pkg_manifest: &PackageManifestFile) -> Result<()> {
916    if let Some(min_forc_version) = &pkg_manifest.project.forc_version {
917        // Get the current version of the toolchain
918        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
938/// Validates the state of the pinned package graph against the given ManifestFile.
939///
940/// Returns the set of invalid dependency edges.
941fn 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 no member nodes, the graph is either empty or corrupted. Remove all edges.
952    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
965/// Recursively validate all dependencies of the given `node`.
966///
967/// Returns the set of invalid dependency edges.
968fn 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
994/// Check the validity of a node's dependency within the graph.
995///
996/// Returns the `ManifestFile` in the case that the dependency is valid.
997fn 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    // Check the validity of the dependency path, including its path root.
1008    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    // Ensure the manifest is accessible.
1017    let dep_manifest = PackageManifestFile::from_dir(&dep_path)?;
1018
1019    // Check that the dependency's source matches the entry in the parent manifest.
1020    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}
1034/// Part of dependency validation, any checks related to the dependency's manifest content.
1035fn 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    // Check if the dependency is either a library or a contract declared as a contract dependency
1042    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    // Ensure the name matches the manifest project name.
1053    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
1066/// Returns the canonical, local path to the given dependency node if it exists, `None` otherwise.
1067///
1068/// Also returns `Err` in the case that the dependency is a `Path` dependency and the path root is
1069/// invalid.
1070fn 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            // Check if the path is directly from the dependency.
1084            if let Some(path) = node_manifest.dep_path(dep_name) {
1085                if path.exists() {
1086                    return Ok(path);
1087                }
1088            }
1089
1090            // Otherwise, check if it comes from a patch.
1091            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            // If a node has a root dependency it is a member of the workspace.
1111            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
1120/// Remove the given set of dependency edges from the `graph`.
1121///
1122/// Also removes all nodes that are no longer connected to any root node as a result.
1123fn remove_deps(
1124    graph: &mut Graph,
1125    member_names: &HashSet<String>,
1126    edges_to_remove: &BTreeSet<EdgeIx>,
1127) {
1128    // Retrieve the project nodes for workspace members.
1129    let member_nodes: HashSet<_> = member_nodes(graph)
1130        .filter(|&n| member_names.contains(&graph[n].name.to_string()))
1131        .collect();
1132
1133    // Before removing edges, sort the nodes in order of dependency for the node removal pass.
1134    let node_removal_order = if let Ok(nodes) = petgraph::algo::toposort(&*graph, None) {
1135        nodes
1136    } else {
1137        // If toposort fails the given graph is cyclic, so invalidate everything.
1138        graph.clear();
1139        return;
1140    };
1141
1142    // Remove the given set of dependency edges.
1143    for &edge in edges_to_remove {
1144        graph.remove_edge(edge);
1145    }
1146
1147    // Remove all nodes that are no longer connected to any project node as a result.
1148    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    /// Retrieve the unique ID for the pinned package.
1165    ///
1166    /// The internal value is produced by hashing the package's name and `source::Pinned`.
1167    pub fn id(&self) -> PinnedId {
1168        PinnedId::new(&self.name, &self.source)
1169    }
1170
1171    /// Retrieve the unpinned version of this source.
1172    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    /// Hash the given name and pinned source to produce a unique pinned package ID.
1181    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        // Format the inner `u64` as hex.
1201        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
1214/// The `pkg::Graph` is of *a -> b* where *a* depends on *b*. We can determine compilation order by
1215/// performing a toposort of the graph with reversed edges. The resulting order ensures all
1216/// dependencies are always compiled before their dependents.
1217pub 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        // Find the strongly connected components.
1221        // If the vector has an element with length > 1, it contains a cyclic path.
1222        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                // We are sure that there is an element in cyclic_path vec.
1228                let starting_node = &graph[*cyclic_path.last().unwrap()];
1229
1230                // Adding first node of the path
1231                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
1246/// Given a graph collects ManifestMap while taking in to account that manifest can be a
1247/// ManifestFile::Workspace. In the case of a workspace each pkg manifest map is collected and
1248/// their added node lists are merged.
1249fn 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
1258/// Given a graph of pinned packages and the project manifest, produce a map containing the
1259/// manifest of for every node in the graph.
1260///
1261/// Assumes the given `graph` only contains valid dependencies (see `validate_graph`).
1262///
1263/// `pkg_graph_to_manifest_map` starts from each node (which corresponds to the given proj_manifest)
1264/// and visits children to collect their manifest files.
1265fn 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    // Traverse the graph from the project node.
1276    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    // Resolve all parents before their dependencies as we require the parent path to construct the
1283    // dependency path. Skip the already added project node at the beginning of traversal.
1284    let mut bfs = Bfs::new(graph, proj_node);
1285    bfs.next(graph);
1286    while let Some(dep_node) = bfs.next(graph) {
1287        // Retrieve the parent node whose manifest is already stored.
1288        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
1313/// Given a `graph`, the node index of a path dependency within that `graph`, and the supposed
1314/// `path_root` of the path dependency, ensure that the `path_root` is valid.
1315///
1316/// See the `path_root` field of the [SourcePathPinned] type for further details.
1317fn 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
1328/// Given any node in the graph, find the node that is the path root for that node.
1329fn 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
1356/// Given an empty or partially completed `graph`, complete the graph.
1357///
1358/// If the given `manifest` is of type ManifestFile::Workspace resulting graph will have multiple
1359/// root nodes, each representing a member of the workspace. Otherwise resulting graph will only
1360/// have a single root node, representing the package that is described by the ManifestFile::Package
1361///
1362/// Checks the created graph after fetching for conflicting salt declarations.
1363fn 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
1385/// Given an empty or partially completed package `graph`, complete the graph.
1386///
1387/// The given `graph` may be empty, partially complete, or fully complete. All existing nodes
1388/// should already be confirmed to be valid nodes via `validate_graph`. All invalid nodes should
1389/// have been removed prior to calling this.
1390///
1391/// Recursively traverses dependencies listed within each package's manifest, fetching and pinning
1392/// each dependency if it does not already exist within the package graph.
1393///
1394/// The accompanying `path_map` should contain a path entry for every existing node within the
1395/// `graph` and will `panic!` otherwise.
1396///
1397/// Upon success, returns the set of nodes that were added to the graph during traversal.
1398fn 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    // Retrieve the project node, or create one if it does not exist.
1407    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    // Traverse the rest of the graph from the root.
1419    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/// Visit the unvisited dependencies of the given node and fetch missing nodes as necessary.
1447///
1448/// Assumes the `node`'s manifest already exists within the `manifest_map`.
1449#[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    // If the current package is a contract, we need to first get the deployment dependencies
1466    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        // If we haven't yet fetched this dependency, fetch it, pin it and add it to the graph.
1489        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        // Ensure we have an edge to the dependency.
1515        graph.update_edge(node, dep_node, dep_edge.clone());
1516
1517        // If we've visited this node during this traversal already, no need to traverse it again.
1518        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        // Fetch the children.
1543        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
1559/// Given a `forc_pkg::BuildProfile`, produce the necessary `sway_core::BuildConfig` required for
1560/// compilation.
1561pub 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    // Prepare the build config to pass through to the compiler.
1569    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/// Builds the dependency namespace for the package at the given node index within the graph.
1594///
1595/// This function is designed to be called for each node in order of compilation.
1596///
1597/// This function ensures that if `std` exists in the graph (the vastly common case) it is also
1598/// present within the namespace. This is a necessity for operators to work for example.
1599///
1600/// This function also ensures that if `std` exists in the graph,
1601/// then the std prelude will also be added.
1602///
1603/// `contract_id_value` should only be Some when producing the `dependency_namespace` for a contract with tests enabled.
1604/// This allows us to provide a contract's `CONTRACT_ID` constant to its own unit tests.
1605#[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    // TODO: Clean this up when config-time constants v1 are removed.
1618    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    // Add direct dependencies.
1634    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                    // On `check` we don't compile contracts, so we use a placeholder.
1649                    .unwrap_or_default();
1650                // Construct namespace with contract id
1651                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
1670/// Compiles the given package.
1671///
1672/// ## Program Types
1673///
1674/// Behaviour differs slightly based on the package's program type.
1675///
1676/// ### Library Packages
1677///
1678/// A Library package will have JSON ABI generated for all publicly exposed `abi`s. The library's
1679/// namespace is returned as the second argument of the tuple.
1680///
1681/// ### Contract
1682///
1683/// Contracts will output both their JSON ABI and compiled bytecode.
1684///
1685/// ### Script, Predicate
1686///
1687/// Scripts and Predicates will be compiled to bytecode and will not emit any JSON ABI.
1688pub 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    // First, compile to an AST. We'll update the namespace and check for JSON ABI output.
1726    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            // Merge the ABI output of ASM gen with ABI gen to handle internal constructors
1832            // generated by the ASM backend.
1833            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    // Metadata to be placed into the binary.
1888    let mut md = [0u8, 0, 0, 0, 0, 0, 0, 0];
1889    // TODO: This should probably be in `fuel_abi_json::generate_json_abi_program`?
1890    // If ABI requires knowing config offsets, they should be inputs to ABI gen.
1891    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            // Filter out all dead configurables (i.e. ones without offsets in the bytecode)
1895            configurables.retain(|c| {
1896                compiled
1897                    .named_data_section_entries_offsets
1898                    .contains_key(&c.name)
1899            });
1900            // Set the actual offsets in the JSON object
1901            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    // We know to set the metadata only for fuelvm right now.
1915    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
1945/// Reports assembly information for a compiled package to an external `dyno` process through `stdout`.
1946fn report_assembly_information(
1947    compiled_asm: &sway_core::CompiledAsm,
1948    compiled_package: &CompiledPackage,
1949) {
1950    // Get the bytes of the compiled package.
1951    let mut bytes = compiled_package.bytecode.bytes.clone();
1952
1953    // Attempt to get the data section offset out of the compiled package bytes.
1954    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    // Remove the data section from the compiled package bytes.
1967    bytes.truncate(data_offset as usize);
1968
1969    // Calculate the unpadded size of each data section section.
1970    // Implementation based directly on `sway_core::asm_generation::Entry::to_bytes`, referenced here:
1971    // https://github.com/FuelLabs/sway/blob/afd6a6709e7cb11c676059a5004012cc466e653b/sway-core/src/asm_generation/fuel/data_section.rs#L147
1972    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    // Compute the assembly information to be reported.
1994    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    // Report the assembly information to the `dyno` process through `stdout`.
2013    println!(
2014        "/dyno info {}",
2015        serde_json::to_string(&asm_information).unwrap()
2016    );
2017}
2018
2019impl PkgEntry {
2020    /// Returns whether this `PkgEntry` corresponds to a test.
2021    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    /// Returns `Some` if the `PkgEntryKind` is `Test`.
2043    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            // Last "should_revert" argument wins ;-)
2074            .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
2110/// The suffix that helps identify the file which contains the hash of the binary file created when
2111/// scripts are built_package.
2112pub const SWAY_BIN_HASH_SUFFIX: &str = "-bin-hash";
2113
2114/// The suffix that helps identify the file which contains the root hash of the binary file created
2115/// when predicates are built_package.
2116pub const SWAY_BIN_ROOT_SUFFIX: &str = "-bin-root";
2117
2118/// Selects the build profile from all available build profiles in the workspace using build_opts.
2119fn 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    // Retrieve the specified build profile
2143    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
2180/// Returns a formatted string of the selected build profile and targets.
2181fn 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}
2190/// Returns the size of the bytecode in a human-readable format.
2191pub 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
2197/// Check if the given node is a contract dependency of any node in the graph.
2198fn 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
2204/// Builds a project with given BuildOptions.
2205pub 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    // Check if manifest used to create the build plan is one of the member manifests or a
2237    // workspace manifest.
2238    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    // Get the selected build profile using build options
2243    let build_profile = build_profile_from_opts(&build_profiles, build_options)?;
2244    // If this is a workspace we want to have all members in the output.
2245    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    // Build it!
2258    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        // Output artifacts for the built package
2294        if let Some(outfile) = &binary_outfile {
2295            built_package.write_bytecode(outfile.as_ref())?;
2296        }
2297        // Generate debug symbols if explicitly requested via -g flag or if in debug build
2298        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    // The ansiterm formatters ignore the `std::fmt` right-align
2333    // formatter, so we manually calculate the padding to align the program
2334    // type and name around the 10th column ourselves.
2335    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
2344/// Returns the ContractId of a built_package contract with specified `salt`.
2345pub fn contract_id(
2346    bytecode: &[u8],
2347    mut storage_slots: Vec<StorageSlot>,
2348    salt: &fuel_tx::Salt,
2349) -> ContractId {
2350    // Construct the contract ID
2351    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
2357/// Checks if there are conflicting `Salt` declarations for the contract dependencies in the graph.
2358fn validate_contract_deps(graph: &Graph) -> Result<()> {
2359    // For each contract dependency node in the graph, check if there are conflicting salt
2360    // declarations.
2361    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
2382/// Build an entire forc package and return the built_package output.
2383///
2384/// This compiles all packages (including dependencies) in the order specified by the `BuildPlan`.
2385///
2386/// Also returns the resulting `sway_core::SourceMap` which may be useful for debugging purposes.
2387pub 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    // This is the Contract ID of the current contract being compiled.
2411    // We will need this for `forc test`.
2412    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        // If we are building a contract and tests are enabled or we are building a contract
2465        // dependency, we need the tests excluded bytecode.
2466        let bytecode_without_tests = if (include_tests
2467            && matches!(manifest.program_type(), Ok(TreeType::Contract)))
2468            || is_contract_dependency
2469        {
2470            // We will build a contract with tests enabled, we will also need the same contract with tests
2471            // disabled for:
2472            //
2473            //   1. Interpreter deployment in `forc-test`.
2474            //   2. Contract ID injection in `forc-pkg` if this is a contract dependency to any
2475            //      other pkg, so that injected contract id is not effected by the tests.
2476            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            // `ContractIdConst` is a None here since we do not yet have a
2486            // contract ID value at this point.
2487            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 this contract is built because:
2520            // 1) it is a contract dependency, or
2521            // 2) tests are enabled,
2522            // we need to insert its CONTRACT_ID into a map for later use.
2523            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                // `forc-test` interpreter deployments are done with zeroed salt.
2531                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                // We finally set the contract ID value here to use for compilation later if tests are enabled.
2537                contract_id_value = Some(format!("0x{contract_id}"));
2538            }
2539            Some(compiled_without_tests.bytecode)
2540        } else {
2541            None
2542        };
2543
2544        // Build all non member nodes with tests disabled by overriding the current profile.
2545        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        // Note that the contract ID value here is only Some if tests are enabled.
2559        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/// Compile the entire forc package and return the lexed, parsed and typed programs
2626/// of the dependencies and project.
2627/// The final item in the returned vector is the project.
2628#[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    // During `check`, we don't compile so this stays empty.
2644    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        // Only inject a dummy CONTRACT_ID in LSP mode, not when check() is called from tests or other non-LSP contexts,
2659        // to avoid polluting namespaces unnecessarily.
2660        let contract_id_value = if lsp_mode.is_some() && (idx == plan.compilation_order.len() - 1) {
2661            // This is necessary because `CONTRACT_ID` is a special constant that's injected into the
2662            // compiler's namespace. Although we only know the contract id during building, we are
2663            // inserting a dummy value here to avoid false error signals being reported in LSP.
2664            // We only do this for the last node in the compilation order because previous nodes
2665            // are dependencies.
2666            //
2667            // See this github issue for more context: https://github.com/FuelLabs/sway-vscode-plugin/issues/154
2668            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
2764/// Format an error message for an absent `Forc.toml`.
2765pub 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
2774/// Format an error message for failed parsing of a manifest.
2775pub 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
2785/// Format an error message if an incorrect program type is present.
2786pub 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
2795/// Format an error message if a given URL fails to produce a working node.
2796pub 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        // Create a temporary file for testing
2879        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        // Create a test BuiltPackage with some bytecode
2888        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        // Write the hexcode
2924        built_package.write_hexcode(path)?;
2925
2926        // Read the file and verify its contents
2927        let contents = fs::read_to_string(path)?;
2928        let expected = r#"{"hex":"0x01020304"}"#;
2929        assert_eq!(contents, expected);
2930
2931        Ok(())
2932    }
2933}