/// An FM-index over a text (Ferragina & Manzini, 2000): a full-text /// substring index that answers [`count`] and [`locate`] in time /// proportional to the pattern, not the text, and [`extract`]s any slice of /// the text. [`build_corpus`] indexes a list of documents as one text and /// maps occurrences back to `(document, offset)`. /// /// import search/fm /// /// let idx = fm.build "banana" /// fm.count idx "ana" // 2 /// fm.locate idx "ana" // [1, 3] /// fm.extract idx 1 3 // "ana" /// /// The pieces: a suffix array of the text plus a sentinel (built by prefix /// doubling, O(n log² n)), its Burrows–Wheeler transform, a table of the /// characters smaller than each, and occurrence checkpoints every 64 rows /// of the transform, which backward search walks. Characters are mapped to /// small integer codes first, so rows compare as `Int`s. /// /// An empty pattern has no matches (`count` is 0, `locate` is `[]`). /// /// Building is O(n log² n) time and O(n) space: right for a per-user corpus /// (notes, messages), not for a document store. In the interpreter keep the /// text small; native builds are the fast ones. import std/array.{type Array} import std/dict.{type Dict} import std/list import std/string /// An FM-index over one text. pub opaque type Index { Index( text: String // The suffix array of `text` with a sentinel appended (code 0, smaller // than every character's code): the `n + 1` suffix start positions, // sorted by the suffix. , sa: Array< Int > // `bwt[i]` is the code of the character before `sa[i]`, cyclically. , bwt: Array< Int > // `c_table[c]`: the rows before code `c` — the count of characters // smaller than it. , c_table: Array< Int > // `occ[c][j]`: the count of code `c` in the first `j * checkpoint()` // rows of `bwt`. , occ: Array< Array > // Each character of the text and its code (1 and up; 0 is the // sentinel). , alphabet: Dict ) } /// An FM-index over a list of documents: their texts joined with the /// U+0000 separator, and each document's start, so [`corpus_locate`] can /// answer `(document, offset)` pairs. Documents and patterns may not /// contain U+0000. pub opaque type Corpus { Corpus(index: Index, offsets: Array) } /// The occurrence checkpoint period, in `bwt` rows. fn checkpoint :: -> Int { 64 } /// The document separator of a `Corpus`; never in a document or a pattern. fn separator :: -> String { "\u{0}" } /// The element at `i` of `a`, which the caller keeps in range. fn at :: a: Array i: Int -> a { match array.get a i { Some(x) -> x, None -> panic "search/fm: index {i} out of range" } } /// `n` zeros. fn zeros :: n: Int -> Array { array.from_list (list.map (list.range 1 n) fn _ { 0 }) } // ---- building ------------------------------------------------------------- /// The index of `text`. pub fn build :: text: String -> Index { let chars = string.chars text let alphabet = make_alphabet chars let k = dict.size alphabet let codes = list.map chars fn c { code_of alphabet c } let ext = array.from_list (list.append codes [0]) let m = string.length text + 1 let sa = suffix_array ext let bwt = array.map sa fn s { at ext ((s + m - 1) % m) } Index( text: text , sa: sa , bwt: bwt , c_table: c_table_of ext k , occ: occ_of bwt k , alphabet: alphabet ) } /// The distinct characters of `chars`, in order, with codes from 1. fn make_alphabet :: chars: List -> Dict { let (_, d) = list.fold (dedupe (list.sort chars)) (1, dict.empty ()) fn acc c { let (next, d) = acc (next + 1, dict.insert d c next) } d } /// `xs` without duplicates (`xs` is sorted). fn dedupe :: xs: List -> List { match xs { [x, y, ..rest] -> if x == y { dedupe [y, ..rest] } else { [x, ..dedupe [y, ..rest]] } , _ -> xs } } /// The code of character `c`, which is in the alphabet. fn code_of :: alphabet: Dict c: String -> Int { match dict.get alphabet c { Some(code) -> code , None -> panic "search/fm: character not in the alphabet" } } /// The suffix array of `codes` by prefix doubling: sort by the first /// character, then repeatedly by twice as many characters (the rank of the /// first half and of the second), until every suffix has its own rank. fn suffix_array :: codes: Array -> Array { let m = array.length codes let sa = list.map (list.sort (list.map (list.range 0 (m - 1)) fn i { (at codes i, i) })) fn p { p.1 } // The codes themselves are the first ranks, in the right order. double codes sa codes 1 (max_rank codes 0) } fn max_rank :: codes: Array acc: Int -> Int { array.fold codes acc fn hi c { if c > hi { c } else { hi } } } fn double :: codes: Array sa: List ranks: Array k: Int max_rank: Int -> Array { let m = array.length codes if max_rank == m - 1 { array.from_list sa } else { let keyed = list.map sa fn i { (at ranks i, rank_at ranks (i + k), i) } let sorted = list.sort keyed let (ranks2, max2) = rerank sorted (zeros m) (-1) (-1, -1) double codes (list.map sorted fn t { t.2 }) ranks2 (k * 2) max2 } } /// The rank of the suffix at `i`; `-1` past the end (it sorts first). fn rank_at :: ranks: Array i: Int -> Int { match array.get ranks i { Some(r) -> r, None -> -1 } } /// Fresh ranks for the sorted `(first, second, index)` triples: equal keys /// share a rank. Answers the ranks and the highest one. fn rerank :: sorted: List<(Int, Int, Int)> ranks: Array r: Int prev: (Int, Int) -> (Array, Int) { match sorted { [] -> (ranks, r) , [(a, b, i), ..rest] -> { let r2 = if (a, b) == prev { r } else { r + 1 } rerank rest (array.set ranks i r2) r2 (a, b) } } } /// `c_table[c]`: the count of codes smaller than `c` in `codes`. fn c_table_of :: codes: Array k: Int -> Array { let counts = array.fold codes (zeros (k + 1)) fn acc c { array.set acc c (at acc c + 1) } prefix counts 0 (array.with_capacity (k + 1)) 0 } /// `acc` with the running sum of `counts` from `i` on, as prefix sums. fn prefix :: counts: Array i: Int acc: Array sum: Int -> Array { if i >= array.length counts { acc } else { prefix counts (i + 1) (array.push acc sum) (sum + at counts i) } } /// The occurrence checkpoints of `bwt`: `occ[c][j]` counts code `c` in the /// first `j * checkpoint()` rows. fn occ_of :: bwt: Array k: Int -> Array> { walk bwt 0 (zeros (k + 1)) (empty_rows (k + 1)) } fn empty_rows :: n: Int -> Array> { array.from_list (list.map (list.range 1 n) fn _ { array.empty () }) } fn walk :: bwt: Array i: Int counts: Array occ: Array> -> Array> { let m = array.length bwt if i > m { occ } else { let occ = if i % checkpoint () == 0 { snapshot occ counts 0 } else { occ } if i == m { occ } else { let c = at bwt i walk bwt (i + 1) (array.set counts c (at counts c + 1)) occ } } } /// `occ` with the running `counts` appended to every code's checkpoints. fn snapshot :: occ: Array> counts: Array c: Int -> Array> { if c >= array.length occ { occ } else { snapshot (array.set occ c (array.push (at occ c) (at counts c))) counts (c + 1) } } // ---- querying --------------------------------------------------------------- /// The occurrences of `pattern`'s characters as codes, or `None` when one /// is not in the text at all. fn codes_of :: idx: Index pattern: String -> Option> { codes_acc idx.alphabet (string.chars pattern) [] } fn codes_acc :: alphabet: Dict chars: List acc: List -> Option> { match chars { [] -> Some(list.reverse acc) , [c, ..rest] -> match dict.get alphabet c { Some(code) -> codes_acc alphabet rest [code, ..acc], None -> None } } } /// The count of code `c` in the first `i` rows of `bwt`. fn occ_at :: idx: Index c: Int i: Int -> Int { let base = at (at idx.occ c) (i / checkpoint ()) scan idx.bwt c ((i / checkpoint ()) * checkpoint ()) i base } fn scan :: bwt: Array c: Int j: Int i: Int acc: Int -> Int { if j >= i { acc } else { scan bwt c (j + 1) i (if at bwt j == c { acc + 1 } else { acc }) } } /// The suffix-array rows `[sp, ep)` whose suffix starts with `codes` /// (matched from the last back), or `(0, 0)` for none. fn row_range :: idx: Index codes: List sp: Int ep: Int -> (Int, Int) { match codes { [] -> (sp, ep) , [c, ..rest] -> { let first_row = at idx.c_table c let sp = first_row + occ_at idx c sp let ep = first_row + occ_at idx c ep if sp >= ep { (0, 0) } else { row_range idx rest sp ep } } } } /// The rows of `pattern` in `idx`: `(0, 0)` for none. An empty pattern /// has none. fn rows_of :: idx: Index pattern: String -> (Int, Int) { if pattern == "" { (0, 0) } else { match codes_of idx pattern { None -> (0, 0) , Some(codes) -> row_range idx (list.reverse codes) 0 (array.length idx.bwt) } } } /// The number of occurrences of `pattern` in the text, overlapping ones /// included: `count (build "banana") "ana"` is 2. pub fn count :: idx: Index pattern: String -> Int { let (sp, ep) = rows_of idx pattern ep - sp } /// Whether `pattern` occurs in the text. pub fn contains :: idx: Index pattern: String -> Bool { count idx pattern > 0 } /// The positions where `pattern` occurs in the text, ascending. pub fn locate :: idx: Index pattern: String -> List { let (sp, ep) = rows_of idx pattern list.sort (list.map (list.range sp (ep - 1)) fn i { at idx.sa i }) } /// The characters of the text from `at` up to `at + length`. pub fn extract :: idx: Index at: Int length: Int -> String { string.slice idx.text at (at + length) } /// The number of characters of the indexed text. pub fn length :: idx: Index -> Int { string.length idx.text } // ---- corpora ----------------------------------------------------------------- /// The index of `docs` as one corpus. Panics when a document contains the /// U+0000 separator. pub fn build_corpus :: docs: List -> Corpus { check_docs docs Corpus( index: build (string.join docs (separator ())) , offsets: offsets_of docs ) } fn check_docs :: docs: List -> () { match docs { [] -> () , [doc, ..rest] -> if string.contains doc (separator ()) { panic "search/fm.build_corpus: a document contains U+0000, the document separator" } else { check_docs rest } } } /// Each document's start in the joined text. fn offsets_of :: docs: List -> Array { let (_, offsets) = list.fold docs (0, []) fn acc doc { let (pos, offsets) = acc (pos + string.length doc + 1, [pos, ..offsets]) } array.from_list (list.reverse offsets) } /// The number of occurrences of `pattern` over the whole corpus. A pattern /// containing U+0000 has none. pub fn corpus_count :: c: Corpus pattern: String -> Int { if string.contains pattern (separator ()) { 0 } else { count c.index pattern } } /// The `(document, offset)` pairs where `pattern` occurs, ascending by /// document, then offset. A pattern containing U+0000 has none. pub fn corpus_locate :: c: Corpus pattern: String -> List<(Int, Int)> { if string.contains pattern (separator ()) { [] } else { use pos <- list.map (locate c.index pattern) let doc = doc_of c.offsets pos (doc, pos - at c.offsets doc) } } /// The document containing position `pos`: the last offset not past it /// (`offsets[0]` is 0, so a real occurrence always has one). fn doc_of :: offsets: Array pos: Int -> Int { bisect offsets 0 (array.length offsets) pos } /// The last index in `[lo, hi)` whose offset is at most `pos`; `lo - 1` /// when there is none. fn bisect :: offsets: Array lo: Int hi: Int pos: Int -> Int { if lo >= hi { lo - 1 } else { let mid = (lo + hi) / 2 if at offsets mid <= pos { bisect offsets (mid + 1) hi pos } else { bisect offsets lo mid pos } } }