~cricket/zckt

ref: 263472288023d6db9a56c9a865aa2166709a3790 zckt/zckt.zig -rw-r--r-- 19.2 KiB
26347228c piapiac add some helper functions + a couple of tests 6 months ago
                                                                                
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
// small, bodged together ckt parser
//
//
const std = @import("std");
const debug = std.debug;
const fmt = std.fmt;
const mem = std.mem;

const Key = []const u8;

const Value = union(enum) {
    string: []const u8,
    table: Table,

    pub fn deinit(self: *Value, a: *mem.Allocator) void {
        switch (self.*) {
            .string => |str| a.free(str),
            .table => |*table| table.deinit(),
        }
    }

    pub fn asString(self: Value) error{NotAString}![]const u8 {
        switch (self) {
            .string => |str| return str,
            .table => return error.NotAString,
        }
    }

    pub fn asTable(self: Value) error{NotATable}!Table {
        switch (self) {
            .string => return error.NotATable,
            .table => |table| return table,
        }
    }

    pub fn format(self: Value, comptime _: []const u8, options: fmt.FormatOptions, writer: anytype) !void {
        switch (self) {
            .string => |str| try writer.print("{s}", .{str}),
            .table => |table| try writer.print("[ ... ]", .{}), //try writer.print("{s}", .{table}),
        }
    }
};

const Table = struct {
    const Map = std.StringArrayHashMap(Value);

    map: Map,
    a: *mem.Allocator,

    pub fn init(a: *mem.Allocator) Table {
        return .{
            .map = Map.init(a),
            .a = a,
        };
    }

    pub fn format(self: Table, comptime _: []const u8, options: fmt.FormatOptions, writer: anytype) !void {
        try writer.print("[ ", .{});
        var iter = self.map.iterator();
        while (iter.next()) |entry| try writer.print("{s}={s};", .{ entry.key, entry.value });
        try writer.print(" ]", .{});
    }

    pub fn get(self: *Table, key: []const u8) ?Value {
        return self.map.get(key);
    }

    pub fn getString(self: *Table, key: []const u8) ?[]const u8 {
        const value = self.map.get(key) orelse return null;
        return value.asString() catch return null;
    }

    pub fn getTable(self: *Table, key: []const u8) ?Table {
        const value = self.map.get(key) orelse return null;
        return value.asTable() catch return null;
    }

    pub fn put(self: *Table, key: []const u8, value: Value) !void {
        var result = try self.map.fetchPut(key, value);

        // free memory if needed
        if (result) |*entry| {
            self.a.free(key);
            entry.value.deinit(self.a);
        }
    }

    pub fn deinit(self: *Table) void {
        var iter = self.map.iterator();

        while (iter.next()) |entry| {
            self.a.free(entry.key);
            entry.value.deinit(self.a);
        }

        self.map.deinit();
    }
};

pub const Token = union(enum) {
    pub const String = union(enum) {
        unquoted: []const u8,
        quoted: []const u8,
        multiline: []const u8,

        pub fn format(self: String, comptime _: []const u8, options: fmt.FormatOptions, writer: anytype) !void {
            switch (self) {
                .unquoted => |str| try writer.print("unquoted: {s}", .{str}),
                .quoted => |str| try writer.print("quoted: {s}", .{str}),
                .multiline => |str| try writer.print("multiline: {s}", .{str}),
            }
        }
    };

    keyeq: String, // key =
    value: String, // value
    table_start, // table start
    table_end,

    // just for pretty printing when debugging lol
    pub fn format(self: Token, comptime _: []const u8, options: fmt.FormatOptions, writer: anytype) !void {
        switch (self) {
            .keyeq => |str| try writer.print("key {{{s}}} =", .{str}),
            .value => |str| try writer.print("value {{{s}}};", .{str}),
            .table_start => |str| try writer.print("[", .{}),
            .table_end => |str| try writer.print("]", .{}),
        }
    }
};

pub const Tokenizer = struct {
    const Error = error{
        EmptyKey,
        InvalidChar,
        UnexpectedNewline,
        UnexpectedEof,
    };

    content: []const u8,

    index: usize,
    last: Token,
    finished: bool,

    pub fn init(data: []const u8) Tokenizer {
        return Tokenizer{
            .content = data,

            .index = 0,
            .last = undefined,
            .finished = false,
        };
    }

    fn eof(self: *Tokenizer) Error!void {
        switch (self.last) {
            .table_start => return Error.UnexpectedEof,
            else => self.finished = true,
        }
    }

    fn skipToNewline(self: *Tokenizer) Error!void {
        while (self.content[self.index] != '\n') {
            self.index += 1;
            if (self.index >= self.content.len) {
                return self.eof();
            }
        }
    }

    fn skipPastNewline(self: *Tokenizer) Error!void {
        try self.skipToNewline();
        self.index += 1;
    }

    fn skipWhitespace(self: *Tokenizer) Error!void {
        while (self.index < self.content.len) : (self.index += 1) {
            switch (self.content[self.index]) {
                // actual whitespace
                ' ', '\t', 0x0B, 0x0C, '\r' => continue,
                '#' => return try self.skipToNewline(),
                else => return,
            }
        }
    }

    fn skipWhitespaceAndNewlines(self: *Tokenizer) Error!void {
        while (self.index < self.content.len) : (self.index += 1) {
            switch (self.content[self.index]) {
                // actual whitespace
                ' ', '\t', 0x0B, 0x0C, '\r' => continue,
                '#' => try self.skipPastNewline(),
                '\n' => continue,
                else => return,
            }
        }
        try self.eof();
    }

    fn skipWhitespaceAndNewlinesAndBreaks(self: *Tokenizer) Error!void {
        while (self.index < self.content.len) : (self.index += 1) {
            switch (self.content[self.index]) {
                // actual whitespace
                ' ', '\t', 0x0B, 0x0C, '\r' => continue,
                ';', ',' => continue,
                '#' => try self.skipPastNewline(),
                '\n' => continue,
                else => return,
            }
        }
        try self.eof();
    }

    fn readString(self: *Tokenizer) ![]const u8 {
        const start_index = self.index;
        while (self.index < self.content.len) : (self.index += 1) {
            const char = self.content[self.index];
            switch (char) {
                '\n', '=', ';', ',', ']' => {
                    // remove trailing whitespace
                    // (eg key = value)
                    var end_index = self.index - 1;
                    while (end_index > start_index) {
                        switch (self.content[end_index]) {
                            ' ', '\t', 0x0B, 0x0C, '\r' => end_index -= 1,
                            else => return self.content[start_index .. end_index + 1],
                        }
                    }
                    return error.EmptyKey;
                },
                else => continue,
            }
        }

        // EOF
        try self.eof();
        return self.content[start_index..self.index];
    }

    fn readQuotedString(self: *Tokenizer, comptime quote: u8) Error![]const u8 {
        const start_index = self.index;

        self.index += 1;

        while (self.index < self.content.len) : (self.index += 1) {
            const char = self.content[self.index];
            switch (char) {
                quote => {
                    self.index += 1;
                    return self.content[start_index..self.index];
                },
                '\n' => return error.UnexpectedNewline,
                '\\' => self.index += 1,
                else => continue,
            }
        }

        // EOF before closing bracket
        return error.UnexpectedEof;
    }

    fn readMultilineString(self: *Tokenizer) Error![]const u8 {
        const start_index = self.index;

        const State = enum { root, line };
        var state = State.root;

        while (self.index < self.content.len) : (self.index += 1) {
            switch (state) {
                .root => {
                    const end_index = self.index;
                    try self.skipWhitespace();
                    switch (self.content[self.index]) {
                        '|' => state = State.line,
                        else => return self.content[start_index..end_index],
                    }
                },
                .line => {
                    switch (self.content[self.index]) {
                        '\n' => state = State.root,
                        else => continue,
                    }
                },
            }
        }

        // empty line or EOF
        return self.content[start_index..self.index];
    }

    pub fn next(self: *Tokenizer) Error!?Token {
        if (!self.finished) {
            self.last = ret: {
                // treat ; and , as whitespace
                try self.skipWhitespaceAndNewlinesAndBreaks();
                if (self.finished) return null;
                const char = self.content[self.index];
                switch (char) {
                    '[' => break :ret Token.table_start,
                    ']' => break :ret Token.table_end,
                    '=' => return error.InvalidChar,
                    else => {
                        var value: Token.String = switch (char) {
                            '"' => Token.String{ .quoted = try self.readQuotedString('"') },
                            '\'' => Token.String{ .quoted = try self.readQuotedString('\'') },
                            '|' => Token.String{ .multiline = try self.readMultilineString() },
                            else => Token.String{ .unquoted = try self.readString() },
                        };
                        try self.skipWhitespaceAndNewlines();
                        if (!self.finished) {
                            switch (self.content[self.index]) {
                                ';', ',' => break :ret Token{ .value = value },
                                '=' => break :ret Token{ .keyeq = value },
                                ']' => {
                                    self.index -= 1;
                                    break :ret Token{ .value = value };
                                },
                                else => {
                                    self.index -= 1;
                                    break :ret Token{ .value = value };
                                },
                            }
                        } else break :ret Token{ .value = value };
                    },
                }
            };
            self.index += 1;
            if (self.index >= self.content.len) try self.eof();
            return self.last;
        } else {
            return null;
        }
    }
};

// just a namespace to put parsing-related functions in,
// rather than having them scattered about in the top-level.
pub const Parser = struct {
    const MemError = error{
        OutOfMemory,
    };

    const StringError = error{
        UnexpectedNewline,
        InvalidEscapeChar,
        InvalidHexEscape,
        InvalidUnicodeEscape,
    };

    fn skipWhitespace(str: []const u8, i: *usize) void {
        while (i.* < str.len) : (i.* += 1) {
            switch (str[i.*]) {
                ' ', '\t', 0x0B, 0x0C, '\r' => continue,
                else => return,
            }
        }
    }

    fn parseMultilineString(str: []const u8, a: *mem.Allocator) MemError![]const u8 {
        const State = enum { root, line };

        var state = State.line;
        var buf = std.ArrayList(u8).init(a);
        defer buf.deinit();

        var i: usize = 0;
        debug.assert(str[i] == '|');
        i += 1; // skip initial pipe

        while (i < str.len) : (i += 1) {
            switch (state) {
                .root => {
                    skipWhitespace(str, &i);
                    switch (str[i]) {
                        '|' => state = State.line,
                        else => return buf.toOwnedSlice(),
                    }
                },
                .line => {
                    const char = str[i];
                    switch (char) {
                        '\\' => {
                            const next_is_newline_or_eof = if (i + 1 < str.len) str[i + 1] == '\n' else true;
                            if (next_is_newline_or_eof) {
                                if (str[i - 1] == '\\') continue;
                                i += 1; // skip over newline
                                state = State.root;
                            } else {
                                try buf.append('\\');
                            }
                        },
                        '\n' => {
                            try buf.append('\n');
                            state = State.root;
                        },
                        else => try buf.append(char),
                    }
                },
            }
        }

        // this shouldn't happen; the tokenizer should've caught and errored on this
        return buf.toOwnedSlice();
    }

    // ~~stolen~~ inspired by std/zig/string_literal.zig
    fn parseQuotedString(str: []const u8, a: *mem.Allocator, comptime quote: u8) (MemError || StringError)![]const u8 {
        const State = enum { root, backslash };

        var state = State.root;
        var buf = std.ArrayList(u8).init(a);
        defer buf.deinit();

        var i: usize = 0;
        i += 1;

        while (i < str.len) : (i += 1) {
            const char = str[i];
            switch (state) {
                .root => switch (char) {
                    '\n' => return error.UnexpectedNewline,
                    '\\' => state = State.backslash,
                    quote => {
                        i += 1;
                        return buf.toOwnedSlice();
                    },
                    else => {
                        try buf.append(char);
                    },
                },
                .backslash => switch (char) {
                    'f' => {
                        try buf.append(0x0C);
                        state = State.root;
                    },
                    'n' => {
                        try buf.append('\n');
                        state = State.root;
                    },
                    'r' => {
                        try buf.append('\r');
                        state = State.root;
                    },
                    't' => {
                        try buf.append('\t');
                        state = State.root;
                    },
                    'v' => {
                        try buf.append(0x0B);
                        state = State.root;
                    },
                    '\\', '"', '\'' => {
                        try buf.append(char);
                        state = State.root;
                    },
                    'x' => {
                        if (str.len < i + 3) return error.InvalidHexEscape;
                        if (fmt.parseUnsigned(u8, str[i + 1 .. i + 3], 16)) |byte| {
                            try buf.append(byte);
                            state = State.root;
                            i += 2;
                        } else |err| {
                            return error.InvalidHexEscape;
                        }
                    },
                    'u' => {
                        if (str.len < i + 5) return error.InvalidUnicodeEscape;
                        if (fmt.parseUnsigned(u16, str[i + 1 .. i + 5], 16)) |unic| {
                            try buf.appendSlice(mem.toBytes(unic)[0..]);
                            state = State.root;
                            i += 4;
                        } else |err| {
                            return error.InvalidUnicodeEscape;
                        }
                    },
                    'U' => {
                        if (str.len < i + 9) return error.InvalidUnicodeEscape;
                        if (fmt.parseUnsigned(u32, str[i + 1 .. i + 9], 16)) |unic| {
                            try buf.appendSlice(mem.toBytes(unic)[0..]);
                            state = State.root;
                            i += 8;
                        } else |err| {
                            return error.InvalidUnicodeEscape;
                        }
                    },
                    else => return error.InvalidEscapeChar,
                },
            }
        }

        // unclosed string
        // the tokenizer should've caught this
        return buf.toOwnedSlice();
    }

    fn parseString(tok: Token.String, a: *mem.Allocator) (MemError || StringError)![]const u8 {
        switch (tok) {
            .unquoted => |str| return a.dupe(u8, str),
            .quoted => |str| return switch (str[0]) {
                '"' => parseQuotedString(str, a, '"'),
                '\'' => parseQuotedString(str, a, '\''),
                else => @panic("unknown quote?"),
            },
            .multiline => |str| return parseMultilineString(str, a),
        }
    }

    pub fn parseTable(tokens: *Tokenizer, a: *mem.Allocator) (MemError || StringError || Tokenizer.Error)!Table {
        var table = Table.init(a);
        var key: ?Key = null;
        var value: ?Value = null;
        var i: usize = 0;

        while (try tokens.next()) |token| {
            switch (token) {
                .table_end => return table,
                .keyeq => |str| key = try parseString(str, a),
                .table_start => value = .{ .table = try parseTable(tokens, a) },
                .value => |str| value = .{ .string = try parseString(str, a) },
            }

            if (value) |val| {
                const keystr = key orelse key: {
                    defer i += 1;
                    break :key try fmt.allocPrint(a, "{d}", .{i});
                };
                try table.put(keystr, val);
                value = null;
                key = null;
            }
        }

        // if no table end, return the table anyway;
        // any unclosed tables should've been caught by the tokenizer
        return table;
    }

    // aka 'put that shit in a hashmap please'
    pub fn parse(data: []const u8, a: *mem.Allocator) !Table {
        var tokenizer = Tokenizer.init(data);
        return parseTable(&tokenizer, a);
    }
};


const testing = std.testing;
const alloc = testing.allocator;

// TODO: more tests
test "key = [ table ]" {
    const zckt =
        \\table = [ this is a table :), this is the second value ]
    ;

    var table = try Parser.parse(zckt, alloc);
    defer table.deinit();

    testing.expectEqualStrings(table.getTable("table").?.getString("1").?, "this is the second value");
}

test "duplicate keys overwrite" {
    const zckt =
        \\key = this is a value
        \\key = haha! overwritten
    ;

    var table = try Parser.parse(zckt, alloc);
    defer table.deinit();

    testing.expectEqualStrings(table.getString("key").?, "haha! overwritten");
}

test "multiline string" {
    const zckt =
        \\multiline string =
        \\  |this is a multiline string
        \\  |that means it can span multiple lines
        \\  |however, i can also make \
        \\  |part of it span one line!
    ;

    const multiline_string =
        \\this is a multiline string
        \\that means it can span multiple lines
        \\however, i can also make part of it span one line!
    ;

    var table = try Parser.parse(zckt, alloc);
    defer table.deinit();

    testing.expectEqualStrings(table.getString("multiline string").?, multiline_string);
}