index: add grep-index crate
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This just contains some prototype code that I wrote years ago at present. But it sets a base on which to build. It also establishes a semver boundary between ripgrep's core indexing and a library-version of that indexing.
authored by Andrew Gallant · committed by Andrew Gallant · parent d958105 · Browse files · 8 files·+1196 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+1196 added−0 removed
- other:+1196 added−0 removed
Provenance
- Commit
be739c7- Tree
ddf83de- Author
Andrew Gallant <jamslam@gmail.com>- Committer
Andrew Gallant <jamslam@gmail.com>- Parent
d958105
8 files changed+1196 added−0 removed
added:crates/index/src/lib.rs+1 added
1+pub mod literal;added:crates/index/src/literal.rs+1000 added
1+// This module is currently a prototype. It was inspired a bit by a similar2+// implementation in codesearch[1]. The main difference is that it isn't fixed3+// to a particular ngram size and isn't quite as smart about reducing memory4+// usage. This was hastily written in order to bootstrap ngram extraction so5+// that other things in this crate could be worked on.6+//7+// [1] - https://github.com/google/codesearch8+9+use std::cmp;10+use std::mem;11+12+use bstr::{BString, ByteVec};13+use regex_syntax::hir::{self, Hir, HirKind};14+15+#[derive(Clone)]16+pub enum GramQuery {17+ Literal(BString),18+ And(Vec<GramQuery>),19+ Or(Vec<GramQuery>),20+}21+22+impl GramQuery {23+ fn nothing() -> GramQuery {24+ GramQuery::Or(vec![])25+ }26+27+ fn anything() -> GramQuery {28+ GramQuery::And(vec![])29+ }30+31+ fn is_nothing(&self) -> bool {32+ match *self {33+ GramQuery::Or(ref qs) => qs.is_empty(),34+ _ => false,35+ }36+ }37+38+ fn is_anything(&self) -> bool {39+ match *self {40+ GramQuery::And(ref qs) => qs.is_empty(),41+ _ => false,42+ }43+ }44+45+ fn is_literal(&self) -> bool {46+ matches!(*self, GramQuery::Literal(..))47+ }48+49+ fn is_and(&self) -> bool {50+ matches!(*self, GramQuery::And(..))51+ }52+53+ fn is_or(&self) -> bool {54+ matches!(*self, GramQuery::Or(..))55+ }56+57+ fn unwrap(self) -> GramQuery {58+ match self {59+ q @ GramQuery::Literal(_) => q,60+ GramQuery::And(qs) => GramQuery::and(qs),61+ GramQuery::Or(qs) => GramQuery::or(qs),62+ }63+ }64+65+ fn unwrap_literal(self) -> BString {66+ match self {67+ GramQuery::Literal(lit) => lit,68+ GramQuery::And(_) => panic!("expected literal, but got And"),69+ GramQuery::Or(_) => panic!("expected literal, but got Or"),70+ }71+ }72+73+ fn or(mut queries: Vec<GramQuery>) -> GramQuery {74+ queries.retain(|q| !q.is_nothing());75+76+ if queries.iter().any(GramQuery::is_anything) {77+ GramQuery::anything()78+ } else if queries.len() == 1 {79+ queries.pop().unwrap()80+ } else if queries.iter().all(GramQuery::is_literal) {81+ let set = LiteralSet::from_vec(82+ queries.into_iter().map(GramQuery::unwrap_literal).collect(),83+ );84+ GramQuery::from_set_or(set)85+ } else if queries.iter().any(GramQuery::is_or) {86+ let mut flat = vec![];87+ for q in queries {88+ match q {89+ GramQuery::Or(qs) => {90+ flat.extend(qs);91+ }92+ q => flat.push(q),93+ }94+ }95+ GramQuery::or(flat)96+ } else {97+ GramQuery::Or(queries)98+ }99+ }100+101+ fn and(mut queries: Vec<GramQuery>) -> GramQuery {102+ queries.retain(|q| !q.is_anything());103+104+ if queries.iter().any(GramQuery::is_nothing) {105+ GramQuery::nothing()106+ } else if queries.len() == 1 {107+ queries.pop().unwrap()108+ } else if queries.iter().all(GramQuery::is_literal) {109+ let set = LiteralSet::from_vec(110+ queries.into_iter().map(GramQuery::unwrap_literal).collect(),111+ );112+ GramQuery::from_set_and(set)113+ } else if queries.iter().any(GramQuery::is_and) {114+ let mut flat = vec![];115+ for q in queries {116+ match q {117+ GramQuery::And(qs) => {118+ flat.extend(qs);119+ }120+ q => flat.push(q),121+ }122+ }123+ GramQuery::and(flat)124+ } else {125+ GramQuery::And(queries)126+ }127+ }128+129+ fn from_set_or(mut set: LiteralSet) -> GramQuery {130+ if set.is_empty() {131+ GramQuery::anything()132+ } else if set.len() == 1 {133+ GramQuery::Literal(set.lits.pop().unwrap())134+ } else {135+ let lits: Vec<_> =136+ set.lits.into_iter().map(GramQuery::Literal).collect();137+ GramQuery::Or(lits)138+ }139+ }140+141+ fn from_set_and(mut set: LiteralSet) -> GramQuery {142+ if set.is_empty() {143+ GramQuery::anything()144+ } else if set.len() == 1 {145+ GramQuery::Literal(set.lits.pop().unwrap())146+ } else {147+ let lits: Vec<_> =148+ set.lits.into_iter().map(GramQuery::Literal).collect();149+ GramQuery::And(lits)150+ }151+ }152+153+ fn union(&mut self, q2: GramQuery) {154+ use self::GramQuery::*;155+156+ let (or, and) = (GramQuery::or, GramQuery::and);157+ let q1 = mem::replace(self, GramQuery::nothing());158+ match (q1, q2) {159+ (Literal(lit1), Literal(lit2)) => {160+ // let set = LiteralSet::from_vec(vec![lit1, lit2]);161+ // *self = GramQuery::from_set_or(set);162+ *self = or(vec![Literal(lit1), Literal(lit2)]);163+ }164+ (Literal(lit1), And(qs2)) => {165+ *self = or(vec![Literal(lit1), and(qs2)]);166+ }167+ (Literal(lit1), Or(mut qs2)) => {168+ qs2.push(Literal(lit1));169+ *self = or(qs2);170+ }171+ (And(qs1), And(qs2)) => {172+ if qs1.iter().all(GramQuery::is_literal)173+ && qs2.iter().all(GramQuery::is_literal)174+ {175+ let (common, not1, not2) = factor(qs1, qs2);176+ let mut disjuncts = vec![];177+ if !not1.is_empty() {178+ disjuncts.push(GramQuery::from_set_and(not1));179+ }180+ if !not2.is_empty() {181+ disjuncts.push(GramQuery::from_set_and(not2));182+ }183+ let mut conjuncts = vec![];184+ if !common.is_empty() {185+ conjuncts.push(GramQuery::from_set_and(common));186+ }187+ if !disjuncts.is_empty() {188+ conjuncts.push(or(disjuncts));189+ }190+ *self = and(conjuncts);191+ } else {192+ *self = or(vec![and(qs1), and(qs2)]);193+ }194+ }195+ (And(qs1), q2) => {196+ *self = or(vec![and(qs1), q2]);197+ }198+ (Or(mut qs1), q2) => {199+ qs1.push(q2);200+ *self = or(qs1);201+ }202+ }203+ }204+205+ fn intersect(&mut self, q2: GramQuery) {206+ use self::GramQuery::*;207+208+ let (or, and) = (GramQuery::or, GramQuery::and);209+ let q1 = mem::replace(self, GramQuery::nothing()).unwrap();210+ let q2 = q2.unwrap();211+ match (q1, q2) {212+ (Literal(lit1), Literal(lit2)) => {213+ *self = and(vec![Literal(lit1), Literal(lit2)]);214+ }215+ (Literal(lit1), And(mut qs2)) => {216+ qs2.push(Literal(lit1));217+ *self = and(qs2);218+ }219+ (Literal(lit1), Or(qs2)) => {220+ *self = and(vec![Literal(lit1), or(qs2)]);221+ }222+ (And(mut qs1), q2) => {223+ qs1.push(q2);224+ *self = and(qs1);225+ }226+ (Or(qs1), Or(qs2)) => {227+ if qs1.iter().all(GramQuery::is_literal)228+ && qs2.iter().all(GramQuery::is_literal)229+ {230+ let (common, not1, not2) = factor(qs1, qs2);231+ let mut conjuncts = vec![];232+ if !not1.is_empty() {233+ conjuncts.push(GramQuery::from_set_or(not1));234+ }235+ if !not2.is_empty() {236+ conjuncts.push(GramQuery::from_set_or(not2));237+ }238+ let mut disjuncts = vec![];239+ if !common.is_empty() {240+ disjuncts.push(GramQuery::from_set_or(common));241+ }242+ if !conjuncts.is_empty() {243+ disjuncts.push(and(conjuncts));244+ }245+ *self = or(disjuncts);246+ } else {247+ *self = and(vec![or(qs1), or(qs2)]);248+ }249+ }250+ (Or(qs1), q2) => {251+ *self = and(vec![or(qs1), q2]);252+ }253+ }254+ }255+256+ fn and_ngrams(&mut self, size: usize, set: &LiteralSet) {257+ if set.min_len() < size {258+ return;259+ }260+ let mut qor = GramQuery::nothing();261+ for lit in &set.lits {262+ if lit.len() < size {263+ continue;264+ }265+266+ let mut set = LiteralSet::new();267+ set.extend(ngrams(size, lit).map(BString::from));268+ qor.union(GramQuery::from_set_and(set));269+ }270+ self.intersect(qor);271+ }272+}273+274+impl std::fmt::Debug for GramQuery {275+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {276+ if f.alternate() {277+ return match *self {278+ GramQuery::Literal(ref lit) => {279+ f.debug_tuple("Literal").field(lit).finish()280+ }281+ GramQuery::And(ref qs) => {282+ f.debug_tuple("And").field(qs).finish()283+ }284+ GramQuery::Or(ref qs) => {285+ f.debug_tuple("Or").field(qs).finish()286+ }287+ };288+ }289+290+ match *self {291+ GramQuery::Literal(ref lit) => {292+ let x = format!("{:?}", lit);293+ write!(f, "'{}'", &x[1..x.len() - 1])294+ }295+ GramQuery::And(ref qs) => {296+ let it = qs.iter().map(|q| {297+ if q.is_literal() {298+ format!("{:?}", q)299+ } else {300+ format!("({:?})", q)301+ }302+ });303+ write!(f, "{}", it.collect::<Vec<String>>().join(" & "))304+ }305+ GramQuery::Or(ref qs) => {306+ let it = qs.iter().map(|q| {307+ if q.is_literal() {308+ format!("{:?}", q)309+ } else {310+ format!("({:?})", q)311+ }312+ });313+ write!(f, "{}", it.collect::<Vec<String>>().join(" | "))314+ }315+ }316+ }317+}318+319+#[derive(Clone, Debug)]320+pub struct Analysis {321+ size: usize,322+ query: GramQuery,323+ exact: LiteralSet,324+ prefix: LiteralSet,325+ suffix: LiteralSet,326+}327+328+impl Analysis {329+ fn exact(size: usize, set: LiteralSet) -> Analysis {330+ Analysis {331+ size,332+ query: GramQuery::anything(),333+ exact: set,334+ prefix: LiteralSet::new(),335+ suffix: LiteralSet::new(),336+ }337+ }338+339+ fn anything(size: usize) -> Analysis {340+ Analysis {341+ size,342+ query: GramQuery::anything(),343+ exact: LiteralSet::new(),344+ prefix: LiteralSet::new(),345+ suffix: LiteralSet::new(),346+ }347+ }348+349+ fn exact_one(size: usize, string: BString) -> Analysis {350+ Analysis {351+ size,352+ query: GramQuery::anything(),353+ exact: LiteralSet::single(string),354+ prefix: LiteralSet::new(),355+ suffix: LiteralSet::new(),356+ }357+ }358+359+ fn empty_string(size: usize) -> Analysis {360+ Analysis::exact(size, LiteralSet::single(BString::from("")))361+ }362+363+ fn max_len(&self) -> usize {364+ cmp::max(365+ self.exact.len(),366+ cmp::max(self.prefix.len(), self.suffix.len()),367+ )368+ }369+370+ fn is_exact(&self) -> bool {371+ !self.exact.is_empty()372+ }373+374+ fn make_inexact(&mut self) {375+ if !self.is_exact() {376+ return;377+ }378+ self.prefix = mem::replace(&mut self.exact, LiteralSet::new());379+ self.suffix = self.prefix.clone();380+ }381+382+ fn save_exact(&mut self) {383+ self.query.and_ngrams(self.size, &self.exact);384+ }385+386+ fn union(&mut self, mut o: Analysis) {387+ if self.is_exact() && o.is_exact() {388+ self.exact.union(o.exact);389+ } else if self.is_exact() {390+ self.save_exact();391+ self.make_inexact();392+ self.prefix.union(o.prefix);393+ self.suffix.union(o.suffix);394+ } else if o.is_exact() {395+ o.save_exact();396+ self.prefix.union(o.exact.clone());397+ self.suffix.union(o.exact);398+ } else {399+ self.prefix.union(o.prefix);400+ self.suffix.union(o.suffix);401+ }402+ self.query.union(o.query);403+ self.simplify();404+ }405+406+ fn concat(&mut self, mut o: Analysis) {407+ let inex_cross = if self.is_exact() && o.is_exact() {408+ self.exact.cross(o.exact);409+ None410+ } else {411+ let self_exact = self.is_exact();412+ let o_exact = o.is_exact();413+ self.make_inexact();414+ o.make_inexact();415+416+ let inex_cross = if !self_exact && !o_exact {417+ let mut cross = self.suffix.clone();418+ cross.cross(o.prefix.clone());419+ Some(cross)420+ } else {421+ None422+ };423+424+ if self_exact {425+ self.prefix.cross(o.prefix);426+ } else if self.prefix.has_empty() {427+ self.prefix.union(o.prefix);428+ }429+ if o_exact {430+ self.suffix.cross(o.suffix);431+ } else if self.suffix.has_empty() {432+ self.suffix.union(o.suffix);433+ } else {434+ self.suffix = o.suffix;435+ }436+ inex_cross437+ };438+ self.query.intersect(o.query);439+ if let Some(cross) = inex_cross {440+ self.query.and_ngrams(self.size, &cross);441+ }442+ self.simplify();443+ }444+445+ fn simplify(&mut self) {446+ if self.is_exact() && self.exact.min_len() >= (self.size + 1) {447+ self.save_exact();448+ for lit in &self.exact.lits {449+ if lit.len() < self.size {450+ self.prefix.lits.push(lit.clone());451+ self.suffix.lits.push(lit.clone());452+ } else {453+ self.prefix.lits.push(lit[..self.size - 1].into());454+ self.suffix455+ .lits456+ .push(lit[lit.len() - (self.size - 1)..].into());457+ }458+ }459+ self.exact.clear();460+ self.prefix.canonicalize();461+ self.suffix.canonicalize();462+ }463+ if !self.is_exact() {464+ self.simplify_prefix();465+ self.simplify_suffix();466+ }467+ }468+469+ fn finalize(&mut self) {470+ if self.is_exact() && self.exact.min_len() >= self.size {471+ self.save_exact();472+ for lit in &self.exact.lits {473+ if lit.len() < self.size {474+ self.prefix.lits.push(lit.clone());475+ self.suffix.lits.push(lit.clone());476+ } else {477+ self.prefix.lits.push(lit[..self.size - 1].into());478+ self.suffix479+ .lits480+ .push(lit[lit.len() - (self.size - 1)..].into());481+ }482+ }483+ self.exact.clear();484+ self.prefix.canonicalize();485+ self.suffix.canonicalize();486+ }487+ if !self.is_exact() {488+ self.simplify_prefix();489+ self.simplify_suffix();490+ }491+ }492+493+ fn simplify_prefix(&mut self) {494+ self.query.and_ngrams(self.size, &self.prefix);495+ self.prefix.retain_prefix(self.size - 1);496+ }497+498+ fn simplify_suffix(&mut self) {499+ self.query.and_ngrams(self.size, &self.suffix);500+ self.suffix.retain_suffix(self.size - 1);501+ }502+}503+504+#[derive(Clone, Debug)]505+struct LiteralSet {506+ lits: Vec<BString>,507+}508+509+impl LiteralSet {510+ fn new() -> LiteralSet {511+ LiteralSet { lits: vec![] }512+ }513+514+ fn single(lit: BString) -> LiteralSet {515+ LiteralSet { lits: vec![lit] }516+ }517+518+ fn from_vec(lits: Vec<BString>) -> LiteralSet {519+ let mut set = LiteralSet { lits };520+ set.canonicalize();521+ set522+ }523+524+ fn clear(&mut self) {525+ self.lits.clear();526+ }527+528+ fn retain_prefix(&mut self, max: usize) {529+ for lit in &mut self.lits {530+ lit.truncate(max);531+ }532+ self.canonicalize();533+ }534+535+ fn retain_suffix(&mut self, max: usize) {536+ for lit in &mut self.lits {537+ if lit.len() <= max {538+ continue;539+ }540+ let start = lit.len() - max;541+ lit.drain(..start);542+ }543+ self.canonicalize();544+ }545+546+ fn extend<I: IntoIterator<Item = BString>>(&mut self, it: I) {547+ self.lits.extend(it);548+ self.canonicalize();549+ }550+551+ fn canonicalize(&mut self) {552+ self.lits.sort();553+ self.lits.dedup();554+ }555+556+ fn factor(self, o: LiteralSet) -> (LiteralSet, LiteralSet, LiteralSet) {557+ // TODO: Do this without cloning every literal.558+559+ let (set1, set2) = (self.lits, o.lits);560+ let (mut common, mut not1, mut not2) = (vec![], vec![], vec![]);561+562+ let (mut i1, mut i2) = (0, 0);563+ while i1 < set1.len() && i2 < set2.len() {564+ if set1[i1] < set2[i2] {565+ not1.push(set1[i1].clone());566+ i1 += 1;567+ } else if set2[i2] < set1[i1] {568+ not2.push(set2[i2].clone());569+ i2 += 1;570+ } else {571+ common.push(set1[i1].clone());572+ i1 += 1;573+ i2 += 1;574+ }575+ }576+ while i1 < set1.len() {577+ not1.push(set1[i1].clone());578+ i1 += 1;579+ }580+ while i2 < set2.len() {581+ not2.push(set2[i2].clone());582+ i2 += 1;583+ }584+ (585+ LiteralSet::from_vec(common),586+ LiteralSet::from_vec(not1),587+ LiteralSet::from_vec(not2),588+ )589+ }590+591+ fn union(&mut self, o: LiteralSet) {592+ self.lits.extend(o.lits);593+ self.canonicalize();594+ }595+596+ fn cross(&mut self, o: LiteralSet) {597+ if o.is_empty() || o.has_only_empty() {598+ return;599+ }600+ if self.is_empty() || self.has_only_empty() {601+ *self = o;602+ return;603+ }604+605+ let orig = mem::take(&mut self.lits);606+ for selflit in &orig {607+ for olit in &o.lits {608+ let mut newlit = selflit.clone();609+ newlit.push_str(olit);610+ self.lits.push(newlit);611+ }612+ }613+ }614+615+ fn is_empty(&self) -> bool {616+ self.lits.is_empty()617+ }618+619+ fn len(&self) -> usize {620+ self.lits.len()621+ }622+623+ fn min_len(&self) -> usize {624+ self.lits.iter().map(|x| x.len()).min().unwrap_or(0)625+ }626+627+ fn has_empty(&self) -> bool {628+ self.lits.first().is_some_and(|x| x.is_empty())629+ }630+631+ fn has_only_empty(&self) -> bool {632+ self.len() == 1 && self.has_empty()633+ }634+}635+636+#[derive(Clone, Debug)]637+pub struct GramQueryBuilder {638+ ngram_size: usize,639+ limit_len: usize,640+ limit_class: usize,641+}642+643+impl GramQueryBuilder {644+ pub fn new() -> GramQueryBuilder {645+ GramQueryBuilder { ngram_size: 3, limit_len: 250, limit_class: 10 }646+ }647+648+ pub fn ngram_size(&mut self, size: usize) -> &mut GramQueryBuilder {649+ // A size smaller than this doesn't make a ton of sense, particularly650+ // given that it is currently measured in bytes, not codepoints (or651+ // graphemes).652+ assert!(size >= 2);653+ self.ngram_size = size;654+ self655+ }656+657+ pub fn limit_len(&mut self, len: usize) -> &mut GramQueryBuilder {658+ self.limit_len = len;659+ self660+ }661+662+ pub fn limit_class(&mut self, len: usize) -> &mut GramQueryBuilder {663+ self.limit_class = len;664+ self665+ }666+667+ pub fn build(&self, exp: &Hir) -> GramQuery {668+ self.build_analysis(exp).query669+ }670+671+ fn build_analysis(&self, exp: &Hir) -> Analysis {672+ let mut ana = self.b(exp);673+ ana.finalize();674+ ana675+ }676+677+ fn b(&self, exp: &Hir) -> Analysis {678+ match *exp.kind() {679+ HirKind::Empty | HirKind::Look(_) => {680+ Analysis::empty_string(self.ngram_size)681+ }682+ HirKind::Literal(ref literal) => Analysis::exact_one(683+ self.ngram_size,684+ BString::from(literal.0.as_ref()),685+ ),686+ HirKind::Class(hir::Class::Unicode(ref cls)) => {687+ if class_over_limit_unicode(cls, self.limit_class) {688+ return Analysis::anything(self.ngram_size);689+ }690+691+ let mut set = LiteralSet::new();692+ for r in cls.iter() {693+ for cp in (r.start() as u32)..=(r.end() as u32) {694+ let Some(ch) = char::from_u32(cp) else {695+ continue;696+ };697+ set.lits.push(BString::from(ch.to_string()));698+ }699+ }700+ set.canonicalize();701+ Analysis::exact(self.ngram_size, set)702+ }703+ HirKind::Class(hir::Class::Bytes(ref cls)) => {704+ if class_over_limit_bytes(cls, self.limit_class) {705+ return Analysis::anything(self.ngram_size);706+ }707+708+ let mut set = LiteralSet::new();709+ for r in cls.iter() {710+ for b in r.start()..=r.end() {711+ set.lits.push(BString::from(vec![b]));712+ }713+ }714+ set.canonicalize();715+ Analysis::exact(self.ngram_size, set)716+ }717+ HirKind::Capture(ref capture) => self.b(&capture.sub),718+ HirKind::Repetition(ref rep) => {719+ if rep.min == 0 {720+ Analysis::anything(self.ngram_size)721+ } else {722+ let mut ana = self.b(&rep.sub);723+ ana.make_inexact();724+ ana725+ }726+ }727+ HirKind::Alternation(ref exps) => {728+ let mut ana = self.b(&exps[0]);729+ for e in exps.iter().skip(1) {730+ ana.union(self.b(e));731+ }732+ ana733+ }734+ HirKind::Concat(ref exps) => {735+ let exps = combine_literals(exps);736+ let mut ana = Analysis::empty_string(self.ngram_size);737+ for e in exps {738+ let next = self.build_literal_or_hir(e);739+ if ana.max_len() + ana.max_len() > self.limit_len {740+ ana.concat(Analysis::anything(self.ngram_size));741+ } else {742+ ana.concat(next);743+ }744+ }745+ ana746+ }747+ }748+ }749+750+ fn build_literal_or_hir(&self, or: LiteralOrHir) -> Analysis {751+ match or {752+ LiteralOrHir::Literal(string) => {753+ Analysis::exact_one(self.ngram_size, string)754+ }755+ LiteralOrHir::Other(exp) => self.b(exp),756+ }757+ }758+}759+760+impl Default for GramQueryBuilder {761+ fn default() -> GramQueryBuilder {762+ GramQueryBuilder::new()763+ }764+}765+766+fn class_over_limit_unicode(cls: &hir::ClassUnicode, limit: usize) -> bool {767+ let mut count = 0;768+ for r in cls.iter() {769+ if count > limit {770+ return true;771+ }772+ count += (r.end() as u32 - r.start() as u32) as usize;773+ }774+ count > limit775+}776+777+fn class_over_limit_bytes(cls: &hir::ClassBytes, limit: usize) -> bool {778+ let mut count = 0;779+ for r in cls.iter() {780+ if count > limit {781+ return true;782+ }783+ count += (r.end() - r.start()) as usize;784+ }785+ count > limit786+}787+788+#[derive(Debug)]789+enum LiteralOrHir<'a> {790+ Literal(BString),791+ // Guaranteed to never contain a HirKind::Literal.792+ Other(&'a Hir),793+}794+795+fn combine_literals(concat: &[Hir]) -> Vec<LiteralOrHir<'_>> {796+ let mut combined = vec![];797+ let mut lit = BString::from(vec![]);798+ for exp in concat {799+ match *exp.kind() {800+ HirKind::Literal(ref literal) => {801+ lit.extend_from_slice(&literal.0);802+ }803+ _ => {804+ if !lit.is_empty() {805+ combined.push(LiteralOrHir::Literal(lit));806+ lit = BString::from(vec![]);807+ }808+ combined.push(LiteralOrHir::Other(exp));809+ }810+ }811+ }812+ if !lit.is_empty() {813+ combined.push(LiteralOrHir::Literal(lit));814+ }815+ combined816+}817+818+/// Returns all ngrams of the given size in a sliding window fashion over the819+/// given literal. If the literal is smaller than the given size, then the820+/// entire literal is returned as an ngram. (An empty literal always results in821+/// a single empty string returned.)822+fn ngrams<'b, B: 'b + AsRef<[u8]> + ?Sized>(823+ size: usize,824+ lit: &'b B,825+) -> impl Iterator<Item = &'b [u8]> {826+ let lit = lit.as_ref();827+ let size = cmp::min(size, lit.len());828+ let end = lit.len() - size;829+ (0..=end).map(move |i| &lit[i..i + size])830+}831+832+fn factor(833+ qs1: Vec<GramQuery>,834+ qs2: Vec<GramQuery>,835+) -> (LiteralSet, LiteralSet, LiteralSet) {836+ let (mut lits1, mut lits2) = (vec![], vec![]);837+ for q in qs1 {838+ lits1.push(q.unwrap_literal());839+ }840+ for q in qs2 {841+ lits2.push(q.unwrap_literal());842+ }843+844+ let set1 = LiteralSet::from_vec(lits1);845+ let set2 = LiteralSet::from_vec(lits2);846+ set1.factor(set2)847+}848+849+#[cfg(test)]850+mod tests {851+ use super::*;852+ use regex_syntax::ParserBuilder;853+854+ fn parse(pattern: &str) -> Hir {855+ ParserBuilder::new().utf8(false).build().parse(pattern).unwrap()856+ }857+858+ fn gramq(pattern: &str) -> GramQuery {859+ let re = parse(pattern);860+ let mut b = GramQueryBuilder::new();861+ b.ngram_size(3);862+ b.build(&re)863+ }864+865+ fn sgramq(pattern: &str) -> String {866+ format!("{:?}", gramq(pattern))867+ }868+869+ #[test]870+ fn iter_ngrams() {871+ let get = |size, lit| -> Vec<BString> {872+ ngrams(size, lit).map(BString::from).collect()873+ };874+875+ assert_eq!(get(3, "foobar"), vec!["foo", "oob", "oba", "bar"]);876+ assert_eq!(get(3, "fooba"), vec!["foo", "oob", "oba"]);877+ assert_eq!(get(3, "foob"), vec!["foo", "oob"]);878+ assert_eq!(get(3, "foo"), vec!["foo"]);879+ assert_eq!(get(3, "fo"), vec!["fo"]);880+ assert_eq!(get(3, "f"), vec!["f"]);881+ assert_eq!(get(3, ""), vec![""]);882+883+ assert_eq!(get(1, "ab"), vec!["a", "b"]);884+ assert_eq!(get(1, "a"), vec!["a"]);885+ assert_eq!(get(1, ""), vec![""]);886+887+ assert_eq!(get(0, "ab"), vec!["", "", ""]);888+ assert_eq!(get(0, "a"), vec!["", ""]);889+ assert_eq!(get(0, ""), vec![""]);890+ }891+892+ // These tests were taken from codesearch's test suite:893+ // https://github.com/google/codesearch894+ #[test]895+ fn queries() {896+ macro_rules! t {897+ ($regex:expr, $expected:expr) => {898+ assert_eq!(sgramq($regex), $expected);899+ };900+ }901+902+ t!("foo", "'foo'");903+ t!("foob", "'foo' & 'oob'");904+ t!("foobar", "'bar' & 'foo' & 'oba' & 'oob'");905+ t!("(abc)(def)", "'abc' & 'bcd' & 'cde' & 'def'");906+ t!("abc.*def", "'abc' & 'def'");907+ t!("abc.*(def|ghi)", "'abc' & ('def' | 'ghi')");908+ t!(909+ "abc(def|ghi)",910+ "'abc' & (('bcd' & 'cde' & 'def') | ('bcg' & 'cgh' & 'ghi'))"911+ );912+ t!("a+hello", "'ahe' & 'ell' & 'hel' & 'llo'");913+ t!(914+ "(a+hello|b+world)",915+ "('ahe' & 'ell' & 'hel' & 'llo') | ('bwo' & 'orl' & 'rld' & 'wor')"916+ );917+ t!("a*bbb", "'bbb'");918+ t!("a?bbb", "'bbb'");919+ t!("(bbb)a*", "'bbb'");920+ t!("(bbb)a?", "'bbb'");921+ t!("^abc", "'abc'");922+ t!("abc$", "'abc'");923+ t!("ab[cde]f", "('abc' & 'bcf') | ('abd' & 'bdf') | ('abe' & 'bef')");924+ t!("(abc|bac)de", "'cde' & (('abc' & 'bcd') | ('acd' & 'bac'))");925+926+ t!("ab[^cde]f", "");927+ t!("ab.f", "");928+ t!(".", "");929+ t!("(?s).", "");930+ t!("()", "");931+932+ // Tests that we keeps track of multiple possible prefix/suffixes.933+ t!(934+ "[ab][cd][ef]",935+ "'ace' | 'acf' | 'ade' | 'adf' | 'bce' | 'bcf' | 'bde' | 'bdf'"936+ );937+ t!("ab[cd]e", "('abc' & 'bce') | ('abd' & 'bde')");938+939+ // Tests that different sized suffixes works.940+ t!("(a|ab)cde", "'cde' & ('acd' | ('abc' & 'bcd'))");941+ t!("(a|b|c|d)(ef|g|hi|j)", "");942+943+ // Case insensitivity sanity check.944+ t!("(?i)a~~", "'A~~' | 'a~~'");945+ t!("(?i)ab~", "'AB~' | 'Ab~' | 'aB~' | 'ab~'");946+ t!(947+ "(?i)abc",948+ "'ABC' | 'ABc' | 'AbC' | 'Abc' | 'aBC' | 'aBc' | 'abC' | 'abc'"949+ );950+951+ // Word boundaries.952+ t!(r"\b", "");953+ t!(r"\B", "");954+ t!(r"\babc", "'abc'");955+ t!(r"\Babc", "'abc'");956+ t!(r"abc\b", "'abc'");957+ t!(r"abc\B", "'abc'");958+ t!(r"ab\bc", "'abc'");959+ t!(r"ab\Bc", "'abc'");960+961+ // Test that factoring out common ngrams works.962+ t!("abc|abc", "'abc'");963+ t!("(ab|ab)c", "'abc'");964+ t!("ab(cab|cat)", "'abc' & 'bca' & ('cab' | 'cat')");965+ t!("(z*(abc|def)z*)(z*(abc|def)z*)", "'abc' | 'def'");966+ t!("(z*abcz*defz*)|(z*abcz*defz*)", "'abc' & 'def'");967+ t!(968+ "(z*abcz*defz*(ghi|jkl)z*)|(z*abcz*defz*(mno|prs)z*)",969+ // "('abc' & 'def' & ('ghi' | 'jkl' | 'mno' | 'prs'))"970+ "('abc' & 'def' & ('ghi' | 'jkl')) \971+ | ('abc' & 'def' & ('mno' | 'prs'))"972+ );973+ }974+975+ #[test]976+ fn scratch() {977+ // println!("{:#?}", analysis(r"a|b|c"));978+ // println!("{:#?}", analysis(r"[2-6]"));979+ // println!("{:#?}", analysis(r"abcQ+def(QQ)+xyz"));980+ // println!("{:#?}", analysis(r".abc(XYZ)+"));981+ // println!("{:#?}", analysis(r".(a)(yz)"));982+ // println!("{:#?}", analysis(r"abc.def.ghi"));983+ // println!("{:#?}", analysis(r"ZZZ+(foo|bar|baz)(a|b)"));984+ // println!("{:#?}", analysis(r"aND|caN|Ha[DS]|WaS"));985+ // println!("{:#?}", analysis(r"\|[^|][^|]*\|"));986+ // println!("{:#?}", analysis(r"a[act]ggtaaa|tttacc[agt]t"));987+ // println!("{:#?}", analysis(r">[^\n]*\n|\n"));988+ // println!("{:#?}", analysis(r"abcd|(efgh|(mnop|uvwx|yzab)|qrst)|ijkl"));989+ // println!("{:#?}", analysis(r"foo|bar"));990+ // println!("{:#?}", analysis(r"foo"));991+ // println!("{:#?}", analysis(r"abc.*"));992+ // println!("{:#?}", analysis(r"abc.*(def|ghi)"));993+ // println!("{:#?}", analysis(r"abc.*def"));994+ // println!("{:#?}", analysis(r"abcd.*efgh"));995+ // println!("{:#?}", analysis(r"abc(def|ghi)"));996+ // println!("{:#?}", analysis(r"a+hello"));997+ // println!("{:#?}", analysis(r"(a|b|c|d)(ef|g|hi|j)"));998+ // println!("{:#?}", analysis(r"(z*(abc|def)z*)(z*(abc|def))"));999+ }1000+}added:crates/index/Cargo.toml+23 added
1234567891011121314151617181920212223[package]publish = falsename = "grep-index"version = "0.0.1" #:versionauthors = ["Andrew Gallant <jamslam@gmail.com>"]description = """Grep, but with an index."""documentation = "https://docs.rs/grep-index"homepage = "https://github.com/BurntSushi/ripgrep"repository = "https://github.com/BurntSushi/ripgrep"readme = "README.md"keywords = ["regex", "grep", "search", "index", "ngram"]license = "Unlicense/MIT"edition = "2024"rust-version = "1.96"
[dependencies]anyhow = "1.0.103"bstr = "1.12.0"fst = "0.4.7"redb = "4.1.0"regex-syntax = "0.8.8"added:crates/index/LICENSE-MIT+21 added
1+The MIT License (MIT)2+3+Copyright (c) 2015 Andrew Gallant4+5+Permission is hereby granted, free of charge, to any person obtaining a copy6+of this software and associated documentation files (the "Software"), to deal7+in the Software without restriction, including without limitation the rights8+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell9+copies of the Software, and to permit persons to whom the Software is10+furnished to do so, subject to the following conditions:11+12+The above copyright notice and this permission notice shall be included in13+all copies or substantial portions of the Software.14+15+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR16+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,17+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE18+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER19+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,20+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN21+THE SOFTWARE.added:crates/index/README.md+100 added
1+grep-index2+==========3+4+`grep-index` is an experimental persistent byte-trigram index for ripgrep.5+It never claims that a file matches. It returns files that cannot be ruled6+out, and ripgrep still performs the real search over those candidates.7+8+The design keeps the useful pieces of Nakala's PLAN.md while delegating the9+embedded-database work to redb:10+11+- writes publish immutable logical segments;12+- each segment assigns dense, one-based `u32` DocIDs in lexicographic path13+ order;14+- a monotonic `fst::Map` provides both path-to-DocID and DocID-to-path15+ lookups;16+- redb stores contiguous delta-varint posting-list blobs, metadata, the17+ active segment catalog and compact tombstone bitmaps;18+- an upsert atomically tombstones older path versions and publishes a new19+ segment;20+- compaction rewrites live documents into one tombstone-free segment.21+22+Only raw byte trigrams are indexed. Document contents and positions are not23+stored.24+25+## API sketch26+27+```rust28+use grep_index::{FileMetadata, Index, Query};29+30+let index = Index::create("corpus.index.redb")?;31+index.upsert("src/lib.rs", contents, FileMetadata::default())?;32+33+// The normal ripgrep-facing path: no metadata decoding.34+let paths = index.candidate_paths(&Query::literal(b"needle"))?;35+36+// Metadata is available when a caller wants post-index filtering/sorting.37+let candidates = index.search_with(&Query::literal(b"needle"), |meta| {38+ !meta.hidden && meta.size < 10_000_00039+})?;40+```41+42+`IndexWriter` batches many files into one segment. `Index::index_directory`43+walks a tree and commits bounded-size segments. The free `build_index`44+function preserves the prototype's one-shot directory API and publishes its45+initial database with a no-clobber hard link.46+47+Logical compaction is for faster searches. A separate storage-compaction48+method asks redb to reclaim unused pages when the caller can afford a slower49+physical rewrite.50+51+`Index::open_read_only` uses redb 4's read-only handle for multi-process52+candidate readers. Multiple read-only handles can coexist, but redb does not53+allow them to overlap a writable `Database` handle.54+55+## Storage notes56+57+Paths are stored as raw platform path bytes instead of UTF-8 strings. On58+Unix this preserves non-UTF-8 paths; on Windows it stores UTF-16 code units.59+DocIDs are assigned only after paths are sorted, which is the invariant60+required by `fst::raw::Fst::get_key_into` for efficient reverse lookup.61+62+Posting values have a count prefix followed by delta-varint encoded sorted63+`u32` DocIDs. Query conjunctions decode the smallest lists first and use a64+galloping intersection when list sizes are highly skewed. The implementation65+is entirely safe Rust; mmap and custom unsafe codecs are intentionally left66+for benchmark-driven follow-up work.67+68+Files with a UTF-16 byte-order mark contribute trigrams from both their raw69+bytes and ripgrep's default UTF-8 transcoding. This preserves conservative70+candidate selection for both default searches and `--encoding none`; the71+extra terms can only create false positives.72+73+File metadata currently records size, the time at which the file was indexed,74+optional modified/created/accessed timestamps, hidden, read-only, executable75+and symlink flags. Metadata has a versioned binary encoding independent of76+posting lists.77+78+An index can also persist an absolute corpus root for resolving its stored79+paths and a minimal set of absolute traversal scopes for ordinary-search80+fallback. `build_index` sets both automatically; callers constructing an81+`Index` directly can use `Index::set_root` and `Index::add_scopes`.82+83+## Current boundaries84+85+- `index_directory` is append/upsert-oriented. It updates files it sees, but86+ does not infer deletes for files that disappeared from the tree; call87+ `Index::delete` for explicit removals.88+- Directory walking intentionally has only small built-in policies: it can89+ skip binary files, hidden entries and `.git`, but it is not ripgrep's full90+ ignore walker yet.91+- Search currently materializes result vectors. The path-only API avoids92+ metadata work, but a streaming visitor is a likely next step for enormous93+ candidate sets.94+- Logical compaction currently materializes its live remap and postings.95+ A streaming, bounded-memory merge like the full Nakala plan is a future96+ optimization.97+- This crate uses redb 4.1 and Rust 1.97. Earlier experimental index formats98+ are rebuild-only.99+100+Dual-licensed under MIT or the [UNLICENSE](http://unlicense.org).added:crates/index/UNLICENSE+24 added
1+This is free and unencumbered software released into the public domain.2+3+Anyone is free to copy, modify, publish, use, compile, sell, or4+distribute this software, either in source code form or as a compiled5+binary, for any purpose, commercial or non-commercial, and by any6+means.7+8+In jurisdictions that recognize copyright laws, the author or authors9+of this software dedicate any and all copyright interest in the10+software to the public domain. We make this dedication for the benefit11+of the public at large and to the detriment of our heirs and12+successors. We intend this dedication to be an overt act of13+relinquishment in perpetuity of all present and future rights to this14+software under copyright law.15+16+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,17+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF18+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.19+IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR20+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,21+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR22+OTHER DEALINGS IN THE SOFTWARE.23+24+For more information, please refer to <http://unlicense.org/>modified:Cargo.lock+26 added
123 unmodified lines124 source = "registry+https://github.com/rust-lang/crates.io-index"125 checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"126 127 [[package]]128+name = "fst"129+version = "0.4.7"130+source = "registry+https://github.com/rust-lang/crates.io-index"131+checksum = "7ab85b9b05e3978cc9a9cf8fea7f01b494e1a09ed3037e16ba39edc7a29eb61a"132+133+[[package]]134 name = "getrandom"135 version = "0.4.3"136 source = "registry+https://github.com/rust-lang/crates.io-index"137 checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"50 unmodified lines188 "winapi-util",189 ]190 191 [[package]]192+name = "grep-index"193+version = "0.0.1"194+dependencies = [195+ "anyhow",196+ "bstr",197+ "fst",198+ "redb",199+ "regex-syntax",200+]201+202+[[package]]203 name = "grep-matcher"204 version = "0.1.9"205 dependencies = [206 "memchr",166 unmodified lines373 source = "registry+https://github.com/rust-lang/crates.io-index"374 checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"375 376 [[package]]377+name = "redb"378+version = "4.1.0"379+source = "registry+https://github.com/rust-lang/crates.io-index"380+checksum = "8e925444704b5f17d32bf42f5b6e2df050bceebc3dcd6e71cc73dafe8092e839"381+dependencies = [382+ "libc",383+]384+385+[[package]]386 name = "regex"387 version = "1.13.0"388 source = "registry+https://github.com/rust-lang/crates.io-index"389 checksum = "2a0e75113e14dc5acb068cd0786884f214f1312650a3d36d269f5c4f3cdee8a2"191 unmodified linesmodified:Cargo.toml+1 added
39 unmodified lines40414243444546474873 unmodified lines39 unmodified linesmembers = [ "crates/globset", "crates/grep", "crates/cli", "crates/index", "crates/matcher", "crates/pcre2", "crates/printer", "crates/regex",73 unmodified lines