summaryrefslogtreecommitdiff
path: root/src/zisp/io/Printer.zig
blob: 4b060054b9341b072c0ef2d904670ceb1d1ace38 (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
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
const std = @import("std");

const Writer = std.Io.Writer;

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

const Parser = io.Parser;
const Value = value.Value;
const IstrPtr = value.istr.IstrPtr;
const ArrayPtr = value.array.ArrayPtr;

const Printer = @This();

writer: *Writer,

pub fn init(writer: *Writer) Printer {
    return .{ .writer = writer };
}

fn write(p: *Printer, bytes: []const u8) !void {
    _ = try p.writer.write(bytes);
}

fn writeByte(p: *Printer, c: u8) !void {
    _ = try p.writer.writeByte(c);
}

pub fn print(p: *Printer, v: Value) anyerror!void {
    if (v.isSstr()) return p.printBareStr(value.sstr.unpack(&v));
    if (v.isRune()) return p.printRune(v);
    if (v.isMisc()) return p.printMisc(v);
    if (value.list.check(v)) return p.printList(v);
    if (value.istr.check(v)) return p.printIstr(v);
    if (value.array.check(.str, v)) |str| return p.printBareStr(str.bytes());
    @panic("Unsupported type to print.");
}

pub fn printBareStr(p: *Printer, s: []const u8) !void {
    if (s.len == 0) @panic("Empty string must be quoted.");
    const no_joins = Parser.isSpecialBareChar(s[0]);
    for (s) |c| {
        if (Parser.isBareChar(c)) {
            try p.writeByte(c);
        } else if (no_joins and (c == '.' or c == ':')) {
            try p.writeByte(c);
        } else {
            @panic("String needs quoting.");
        }
    }
}

pub fn printIstr(p: *Printer, v: Value) !void {
    const istr = value.istr.unpack(v);
    try p.printBareStr(istr.bytes());
}

pub fn printRune(p: *Printer, v: Value) !void {
    try p.write("#");
    try p.write(value.rune.unpack(&v));
}

pub fn printMisc(p: *Printer, v: Value) !void {
    try switch (v.bits) {
        value.f.bits => p.write("#f"),
        value.t.bits => p.write("#t"),
        value.nil.bits => p.write("()"),
        value.eof.bits => p.write("#EOF"),
        else => @panic("Unsupported misc value to print."),
    };
}

pub fn printList(p: *Printer, list: Value) !void {
    const len = value.list.getLenTag(list);
    const ptr = value.list.getValPtr(list);
    try switch (len) {
        2 => switch (ptr[0].bits) {
            Parser.SHBANG.bits => p.printShebang(ptr[1]),
            Parser.LABEL.bits => p.printLabel(ptr[1]),
            Parser.HASH.bits => p.printHashDatum(ptr[1]),
            Parser.PQSTR.bits => p.printQuotStr(ptr[1], '|'),
            Parser.DQSTR.bits => p.printQuotStr(ptr[1], '"'),
            Parser.ATSTR.bits => p.printAtLenStr(ptr[1]),
            Parser.QUOTE.bits => p.printQuoteWithChar('\'', ptr[1]),
            Parser.GRAVE.bits => p.printQuoteWithChar('`', ptr[1]),
            Parser.COMMA.bits => p.printQuoteWithChar(',', ptr[1]),
            Parser.SQUARE.bits => p.printListDirect(len, ptr),
            Parser.BRACE.bits => p.printListDirect(len, ptr),
            else => if (ptr[0].isRune()) {
                return p.printRuneDatum(ptr[0], ptr[1]);
            } else {
                return p.printListDirect(len, ptr);
            },
        },
        3 => switch (ptr[0].bits) {
            Parser.DOT.bits => p.printJoinWithChar('.', ptr[1], ptr[2]),
            Parser.COLON.bits => p.printJoinWithChar(':', ptr[1], ptr[2]),
            Parser.JOIN.bits => p.printJoin(ptr[1], ptr[2]),
            Parser.SHBANG.bits => p.printShebangWithArgs(ptr[1], ptr[2]),
            Parser.LABEL.bits => p.printLabelDatum(ptr[1], ptr[2]),
            Parser.ATSTR.bits => p.printAtStr(ptr[1], ptr[2]),
            else => p.printListDirect(len, ptr),
        },
        else => p.printListDirect(len, ptr),
    };
}

fn printJoinWithChar(p: *Printer, c: u8, d1: Value, d2: Value) !void {
    try p.print(d1);
    try p.writeByte(c);
    try p.print(d2);
}

fn printJoin(p: *Printer, d1: Value, d2: Value) !void {
    try p.print(d1);
    try p.print(d2);
}

fn printShebang(p: *Printer, str: Value) !void {
    try p.write("#!");
    try p.write(value.string.getBytes(&str));
    try p.write("\n");
}

fn printShebangWithArgs(p: *Printer, str: Value, str2: Value) !void {
    try p.write("#!");
    try p.write(value.string.getBytes(&str));
    try p.write(" ");
    try p.write(value.string.getBytes(&str2));
    try p.write("\n");
}

fn printLabel(p: *Printer, num: Value) !void {
    try p.printLabelNum(num);
    try p.write("%");
}

fn printLabelDatum(p: *Printer, num: Value, dat: Value) !void {
    try p.printLabelNum(num);
    try p.write("=");
    try p.print(dat);
}

fn printLabelNum(p: *Printer, num: Value) !void {
    const x = value.fixnum.unpack(num);
    std.debug.assert(x >= 0);
    std.debug.assert(x <= std.math.maxInt(u48));

    var buf: [12]u8 = undefined;
    const end = std.fmt.printInt(&buf, x, 16, .lower, .{});

    try p.write("#%");
    try p.write(buf[0..end]);
}

fn printHashDatum(p: *Printer, d: Value) !void {
    try p.write("#");
    if (value.string.isString(d)) try p.write("\\");
    try p.print(d);
}

fn printRuneDatum(p: *Printer, r: Value, d: Value) !void {
    try p.printRune(r);
    if (value.string.isString(d)) try p.write("\\");
    try p.print(d);
}

fn printQuotStr(p: *Printer, str: Value, comptime qchar: u8) !void {
    try p.writeByte(qchar);
    for (value.string.getBytes(&str)) |c| switch (c) {
        qchar => {
            try p.writeByte('\\');
            try p.writeByte(qchar);
        },
        '\\' => {
            try p.writeByte('\\');
            try p.writeByte('\\');
        },
        else => {
            try p.writeByte(c);
        },
    };
    try p.writeByte(qchar);
}

fn printAtLenStr(p: *Printer, str: Value) !void {
    const bytes = value.string.getBytes(&str);

    try p.write("@");
    try p.writeByte(255);

    var buf: [6]u8 = undefined;
    var len = bytes.len;
    inline for (0..6) |i| {
        buf[5 - i] = @truncate(len);
        len >>= 8;
    }

    try p.write(buf[0..6]);
    try p.write(bytes);
}

fn printAtStr(p: *Printer, sentinel: Value, str: Value) !void {
    const sentinel_num = value.fixnum.unpack(sentinel);
    if (sentinel_num > 254) {
        @panic("At-string sentinel must be <= 254.");
    }

    const byte: u8 = @intCast(sentinel_num);
    const str_bytes = value.string.getBytes(&str);
    for (str_bytes) |c| {
        if (c == byte) @panic("String contains sentinel byte.");
    }
    try p.write("@");
    try p.writeByte(byte);
    try p.write(str_bytes);
    try p.writeByte(byte);
}

fn printQuoteWithChar(p: *Printer, c: u8, d: Value) !void {
    try p.writeByte(c);
    try p.print(d);
}

fn printListDirect(p: *Printer, len: u3, vals: [*]Value) !void {
    var close = ")";
    var i: usize = 0;

    switch (vals[0].bits) {
        Parser.SQUARE.bits => {
            try p.write("[");
            close = "]";
            i = 1;
        },
        Parser.BRACE.bits => {
            try p.write("{");
            close = "}";
            i = 1;
        },
        else => {
            if (vals[0].isRune()) {
                try p.printRune(vals[0]);
                i = 1;
            }
            try p.write("(");
        },
    }

    if (len != 0) {
        var first = true;
        for (i..len) |j| {
            if (!first) try p.write(" ");
            first = false;
            try p.print(vals[j]);
        }
    } else {
        try p.print(vals[i]);
        i += 1;
        while (vals[i].bits != value.none.bits) : (i += 1) {
            try p.write(" ");
            try p.print(vals[i]);
        }
    }

    try p.write(close);
}