forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli_output.rs
More file actions
3738 lines (3395 loc) · 127 KB
/
Copy pathcli_output.rs
File metadata and controls
3738 lines (3395 loc) · 127 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 dir_test::{Fixture, dir_test};
use serde_json::Value;
use std::{fs, io::IsTerminal, path::Path, process::Command};
use tempfile::tempdir;
use test_utils::{
normalize::{normalize_newlines, normalize_path_separators, replace_path_token},
snap_test,
};
// Helper function to normalize paths in output for portability
fn normalize_output(output: &str) -> String {
let output = normalize_newlines(output);
let output = normalize_path_separators(output.as_ref());
let manifest_dir = env!("CARGO_MANIFEST_DIR");
let project_root = std::path::Path::new(manifest_dir)
.parent()
.expect("parent")
.parent()
.expect("parent");
let normalized = replace_path_token(&output, project_root, "<project>");
normalize_timing_output(&normalized)
}
fn normalize_timing_output(output: &str) -> String {
let has_trailing_newline = output.ends_with('\n');
let mut normalized = output
.lines()
.map(normalize_timing_line)
.collect::<Vec<_>>()
.join("\n");
if has_trailing_newline {
normalized.push('\n');
}
normalized
}
fn normalize_timing_line(line: &str) -> String {
let Some(status_idx) = ["PASS [", "FAIL [", "READY [", "ERROR ["]
.into_iter()
.filter_map(|marker| line.find(marker))
.min()
else {
return line.to_string();
};
let Some(open_rel) = line[status_idx..].find('[') else {
return line.to_string();
};
let open = status_idx + open_rel;
let Some(close_rel) = line[open..].find(']') else {
return line.to_string();
};
let close = open + close_rel;
let bracket = &line[open + 1..close];
let Some(seconds) = bracket.strip_suffix('s') else {
return line.to_string();
};
if seconds.is_empty()
|| !seconds
.chars()
.all(|ch| ch.is_ascii_digit() || ch == '.' || ch == ' ')
{
return line.to_string();
}
let mut normalized = String::new();
normalized.push_str(&line[..open]);
normalized.push_str("[<time>]");
normalized.push_str(&line[close + 1..]);
normalized
}
// Helper function to run fe check
fn run_fe_check(path: &str) -> (String, i32) {
run_fe_command("check", path)
}
// Helper function to run fe tree
fn run_fe_tree(path: &str) -> (String, i32) {
run_fe_command("tree", path)
}
// Helper function to run fe binary with specified subcommand
fn run_fe_command(subcommand: &str, path: &str) -> (String, i32) {
run_fe_command_with_args(subcommand, path, &[])
}
fn run_fe_command_with_args(subcommand: &str, path: &str, extra: &[&str]) -> (String, i32) {
let mut args = Vec::with_capacity(2 + extra.len());
args.push(subcommand);
args.extend_from_slice(extra);
args.push(path);
run_fe_main(&args)
}
// Helper function to run fe binary with specified args
fn run_fe_main(args: &[&str]) -> (String, i32) {
let out = run_fe_main_impl(args, None, &[]);
(out.combined(), out.exit_code)
}
fn run_fe_main_in_dir(args: &[&str], cwd: &Path) -> (String, i32) {
let out = run_fe_main_impl(args, Some(cwd), &[]);
(out.combined(), out.exit_code)
}
fn run_fe_main_with_stdin(args: &[&str], stdin_data: &str) -> (String, i32) {
use std::io::Write;
use std::process::Stdio;
let mut child = Command::new(fe_binary())
.args(args)
.env("NO_COLOR", "1")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap_or_else(|_| panic!("Failed to spawn fe {args:?}"));
child
.stdin
.take()
.expect("child stdin")
.write_all(stdin_data.as_bytes())
.expect("write stdin");
let output = child.wait_with_output().expect("wait for fe");
let out = FeOutput {
stdout: normalize_output(&String::from_utf8_lossy(&output.stdout)),
stderr: normalize_output(&String::from_utf8_lossy(&output.stderr)),
exit_code: output.status.code().unwrap_or(-1),
};
(out.combined(), out.exit_code)
}
#[test]
fn test_cli_check_invalid_named_const_used_in_type_position_reports_error_instead_of_panicking() {
let temp = tempdir().expect("tempdir");
let file = temp.path().join("invalid_const_ty_use.fe");
fs::write(
&file,
r#"
const N: usize = nope()
fn f() {
let _x: [u8; N] = [0; 1]
}
"#,
)
.expect("write fixture");
let (output, exit_code) = run_fe_check(file.to_str().expect("fixture path utf8"));
assert_eq!(exit_code, 1, "expected check failure:\n{output}");
assert!(
output.contains("undefined variable `nope`"),
"expected undefined variable diagnostic instead of panic:\n{output}"
);
assert!(
!output.contains("semantic lowering missing for call-like expression"),
"unexpected semantic lowering panic:\n{output}"
);
}
#[test]
fn test_cli_check_unresolved_record_init_path_reports_error_instead_of_panicking() {
let temp = tempdir().expect("tempdir");
let file = temp.path().join("unresolved_record_init_path.fe");
fs::write(
&file,
r#"
fn trigger() {
let s = missing::S {}
}
"#,
)
.expect("write fixture");
let (output, exit_code) = run_fe_check(file.to_str().expect("fixture path utf8"));
assert_eq!(exit_code, 1, "expected check failure:\n{output}");
assert!(
output.contains("`missing` is not found"),
"expected unresolved path diagnostic instead of panic:\n{output}"
);
assert!(
!output.contains("record init lowering missing"),
"unexpected semantic lowering panic:\n{output}"
);
}
struct FeOutput {
stdout: String,
stderr: String,
exit_code: i32,
}
impl FeOutput {
/// Combined display format used by snapshot tests.
fn combined(&self) -> String {
let mut out = String::new();
if !self.stdout.is_empty() {
out.push_str("=== STDOUT ===\n");
out.push_str(&self.stdout);
}
if !self.stderr.is_empty() {
if !out.is_empty() {
out.push('\n');
}
out.push_str("=== STDERR ===\n");
out.push_str(&self.stderr);
}
out.push_str(&format!("\n=== EXIT CODE: {} ===", self.exit_code));
normalize_output(&out)
}
}
fn fe_binary() -> &'static str {
env!("CARGO_BIN_EXE_fe")
}
fn run_fe_main_impl(args: &[&str], cwd: Option<&Path>, extra_env: &[(&str, &str)]) -> FeOutput {
let mut cmd = Command::new(fe_binary());
cmd.args(args).env("NO_COLOR", "1");
for (key, value) in extra_env {
cmd.env(key, value);
}
if let Some(dir) = cwd {
cmd.current_dir(dir);
}
let output = cmd
.output()
.unwrap_or_else(|_| panic!("Failed to run fe {:?}", args));
FeOutput {
stdout: normalize_output(&String::from_utf8_lossy(&output.stdout)),
stderr: normalize_output(&String::from_utf8_lossy(&output.stderr)),
exit_code: output.status.code().unwrap_or(-1),
}
}
fn fe_test_runner_fixture_dir(name: &str) -> std::path::PathBuf {
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures/fe_test_runner")
.join(name)
}
#[dir_test(
dir: "$CARGO_MANIFEST_DIR/tests/fixtures/cli_output/build",
glob: "*.fe",
)]
fn test_cli_build_contract_not_found(fixture: Fixture<&str>) {
let fixture_path = std::path::Path::new(fixture.path());
let fixture_name = fixture_path
.file_stem()
.expect("fixture should have stem")
.to_str()
.expect("fixture stem should be utf8");
let snapshot_path = fixture_path
.parent()
.expect("fixture should have parent")
.join(format!("{fixture_name}_build_contract_not_found.case"));
let (output, exit_code) = run_fe_main(&["build", "--contract", "DoesNotExist", fixture.path()]);
assert_ne!(exit_code, 0, "expected non-zero exit code:\n{output}");
snap_test!(output, snapshot_path.to_str().unwrap());
}
#[test]
fn test_cli_build_sonatina_ir_respects_contract_filter() {
let fixture_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures/cli_output/build/multi_contract.fe");
let fixture_path_str = fixture_path.to_str().expect("fixture path utf8");
let temp = tempdir().expect("tempdir");
let out_dir = temp.path().join("out");
let out_dir_str = out_dir.to_string_lossy().to_string();
let (output, exit_code) = run_fe_main(&[
"build",
"--emit",
"ir",
"--contract",
"Foo",
"--out-dir",
out_dir_str.as_str(),
fixture_path_str,
]);
assert_eq!(exit_code, 0, "fe build failed:\n{output}");
let ir_path = out_dir.join("multi_contract.sona");
let ir = fs::read_to_string(&ir_path).expect("read Sonatina IR");
assert!(ir.contains("object @Foo"), "expected Foo object:\n{ir}");
assert!(
!ir.contains("object @Bar"),
"contract filter should exclude Bar object:\n{ir}"
);
}
#[test]
fn test_cli_build_nested_storage_map_effect_forwarding() {
let temp = tempdir().expect("tempdir");
let fixture = temp.path().join("nested_storage_map_effect_forwarding.fe");
fs::write(
&fixture,
r#"
use std::evm::StorageMap
msg Msg {
#[selector = 1]
Check { key: u256, next: u256, initialized: bool },
}
fn is_set(_ key: u256) -> bool
uses (map: StorageMap<u256, u256>)
{
map.get(key: key) != 0
}
fn nested(_ key: u256) -> bool
uses (map: StorageMap<u256, u256>)
{
is_set(key)
}
struct Store {
map: StorageMap<u256, u256>,
}
pub contract Test {
mut store: Store
recv Msg {
Check { key, next, initialized } uses (store) {
let mut cursor = key
while cursor > next {
assert!(!with (store.map) {
nested(cursor)
})
cursor = cursor - 1
}
assert!(with (store.map) {
nested(next)
} == initialized)
}
}
}
"#,
)
.expect("write fixture");
let out_dir = temp.path().join("out");
let out_dir_str = out_dir.to_string_lossy().to_string();
let fixture_str = fixture.to_string_lossy().to_string();
let (output, exit_code) = run_fe_main(&[
"build",
"--standalone",
"--emit",
"bytecode",
"--out-dir",
out_dir_str.as_str(),
fixture_str.as_str(),
]);
assert_eq!(exit_code, 0, "fe build failed:\n{output}");
}
#[test]
fn test_cli_build_emit_abi_writes_json_artifact() {
let fixture_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures/cli_output/emit_abi/abi_contract.fe");
let fixture_path_str = fixture_path.to_str().expect("fixture path utf8");
let temp = tempdir().expect("tempdir");
let out_dir = temp.path().join("out");
let out_dir_str = out_dir.to_string_lossy().to_string();
let (output, exit_code) = run_fe_main(&[
"build",
"--emit",
"abi",
"--contract",
"Foo",
"--out-dir",
out_dir_str.as_str(),
fixture_path_str,
]);
assert_eq!(exit_code, 0, "fe build failed:\n{output}");
let abi_path = out_dir.join("Foo.abi.json");
assert!(abi_path.is_file(), "missing ABI artifact:\n{output}");
assert!(
!out_dir.join("Foo.bin").exists(),
"unexpected deploy artifact"
);
assert!(
!out_dir.join("Foo.runtime.bin").exists(),
"unexpected runtime artifact"
);
let abi: Value = serde_json::from_str(&fs::read_to_string(&abi_path).expect("read ABI"))
.expect("parse ABI JSON");
let function = abi
.as_array()
.expect("abi array")
.iter()
.find(|entry| entry["type"] == "function")
.expect("function entry");
assert!(
output.contains("Foo.abi.json"),
"unexpected output:\n{output}"
);
assert_eq!(function["name"], "ping");
assert_eq!(function["inputs"][0]["name"], "value");
assert_eq!(function["inputs"][0]["type"], "uint256");
assert_eq!(function["outputs"][0]["type"], "uint256");
}
#[test]
fn test_cli_build_emit_abi_dyn_string_matches_string_selector() {
let fixture_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures/cli_output/emit_abi/abi_dyn_string.fe");
let fixture_path_str = fixture_path.to_str().expect("fixture path utf8");
let temp = tempdir().expect("tempdir");
let out_dir = temp.path().join("out");
let out_dir_str = out_dir.to_string_lossy().to_string();
let (output, exit_code) = run_fe_main(&[
"build",
"--emit",
"abi",
"--contract",
"Foo",
"--out-dir",
out_dir_str.as_str(),
fixture_path_str,
]);
assert_eq!(exit_code, 0, "fe build failed:\n{output}");
let abi_path = out_dir.join("Foo.abi.json");
let abi: Value = serde_json::from_str(&fs::read_to_string(&abi_path).expect("read ABI"))
.expect("parse ABI JSON");
// A `DynString` field under a `string` selector argument is the matching
// pairing and must emit ABI type `string`.
let function = abi
.as_array()
.expect("abi array")
.iter()
.find(|entry| entry["type"] == "function")
.expect("function entry");
assert_eq!(function["name"], "set_name");
assert_eq!(function["inputs"][0]["name"], "name");
assert_eq!(function["inputs"][0]["type"], "string");
}
#[test]
fn test_cli_build_emit_abi_follows_inherent_const_selector() {
let fixture_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures/cli_output/emit_abi/abi_inherent_const_selector.fe");
let fixture_path_str = fixture_path.to_str().expect("fixture path utf8");
let temp = tempdir().expect("tempdir");
let out_dir = temp.path().join("out");
let out_dir_str = out_dir.to_string_lossy().to_string();
let (output, exit_code) = run_fe_main(&[
"build",
"--emit",
"abi",
"--contract",
"Foo",
"--out-dir",
out_dir_str.as_str(),
fixture_path_str,
]);
assert_eq!(exit_code, 0, "fe build failed:\n{output}");
let abi_path = out_dir.join("Foo.abi.json");
let abi: Value = serde_json::from_str(&fs::read_to_string(&abi_path).expect("read ABI"))
.expect("parse ABI JSON");
// The recv arm must survive ABI generation: the selector signature is
// resolved by following the inherent const's `sol(...)` body.
let function = abi
.as_array()
.expect("abi array")
.iter()
.find(|entry| entry["type"] == "function")
.expect("function entry derived from inherent-const selector");
assert_eq!(function["name"], "ping");
assert_eq!(function["inputs"][0]["type"], "uint256");
}
#[test]
fn test_cli_build_emit_metadata_standalone_writes_single_source() {
let fixture_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures/cli_output/emit_abi/abi_contract.fe");
let fixture_path_str = fixture_path.to_str().expect("fixture path utf8");
let fixture_contents = fs::read_to_string(&fixture_path).expect("read fixture");
let temp = tempdir().expect("tempdir");
let out_dir = temp.path().join("out");
let out_dir_str = out_dir.to_string_lossy().to_string();
let (output, exit_code) = run_fe_main(&[
"build",
"--emit",
"metadata",
"--contract",
"Foo",
"--out-dir",
out_dir_str.as_str(),
fixture_path_str,
]);
assert_eq!(exit_code, 0, "fe build failed:\n{output}");
let metadata_path = out_dir.join("Foo.metadata.json");
assert!(
metadata_path.is_file(),
"missing metadata artifact:\n{output}"
);
assert!(
output.contains("Foo.metadata.json"),
"expected metadata filename in output:\n{output}"
);
let value: Value =
serde_json::from_str(&fs::read_to_string(&metadata_path).expect("read metadata"))
.expect("parse metadata");
assert_eq!(value["version"], 1);
assert_eq!(value["language"], "Fe");
assert!(
value["compiler"]["version"].is_string(),
"compiler.version must be a string: {value:?}"
);
assert_eq!(
value["settings"]["compilationTarget"]["abi_contract.fe"],
"Foo"
);
assert_eq!(value["settings"]["evmVersion"], "osaka");
let sources = value["sources"].as_object().expect("sources object");
assert_eq!(sources.len(), 1, "expected exactly one source: {sources:?}");
assert_eq!(sources["abi_contract.fe"]["content"], fixture_contents);
assert!(
sources["abi_contract.fe"]["keccak256"]
.as_str()
.is_some_and(|h| h.starts_with("0x") && h.len() == 66),
"expected 0x-prefixed keccak256: {sources:?}"
);
}
#[test]
fn test_cli_build_emit_metadata_compiler_commit_matches_version_output() {
// `compiler.commit` must mirror the git hash embedded in `fe --version` (present iff that is).
let (version_output, version_code) = run_fe_main(&["--version"]);
assert_eq!(version_code, 0, "fe --version failed:\n{version_output}");
let expected_commit = version_output
.split_once('(')
.and_then(|(_, rest)| rest.split_once(')'))
.map(|(hash, _)| hash.trim().to_string());
let fixture_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures/cli_output/emit_abi/abi_contract.fe");
let temp = tempdir().expect("tempdir");
let out_dir = temp.path().join("out");
let (output, exit_code) = run_fe_main(&[
"build",
"--emit",
"metadata",
"--contract",
"Foo",
"--out-dir",
out_dir.to_str().expect("out utf8"),
fixture_path.to_str().expect("fixture utf8"),
]);
assert_eq!(exit_code, 0, "fe build failed:\n{output}");
let value: Value = serde_json::from_str(
&fs::read_to_string(out_dir.join("Foo.metadata.json")).expect("read metadata"),
)
.expect("parse metadata");
assert!(value["compiler"]["version"].is_string());
match expected_commit {
Some(hash) => assert_eq!(
value["compiler"]["commit"], hash,
"compiler.commit must equal the hash in `fe --version`"
),
None => assert!(
value["compiler"].get("commit").is_none(),
"compiler.commit must be absent when no git hash is embedded"
),
}
}
#[test]
fn test_cli_build_emit_metadata_ingot_includes_all_sources() {
let temp = tempdir().expect("tempdir");
let src_dir = temp.path().join("src");
fs::create_dir_all(&src_dir).expect("create src dir");
fs::write(
temp.path().join("fe.toml"),
"[ingot]\nname = \"metadata_ingot\"\nversion = \"0.1.0\"\n",
)
.expect("write fe.toml");
let lib_src = "use ingot::counter::Counter\n";
let counter_src = "pub contract Counter {\n}\n";
fs::write(src_dir.join("lib.fe"), lib_src).expect("write lib.fe");
fs::write(src_dir.join("counter.fe"), counter_src).expect("write counter.fe");
let out_dir = temp.path().join("out");
let out_dir_str = out_dir.to_string_lossy().to_string();
let project_path = temp.path().to_str().expect("project path utf8");
let (output, exit_code) = run_fe_main(&[
"build",
"--emit",
"metadata",
"--out-dir",
out_dir_str.as_str(),
project_path,
]);
assert_eq!(exit_code, 0, "fe build failed:\n{output}");
let metadata_path = out_dir.join("Counter.metadata.json");
assert!(
metadata_path.is_file(),
"missing metadata artifact:\n{output}"
);
let value: Value =
serde_json::from_str(&fs::read_to_string(&metadata_path).expect("read metadata"))
.expect("parse metadata");
assert_eq!(
value["settings"]["compilationTarget"]["src/counter.fe"],
"Counter"
);
let sources = value["sources"].as_object().expect("sources object");
assert_eq!(sources["src/lib.fe"]["content"], lib_src);
assert_eq!(sources["src/counter.fe"]["content"], counter_src);
assert!(
!sources
.keys()
.any(|k| k.starts_with("std/") || k.starts_with("core/")),
"std/core must not appear in sources: {sources:?}"
);
}
#[test]
fn test_cli_build_ingot_with_multiple_library_modules() {
// An ingot with several non-contract "library" modules plus a contract must
// build the contract without colliding on a synthesized `main` object (one
// was previously emitted per non-contract module). See the duplicate-`main`
// regression.
let temp = tempdir().expect("tempdir");
let src_dir = temp.path().join("src");
fs::create_dir_all(&src_dir).expect("create src dir");
fs::write(
temp.path().join("fe.toml"),
"[ingot]\nname = \"dup_main\"\nversion = \"0.1.0\"\n",
)
.expect("write fe.toml");
fs::write(
src_dir.join("lib.fe"),
"pub use libmod::{self, *}\npub use libmod2::{self, *}\npub use contractmod::{self, *}\n",
)
.expect("write lib.fe");
fs::write(src_dir.join("libmod.fe"), "pub fn helper() -> u256 { 1 }\n").expect("write libmod");
fs::write(
src_dir.join("libmod2.fe"),
"pub fn helper2() -> u256 { 2 }\n",
)
.expect("write libmod2");
fs::write(
src_dir.join("contractmod.fe"),
"pub msg AMsg {\n #[selector = sol(\"foo()\")]\n Foo -> u256,\n}\n\npub contract A {\n recv AMsg {\n Foo -> u256 { 1 }\n }\n}\n",
)
.expect("write contractmod");
let out_dir = temp.path().join("out");
let out_dir_str = out_dir.to_string_lossy().to_string();
let project_path = temp.path().to_str().expect("project path utf8");
let (output, exit_code) =
run_fe_main(&["build", "--out-dir", out_dir_str.as_str(), project_path]);
assert_eq!(exit_code, 0, "fe build failed:\n{output}");
assert!(out_dir.join("A.bin").is_file(), "missing A.bin:\n{output}");
assert!(
out_dir.join("A.runtime.bin").is_file(),
"missing A.runtime.bin:\n{output}"
);
// Library modules must not produce deployable `main` artifacts.
assert!(
!out_dir.join("main.bin").exists() && !out_dir.join("main.runtime.bin").exists(),
"library modules should not emit a `main` object:\n{:?}",
fs::read_dir(&out_dir).map(|d| d
.filter_map(|e| e.ok().map(|e| e.file_name()))
.collect::<Vec<_>>())
);
}
#[test]
fn test_cli_build_ingot_contract_uses_effectful_library_helper() {
// A contract that calls a helper defined in a non-contract child module, where
// the helper takes a `uses` effect parameter, must build: the helper is lowered
// as a dependency of the contract, not validated as a standalone runtime root
// (which would reject its ordinary effect parameter).
let temp = tempdir().expect("tempdir");
let src_dir = temp.path().join("src");
fs::create_dir_all(&src_dir).expect("create src dir");
fs::write(
temp.path().join("fe.toml"),
"[ingot]\nname = \"effect_helper\"\nversion = \"0.1.0\"\n",
)
.expect("write fe.toml");
fs::write(
src_dir.join("lib.fe"),
"pub use libmod::{self, *}\n\npub msg AMsg {\n #[selector = sol(\"foo()\")]\n Foo -> u256,\n}\n\npub contract A {\n recv AMsg {\n Foo -> u256 {\n let mut value: u256 = 1\n with (value) { needs_effect() }\n }\n }\n}\n",
)
.expect("write lib.fe");
fs::write(
src_dir.join("libmod.fe"),
"pub fn needs_effect() -> u256 uses (value: mut u256) {\n value += 1\n value\n}\n",
)
.expect("write libmod");
let out_dir = temp.path().join("out");
let out_dir_str = out_dir.to_string_lossy().to_string();
let project_path = temp.path().to_str().expect("project path utf8");
let (output, exit_code) =
run_fe_main(&["build", "--out-dir", out_dir_str.as_str(), project_path]);
assert_eq!(exit_code, 0, "fe build failed:\n{output}");
assert!(out_dir.join("A.bin").is_file(), "missing A.bin:\n{output}");
assert!(
out_dir.join("A.runtime.bin").is_file(),
"missing A.runtime.bin:\n{output}"
);
}
/// A root-module function named `main` is only an ingot executable when it is a
/// valid standalone root (same validation as a single-module build). A `main`
/// with ordinary parameters is not - it must be ignored, not synthesized into a
/// `main` object (which previously panicked on an arg-count mismatch).
#[test]
fn test_cli_build_ingot_root_main_with_params_is_not_executable() {
let temp = tempdir().expect("tempdir");
let src_dir = temp.path().join("src");
fs::create_dir_all(&src_dir).expect("create src dir");
fs::write(
temp.path().join("fe.toml"),
"[ingot]\nname = \"param_main\"\nversion = \"0.1.0\"\n",
)
.expect("write fe.toml");
fs::write(
src_dir.join("lib.fe"),
"pub use contractmod::{self, *}\n\npub fn main(_ x: u256) {}\n",
)
.expect("write lib.fe");
fs::write(
src_dir.join("contractmod.fe"),
"pub msg AMsg {\n #[selector = sol(\"foo()\")]\n Foo -> u256,\n}\n\npub contract A {\n recv AMsg {\n Foo -> u256 { 1 }\n }\n}\n",
)
.expect("write contractmod");
let out_dir = temp.path().join("out");
let out_dir_str = out_dir.to_string_lossy().to_string();
let project_path = temp.path().to_str().expect("project path utf8");
let (output, exit_code) =
run_fe_main(&["build", "--out-dir", out_dir_str.as_str(), project_path]);
assert_eq!(exit_code, 0, "fe build failed:\n{output}");
assert!(out_dir.join("A.bin").is_file(), "missing A.bin:\n{output}");
assert!(
!out_dir.join("main.bin").exists() && !out_dir.join("main.runtime.bin").exists(),
"a `main` with parameters must not produce a `main` object:\n{output}"
);
}
/// A `#[test]`-attributed `main` in the root module is not an executable entry
/// and must not produce a deployable `main` object during `fe build`.
#[test]
fn test_cli_build_ingot_root_test_main_is_not_executable() {
let temp = tempdir().expect("tempdir");
let src_dir = temp.path().join("src");
fs::create_dir_all(&src_dir).expect("create src dir");
fs::write(
temp.path().join("fe.toml"),
"[ingot]\nname = \"test_main\"\nversion = \"0.1.0\"\n",
)
.expect("write fe.toml");
fs::write(
src_dir.join("lib.fe"),
"pub use contractmod::{self, *}\n\n#[test]\nfn main() {}\n",
)
.expect("write lib.fe");
fs::write(
src_dir.join("contractmod.fe"),
"pub msg AMsg {\n #[selector = sol(\"foo()\")]\n Foo -> u256,\n}\n\npub contract A {\n recv AMsg {\n Foo -> u256 { 1 }\n }\n}\n",
)
.expect("write contractmod");
let out_dir = temp.path().join("out");
let out_dir_str = out_dir.to_string_lossy().to_string();
let project_path = temp.path().to_str().expect("project path utf8");
let (output, exit_code) =
run_fe_main(&["build", "--out-dir", out_dir_str.as_str(), project_path]);
assert_eq!(exit_code, 0, "fe build failed:\n{output}");
assert!(out_dir.join("A.bin").is_file(), "missing A.bin:\n{output}");
assert!(
!out_dir.join("main.bin").exists() && !out_dir.join("main.runtime.bin").exists(),
"a `#[test]` `main` must not produce a `main` object:\n{output}"
);
}
#[test]
fn test_cli_build_emit_metadata_includes_transitive_dependency() {
let temp = tempdir().expect("tempdir");
let root = temp.path();
write_app_with_path_dependency(root);
let out_dir = root.join("app/out");
let (output, exit_code) = run_fe_main(&[
"build",
"--emit",
"metadata",
"--out-dir",
out_dir.to_str().expect("out utf8"),
root.join("app").to_str().expect("app utf8"),
]);
assert_eq!(exit_code, 0, "fe build failed:\n{output}");
let value: Value = serde_json::from_str(
&fs::read_to_string(out_dir.join("Foo.metadata.json")).expect("read metadata"),
)
.expect("parse metadata");
let sources = value["sources"].as_object().expect("sources object");
assert!(
sources.contains_key("src/main.fe"),
"root source missing: {sources:?}"
);
assert!(
sources.contains_key("mylib/src/lib.fe"),
"dependency source must be alias-namespaced: {sources:?}"
);
assert!(
!sources
.keys()
.any(|k| k.starts_with("std/") || k.starts_with("core/")),
"std/core must not appear in sources: {sources:?}"
);
let ingots = value["settings"]["ingots"]
.as_array()
.expect("ingots array");
let app = ingots
.iter()
.find(|i| i["name"] == "app")
.expect("app ingot entry");
assert_eq!(app["namespace"], "");
assert_eq!(app["dependencies"]["mylib"], "mylib");
let mylib = ingots
.iter()
.find(|i| i["name"] == "mylib")
.expect("mylib ingot entry");
assert_eq!(mylib["namespace"], "mylib");
assert_eq!(mylib["version"], "1.2.0");
// mylib's fe.toml sets `arithmetic = "unchecked"`; the resolved effective value is recorded.
assert_eq!(mylib["arithmetic"], "unchecked");
}
#[test]
fn test_cli_build_emit_metadata_settings_reflect_optimize_and_arithmetic() {
let temp = tempdir().expect("tempdir");
let src_dir = temp.path().join("src");
fs::create_dir_all(&src_dir).expect("create src dir");
fs::write(
temp.path().join("fe.toml"),
"[ingot]\nname = \"metadata_settings\"\nversion = \"0.1.0\"\narithmetic = \"unchecked\"\n",
)
.expect("write fe.toml");
fs::write(src_dir.join("lib.fe"), "pub contract Foo {\n}\n").expect("write lib.fe");
let out_dir = temp.path().join("out");
let (output, exit_code) = run_fe_main(&[
"build",
"--emit",
"metadata",
"--optimize",
"2",
"--out-dir",
out_dir.to_str().expect("out utf8"),
temp.path().to_str().expect("project utf8"),
]);
assert_eq!(exit_code, 0, "fe build failed:\n{output}");
let value: Value = serde_json::from_str(
&fs::read_to_string(out_dir.join("Foo.metadata.json")).expect("read metadata"),
)
.expect("parse metadata");
assert_eq!(value["settings"]["optimizer"]["level"], "2");
assert_eq!(value["settings"]["arithmetic"], "unchecked");
// `dependencyArithmetic` defaults to `defer` when unset.
assert_eq!(value["settings"]["dependencyArithmetic"], "defer");
}
#[test]
fn test_cli_build_emit_metadata_combined_with_other_artifacts() {
let temp = tempdir().expect("tempdir");
let src_dir = temp.path().join("src");
fs::create_dir_all(&src_dir).expect("create src dir");
fs::write(
temp.path().join("fe.toml"),
"[ingot]\nname = \"metadata_combined\"\nversion = \"0.1.0\"\n",
)
.expect("write fe.toml");
fs::write(
src_dir.join("lib.fe"),
"pub msg FooMsg {\n #[selector = sol(\"run()\")]\n Run -> u256,\n}\n\npub contract Foo {\n recv FooMsg {\n Run -> u256 {\n 1\n }\n }\n}\n",
)
.expect("write lib.fe");
let out_dir = temp.path().join("out");
let (output, exit_code) = run_fe_main(&[
"build",
"--emit",
"bytecode,runtime-bytecode,abi,metadata",
"--out-dir",
out_dir.to_str().expect("out utf8"),
temp.path().to_str().expect("project utf8"),
]);
assert_eq!(exit_code, 0, "fe build failed:\n{output}");
for artifact in [
"Foo.bin",
"Foo.runtime.bin",
"Foo.abi.json",
"Foo.metadata.json",
] {
assert!(
out_dir.join(artifact).is_file(),
"missing {artifact}:\n{output}"
);
}
// `output.abi` in the metadata must match the standalone `.abi.json` artifact.
let metadata: Value = serde_json::from_str(
&fs::read_to_string(out_dir.join("Foo.metadata.json")).expect("read metadata"),
)
.expect("parse metadata");
let abi_json: Value = serde_json::from_str(
&fs::read_to_string(out_dir.join("Foo.abi.json")).expect("read abi.json"),
)
.expect("parse abi.json");
assert_eq!(
metadata["output"]["abi"], abi_json,
"metadata output.abi must equal the .abi.json artifact"
);
}
#[test]
fn test_cli_build_metadata_round_trip_reproduces_runtime_bytecode() {
let temp = tempdir().expect("tempdir");
let root = temp.path();
write_app_with_path_dependency(root);
// Original build: emit metadata + runtime bytecode.
let out_dir = root.join("app/out");
let (output, exit_code) = run_fe_main(&[
"build",
"--emit",
"metadata,runtime-bytecode",
"--out-dir",
out_dir.to_str().expect("out utf8"),
root.join("app").to_str().expect("app utf8"),
]);
assert_eq!(exit_code, 0, "original build failed:\n{output}");
let original_runtime =
fs::read_to_string(out_dir.join("Foo.runtime.bin")).expect("read original runtime.bin");
// Rebuild solely from the metadata artifact via `--from-metadata`.
let metadata_path = out_dir.join("Foo.metadata.json");
let recon = tempdir().expect("recon tempdir");
let recon_out = recon.path().join("out");
let (output, exit_code) = run_fe_main(&[
"build",
"--from-metadata",
metadata_path.to_str().expect("metadata utf8"),
"--emit",
"runtime-bytecode",
"--out-dir",
recon_out.to_str().expect("out utf8"),
]);
assert_eq!(exit_code, 0, "rebuild from metadata failed:\n{output}");
let rebuilt_runtime =
fs::read_to_string(recon_out.join("Foo.runtime.bin")).expect("read rebuilt runtime.bin");
assert_eq!(
original_runtime, rebuilt_runtime,
"runtime bytecode rebuilt from metadata.json must be byte-identical"
);
}