//! //! == 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 and various immediates //! //! sign = 0, quiet = 0 :: Internal use by interpreter //! //! //! === 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 a bitsiwe NOT (implemented as an XOR mask to //! combine it with removal of NaN-related high bits) to avoid the all-zero //! payload value, which would step on Forbidden Value #2, Negative Infinity. //! //! //! === Pointers and immediates === //! //! This region of 51-bit values is divided as follows based on the three high //! bits, providing a payload value of 48 bits for each. //! //! 000 :: Regular pointer to Zisp heap (type tagged) //! //! 001 :: Weak pointer to Zisp heap (type tagged) //! //! 010 :: List segment array pointer (length tagged) //! //! 011 :: Interned string pointer (untagged) //! //! 100 :: 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.) //! //! 101 :: Short immediate string //! //! 11s :: Small rational (signed) //! //! ==== Type-tagged pointers ==== //! //! Zisp heap pointers use 48-bit addresses. This is sufficient, since the //! address space of user-land applications is effectively 48 bits on 64-bit //! systems. Further, Zisp heap objects are allocated at 16-byte boundaries, //! meaning the lowest 4 bits are always zero; this is used for type tagging, //! providing immediate information about the type of object pointed to. //! //! Forbidden Value #3, Positive cqNaN, is avoided thanks to the fact that a //! regular Zisp heap pointer can never be null. //! //! ==== Segmented lists ==== //! //! List segment arrays are also allocated at 16-byte boundaries, but use their //! low 4 bits for segment length; see documentation of this API for details. //! //! ==== Interned strings ==== //! //! Interned string pointers don't use any low tag bits. Unlike other heap //! objects, they can be allocated at any address. //! //! ==== Runes and misc. small values ==== //! //! Runes are symbols up 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. //! //! 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. A virtually //! unlimited number of user-defined enum types can fit here. //! //! ==== Short 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. //! //! //! === Internal use values === //! //! The final 51-bit range is used for various internal purposes by the Zisp //! interpreter, mostly related to transparent code optimization: //! //! 000 :: Direct function pointer aka CALL instruction //! //! 001 :: Lexically scoped variable reference by index //! //! 010 :: Pointer to heap object as constant data //! //! 011 :: Short immediate string as constant data //! //! 1.. :: TBD //! //! Forbidden Value #4, Positive Infinity, is avoided thanks to the fact that //! direct function pointers cannot be null. //! 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 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 ptr = @import("value/ptr.zig"); pub const pair = @import("value/pair.zig"); pub const istr = @import("value/istr.zig"); pub const array = @import("value/array.zig"); pub const string = @import("value/string.zig"); const endian = builtin.target.cpu.arch.endian(); const max = std.math.maxInt; /// 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) = @splat(0); 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), }; } /// Transform back and forth between rune and sstr pub fn runeXsstr(v: Value) Value { return @bitCast(v.bits ^ (1 << 48)); } // 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 plain (unpacked, untagged) pointer into the Zisp heap. May point to any /// kind of object. pub const Zptr = *align(16) anyopaque; /// Values for the lowest 4 bits of a heap pointer, indicating the heap type. pub const PtrTag = enum(u4) { /// Pair aka cons cell aka *[2]Value pair, /// Interned string buffer (8-bit length, then contents) istr, /// Array of various types (see `Array` type for details) array, /// Procedure proc, pub fn ptype(self: PtrTag) type { return switch (self) { .pair => pair.PairPtr, .istr => istr.IstrPtr, .array => array.ArrayPtr, else => @panic("not implemented"), }; } }; pub const PtrTagUIntType = @typeInfo(PtrTag).@"enum".tag_type; // "Pointer etc." high bits (sign=0,exp=MAX,quiet=1) as a u13 field. const ptr_etc: u13 = max(u13) - 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 optimal 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, _1: bool = false, _2: bool = false, _: u13 = ptr_etc, }, /// List segment array pointers lsa: packed struct { tagged_value: u48, _id: u3 = 0b010, _: u13 = ptr_etc, }, /// Interned string pointer isp: packed struct { pointer: u48, _id: u3 = 0b011, _: u13 = ptr_etc, }, /// For initializing and reading runes. rune: packed struct { // actually [6]u8 but packed struct cannot contain arrays name: u48, _id: u3 = 0b100, _: u13 = ptr_etc, }, /// For initializing and reading short strings. sstr: packed struct { // actually [6]u8 but packed struct cannot contain arrays bytes: u48, _id: u3 = 0b101, _: u13 = ptr_etc, }, /// For initializing and reading small rats (rational numbers). srat: packed struct { q: u24, p: i25, _tag: u2 = 0b11, _: u13 = ptr_etc, }, // TODO: Use a general Small Value type registration mechanism. /// For initializing and reading characters. char: packed struct { value: u24, _sv_tag: u24 = 0x000080, _id: u3 = 0b100, _: u13 = ptr_etc, }, // TODO: Use a general Small Value type registration mechanism. /// For initializing and reading miscellaneous values. misc: packed struct { value: MiscValue, _sv_tag: u40 = 0x0000000080, _id: u3 = 0b100, _: u13 = ptr_etc, }, // 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 // Mask for pointer type tag bits const mask_ptr_tag: u48 = max(PtrTagUIntType); /// 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 }); } /// To treat the 64-bit value as an 8-byte array. pub fn bufRO(v: *const Value) *const [8]u8 { return @ptrCast(v); } /// To treat the 64-bit value as an 8-byte array. pub fn bufRW(v: *Value) *[8]u8 { return @ptrCast(v); } /// 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, comptime tag: PtrTag) ?tag.ptype() { // 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 hi_bits: u14 = @intCast(v.bits >> 50); const ptr_val: u48 = @intCast(v.bits & ~mask_ptr_tag); const tag_bits: PtrTagUIntType = @intCast(v.bits & mask_ptr_tag); const is_ptr = hi_bits == 0b01111111111110; const is_tag = tag_bits == @intFromEnum(tag); return if (is_ptr and is_tag) @ptrFromInt(ptr_val) else null; } /// Checks for a pointer and returns the value and tag separately, or null /// if this isn't a pointer at all. This could be useful for a dispatch /// table based on type. pub fn getPtrAny(v: Value) ?struct { Zptr, PtrTag } { // See last function, which is almost identical. const hi_bits: u14 = @intCast(v.bits >> 50); const ptr_val: u48 = @intCast(v.bits & ~mask_ptr_tag); const tag_bits: PtrTagUIntType = @intCast(v.bits & mask_ptr_tag); const is_ptr = hi_bits == 0b01111111111110; const zptr: Zptr = @ptrFromInt(ptr_val); const tag: PtrTag = @enumFromInt(tag_bits); return if (is_ptr) .{ zptr, tag } 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: u14 = @intCast(v.bits >> 50); const lo: u50 = @truncate(v.bits); return hi == 0b01111111111110 and lo != 0; } // TODO: Needs update from here on, and test the above /// 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; } };