-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Expand file tree
/
Copy pathpkg.rs
More file actions
3011 lines (2746 loc) · 106 KB
/
pkg.rs
File metadata and controls
3011 lines (2746 loc) · 106 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::manifest::GenericManifestFile;
use crate::{
lock::Lock,
manifest::{Dependency, ManifestFile, MemberManifestFiles, PackageManifestFile},
source::{self, IPFSNode, Source},
BuildProfile,
};
use anyhow::{anyhow, bail, Context, Error, Result};
use byte_unit::{Byte, UnitType};
use forc_tracing::{println_action_green, println_warning};
use forc_util::{
default_output_directory, find_file_name, kebab_to_snake_case, print_compiling, print_infos,
print_on_failure, print_warnings,
};
use petgraph::{
self, dot,
visit::{Bfs, Dfs, EdgeRef, Walker},
Directed, Direction,
};
use serde::{Deserialize, Serialize};
use std::{
collections::{hash_map, BTreeSet, HashMap, HashSet},
fmt,
fs::{self, File},
hash::{Hash, Hasher},
io::Write,
path::{Path, PathBuf},
str::FromStr,
sync::{atomic::AtomicBool, Arc},
};
use sway_core::transform::AttributeArg;
pub use sway_core::Programs;
use sway_core::{
abi_generation::{
evm_abi,
fuel_abi::{self, AbiContext},
},
asm_generation::ProgramABI,
decl_engine::DeclRefFunction,
fuel_prelude::{
fuel_crypto,
fuel_tx::{self, Contract, ContractId, StorageSlot},
},
language::parsed::TreeType,
semantic_analysis::namespace,
source_map::SourceMap,
write_dwarf, BuildTarget, Engines, FinalizedEntry, LspConfig,
};
use sway_core::{namespace::Package, Observer};
use sway_core::{set_bytecode_configurables_offset, DbgGeneration, IrCli, PrintAsm};
use sway_error::{error::CompileError, handler::Handler, warning::CompileWarning};
use sway_features::ExperimentalFeatures;
use sway_types::{Ident, ProgramId, Span, Spanned};
use sway_utils::{constants, time_expr, PerformanceData, PerformanceMetric};
use tracing::{debug, info};
type GraphIx = u32;
type Node = Pinned;
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Edge {
/// The name specified on the left hand side of the `=` in a dependency declaration under
/// `[dependencies]` or `[contract-dependencies]` within a forc manifest.
///
/// The name of a dependency may differ from the package name in the case that the dependency's
/// `package` field is specified.
///
/// For example, in the following, `foo` is assumed to be both the package name and the dependency
/// name:
///
/// ```toml
/// foo = { git = "https://github.com/owner/repo", branch = "master" }
/// ```
///
/// In the following case however, `foo` is the package name, but the dependency name is `foo-alt`:
///
/// ```toml
/// foo-alt = { git = "https://github.com/owner/repo", branch = "master", package = "foo" }
/// ```
pub name: String,
pub kind: DepKind,
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum DepKind {
/// The dependency is a library and declared under `[dependencies]`.
Library,
/// The dependency is a contract and declared under `[contract-dependencies]`.
Contract { salt: fuel_tx::Salt },
}
pub type Graph = petgraph::stable_graph::StableGraph<Node, Edge, Directed, GraphIx>;
pub type EdgeIx = petgraph::graph::EdgeIndex<GraphIx>;
pub type NodeIx = petgraph::graph::NodeIndex<GraphIx>;
pub type ManifestMap = HashMap<PinnedId, PackageManifestFile>;
/// A unique ID for a pinned package.
///
/// The internal value is produced by hashing the package's name and `source::Pinned`.
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
pub struct PinnedId(u64);
/// The result of successfully compiling a package.
#[derive(Debug, Clone)]
pub struct BuiltPackage {
pub descriptor: PackageDescriptor,
pub program_abi: ProgramABI,
pub storage_slots: Vec<StorageSlot>,
pub warnings: Vec<CompileWarning>,
pub source_map: SourceMap,
pub tree_type: TreeType,
pub bytecode: BuiltPackageBytecode,
/// `Some` for contract member builds where tests were included. This is
/// required so that we can deploy once instance of the contract (without
/// tests) with a valid contract ID before executing the tests as scripts.
///
/// For non-contract members, this is always `None`.
pub bytecode_without_tests: Option<BuiltPackageBytecode>,
}
/// The package descriptors that a `BuiltPackage` holds so that the source used for building the
/// package can be retrieved later on.
#[derive(Debug, Clone)]
pub struct PackageDescriptor {
pub name: String,
pub target: BuildTarget,
pub manifest_file: PackageManifestFile,
pub pinned: Pinned,
}
/// The bytecode associated with a built package along with its entry points.
#[derive(Debug, Clone)]
pub struct BuiltPackageBytecode {
pub bytes: Vec<u8>,
pub entries: Vec<PkgEntry>,
}
/// Represents a package entry point.
#[derive(Debug, Clone)]
pub struct PkgEntry {
pub finalized: FinalizedEntry,
pub kind: PkgEntryKind,
}
/// Data specific to each kind of package entry point.
#[derive(Debug, Clone)]
pub enum PkgEntryKind {
Main,
Test(PkgTestEntry),
}
/// The possible conditions for a test result to be considered "passing".
#[derive(Debug, Clone)]
pub enum TestPassCondition {
ShouldRevert(Option<u64>),
ShouldNotRevert,
}
/// Data specific to the test entry point.
#[derive(Debug, Clone)]
pub struct PkgTestEntry {
pub pass_condition: TestPassCondition,
pub span: Span,
pub file_path: Arc<PathBuf>,
}
/// The result of successfully compiling a workspace.
pub type BuiltWorkspace = Vec<Arc<BuiltPackage>>;
#[derive(Debug, Clone)]
pub enum Built {
/// Represents a standalone package build.
Package(Arc<BuiltPackage>),
/// Represents a workspace build.
Workspace(BuiltWorkspace),
}
/// The result of the `compile` function, i.e. compiling a single package.
pub struct CompiledPackage {
pub source_map: SourceMap,
pub tree_type: TreeType,
pub program_abi: ProgramABI,
pub storage_slots: Vec<StorageSlot>,
pub bytecode: BuiltPackageBytecode,
pub namespace: namespace::Package,
pub warnings: Vec<CompileWarning>,
pub metrics: PerformanceData,
}
/// Compiled contract dependency parts relevant to calculating a contract's ID.
pub struct CompiledContractDependency {
pub bytecode: Vec<u8>,
pub storage_slots: Vec<StorageSlot>,
}
/// The set of compiled contract dependencies, provided to dependency namespace construction.
pub type CompiledContractDeps = HashMap<NodeIx, CompiledContractDependency>;
/// A package uniquely identified by name along with its source.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Deserialize, Serialize)]
pub struct Pkg {
/// The unique name of the package as declared in its manifest.
pub name: String,
/// Where the package is sourced from.
pub source: Source,
}
/// A package uniquely identified by name along with its pinned source.
#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
pub struct Pinned {
pub name: String,
pub source: source::Pinned,
}
/// Represents the full build plan for a project.
#[derive(Clone, Debug)]
pub struct BuildPlan {
graph: Graph,
manifest_map: ManifestMap,
compilation_order: Vec<NodeIx>,
}
/// Error returned upon failed parsing of `PinnedId::from_str`.
#[derive(Clone, Debug)]
pub struct PinnedIdParseError;
#[derive(Default, Clone)]
pub struct PkgOpts {
/// Path to the project, if not specified, current working directory will be used.
pub path: Option<String>,
/// Offline mode, prevents Forc from using the network when managing dependencies.
/// Meaning it will only try to use previously downloaded dependencies.
pub offline: bool,
/// Terse mode. Limited warning and error output.
pub terse: bool,
/// Requires that the Forc.lock file is up-to-date. If the lock file is missing, or it
/// needs to be updated, Forc will exit with an error
pub locked: bool,
/// The directory in which the sway compiler output artifacts are placed.
///
/// By default, this is `<project-root>/out`.
pub output_directory: Option<String>,
/// The IPFS node to be used for fetching IPFS sources.
pub ipfs_node: IPFSNode,
}
#[derive(Default, Clone)]
pub struct PrintOpts {
/// Print the generated Sway AST (Abstract Syntax Tree).
pub ast: bool,
/// Print the computed Sway DCA (Dead Code Analysis) graph to the specified path.
/// If not specified prints to stdout.
pub dca_graph: Option<String>,
/// Specifies the url format to be used in the generated dot file.
/// Variables {path}, {line} {col} can be used in the provided format.
/// An example for vscode would be: "vscode://file/{path}:{line}:{col}"
pub dca_graph_url_format: Option<String>,
/// Print the generated ASM.
pub asm: PrintAsm,
/// Print the bytecode. This is the final output of the compiler.
pub bytecode: bool,
/// Print the original source code together with bytecode.
pub bytecode_spans: bool,
/// Print the generated Sway IR (Intermediate Representation).
pub ir: IrCli,
/// Output build errors and warnings in reverse order.
pub reverse_order: bool,
}
#[derive(Default, Clone)]
pub struct MinifyOpts {
/// By default the JSON for ABIs is formatted for human readability. By using this option JSON
/// output will be "minified", i.e. all on one line without whitespace.
pub json_abi: bool,
/// By default the JSON for initial storage slots is formatted for human readability. By using
/// this option JSON output will be "minified", i.e. all on one line without whitespace.
pub json_storage_slots: bool,
}
/// Represents a compiled contract ID as a pub const in a contract.
type ContractIdConst = String;
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)]
pub struct DumpOpts {
/// Dump all trait implementations for the given type name.
pub dump_impls: Option<String>,
}
/// The set of options provided to the `build` functions.
#[derive(Default, Clone)]
pub struct BuildOpts {
pub pkg: PkgOpts,
pub print: PrintOpts,
pub verify_ir: IrCli,
pub minify: MinifyOpts,
pub dump: DumpOpts,
/// If set, generates a JSON file containing the hex-encoded script binary.
pub hex_outfile: Option<String>,
/// If set, outputs a binary file representing the script bytes.
pub binary_outfile: Option<String>,
/// If set, outputs debug info to the provided file.
/// If the argument provided ends with .json, a JSON is emitted,
/// otherwise, an ELF file containing DWARF is emitted.
pub debug_outfile: Option<String>,
/// Build target to use.
pub build_target: BuildTarget,
/// Name of the build profile to use.
pub build_profile: String,
/// Use the release build profile.
/// The release profile can be customized in the manifest file.
pub release: bool,
/// Output the time elapsed over each part of the compilation process.
pub time_phases: bool,
/// Profile the build process.
pub profile: bool,
/// If set, outputs compilation metrics info in JSON format.
pub metrics_outfile: Option<String>,
/// Warnings must be treated as compiler errors.
pub error_on_warnings: bool,
/// Include all test functions within the build.
pub tests: bool,
/// The set of options to filter by member project kind.
pub member_filter: MemberFilter,
/// Set of enabled experimental flags
pub experimental: Vec<sway_features::Feature>,
/// Set of disabled experimental flags
pub no_experimental: Vec<sway_features::Feature>,
/// Do not output any build artifacts, e.g., bytecode, ABI JSON, etc.
pub no_output: bool,
}
/// The set of options to filter type of projects to build in a workspace.
#[derive(Clone)]
pub struct MemberFilter {
pub build_contracts: bool,
pub build_scripts: bool,
pub build_predicates: bool,
pub build_libraries: bool,
}
impl Default for MemberFilter {
fn default() -> Self {
Self {
build_contracts: true,
build_scripts: true,
build_predicates: true,
build_libraries: true,
}
}
}
impl MemberFilter {
/// Returns a new `MemberFilter` that only builds scripts.
pub fn only_scripts() -> Self {
Self {
build_contracts: false,
build_scripts: true,
build_predicates: false,
build_libraries: false,
}
}
/// Returns a new `MemberFilter` that only builds contracts.
pub fn only_contracts() -> Self {
Self {
build_contracts: true,
build_scripts: false,
build_predicates: false,
build_libraries: false,
}
}
/// Returns a new `MemberFilter`, that only builds predicates.
pub fn only_predicates() -> Self {
Self {
build_contracts: false,
build_scripts: false,
build_predicates: true,
build_libraries: false,
}
}
/// Filter given target of output nodes according to the this `MemberFilter`.
pub fn filter_outputs(
&self,
build_plan: &BuildPlan,
outputs: HashSet<NodeIx>,
) -> HashSet<NodeIx> {
let graph = build_plan.graph();
let manifest_map = build_plan.manifest_map();
outputs
.into_iter()
.filter(|&node_ix| {
let pkg = &graph[node_ix];
let pkg_manifest = &manifest_map[&pkg.id()];
let program_type = pkg_manifest.program_type();
// Since parser cannot recover for program type detection, for the scenarios that
// parser fails to parse the code, program type detection is not possible. So in
// failing to parse cases we should try to build at least until
// https://github.com/FuelLabs/sway/issues/3017 is fixed. Until then we should
// build those members because of two reasons:
//
// 1. The member could already be from the desired member type
// 2. If we do not try to build there is no way users can know there is a code
// piece failing to be parsed in their workspace.
match program_type {
Ok(program_type) => match program_type {
TreeType::Predicate => self.build_predicates,
TreeType::Script => self.build_scripts,
TreeType::Contract => self.build_contracts,
TreeType::Library => self.build_libraries,
},
Err(_) => true,
}
})
.collect()
}
}
impl BuildOpts {
/// Return a `BuildOpts` with modified `tests` field.
pub fn include_tests(self, include_tests: bool) -> Self {
Self {
tests: include_tests,
..self
}
}
}
impl Edge {
pub fn new(name: String, kind: DepKind) -> Edge {
Edge { name, kind }
}
}
impl BuiltPackage {
/// Writes bytecode of the BuiltPackage to the given `path`.
pub fn write_bytecode(&self, path: &Path) -> Result<()> {
fs::write(path, &self.bytecode.bytes)?;
Ok(())
}
pub fn write_hexcode(&self, path: &Path) -> Result<()> {
let hex_file = serde_json::json!({
"hex": format!("0x{}", hex::encode(&self.bytecode.bytes)),
});
fs::write(path, hex_file.to_string())?;
Ok(())
}
/// Writes debug_info (source_map) of the BuiltPackage to the given `out_file`.
pub fn write_debug_info(&self, out_file: &Path) -> Result<()> {
if matches!(out_file.extension(), Some(ext) if ext == "json") {
let source_map_json =
serde_json::to_vec(&self.source_map).expect("JSON serialization failed");
fs::write(out_file, source_map_json)?;
} else {
let primary_dir = self.descriptor.manifest_file.dir();
let primary_src = self.descriptor.manifest_file.entry_path();
write_dwarf(&self.source_map, primary_dir, &primary_src, out_file)?;
}
Ok(())
}
pub fn json_abi_string(&self, minify_json_abi: bool) -> Result<Option<String>> {
match &self.program_abi {
ProgramABI::Fuel(program_abi) => {
if !program_abi.functions.is_empty() {
let json_string = if minify_json_abi {
serde_json::to_string(&program_abi)
} else {
serde_json::to_string_pretty(&program_abi)
}?;
Ok(Some(json_string))
} else {
Ok(None)
}
}
ProgramABI::Evm(program_abi) => {
if !program_abi.is_empty() {
let json_string = if minify_json_abi {
serde_json::to_string(&program_abi)
} else {
serde_json::to_string_pretty(&program_abi)
}?;
Ok(Some(json_string))
} else {
Ok(None)
}
}
// TODO?
ProgramABI::MidenVM(()) => Ok(None),
}
}
/// Writes the ABI in JSON format to the given `path`.
pub fn write_json_abi(&self, path: &Path, minify: &MinifyOpts) -> Result<()> {
if let Some(json_abi_string) = self.json_abi_string(minify.json_abi)? {
let mut file = File::create(path)?;
file.write_all(json_abi_string.as_bytes())?;
}
Ok(())
}
/// Writes BuiltPackage to `output_dir`.
pub fn write_output(
&self,
minify: &MinifyOpts,
pkg_name: &str,
output_dir: &Path,
) -> Result<()> {
if !output_dir.exists() {
fs::create_dir_all(output_dir)?;
}
// Place build artifacts into the output directory.
let bin_path = output_dir.join(pkg_name).with_extension("bin");
self.write_bytecode(&bin_path)?;
let program_abi_stem = format!("{pkg_name}-abi");
let json_abi_path = output_dir.join(program_abi_stem).with_extension("json");
self.write_json_abi(&json_abi_path, minify)?;
debug!(
" Bytecode size: {} bytes ({})",
self.bytecode.bytes.len(),
format_bytecode_size(self.bytecode.bytes.len())
);
// Additional ops required depending on the program type
match self.tree_type {
TreeType::Contract => {
// For contracts, emit a JSON file with all the initialized storage slots.
let storage_slots_stem = format!("{pkg_name}-storage_slots");
let storage_slots_path = output_dir.join(storage_slots_stem).with_extension("json");
let storage_slots_file = File::create(storage_slots_path)?;
let res = if minify.json_storage_slots {
serde_json::to_writer(&storage_slots_file, &self.storage_slots)
} else {
serde_json::to_writer_pretty(&storage_slots_file, &self.storage_slots)
};
res?;
}
TreeType::Predicate => {
// Get the root hash of the bytecode for predicates and store the result in a file in the output directory
let root = format!(
"0x{}",
fuel_tx::Input::predicate_owner(&self.bytecode.bytes)
);
let root_file_name = format!("{}{}", &pkg_name, SWAY_BIN_ROOT_SUFFIX);
let root_path = output_dir.join(root_file_name);
fs::write(root_path, &root)?;
info!(" Predicate root [{}]: {}", pkg_name, root);
}
TreeType::Script => {
// hash the bytecode for scripts and store the result in a file in the output directory
let bytecode_hash =
format!("0x{}", fuel_crypto::Hasher::hash(&self.bytecode.bytes));
let hash_file_name = format!("{}{}", &pkg_name, SWAY_BIN_HASH_SUFFIX);
let hash_path = output_dir.join(hash_file_name);
fs::write(hash_path, &bytecode_hash)?;
debug!(" Bytecode hash: {}", bytecode_hash);
}
_ => (),
}
Ok(())
}
}
impl Built {
/// Returns an iterator yielding all member built packages.
pub fn into_members<'a>(
&'a self,
) -> Box<dyn Iterator<Item = (&'a Pinned, Arc<BuiltPackage>)> + 'a> {
// NOTE: Since pkg is a `Arc<_>`, pkg clones in this function are only reference
// increments. `BuiltPackage` struct does not get copied.`
match self {
Built::Package(pkg) => {
let pinned = &pkg.as_ref().descriptor.pinned;
let pkg = pkg.clone();
Box::new(std::iter::once((pinned, pkg)))
}
Built::Workspace(workspace) => Box::new(
workspace
.iter()
.map(|pkg| (&pkg.descriptor.pinned, pkg.clone())),
),
}
}
/// Tries to retrieve the `Built` as a `BuiltPackage`.
pub fn expect_pkg(self) -> Result<Arc<BuiltPackage>> {
match self {
Built::Package(built_pkg) => Ok(built_pkg),
Built::Workspace(_) => bail!("expected `Built` to be `Built::Package`"),
}
}
}
impl BuildPlan {
/// Create a new build plan for the project from the build options provided.
///
/// To do so, it tries to read the manifet file at the target path and creates the plan with
/// `BuildPlan::from_lock_and_manifest`.
pub fn from_pkg_opts(pkg_options: &PkgOpts) -> Result<Self> {
let path = &pkg_options.path;
let manifest_dir = if let Some(ref path) = path {
PathBuf::from(path)
} else {
std::env::current_dir()?
};
let manifest_file = ManifestFile::from_dir(manifest_dir)?;
let member_manifests = manifest_file.member_manifests()?;
// Check if we have members to build so that we are not trying to build an empty workspace.
if member_manifests.is_empty() {
bail!("No member found to build")
}
let lock_path = manifest_file.lock_path()?;
Self::from_lock_and_manifests(
&lock_path,
&member_manifests,
pkg_options.locked,
pkg_options.offline,
&pkg_options.ipfs_node,
)
}
/// Create a new build plan for the project by fetching and pinning all dependencies.
///
/// To account for an existing lock file, use `from_lock_and_manifest` instead.
pub fn from_manifests(
manifests: &MemberManifestFiles,
offline: bool,
ipfs_node: &IPFSNode,
) -> Result<Self> {
// Check toolchain version
validate_version(manifests)?;
let mut graph = Graph::default();
let mut manifest_map = ManifestMap::default();
fetch_graph(manifests, offline, ipfs_node, &mut graph, &mut manifest_map)?;
// Validate the graph, since we constructed the graph from scratch the paths will not be a
// problem but the version check is still needed
validate_graph(&graph, manifests)?;
let compilation_order = compilation_order(&graph)?;
Ok(Self {
graph,
manifest_map,
compilation_order,
})
}
/// Create a new build plan taking into account the state of both the PackageManifest and the existing
/// lock file if there is one.
///
/// This will first attempt to load a build plan from the lock file and validate the resulting
/// graph using the current state of the PackageManifest.
///
/// This includes checking if the [dependencies] or [patch] tables have changed and checking
/// the validity of the local path dependencies. If any changes are detected, the graph is
/// updated and any new packages that require fetching are fetched.
///
/// The resulting build plan should always be in a valid state that is ready for building or
/// checking.
// TODO: Currently (if `--locked` isn't specified) this writes the updated lock directly. This
// probably should not be the role of the `BuildPlan` constructor - instead, we should return
// the manifest alongside some lock diff type that can be used to optionally write the updated
// lock file and print the diff.
pub fn from_lock_and_manifests(
lock_path: &Path,
manifests: &MemberManifestFiles,
locked: bool,
offline: bool,
ipfs_node: &IPFSNode,
) -> Result<Self> {
// Check toolchain version
validate_version(manifests)?;
// Keep track of the cause for the new lock file if it turns out we need one.
let mut new_lock_cause = None;
// First, attempt to load the lock.
let lock = Lock::from_path(lock_path).unwrap_or_else(|e| {
new_lock_cause = if e.to_string().contains("No such file or directory") {
Some(anyhow!("lock file did not exist"))
} else {
Some(e)
};
Lock::default()
});
// Next, construct the package graph from the lock.
let mut graph = lock.to_graph().unwrap_or_else(|e| {
new_lock_cause = Some(anyhow!("Invalid lock: {}", e));
Graph::default()
});
// Since the lock file was last created there are many ways in which it might have been
// invalidated. E.g. a package's manifest `[dependencies]` table might have changed, a user
// might have edited the `Forc.lock` file when they shouldn't have, a path dependency no
// longer exists at its specified location, etc. We must first remove all invalid nodes
// before we can determine what we need to fetch.
let invalid_deps = validate_graph(&graph, manifests)?;
let members: HashSet<String> = manifests.keys().cloned().collect();
remove_deps(&mut graph, &members, &invalid_deps);
// We know that the remaining nodes have valid paths, otherwise they would have been
// removed. We can safely produce an initial `manifest_map`.
let mut manifest_map = graph_to_manifest_map(manifests, &graph)?;
// Attempt to fetch the remainder of the graph.
let _added = fetch_graph(manifests, offline, ipfs_node, &mut graph, &mut manifest_map)?;
// Determine the compilation order.
let compilation_order = compilation_order(&graph)?;
let plan = Self {
graph,
manifest_map,
compilation_order,
};
// Construct the new lock and check the diff.
let new_lock = Lock::from_graph(plan.graph());
let lock_diff = new_lock.diff(&lock);
if !lock_diff.removed.is_empty() || !lock_diff.added.is_empty() {
new_lock_cause.get_or_insert(anyhow!("lock file did not match manifest"));
}
// If there was some change in the lock file, write the new one and print the cause.
if let Some(cause) = new_lock_cause {
if locked {
bail!(
"The lock file {} needs to be updated (Cause: {}) \
but --locked was passed to prevent this.",
lock_path.to_string_lossy(),
cause,
);
}
println_action_green(
"Creating",
&format!("a new `Forc.lock` file. (Cause: {cause})"),
);
let member_names = manifests
.values()
.map(|manifest| manifest.project.name.to_string())
.collect();
crate::lock::print_diff(&member_names, &lock_diff);
let string = toml::ser::to_string_pretty(&new_lock)
.map_err(|e| anyhow!("failed to serialize lock file: {}", e))?;
fs::write(lock_path, string)
.map_err(|e| anyhow!("failed to write lock file: {}", e))?;
debug!(" Created new lock file at {}", lock_path.display());
}
Ok(plan)
}
/// Produce an iterator yielding all contract dependencies of given node in the order of
/// compilation.
pub fn contract_dependencies(&self, node: NodeIx) -> impl Iterator<Item = NodeIx> + '_ {
let graph = self.graph();
let connected: HashSet<_> = Dfs::new(graph, node).iter(graph).collect();
self.compilation_order()
.iter()
.cloned()
.filter(move |&n| n != node)
.filter(|&n| {
graph
.edges_directed(n, Direction::Incoming)
.any(|edge| matches!(edge.weight().kind, DepKind::Contract { .. }))
})
.filter(move |&n| connected.contains(&n))
}
/// Produce an iterator yielding all workspace member nodes in order of compilation.
///
/// In the case that this [BuildPlan] was constructed for a single package,
/// only that package's node will be yielded.
pub fn member_nodes(&self) -> impl Iterator<Item = NodeIx> + '_ {
self.compilation_order()
.iter()
.copied()
.filter(|&n| self.graph[n].source == source::Pinned::MEMBER)
}
/// Produce an iterator yielding all workspace member pinned pkgs in order of compilation.
///
/// In the case that this `BuildPlan` was constructed for a single package,
/// only that package's pinned pkg will be yielded.
pub fn member_pinned_pkgs(&self) -> impl Iterator<Item = Pinned> + '_ {
let graph = self.graph();
self.member_nodes().map(|node| &graph[node]).cloned()
}
/// View the build plan's compilation graph.
pub fn graph(&self) -> &Graph {
&self.graph
}
/// View the build plan's map of pinned package IDs to their associated manifest.
pub fn manifest_map(&self) -> &ManifestMap {
&self.manifest_map
}
/// The order in which nodes are compiled, determined via a toposort of the package graph.
pub fn compilation_order(&self) -> &[NodeIx] {
&self.compilation_order
}
/// Produce the node index of the member with the given name.
pub fn find_member_index(&self, member_name: &str) -> Option<NodeIx> {
self.member_nodes()
.find(|node_ix| self.graph[*node_ix].name == member_name)
}
/// Produce an iterator yielding indices for the given node and its dependencies in BFS order.
pub fn node_deps(&self, n: NodeIx) -> impl '_ + Iterator<Item = NodeIx> {
let bfs = Bfs::new(&self.graph, n);
// Return an iterator yielding visitable nodes from the given node.
bfs.iter(&self.graph)
}
/// Produce an iterator yielding build profiles from the member nodes of this BuildPlan.
pub fn build_profiles(&self) -> impl '_ + Iterator<Item = (String, BuildProfile)> {
let manifest_map = &self.manifest_map;
let graph = &self.graph;
self.member_nodes().flat_map(|member_node| {
manifest_map[&graph[member_node].id()]
.build_profiles()
.map(|(n, p)| (n.clone(), p.clone()))
})
}
/// Returns a salt for the given pinned package if it is a contract and `None` for libraries.
pub fn salt(&self, pinned: &Pinned) -> Option<fuel_tx::Salt> {
let graph = self.graph();
let node_ix = graph
.node_indices()
.find(|node_ix| graph[*node_ix] == *pinned);
node_ix.and_then(|node| {
graph
.edges_directed(node, Direction::Incoming)
.map(|e| match e.weight().kind {
DepKind::Library => None,
DepKind::Contract { salt } => Some(salt),
})
.next()
.flatten()
})
}
/// Returns a [String] representing the build dependency graph in GraphViz DOT format.
pub fn visualize(&self, url_file_prefix: Option<String>) -> String {
format!(
"{:?}",
dot::Dot::with_attr_getters(
&self.graph,
&[dot::Config::NodeNoLabel, dot::Config::EdgeNoLabel],
&|_, _| String::new(),
&|_, nr| {
let url = url_file_prefix.clone().map_or(String::new(), |prefix| {
self.manifest_map
.get(&nr.1.id())
.map_or(String::new(), |manifest| {
format!("URL = \"{}{}\"", prefix, manifest.path().to_string_lossy())
})
});
format!("label = \"{}\" shape = box {url}", nr.1.name)
},
)
)
}
}
/// Given a graph and the known project name retrieved from the manifest, produce an iterator
/// yielding any nodes from the graph that might potentially be a project node.
fn potential_proj_nodes<'a>(g: &'a Graph, proj_name: &'a str) -> impl 'a + Iterator<Item = NodeIx> {
member_nodes(g).filter(move |&n| g[n].name == proj_name)
}
/// Given a graph, find the project node.
///
/// This should be the only node that satisfies the following conditions:
///
/// - The package name matches `proj_name`
/// - The node has no incoming edges, i.e. is not a dependency of another node.
fn find_proj_node(graph: &Graph, proj_name: &str) -> Result<NodeIx> {
let mut potentials = potential_proj_nodes(graph, proj_name);
let proj_node = potentials
.next()
.ok_or_else(|| anyhow!("graph contains no project node"))?;
match potentials.next() {
None => Ok(proj_node),
Some(_) => Err(anyhow!("graph contains more than one project node")),
}
}
/// Checks if the toolchain version is in compliance with minimum implied by `manifest`.
///
/// If the `manifest` is a ManifestFile::Workspace, check all members of the workspace for version
/// validation. Otherwise only the given package is checked.
fn validate_version(member_manifests: &MemberManifestFiles) -> Result<()> {
for member_pkg_manifest in member_manifests.values() {
validate_pkg_version(member_pkg_manifest)?;
}
Ok(())
}
/// Check minimum forc version given in the package manifest file
///
/// If required minimum forc version is higher than current forc version return an error with
/// upgrade instructions
fn validate_pkg_version(pkg_manifest: &PackageManifestFile) -> Result<()> {
if let Some(min_forc_version) = &pkg_manifest.project.forc_version {
// Get the current version of the toolchain
let crate_version = env!("CARGO_PKG_VERSION");
let toolchain_version = semver::Version::parse(crate_version)?;
if toolchain_version < *min_forc_version {
bail!(
"{:?} requires forc version {} but current forc version is {}\nUpdate the toolchain by following: https://fuellabs.github.io/sway/v{}/introduction/installation.html",
pkg_manifest.project.name,
min_forc_version,
crate_version,
crate_version
);
}
};
Ok(())
}
fn member_nodes(g: &Graph) -> impl Iterator<Item = NodeIx> + '_ {
g.node_indices()
.filter(|&n| g[n].source == source::Pinned::MEMBER)
}
/// Validates the state of the pinned package graph against the given ManifestFile.
///
/// Returns the set of invalid dependency edges.
fn validate_graph(graph: &Graph, manifests: &MemberManifestFiles) -> Result<BTreeSet<EdgeIx>> {
let mut member_pkgs: HashMap<&String, &PackageManifestFile> = manifests.iter().collect();
let member_nodes: Vec<_> = member_nodes(graph)
.filter_map(|n| {
member_pkgs
.remove(&graph[n].name.to_string())
.map(|pkg| (n, pkg))
})
.collect();
// If no member nodes, the graph is either empty or corrupted. Remove all edges.
if member_nodes.is_empty() {
return Ok(graph.edge_indices().collect());
}
let mut visited = HashSet::new();
let edges = member_nodes
.into_iter()
.flat_map(move |(n, _)| validate_deps(graph, n, manifests, &mut visited))
.collect();
Ok(edges)
}
/// Recursively validate all dependencies of the given `node`.
///
/// Returns the set of invalid dependency edges.
fn validate_deps(
graph: &Graph,
node: NodeIx,
manifests: &MemberManifestFiles,
visited: &mut HashSet<NodeIx>,
) -> BTreeSet<EdgeIx> {
let mut remove = BTreeSet::default();
for edge in graph.edges_directed(node, Direction::Outgoing) {
let dep_name = edge.weight();
let dep_node = edge.target();
match validate_dep(graph, manifests, dep_name, dep_node) {
Err(_) => {
remove.insert(edge.id());
}
Ok(_) => {
if visited.insert(dep_node) {
let rm = validate_deps(graph, dep_node, manifests, visited);
remove.extend(rm);
}
continue;
}
}
}
remove
}
/// Check the validity of a node's dependency within the graph.
///
/// Returns the `ManifestFile` in the case that the dependency is valid.
fn validate_dep(
graph: &Graph,
manifests: &MemberManifestFiles,