// // === NaN Packing Strategy === // // Format of a double, in most to least significant field order: // // { sign: u1, exponent: u11, fraction: u52 } // // When the exponent bits are all set, it's either a NaN or an Infinity. // // For value packing, almost all remaining 53 bits are available, giving us // about 2^53 values, except for the four following bit patterns: // // *** FORBIDDEN VALUES *** // // 1. Negative cqNaN = { sign = 1, exponent = max, fraction = 2^51 } // // 2. Negative Infinity = { sign = 1, exponent = max, fraction = 0 } // // 3. Positive cqNaN = { sign = 0, exponent = max, fraction = 2^51 } // // 4. Positive Infinity = { sign = 0, exponent = max, fraction = 0 } // // The abbreviation "cqNaN" stands for canonical quiet NaN. // // Note that 2^51 means the MSb of the 52 fraction bits being set, and the rest // being zero. The fraction MSb is also called the is_quiet flag, because it // 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 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. (51-bit values excluding zero.) // // sign = 1, quiet = 1 :: Negative Fixnum from -1 to -2^51+1 // // sign = 1, quiet = 0 :: Positive Fixnum from 0 to 2^51-2 // // sign = 0, quiet = 1 :: Pointers // // sign = 0, quiet = 0 :: Others // // // === Fixnums === // // 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. // // 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. // // // === Pointers === // // Pointers are further subdivided as follows based on the remaining 51 bits, // with the first three bits used as a sort of tag: // // 000 :: Regular pointer to Zisp heap object (string, vector, etc.) // // 001 :: Weak pointer to Zisp heap object // // 01. :: Undefined // // 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 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. // // 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. // // // === Other values === // // This 51-bit range is divided as follows: // // 000 :: Subdivided as follows: // // 0....... 0....... 0....... (etc.) :: Rune // // 1....... :: 128 40-bit types // // 0....... 1....... :: 16384 32-bit types // // 0....... 0....... 1....... :: 2097152 24-bit types // // (etc.) // // 001 :: Short string // // 01. :: Small rational // // 1.. :: Undefined // // ==== Runes and Small Values ==== // // 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. // // 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. // // 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. // // 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. // // 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. // // ==== Strings ==== // // Another 48-bit space is used for strings of zero to six bytes. Like runes, // these are NUL-terminated if shorter than six bytes, meaning that NUL cannot // appear in them, but otherwise they allow arbitrary bytes. // // ==== Small rationals ==== // // 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. // 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"); pub const ptr = @import("value/ptr.zig"); pub const seq = @import("value/seq.zig"); pub const rune = @import("value/rune.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"); const endian = builtin.target.cpu.arch.endian(); const max = std.math.maxInt; /// Used when dealing with runes and short strings. pub const ShortString = struct { len: u8, buf: [6]u8, pub fn slice(this: @This()) []const u8 { return this.buf[0..this.len]; } }; /// 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 pub const f = Value{ .misc = .{ .value = .f } }; pub const t = Value{ .misc = .{ .value = .t } }; pub const nil = Value{ .misc = .{ .value = .nil } }; pub const eof = Value{ .misc = .{ .value = .eof } }; 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? 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, exp: u11, sign: bool, }, /// For initializing and reading fixnums. fixnum: packed struct { code: u51, negative: bool, _: u11 = max(u11), _is_fixnum: bool = true, }, /// For initializing and reading pointers. ptr: packed struct { tagged_value: u48, is_weak: bool = false, _unused1: bool = false, _unused2: bool = false, _is_ptr: bool = true, _: u11 = max(u11), _is_fixnum: bool = false, }, /// For initializing and reading runes. rune: packed struct { // actually [6]u8 but packed struct cannot contain arrays name: u48, _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: u3 = 0b001, _: u13 = non_ptr, }, /// For initializing and reading small rats (rational numbers). srat: packed struct { q: u24, p: u25, _tag: u2 = 0b01, _: u13 = non_ptr, }, // 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 /// Dumps the value for inspection. pub fn dump(v: Value) void { 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. pub fn eq(v1: Value, v2: Value) bool { return v1.bits == v2.bits; } // 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 { // 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; } // 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 { // 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 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 if the value is a short string of either kind. pub fn isSstr(v: Value) bool { return v.bits >> 48 == 0x7ff1; } /// Checks if the value is a small rat (rational number). pub fn isSrat(v: Value) bool { return v.bits >> 49 == 0x7ff2 >> 1; } };