diff options
| author | Cliff Click <cliffc@acm.org> | 2026-12-04 14:30:06 -0800 |
|---|---|---|
| committer | Cliff Click <cliffc@acm.org> | 2026-12-04 14:30:06 -0800 |
| commit | b5786e4f67c166a11533660647196c15e04508cd (patch) | |
| tree | 9b9e4b00eb0b41d3ad34ced4d857bb1c50771dcf /chapter33/src/main/java | |
| parent | 2711be2c12980124b89e6c30a66a62f6d19a76cd (diff) | |
| download | Simple-b5786e4f67c166a11533660647196c15e04508cd.tar.gz Simple-b5786e4f67c166a11533660647196c15e04508cd.zip | |
Add interned TypeSet with duals, reset, and reusable scratch storage
Retain the local/external default design and explicit rebasing API. Add uniform-default overloads for migrating existing finite/cofinite compiler sets without changing import semantics. Tests cover the lattice, discovery, rebasing, reset, and allocation-free warmed intern hits.
Validation: make -k -j8 tests passes (834 executions); existing compiler sites still use XInt at this checkpoint.
Diffstat (limited to 'chapter33/src/main/java')
| -rw-r--r-- | chapter33/src/main/java/com/seaofnodes/simple/type/Type.java | 1 | ||||
| -rw-r--r-- | chapter33/src/main/java/com/seaofnodes/simple/type/TypeSet.java | 322 |
2 files changed, 323 insertions, 0 deletions
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/type/Type.java b/chapter33/src/main/java/com/seaofnodes/simple/type/Type.java index 221de04c..0b8d1a34 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/type/Type.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/type/Type.java @@ -257,6 +257,7 @@ public class Type /*implements Cloneable*/ { VISIT.clear(); INTERN.putAll(INTERN0); } + TypeSet.reset(); } // ---------------------------------------------------------- diff --git a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeSet.java b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeSet.java new file mode 100644 index 00000000..d49c1e25 --- /dev/null +++ b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeSet.java @@ -0,0 +1,322 @@ +package com.seaofnodes.simple.type; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import com.seaofnodes.simple.util.Ary; +import com.seaofnodes.simple.util.BAOS; +import com.seaofnodes.simple.util.SB; + +/** + * Interned co-finite set with independent local and external defaults and + * finite XOR exceptions. Meet is union; dual complements both defaults, + * and shares the bits. This is a lattice component, not a new runtime Type. + * + * Used for FIDX, alias and RPC collections; callers keep those namespaces + * separate. Each default describes membership of undiscovered identities + * with that ownership. Uniform defaults need no ownership mask. + */ +public final class TypeSet { + private static final HashMap<TypeSet,TypeSet> INTERN = new HashMap<>(); + private static final HashMap<TypeSet,TypeSet> INTERN0 = new HashMap<>(); + private static final Ary<TypeSet> FREE = new Ary<>(TypeSet.class); + private static final Ary<Ary<int[]>> FREE_BITS = new Ary(Ary.class); + + public static final TypeSet EMPTY = intern(0,allocBits(0)); + public static final TypeSet FULL = EMPTY.dual(); + public static final TypeSet LOCAL = intern(1,allocBits(0)); + public static final TypeSet EXTERNAL = LOCAL.dual(); + public static final TypeSet SET1 = of(1); + public static final TypeSet SET3 = of(1,2); + public static final int[] NO_EXTERNAL = new int[0]; + + // Mutable only while probing or on the free list. + private byte _defaults;// Bit 0: local; bit 1: external. + private int[] _bits; // Finite exceptions, canonical zero padding. + private int _len; // Probe's significant words; interned arrays have this length. + private int _hash; + private TypeSet _dual; + + private TypeSet() { } + private static TypeSet malloc(int defaults, int[] bits, int len) { + TypeSet set = FREE.pop(); + if( set==null ) set = new TypeSet(); + set._defaults = (byte)defaults; + set._bits = bits; + set._len = len; + int hash = 1; + for( int i=0; i<len; i++ ) hash = 31*hash+bits[i]; + set._hash = 31*defaults+hash; + return set; + } + private static void free(TypeSet set) { + set._bits = null; + set._dual = null; + set._hash = set._len = 0; + set._defaults = 0; + FREE.push(set); + } + + private static Ary<int[]> bitsFreeList(int len) { + Ary<int[]> free = FREE_BITS.atX(len); + if( free==null ) FREE_BITS.setX(len,free = new Ary<>(int[].class)); + return free; + } + // All free arrays are zeroed. Retained arrays are never on this list. + private static int[] allocBits(int len) { + int[] bits = bitsFreeList(len).pop(); + return bits==null ? new int[len] : bits; + } + private static void freeBits(int[] bits) { + Arrays.fill(bits,0); + bitsFreeList(bits.length).push(bits); + } + + public static TypeSet make(boolean localDefault, boolean externalDefault) { + return localDefault ? externalDefault ? FULL : LOCAL : externalDefault ? EXTERNAL : EMPTY; + } + + /** The IDs are exceptions to the defaults, not necessarily members. */ + public static TypeSet make(boolean localDefault, boolean externalDefault, int... exceptions) { + int max = -1; + for( int id : exceptions ) { check(id); max = Math.max(max,id); } + int[] bits = allocBits((max+32)>>>5); + for( int id : exceptions ) bits[id>>>5] |= 1<<id; + return intern((localDefault ? 1 : 0) | (externalDefault ? 2 : 0),bits); + } + + private static void check(int id) { + if( id<0 ) throw new IndexOutOfBoundsException("Negative bit: "+id); + } + + // Interns bits arrays; they are immutable and shared after this step. + private static TypeSet intern(int defaults, int[] bits) { + // Canonicalize; remove trailing zeros + int len = bits.length; + while( len>0 && bits[len-1]==0 ) len--; + // Probe with a logical length before compacting: a hit needs neither + // a newly allocated candidate nor an array of the trimmed size. + TypeSet set = malloc(defaults,bits,len); + TypeSet old = INTERN.get(set); + if( old!=null ) { + freeBits(bits); + free(set); + return old; + } + if( len!=bits.length ) { + int[] compact = allocBits(len); + System.arraycopy(bits,0,compact,0,len); + freeBits(bits); + set._bits = bits = compact; + } + TypeSet dual = malloc(defaults^3,bits,len); + set._dual = dual; + dual._dual = set; + INTERN.put(set,set); + INTERN.put(dual,dual); + return set; + } + + /** Called by Type.reset after its basic types have initialized. Capture the + * initial table once, then discard per-compilation sets on subsequent resets. + * Like Type, callers must not carry compilation-specific sets across resets. */ + public static void reset() { + if( INTERN0.isEmpty() ) INTERN0.putAll(INTERN); + else { + for( Iterator<TypeSet> it = INTERN.keySet().iterator(); it.hasNext(); ) { + TypeSet set = it.next(); + if( INTERN0.containsKey(set) ) continue; + it.remove(); + // A pair shares one array. Release it only after both keys + // leave INTERN; the first recycled partner has null bits. + if( set._dual._bits==null ) freeBits(set._bits); + free(set); + } + } + } + + public boolean localDefault() { return (_defaults & 1)!=0; } + public boolean externalDefault() { return (_defaults & 2)!=0; } + public boolean isFinite() { return _defaults==0; } + public boolean isEmpty() { return this==EMPTY; } + + public static TypeSet of(int... members) { return make(false,false,members); } + public static TypeSet of(int member) { return EMPTY.with(member,false); } + public boolean isConstant() { return isFinite() && bitCount()==1; } + public int bitCount() { + assert isFinite(); + int count = 0; + for( int bits : _bits ) count += Integer.bitCount(bits); + return count; + } + public int onlyBit() { + assert isConstant(); + return next(-1); + } + /** Finite membership enumeration, independent of ownership. */ + public int next(int after) { + assert isFinite(); + return nextKnown(after,_bits.length<<5,NO_EXTERNAL); + } + + public void packed(BAOS out) { + out.packed1(_defaults); + out.packed4(_bits.length); + for( int bits : _bits ) out.packed4(bits); + } + public static TypeSet unpack(BAOS in) { + int defaults = in.packed1(), len = in.packed4(); + if( defaults>3 || len<0 || len>in.buf().length-in.size() ) + throw new IllegalArgumentException("Invalid packed TypeSet"); + int[] bits = allocBits(len); + for( int i=0; i<len; i++ ) bits[i] = in.packed4(); + return intern(defaults,bits); + } + + public String str(int[] external) { return str(new SB(),external).toString(); } + public SB str(SB sb, int[] external) { + sb.p("[ "); + int limit = Math.max(32,_bits.length<<5), low = -1; + for( int i=1; i<=limit; i++ ) { + if( i<limit && contains(i,external(external,i)) ) { + if( low<0 ) low=i; + } else if( low>=0 ) { + sb.p(low); + if( i-1>low ) sb.p(i-1==low+1 ? ',' : '-').p(i-1); + sb.p(','); + low=-1; + } + } + sb.unchar(); + if( !isFinite() ) sb.p(localDefault()==externalDefault() ? ",..." : externalDefault() ? ",external..." : ",local..."); + return sb.p("]"); + } + + // Default membership for a word given its external-identity mask. + private int baseline(int external) { + return (localDefault() ? ~external : 0) | (externalDefault() ? external : 0); + } + // Word or zero, pre-scaled word index + private static int word(int[] bits, int i) { return i<bits.length ? bits[i] : 0; } + // Bit from packed bit array, or 0; + private static boolean external(int[] bits, int id) { return (word(bits,id>>>5) & (1<<id))!=0; } + + /** external describes this identity's ownership, not whether it escaped. */ + public boolean contains(int id, boolean external) { + check(id); + boolean def = external ? externalDefault() : localDefault(); + return def ^ ((word(_bits,id>>>5) & (1<<id))!=0); + } + + public boolean contains(int id, int[] external) { return contains(id,external(external,id)); } + public TypeSet with(int id, int[] external) { return with(id,external(external,id)); } + public TypeSet without(int id, int[] external) { return without(id,external(external,id)); } + + public TypeSet with (int id, boolean external) { return set(id,external,true ); } + public TypeSet without(int id, boolean external) { return set(id,external,false); } + // Set a bit + private TypeSet set(int id, boolean external, boolean member) { + if( contains(id,external)==member ) return this; + int[] bits = allocBits(Math.max(_bits.length,(id>>>5)+1)); + System.arraycopy(_bits,0,bits,0,_bits.length); + bits[id>>>5] ^= 1<<id; + return intern(_defaults,bits); + } + + // Uniform-default operations preserve ordinary finite/cofinite set semantics. + // Distinct defaults require the explicit ownership-mask overloads below. + private void uniform() { assert localDefault()==externalDefault() : "Ownership mask required"; } + public boolean contains(int id) { uniform(); return contains(id,false); } + public TypeSet with(int id) { uniform(); return with(id,false); } + public TypeSet without(int id) { uniform(); return without(id,false); } + public TypeSet meet(TypeSet that) { uniform(); that.uniform(); return meet(that,NO_EXTERNAL); } + public TypeSet join(TypeSet that) { uniform(); that.uniform(); return join(that,NO_EXTERNAL); } + public boolean isa(TypeSet that) { return meet(that)==that; } + public int nextKnown(int after, int limit) { uniform(); return nextKnown(after,limit,NO_EXTERNAL); } + public String str() { uniform(); return str(NO_EXTERNAL); } + public SB str(SB sb) { uniform(); return str(sb,NO_EXTERNAL); } + + public TypeSet dual() { return _dual; } + + /** Set union, following Type.meet's ordering. Work is bounded by the + * exception arrays, not the number of identities in the namespace. */ + public TypeSet meet(TypeSet that, int[] external) { + if( this==that ) return this; + int defaults = _defaults | that._defaults; + int[] bits = allocBits(Math.max(_bits.length,that._bits.length)); + for( int i=0; i<bits.length; i++ ) { + int mask = word(external,i); + int x = baseline(mask), y = that.baseline(mask); + int a = x ^ (i<_bits.length ? _bits[i] : 0); + int b = y ^ (i<that._bits.length ? that._bits[i] : 0); + bits[i] = (a | b) ^ (x | y); + } + return intern(defaults,bits); + } + + public TypeSet join(TypeSet that, int[] external) { return dual().meet(that.dual(),external).dual(); } + public boolean isa(TypeSet that, int[] external) { return meet(that,external)==that; } + + /** Enumerate only currently known members. Nonzero defaults may also admit + * undiscovered identities; reaching -1 does not mean those are absent. */ + public int nextKnown(int after, int limit, int[] external) { + if( limit<0 ) throw new IllegalArgumentException("limit < 0"); + if( after < -1 ) throw new IllegalArgumentException("after < -1"); + if( after>=limit-1 ) return -1; + int id = after+1, word = id>>>5; + int words = (limit+31)>>>5; + for( ; word<words; word++, id=word<<5 ) { + int bits = baseline(word(external,word)) ^ word(_bits,word); + bits &= -1 << (id&31); + if( bits!=0 ) { + int next = (word<<5)+Integer.numberOfTrailingZeros(bits); + return next<limit ? next : -1; + } + } + return -1; + } + + /** Interpret a source set in a receiving namespace, preserving every known + * source membership. The map is total and injective over the source IDs. + * The caller chooses the receiving defaults: imported unknown facts and + * unrestricted declarations differ. Unmapped receiving IDs use those defaults. + * This is a boundary interpretation, not a promise to commute with dual. */ + public TypeSet rebase(int[] ids, int[] sourceExternal, int[] targetExternal, + boolean localDefault, boolean externalDefault) { + int max = -1; + for( int id : ids ) { + check(id); + max = Math.max(max,id); + } + int[] bits = allocBits((max+32)>>>5); + for( int id : ids ) { + if( (bits[id>>>5] & (1<<id))!=0 ) { + freeBits(bits); + throw new IllegalArgumentException("Identity map is not injective"); + } + bits[id>>>5] |= 1<<id; + } + Arrays.fill(bits,0); // Reuse the validation scratch as the result. + for( int i=0; i<ids.length; i++ ) + if( contains(i,external(sourceExternal,i))!=(external(targetExternal,ids[i]) ? externalDefault : localDefault) ) + bits[ids[i]>>>5] |= 1<<ids[i]; + return intern((localDefault ? 1 : 0) | (externalDefault ? 2 : 0),bits); + } + + @Override public int hashCode() { return _hash; } + @Override public boolean equals(Object obj) { + return this==obj || obj instanceof TypeSet that && + _defaults==that._defaults && _len==that._len && Arrays.equals(_bits,0,_len,that._bits,0,_len); + } + + @Override public String toString() { + StringBuilder sb = new StringBuilder("{local=").append(localDefault() ? 1 : 0) + .append(", external=").append(externalDefault() ? 1 : 0).append("; xor:"); + for( int word=0; word<_bits.length; word++ ) + for( int bits=_bits[word]; bits!=0; bits &= bits-1 ) { + int id = (word<<5)+Integer.numberOfTrailingZeros(bits); + sb.append(' ').append(id); + } + return sb.append('}').toString(); + } +} |
