tree.go raw

   1  package iskra
   2  
   3  import (
   4  	"fmt"
   5  
   6  	"git.smesh.lol/go-iskra/lattice"
   7  )
   8  
   9  // Tree is the iskra layer over one lattice tree: the record metadata, byte and
  10  // token pools, the dictionary, and the two indices rebuilt on open.
  11  //
  12  // TokenPool keeps every content token id in memory. The .tokpool file layout is
  13  // plain LE uint32 (iskra/storage.mx), so a base path whose .tokpool is
  14  // non-empty is read as a warning-free in-memory image and written back to
  15  // .tokpool on flush, one uint32 per entry; no content is lost either way.
  16  type Tree struct {
  17  	DB         *lattice.Tree
  18  	RecMeta    []lattice.MetaRecord
  19  	StringPool []byte
  20  	TokenPool  []uint32
  21  	Dict       *Dict // the dictionary TokenPool ids index
  22  	TokFile    bool  // base path has a .tokpool companion
  23  	BigramIdx  map[string][]uint32
  24  	SigIdx     map[uint32][]uint32
  25  	BulkMode   bool
  26  }
  27  
  28  // NewTree wraps a lattice tree.
  29  func NewTree(db *lattice.Tree) *Tree {
  30  	return &Tree{
  31  		DB:        db,
  32  		Dict:      NewDict(),
  33  		BigramIdx: make(map[string][]uint32),
  34  		SigIdx:    make(map[uint32][]uint32),
  35  	}
  36  }
  37  
  38  // MetaAt returns the metadata at a record index, growing the slice through
  39  // gaps with zero entries as iskra/storage.mx metaSet does. Record indices are
  40  // not monotone when iskradb's free list is reused.
  41  func (t *Tree) MetaAt(recIdx uint32) *lattice.MetaRecord {
  42  	for uint32(len(t.RecMeta)) <= recIdx {
  43  		t.RecMeta = append(t.RecMeta, lattice.MetaRecord{})
  44  	}
  45  	return &t.RecMeta[recIdx]
  46  }
  47  
  48  // Meta returns the metadata at a record index, or nil when absent.
  49  func (t *Tree) Meta(recIdx uint32) *lattice.MetaRecord {
  50  	if uint64(recIdx) < uint64(len(t.RecMeta)) {
  51  		return &t.RecMeta[recIdx]
  52  	}
  53  	return nil
  54  }
  55  
  56  // SetMeta stores a metadata entry at a record index.
  57  func (t *Tree) SetMeta(recIdx uint32, m lattice.MetaRecord) {
  58  	*t.MetaAt(recIdx) = m
  59  }
  60  
  61  // MetaInc bumps the occurrence count of a record.
  62  func (t *Tree) MetaInc(recIdx uint32) {
  63  	if m := t.Meta(recIdx); m != nil {
  64  		m.Count++
  65  	}
  66  }
  67  
  68  // Insert adds a named segment at a branch and stage and returns the record
  69  // index. The form goes on the record, the metadata gets kind and stage, and the
  70  // content goes to the token pool.
  71  func (t *Tree) Insert(branch lattice.Branch, key lattice.Key, form string, kind lattice.NodeKind, stage uint8) (uint32, error) {
  72  	var rec lattice.Record
  73  	lattice.SetFormOnRecord(&rec, form, &t.StringPool)
  74  	rec.Branch = uint8(branch)
  75  	recIdx, err := t.DB.InsertRec(branch, key, rec)
  76  	if err != nil {
  77  		return 0, err
  78  	}
  79  	if k := uint64(t.DB.RecordCount()); recIdx >= uint32(k) {
  80  		return 0, fmt.Errorf("iskra: record index %d reached the count %d", recIdx, k)
  81  	}
  82  	t.SetMeta(recIdx, lattice.MetaRecord{Kind: kind, StageTag: stage})
  83  	return recIdx, nil
  84  }
  85  
  86  // SetContent tokenises content into the shared dictionary and the token pool
  87  // and records the run on the metadata at recIdx.
  88  //
  89  // A segment that TokenizeToken yields as exactly one token stores its
  90  // dictionary id in the entry's Extra[0] as a single byte, which is the on-disk
  91  // convention the moxie reader of .meta expects (iskra/meta.mx: "Single-chunk
  92  // token: store dictID in Extra[0]"). A longer segment leaves Extra untouched.
  93  func (t *Tree) SetContent(recIdx uint32, content []byte) {
  94  	off := uint32(len(t.TokenPool))
  95  	seq := t.Dict.Tokenize(content)
  96  	t.TokenPool = append(t.TokenPool, seq...)
  97  	m := t.MetaAt(recIdx)
  98  	m.SetContentRef(off, uint32(len(seq)))
  99  	if len(seq) == 1 && seq[0] < 255 {
 100  		m.Extra[0] = byte(seq[0])
 101  	}
 102  }
 103  
 104  // TokenSeq returns the token ids of a record's content.
 105  func (t *Tree) TokenSeq(recIdx uint32) []uint32 {
 106  	m := t.Meta(recIdx)
 107  	if m == nil {
 108  		return nil
 109  	}
 110  	off, n := m.ContentOffset(), m.ContentLen()
 111  	end := uint64(off) + uint64(n)
 112  	if end > uint64(len(t.TokenPool)) {
 113  		if uint64(off) >= uint64(len(t.TokenPool)) {
 114  			return nil
 115  		}
 116  		return t.TokenPool[off:]
 117  	}
 118  	return t.TokenPool[off:end]
 119  }
 120  
 121  // Content renders a record's content from its token ids, two-char chunks
 122  // joined by a space, which is how the token pool reads back.
 123  func (t *Tree) Content(recIdx uint32) []byte {
 124  	seq := t.TokenSeq(recIdx)
 125  	if len(seq) == 0 {
 126  		return nil
 127  	}
 128  	if len(seq) == 1 {
 129  		return t.Dict.Get(seq[0])
 130  	}
 131  	out := make([]byte, 0, len(seq)*3)
 132  	for i, idx := range seq {
 133  		if int(idx) >= len(t.Dict.Entries) {
 134  			continue
 135  		}
 136  		if i > 0 {
 137  			out = append(out, ' ')
 138  		}
 139  		out = append(out, t.Dict.Get(idx)...)
 140  	}
 141  	return out
 142  }
 143  
 144  // Form returns the surface form stored on a record.
 145  func (t *Tree) Form(recIdx uint32) string {
 146  	r, err := t.DB.GetRecord(recIdx)
 147  	if err != nil {
 148  		return ""
 149  	}
 150  	return lattice.FormFromRecord(r, t.StringPool)
 151  }
 152  
 153  // LookupRecIdx returns the record index of a key in a branch, or NullRec.
 154  func (t *Tree) LookupRecIdx(branch lattice.Branch, key lattice.Key) (uint32, error) {
 155  	return t.DB.LookupRecIdx(branch, key)
 156  }
 157  
 158  // LookupName looks a segment up by name at a stage, then by its segment id,
 159  // which is what the corpus loader stores. It returns the record index for the
 160  // name that matched and the stage it was found at.
 161  func (t *Tree) LookupName(stage uint8, name string) (ri uint32, matched uint8, err error) {
 162  	for _, s := range []uint8{stage} {
 163  		if s == 0 {
 164  			continue
 165  		}
 166  		if ri, err := t.LookupRecIdxAny(NameKey(s, name)); err != nil {
 167  			return lattice.NullRec, 0, err
 168  		} else if ri != lattice.NullRec {
 169  			return ri, s, nil
 170  		}
 171  	}
 172  	return lattice.NullRec, 0, nil
 173  }
 174  
 175  // LookupRecIdxAny searches every branch for a key.
 176  func (t *Tree) LookupRecIdxAny(key lattice.Key) (uint32, error) {
 177  	for b := 0; b < lattice.C; b++ {
 178  		ri, err := t.DB.LookupRecIdx(lattice.Branch(b), key)
 179  		if err != nil {
 180  			return lattice.NullRec, err
 181  		}
 182  		if ri != lattice.NullRec {
 183  			return ri, nil
 184  		}
 185  	}
 186  	return lattice.NullRec, nil
 187  }
 188  
 189  // StageLinksFor returns the record indices of the same named entity at every
 190  // other stage, found by name hash with the stage byte replaced.
 191  func (t *Tree) StageLinksFor(branch lattice.Branch, key lattice.Key) []uint32 {
 192  	var out []uint32
 193  	hash := lattice.KeyHash(key)
 194  	stage := lattice.KeyStage(key)
 195  	for s := uint8(1); s <= 5; s++ {
 196  		if s == stage {
 197  			continue
 198  		}
 199  		ri, err := t.DB.LookupRecIdx(branch, lattice.MakeCodeKey(s, hash))
 200  		if err == nil && ri != lattice.NullRec {
 201  			out = append(out, ri)
 202  		}
 203  	}
 204  	return out
 205  }
 206  
 207  // FinalizeLinks wires Record.Link[0] and Link[1] across branches after all
 208  // inserts are done. The branch comes from the kind, and the partner key is the
 209  // same stage and name hash in the two other branches.
 210  func (t *Tree) FinalizeLinks() error {
 211  	others := [lattice.C][]lattice.Branch{}
 212  	for b := 0; b < lattice.C; b++ {
 213  		var o []lattice.Branch
 214  		for c := 0; c < lattice.C; c++ {
 215  			if c != b {
 216  				o = append(o, lattice.Branch(c))
 217  			}
 218  		}
 219  		others[b] = o
 220  	}
 221  	for recIdx := 0; uint32(recIdx) < uint32(len(t.RecMeta)); recIdx++ {
 222  		m := &t.RecMeta[recIdx]
 223  		b := KindToBranch(m.Kind)
 224  		key, ok := t.DB.RecKey[uint32(recIdx)]
 225  		if !ok {
 226  			continue
 227  		}
 228  		stage := lattice.KeyStage(key)
 229  		hash := lattice.KeyHash(key)
 230  		rec, err := t.DB.GetRecord(uint32(recIdx))
 231  		if err != nil {
 232  			return err
 233  		}
 234  		for i, other := range others[b] {
 235  			ri, err := t.DB.LookupRecIdx(other, lattice.MakeCodeKey(stage, hash))
 236  			if err != nil {
 237  				return err
 238  			}
 239  			if ri != lattice.NullRec {
 240  				rec.Link[i] = ri
 241  			}
 242  		}
 243  	}
 244  	return nil
 245  }
 246  
 247  // RebuildSigIdx rebuilds the signature bucket index from the metadata.
 248  func (t *Tree) RebuildSigIdx() {
 249  	t.SigIdx = make(map[uint32][]uint32)
 250  	for i := range t.RecMeta {
 251  		m := &t.RecMeta[i]
 252  		h := m.SigHash()
 253  		if h == 0 {
 254  			continue
 255  		}
 256  		bucket := (uint32(m.StageTag) << 24) | h
 257  		t.SigIdx[bucket] = append(t.SigIdx[bucket], uint32(i))
 258  	}
 259  }
 260  
 261  // SigIdxAdd registers one record in the signature index.
 262  func (t *Tree) SigIdxAdd(recIdx uint32, stage uint8, sighash uint32) {
 263  	if sighash == 0 {
 264  		return
 265  	}
 266  	bucket := (uint32(stage) << 24) | sighash
 267  	t.SigIdx[bucket] = append(t.SigIdx[bucket], recIdx)
 268  }
 269  
 270  // KindToBranch maps a node kind to the branch it is stored in.
 271  func KindToBranch(kind lattice.NodeKind) lattice.Branch {
 272  	switch {
 273  	case kind.Has(lattice.KindFunc | lattice.KindMethod):
 274  		return lattice.Bverb
 275  	case kind.Has(lattice.KindType | lattice.KindPkg | lattice.KindImport | lattice.KindConst | lattice.KindVar):
 276  		return lattice.Bnoun
 277  	default:
 278  		return lattice.Bmodifier
 279  	}
 280  }
 281  
 282  // OtherBranches returns the two branches that are not b.
 283  func OtherBranches(b lattice.Branch) [2]lattice.Branch {
 284  	switch b {
 285  	case lattice.Bnoun:
 286  		return [2]lattice.Branch{lattice.Bverb, lattice.Bmodifier}
 287  	case lattice.Bverb:
 288  		return [2]lattice.Branch{lattice.Bnoun, lattice.Bmodifier}
 289  	default:
 290  		return [2]lattice.Branch{lattice.Bnoun, lattice.Bverb}
 291  	}
 292  }
 293