//! //! === Syntax === //! //! See /doc/0/1-parse.md to understand the implemented syntax. //! //! //! === Trampolining strategy === //! //! Instead of using recursion directly, the parser is written in a "trampoline" //! style, which ensures that parse depth is not limited by stack size. //! //! All state and context is passed around via a struct pointer. The parser has //! a main loop, which calls a function as dictated by parser.context.next, and //! the function may update the state to have another function called next. //! //! If a function wants to call a recursive subroutine, it pushes some of the //! current context onto a stack, including what function the subroutine should //! return to, and then updates the state to instruct the main loop to call one //! of the entry point subroutines. //! //! If a function wants to make the parser return, either from a subroutine or //! from the main loop, it sets the .result field, and tries to pop the saved //! context. If the context stack was empty, the main loop returns. //! //! //! === Buffering === //! //! For efficiency, call the parser on an input stream with implicit buffering. //! //! The parser does not use its own buffer, beyond one character that may be //! written back into the unread_char field, which is checked at the end to //! ensure it's nothing other than a trailing blank or comment. //! const builtin = @import("builtin"); const std = @import("std"); const Alloc = std.mem.Allocator; const List = std.ArrayListUnmanaged; const Reader = std.Io.Reader; const gc = @import("../gc.zig"); const io = @import("../io.zig"); const lib = @import("../lib.zig"); const value = @import("../value.zig"); const ListPool = gc.ListPool; const IstrPool = gc.IstrPool; const Decoder = io.Decoder; const Value = value.Value; const Parser = @This(); const is_test = builtin.is_test; const is_debug = builtin.mode == .Debug; const detailed_debug = false; // zig fmt: off pub const JDOT = value.rune.pack("JDOT"); pub const JCOL = value.rune.pack("JCOL"); pub const JOIN = value.rune.pack("JOIN"); pub const SHBANG = value.rune.pack("SHBANG"); pub const LABEL = value.rune.pack("LABEL"); pub const HASH = value.rune.pack("HASH"); pub const PQSTR = value.rune.pack("PQSTR"); pub const DQSTR = value.rune.pack("DQSTR"); pub const ATSTR = value.rune.pack("ATSTR"); pub const QUOTE = value.rune.pack("QUOTE"); pub const GRAVE = value.rune.pack("GRAVE"); pub const COMMA = value.rune.pack("COMMA"); pub const SQBRAC = value.rune.pack("SQBRAC"); pub const CRBRAC = value.rune.pack("CRBRAC"); // zig fmt: on pub const Error = enum { ReadError, UnexpectedEof, InvalidCharacter, UnicodeLengthError, UnicodeEncodeError, RuneTooLong, OutOfRange, }; pub const Context = struct { /// What to do next. next: ?Fn = null, /// For storing a context value, like datum to join in join syntax. val: Value = value.none, /// For storing a context char, like list opening bracket. char: u8 = 0, /// Start index of list elements on current parse level, within the global /// list element accumulation array. list_start: usize = 0, /// Are we in a comment? comment: bool = false, }; list_pool: ?*ListPool, istr_pool: ?*IstrPool, alloc: Alloc, ctx_stack: List(Context), str_chars: List(u8), list_elts: List(Value), decoder: ?*Decoder, reader: *Reader = undefined, context: Context = .{}, result: Value = undefined, unread_char: ?u8 = null, err_msg: []const u8 = undefined, pub fn init() !Parser { const list_pool = gc.mainListPool(); const istr_pool = gc.mainIstrPool(); const alloc = gc.mainAlloc(); const decoder = io.mainDecoder(); return initCustom(list_pool, istr_pool, alloc, 16, 512, 32, decoder); } pub fn initCustom( list_pool: ?*ListPool, istr_pool: ?*IstrPool, alloc: Alloc, init_ctx_stack_cap: usize, init_str_chars_cap: usize, init_list_elts_cap: usize, decoder: ?*Decoder, ) !Parser { // Force some sane minimum values. const ctx_cap = @max(1, init_ctx_stack_cap); const str_cap = @max(8, init_str_chars_cap); const lst_cap = @max(2, init_list_elts_cap); return .{ .list_pool = list_pool, .istr_pool = istr_pool, .alloc = alloc, .ctx_stack = try .initCapacity(alloc, ctx_cap), .str_chars = try .initCapacity(alloc, str_cap), .list_elts = try .initCapacity(alloc, lst_cap), .decoder = decoder, }; } pub fn deinit(p: *Parser) void { p.ctx_stack.deinit(p.alloc); p.str_chars.deinit(p.alloc); p.list_elts.deinit(p.alloc); } // // Input reading & unreading // fn read(p: *Parser) !?u8 { if (is_debug and p.unread_char != null) { std.debug.panic( "Called read() while there was an unused character! '{c}'", .{p.unread_char.?}, ); } const c = p.reader.takeByte() catch |e| switch (e) { error.EndOfStream => return null, else => return p.err(.ReadError, "???"), }; if (detailed_debug) { std.debug.print("{c}", .{c}); } return c; } fn readIntoSlice(p: *Parser, slice: []u8) !void { p.reader.readSliceAll(slice) catch |e| return switch (e) { error.EndOfStream => p.err(.UnexpectedEof, "reading into slice"), else => p.err(.ReadError, "???"), }; } fn readNoEof(p: *Parser, comptime emsg: []const u8) !u8 { return try p.read() orelse p.err(.UnexpectedEof, emsg); } // Fake optional, for use in: while (readNoEofOpt()) |c| { } fn readNoEofOpt(p: *Parser, comptime emsg: []const u8) !?u8 { return try p.readNoEof(emsg); } fn unread(p: *Parser, c: u8) void { p.unread_char = c; } fn getUnread(p: *Parser) ?u8 { const c = p.unread_char orelse return null; p.unread_char = null; return c; } // // String accumulation & creation // fn addChar(p: *Parser, c: u8) !void { if (p.context.comment) return; try p.str_chars.append(p.alloc, c); } fn addUnicode(p: *Parser, uc: u21) !void { if (p.context.comment) return; const n = std.unicode.utf8CodepointSequenceLength(uc) catch { return p.err(.UnicodeLengthError, "Unicode/UTF-8 escape"); }; const buf = try p.str_chars.addManyAsSlice(p.alloc, n); const n2 = std.unicode.utf8Encode(uc, buf) catch { return p.err(.UnicodeEncodeError, "Unicode/UTF-8 escape"); }; std.debug.assert(n == n2); } fn getCharsAsString(p: *Parser) !Value { defer p.str_chars.clearRetainingCapacity(); const s = p.str_chars.items; if (value.sstr.isValidSstr(s)) { return value.sstr.pack(s); } else if (value.istr.isValidIstr(s)) { return value.istr.pack(try p.getIstr(s)); } else { return try value.array.newString(p.alloc, s); } } fn getIstr(p: *Parser, s: []const u8) !Value { if (p.istr_pool) |set| { return try value.istr.getOrNewInSet(set, s); } else { return try value.istr.new(p.alloc, s); } } fn getCharsAsRune(p: *Parser) Value { defer p.str_chars.clearRetainingCapacity(); return value.rune.pack(p.str_chars.items); } // // List creation // fn addListElt(p: *Parser, elt: Value) !void { if (p.context.comment) return; try p.list_elts.append(p.alloc, elt); } fn getList(p: *Parser) !Value { if (p.context.comment) return value.nil; if (p.list_elts.items.len == p.context.list_start) return value.nil; defer p.list_elts.shrinkRetainingCapacity(p.context.list_start); const vals = p.list_elts.items[p.context.list_start..]; return value.list.new(p.alloc, p.list_pool, vals); } fn makeList(p: *Parser, vals: []const Value) !Value { return value.list.new(p.alloc, p.list_pool, vals); } // // Stack management & control flow // const Fn = enum { parseUnit, endUnit, returnContext, parseDatum, endDatum, endJoinDatum, parseHashDatum, endHashDatum, endRuneDatum, endLabelDatum, continueList, endQuoteExpr, }; inline fn call(p: *Parser, f: Fn) !void { try switch (f) { .parseUnit => p.parseUnit(), .endUnit => p.endUnit(), .returnContext => p.returnContext(), .parseDatum => p.parseDatum(), .endDatum => p.endDatum(), .endJoinDatum => p.endJoinDatum(), .parseHashDatum => p.parseHashDatum(), .endHashDatum => p.endHashDatum(), .endRuneDatum => p.endRuneDatum(), .endLabelDatum => p.endLabelDatum(), .continueList => p.continueList(), .endQuoteExpr => p.endQuoteExpr(), }; } pub fn run(p: *Parser, reader: *Reader) !Value { p.reader = reader; p.context.next = .parseUnit; while (p.context.next) |next| { if (detailed_debug) p.printStack(); try p.call(next); } if (p.unread_char) |_| { return p.err(.InvalidCharacter, "top-level"); } return p.result; } fn printStack(p: *Parser) void { const stack = p.ctx_stack.items; std.debug.print("\n\n{}:{any} ctx:'{c}' unread:'{c}' \n", .{ stack.len, p.context.next, p.context.char, p.unread_char orelse '_', }); if (stack.len > 0) { var i = stack.len; while (i > 0) : (i -= 1) { const prev = stack[i - 1]; std.debug.print("{}:{any} ctx:'{c}'\n", .{ i - 1, prev.next, prev.char, }); } } } fn err( p: *Parser, comptime e: Error, comptime msg: []const u8, ) error{ParseError} { @branchHint(.cold); p.err_msg = @tagName(e) ++ " @ " ++ msg; return error.ParseError; } fn push(p: *Parser, next: Fn) !void { try p.ctx_stack.append(p.alloc, .{ .next = next, .comment = p.context.comment, }); } fn pushContext(p: *Parser, next: Fn) !void { try p.ctx_stack.append(p.alloc, .{ .next = next, .val = p.context.val, .char = p.context.char, .list_start = p.context.list_start, .comment = p.context.comment, }); } fn ret(p: *Parser) void { if (p.ctx_stack.pop()) |c| { p.context = c; } else { p.context.next = null; } } fn subr(p: *Parser, start: Fn, next: Fn) !void { try p.pushContext(next); p.context.next = start; } fn jump(p: *Parser, next: Fn, val: Value) !void { p.result = try p.decode(val); p.context.next = next; } fn abort(p: *Parser, next: Fn, unread_c: u8) void { p.result = value.none; p.unread_char = unread_c; p.context.next = next; } fn retval(p: *Parser, val: Value) !void { p.result = try p.decode(val); p.ret(); } fn retNoDecode(p: *Parser, val: Value) void { p.result = val; p.ret(); } fn decode(p: *Parser, val: Value) !Value { if (p.context.comment) return val; if (p.decoder) |dec| return dec.decodeInPlace(val); return val; } // // Start parser functions // fn parseUnit(p: *Parser) !void { var c1 = p.getUnread() orelse try p.read(); while (c1) |c| : (c1 = try p.read()) { switch (try p.checkBlank(c)) { .yes => {}, .skip_unit => return p.skipUnit(.parseUnit), .no => { p.unread(c); return p.subr(.parseDatum, .endUnit); }, } } return p.retNoDecode(value.eof); } fn skipUnit(p: *Parser, next: Fn) !void { try p.push(next); p.context.comment = true; return p.jump(.parseUnit, value.none); } fn endUnit(p: *Parser) !void { const c = p.getUnread() orelse return p.ret(); switch (try p.checkBlank(c)) { .yes => {}, .skip_unit => { p.context.val = p.result; return p.skipUnit(.returnContext); }, .no => p.unread(c), } return p.ret(); } fn returnContext(p: *Parser) !void { return p.retNoDecode(p.context.val); } fn parseDatum(p: *Parser) !void { const c = p.getUnread() orelse try p.readNoEof("datum"); if (isBareChar(c) or isSpecialBareChar(c)) { return p.jump(.endDatum, try p.getBareString(c)); } else { return p.parseCladDatum(c, .endDatum); } } fn endDatum(p: *Parser) !void { if (p.result.eq(value.none)) { return p.ret(); } const c = p.getUnread() orelse try p.read() orelse return p.ret(); switch (c) { '.', ':' => { p.context.char = c; p.unread(try p.readNoEof("join datum")); }, else => { p.context.char = 0; p.unread(c); }, } p.context.val = p.result; return p.subr(.parseDatum, .endJoinDatum); } fn endJoinDatum(p: *Parser) !void { const prev = p.context.val; const join = p.context.char; if (p.result.eq(value.none)) { if (join == 0) { return p.retNoDecode(prev); } else { return p.err(.InvalidCharacter, "join datum"); } } const rune = switch (join) { 0 => JOIN, '.' => JDOT, ':' => JCOL, else => unreachable, }; const joined = try p.makeList(&.{ rune, prev, p.result }); return p.jump(.endDatum, joined); } fn getBareString(p: *Parser, c1: u8) !Value { const swallow_joins = isSpecialBareChar(c1); try p.addChar(c1); while (try p.read()) |c| { if (isBareChar(c)) { try p.addChar(c); } else if (swallow_joins and (c == '.' or c == ':')) { try p.addChar(c); } else { p.unread(c); break; } } return p.getCharsAsString(); } fn parseCladDatum(p: *Parser, c: u8, next: Fn) !void { return switch (c) { '|' => p.jump(next, try p.getString('|')), '"' => p.jump(next, try p.getString('"')), '@' => p.jump(next, try p.getAtString()), '#' => p.parseHashExpr(next), '(', '[', '{' => p.parseList(c, next), '\'', '`', ',' => p.parseQuoteExpr(c, next), else => p.abort(next, c), }; } fn getString(p: *Parser, comptime close: u8) !Value { const msg = "string(" ++ .{close} ++ ")"; while (try p.readNoEofOpt(msg)) |c| sw: switch (c) { close => break, '\\' => switch (try p.readNoEof("string backslash escape")) { '\\', '|', '"' => |c2| try p.addChar(c2), '\t', ' ' => { const c2 = try p.skipStringLfEscape(); continue :sw c2; }, '\n' => { const c2 = try p.skipStringIndent(); continue :sw c2; }, 'x' => try p.parseStringRawHexEsc(), 'u' => try p.parseStringUniHexEsc(), else => |c2| try p.parseStringCharEsc(c2), }, // Important to use a capture here, since it may come from a labeled // continue statement passing a new char directly to the switch. else => |c2| try p.addChar(c2), }; const s = try p.getCharsAsString(); return switch (close) { '|' => try p.makeList(&.{ PQSTR, s }), '"' => try p.makeList(&.{ DQSTR, s }), else => unreachable, }; } fn getAtString(p: *Parser) !Value { const stop = try p.readNoEof("at-string"); return if (stop == 255) p.getAtLenStr() else p.getAtSentinelStr(stop); } fn getAtLenStr(p: *Parser) !Value { var len: u48 = 0; inline for (0..6) |_| { len <<= 8; len += try p.readNoEof("at-length-string"); } const AH = value.array.ArrayHeader; const aln: std.mem.Alignment = @enumFromInt(@alignOf(AH)); const mem = try p.alloc.alignedAlloc(u8, aln, @sizeOf(AH) + len); const arr: value.array.ArrayPtr = @ptrCast(mem); arr.* = .{ .len_or_ptr = len, .type = .str, .info = .{ .str = .{} }, }; try p.readIntoSlice(arr.bytes()); return p.makeList(&.{ ATSTR, value.ptr.pack(.array, arr) }); } fn getAtSentinelStr(p: *Parser, stop: u8) !Value { while (try p.readNoEofOpt("at-string")) |c| { if (c == stop) break; try p.addChar(c); } const str = try p.getCharsAsString(); const byte = value.fixnum.pack(stop); return p.makeList(&.{ ATSTR, byte, str }); } fn skipStringLfEscape(p: *Parser) !u8 { const msg = "string linefeed escape"; while (try p.readNoEofOpt(msg)) |c| switch (c) { '\t', ' ' => continue, '\n' => return p.skipStringIndent(), else => return p.err(.InvalidCharacter, msg), }; unreachable; } fn skipStringIndent(p: *Parser) !u8 { const msg = "string newline escape"; while (try p.readNoEofOpt(msg)) |c| switch (c) { '\t', ' ' => continue, else => return c, }; unreachable; } fn parseStringRawHexEsc(p: *Parser) !void { const msg = "string raw hex escape"; while (try p.readNoEofOpt(msg)) |c1| { if (c1 == ';') break; const c2 = try p.readNoEof(msg); const hi = try p.parseHexDigit(c1, msg); const lo = try p.parseHexDigit(c2, msg); try p.addChar(hi << 4 | lo); } } fn parseStringUniHexEsc(p: *Parser) !void { const msg = "string unicode escape"; const uc = try p.parseHex(u21, msg); const c = p.getUnread() orelse try p.readNoEof(msg); if (c != ';') { return p.err(.InvalidCharacter, msg); } try p.addUnicode(uc); } fn parseStringCharEsc(p: *Parser, c: u8) !void { try p.addChar(switch (c) { '0' => 0, 'a' => 7, 'b' => 8, 't' => 9, 'n' => 10, 'v' => 11, 'f' => 12, 'r' => 13, 'e' => 27, else => return p.err(.InvalidCharacter, "string backslash escape"), }); } fn parseHashExpr(p: *Parser, next: Fn) !void { switch (try p.readNoEof("hash")) { 'a'...'z', 'A'...'Z' => |c| { const rune = try p.getRune(c); return p.parseRuneEnd(rune, next); }, '\\' => { const c1 = try p.readNoEof("hash-backslash"); const str = try p.getBareString(c1); const val = try p.makeList(&.{ HASH, str }); return p.jump(next, val); }, '!' => return p.parseHashBang(next), '%' => return p.parseLabel(next), else => |c| { p.unread(c); return p.subr(.parseHashDatum, next); }, } } fn parseHashDatum(p: *Parser) !void { return p.parseCladDatum(p.getUnread().?, .endHashDatum); } fn endHashDatum(p: *Parser) !void { if (p.result.eq(value.none)) { return p.err(.InvalidCharacter, "hash datum"); } return p.retval(try p.makeList(&.{ HASH, p.result })); } fn getRune(p: *Parser, c1: u8) !Value { try p.addChar(c1); var len: usize = 1; while (try p.read()) |c| : (len += 1) { if (!std.ascii.isAlphanumeric(c)) { p.unread(c); return p.getCharsAsRune(); } if (len == 6) { return p.err(.RuneTooLong, "rune"); } try p.addChar(c); } return p.getCharsAsRune(); } fn parseRuneEnd(p: *Parser, r: Value, next: Fn) !void { const c = p.getUnread() orelse return p.jump(next, r); switch (c) { '\\' => { const c1 = try p.readNoEof("rune-backslash"); const str = try p.getBareString(c1); const val = try p.makeList(&.{ r, str }); return p.jump(next, val); }, '"' => { const str = try p.getString('"'); const val = try p.makeList(&.{ r, str }); return p.jump(next, val); }, '|' => { const str = try p.getString('|'); const val = try p.makeList(&.{ r, str }); return p.jump(next, val); }, '@' => { const str = try p.getAtString(); const val = try p.makeList(&.{ r, str }); return p.jump(next, val); }, '#', '(', '[', '{', '\'', '`', ',' => { p.unread(c); try p.push(next); p.context.val = r; return p.subr(.parseDatum, .endRuneDatum); }, else => { p.unread(c); return p.jump(next, r); }, } } fn endRuneDatum(p: *Parser) !void { return p.retval(try p.makeList(&.{ p.context.val, p.result })); } fn parseHashBang(p: *Parser, next: Fn) !void { const interp, const arg_line = try p.getHashBangValue(); if (arg_line) |args| { return p.jump(next, try p.makeList(&.{ SHBANG, interp, args })); } else { return p.jump(next, try p.makeList(&.{ SHBANG, interp })); } } fn getHashBangValue(p: *Parser) !struct { Value, ?Value } { while (try p.readNoEofOpt("hash-bang")) |c| switch (c) { ' ', '\t' => continue, '\n' => return p.err(.InvalidCharacter, "hash-bang"), else => { try p.addChar(c); while (try p.read()) |c2| switch (c2) { '\n' => return .{ try p.getCharsAsString(), null }, ' ', '\t' => break, else => try p.addChar(c2), }; const interp = try p.getCharsAsString(); return .{ interp, try p.getHashBangArgLine() }; }, }; unreachable; } fn getHashBangArgLine(p: *Parser) !?Value { while (try p.read()) |c| switch (c) { ' ', '\t' => continue, '\n' => return null, else => { try p.addChar(c); while (try p.read()) |c2| { if (c2 == '\n') break; try p.addChar(c2); } return try p.getCharsAsString(); }, }; return null; } fn parseLabel(p: *Parser, next: Fn) !void { const n = try p.parseHex(u48, "datum label"); const l = value.fixnum.pack(n); switch (p.getUnread() orelse try p.readNoEof("datum label")) { '%' => return p.jump(next, try p.makeList(&.{ LABEL, l })), '=' => { try p.push(next); p.context.val = l; return p.subr(.parseDatum, .endLabelDatum); }, else => return p.err(.InvalidCharacter, "datum label"), } } fn endLabelDatum(p: *Parser) !void { if (p.result.eq(value.none)) { return p.err(.InvalidCharacter, "label datum"); } return p.retval(try p.makeList(&.{ LABEL, p.context.val, p.result })); } fn parseList(p: *Parser, open: u8, next: Fn) !void { try p.push(next); p.context.char = switch (open) { '(' => ')', '[' => ']', '{' => '}', else => unreachable, }; p.context.list_start = p.list_elts.items.len; switch (open) { '(' => {}, '[' => try p.addListElt(SQBRAC), '{' => try p.addListElt(CRBRAC), else => unreachable, } return p.subr(.parseUnit, .continueList); } fn continueList(p: *Parser) !void { if (p.result.eq(value.eof)) { return p.err(.UnexpectedEof, "list"); } if (p.result.eq(value.none)) { const close = p.context.char; const c = p.getUnread().?; if (c == close) { return p.endList(); } return p.err(.InvalidCharacter, "list"); } try p.addListElt(p.result); return p.subr(.parseUnit, .continueList); } fn endList(p: *Parser) !void { return p.retval(try p.getList()); } fn parseQuoteExpr(p: *Parser, c1: u8, next: Fn) !void { const q = switch (c1) { '\'' => QUOTE, '`' => GRAVE, ',' => COMMA, else => unreachable, }; try p.push(next); p.context.val = q; p.unread(try p.readNoEof("quote expression")); return p.subr(.parseDatum, .endQuoteExpr); } fn endQuoteExpr(p: *Parser) !void { if (p.result.eq(value.none)) { return p.err(.InvalidCharacter, "quote expression datum"); } return p.retval(try p.makeList(&.{ p.context.val, p.result })); } // Helpers fn checkBlank(p: *Parser, c: u8) !enum { yes, skip_unit, no } { switch (c) { '\t'...'\r', ' ' => return .yes, ';' => { var c2 = try p.read() orelse return .yes; if (c2 == '~') return .skip_unit; while (c2 != '\n') c2 = try p.read() orelse break; return .yes; }, else => return .no, } } pub fn isSpecialBareChar(c: u8) bool { return switch (c) { '+', '-', '.', ':', '0'...'9' => true, else => false, }; } pub fn isBareChar(c: u8) bool { return switch (c) { // zig fmt: off 'a'...'z' , 'A'...'Z' , '0'...'9' , '!' , '$' , '%' , '&' , '*' , '+' , '-' , '/' , '<' , '=' , '>' , '?' , '^' , '_' , '~' , => true, // zig fmt: on else => false, }; } fn parseHex(p: *Parser, T: type, comptime emsg: []const u8) !T { const c1 = try p.readNoEof(emsg); var uc: T = try p.parseHexDigit(c1, emsg); while (try p.read()) |c| { if (!std.ascii.isHex(c)) { p.unread(c); return uc; } const shl = std.math.shlExact; uc = shl(T, uc, 4) catch return p.err(.OutOfRange, emsg); uc |= try p.parseHexDigit(c, emsg); } return uc; } fn parseHexDigit(p: *Parser, c: u8, comptime emsg: []const u8) !u8 { return switch (c) { '0'...'9' => c - '0', 'A'...'F' => c - 'A' + 10, 'a'...'f' => c - 'a' + 10, else => p.err(.InvalidCharacter, emsg), }; }