summaryrefslogtreecommitdiff
path: root/src/zisp
diff options
context:
space:
mode:
authorTaylan Kammer <taylan.kammer@gmail.com>2025-04-05 17:11:29 +0200
committerTaylan Kammer <taylan.kammer@gmail.com>2025-04-05 17:11:29 +0200
commit70089dacfa6bab5a1e1d0d5aa257e2d671493beb (patch)
tree913b19c94792e2d41fdc800d728ad0bdabf0fada /src/zisp
parentcf934006c650d3d008a4408bedbd95597f906e43 (diff)
uhhhh buncha changes
Diffstat (limited to 'src/zisp')
-rw-r--r--src/zisp/gc.zig60
-rw-r--r--src/zisp/io/Parser.zig165
-rw-r--r--src/zisp/io/unparser.zig98
-rw-r--r--src/zisp/lib/list.zig8
-rw-r--r--src/zisp/value.zig432
-rw-r--r--src/zisp/value/boole.zig4
-rw-r--r--src/zisp/value/char.zig4
-rw-r--r--src/zisp/value/fixnum.zig6
-rw-r--r--src/zisp/value/istr.zig51
-rw-r--r--src/zisp/value/pair.zig36
-rw-r--r--src/zisp/value/ptr.zig134
-rw-r--r--src/zisp/value/rune.zig35
-rw-r--r--src/zisp/value/seq.zig3
-rw-r--r--src/zisp/value/sstr.zig39
14 files changed, 513 insertions, 562 deletions
diff --git a/src/zisp/gc.zig b/src/zisp/gc.zig
index d778b77..cf2d32f 100644
--- a/src/zisp/gc.zig
+++ b/src/zisp/gc.zig
@@ -3,15 +3,11 @@ const std = @import("std");
const value = @import("value.zig");
+const ptr = value.ptr;
const seq = value.seq;
const Value = value.Value;
-
-/// A "heap value" that could be a Value or object header.
-pub const Hval = union {
- value: Value,
- seq_header: seq.Header,
-};
+const Zptr = value.Zptr;
pub const alloc = std.heap.smp_allocator;
@@ -28,20 +24,42 @@ pub fn cons(v1: Value, v2: Value) *[2]Value {
// Interned strings
-var istr_pool = std.hash_map.StringHashMap(void).init(alloc);
-
-pub fn intern(header: seq.Header, str: []const u8) *seq.Header {
- const hs = @sizeOf(seq.Header);
- const size = str.len + hs;
- const copy = alloc.alloc(u8, size) catch @panic("OOM");
- const header_bytes: [hs]u8 = @bitCast(header);
- @memcpy(copy[0..hs], &header_bytes);
- @memcpy(copy[hs..size], str);
- const entry = istr_pool.getOrPutValue(copy, {}) catch @panic("OOM");
- return @ptrCast(entry.key_ptr);
-}
+const istr_ctx = std.hash_map.StringContext{};
+var istr_pool = std.hash_map.StringHashMap(*seq.Header).init(alloc);
+
+pub fn internString(str: []const u8) Value {
+ const gop = istr_pool.getOrPutAdapted(
+ str,
+ istr_ctx,
+ ) catch @panic("OOM");
+ if (gop.found_existing) {
+ const p: *seq.Header = gop.value_ptr.*;
+ return ptr.pack(p, .seq);
+ }
+
+ std.debug.assert(str.len <= std.math.maxInt(u48));
+
+ const header: seq.Header = .{
+ .type = .string,
+ .info = .{ .string = .{
+ .enc = .utf8,
+ .interned = true,
+ } },
+ .size = @intCast(str.len),
+ };
+
+ const h_align = @alignOf(seq.Header);
+ const h_size = @sizeOf(seq.Header);
+ const size = str.len + h_size;
+
+ const mem = alloc.alignedAlloc(u8, h_align, size) catch @panic("OOM");
+
+ const h_bytes: [h_size]u8 = @bitCast(header);
+ @memcpy(mem[0..h_size], &h_bytes);
+ @memcpy(mem[h_size..size], str);
+
+ gop.key_ptr.* = alloc.dupe(u8, str) catch @panic("OOM");
+ gop.value_ptr.* = @ptrCast(mem.ptr);
-pub fn istrHeader(ptr: *Hval) *seq.Header {
- const entry_key: *[]u8 = @ptrCast(ptr);
- return @alignCast(@ptrCast(entry_key.ptr));
+ return ptr.pack(mem.ptr, .seq);
}
diff --git a/src/zisp/io/Parser.zig b/src/zisp/io/Parser.zig
index 7d14808..14db959 100644
--- a/src/zisp/io/Parser.zig
+++ b/src/zisp/io/Parser.zig
@@ -188,20 +188,12 @@ fn addChar(p: *Parser, c: u8) !void {
try p.chars.append(p.alloc.chars, c);
}
-fn getBareString(p: *Parser) Value {
+fn getString(p: *Parser) Value {
defer p.chars.clearRetainingCapacity();
- return if (p.chars.items.len <= 6)
+ return if (value.sstr.isValidSstr(p.chars.items))
value.sstr.pack(p.chars.items)
else
- value.istr.intern(p.chars.items, false);
-}
-
-fn getQuotedString(p: *Parser) Value {
- defer p.chars.clearRetainingCapacity();
- return if (p.chars.items.len <= 6)
- value.sstr.packQuoted(p.chars.items)
- else
- value.istr.intern(p.chars.items, true);
+ value.istr.intern(p.chars.items);
}
fn getRune(p: *Parser) Value {
@@ -223,7 +215,6 @@ const Fn = enum {
parseJoin,
parseHashDatum,
endHashDatum,
- parseRuneDatum,
endRuneDatum,
endLabelDatum,
continueList,
@@ -234,22 +225,21 @@ const Fn = enum {
fn call(p: *Parser, f: Fn) !void {
try switch (f) {
- .parseUnit => parseUnit(p),
- .parseDatum => parseDatum(p),
- .endUnit => endUnit(p),
- .returnContext => returnContext(p),
- .endFirstDatum => endFirstDatum(p),
- .endJoinDatum => endJoinDatum(p),
- .parseJoin => parseJoin(p),
- .parseHashDatum => parseHashDatum(p),
- .endHashDatum => endHashDatum(p),
- .parseRuneDatum => parseRuneDatum(p),
- .endRuneDatum => endRuneDatum(p),
- .endLabelDatum => endLabelDatum(p),
- .continueList => continueList(p),
- .endImproperList => endImproperList(p),
- .closeImproperList => closeImproperList(p),
- .endQuoteExpr => endQuoteExpr(p),
+ .parseUnit => p.parseUnit(),
+ .parseDatum => p.parseDatum(),
+ .endUnit => p.endUnit(),
+ .returnContext => p.returnContext(),
+ .endFirstDatum => p.endFirstDatum(),
+ .endJoinDatum => p.endJoinDatum(),
+ .parseJoin => p.parseJoin(),
+ .parseHashDatum => p.parseHashDatum(),
+ .endHashDatum => p.endHashDatum(),
+ .endRuneDatum => p.endRuneDatum(),
+ .endLabelDatum => p.endLabelDatum(),
+ .continueList => p.continueList(),
+ .endImproperList => p.endImproperList(),
+ .closeImproperList => p.closeImproperList(),
+ .endQuoteExpr => p.endQuoteExpr(),
};
}
@@ -257,7 +247,7 @@ pub fn run(p: *Parser, input: std.io.AnyReader) !Value {
p.input = input;
p.context.next = .parseUnit;
while (p.context.next) |next| {
- if (detailed_debug) printStack(p);
+ if (detailed_debug) p.printStack();
try p.call(next);
}
if (p.unread_char) |_| {
@@ -360,7 +350,7 @@ fn endUnit(p: *Parser) !void {
const c = p.getUnread() orelse return p.ret();
switch (try p.checkBlanks(c)) {
.yes => {},
- .skip_unit => return skipUnitAndReturn(p),
+ .skip_unit => return p.skipUnitAndReturn(),
.no => p.unread(c),
}
return p.ret();
@@ -383,7 +373,7 @@ fn endFirstDatum(p: *Parser) !void {
if (p.result.eq(value.none)) {
return p.ret();
}
- return parseJoin(p);
+ return p.parseJoin();
}
fn parseJoin(p: *Parser) !void {
@@ -429,54 +419,27 @@ fn parseOneDatum(p: *Parser, c: u8, next: Fn) !void {
return p.parseCladDatum(c, next);
}
-fn parseBareString(p: *Parser, c: u8) !Value {
- const allow_dots = std.ascii.isDigit(c) or switch (c) {
+fn parseBareString(p: *Parser, c1: u8) !Value {
+ const allow_dots = std.ascii.isDigit(c1) or switch (c1) {
'.', '+', '-' => true,
else => false,
};
- try p.addChar(c);
- return p.parseBareStringRest(allow_dots);
-}
-
-fn parseBareEscString(p: *Parser) !Value {
- try p.addChar(try parseBareEsc(p));
- return p.parseBareStringRest(false);
-}
-
-fn parseBareStringRest(p: *Parser, allow_dots: bool) !Value {
+ try p.addChar(c1);
while (try p.read()) |c| {
if (isBareChar(c) or (allow_dots and c == '.')) {
try p.addChar(c);
- } else if (c == '\\') {
- try p.addChar(try parseBareEsc(p));
} else {
p.unread(c);
break;
}
}
- return p.getBareString();
-}
-
-fn parseBareEsc(p: *Parser) !u8 {
- const c = try p.readNoEof("bare escape");
- if (isBareEsc(c)) {
- return c;
- } else {
- return p.err(.InvalidCharacter, "bare escape");
- }
+ return p.getString();
}
fn parseCladDatum(p: *Parser, c: u8, next: Fn) !void {
- if (c == '\\') {
- return p.jump(next, try parseBareEscString(p));
- }
- if (c == '"') {
- return p.jump(next, try p.parseQuotedString('"'));
- }
- if (c == '|') {
- return p.jump(next, try p.parseQuotedString('|'));
- }
return switch (c) {
+ '|' => p.jump(next, try p.parseEscapedString('|')),
+ '"' => p.jump(next, try p.parseEscapedString('"')),
'#' => p.parseHashExpression(next),
'(', '[', '{' => p.parseList(c, next),
'\'', '`', ',' => p.parseQuoteExpr(c, next),
@@ -484,10 +447,11 @@ fn parseCladDatum(p: *Parser, c: u8, next: Fn) !void {
};
}
-fn parseQuotedString(p: *Parser, close: u8) !Value {
+fn parseEscapedString(p: *Parser, close: u8) !Value {
while (try p.read()) |c| {
if (c == close) {
- return p.getQuotedString();
+ const s = p.getString();
+ return if (close == '"') p.cons(QUOTE, s) else s;
}
if (c != '\\') {
try p.addChar(c);
@@ -500,12 +464,8 @@ fn parseQuotedString(p: *Parser, close: u8) !Value {
fn parseQuotedEsc(p: *Parser, close: u8) !void {
const c = try p.readNoEof("quoted escape");
- if (c == close) {
- return p.addChar(close);
- }
- if (c == 'u') {
- return parseUniHexHandleErrors(p);
- }
+ if (c == close) return p.addChar(close);
+ if (c == 'u') return p.parseUniHexHandleErrors();
try p.addChar(switch (c) {
'\\' => c,
'0' => 0,
@@ -523,7 +483,7 @@ fn parseQuotedEsc(p: *Parser, close: u8) !void {
}
fn parseUniHexHandleErrors(p: *Parser) !void {
- return parseUniHex(p) catch |e| switch (e) {
+ return p.parseUniHex() catch |e| switch (e) {
error.Utf8CannotEncodeSurrogateHalf => p.err(
.UnicodeError,
"unicode escape",
@@ -552,16 +512,16 @@ fn parseUniHex(p: *Parser) !void {
fn parseHashExpression(p: *Parser, next: Fn) !void {
const c = try p.readNoEof("hash expression");
- if (try p.checkBlanks(c) != .no) {
- return p.err(.InvalidCharacter, "hash expression");
- }
if (std.ascii.isAlphabetic(c)) {
const r = try p.parseRune(c);
return p.parseRuneEnd(r, next);
}
+ if (c == '\\') {
+ const c1 = try p.readNoEof("bare string after hash");
+ return p.jump(next, p.cons(HASH, try p.parseBareString(c1)));
+ }
if (c == '%') {
- const l = try parseLabel(p);
- return p.parseLabelEnd(l, next);
+ return p.parseLabel(next);
}
p.unread(c);
return p.subr(.parseHashDatum, next);
@@ -594,53 +554,42 @@ fn parseRune(p: *Parser, c1: u8) !Value {
fn parseRuneEnd(p: *Parser, r: Value, next: Fn) !void {
const c = p.getUnread() orelse return p.jump(next, r);
if (c == '\\') {
- return p.jump(next, p.cons(r, try p.parseBareString(c)));
+ const c1 = try p.readNoEof("bare string at rune end");
+ return p.jump(next, p.cons(r, try p.parseBareString(c1)));
}
if (c == '"') {
- return p.jump(next, p.cons(r, try p.parseQuotedString('"')));
+ return p.jump(next, p.cons(r, try p.parseEscapedString('"')));
}
if (c == '|') {
- return p.jump(next, p.cons(r, try p.parseQuotedString('|')));
+ return p.jump(next, p.cons(r, try p.parseEscapedString('|')));
}
p.unread(c);
switch (c) {
'#', '(', '[', '{', '\'', '`', ',' => {
try p.push(next);
p.context.val = r;
- // Use jump to prevent recursion.
- return p.jump(.parseRuneDatum, null);
+ return p.subr(.parseDatum, .endRuneDatum);
},
else => return p.jump(next, r),
}
}
-fn parseRuneDatum(p: *Parser) !void {
- return p.parseCladDatum(p.getUnread().?, .endRuneDatum);
-}
-
fn endRuneDatum(p: *Parser) !void {
- if (p.result.eq(value.none)) {
- p.retval(p.context.val);
- }
return p.retval(p.cons(p.context.val, p.result));
}
-fn parseLabel(p: *Parser) !Value {
- const label = try p.parseHex(u48, "datum label");
- return value.fixnum.pack(label);
-}
-
-fn parseLabelEnd(p: *Parser, l: Value, next: Fn) !void {
- const c = p.getUnread() orelse return p.err(.UnexpectedEof, "datum label");
- if (c == '%') {
- return p.jump(next, p.cons(LABEL, l));
- }
- if (c == '=') {
- try p.push(next);
- p.context.val = l;
- return p.subr(.parseDatum, .endLabelDatum);
+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, p.cons(LABEL, l)),
+ '=' => {
+ try p.push(next);
+ p.context.val = l;
+ return p.subr(.parseDatum, .endLabelDatum);
+ },
+ else => return p.err(.InvalidCharacter, "datum label"),
}
- return p.err(.InvalidCharacter, "datum label");
}
fn endLabelDatum(p: *Parser) !void {
@@ -696,7 +645,7 @@ fn continueList(p: *Parser) !void {
if (p.result.eq(value.none)) {
const c = p.getUnread().?;
if (c == close) {
- return endList(p);
+ return p.endList();
}
return p.err(.InvalidCharacter, "list");
}
@@ -710,7 +659,7 @@ fn continueList(p: *Parser) !void {
var c1 = p.getUnread() orelse try p.read();
while (c1) |c| : (c1 = try p.read()) {
if (c == close) {
- return endList(p);
+ return p.endList();
}
switch (try p.checkBlanks(c)) {
.yes => {},
@@ -736,7 +685,7 @@ fn endImproperList(p: *Parser) !void {
return p.err(.InvalidCharacter, "list tail");
}
p.context.val = lib.list.reverseWithTail(p.context.val, p.result);
- return closeImproperList(p);
+ return p.closeImproperList();
}
fn closeImproperList(p: *Parser) !void {
diff --git a/src/zisp/io/unparser.zig b/src/zisp/io/unparser.zig
index e72f130..64e18d0 100644
--- a/src/zisp/io/unparser.zig
+++ b/src/zisp/io/unparser.zig
@@ -1,23 +1,27 @@
const std = @import("std");
+const gc = @import("../gc.zig");
const value = @import("../value.zig");
const istr = value.istr;
const seq = value.seq;
const ShortString = value.ShortString;
-const OtherTag = value.OtherTag;
const Value = value.Value;
pub fn unparse(w: anytype, v: Value) anyerror!void {
- try if (value.double.check(v))
- unparseDouble(w, v)
- else if (value.fixnum.check(v))
- unparseFixnum(w, v)
- else if (value.ptr.checkZisp(v))
- unparseHeap(w, v)
- else
- unparseOther(w, v);
+ // zig fmt: off
+ try if (v.isDouble()) unparseDouble(w, v)
+ else if (v.isFixnum()) unparseFixnum(w, v)
+ else if (v.getPtr(.pair)) |p| unparsePair(w, @ptrCast(p))
+ else if (v.getPtr(.seq)) |p| unparseSeq(w, @ptrCast(p))
+ else if (v.isRune()) unparseRune(w, v)
+ else if (v.isChar()) unparseChar(w, v)
+ else if (v.isMisc()) unparseMisc(w, v)
+ else if (v.isSrat()) unparseSrat(w, v)
+ else if (v.isSstr()) unparseSstr(w, v)
+ ;
+ // zig fmt: on
}
fn unparseDouble(w: anytype, v: Value) !void {
@@ -32,25 +36,6 @@ fn unparseFixnum(w: anytype, v: Value) !void {
@panic("not implemented");
}
-fn unparseHeap(w: anytype, v: Value) !void {
- const p, const t = value.ptr.unpack(v);
- try switch (t) {
- .pair => unparsePair(w, @ptrCast(p)),
- .seq => unparseSeq(w, @ptrCast(p)),
- else => @panic("not implemented"),
- };
-}
-
-fn unparseOther(w: anytype, v: Value) !void {
- try switch (v.other.tag) {
- .rune => unparseRune(w, v),
- .sstr => unparseSstr(w, v),
- .qstr => unparseQstr(w, v),
- .char => unparseChar(w, v),
- .misc => unparseMisc(w, v),
- };
-}
-
fn unparseRune(w: anytype, v: Value) !void {
const name = value.rune.unpack(v);
try w.writeByte('#');
@@ -58,41 +43,43 @@ fn unparseRune(w: anytype, v: Value) !void {
}
fn unparseSstr(w: anytype, v: Value) !void {
+ // TODO: Check if pipes/escapes necessary.
const str = value.sstr.unpack(v);
try w.writeAll(str.constSlice());
}
-fn unparseQstr(w: anytype, v: Value) !void {
- const str = value.sstr.unpack(v);
- try w.writeByte('"');
- try w.writeAll(str.constSlice());
- try w.writeByte('"');
-}
-
fn unparseChar(w: anytype, v: Value) !void {
+ const uc: u21 = value.char.unpack(v);
var buf: [4]u8 = undefined;
- const len = try std.unicode.utf8Encode(v.char.value, &buf);
+ const len = try std.unicode.utf8Encode(uc, &buf);
try w.writeAll(buf[0..len]);
}
fn unparseMisc(w: anytype, v: Value) !void {
- try switch (v.misc.value) {
- .f => w.writeAll("#f"),
- .t => w.writeAll("#t"),
- .nil => w.writeAll("()"),
- .eof => w.writeAll("#EOF"),
- .none => w.writeAll("#NONE"),
- .undef => w.writeAll("#UNDEF"),
+ try switch (v.bits) {
+ value.f.bits => w.writeAll("#f"),
+ value.t.bits => w.writeAll("#t"),
+ value.nil.bits => w.writeAll("()"),
+ value.eof.bits => w.writeAll("#EOF"),
+ value.none.bits => w.writeAll("#NONE"),
+ value.undef.bits => w.writeAll("#UNDEF"),
+ else => @panic("not implemented"),
};
}
+fn unparseSrat(w: anytype, v: Value) !void {
+ _ = w;
+ _ = v;
+ @panic("not implemented");
+}
+
fn unparsePair(w: anytype, p: *[2]Value) !void {
try w.writeByte('(');
try unparse(w, p[0]);
var cdr = p[1];
- while (value.pair.check(cdr)) : (cdr = value.pair.cdr(cdr)) {
+ while (value.pair.check(cdr)) |p2| : (cdr = value.pair.cdr(cdr)) {
try w.writeByte(' ');
- try unparse(w, value.pair.car(cdr));
+ try unparse(w, p2[0]);
}
if (!value.nil.eq(cdr)) {
try w.writeByte(' ');
@@ -103,21 +90,16 @@ fn unparsePair(w: anytype, p: *[2]Value) !void {
try w.writeByte(')');
}
-fn unparseSeq(w: anytype, p: *seq.Header) !void {
- const h = istr.getHeaderFromPtr(@ptrCast(p));
- switch (h.type) {
- .string => try unparseString(w, h),
+fn unparseSeq(w: anytype, s: *seq.Header) !void {
+ switch (s.type) {
+ .string => try unparseString(w, s),
else => @panic("not implemented"),
}
}
-fn unparseString(w: anytype, h: *seq.Header) !void {
- const info = h.info.string;
- if (info.quoted) {
- try w.writeByte('"');
- }
- try w.writeAll(h.bytes());
- if (info.quoted) {
- try w.writeByte('"');
- }
+fn unparseString(w: anytype, s: *seq.Header) !void {
+ // TODO: Check if pipes/escapes necessary.
+ try w.writeByte('|');
+ try w.writeAll(s.bytes());
+ try w.writeByte('|');
}
diff --git a/src/zisp/lib/list.zig b/src/zisp/lib/list.zig
index be40af7..cd6b553 100644
--- a/src/zisp/lib/list.zig
+++ b/src/zisp/lib/list.zig
@@ -10,11 +10,9 @@ pub fn reverseWithTail(list: Value, tail: Value) Value {
var head = list;
var result = tail;
while (!value.nil.eq(head)) {
- value.pair.assert(head);
- const car = value.pair.car(head);
- const cdr = value.pair.cdr(head);
- result = value.pair.cons(car, result);
- head = cdr;
+ const p = value.pair.unpack(head);
+ result = value.pair.cons(p[0], result);
+ head = p[1];
}
return result;
}
diff --git a/src/zisp/value.zig b/src/zisp/value.zig
index 47ac144..465cbbb 100644
--- a/src/zisp/value.zig
+++ b/src/zisp/value.zig
@@ -1,9 +1,9 @@
//
// === NaN Packing Strategy ===
//
-// Format of a double, in Zig least-to-most significant field order:
+// Format of a double, in most to least significant field order:
//
-// { fraction: u52, exponent: u11, sign: u1 }
+// { sign: u1, exponent: u11, fraction: u52 }
//
// When the exponent bits are all set, it's either a NaN or an Infinity.
//
@@ -27,14 +27,17 @@
// demarcates quiet NaNs. The rest being zero makes it the canonical qNaN.
//
// The positive and negative cqNaN are the *only* NaN values that can actually
-// be returned by any FP operations, which is why we don't use them to pack
-// values; we want to be able to represent NaN in Zisp as a double.
+// be returned by FP operations, which is convenient because it means we can
+// simply use them to represent themselves in Zisp.
+//
+// Infinity values may also be returned by FP operations, and we want them to
+// exist in Zisp as doubles as well, so they also represent themselves.
//
// Beyond those four bit patterns, all values with a maximum exponent (all bits
// set) are fair game for representing other values, so 2^53 - 4 possibilities.
//
// We split those 2^53 - 4 available values into four groups, each allowing for
-// 2^51 - 1 different values to be encoded in them:
+// 2^51 - 1 different values to be encoded. (51-bit values excluding zero.)
//
// sign = 1, quiet = 1 :: Negative Fixnum from -1 to -2^51+1
//
@@ -49,11 +52,11 @@
//
// Negative fixnums actually represent themselves without needing to go through
// any transformation. Only the smallest 52-bit signed negative, -2^51, cannot
-// be represented, as it would step on forbidden value 1, Negative cqNaN.
+// be represented, as it would step on Forbidden Value #1, Negative cqNaN.
//
// Positive fixnums go through bitsiwe NOT (implemented via an XOR mask here to
// make it one operation together with the NaN masking) to avoid the all-zero
-// payload value, which would step on forbidden value 2, Negative Infinity.
+// payload value, which would step on Forbidden Value #2, Negative Infinity.
//
//
// === Pointers ===
@@ -61,90 +64,93 @@
// Pointers are further subdivided as follows based on the remaining 51 bits,
// with the first three bits used as a sort of tag:
//
-// 000 :: Pointer to Zisp heap object (string, vector, etc.)
+// 000 :: Regular pointer to Zisp heap object (string, vector, etc.)
//
// 001 :: Weak pointer to Zisp heap object
//
-// 01. :: Undefined (may be used by GC to flag pointers for some reason?)
+// 01. :: Undefined
//
-// 1.. :: Foreign pointer (basically, a 50-bit fixnum of another type)
+// 1.. :: Undefined
//
// This means pointers to the Zisp heap are 48 bits. Of those, we only really
// need 45, since 64-bit platforms are in practice limited to 48-bit addresses,
-// and allocations happen at 8-byte boundaries, meaning the least significant 3
+// and Zisp heap allocations happen at 8-byte boundaries, meaning the lowest 3
// bits are always unset. Thus, we are able to store yet another 3-bit tag in
// those 48-bit pointers alongside the actual, multiple-of-8, 48-bit address.
//
-// The forbidden value 3, Positive cqNaN, is avoided thanks to the fact that a
+// Forbidden Value #3, Positive cqNaN, is avoided thanks to the fact that a
// regular Zisp heap pointer can never be null. Weak pointers, which can be
// null, avoid stepping on that forbidden value thanks to bit 49 being set.
//
-// Foreign pointers allow storing arbitrary pointers, or integers basically, of
-// up to 50 bits, without any further definition in Zisp of what they mean.
-//
//
// === Other values ===
//
-// This 51-bit range is divided as follows, based on the high bits:
+// This 51-bit range is divided as follows:
//
-// 000 :: Rune
+// 000 :: Subdivided as follows:
//
-// 001 :: Short string
+// 0....... 0....... 0....... (etc.) :: Rune
//
-// 010 :: Short string literal
+// 1....... :: 128 40-bit types
//
-// 011 :: Unicode code point
+// 0....... 1....... :: 16384 32-bit types
//
-// 100 :: Singleton values
+// 0....... 0....... 1....... :: 2097152 24-bit types
//
-// 101, 110, 111 :: Undefined
+// (etc.)
//
-// Runes are symbols of 1 to 6 ASCII characters used to implement reader syntax.
+// 001 :: Short string
//
-// Zisp strings are immutable. Any string fitting into 6 bytes or less will be
-// stored as an immediate value, not requiring any heap allocation or interning.
-// It's implicitly interned, so to speak. This includes the empty string.
+// 01. :: Small rational
//
-// The null byte serves as a terminator for strings shorter than 6 bytes, and
-// therefore cannot appear in these strings; a string that short but actually
-// containing a null byte will need to be heap allocated like other strings.
+// 1.. :: Undefined
//
-// There may also be strings that are this short, but ended up on the heap due
-// to being uninterned. Interning them will return the equivalent short string
-// as an immediate.
+// ==== Runes and Small Values ====
//
-// The separate type for a short string *literal* is for an efficiency hack in
-// the parser; see commentary there.
+// Runes are symbols of 1 to 6 ASCII characters used to implement reader syntax.
+// They are NUL-terminated if shorter than six characters, meaning they cannot
+// contain the NUL byte in their value.
//
-// Unicode code points need a maximum of 21 bits, yet we have 48 available.
-// This may be exploited for a future extension.
+// NOTE: The order in which the characters of the rune are encoded depends on
+// endianness. On little-endian systems (i.e. most modern architectures) the
+// characters will be in "reverse" order, with the first character in lowest
+// position, so the terminating NUL has to be searched from low to high.
//
-// Similarly, it's very unlikely that we will ever need more than a handful of
-// singleton values (false, true, nil, and so on). As such, this range of bit
-// patterns may be subdivided in the future. Right now, only the lowest 8 bits
-// are allowed to be set, with the other 40 being reserved, so there's a limit
-// of 256 singleton values that can be defined.
+// Forbidden Value #4, Positive Infinity, would denote a rune of length zero
+// (all NUL bytes) which isn't allowed, so we avoid stepping on it.
//
-// And top of that, we have three more 48-bit value ranges that are unused!
+// The fact that runes are limited to ASCII opens up a lot of space for other
+// small values to co-inhabit the same 48-bit range. We subdivide this space
+// into increasingly many potential types, with smaller and smaller payloads,
+// where the highest byte with a non-zero MSb determines which size category
+// we're in: If the highest byte has its MSb set, then its seven non-MSb bits
+// define a type and each type has a 40-bit value range; if the second highest
+// byte has its MSb set, then the 14 non-MSb bits of the two high bytes define
+// the type and each has a 32-bit value range; and so on.
//
-// The forbidden value 4, Positive Infinity, would be the "empty string rune"
-// but that isn't allowed anyway, so all is fine.
+// Unicode code points need 21 bits, so we use a 24-bit type for Characters.
+// Miscellaneous values like true, false, nil, eof, etc. are placed into an
+// 8-bit type, since there will never be that many of them.
//
-
-// Here's the original article explaining the strategy:
+// ==== Strings ====
//
-// https://tkammer.de/zisp/notes/nan.html
+// Another 48-bit space is used for strings of zero to six bytes. These are
+// NUL-terminated if shorter than six bytes, meaning that NUL cannot appear in
+// them, and they must be valid UTF-8, meaning that some other values could be
+// hidden here in the future. (UTF-8 sequences cannot contain 0xFE or 0xFF.)
//
-// More about runes:
+// ==== Small rationals ====
//
-// https://tkammer.de/zisp/notes/symbols.html
+// We use a 49-bit space for small exact rational numbers, with the numerator
+// being a two's complement 25-bit signed integer, and denominator a 24-bit
+// unsigned integer.
//
-// Note: Packed structs are least-to-most significant, so the order of fields
-// must be reversed relative to a typical big-endian illustration of the bit
-// patterns of IEEE 754 double-precision floating point numbers.
+const builtin = @import("builtin");
const std = @import("std");
+const gc = @import("gc.zig");
+
pub const double = @import("value/double.zig");
pub const fixnum = @import("value/fixnum.zig");
@@ -152,22 +158,38 @@ pub const ptr = @import("value/ptr.zig");
pub const seq = @import("value/seq.zig");
pub const rune = @import("value/rune.zig");
-pub const sstr = @import("value/sstr.zig");
pub const char = @import("value/char.zig");
pub const misc = @import("value/misc.zig");
+pub const sstr = @import("value/sstr.zig");
pub const boole = @import("value/boole.zig");
pub const pair = @import("value/pair.zig");
pub const istr = @import("value/istr.zig");
-// To fill up the u11 exponent part of a NaN.
-const FILL = 0x7ff;
+const endian = builtin.target.cpu.arch.endian();
-// Used when dealing with runes and short strings.
-pub const ShortString = std.BoundedArray(u8, 6);
+const max = std.math.maxInt;
-pub const OtherTag = enum(u3) { rune, sstr, qstr, char, misc };
+/// Used when dealing with runes and short strings.
+pub const ShortString = std.BoundedArray(u8, 6);
+/// Used to find the length of a rune or short string.
+pub fn sstrLen(x: u64) u8 {
+ const bytes: @Vector(8, u8) = @bitCast(x);
+ const nulls: @Vector(8, u8) = [_]u8{0} ** 8;
+ const comps: u8 = @bitCast(bytes == nulls);
+ // Two bits will always be 0, since the actual short string starts at the
+ // third byte; third lowest or third highest depending on endianness. So,
+ // depending on endianness, either cut off the two leading bits and ensure
+ // that the second-last is set, or ensure that the second highest set, to
+ // limit the length to 6.
+ return switch (endian) {
+ .big => @clz(comps << 2 | 2),
+ .little => @ctz(comps | 64),
+ };
+}
+
+// Make sure false/true only differ in LSb.
pub const MiscValue = enum(u8) { f, t, nil, eof, none, undef };
// zig fmt: off
@@ -179,18 +201,39 @@ pub const none = Value{ .misc = .{ .value = .none } };
pub const undef = Value{ .misc = .{ .value = .undef } };
// zig fmt: on
+/// A pointer into the Zisp heap.
+pub const Zptr = *align(8) anyopaque;
+
+/// Values for the lowest 3 bits of a heap pointer, indicating the heap type.
+pub const PtrTag = enum(u3) {
+ /// Pair aka cons cell aka *[2]Value
+ pair,
+ /// Sequence of various kinds (16-bit meta, 48-bit length, then data)
+ seq,
+ /// Procedure
+ proc,
+};
+
+// Non-pointer high bits (sign=0,exp=MAX,quiet=0) but as a u13 field.
+const non_ptr: u13 = max(u11) << 1;
+
/// Represents a Zisp value/object.
pub const Value = packed union {
/// To get the value as a regular double.
double: f64,
- /// To get an agnostic value for direct comparison with == i.e. eq?.
+ /// To get an agnostic value for direct comparison with == i.e. eq? as well
+ /// as manual bit-fiddling to test for and extract packed values.
bits: u64,
// Some of the structs below are just for inspection, whereas others are to
// initialize a new value of that category as well as read it that way.
+ // Note: Zig packed struct fields are ordered from LSb to MSb, contrary to
+ // most diagrams used to represent IEEE 754, including our own at the top.
+
/// Inspection through the lens of the general IEEE 754 double layout.
+ /// (Unused because we do manual bit-fiddling for optimum results.)
ieee: packed struct {
rest: u51,
quiet: bool,
@@ -202,93 +245,83 @@ pub const Value = packed union {
fixnum: packed struct {
code: u51,
negative: bool,
- _: u11 = FILL,
+ _: u11 = max(u11),
_is_fixnum: bool = true,
},
- /// Inspection through the lens of the ptr category.
+ /// For initializing and reading pointers.
ptr: packed struct {
- _value: u48,
- is_weak: bool,
- _unused: bool,
- is_foreign: bool,
- _is_ptr: bool,
- _: u11,
- _is_fixnum: bool,
- },
-
- /// For initializing and reading foreign pointers.
- fptr: packed struct {
- value: u50,
- _is_foreign: bool = true,
- _is_ptr: bool = true,
- _: u11 = FILL,
- _is_fixnum: bool = false,
- },
-
- /// For initializing and reading Zisp heap pointers.
- zptr: packed struct {
tagged_value: u48,
is_weak: bool = false,
- _unused: bool = false,
- _is_foreign: bool = false,
+ _unused1: bool = false,
+ _unused2: bool = false,
_is_ptr: bool = true,
- _: u11 = FILL,
+ _: u11 = max(u11),
_is_fixnum: bool = false,
},
- /// Inspection as an other (non-fixnum, non-pointer) packed value.
- other: packed struct {
- _value: u48,
- tag: OtherTag,
- _is_ptr: bool,
- _: u11,
- _is_ifxnum: bool,
- },
-
/// For initializing and reading runes.
rune: packed struct {
// actually [6]u8 but packed struct cannot contain arrays
name: u48,
- _tag: OtherTag = .rune,
- _is_ptr: bool = false,
- _: u11 = FILL,
- _is_fixnum: bool = false,
+ _tag: u3 = 0b000,
+ _: u13 = non_ptr,
+ },
+
+ // TODO: Use a general Small Value type registration mechanism.
+ /// For initializing and reading characters.
+ char: packed struct {
+ value: u24,
+ _sv_tag: u24 = 0x000080,
+ _tag: u3 = 0b000,
+ _: u13 = non_ptr,
+ },
+
+ // TODO: Use a general Small Value type registration mechanism.
+ /// For initializing and reading miscellaneous values.
+ misc: packed struct {
+ value: MiscValue,
+ _sv_tag: u40 = 0x0000000080,
+ _tag: u3 = 0b000,
+ _: u13 = non_ptr,
},
/// For initializing and reading short strings.
sstr: packed struct {
// actually [6]u8 but packed struct cannot contain arrays
string: u48,
- tag: OtherTag,
- _is_ptr: bool = false,
- _: u11 = FILL,
- _is_fixnum: bool = false,
+ _tag: u3 = 0b001,
+ _: u13 = non_ptr,
},
- /// For initializing and reading characters.
- char: packed struct {
- value: u21,
- _reserved: u27 = 0,
- _tag: OtherTag = .char,
- _is_ptr: bool = false,
- _: u11 = FILL,
- _is_fixnum: bool = false,
+ /// For initializing and reading small rats (rational numbers).
+ srat: packed struct {
+ q: u24,
+ p: u25,
+ _tag: u2 = 0b01,
+ _: u13 = non_ptr,
},
- /// For initializing and reading misc values aka singletons.
- misc: packed struct {
- value: MiscValue,
- _reserved: u40 = 0,
- _tag: OtherTag = .misc,
- _is_ptr: bool = false,
- _: u11 = FILL,
- _is_fixnum: bool = false,
- },
+ // Disjoint masks where a specific bit or bit-group are set.
+ // zig fmt: off
+ const mask_sign: u64 = 1 << 63 ; // 1 sign bit
+ const mask_exp: u64 = max(u11) << 52 ; // 11 exponent bits
+ const mask_quiet: u64 = 1 << 51 ; // 1 quiet bit of fraction
+ const mask_rest: u64 = max(u51) ; // 51 rest bits of fraction
+ // zig fmt: on
- /// Hexdumps the value.
+ /// Dumps the value for inspection.
pub fn dump(v: Value) void {
- std.debug.dumpHex(std.mem.asBytes(&v));
+ const sign: u1 = @intCast((v.bits & mask_sign) >> 63);
+ const exp: u11 = @intCast((v.bits & mask_exp) >> 52);
+ const quiet: u1 = @intCast((v.bits & mask_quiet) >> 51);
+ const rest: u51 = @intCast(v.bits & mask_rest);
+ std.debug.print(
+ \\value: 0x{x}
+ \\sign: {}, exp: {b}, quiet: {}
+ \\rest: 0x{x}
+ \\
+ , .{ v.bits, sign, exp, quiet, rest });
}
/// Checks for bit-equality i.e. == comprison.
@@ -296,37 +329,160 @@ pub const Value = packed union {
return v1.bits == v2.bits;
}
- // The following aren't type predicates per se, but rather determine which
- // general category the value is in. The exceptions are fixnum and double,
- // since those aren't sub-categorized into further types.
+ // It would be great if we could just write the most readable code here,
+ // using the packed struct definitions above, but the optimizer isn't
+ // sufficiently intelligent to turn that into optimal instructions, so
+ // manual bit fiddling it is.
+
+ // The isDouble and isFixnum checks are not as efficient as we would like
+ // them to be, each requiring two 10-byte MOV instructions to load 64-bit
+ // values for masking and comparison. This seems difficult to improve on
+ // without sacrificing large value ranges in our NaN-packing scheme; it's
+ // probably best to leave it like this and hope that type checks will be
+ // hoisted outside hot-spots by a smart compiler.
/// Checks for a Zisp double, including: +nan.0, -nan.0, +inf.0, -inf.0
pub fn isDouble(v: Value) bool {
- return v.ieee.exp != FILL or v.ieee.rest == 0;
+ // Readable version:
+ //
+ // return v.ieee.exp != max(u11) or v.ieee.rest == 0;
+ //
+ // Optimized:
+ //
+ // 1. AND away the sign and quiet bits, since they may vary.
+ //
+ // 2. If exp is all 1, and rest non-zero, it's a packed value, so check
+ // if the value is less than that.
+ //
+ return v.bits & ~(mask_sign | mask_quiet) <= mask_exp;
}
- /// Checks for a non-double Zisp value packed into a NaN.
- pub fn isPacked(v: Value) bool {
- return !v.isDouble();
- }
+ // Imagine there's an isPacked() implemented as !isDouble() here, used to
+ // make the following functions more readable.
/// Checks for a fixnum.
pub fn isFixnum(v: Value) bool {
- return v.isPacked() and v.ieee.sign;
+ // Readable version:
+ //
+ // return v.isPacked() and v.ieee.sign;
+ //
+ // Optimized:
+ //
+ // 1. AND away the quiet bit, since it may vary.
+ //
+ // 2. Check if highest 12 all 1, rest not all 0, with a greater-than.
+ //
+ return v.bits & ~mask_quiet > mask_sign | mask_exp;
+ }
+
+ /// Checks for a pointer with a given type tag, returning null on failure
+ /// and the pointer value otherwise. This function is for when a value is
+ /// assumed to be of a heap type, such as when `car` is called on it, and
+ /// the "high" pointer tags (49-51) that encode properties like weakness
+ /// don't matter; we only care if it's some kind of valid heap pointer of
+ /// the given type, so we only check the type tag in the low bits (0-2).
+ pub fn getPtr(v: Value, tag: PtrTag) ?Zptr {
+ // Readable version:
+ //
+ // if (v.isPacked() and !v.ieee.sign and v.ieee.quiet ...)
+ //
+ // Optimized:
+ //
+ // I'm not explaining that shit. Figure it out yourself.
+ //
+ // Jokes aside, the code should be self-explanatory, except for:
+ //
+ // Intermediate values should be given explicit types here, for optimal
+ // code-gen. And it should be noted that the null pointer, with no
+ // other high bits set (49-51), which would represent +cqNaN, also
+ // results in a null return, so it can't be mistaken for a pointer.
+ //
+ // This function currently assumes that bits 50 and 51 being set, which
+ // has no defined semantics right now, doesn't change the fact that the
+ // pointer is a Zisp heap pointer. If we decide to use those bits for
+ // something else, simply change the hi_bits check to include them, so
+ // that for example bits 50 and 51 must be zero, or 51 must be zero
+ // while 50 is still ignored, and so on, as appropriate.
+ //
+ const ptr_val: u48 = @intCast(v.bits & (max(u45) << 3));
+ const hi_bits: u13 = @intCast(v.bits >> 51);
+ const tag_bits: u3 = @intCast(v.bits & 7);
+ const is_ptr = hi_bits == 0b0111111111111;
+ const is_tag = tag_bits == @intFromEnum(tag);
+ return if (is_ptr and is_tag) @ptrFromInt(ptr_val) else null;
+ }
+
+ /// Checks whether the value is a pointer with certain property bits, not
+ /// caring about the type tag bits. NOTE: This function doesn't check for
+ /// +cqNaN, which will be mis-identified as a pointer with zero props and
+ /// address. Therefore, don't expose this function to Zisp! Parameter
+ /// `props_mask` specifies props bits to mask away with a NAND, so it's
+ /// possible to only check for bits you care for. For example, to check
+ /// weakness, pass `0b110` for `props_mask` and `0b001` for `props`.
+ pub fn isPtrProps(v: Value, props_mask: u3, props: u3) bool {
+ const hi_bits: u16 = @intCast(v.bits >> 48 & ~@as(u16, props_mask));
+ return hi_bits == 0b0111111111111000 | @as(u16, props);
+ }
+
+ /// Checks whether the value is any kind of pointer, making sure not to
+ /// mis-identify +cqNaN as a null pointer with zero property bits, which
+ /// makes this a bit slower than `isPtrProps()`.
+ pub fn isPtrAny(v: Value) bool {
+ const hi: u13 = @intCast(v.bits >> 51);
+ const lo: u51 = @truncate(v.bits);
+ return hi == 0b0111111111111 and lo != 0;
+ }
+
+ /// Checks for a rune.
+ pub fn isRune(v: Value) bool {
+ //
+ // 1. AND away non-MSb bits of the low 6 bytes, since they may vary.
+ //
+ // 2. Check if the rest is the exact pattern we expect, with sign = 0,
+ // exp all 1, quiet = 0, 3-bit tag = 0, and MSb of remaining bytes 0,
+ // i.e., only the exp bits are set.
+ //
+ // 3. Ensnure that the "first" (based on endianness) of the 6 lowest
+ // bytes is not NUL, which would mean it's the illegal "empty string"
+ // rune corresponding to +Infinity.
+ //
+ // Note that, while this is a rather complicated check for a type that
+ // appears ubiquitously in parser output, we rarely use this type check,
+ // instead using direct comparison to specific rune values, so it's not
+ // important if this is a little inefficient.
+ //
+ const msb_mask = 0xffff808080808080;
+ const nul_mask = switch (endian) {
+ .big => 127 << 40,
+ .little => 127,
+ };
+ return v.bits & msb_mask == mask_exp and v.bits & nul_mask != 0;
+ }
+
+ // The rest are straightforward compared to the above, since the cqNaN and
+ // Infinity special-cases are out of the way and we just need to compare N
+ // high bits to a specific pattern.
+
+ /// Checks for a 24-bit character value. This makes no guarantees related
+ /// to Unicode, such as being a valid Code Point or Unicode Scalar Value.
+ pub fn isChar(v: Value) bool {
+ // TODO: Use a general Small Value type registration mechanism.
+ return v.bits >> 24 == 0x7ff0000080;
}
- /// Checks for any kind of pointer.
- pub fn isPtr(v: Value) bool {
- return v.isPacked() and !v.ieee.sign and v.ieee.quiet;
+ /// Checks for an 8-bit miscellaneous value.
+ pub fn isMisc(v: Value) bool {
+ // TODO: Use a general Small Value type registration mechanism.
+ return v.bits >> 8 == 0x7ff00000000080;
}
- /// Checks for a non-double, non-fixnum, non-pointer Zisp value.
- pub fn isOther(v: Value) bool {
- return v.isPacked() and !v.ieee.sign and !v.ieee.quiet;
+ /// Checks if the value is a short string of either kind.
+ pub fn isSstr(v: Value) bool {
+ return v.bits >> 48 == 0x7ff1;
}
- /// Checks for an other type of value based on tag.
- pub fn isOtherTag(v: Value, tag: OtherTag) bool {
- return v.isOther() and v.other.tag == tag;
+ /// Checks if the value is a small rat (rational number).
+ pub fn isSrat(v: Value) bool {
+ return v.bits >> 49 == 0x7ff2 >> 1;
}
};
diff --git a/src/zisp/value/boole.zig b/src/zisp/value/boole.zig
index 26a1a0a..2e4933c 100644
--- a/src/zisp/value/boole.zig
+++ b/src/zisp/value/boole.zig
@@ -6,7 +6,7 @@ const Value = value.Value;
/// Checks if the value is a boole.
pub fn check(v: Value) bool {
- return v.eq(value.f) or v.eq(value.t);
+ return v.bits >> 1 == value.f.bits >> 1;
}
pub fn assert(v: Value) void {
@@ -17,7 +17,7 @@ pub fn assert(v: Value) void {
}
pub fn pack(b: bool) Value {
- return if (b) value.t else value.f;
+ return @bitCast(value.f.bits | @intFromBool(b));
}
pub fn unpack(v: Value) bool {
diff --git a/src/zisp/value/char.zig b/src/zisp/value/char.zig
index 09a3034..7091303 100644
--- a/src/zisp/value/char.zig
+++ b/src/zisp/value/char.zig
@@ -5,7 +5,7 @@ const Value = value.Value;
// Zig API
pub fn check(v: Value) bool {
- return v.isOtherTag(.char);
+ return v.isChar();
}
pub fn assert(v: Value) void {
@@ -21,7 +21,7 @@ pub fn pack(c: u21) Value {
pub fn unpack(v: Value) u21 {
assert(v);
- return @truncate(v.char.value);
+ return @intCast(v.char.value);
}
// Zisp API
diff --git a/src/zisp/value/fixnum.zig b/src/zisp/value/fixnum.zig
index 80fb4ae..d6e9184 100644
--- a/src/zisp/value/fixnum.zig
+++ b/src/zisp/value/fixnum.zig
@@ -33,6 +33,8 @@ fn assertValidRange(int: i64) void {
}
}
+const positive_mask: u64 = 0xfff7ffffffffffff;
+
fn packNegative(int: i64) Value {
return @bitCast(int);
}
@@ -41,8 +43,6 @@ fn unpackNegative(v: Value) i64 {
return @bitCast(v);
}
-const positive_mask: u64 = 0xfff7ffffffffffff;
-
fn packPositive(int: i64) Value {
const uint: u64 = @bitCast(int);
return @bitCast(uint ^ positive_mask);
@@ -53,6 +53,8 @@ fn unpackPositive(v: Value) i64 {
return @bitCast(uint ^ positive_mask);
}
+// Although we use if, these should compile to branchless code using cmov.
+
pub fn pack(int: i64) Value {
assertValidRange(int);
if (int < 0) {
diff --git a/src/zisp/value/istr.zig b/src/zisp/value/istr.zig
index abd0447..c1c7093 100644
--- a/src/zisp/value/istr.zig
+++ b/src/zisp/value/istr.zig
@@ -6,60 +6,39 @@ const gc = @import("../gc.zig");
const ptr = @import("ptr.zig");
const seq = @import("seq.zig");
-const Hval = gc.Hval;
-
const Value = value.Value;
// Zig API
-pub fn check(v: Value) bool {
- return ptr.checkZispTag(v, .seq);
+pub fn check(v: Value) ?*seq.Header {
+ if (v.getPtr(.seq)) |p| {
+ const h: *seq.Header = @ptrCast(p);
+ if (h.type == .string and h.info.string.interned) {
+ return h;
+ }
+ }
+ return null;
}
-pub fn assert(v: Value) void {
- if (!check(v)) {
+pub fn assert(v: Value) *seq.Header {
+ return check(v) orelse {
v.dump();
@panic("not istr");
- }
-}
-
-pub fn intern(str: []const u8, quoted: bool) Value {
- if (str.len > value.fixnum.max) {
- @panic("String length out of fixnum range.");
- }
- const header: seq.Header = .{
- .type = .string,
- .info = .{ .string = .{
- .enc = .utf8,
- .quoted = quoted,
- .interned = true,
- } },
- .size = @intCast(str.len),
};
- const header_ptr = gc.intern(header, str);
- return ptr.pack(@ptrCast(header_ptr), .seq);
-}
-
-pub fn getHeader(v: Value) *seq.Header {
- assert(v);
- const header_ptr, _ = ptr.unpack(v);
- return gc.istrHeader(header_ptr);
}
-pub fn getHeaderFromPtr(p: *Hval) *seq.Header {
- return gc.istrHeader(p);
+pub fn intern(str: []const u8) Value {
+ return gc.internString(str);
}
// Zisp API
pub fn pred(v: Value) Value {
- return value.boole.pack(check(v));
+ return value.boole.pack(check(v) != null);
}
pub fn len(v: Value) Value {
- const l = getHeader(v).size;
- if (l > value.fixnum.max) {
- @panic("string length out of range");
- }
+ const l = assert(v).size;
+ std.debug.assert(l <= value.fixnum.max);
return value.fixnum.pack(@intCast(l));
}
diff --git a/src/zisp/value/pair.zig b/src/zisp/value/pair.zig
index 6ea1edf..9afaf12 100644
--- a/src/zisp/value/pair.zig
+++ b/src/zisp/value/pair.zig
@@ -9,47 +9,43 @@ const Value = value.Value;
// Zig API
-pub fn check(v: Value) bool {
- return ptr.checkZispTag(v, .pair);
+pub fn check(v: Value) ?*[2]Value {
+ return @ptrCast(v.getPtr(.pair));
}
-pub fn assert(v: Value) void {
- if (!check(v)) {
+pub fn assert(v: Value) *[2]Value {
+ return check(v) orelse {
v.dump();
@panic("not pair");
- }
+ };
+}
+
+pub fn unpack(v: Value) *[2]Value {
+ return assert(v);
}
// Zisp API
pub fn pred(v: Value) Value {
- return value.boole.pack(check(v));
+ return value.boole.pack(check(v) != null);
}
pub fn cons(v1: Value, v2: Value) Value {
return ptr.pack(@ptrCast(gc.cons(v1, v2)), .pair);
}
-fn getMem(v: Value) *[2]Value {
- return @ptrCast(ptr.unpack(v).@"0");
-}
-
pub fn car(v: Value) Value {
- assert(v);
- return getMem(v)[0];
+ return unpack(v)[0];
}
pub fn cdr(v: Value) Value {
- assert(v);
- return getMem(v)[1];
+ return unpack(v)[1];
}
-pub fn setcar(v: Value, new: Value) void {
- assert(v);
- getMem(v)[0] = new;
+pub fn setCar(v: Value, new: Value) void {
+ unpack(v)[0] = new;
}
-pub fn setcdr(v: Value, new: Value) void {
- assert(v);
- getMem(v)[1] = new;
+pub fn setCdr(v: Value, new: Value) void {
+ unpack(v)[1] = new;
}
diff --git a/src/zisp/value/ptr.zig b/src/zisp/value/ptr.zig
index aa2e9a6..8696056 100644
--- a/src/zisp/value/ptr.zig
+++ b/src/zisp/value/ptr.zig
@@ -3,155 +3,75 @@ const std = @import("std");
const gc = @import("../gc.zig");
const value = @import("../value.zig");
-const Hval = gc.Hval;
-
+const PtrTag = value.PtrTag;
const Value = value.Value;
+const Zptr = value.Zptr;
// Zig API
pub fn check(v: Value) bool {
- return v.isPtr();
+ return v.isPtrAny();
}
pub fn assert(v: Value) void {
if (!check(v)) {
v.dump();
- @panic("not a pointer");
- }
-}
-
-// Foreign Pointers
-
-pub fn checkForeign(v: Value) bool {
- return check(v) and v.ptr.is_foreign;
-}
-
-pub fn assertForeign(v: Value) void {
- if (!checkForeign(v)) {
- v.dump();
- @panic("not foreign pointer");
- }
-}
-
-pub fn packForeign(int: u50) Value {
- return .{ .fptr = .{ .value = int } };
-}
-
-pub fn unpackForeign(v: Value) u50 {
- assertForeign(v);
- return v.fptr.value;
-}
-
-// Zisp Pointers
-
-pub fn checkZisp(v: Value) bool {
- return check(v) and !v.ptr.is_foreign;
-}
-
-pub fn assertZisp(v: Value) void {
- if (!checkZisp(v)) {
- v.dump();
- @panic("not zisp pointer");
+ @panic("not pointer");
}
}
pub fn checkWeak(v: Value) bool {
- return checkZisp(v) and v.zptr.is_weak;
+ return v.isPtrProps(0b110, 0b001);
}
pub fn assertWeak(v: Value) void {
if (!checkWeak(v)) {
v.dump();
- @panic("not zisp weak pointer");
+ @panic("not weak pointer");
}
}
-pub fn checkZispTag(v: Value, tag: Tag) bool {
- return checkZisp(v) and unpack(v).@"1" == tag;
+pub fn _pack(ptr: Zptr, tag: PtrTag, is_weak: bool) Value {
+ const ptr_val: usize = @intFromPtr(ptr);
+ std.debug.assert(ptr_val < std.math.maxInt(u48));
+ const tagged: u48 = @intCast(ptr_val | @intFromEnum(tag));
+ return .{ .ptr = .{ .tagged_value = tagged, .is_weak = is_weak } };
}
-pub fn assertZispTag(v: Value, tag: Tag) void {
- if (!checkZispTag(v, tag)) {
- v.dump();
- @panic("not zisp pointer or wrong tag");
- }
-}
-
-pub fn checkStrong(v: Value) bool {
- return checkZisp(v) and !v.zptr.is_weak;
-}
-
-pub fn assertStrong(v: Value) void {
- if (!checkStrong(v)) {
- v.dump();
- @panic("not zisp strong pointer");
- }
-}
-
-pub fn packZisp(ptr: *Hval, tag: Tag, is_weak: bool) Value {
- return .{ .zptr = .{
- .tagged_value = tagPtr(ptr, tag),
- .is_weak = is_weak,
- } };
+pub fn pack(ptr: Zptr, tag: PtrTag) Value {
+ return _pack(ptr, tag, false);
}
-pub fn pack(ptr: *Hval, tag: Tag) Value {
- return packZisp(ptr, tag, false);
-}
-
-pub fn packWeak(ptr: *Hval, tag: Tag) Value {
- return packZisp(ptr, tag, true);
-}
-
-// Unpacks weak as well; no need for a separate fn.
-pub fn unpack(v: Value) struct { *Hval, Tag } {
- assertZisp(v);
- return untagPtr(v.zptr.tagged_value);
+pub fn packWeak(ptr: Zptr, tag: PtrTag) Value {
+ return _pack(ptr, tag, true);
}
pub fn setWeakNull(v: *Value) void {
assertWeak(v.*);
- v.zptr.tagged_value = 0;
+ v.ptr.tagged_value = 0;
}
pub fn isWeakNull(v: Value) bool {
assertWeak(v);
- return v.zptr.tagged_value == 0;
+ return v.ptr.tagged_value == 0;
}
-fn tagPtr(ptr: *Hval, tag: Tag) u48 {
- const int: usize = @intFromPtr(ptr);
- const untagged: u48 = @intCast(int);
- return untagged | @intFromEnum(tag);
-}
-
-fn untagPtr(tagged: u48) struct { *Hval, Tag } {
- const untagged: u48 = tagged & 0xfffffffffff8;
- const ptr: *Hval = @ptrFromInt(untagged);
- const int: u3 = @truncate(tagged);
- const tag: Tag = @enumFromInt(int);
+pub fn unpack(v: Value) struct { Zptr, PtrTag } {
+ assert(v);
+ const tagged = v.ptr.tagged_value;
+ const ptr_val: u48 = tagged & ~@as(u48, 7);
+ const tag_val: u3 = @intCast(tagged & 7);
+ const ptr: Zptr = @ptrFromInt(ptr_val);
+ const tag: PtrTag = @enumFromInt(tag_val);
return .{ ptr, tag };
}
-pub const Tag = enum(u3) {
- /// Pair aka cons cell aka *[2]Value
- pair,
- /// Sequence of various kinds (16-bit meta, 48-bit length, then data)
- seq,
- /// Procedure
- proc,
-};
-
// Zisp API
-pub fn predForeign(v: Value) Value {
- return value.boole.pack(checkForeign(v));
-}
-
pub fn makeWeak(v: Value) Value {
- assertStrong(v);
+ assert(v);
var copy = v;
- copy.zptr.is_weak = true;
+ copy.ptr.is_weak = true;
return copy;
}
@@ -168,7 +88,7 @@ pub fn getWeak(v: Value) Value {
return value.f;
} else {
var copy = v;
- copy.zptr.is_weak = false;
+ copy.ptr.is_weak = false;
return copy;
}
}
diff --git a/src/zisp/value/rune.zig b/src/zisp/value/rune.zig
index 195210e..e75c276 100644
--- a/src/zisp/value/rune.zig
+++ b/src/zisp/value/rune.zig
@@ -8,7 +8,7 @@ const Value = value.Value;
// Zig API
pub fn check(v: Value) bool {
- return v.isOtherTag(.rune);
+ return v.isRune();
}
pub fn assert(v: Value) void {
@@ -19,17 +19,9 @@ pub fn assert(v: Value) void {
}
pub fn isValidRune(s: []const u8) bool {
- if (s.len == 0 or s.len > 6) {
- return false;
- }
- if (!std.ascii.isAlphabetic(s[0])) {
- return false;
- }
- for (s[1..]) |c| {
- if (!std.ascii.isAlphanumeric(c)) {
- return false;
- }
- }
+ if (s.len == 0 or s.len > 6) return false;
+ if (!std.ascii.isAlphabetic(s[0])) return false;
+ for (s[1..]) |c| if (!std.ascii.isAlphanumeric(c)) return false;
return true;
}
@@ -48,6 +40,7 @@ pub fn pack(s: []const u8) Value {
}
pub fn packForced(s: []const u8) Value {
+ std.debug.assert(0 < s.len and s.len < 7);
var v = Value{ .rune = .{ .name = 0 } };
const dest: [*]u8 = @ptrCast(&v.rune.name);
@memcpy(dest, s);
@@ -57,10 +50,8 @@ pub fn packForced(s: []const u8) Value {
pub fn unpack(v: Value) ShortString {
assert(v);
const s: [6]u8 = @bitCast(v.rune.name);
- inline for (0..6) |i| {
- if (s[i] == 0) return .{ .buffer = s, .len = i };
- }
- return .{ .buffer = s, .len = 6 };
+ const l = value.sstrLen(v.bits);
+ return .{ .buffer = s, .len = l };
}
// Zisp API
@@ -68,15 +59,3 @@ pub fn unpack(v: Value) ShortString {
pub fn pred(v: Value) Value {
return value.boole.pack(check(v));
}
-
-pub fn make(v: Value) Value {
- const s, const l = value.sstr.unpack(v);
- return pack(s[0..l]);
-}
-
-pub fn getName(v: Value) Value {
- const s, const l = unpack(v);
- return value.sstr.pack(s[0..l]);
-}
-
-// TODO: Registering decoders
diff --git a/src/zisp/value/seq.zig b/src/zisp/value/seq.zig
index 3418a5a..cba46ab 100644
--- a/src/zisp/value/seq.zig
+++ b/src/zisp/value/seq.zig
@@ -31,9 +31,8 @@ pub const Header = packed struct(u64) {
string: packed struct(u14) {
enc: enum(u4) { utf8, utf16, utf24, utf32 },
endian: Endian = .native,
- quoted: bool,
interned: bool,
- _: u7 = 0,
+ _: u8 = 0,
},
ints: packed struct(u14) {
signed: bool,
diff --git a/src/zisp/value/sstr.zig b/src/zisp/value/sstr.zig
index b02fd3d..4f0336e 100644
--- a/src/zisp/value/sstr.zig
+++ b/src/zisp/value/sstr.zig
@@ -3,13 +3,12 @@ const std = @import("std");
const value = @import("../value.zig");
const ShortString = value.ShortString;
-const OtherTag = value.OtherTag;
const Value = value.Value;
// Zig API
pub fn check(v: Value) bool {
- return v.isOtherTag(.sstr) or v.isOtherTag(.qstr);
+ return v.isSstr();
}
pub fn assert(v: Value) void {
@@ -19,21 +18,11 @@ pub fn assert(v: Value) void {
}
}
-pub fn checkQuoted(v: Value) bool {
- return v.isOtherTag(.qstr);
-}
-
// For now, ignore encoding, just treat it as []u8.
pub fn isValidSstr(s: []const u8) bool {
- if (s.len > 6) {
- return false;
- }
- for (s) |c| {
- if (c == 0) {
- return false;
- }
- }
+ if (s.len > 6) return false;
+ for (s) |c| if (c == 0) return false;
return true;
}
@@ -44,23 +33,9 @@ fn assertValidSstr(s: []const u8) void {
}
}
-// Different ways of doing the following have been tested, including manual
-// shifting and bit masking, but memcpy always wins easily according to our
-// micro-benchmarks, under both ReleaseSafe and ReleaseFast.
-
-// Note: rune.zig uses equivalent code; probably good to keep in sync.
-
pub fn pack(s: []const u8) Value {
- return _pack(s, .sstr);
-}
-
-pub fn packQuoted(s: []const u8) Value {
- return _pack(s, .qstr);
-}
-
-fn _pack(s: []const u8, tag: OtherTag) Value {
assertValidSstr(s);
- var v = Value{ .sstr = .{ .string = 0, .tag = tag } };
+ var v = Value{ .sstr = .{ .string = 0 } };
const dest: [*]u8 = @ptrCast(&v.sstr.string);
@memcpy(dest, s);
return v;
@@ -69,10 +44,8 @@ fn _pack(s: []const u8, tag: OtherTag) Value {
pub fn unpack(v: Value) ShortString {
assert(v);
const s: [6]u8 = @bitCast(v.sstr.string);
- inline for (0..6) |i| {
- if (s[i] == 0) return .{ .buffer = s, .len = i };
- }
- return .{ .buffer = s, .len = 6 };
+ const l = value.sstrLen(v.bits);
+ return .{ .buffer = s, .len = l };
}
// No Zisp API for sstr specifically, since it's a string. See string.zig.