1
//! The lambdas `DEFSTRUCT` defines over the runtime struct natives: each one
2
//! compiles to wasm that validates, and a wrong operand is a compile error
3
//! naming the accessor.
4

            
5
use super::common::{compile_and_validate, compile_expect_error};
6

            
7
const PT: &str = "(defstruct pt x y)";
8

            
9
11
fn with_pt(body: &str) -> String {
10
11
    format!("{PT} {body}")
11
11
}
12

            
13
#[test]
14
1
fn a_constructor_takes_its_fields_by_keyword() {
15
1
    compile_and_validate(&with_pt("(make-pt :x 1 :y 2)"));
16
1
}
17

            
18
#[test]
19
1
fn a_constructor_defaults_a_missing_field_to_nil() {
20
1
    compile_and_validate(&with_pt("(make-pt :y 2)"));
21
1
}
22

            
23
#[test]
24
1
fn a_constructor_rejects_an_unknown_keyword() {
25
1
    let err = compile_expect_error(&with_pt("(make-pt :z 1)"));
26
1
    assert!(err.contains(":Z") || err.contains("Z"), "got: {err}");
27
1
}
28

            
29
#[test]
30
1
fn an_accessor_reads_a_field() {
31
1
    compile_and_validate(&with_pt("(let ((p (make-pt :x 1 :y 2))) (pt-y p))"));
32
1
}
33

            
34
#[test]
35
1
fn a_setf_accessor_stores_a_field() {
36
1
    compile_and_validate(&with_pt(
37
1
        "(let ((p (make-pt :x 1 :y 2))) (setf (pt-x p) 3) (pt-x p))",
38
1
    ));
39
1
}
40

            
41
#[test]
42
1
fn the_predicate_and_the_copier_compile() {
43
1
    compile_and_validate(&with_pt(
44
1
        "(let ((p (make-pt :x 1 :y 2))) (list (pt-p p) (pt-x (copy-pt p))))",
45
1
    ));
46
1
}
47

            
48
#[test]
49
1
fn an_accessor_of_a_value_that_is_no_struct_names_itself() {
50
1
    let err = compile_expect_error(&with_pt("(pt-x 5)"));
51
1
    assert!(err.contains("PT-X: expected a PT"), "got: {err}");
52
1
}
53

            
54
#[test]
55
1
fn a_setf_accessor_of_a_value_that_is_no_struct_names_itself() {
56
1
    let err = compile_expect_error(&with_pt("(setf (pt-x 5) 1)"));
57
1
    assert!(err.contains("(SETF PT-X): expected a PT"), "got: {err}");
58
1
}
59

            
60
#[test]
61
1
fn a_place_without_a_setf_accessor_is_an_error() {
62
1
    let err = compile_expect_error(&with_pt("(let ((p (make-pt))) (setf (pt-z p) 1))"));
63
1
    assert!(err.contains("PT-Z"), "got: {err}");
64
1
}
65

            
66
#[test]
67
1
fn a_struct_cannot_be_defined_again_with_other_fields() {
68
1
    let err = compile_expect_error(&with_pt("(defstruct pt x)"));
69
1
    assert!(err.contains("DEFSTRUCT PT"), "got: {err}");
70
1
}
71

            
72
#[test]
73
1
fn a_struct_defined_again_with_its_fields_still_compiles() {
74
1
    compile_and_validate(&with_pt("(defstruct pt x y) (make-pt :x 1)"));
75
1
}
76

            
77
#[test]
78
1
fn the_natives_are_not_callable_by_name() {
79
1
    let err = compile_expect_error("(struct-new 0 1)");
80
1
    assert!(err.contains("STRUCT-NEW"), "got: {err}");
81
1
}