diff options
| author | Taylan Kammer <taylan.kammer@gmail.com> | 2025-04-05 17:11:29 +0200 |
|---|---|---|
| committer | Taylan Kammer <taylan.kammer@gmail.com> | 2025-04-05 17:11:29 +0200 |
| commit | 70089dacfa6bab5a1e1d0d5aa257e2d671493beb (patch) | |
| tree | 913b19c94792e2d41fdc800d728ad0bdabf0fada /src/zisp/value.zig | |
| parent | cf934006c650d3d008a4408bedbd95597f906e43 (diff) | |
uhhhh buncha changes
Diffstat (limited to 'src/zisp/value.zig')
| -rw-r--r-- | src/zisp/value.zig | 432 |
1 files changed, 294 insertions, 138 deletions
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; } }; |
