1
use super::define_struct;
2
use crate::ast::Expr;
3
use crate::compiler::native::{STRUCT_COPY, STRUCT_NEW, STRUCT_P, STRUCT_REF, STRUCT_SET};
4
use crate::runtime::{Head, SymbolTable};
5

            
6
3
fn defined(fields: &[&str]) -> SymbolTable {
7
3
    let mut table = SymbolTable::with_builtins();
8
3
    let fields = fields.iter().map(ToString::to_string).collect();
9
3
    define_struct(&mut table, "PT", fields).expect("struct defines");
10
3
    table
11
3
}
12

            
13
10
fn calls(table: &SymbolTable, name: &str, native: &str) -> bool {
14
10
    matches!(table.resolve_head(name), Head::Function(_, Expr::List(body))
15
9
        if matches!(body.first(), Some(Expr::Symbol(head)) if head == native))
16
10
}
17

            
18
#[test]
19
1
fn every_function_of_a_struct_is_a_lambda_over_a_native() {
20
1
    let table = defined(&["X", "Y"]);
21
1
    assert!(calls(&table, "MAKE-PT", STRUCT_NEW));
22
1
    assert!(calls(&table, "PT-P", STRUCT_P));
23
1
    assert!(calls(&table, "COPY-PT", STRUCT_COPY));
24
1
    assert!(calls(&table, "PT-X", STRUCT_REF));
25
1
    assert!(calls(&table, "PT-Y", STRUCT_REF));
26
1
    assert!(calls(&table, "(SETF PT-X)", STRUCT_SET));
27
1
    assert!(calls(&table, "(SETF PT-Y)", STRUCT_SET));
28
1
}
29

            
30
#[test]
31
1
fn a_field_named_p_makes_the_predicate_name_an_accessor() {
32
1
    let mut table = SymbolTable::with_builtins();
33
1
    define_struct(&mut table, "BOX", vec!["P".to_string()]).expect("struct defines");
34
1
    assert!(calls(&table, "BOX-P", STRUCT_REF));
35
1
}
36

            
37
#[test]
38
1
fn defining_a_struct_again_with_other_fields_is_an_error() {
39
1
    let mut table = defined(&["X"]);
40
1
    let err = define_struct(&mut table, "PT", vec!["X".to_string(), "Y".to_string()]);
41
1
    assert!(err.is_err());
42
1
    assert!(calls(&table, "PT-X", STRUCT_REF));
43
1
    assert!(!calls(&table, "PT-Y", STRUCT_REF));
44
1
}
45

            
46
#[test]
47
1
fn defining_a_struct_again_with_its_fields_keeps_its_layout() {
48
1
    let mut table = defined(&["X"]);
49
1
    let fields = vec!["X".to_string()];
50
1
    let before = table.define_struct("PT", fields.clone()).expect("known");
51
1
    define_struct(&mut table, "PT", fields.clone()).expect("same fields");
52
1
    let after = table.define_struct("PT", fields.clone()).expect("known");
53
1
    assert_eq!(after, before);
54
1
    assert_eq!(
55
1
        table.struct_layout(after).map(|l| l.fields.clone()),
56
1
        Some(fields)
57
    );
58
1
}