~cricket/zckt

ref: 6f63ef3030a5a016af270c4a4b5b6efd85b418e6 zckt/parser.zig -rw-r--r-- 9.9 KiB
6f63ef30 — c piapiac changes to fit ckt changes 3 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
const std = @import("std");
const fmt = std.fmt;
const mem = std.mem;
const meta = std.meta;
const debug = std.debug;

const tknzr = @import("tokenizer.zig");
const Token = tknzr.Token;
const Tokenizer = tknzr.Tokenizer;

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', '\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] == '|');

    // skip initial pipe
    i += 1;

    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();
}

// inspired by std/zig/string_literal.zig
// think about making this match json's string escapes to make CKT -> JSON easy peasy
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),
    }
}

// parse into a hashmap
// (is there a better way to name this ?)
pub const table_parser = struct {
    pub const Key = []const u8;

    pub 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("[ ... ]", .{}),
            }
        }
    };

    pub const Table = struct {
        pub 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 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 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 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 parseTable(
        tokens: *Tokenizer,
        a: *mem.Allocator,
    ) (MemError || StringError || Tokenizer.Error)!Table {
        var table = Table.init(a);
        errdefer table.deinit();

        var key: ?Key = null;
        var value: ?Value = null;
        var i: usize = 0;

        while (try tokens.next()) |token| {
            switch (token) {
                .table_end => return table,
                .key => |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;
    }

    pub fn parse(data: []const u8, a: *mem.Allocator) !Table {
        var tokenizer = Tokenizer.init(data);
        return parseTable(&tokenizer, a);
    }
};