package iskra import ( "fmt" "git.smesh.lol/go-iskra/lattice" ) // Tree is the iskra layer over one lattice tree: the record metadata, byte and // token pools, the dictionary, and the two indices rebuilt on open. // // TokenPool keeps every content token id in memory. The .tokpool file layout is // plain LE uint32 (iskra/storage.mx), so a base path whose .tokpool is // non-empty is read as a warning-free in-memory image and written back to // .tokpool on flush, one uint32 per entry; no content is lost either way. type Tree struct { DB *lattice.Tree RecMeta []lattice.MetaRecord StringPool []byte TokenPool []uint32 Dict *Dict // the dictionary TokenPool ids index TokFile bool // base path has a .tokpool companion BigramIdx map[string][]uint32 SigIdx map[uint32][]uint32 BulkMode bool } // NewTree wraps a lattice tree. func NewTree(db *lattice.Tree) *Tree { return &Tree{ DB: db, Dict: NewDict(), BigramIdx: make(map[string][]uint32), SigIdx: make(map[uint32][]uint32), } } // MetaAt returns the metadata at a record index, growing the slice through // gaps with zero entries as iskra/storage.mx metaSet does. Record indices are // not monotone when iskradb's free list is reused. func (t *Tree) MetaAt(recIdx uint32) *lattice.MetaRecord { for uint32(len(t.RecMeta)) <= recIdx { t.RecMeta = append(t.RecMeta, lattice.MetaRecord{}) } return &t.RecMeta[recIdx] } // Meta returns the metadata at a record index, or nil when absent. func (t *Tree) Meta(recIdx uint32) *lattice.MetaRecord { if uint64(recIdx) < uint64(len(t.RecMeta)) { return &t.RecMeta[recIdx] } return nil } // SetMeta stores a metadata entry at a record index. func (t *Tree) SetMeta(recIdx uint32, m lattice.MetaRecord) { *t.MetaAt(recIdx) = m } // MetaInc bumps the occurrence count of a record. func (t *Tree) MetaInc(recIdx uint32) { if m := t.Meta(recIdx); m != nil { m.Count++ } } // Insert adds a named segment at a branch and stage and returns the record // index. The form goes on the record, the metadata gets kind and stage, and the // content goes to the token pool. func (t *Tree) Insert(branch lattice.Branch, key lattice.Key, form string, kind lattice.NodeKind, stage uint8) (uint32, error) { var rec lattice.Record lattice.SetFormOnRecord(&rec, form, &t.StringPool) rec.Branch = uint8(branch) recIdx, err := t.DB.InsertRec(branch, key, rec) if err != nil { return 0, err } if k := uint64(t.DB.RecordCount()); recIdx >= uint32(k) { return 0, fmt.Errorf("iskra: record index %d reached the count %d", recIdx, k) } t.SetMeta(recIdx, lattice.MetaRecord{Kind: kind, StageTag: stage}) return recIdx, nil } // SetContent tokenises content into the shared dictionary and the token pool // and records the run on the metadata at recIdx. // // A segment that TokenizeToken yields as exactly one token stores its // dictionary id in the entry's Extra[0] as a single byte, which is the on-disk // convention the moxie reader of .meta expects (iskra/meta.mx: "Single-chunk // token: store dictID in Extra[0]"). A longer segment leaves Extra untouched. func (t *Tree) SetContent(recIdx uint32, content []byte) { off := uint32(len(t.TokenPool)) seq := t.Dict.Tokenize(content) t.TokenPool = append(t.TokenPool, seq...) m := t.MetaAt(recIdx) m.SetContentRef(off, uint32(len(seq))) if len(seq) == 1 && seq[0] < 255 { m.Extra[0] = byte(seq[0]) } } // TokenSeq returns the token ids of a record's content. func (t *Tree) TokenSeq(recIdx uint32) []uint32 { m := t.Meta(recIdx) if m == nil { return nil } off, n := m.ContentOffset(), m.ContentLen() end := uint64(off) + uint64(n) if end > uint64(len(t.TokenPool)) { if uint64(off) >= uint64(len(t.TokenPool)) { return nil } return t.TokenPool[off:] } return t.TokenPool[off:end] } // Content renders a record's content from its token ids, two-char chunks // joined by a space, which is how the token pool reads back. func (t *Tree) Content(recIdx uint32) []byte { seq := t.TokenSeq(recIdx) if len(seq) == 0 { return nil } if len(seq) == 1 { return t.Dict.Get(seq[0]) } out := make([]byte, 0, len(seq)*3) for i, idx := range seq { if int(idx) >= len(t.Dict.Entries) { continue } if i > 0 { out = append(out, ' ') } out = append(out, t.Dict.Get(idx)...) } return out } // Form returns the surface form stored on a record. func (t *Tree) Form(recIdx uint32) string { r, err := t.DB.GetRecord(recIdx) if err != nil { return "" } return lattice.FormFromRecord(r, t.StringPool) } // LookupRecIdx returns the record index of a key in a branch, or NullRec. func (t *Tree) LookupRecIdx(branch lattice.Branch, key lattice.Key) (uint32, error) { return t.DB.LookupRecIdx(branch, key) } // LookupName looks a segment up by name at a stage, then by its segment id, // which is what the corpus loader stores. It returns the record index for the // name that matched and the stage it was found at. func (t *Tree) LookupName(stage uint8, name string) (ri uint32, matched uint8, err error) { for _, s := range []uint8{stage} { if s == 0 { continue } if ri, err := t.LookupRecIdxAny(NameKey(s, name)); err != nil { return lattice.NullRec, 0, err } else if ri != lattice.NullRec { return ri, s, nil } } return lattice.NullRec, 0, nil } // LookupRecIdxAny searches every branch for a key. func (t *Tree) LookupRecIdxAny(key lattice.Key) (uint32, error) { for b := 0; b < lattice.C; b++ { ri, err := t.DB.LookupRecIdx(lattice.Branch(b), key) if err != nil { return lattice.NullRec, err } if ri != lattice.NullRec { return ri, nil } } return lattice.NullRec, nil } // StageLinksFor returns the record indices of the same named entity at every // other stage, found by name hash with the stage byte replaced. func (t *Tree) StageLinksFor(branch lattice.Branch, key lattice.Key) []uint32 { var out []uint32 hash := lattice.KeyHash(key) stage := lattice.KeyStage(key) for s := uint8(1); s <= 5; s++ { if s == stage { continue } ri, err := t.DB.LookupRecIdx(branch, lattice.MakeCodeKey(s, hash)) if err == nil && ri != lattice.NullRec { out = append(out, ri) } } return out } // FinalizeLinks wires Record.Link[0] and Link[1] across branches after all // inserts are done. The branch comes from the kind, and the partner key is the // same stage and name hash in the two other branches. func (t *Tree) FinalizeLinks() error { others := [lattice.C][]lattice.Branch{} for b := 0; b < lattice.C; b++ { var o []lattice.Branch for c := 0; c < lattice.C; c++ { if c != b { o = append(o, lattice.Branch(c)) } } others[b] = o } for recIdx := 0; uint32(recIdx) < uint32(len(t.RecMeta)); recIdx++ { m := &t.RecMeta[recIdx] b := KindToBranch(m.Kind) key, ok := t.DB.RecKey[uint32(recIdx)] if !ok { continue } stage := lattice.KeyStage(key) hash := lattice.KeyHash(key) rec, err := t.DB.GetRecord(uint32(recIdx)) if err != nil { return err } for i, other := range others[b] { ri, err := t.DB.LookupRecIdx(other, lattice.MakeCodeKey(stage, hash)) if err != nil { return err } if ri != lattice.NullRec { rec.Link[i] = ri } } } return nil } // RebuildSigIdx rebuilds the signature bucket index from the metadata. func (t *Tree) RebuildSigIdx() { t.SigIdx = make(map[uint32][]uint32) for i := range t.RecMeta { m := &t.RecMeta[i] h := m.SigHash() if h == 0 { continue } bucket := (uint32(m.StageTag) << 24) | h t.SigIdx[bucket] = append(t.SigIdx[bucket], uint32(i)) } } // SigIdxAdd registers one record in the signature index. func (t *Tree) SigIdxAdd(recIdx uint32, stage uint8, sighash uint32) { if sighash == 0 { return } bucket := (uint32(stage) << 24) | sighash t.SigIdx[bucket] = append(t.SigIdx[bucket], recIdx) } // KindToBranch maps a node kind to the branch it is stored in. func KindToBranch(kind lattice.NodeKind) lattice.Branch { switch { case kind.Has(lattice.KindFunc | lattice.KindMethod): return lattice.Bverb case kind.Has(lattice.KindType | lattice.KindPkg | lattice.KindImport | lattice.KindConst | lattice.KindVar): return lattice.Bnoun default: return lattice.Bmodifier } } // OtherBranches returns the two branches that are not b. func OtherBranches(b lattice.Branch) [2]lattice.Branch { switch b { case lattice.Bnoun: return [2]lattice.Branch{lattice.Bverb, lattice.Bmodifier} case lattice.Bverb: return [2]lattice.Branch{lattice.Bnoun, lattice.Bmodifier} default: return [2]lattice.Branch{lattice.Bnoun, lattice.Bverb} } }