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
use crate::pkg::{manifest_file_missing, parsing_failed, wrong_program_type};
use anyhow::{anyhow, bail, Context, Result};
use forc_tracing::println_yellow_err;
use forc_util::{find_manifest_dir, validate_name};
use serde::{Deserialize, Serialize};
use std::{
collections::BTreeMap,
path::{Path, PathBuf},
sync::Arc,
};
use sway_core::{fuel_prelude::fuel_tx, language::parsed::TreeType, parse_tree_type};
pub use sway_types::ConfigTimeConstant;
use sway_utils::constants;
pub type MemberName = String;
pub type MemberManifestFiles = BTreeMap<MemberName, PackageManifestFile>;
pub enum ManifestFile {
Package(Box<PackageManifestFile>),
Workspace(WorkspaceManifestFile),
}
impl ManifestFile {
pub fn from_dir(manifest_dir: &Path) -> Result<Self> {
let maybe_pkg_manifest = PackageManifestFile::from_dir(manifest_dir);
let manifest_file = if let Err(e) = maybe_pkg_manifest {
if e.to_string().contains("missing field `project`") {
let workspace_manifest_file = WorkspaceManifestFile::from_dir(manifest_dir)?;
ManifestFile::Workspace(workspace_manifest_file)
} else {
bail!("{}", e)
}
} else if let Ok(pkg_manifest) = maybe_pkg_manifest {
ManifestFile::Package(Box::new(pkg_manifest))
} else {
bail!("Cannot find a valid `Forc.toml` at {:?}", manifest_dir)
};
Ok(manifest_file)
}
pub fn from_file(path: PathBuf) -> Result<Self> {
let maybe_pkg_manifest = PackageManifestFile::from_file(path.clone());
let manifest_file = if let Err(e) = maybe_pkg_manifest {
if e.to_string().contains("missing field `project`") {
let workspace_manifest_file = WorkspaceManifestFile::from_file(path)?;
ManifestFile::Workspace(workspace_manifest_file)
} else {
bail!("{}", e)
}
} else if let Ok(pkg_manifest) = maybe_pkg_manifest {
ManifestFile::Package(Box::new(pkg_manifest))
} else {
bail!("Cannot find a valid `Forc.toml` at {:?}", path)
};
Ok(manifest_file)
}
pub fn path(&self) -> &Path {
match self {
ManifestFile::Package(pkg_manifest_file) => pkg_manifest_file.path(),
ManifestFile::Workspace(workspace_manifest_file) => workspace_manifest_file.path(),
}
}
pub fn dir(&self) -> &Path {
self.path()
.parent()
.expect("failed to retrieve manifest directory")
}
pub fn member_manifests(&self) -> Result<MemberManifestFiles> {
let mut member_manifest_files = BTreeMap::new();
match self {
ManifestFile::Package(pkg_manifest_file) => {
if let Some(workspace_manifest_file) = pkg_manifest_file.workspace()? {
for member_manifest in workspace_manifest_file.member_pkg_manifests()? {
let member_manifest =
member_manifest.with_context(|| "Invalid member manifest")?;
member_manifest_files
.insert(member_manifest.project.name.clone(), member_manifest);
}
} else {
let member_name = &pkg_manifest_file.project.name;
member_manifest_files.insert(member_name.clone(), *pkg_manifest_file.clone());
}
}
ManifestFile::Workspace(workspace_manifest_file) => {
for member_manifest in workspace_manifest_file.member_pkg_manifests()? {
let member_manifest =
member_manifest.with_context(|| "Invalid member manifest")?;
member_manifest_files
.insert(member_manifest.project.name.clone(), member_manifest);
}
}
}
Ok(member_manifest_files)
}
pub fn lock_path(&self) -> Result<PathBuf> {
match self {
ManifestFile::Package(pkg_manifest) => pkg_manifest.lock_path(),
ManifestFile::Workspace(workspace_manifest) => Ok(workspace_manifest.lock_path()),
}
}
}
type PatchMap = BTreeMap<String, Dependency>;
#[derive(Clone, Debug)]
pub struct PackageManifestFile {
manifest: PackageManifest,
path: PathBuf,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct PackageManifest {
pub project: Project,
pub network: Option<Network>,
pub dependencies: Option<BTreeMap<String, Dependency>>,
pub patch: Option<BTreeMap<String, PatchMap>>,
pub constants: Option<BTreeMap<String, ConfigTimeConstant>>,
build_profile: Option<BTreeMap<String, BuildProfile>>,
pub contract_dependencies: Option<BTreeMap<String, ContractDependency>>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct Project {
pub authors: Option<Vec<String>>,
pub name: String,
pub organization: Option<String>,
pub license: String,
#[serde(default = "default_entry")]
pub entry: String,
pub implicit_std: Option<bool>,
pub forc_version: Option<semver::Version>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct Network {
#[serde(default = "default_url")]
pub url: String,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct ContractDependency {
#[serde(flatten)]
pub dependency: Dependency,
#[serde(default = "fuel_tx::Salt::default")]
pub salt: fuel_tx::Salt,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(untagged)]
pub enum Dependency {
Simple(String),
Detailed(DependencyDetails),
}
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "kebab-case")]
pub struct DependencyDetails {
pub(crate) version: Option<String>,
pub path: Option<String>,
pub(crate) git: Option<String>,
pub(crate) branch: Option<String>,
pub(crate) tag: Option<String>,
pub(crate) package: Option<String>,
pub(crate) rev: Option<String>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct BuildProfile {
pub print_ast: bool,
pub print_dca_graph: bool,
pub print_ir: bool,
pub print_finalized_asm: bool,
pub print_intermediate_asm: bool,
pub terse: bool,
pub time_phases: bool,
pub include_tests: bool,
}
impl Dependency {
pub fn package(&self) -> Option<&str> {
match *self {
Self::Simple(_) => None,
Self::Detailed(ref det) => det.package.as_deref(),
}
}
}
impl PackageManifestFile {
pub fn from_file(path: PathBuf) -> Result<Self> {
let path = path.canonicalize()?;
let manifest = PackageManifest::from_file(&path)?;
Ok(Self { manifest, path })
}
pub fn from_dir(manifest_dir: &Path) -> Result<Self> {
let dir = forc_util::find_manifest_dir(manifest_dir)
.ok_or_else(|| manifest_file_missing(manifest_dir))?;
let path = dir.join(constants::MANIFEST_FILE_NAME);
Self::from_file(path)
}
pub fn validate(&self, path: &Path) -> Result<()> {
self.manifest.validate()?;
let mut entry_path = path.to_path_buf();
entry_path.pop();
let entry_path = entry_path
.join(constants::SRC_DIR)
.join(&self.project.entry);
if !entry_path.exists() {
bail!(
"failed to validate path from entry field {:?} in Forc manifest file.",
self.project.entry
)
}
Ok(())
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn dir(&self) -> &Path {
self.path()
.parent()
.expect("failed to retrieve manifest directory")
}
pub fn entry_path(&self) -> PathBuf {
self.dir()
.join(constants::SRC_DIR)
.join(&self.project.entry)
}
pub fn entry_string(&self) -> Result<Arc<str>> {
let entry_path = self.entry_path();
let entry_string = std::fs::read_to_string(entry_path)?;
Ok(Arc::from(entry_string))
}
pub fn program_type(&self) -> Result<TreeType> {
let entry_string = self.entry_string()?;
let parse_res = parse_tree_type(entry_string);
parse_res
.value
.ok_or_else(|| parsing_failed(&self.project.name, parse_res.errors))
}
pub fn check_program_type(&self, expected_types: Vec<TreeType>) -> Result<()> {
let parsed_type = self.program_type()?;
if !expected_types.contains(&parsed_type) {
bail!(wrong_program_type(
&self.project.name,
expected_types,
parsed_type
));
} else {
Ok(())
}
}
pub fn build_profile(&self, profile_name: &str) -> Option<&BuildProfile> {
self.build_profile
.as_ref()
.and_then(|profiles| profiles.get(profile_name))
}
pub fn dep_path(&self, dep_name: &str) -> Option<PathBuf> {
let dir = self.dir();
let details = self.dep_detailed(dep_name)?;
details.path.as_ref().and_then(|path_str| {
let path = Path::new(path_str);
match path.is_absolute() {
true => Some(path.to_owned()),
false => dir.join(path).canonicalize().ok(),
}
})
}
pub fn config_time_constants(&self) -> BTreeMap<String, ConfigTimeConstant> {
self.constants.as_ref().cloned().unwrap_or_default()
}
pub fn workspace(&self) -> Result<Option<WorkspaceManifestFile>> {
let parent_dir = match self.dir().parent() {
None => return Ok(None),
Some(dir) => dir,
};
let ws_manifest = match WorkspaceManifestFile::from_dir(parent_dir) {
Ok(manifest) => manifest,
Err(e) => {
if e.to_string().contains("could not find") {
return Ok(None);
} else {
return Err(e);
}
}
};
if ws_manifest.is_member_path(self.dir())? {
Ok(Some(ws_manifest))
} else {
Ok(None)
}
}
pub fn lock_path(&self) -> Result<PathBuf> {
let workspace_manifest = self.workspace()?;
if let Some(workspace_manifest) = workspace_manifest {
Ok(workspace_manifest.lock_path())
} else {
Ok(self.dir().to_path_buf().join(constants::LOCK_FILE_NAME))
}
}
}
impl PackageManifest {
pub const DEFAULT_ENTRY_FILE_NAME: &'static str = "main.sw";
pub fn from_file(path: &Path) -> Result<Self> {
let mut warnings = vec![];
let manifest_str = std::fs::read_to_string(path)
.map_err(|e| anyhow!("failed to read manifest at {:?}: {}", path, e))?;
let toml_de = &mut toml::de::Deserializer::new(&manifest_str);
let mut manifest: Self = serde_ignored::deserialize(toml_de, |path| {
let warning = format!(" WARNING! unused manifest key: {}", path);
warnings.push(warning);
})
.map_err(|e| anyhow!("failed to parse manifest: {}.", e))?;
for warning in warnings {
println_yellow_err(&warning);
}
manifest.implicitly_include_std_if_missing();
manifest.implicitly_include_default_build_profiles_if_missing();
manifest.validate()?;
Ok(manifest)
}
pub fn validate(&self) -> Result<()> {
validate_name(&self.project.name, "package name")?;
if let Some(ref org) = self.project.organization {
validate_name(org, "organization name")?;
}
Ok(())
}
pub fn from_dir(dir: &Path) -> Result<Self> {
let manifest_dir = find_manifest_dir(dir).ok_or_else(|| manifest_file_missing(dir))?;
let file_path = manifest_dir.join(constants::MANIFEST_FILE_NAME);
Self::from_file(&file_path)
}
pub fn deps(&self) -> impl Iterator<Item = (&String, &Dependency)> {
self.dependencies
.as_ref()
.into_iter()
.flat_map(|deps| deps.iter())
}
pub fn build_profiles(&self) -> impl Iterator<Item = (&String, &BuildProfile)> {
self.build_profile
.as_ref()
.into_iter()
.flat_map(|deps| deps.iter())
}
pub fn contract_deps(&self) -> impl Iterator<Item = (&String, &ContractDependency)> {
self.contract_dependencies
.as_ref()
.into_iter()
.flat_map(|deps| deps.iter())
}
pub fn deps_detailed(&self) -> impl Iterator<Item = (&String, &DependencyDetails)> {
self.deps().filter_map(|(name, dep)| match dep {
Dependency::Detailed(ref det) => Some((name, det)),
Dependency::Simple(_) => None,
})
}
pub fn patches(&self) -> impl Iterator<Item = (&String, &PatchMap)> {
self.patch
.as_ref()
.into_iter()
.flat_map(|patches| patches.iter())
}
fn implicitly_include_std_if_missing(&mut self) {
use crate::{CORE, STD};
if self.project.name == CORE
|| self.project.name == STD
|| self.pkg_dep(CORE).is_some()
|| self.pkg_dep(STD).is_some()
|| self.dep(STD).is_some()
|| !self.project.implicit_std.unwrap_or(true)
{
return;
}
let deps = self.dependencies.get_or_insert_with(Default::default);
let std_dep = implicit_std_dep();
deps.insert(STD.to_string(), std_dep);
}
fn implicitly_include_default_build_profiles_if_missing(&mut self) {
let build_profiles = self.build_profile.get_or_insert_with(Default::default);
if build_profiles.get(BuildProfile::DEBUG).is_none() {
build_profiles.insert(BuildProfile::DEBUG.into(), BuildProfile::debug());
}
if build_profiles.get(BuildProfile::RELEASE).is_none() {
build_profiles.insert(BuildProfile::RELEASE.into(), BuildProfile::release());
}
}
pub fn dep(&self, dep_name: &str) -> Option<&Dependency> {
self.dependencies
.as_ref()
.and_then(|deps| deps.get(dep_name))
}
pub fn dep_detailed(&self, dep_name: &str) -> Option<&DependencyDetails> {
self.dep(dep_name).and_then(|dep| match dep {
Dependency::Simple(_) => None,
Dependency::Detailed(detailed) => Some(detailed),
})
}
pub fn patch(&self, patch_name: &str) -> Option<&PatchMap> {
self.patch
.as_ref()
.and_then(|patches| patches.get(patch_name))
}
pub fn contract_dep(&self, contract_dep_name: &str) -> Option<&ContractDependency> {
self.contract_dependencies
.as_ref()
.and_then(|contract_dependencies| contract_dependencies.get(contract_dep_name))
}
pub fn contract_dependency_detailed(
&self,
contract_dep_name: &str,
) -> Option<&DependencyDetails> {
self.contract_dep(contract_dep_name)
.and_then(|contract_dep| match &contract_dep.dependency {
Dependency::Simple(_) => None,
Dependency::Detailed(detailed) => Some(detailed),
})
}
fn pkg_dep<'a>(&'a self, pkg_name: &str) -> Option<&'a str> {
for (dep_name, dep) in self.deps() {
if dep.package().unwrap_or(dep_name) == pkg_name {
return Some(dep_name);
}
}
None
}
}
impl BuildProfile {
pub const DEBUG: &'static str = "debug";
pub const RELEASE: &'static str = "release";
pub const DEFAULT: &'static str = Self::DEBUG;
pub fn debug() -> Self {
Self {
print_ast: false,
print_dca_graph: false,
print_ir: false,
print_finalized_asm: false,
print_intermediate_asm: false,
terse: false,
time_phases: false,
include_tests: false,
}
}
pub fn release() -> Self {
Self {
print_ast: false,
print_dca_graph: false,
print_ir: false,
print_finalized_asm: false,
print_intermediate_asm: false,
terse: false,
time_phases: false,
include_tests: false,
}
}
}
impl std::ops::Deref for PackageManifestFile {
type Target = PackageManifest;
fn deref(&self) -> &Self::Target {
&self.manifest
}
}
impl Default for BuildProfile {
fn default() -> Self {
Self::debug()
}
}
fn implicit_std_dep() -> Dependency {
const VERSION: &str = env!("CARGO_PKG_VERSION");
const SWAY_GIT_REPO_URL: &str = "https://github.com/fuellabs/sway";
fn rev_from_build_metadata(build_metadata: &str) -> Option<String> {
build_metadata.split('.').last().map(|r| r.to_string())
}
let sway_git_tag: String = "v".to_string() + VERSION;
let mut det = DependencyDetails {
git: Some(SWAY_GIT_REPO_URL.to_string()),
tag: Some(sway_git_tag),
..Default::default()
};
if let Some((_tag, build_metadata)) = VERSION.split_once('+') {
let rev = rev_from_build_metadata(build_metadata);
det.tag = None;
det.rev = rev;
};
Dependency::Detailed(det)
}
fn default_entry() -> String {
PackageManifest::DEFAULT_ENTRY_FILE_NAME.to_string()
}
fn default_url() -> String {
constants::DEFAULT_NODE_URL.into()
}
#[derive(Clone, Debug)]
pub struct WorkspaceManifestFile {
manifest: WorkspaceManifest,
path: PathBuf,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct WorkspaceManifest {
workspace: Workspace,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct Workspace {
pub members: Vec<PathBuf>,
}
impl WorkspaceManifestFile {
pub fn from_file(path: PathBuf) -> Result<Self> {
let path = path.canonicalize()?;
let parent = path
.parent()
.ok_or_else(|| anyhow!("Cannot get parent dir of {:?}", path))?;
let manifest = WorkspaceManifest::from_file(&path)?;
manifest.validate(parent)?;
Ok(Self { manifest, path })
}
pub fn from_dir(manifest_dir: &Path) -> Result<Self> {
let dir = forc_util::find_manifest_dir_with_check(manifest_dir, |possible_manifest_dir| {
let possible_path = possible_manifest_dir.join(constants::MANIFEST_FILE_NAME);
Self::from_file(possible_path)
.err()
.map(|e| !e.to_string().contains("missing field `workspace`"))
.unwrap_or_else(|| true)
})
.ok_or_else(|| manifest_file_missing(manifest_dir))?;
let path = dir.join(constants::MANIFEST_FILE_NAME);
Self::from_file(path)
}
pub fn members(&self) -> impl Iterator<Item = &PathBuf> + '_ {
self.workspace.members.iter()
}
pub fn member_paths(&self) -> Result<impl Iterator<Item = PathBuf> + '_> {
Ok(self
.workspace
.members
.iter()
.map(|member| self.dir().join(member)))
}
pub fn member_pkg_manifests(
&self,
) -> Result<impl Iterator<Item = Result<PackageManifestFile>> + '_> {
let member_paths = self.member_paths()?;
let member_pkg_manifests =
member_paths.map(|member_path| PackageManifestFile::from_dir(&member_path));
Ok(member_pkg_manifests)
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn dir(&self) -> &Path {
self.path()
.parent()
.expect("failed to retrieve manifest directory")
}
pub fn is_member_path(&self, path: &Path) -> Result<bool> {
Ok(self.member_paths()?.any(|member_path| member_path == path))
}
pub fn lock_path(&self) -> PathBuf {
self.dir().to_path_buf().join(constants::LOCK_FILE_NAME)
}
}
impl WorkspaceManifest {
pub fn from_file(path: &Path) -> Result<Self> {
let mut warnings = vec![];
let manifest_str = std::fs::read_to_string(path)
.map_err(|e| anyhow!("failed to read manifest at {:?}: {}", path, e))?;
let toml_de = &mut toml::de::Deserializer::new(&manifest_str);
let manifest: Self = serde_ignored::deserialize(toml_de, |path| {
let warning = format!(" WARNING! unused manifest key: {}", path);
warnings.push(warning);
})
.map_err(|e| anyhow!("failed to parse manifest: {}.", e))?;
for warning in warnings {
println_yellow_err(&warning);
}
Ok(manifest)
}
pub fn validate(&self, path: &Path) -> Result<()> {
for member in self.workspace.members.iter() {
let member_path = path.join(member).join("Forc.toml");
if !member_path.exists() {
bail!(
"{:?} is listed as a member of the workspace but {:?} does not exists",
&member,
member_path
);
}
}
Ok(())
}
}
impl std::ops::Deref for WorkspaceManifestFile {
type Target = WorkspaceManifest;
fn deref(&self) -> &Self::Target {
&self.manifest
}
}