summaryrefslogtreecommitdiff
path: root/src/zisp/value/pair.zig
blob: c4b6f2c3408a2f97d80d6cfcba2ca99d1aaee10d (plain)
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
const std = @import("std");

const gc = @import("../gc.zig");
const value = @import("../value.zig");

const Alloc = std.mem.Allocator;

const Value = value.Value;

pub const PairPtr = *align(@alignOf(value.HeapPtr)) Pair;

pub const Pair = struct {
    car: Value,
    cdr: Value,
};

// Zig API

pub fn check(v: Value) ?PairPtr {
    if (!v.isHptrTyp(.pair)) return null;
    return @ptrCast(gc.heapPtrFromIdx(v.hptr.idx));
}

pub fn assert(v: Value) PairPtr {
    return check(v) orelse {
        v.dump();
        @panic("not pair");
    };
}

pub fn unpack(v: Value) PairPtr {
    return assert(v);
}

// Zisp API

pub fn pred(v: Value) Value {
    return value.boole.pack(check(v) != null);
}

pub fn cons(car: Value, cdr: Value) !Value {
    const pair = try gc.createHeap(.pair);
    pair.car = car;
    pair.cdr = cdr;
    return gc.packHeap(pair);
}

pub fn getCar(v: Value) Value {
    return unpack(v).car;
}

pub fn getCdr(v: Value) Value {
    return unpack(v).cdr;
}

pub fn setCar(v: Value, new: Value) void {
    unpack(v).car = new;
}

pub fn setCdr(v: Value, new: Value) void {
    unpack(v).cdr = new;
}