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
use crate::{
lock::Lock,
manifest::{Dependency, Manifest},
};
use anyhow::{anyhow, bail, Result};
use forc_util::{
find_file_name, git_checkouts_directory, print_on_failure, print_on_success,
print_on_success_library, println_yellow_err,
};
use petgraph::{self, visit::EdgeRef, Directed, Direction};
use serde::{Deserialize, Serialize};
use std::{
collections::{hash_map, BTreeSet, HashMap, HashSet},
hash::{Hash, Hasher},
path::{Path, PathBuf},
str::FromStr,
};
use sway_core::{
source_map::SourceMap, BytecodeCompilationResult, CompileAstResult, NamespaceRef,
NamespaceWrapper, TreeType, TypedParseTree,
};
use sway_types::JsonABI;
use url::Url;
type GraphIx = u32;
type Node = Pinned;
type Edge = ();
pub type Graph = petgraph::Graph<Node, Edge, Directed, GraphIx>;
pub type NodeIx = petgraph::graph::NodeIndex<GraphIx>;
pub type PathMap = HashMap<PinnedId, PathBuf>;
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub struct PinnedId(u64);
pub struct Compiled {
pub json_abi: JsonABI,
pub bytecode: Vec<u8>,
}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Deserialize, Serialize)]
pub struct Pkg {
pub name: String,
pub source: Source,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
pub struct Pinned {
pub name: String,
pub source: SourcePinned,
}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Deserialize, Serialize)]
pub enum Source {
Git(SourceGit),
Path(PathBuf),
Registry(SourceRegistry),
}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Deserialize, Serialize)]
pub struct SourceGit {
pub repo: Url,
pub reference: String,
}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Deserialize, Serialize)]
pub struct SourceRegistry {
pub version: semver::Version,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
pub struct SourceGitPinned {
pub source: SourceGit,
pub commit_hash: String,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
pub struct SourceRegistryPinned {
pub source: SourceRegistry,
pub version: semver::Version,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
pub enum SourcePinned {
Git(SourceGitPinned),
Path,
Registry(SourceRegistryPinned),
}
#[derive(Clone)]
pub struct BuildPlan {
graph: Graph,
path_map: PathMap,
compilation_order: Vec<NodeIx>,
}
pub struct BuildConfig {
pub use_ir: bool,
pub print_ir: bool,
pub print_finalized_asm: bool,
pub print_intermediate_asm: bool,
pub silent: bool,
}
#[derive(Clone, Debug)]
pub enum SourceGitPinnedParseError {
Prefix,
Url,
Reference,
CommitHash,
}
impl BuildPlan {
pub fn new(manifest_dir: &Path, offline: bool) -> Result<Self> {
let manifest = Manifest::from_dir(manifest_dir)?;
let (graph, path_map) = fetch_deps(manifest_dir.to_path_buf(), &manifest, offline)?;
let compilation_order = compilation_order(&graph)?;
Ok(Self {
graph,
path_map,
compilation_order,
})
}
pub fn from_lock(proj_path: &Path, lock: &Lock) -> Result<Self> {
let graph = lock.to_graph()?;
let compilation_order = compilation_order(&graph)?;
let path_map = graph_to_path_map(proj_path, &graph, &compilation_order)?;
Ok(Self {
graph,
path_map,
compilation_order,
})
}
pub fn from_lock_file(lock_path: &Path) -> Result<Self> {
let proj_path = lock_path.parent().unwrap();
let lock = Lock::from_path(lock_path)?;
Self::from_lock(proj_path, &lock)
}
pub fn validate(&self, manifest: &Manifest) -> Result<()> {
let proj_node = *self
.compilation_order
.last()
.ok_or_else(|| anyhow!("Invalid Graph"))?;
let plan_dep_pkgs: BTreeSet<_> = self
.graph
.edges_directed(proj_node, Direction::Outgoing)
.map(|e| self.graph[e.target()].unpinned(&self.path_map))
.collect();
let proj_id = self.graph[proj_node].id();
let proj_path = &self.path_map[&proj_id];
let manifest_dep_pkgs = manifest
.dependencies
.as_ref()
.into_iter()
.flat_map(|deps| deps.iter())
.map(|(name, dep)| {
if let Dependency::Detailed(det) = dep {
if det.version.is_some() {
println_yellow_err(&format!(
" WARNING! Dependency \"{}\" specifies the unused `version` field: \
consider using `branch` or `tag` instead",
name
))
.unwrap();
}
}
let name = name.clone();
let source = dep_to_source(proj_path, dep)?;
Ok(Pkg { name, source })
})
.collect::<Result<BTreeSet<_>>>()?;
if plan_dep_pkgs != manifest_dep_pkgs {
bail!("Manifest dependencies do not match");
}
Ok(())
}
pub fn graph(&self) -> &Graph {
&self.graph
}
pub fn path_map(&self) -> &PathMap {
&self.path_map
}
pub fn compilation_order(&self) -> &[NodeIx] {
&self.compilation_order
}
}
impl Pinned {
pub fn id(&self) -> PinnedId {
PinnedId::new(&self.name, &self.source)
}
pub fn unpinned(&self, path_map: &PathMap) -> Pkg {
let id = self.id();
let source = match &self.source {
SourcePinned::Git(git) => Source::Git(git.source.clone()),
SourcePinned::Path => Source::Path(path_map[&id].to_path_buf()),
SourcePinned::Registry(reg) => Source::Registry(reg.source.clone()),
};
let name = self.name.clone();
Pkg { name, source }
}
}
impl PinnedId {
pub fn new(name: &str, source: &SourcePinned) -> Self {
let mut hasher = hash_map::DefaultHasher::default();
name.hash(&mut hasher);
source.hash(&mut hasher);
Self(hasher.finish())
}
}
impl ToString for SourceGitPinned {
fn to_string(&self) -> String {
format!(
"git+{}?reference={}#{}",
self.source.repo, self.source.reference, self.commit_hash,
)
}
}
impl FromStr for SourceGitPinned {
type Err = SourceGitPinnedParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let s = s.trim();
const PREFIX: &str = "git+";
if s.find(PREFIX) != Some(0) {
return Err(SourceGitPinnedParseError::Prefix);
}
let s = &s[PREFIX.len()..];
let repo_str = s.split('?').next().ok_or(SourceGitPinnedParseError::Url)?;
let repo = Url::parse(repo_str).map_err(|_| SourceGitPinnedParseError::Url)?;
let s = &s[repo_str.len() + "?".len()..];
const REFERENCE: &str = "reference=";
if s.find(REFERENCE) != Some(0) {
return Err(SourceGitPinnedParseError::Reference);
}
let s = &s[REFERENCE.len()..];
let mut s_iter = s.split('#');
let reference = s_iter
.next()
.ok_or(SourceGitPinnedParseError::Reference)?
.to_string();
let commit_hash = s_iter
.next()
.ok_or(SourceGitPinnedParseError::CommitHash)?
.to_string();
let source = SourceGit { repo, reference };
Ok(Self {
source,
commit_hash,
})
}
}
pub fn compilation_order(graph: &Graph) -> Result<Vec<NodeIx>> {
let rev_pkg_graph = petgraph::visit::Reversed(&graph);
petgraph::algo::toposort(rev_pkg_graph, None)
.map_err(|e| anyhow!("dependency cycle detected: {:?}", e))
}
pub fn graph_to_path_map(
proj_manifest_dir: &Path,
graph: &Graph,
compilation_order: &[NodeIx],
) -> Result<PathMap> {
let mut path_map = PathMap::new();
let mut path_resolve_order = compilation_order.iter().cloned().rev();
let proj_node = path_resolve_order
.next()
.ok_or_else(|| anyhow!("graph must contain at least the project node"))?;
let proj_id = graph[proj_node].id();
path_map.insert(proj_id, proj_manifest_dir.to_path_buf());
let fetch_ts = std::time::Instant::now();
let fetch_id = fetch_id(&path_map[&proj_id], fetch_ts);
for dep_node in path_resolve_order {
let dep = &graph[dep_node];
let dep_path = match &dep.source {
SourcePinned::Git(git) => {
git_commit_path(&dep.name, &git.source.repo, &git.commit_hash)
}
SourcePinned::Path => {
let parent_node = graph
.edges_directed(dep_node, Direction::Incoming)
.next()
.ok_or_else(|| anyhow!("more than one root package detected in graph"))?
.source();
let parent = &graph[parent_node];
let parent_path = &path_map[&parent.id()];
let parent_manifest = Manifest::from_dir(parent_path)?;
let detailed = parent_manifest
.dependencies
.as_ref()
.and_then(|deps| match &deps[&dep.name] {
Dependency::Detailed(detailed) => Some(detailed),
Dependency::Simple(_) => None,
})
.ok_or_else(|| anyhow!("missing path info for dependency: {}", dep.name))?;
let rel_dep_path = detailed
.path
.as_ref()
.ok_or_else(|| anyhow!("missing path info for dependency: {}", dep.name))?;
parent_path.join(rel_dep_path)
}
SourcePinned::Registry(_reg) => {
bail!("registry dependencies are not yet supported");
}
};
if !dep_path.exists() {
match &dep.source {
SourcePinned::Path => {
bail!("pinned `path` dependency \"{}\" source missing", dep.name);
}
SourcePinned::Git(git) => {
println!(" Fetching {}", git.to_string());
fetch_git(fetch_id, &dep.name, git)?;
}
SourcePinned::Registry(_reg) => {
bail!("registry dependencies are not yet supported");
}
}
}
path_map.insert(dep.id(), dep_path);
}
Ok(path_map)
}
pub(crate) fn fetch_deps(
proj_manifest_dir: PathBuf,
proj_manifest: &Manifest,
offline_mode: bool,
) -> Result<(Graph, PathMap)> {
let mut graph = Graph::new();
let mut path_map = PathMap::new();
let name = proj_manifest.project.name.clone();
let path = proj_manifest_dir;
let source = SourcePinned::Path;
let pkg = Pinned { name, source };
let pkg_id = pkg.id();
path_map.insert(pkg_id, path);
let root = graph.add_node(pkg);
let mut visited = HashMap::new();
visited.insert(graph[root].clone(), root);
let fetch_ts = std::time::Instant::now();
let fetch_id = fetch_id(&path_map[&pkg_id], fetch_ts);
fetch_children(
fetch_id,
offline_mode,
root,
&mut graph,
&mut path_map,
&mut visited,
)?;
Ok((graph, path_map))
}
fn fetch_id(path: &Path, timestamp: std::time::Instant) -> u64 {
let mut hasher = hash_map::DefaultHasher::new();
path.hash(&mut hasher);
timestamp.hash(&mut hasher);
hasher.finish()
}
fn fetch_children(
fetch_id: u64,
offline_mode: bool,
node: NodeIx,
graph: &mut Graph,
path_map: &mut PathMap,
visited: &mut HashMap<Pinned, NodeIx>,
) -> Result<()> {
let parent = &graph[node];
let parent_path = path_map[&parent.id()].clone();
let manifest = Manifest::from_dir(&parent_path)?;
let deps = match &manifest.dependencies {
None => return Ok(()),
Some(deps) => deps,
};
for (name, dep) in deps {
let name = name.clone();
let source = dep_to_source(&parent_path, dep)?;
if offline_mode && !matches!(source, Source::Path(_)) {
bail!("Unable to fetch pkg {:?} in offline mode", source);
}
let pkg = Pkg { name, source };
let pinned = pin_pkg(fetch_id, &pkg, path_map)?;
let dep_node = if let hash_map::Entry::Vacant(entry) = visited.entry(pinned.clone()) {
let node = graph.add_node(pinned);
entry.insert(node);
fetch_children(fetch_id, offline_mode, node, graph, path_map, visited)?;
node
} else {
visited[&pinned]
};
graph.add_edge(node, dep_node, ());
}
Ok(())
}
fn git_repo_dir_name(name: &str, repo: &Url) -> String {
let repo_url_hash = hash_url(repo);
format!("{}-{:x}", name, repo_url_hash)
}
fn hash_url(url: &Url) -> u64 {
let mut hasher = hash_map::DefaultHasher::new();
url.hash(&mut hasher);
hasher.finish()
}
fn tmp_git_repo_dir(fetch_id: u64, name: &str, repo: &Url) -> PathBuf {
let repo_dir_name = format!("{:x}-{}", fetch_id, git_repo_dir_name(name, repo));
git_checkouts_directory().join("tmp").join(repo_dir_name)
}
fn with_tmp_git_repo<F, O>(fetch_id: u64, name: &str, source: &Url, f: F) -> Result<O>
where
F: FnOnce(git2::Repository) -> Result<O>,
{
let repo_dir = tmp_git_repo_dir(fetch_id, name, source);
if repo_dir.exists() {
let _ = std::fs::remove_dir_all(&repo_dir);
}
let repo_url_string = format!("{}", source);
let repo = git2::Repository::clone(&repo_url_string, &repo_dir).map_err(|e| {
anyhow!(
"failed to clone package '{}' from '{}': {}",
name,
source,
e
)
})?;
let output = f(repo)?;
if repo_dir.exists() {
let _ = std::fs::remove_dir_all(&repo_dir);
}
Ok(output)
}
fn pin_git(fetch_id: u64, name: &str, source: SourceGit) -> Result<SourceGitPinned> {
let commit_hash = with_tmp_git_repo(fetch_id, name, &source.repo, |repo| {
let reference = repo
.resolve_reference_from_short_name(&source.reference)
.map_err(|e| {
anyhow!(
"failed to find git ref '{}' for package '{}': {}",
source.reference,
name,
e
)
})?;
let commit = reference.peel_to_commit().map_err(|e| {
anyhow!(
"failed to obtain commit for ref '{}' of package '{}': {}",
source.reference,
name,
e
)
})?;
Ok(format!("{}", commit.id()))
})?;
Ok(SourceGitPinned {
source,
commit_hash,
})
}
fn pin_pkg(fetch_id: u64, pkg: &Pkg, path_map: &mut PathMap) -> Result<Pinned> {
let name = pkg.name.clone();
let pinned = match &pkg.source {
Source::Path(path) => {
let source = SourcePinned::Path;
let pinned = Pinned { name, source };
let id = pinned.id();
path_map.insert(id, path.clone());
pinned
}
Source::Git(ref source) => {
let pinned_git = pin_git(fetch_id, &name, source.clone())?;
let path = git_commit_path(&name, &pinned_git.source.repo, &pinned_git.commit_hash);
let source = SourcePinned::Git(pinned_git.clone());
let pinned = Pinned { name, source };
let id = pinned.id();
if let hash_map::Entry::Vacant(entry) = path_map.entry(id) {
if !path.exists() {
println!(" Fetching {}", pinned_git.to_string());
fetch_git(fetch_id, &pinned.name, &pinned_git)?;
}
entry.insert(path);
}
pinned
}
Source::Registry(ref _source) => {
bail!("registry dependencies are not yet supported");
}
};
Ok(pinned)
}
fn git_commit_path(name: &str, repo: &Url, commit_hash: &str) -> PathBuf {
let repo_dir_name = git_repo_dir_name(name, repo);
git_checkouts_directory()
.join(repo_dir_name)
.join(commit_hash)
}
fn fetch_git(fetch_id: u64, name: &str, pinned: &SourceGitPinned) -> Result<PathBuf> {
let path = git_commit_path(name, &pinned.source.repo, &pinned.commit_hash);
with_tmp_git_repo(fetch_id, name, &pinned.source.repo, |repo| {
let id = git2::Oid::from_str(&pinned.commit_hash)?;
repo.set_head_detached(id)?;
if path.exists() {
let _ = std::fs::remove_dir_all(&path);
}
std::fs::create_dir_all(&path)?;
let mut checkout = git2::build::CheckoutBuilder::new();
checkout.force().target_dir(&path);
repo.checkout_head(Some(&mut checkout))?;
Ok(())
})?;
Ok(path)
}
fn dep_to_source(pkg_path: &Path, dep: &Dependency) -> Result<Source> {
let source = match dep {
Dependency::Simple(ref ver_str) => {
bail!(
"Unsupported dependency declaration in \"{}\": `{}` - \
currently only `git` and `path` dependencies are supported",
pkg_path.display(),
ver_str
)
}
Dependency::Detailed(ref det) => {
match (&det.path, &det.version, &det.git, &det.branch, &det.tag) {
(Some(relative_path), _, _, _, _) => {
let path = pkg_path.join(relative_path);
Source::Path(path)
}
(_, _, Some(repo), branch, tag) => {
let reference = match (branch, tag) {
(Some(branch), None) => branch.clone(),
(None, Some(tag)) => tag.clone(),
_ => "master".to_string(),
};
let repo = Url::parse(repo)?;
let source = SourceGit { repo, reference };
Source::Git(source)
}
_ => {
bail!("unsupported set of arguments for dependency: {:?}", dep);
}
}
}
};
Ok(source)
}
pub fn sway_build_config(
path: PathBuf,
manifest: &Manifest,
build_conf: &BuildConfig,
) -> Result<sway_core::BuildConfig> {
let entry_path = manifest.entry_path(&path);
let file_name = find_file_name(&path, &entry_path)?;
let build_config = sway_core::BuildConfig::root_from_file_name_and_manifest_path(
file_name.to_path_buf(),
path.to_path_buf(),
)
.use_ir(build_conf.use_ir || build_conf.print_ir)
.print_finalized_asm(build_conf.print_finalized_asm)
.print_intermediate_asm(build_conf.print_intermediate_asm)
.print_ir(build_conf.print_ir);
Ok(build_config)
}
pub fn dependency_namespace(
namespace_map: &HashMap<NodeIx, NamespaceRef>,
graph: &Graph,
compilation_order: &[NodeIx],
node: NodeIx,
) -> NamespaceRef {
use petgraph::visit::{Dfs, Walker};
let deps: HashSet<NodeIx> = Dfs::new(graph, node).iter(graph).collect();
let namespace = sway_core::create_module();
for dep_node in compilation_order.iter().filter(|n| deps.contains(n)) {
if *dep_node == node {
break;
}
namespace.insert_module_ref(graph[*dep_node].name.clone(), namespace_map[dep_node]);
}
namespace
}
pub fn compile(
pkg: &Pinned,
pkg_path: &Path,
build_config: &BuildConfig,
namespace: NamespaceRef,
source_map: &mut SourceMap,
) -> Result<(Compiled, Option<NamespaceRef>)> {
let manifest = Manifest::from_dir(pkg_path)?;
let source = manifest.entry_string(pkg_path)?;
let sway_build_config = sway_build_config(pkg_path.to_path_buf(), &manifest, build_config)?;
let silent_mode = build_config.silent;
let ast_res = sway_core::compile_to_ast(source, namespace, &sway_build_config);
match &ast_res {
CompileAstResult::Failure { warnings, errors } => {
print_on_failure(silent_mode, warnings, errors);
bail!("Failed to compile {}", pkg.name);
}
CompileAstResult::Success {
parse_tree,
tree_type,
warnings,
} => {
let json_abi = generate_json_abi(&*parse_tree);
match tree_type {
TreeType::Library { .. } => {
print_on_success_library(silent_mode, &pkg.name, warnings);
let bytecode = vec![];
let lib_namespace = parse_tree.clone().get_namespace_ref();
let compiled = Compiled { json_abi, bytecode };
Ok((compiled, Some(lib_namespace)))
}
TreeType::Contract | TreeType::Predicate | TreeType::Script => {
let tree_type = tree_type.clone();
let asm_res = sway_core::ast_to_asm(ast_res, &sway_build_config);
let bc_res = sway_core::asm_to_bytecode(asm_res, source_map);
match bc_res {
BytecodeCompilationResult::Success { bytes, warnings } => {
print_on_success(silent_mode, &pkg.name, &warnings, &tree_type);
let bytecode = bytes;
let compiled = Compiled { json_abi, bytecode };
Ok((compiled, None))
}
BytecodeCompilationResult::Library { .. } => {
unreachable!("compilation of library program types is handled above")
}
BytecodeCompilationResult::Failure { errors, warnings } => {
print_on_failure(silent_mode, &warnings, &errors);
bail!("Failed to compile {}", pkg.name);
}
}
}
}
}
}
}
pub fn build(plan: &BuildPlan, conf: &BuildConfig) -> anyhow::Result<(Compiled, SourceMap)> {
let mut namespace_map = Default::default();
let mut source_map = SourceMap::new();
let mut json_abi = vec![];
let mut bytecode = vec![];
for &node in &plan.compilation_order {
let dep_namespace =
dependency_namespace(&namespace_map, &plan.graph, &plan.compilation_order, node);
let pkg = &plan.graph[node];
let path = &plan.path_map[&pkg.id()];
let res = compile(pkg, path, conf, dep_namespace, &mut source_map)?;
let (compiled, maybe_namespace) = res;
if let Some(namespace) = maybe_namespace {
namespace_map.insert(node, namespace);
}
json_abi.extend(compiled.json_abi);
bytecode = compiled.bytecode;
source_map.insert_dependency(path.clone());
}
let compiled = Compiled { bytecode, json_abi };
Ok((compiled, source_map))
}
fn generate_json_abi(ast: &TypedParseTree) -> JsonABI {
match ast {
TypedParseTree::Contract { abi_entries, .. } => {
abi_entries.iter().map(|x| x.generate_json_abi()).collect()
}
_ => vec![],
}
}
#[test]
fn test_source_git_pinned_parsing() {
let strings = [
"git+https://github.com/foo/bar?reference=baz#64092602dd6158f3e41d775ed889389440a2cd86",
"git+https://github.com/fuellabs/sway-lib-std?reference=v0.1.0#0000000000000000000000000000000000000000",
"git+https://github.com/fuellabs/sway-lib-core?reference=v0.0.1#0000000000000000000000000000000000000000",
];
let expected = [
SourceGitPinned {
source: SourceGit {
repo: Url::parse("https://github.com/foo/bar").unwrap(),
reference: "baz".to_string(),
},
commit_hash: "64092602dd6158f3e41d775ed889389440a2cd86".to_string(),
},
SourceGitPinned {
source: SourceGit {
repo: Url::parse("https://github.com/fuellabs/sway-lib-std").unwrap(),
reference: "v0.1.0".to_string(),
},
commit_hash: "0000000000000000000000000000000000000000".to_string(),
},
SourceGitPinned {
source: SourceGit {
repo: Url::parse("https://github.com/fuellabs/sway-lib-core").unwrap(),
reference: "v0.0.1".to_string(),
},
commit_hash: "0000000000000000000000000000000000000000".to_string(),
},
];
for (&string, expected) in strings.iter().zip(&expected) {
let parsed = SourceGitPinned::from_str(string).unwrap();
assert_eq!(&parsed, expected);
let serialized = expected.to_string();
assert_eq!(&serialized, string);
}
}