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

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

const Alloc = std.mem.Allocator;
const Reader = std.Io.Reader;
const Writer = std.Io.Writer;

const Value = value.Value;

pub const Parser = @import("io/Parser.zig");
pub const Printer = @import("io/Printer.zig");

pub const Decoder = @import("io/Decoder.zig");
pub const Encoder = @import("io/Encoder.zig");

var main_io: std.Io = undefined;
var main_decoder: Decoder = undefined;
var main_encoder: Encoder = undefined;

var init_done = false;

pub fn init() !void {
    if (init_done) return;
    defer init_done = true;
    main_io = std.Io.Threaded.global_single_threaded.io();
    main_decoder = try .init(gc.mainAlloc());
    main_encoder = try .init(gc.mainAlloc());
}

pub fn mainIo() std.Io {
    init() catch @panic("OOM"); // TODO this is only here for the test suite
    return main_io;
}

pub fn mainDecoder() *Decoder {
    init() catch @panic("OOM"); // TODO this is only here for the test suite
    return &main_decoder;
}

pub fn mainEncoder() *Encoder {
    init() catch @panic("OOM"); // TODO this is only here for the test suite
    return &main_encoder;
}

// Parse

const ParserErrors = error{
    ParseError,
    OutOfMemory,
};

pub fn parse(reader: *Reader) ParserErrors!Value {
    var p = try Parser.init();
    defer p.deinit();
    return p.run(reader);
}

pub fn parseNoError(reader: *Reader) Value {
    var p = Parser.init() catch @panic("OOM");
    defer p.deinit();
    return p.run(reader) catch |e| switch (e) {
        error.OutOfMemory => @panic("OOM"),
        error.ParseError => {
            const format = "Parse error: {s}, unread_char: {s}\n";
            const unread: [4]u8 =
                if (p.unread_char) |c|
                    "0x".* ++ std.fmt.hex(c)
                else
                    "none".*;
            std.debug.panic(format, .{ p.err_msg, unread });
        },
    };
}

// Print

pub fn print(writer: *Writer, v: Value) !void {
    var p = Printer.init(writer);
    try p.print(v);
}

pub fn printStdout(v: Value) !void {
    var stdout_buffer: [4096]u8 = undefined;
    var stdout_writer = std.Io.File.stdout().writer(main_io, &stdout_buffer);
    const writer = &stdout_writer.interface;
    try print(writer, v);
    try writer.writeByte('\n');
    try writer.flush();
}