forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.rs
More file actions
2181 lines (2027 loc) · 72.7 KB
/
Copy pathbuild.rs
File metadata and controls
2181 lines (2027 loc) · 72.7 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 std::{
collections::{BTreeMap, BTreeSet, HashMap, HashSet},
fs,
};
use camino::{Utf8Path, Utf8PathBuf};
use codegen::{OptLevel, SonatinaContractBytecode};
use common::{
InputDb,
config::{
ArithmeticMode, Config, DependencyArithmeticMode, resolve_dependency_arithmetic_mode,
},
dependencies::WorkspaceMemberRecord,
file::IngotFileKind,
ingot::{IngotBaseUrl, IngotKind},
};
use driver::DriverDataBase;
use driver::cli_target::{CliTarget, resolve_cli_target};
use hir::hir_def::{HirIngot, ManualContractRootAttr, TopLevelMod};
use hir::lower::map_file_to_mod;
use mir::build_runtime_package;
use salsa::Setter;
use smol_str::SmolStr;
use tiny_keccak::{Hasher, Keccak};
use url::Url;
use crate::{
BuildEmit,
dependency_diagnostics::{CompilationDiagnostics, DependencyIssues},
report::{
ReportStaging, copy_input_into_report, create_dir_all_utf8, create_report_staging_root,
enable_panic_report, normalize_report_out_path, tar_gz_dir, write_report_meta,
},
workspace_ingot::{
INGOT_REQUIRES_WORKSPACE_ROOT, WorkspaceMemberRef, ingot_has_source_files,
select_workspace_member_paths,
},
};
#[derive(Debug, Default, Clone, Copy)]
struct BuildSummary {
had_errors: bool,
}
#[derive(Debug, Clone)]
struct BuildReportContext {
root_dir: Utf8PathBuf,
}
#[derive(Debug, Default)]
struct IngotBuildAnalysis {
contract_names: Vec<String>,
abi_artifact_names: Vec<String>,
}
#[derive(Debug, Clone, Copy)]
struct EmitSelection {
bytecode: bool,
runtime_bytecode: bool,
ir: bool,
abi: bool,
metadata: bool,
}
impl EmitSelection {
fn from_requested(requested: &[BuildEmit]) -> Self {
let mut selection = Self {
bytecode: false,
runtime_bytecode: false,
ir: false,
abi: false,
metadata: false,
};
for emit in requested {
match emit {
BuildEmit::Bytecode => selection.bytecode = true,
BuildEmit::RuntimeBytecode => selection.runtime_bytecode = true,
BuildEmit::Ir => selection.ir = true,
BuildEmit::Abi => selection.abi = true,
BuildEmit::Metadata => selection.metadata = true,
}
}
selection
}
fn writes_any_bytecode(self) -> bool {
self.bytecode || self.runtime_bytecode
}
}
fn create_build_report_staging() -> Result<ReportStaging, String> {
create_report_staging_root("target/fe-build-report-staging", "fe-build-report")
}
fn write_report_file(report: &BuildReportContext, rel: &str, contents: &str) {
let path = report.root_dir.join(rel);
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent.as_std_path());
}
let _ = std::fs::write(path.as_std_path(), contents);
}
#[allow(clippy::too_many_arguments)]
fn write_build_manifest(
report: &BuildReportContext,
path: &Utf8PathBuf,
ingot: Option<&str>,
force_standalone: bool,
contract: Option<&str>,
opt_level: OptLevel,
emit: EmitSelection,
out_dir: Option<&Utf8PathBuf>,
has_errors: bool,
) {
let mut out = String::new();
out.push_str("fe build report\n");
out.push_str(&format!("path: {path}\n"));
out.push_str(&format!("ingot: {}\n", ingot.unwrap_or("<all>")));
out.push_str(&format!("standalone: {force_standalone}\n"));
out.push_str(&format!("contract: {}\n", contract.unwrap_or("<all>")));
out.push_str("backend: sonatina\n");
out.push_str(&format!("opt_level: {opt_level}\n"));
out.push_str(&format!("emit: {}\n", describe_emit_selection(emit)));
out.push_str(&format!(
"out_dir: {}\n",
out_dir.map(|p| p.as_str()).unwrap_or("<default>")
));
out.push_str(&format!(
"status: {}\n",
if has_errors { "failed" } else { "ok" }
));
out.push_str(&format!("fe_version: {}\n", env!("CARGO_PKG_VERSION")));
write_report_file(report, "manifest.txt", &out);
}
fn report_scope_dir(report: Option<&BuildReportContext>, scope: &str) -> Option<Utf8PathBuf> {
let report = report?;
let dir = report
.root_dir
.join("artifacts")
.join(sanitize_filename(scope));
let _ = create_dir_all_utf8(&dir);
Some(dir)
}
#[allow(clippy::too_many_arguments)]
pub fn build(
path: &Utf8PathBuf,
ingot: Option<&str>,
force_standalone: bool,
contract: Option<&str>,
opt_level: OptLevel,
emit: &[BuildEmit],
out_dir: Option<&Utf8PathBuf>,
profile: &str,
report_out: Option<&Utf8PathBuf>,
report_failed_only: bool,
use_recovery_mode: bool,
) {
let emit = EmitSelection::from_requested(emit);
let mut db = DriverDataBase::default();
db.compiler_options()
.set_recovery_mode(&mut db)
.to(use_recovery_mode);
db.compilation_settings()
.set_profile(&mut db)
.to(profile.into());
let report_root = match report_out
.map(|out| -> Result<_, String> {
let staging = create_build_report_staging()?;
let out = normalize_report_out_path(out)?;
Ok((out, staging))
})
.transpose()
{
Ok(v) => v,
Err(err) => {
eprintln!("Error: {err}");
std::process::exit(1);
}
};
let report_ctx = match report_root
.as_ref()
.map(|(_, staging)| -> Result<_, String> {
let root = &staging.root_dir;
create_dir_all_utf8(&root.join("inputs"))?;
create_dir_all_utf8(&root.join("artifacts"))?;
create_dir_all_utf8(&root.join("errors"))?;
write_report_meta(root, "fe build report", None);
Ok(BuildReportContext {
root_dir: root.clone(),
})
})
.transpose()
{
Ok(v) => v,
Err(err) => {
eprintln!("Error: {err}");
std::process::exit(1);
}
};
let _panic_guard = report_ctx
.as_ref()
.map(|report| enable_panic_report(report.root_dir.join("errors/panic_full.txt")));
let target = match resolve_cli_target(&mut db, path, force_standalone) {
Ok(target) => target,
Err(message) => {
eprintln!("Error: {message}");
if let Some(report) = report_ctx.as_ref() {
write_report_file(report, "errors/cli_target.txt", &format!("{message}\n"));
}
if let Some((out, staging)) = report_root {
let has_errors = true;
if report_ctx.as_ref().is_some() && (!report_failed_only || has_errors) {
write_build_manifest(
report_ctx.as_ref().expect("report ctx"),
path,
ingot,
force_standalone,
contract,
opt_level,
emit,
out_dir,
has_errors,
);
if let Err(err) = tar_gz_dir(&staging.root_dir, &out) {
eprintln!("Error: failed to write report `{out}`: {err}");
eprintln!("Report staging directory left at `{}`", staging.temp_dir);
} else {
let _ = std::fs::remove_dir_all(&staging.temp_dir);
println!("wrote report: {out}");
}
} else {
let _ = std::fs::remove_dir_all(&staging.temp_dir);
}
}
std::process::exit(1);
}
};
if let Some(report) = report_ctx.as_ref() {
let inputs_dir = report.root_dir.join("inputs");
let source = match &target {
CliTarget::StandaloneFile(file) => file,
CliTarget::Directory(dir) => dir,
};
if let Err(err) = copy_input_into_report(source, &inputs_dir) {
write_report_file(report, "errors/report_inputs.txt", &format!("{err}\n"));
}
}
let had_errors = match target {
CliTarget::StandaloneFile(file_path) => build_file(
&mut db,
&file_path,
ingot,
contract,
opt_level,
emit,
out_dir,
report_ctx.as_ref(),
),
CliTarget::Directory(dir_path) => build_directory(
&mut db,
&dir_path,
ingot,
contract,
None,
opt_level,
emit,
out_dir,
report_ctx.as_ref(),
),
};
if let Some((out, staging)) = report_root {
let should_write = !report_failed_only || had_errors;
if should_write {
write_build_manifest(
report_ctx.as_ref().expect("report ctx"),
path,
ingot,
force_standalone,
contract,
opt_level,
emit,
out_dir,
had_errors,
);
if let Err(err) = tar_gz_dir(&staging.root_dir, &out) {
eprintln!("Error: failed to write report `{out}`: {err}");
eprintln!("Report staging directory left at `{}`", staging.temp_dir);
} else {
// Best-effort cleanup.
let _ = std::fs::remove_dir_all(&staging.temp_dir);
println!("wrote report: {out}");
}
} else {
let _ = std::fs::remove_dir_all(&staging.temp_dir);
}
}
if had_errors {
std::process::exit(1);
}
}
/// `fe build --from-metadata`: rebuild from a `metadata.json` recompilation
/// input instead of a source tree. Reads the metadata (from a file, or stdin
/// for `-`), materializes the recorded project into a temporary directory,
/// and runs the normal ingot build on it. Exits the process on failure.
pub fn build_from_metadata(
input: &Utf8Path,
contract: Option<&str>,
optimize: Option<&str>,
emit: &[BuildEmit],
out_dir: Option<&Utf8PathBuf>,
profile: &str,
use_recovery_mode: bool,
) {
let emit = EmitSelection::from_requested(emit);
let metadata = match crate::metadata_input::read_metadata(input) {
Ok(metadata) => metadata,
Err(err) => {
eprintln!("Error: {err}");
std::process::exit(1);
}
};
if let Err(err) = crate::metadata_input::validate_metadata(&metadata) {
eprintln!("Error: {err}");
std::process::exit(1);
}
// Exact reproduction is only guaranteed with the same compiler version.
if let Some(version) = metadata["compiler"]["version"].as_str() {
let running = env!("CARGO_PKG_VERSION");
if version != running {
eprintln!(
"Warning: metadata was produced by fe {version}, but this is fe {running}; \
the rebuilt bytecode may differ from the original"
);
}
}
// Non-release builds share a package version; the recorded commit pins the
// exact source revision.
if let (Some(recorded), Some(running)) = (
metadata["compiler"]["commit"].as_str(),
option_env!("FE_GIT_HASH").filter(|hash| !hash.is_empty()),
) && recorded != running
{
eprintln!(
"Warning: metadata was produced by fe commit {recorded}, but this is fe commit \
{running}; the rebuilt bytecode may differ from the original"
);
}
// The metadata's optimizer level is the default; an explicit `-O` wins.
let recorded_level = metadata["settings"]["optimizer"]["level"].as_str();
let level = match (optimize, recorded_level) {
(Some(flag), Some(recorded)) if flag != recorded => {
eprintln!(
"Warning: -O {flag} overrides optimizer level {recorded} recorded in the \
metadata; the rebuilt bytecode will not match the verified artifact"
);
flag
}
(Some(flag), _) => flag,
(None, Some(recorded)) => recorded,
(None, None) => "1",
};
let opt_level: OptLevel = match level.parse() {
Ok(level) => level,
Err(err) => {
eprintln!("Error: {err}");
std::process::exit(1);
}
};
// Default target: the contract recorded in `compilationTarget`; an
// explicit `--contract` overrides it.
let compilation_target = &metadata["settings"]["compilationTarget"];
let recorded_target = if compilation_target.is_null() {
None
} else {
let target = compilation_target
.as_object()
.filter(|target| target.len() == 1)
.and_then(|target| {
let (path, name) = target.iter().next()?;
Some((path.clone(), name.as_str()?.to_string()))
});
if target.is_none() {
eprintln!(
"Error: `settings.compilationTarget` must contain exactly one \
source-path/contract-name pair"
);
std::process::exit(1);
}
target
};
let contract = contract
.map(str::to_string)
.or_else(|| recorded_target.as_ref().map(|(_, name)| name.clone()));
// The recorded source path pins which module defines the target, in case
// another module defines a same-named contract; it only applies while
// building the recorded contract. Standalone-target metadata keys its
// source by bare file basename, which `reconstruct_project` materializes
// under `src/`; mirror that so the path resolves in the rebuilt ingot.
let target_source = recorded_target
.filter(|(_, name)| contract.as_deref() == Some(name))
.map(|(path, _)| {
if path.contains('/') {
path
} else {
format!("src/{path}")
}
});
let temp = match tempfile::Builder::new()
.prefix("fe-from-metadata")
.tempdir()
{
Ok(temp) => temp,
Err(err) => {
eprintln!("Error: Failed to create temporary project directory: {err}");
std::process::exit(1);
}
};
let Some(temp_root) = Utf8Path::from_path(temp.path()) else {
eprintln!("Error: temporary project directory path is not valid UTF-8");
std::process::exit(1);
};
let root_dir = match crate::metadata_input::reconstruct_project(&metadata, temp_root) {
Ok(dir) => dir,
Err(err) => {
eprintln!("Error: {err}");
std::process::exit(1);
}
};
let out_dir = out_dir.cloned().unwrap_or_else(|| Utf8PathBuf::from("out"));
let mut db = DriverDataBase::default();
db.compiler_options()
.set_recovery_mode(&mut db)
.to(use_recovery_mode);
db.compilation_settings()
.set_profile(&mut db)
.to(profile.into());
let had_errors = build_directory(
&mut db,
&root_dir,
None,
contract.as_deref(),
target_source.as_deref(),
opt_level,
emit,
Some(&out_dir),
None,
);
drop(temp);
if had_errors {
std::process::exit(1);
}
}
#[allow(clippy::too_many_arguments)]
fn build_file(
db: &mut DriverDataBase,
file_path: &Utf8PathBuf,
ingot: Option<&str>,
contract: Option<&str>,
opt_level: OptLevel,
emit: EmitSelection,
out_dir: Option<&Utf8PathBuf>,
report: Option<&BuildReportContext>,
) -> bool {
if ingot.is_some() {
eprintln!("Error: {INGOT_REQUIRES_WORKSPACE_ROOT}");
return true;
}
let canonical = match file_path.canonicalize_utf8() {
Ok(path) => path,
Err(_) => {
eprintln!("Error: Invalid file path: {file_path}");
return true;
}
};
let url = match Url::from_file_path(canonical.as_std_path()) {
Ok(url) => url,
Err(_) => {
eprintln!("Error: Invalid file path: {file_path}");
return true;
}
};
let content = match fs::read_to_string(&canonical) {
Ok(content) => content,
Err(err) => {
eprintln!("Error: Failed to read file {file_path}: {err}");
return true;
}
};
db.workspace().touch(db, url.clone(), Some(content));
let Some(file) = db.workspace().get(db, &url) else {
eprintln!("Error: Could not process file {file_path}");
return true;
};
let top_mod = db.top_mod(file);
let diagnostics = CompilationDiagnostics::for_top_mod(db, top_mod, &url);
let mut has_errors = false;
if !diagnostics.hir.is_empty() {
diagnostics.hir.emit(db);
has_errors = true;
}
let dependency_has_errors = emit_dependency_diagnostics(db, &diagnostics.dependencies);
has_errors |= dependency_has_errors;
if !diagnostics.mir.is_empty() {
db.emit_complete_diagnostics(&diagnostics.mir);
has_errors = true;
}
if has_errors {
return true;
}
let default_out_dir = canonical
.parent()
.map(|parent| parent.join("out"))
.unwrap_or_else(|| Utf8PathBuf::from("out"));
let out_dir = out_dir.cloned().unwrap_or(default_out_dir);
let ir_file_stem = canonical
.file_stem()
.map(|stem| sanitize_name_with_default(stem, "module"))
.unwrap_or_else(|| "module".to_string());
let report_dir = report_scope_dir(
report,
&format!(
"file-{}",
canonical
.file_stem()
.map(|s| s.to_string())
.unwrap_or_else(|| "build".to_string())
),
);
build_top_mod(
db,
top_mod,
contract,
opt_level,
emit,
&out_dir,
&out_dir,
ir_file_stem.as_str(),
true,
report_dir.as_ref(),
)
.had_errors
}
#[allow(clippy::too_many_arguments)]
fn build_directory(
db: &mut DriverDataBase,
dir_path: &Utf8PathBuf,
ingot: Option<&str>,
contract: Option<&str>,
target_source: Option<&str>,
opt_level: OptLevel,
emit: EmitSelection,
out_dir: Option<&Utf8PathBuf>,
report: Option<&BuildReportContext>,
) -> bool {
let canonical = match dir_path.canonicalize_utf8() {
Ok(path) => path,
Err(_) => {
eprintln!("Error: Invalid or non-existent directory path: {dir_path}");
return true;
}
};
if !canonical.join("fe.toml").is_file() {
if ingot.is_some() {
eprintln!("Error: {INGOT_REQUIRES_WORKSPACE_ROOT}");
return true;
}
eprintln!("Error: No fe.toml file found in the provided directory: {canonical}");
return true;
}
let url = match Url::from_directory_path(canonical.as_str()) {
Ok(url) => url,
Err(_) => {
eprintln!("Error: Invalid directory path: {dir_path}");
return true;
}
};
if driver::init_ingot(db, &url) {
return true;
}
let config = match fs::read_to_string(canonical.join("fe.toml")) {
Ok(content) => match Config::parse(&content) {
Ok(config) => config,
Err(err) => {
eprintln!("Error: Failed to parse {}/fe.toml: {err}", canonical);
return true;
}
},
Err(err) => {
eprintln!("Error: Failed to read {}/fe.toml: {err}", canonical);
return true;
}
};
match config {
Config::Workspace(_) => build_workspace(
db, &canonical, url, ingot, contract, opt_level, emit, out_dir, report,
),
Config::Ingot(_) => {
if ingot.is_some() {
eprintln!("Error: {INGOT_REQUIRES_WORKSPACE_ROOT}");
return true;
}
let default_out_dir = canonical.join("out");
let out_dir = out_dir.cloned().unwrap_or(default_out_dir);
let report_dir = report_scope_dir(
report,
&format!(
"ingot-{}",
canonical
.file_name()
.map(|s| s.to_string())
.unwrap_or_else(|| "build".to_string())
),
);
build_ingot_url(
db,
&url,
contract,
target_source,
opt_level,
emit,
&out_dir,
None,
None,
true,
report_dir.as_ref(),
)
.had_errors
}
}
}
#[allow(clippy::too_many_arguments)]
fn build_workspace(
db: &mut DriverDataBase,
workspace_root: &Utf8PathBuf,
workspace_url: Url,
ingot: Option<&str>,
contract: Option<&str>,
opt_level: OptLevel,
emit: EmitSelection,
out_dir: Option<&Utf8PathBuf>,
report: Option<&BuildReportContext>,
) -> bool {
let mut members = db
.dependency_graph()
.workspace_member_records(db, &workspace_url);
members.sort_by(|a, b| a.path.cmp(&b.path));
if members.is_empty() {
eprintln!(
"Warning: No workspace members found. Check that member paths in fe.toml exist on disk."
);
return false;
}
let selected_member_paths = match select_workspace_member_paths(
workspace_root,
workspace_root,
members.iter().map(|member| {
WorkspaceMemberRef::new(member.path.as_path(), Some(member.name.as_str()))
}),
ingot,
) {
Ok(paths) => paths,
Err(err) => {
eprintln!("Error: {err}");
return true;
}
};
let selected_member_paths: HashSet<Utf8PathBuf> = selected_member_paths.into_iter().collect();
let out_dir = out_dir
.cloned()
.unwrap_or_else(|| workspace_root.join("out"));
let abi_collision_check_needs_filtering =
emit.abi && !emit.writes_any_bytecode() && contract.is_none();
let mut contract_names_by_member = Vec::with_capacity(selected_member_paths.len());
let mut abi_artifact_names_by_member = Vec::with_capacity(selected_member_paths.len());
for member in members {
let member_path = workspace_root.join(member.path.as_str());
if !selected_member_paths.contains(&member_path) {
continue;
}
let analysis = match analyze_ingot_build_artifacts(
db,
&member.url,
abi_collision_check_needs_filtering,
) {
Ok(analysis) => analysis,
Err(()) => return true,
};
contract_names_by_member.push((member.clone(), analysis.contract_names));
if abi_collision_check_needs_filtering {
abi_artifact_names_by_member.push((member, analysis.abi_artifact_names));
}
}
if let Some(contract) = contract {
let matches: Vec<_> = contract_names_by_member
.iter()
.filter(|(_, names)| names.iter().any(|name| name == contract))
.map(|(member, _)| member)
.collect();
match matches.len() {
0 => {
eprintln!("Error: Contract \"{contract}\" not found in any workspace member");
let mut available: Vec<String> = contract_names_by_member
.iter()
.flat_map(|(_, names)| names.iter().cloned())
.collect();
available.sort();
available.dedup();
if !available.is_empty() {
eprintln!("Available contracts:");
const MAX: usize = 50;
for name in available.iter().take(MAX) {
eprintln!(" - {name}");
}
if available.len() > MAX {
eprintln!(" ... and {} more", available.len() - MAX);
}
}
return true;
}
1 => {
let report_dir =
report_scope_dir(report, &format!("member-{}", matches[0].name.as_str()));
let summary = build_ingot_url(
db,
&matches[0].url,
Some(contract),
None,
opt_level,
emit,
&out_dir,
workspace_member_ir_out_dir(emit, &out_dir, matches[0].name.as_str()),
Some(matches[0].name.as_str()),
true,
report_dir.as_ref(),
);
return summary.had_errors;
}
_ => {
eprintln!(
"Error: Contract \"{contract}\" is defined in multiple workspace members"
);
eprintln!("Matches:");
for member in matches {
eprintln!(" - {} ({})", member.name, member.path);
}
eprintln!("Hint: build a specific member by name or path instead.");
return true;
}
}
}
if (emit.writes_any_bytecode() || emit.metadata)
&& let Err(()) = check_workspace_artifact_name_collisions(&contract_names_by_member)
{
return true;
}
if abi_collision_check_needs_filtering
&& let Err(()) = check_workspace_artifact_name_collisions(&abi_artifact_names_by_member)
{
return true;
}
if emit.ir
&& let Err(()) = check_workspace_ir_output_name_collisions(&contract_names_by_member)
{
return true;
}
let mut had_errors = false;
let mut any_contracts = false;
for (member, contract_names) in contract_names_by_member {
if contract_names.is_empty() {
continue;
}
any_contracts = true;
let report_dir = report_scope_dir(report, &format!("member-{}", member.name.as_str()));
let summary = build_ingot_url(
db,
&member.url,
None,
None,
opt_level,
emit,
&out_dir,
workspace_member_ir_out_dir(emit, &out_dir, member.name.as_str()),
Some(member.name.as_str()),
true,
report_dir.as_ref(),
);
had_errors |= summary.had_errors;
}
if !any_contracts {
eprintln!("Error: No contracts found to build");
return true;
}
had_errors
}
fn analyze_ingot_build_artifacts(
db: &mut DriverDataBase,
ingot_url: &Url,
include_abi_artifact_names: bool,
) -> Result<IngotBuildAnalysis, ()> {
let Some(ingot) = db.workspace().containing_ingot(db, ingot_url.clone()) else {
eprintln!("Error: Could not resolve ingot from directory");
return Err(());
};
if !ingot_has_source_files(db, ingot) {
eprintln!("Error: Could not find source files for ingot {ingot_url}");
return Err(());
}
let diagnostics = CompilationDiagnostics::for_ingot(db, ingot);
let mut has_errors = false;
if !diagnostics.hir.is_empty() {
diagnostics.hir.emit(db);
has_errors = true;
}
let dependency_has_errors = emit_dependency_diagnostics(db, &diagnostics.dependencies);
has_errors |= dependency_has_errors;
if !diagnostics.mir.is_empty() {
db.emit_complete_diagnostics(&diagnostics.mir);
has_errors = true;
}
if has_errors {
return Err(());
}
let contract_names = collect_workspace_contract_names(db, ingot);
let abi_artifact_names = if include_abi_artifact_names {
collect_ingot_abi_artifact_names(db, ingot).map_err(|err| {
eprintln!("Error: Failed to analyze ABI artifacts: {err}");
})?
} else {
Vec::new()
};
Ok(IngotBuildAnalysis {
contract_names,
abi_artifact_names,
})
}
fn emit_dependency_diagnostics(db: &DriverDataBase, issues: &DependencyIssues<'_>) -> bool {
if issues.is_empty() {
return false;
}
eprint!("{}", issues.format(db));
true
}
fn check_workspace_artifact_name_collisions(
contract_names_by_member: &[(WorkspaceMemberRecord, Vec<String>)],
) -> Result<(), ()> {
struct CollisionEntry {
member_name: SmolStr,
member_path: Utf8PathBuf,
contract_name: String,
artifact: String,
}
// Use a case-insensitive key to avoid filesystem-dependent artifact collisions
// (e.g. macOS default case-insensitive APFS).
let mut collisions: BTreeMap<String, Vec<CollisionEntry>> = BTreeMap::new();
for (member, contract_names) in contract_names_by_member {
for name in contract_names {
let artifact = sanitize_filename(name);
let key = artifact.to_ascii_lowercase();
collisions.entry(key).or_default().push(CollisionEntry {
member_name: member.name.clone(),
member_path: member.path.clone(),
contract_name: name.clone(),
artifact,
});
}
}
let duplicates: Vec<_> = collisions
.into_iter()
.filter(|(_, entries)| entries.len() > 1)
.collect();
if duplicates.is_empty() {
return Ok(());
}
eprintln!("Error: Contract names collide in a flat workspace output directory");
eprintln!("Conflicts:");
for (key, entries) in duplicates {
let mut artifacts: Vec<String> = entries.iter().map(|e| e.artifact.clone()).collect();
artifacts.sort();
artifacts.dedup();
let header = if artifacts.len() == 1 {
artifacts[0].clone()
} else {
format!("{key} (case-insensitive)")
};
let mut labels: Vec<String> = entries
.into_iter()
.map(|entry| {
format!(
"{} in {} ({})",
entry.contract_name, entry.member_name, entry.member_path
)
})
.collect();
labels.sort();
eprintln!(" - {header}");
for label in labels {
eprintln!(" - {label}");
}
}
eprintln!("Hint: build a specific member by name or path instead.");
Err(())
}
fn check_workspace_ir_output_name_collisions(
contract_names_by_member: &[(WorkspaceMemberRecord, Vec<String>)],
) -> Result<(), ()> {
struct CollisionEntry {
member_name: SmolStr,
member_path: Utf8PathBuf,
artifact: String,
}
// Use a case-insensitive key to avoid filesystem-dependent artifact collisions
// (e.g. macOS default case-insensitive APFS).
let mut collisions: BTreeMap<String, Vec<CollisionEntry>> = BTreeMap::new();
for (member, contract_names) in contract_names_by_member {
if contract_names.is_empty() {
continue;
}
let artifact = sanitize_filename(member.name.as_str());
let key = artifact.to_ascii_lowercase();
collisions.entry(key).or_default().push(CollisionEntry {
member_name: member.name.clone(),
member_path: member.path.clone(),
artifact,
});
}
let duplicates: Vec<_> = collisions
.into_iter()
.filter(|(_, entries)| entries.len() > 1)
.collect();
if duplicates.is_empty() {
return Ok(());
}
eprintln!("Error: Workspace member names collide in IR output directories");
eprintln!("Conflicts:");
for (key, entries) in duplicates {
let mut artifacts: Vec<String> = entries.iter().map(|e| e.artifact.clone()).collect();
artifacts.sort();
artifacts.dedup();