regex: remove old inner literal extractor
Before adoption: this commit came in with the history the project adopted, so no landing records it.
(It had already been removed from the crate.)
authored by Andrew Gallant · committed by Andrew Gallant · parent 7b72e98 · Browse files · 1 file·+0 added−466 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+0 added−466 removed
- other:+0 added−466 removed
Provenance
- Commit
3ac4541- Tree
bec78fb- Author
Andrew Gallant <jamslam@gmail.com>- Committer
Andrew Gallant <jamslam@gmail.com>- Parent
7b72e98
1 file changed+0 added−466 removed
deleted:crates/regex/src/literalold.rs-466 removed
1-/*2-This module is responsible for extracting *inner* literals out of the AST of a3-regular expression. Normally this is the job of the regex engine itself, but4-the regex engine doesn't look for inner literals. Since we're doing line based5-searching, we can use them, so we need to do it ourselves.6-*/7-8-use {9- bstr::ByteSlice,10- regex_syntax::hir::{11- self,12- literal::{self, Literal, Seq},13- Hir, HirKind,14- },15-};16-17-use crate::util;18-19-/// Represents prefix, suffix and inner "required" literals for a regular20-/// expression.21-///22-/// Prefixes and suffixes are detected using regex-syntax. The inner required23-/// literals are detected using something custom (but based on the code in24-/// regex-syntax).25-#[derive(Clone, Debug)]26-pub struct LiteralSets {27- /// A set of prefix literals.28- prefixes: Seq,29- /// A set of suffix literals.30- suffixes: Seq,31- /// A set of literals such that at least one of them must appear in every32- /// match. A literal in this set may be neither a prefix nor a suffix.33- required: Seq,34-}35-36-impl LiteralSets {37- /// Create a set of literals from the given HIR expression.38- pub fn new(expr: &Hir) -> LiteralSets {39- let mut required = Seq::singleton(Literal::exact(vec![]));40- union_required(expr, &mut required);41- LiteralSets {42- prefixes: prefixes(expr),43- suffixes: suffixes(expr),44- required,45- }46- }47-48- /// If it is deemed advantageuous to do so (via various suspicious49- /// heuristics), this will return a single regular expression pattern that50- /// matches a subset of the language matched by the regular expression that51- /// generated these literal sets. The idea here is that the pattern52- /// returned by this method is much cheaper to search for. i.e., It is53- /// usually a single literal or an alternation of literals.54- pub fn one_regex(&self, word: bool) -> Option<String> {55- // TODO: The logic in this function is basically inscrutable. It grew56- // organically in the old grep 0.1 crate. Ideally, it would be57- // re-worked. In fact, the entire inner literal extraction should be58- // re-worked. Actually, most of regex-syntax's literal extraction59- // should also be re-worked. Alas... only so much time in the day.60-61- if !word {62- if self.prefixes.is_exact() && !self.prefixes.is_empty() {63- log::debug!("literal prefixes detected: {:?}", self.prefixes);64- // When this is true, the regex engine will do a literal scan,65- // so we don't need to return anything. But we only do this66- // if we aren't doing a word regex, since a word regex adds67- // a `(?:\W|^)` to the beginning of the regex, thereby68- // defeating the regex engine's literal detection.69- return None;70- }71- }72-73- // Out of inner required literals, prefixes and suffixes, which one74- // is the longest? We pick the longest to do fast literal scan under75- // the assumption that a longer literal will have a lower false76- // positive rate.77- let pre_lcp = self.prefixes.longest_common_prefix().unwrap_or(&[]);78- let pre_lcs = self.prefixes.longest_common_suffix().unwrap_or(&[]);79- let suf_lcp = self.suffixes.longest_common_prefix().unwrap_or(&[]);80- let suf_lcs = self.suffixes.longest_common_suffix().unwrap_or(&[]);81-82- let req_lits = self.required.literals().unwrap_or(&[]);83- let req = match req_lits.iter().max_by_key(|lit| lit.len()) {84- None => &[],85- Some(req) => req.as_bytes(),86- };87-88- let mut lit = pre_lcp;89- if pre_lcs.len() > lit.len() {90- lit = pre_lcs;91- }92- if suf_lcp.len() > lit.len() {93- lit = suf_lcp;94- }95- if suf_lcs.len() > lit.len() {96- lit = suf_lcs;97- }98- if req_lits.len() == 1 && req.len() > lit.len() {99- lit = req;100- }101-102- // Special case: if we detected an alternation of inner required103- // literals and its longest literal is bigger than the longest104- // prefix/suffix, then choose the alternation. In practice, this105- // helps with case insensitive matching, which can generate lots of106- // inner required literals.107- let any_empty = req_lits.iter().any(|lit| lit.is_empty());108- let any_white = has_only_whitespace(&req_lits);109- if req.len() > lit.len()110- && req_lits.len() > 1111- && !any_empty112- && !any_white113- {114- log::debug!("required literals found: {:?}", req_lits);115- let alts: Vec<String> = req_lits116- .into_iter()117- .map(|x| util::bytes_to_regex(x.as_bytes()))118- .collect();119- // We're matching raw bytes, so disable Unicode mode.120- Some(format!("(?-u:{})", alts.join("|")))121- } else if lit.is_empty() {122- // If we're here, then we have no LCP. No LCS. And no detected123- // inner required literals. In theory this shouldn't happen, but124- // the inner literal detector isn't as nice as we hope and doesn't125- // actually support returning a set of alternating required126- // literals. (Instead, it only returns a set where EVERY literal127- // in it is required. It cannot currently express "either P or Q128- // is required.")129- //130- // In this case, it is possible that we still have meaningful131- // prefixes or suffixes to use. So we look for the set of literals132- // with the highest minimum length and use that to build our "fast"133- // regex.134- //135- // This manifests in fairly common scenarios. e.g.,136- //137- // rg -w 'foo|bar|baz|quux'138- //139- // Normally, without the `-w`, the regex engine itself would140- // detect the prefix correctly. Unfortunately, the `-w` option141- // turns the regex into something like this:142- //143- // rg '(^|\W)(foo|bar|baz|quux)($|\W)'144- //145- // Which will defeat all prefix and suffix literal optimizations.146- // (Not in theory---it could be better. But the current147- // implementation isn't good enough.) ... So we make up for it148- // here.149- if !word {150- return None;151- }152- let p_min_len = self.prefixes.min_literal_len();153- let s_min_len = self.suffixes.min_literal_len();154- let lits = match (p_min_len, s_min_len) {155- (None, None) => return None,156- (Some(_), None) => {157- log::debug!("prefix literals found");158- self.prefixes.literals().unwrap()159- }160- (None, Some(_)) => {161- log::debug!("suffix literals found");162- self.suffixes.literals().unwrap()163- }164- (Some(p), Some(s)) => {165- if p >= s {166- log::debug!("prefix literals found");167- self.prefixes.literals().unwrap()168- } else {169- log::debug!("suffix literals found");170- self.suffixes.literals().unwrap()171- }172- }173- };174-175- log::debug!("prefix/suffix literals found: {:?}", lits);176- if has_only_whitespace(lits) {177- log::debug!("dropping literals because one was whitespace");178- return None;179- }180- let alts: Vec<String> = lits181- .into_iter()182- .map(|x| util::bytes_to_regex(x.as_bytes()))183- .collect();184- // We're matching raw bytes, so disable Unicode mode.185- Some(format!("(?-u:{})", alts.join("|")))186- } else {187- log::debug!("required literal found: {:?}", util::show_bytes(lit));188- if lit.chars().all(|c| c.is_whitespace()) {189- log::debug!("dropping literal because one was whitespace");190- return None;191- }192- Some(format!("(?-u:{})", util::bytes_to_regex(&lit)))193- }194- }195-}196-197-fn union_required(expr: &Hir, lits: &mut Seq) {198- match *expr.kind() {199- HirKind::Literal(hir::Literal(ref bytes)) => {200- lits.cross_forward(&mut Seq::new([bytes]));201- }202- HirKind::Class(hir::Class::Unicode(_)) => {203- lits.make_inexact();204- }205- HirKind::Class(hir::Class::Bytes(_)) => {206- lits.make_inexact();207- }208- HirKind::Capture(hir::Capture { ref sub, .. }) => {209- union_required(&**sub, lits);210- }211- HirKind::Repetition(hir::Repetition { min, max, greedy, ref sub }) => {212- repeat_range_literals(213- &sub,214- min,215- max,216- greedy,217- lits,218- union_required,219- );220- }221- HirKind::Concat(ref es) if es.is_empty() => {}222- HirKind::Concat(ref es) if es.len() == 1 => {223- union_required(&es[0], lits)224- }225- HirKind::Concat(ref es) => {226- for e in es {227- let mut lits2 = Seq::singleton(Literal::exact(vec![]));228- union_required(e, &mut lits2);229- if lits2.len() == Some(1) && lits2.min_literal_len() == Some(0)230- {231- lits.make_inexact();232- continue;233- }234- if lits2.min_literal_len() == Some(0) || !is_simple(&e) {235- lits.make_inexact();236- }237- lits.cross_forward(&mut lits2);238- if lits2.is_inexact() {239- // If this expression couldn't yield any literal that240- // could be extended, then we need to quit. Since we're241- // short-circuiting, we also need to freeze every member.242- lits.make_inexact();243- break;244- }245- }246- }247- HirKind::Alternation(ref es) => {248- alternate_literals(es, lits, union_required);249- }250- _ => lits.make_inexact(),251- }252-}253-254-fn repeat_range_literals<F: FnMut(&Hir, &mut Seq)>(255- e: &Hir,256- min: u32,257- _max: Option<u32>,258- _greedy: bool,259- lits: &mut Seq,260- mut f: F,261-) {262- if min == 0 {263- // This is a bit conservative. If `max` is set, then we could264- // treat this as a finite set of alternations. For now, we265- // just treat it as `e*`.266- lits.make_inexact();267- } else {268- // We only extract literals from a single repetition, even though269- // we could do more. e.g., `a{3}` will have `a` extracted instead of270- // `aaa`. The reason is that inner literal extraction can't be unioned271- // across repetitions. e.g., extracting `foofoofoo` from `(\w+foo){3}`272- // is wrong.273- f(e, lits);274- lits.make_inexact();275- }276-}277-278-fn alternate_literals<F: FnMut(&Hir, &mut Seq)>(279- es: &[Hir],280- lits: &mut Seq,281- mut f: F,282-) {283- let mut lits2 = Seq::empty();284- for e in es {285- let mut lits3 = Seq::empty();286- // FIXME287- // lits3.set_limit_size(lits.limit_size() / 5);288- f(e, &mut lits3);289- if lits3.is_empty() {290- lits.make_inexact();291- return;292- }293- lits2.union(&mut lits3);294- }295- // All we do at the moment is look for prefixes and suffixes. If both296- // are empty, then we report nothing. We should be able to do better than297- // this, but we'll need something more expressive than just a "set of298- // literals."299- if let Some(lcp) = lits2.longest_common_prefix() {300- lits.cross_forward(&mut Seq::new([lcp]));301- }302- lits.make_inexact();303- if let Some(lcs) = lits2.longest_common_suffix() {304- lits.push(Literal::exact([]));305- lits.push(Literal::exact(lcs));306- }307- /*308- let lcp = lits2.longest_common_prefix();309- let lcs = lits2.longest_common_suffix();310- if !lcp.is_empty() {311- lits.cross_forward(lcp);312- }313- lits.make_inexact();314- if !lcs.is_empty() {315- lits.push(Literal::exact([]));316- lits.push(Literal::exact(lcs));317- }318- */319-}320-321-fn is_simple(expr: &Hir) -> bool {322- match *expr.kind() {323- HirKind::Empty324- | HirKind::Literal(_)325- | HirKind::Class(_)326- | HirKind::Concat(_)327- | HirKind::Alternation(_) => true,328- HirKind::Look(_) | HirKind::Capture(_) | HirKind::Repetition(_) => {329- false330- }331- }332-}333-334-/*335-/// Return the number of characters in the given class.336-fn count_unicode_class(cls: &hir::ClassUnicode) -> u32 {337- cls.iter().map(|r| 1 + (r.end() as u32 - r.start() as u32)).sum()338-}339-340-/// Return the number of bytes in the given class.341-fn count_byte_class(cls: &hir::ClassBytes) -> u32 {342- cls.iter().map(|r| 1 + (r.end() as u32 - r.start() as u32)).sum()343-}344-*/345-346-/// Returns true if and only if any of the literals in the given set is347-/// entirely whitespace.348-fn has_only_whitespace(lits: &[Literal]) -> bool {349- for lit in lits {350- if lit.as_bytes().chars().all(|c| c.is_whitespace()) {351- return true;352- }353- }354- false355-}356-357-fn prefixes(hir: &Hir) -> Seq {358- let mut extractor = literal::Extractor::new();359- extractor.kind(literal::ExtractKind::Prefix);360- let mut prefixes = extractor.extract(hir);361- log::debug!(362- "prefixes (len={:?}, exact={:?}) extracted before optimization: {:?}",363- prefixes.len(),364- prefixes.is_exact(),365- prefixes366- );367- prefixes.optimize_for_prefix_by_preference();368- log::debug!(369- "prefixes (len={:?}, exact={:?}) extracted after optimization: {:?}",370- prefixes.len(),371- prefixes.is_exact(),372- prefixes373- );374- prefixes375-}376-377-fn suffixes(hir: &Hir) -> Seq {378- let mut extractor = literal::Extractor::new();379- extractor.kind(literal::ExtractKind::Suffix);380- let mut suffixes = extractor.extract(hir);381- log::debug!(382- "suffixes (len={:?}, exact={:?}) extracted before optimization: {:?}",383- suffixes.len(),384- suffixes.is_exact(),385- suffixes386- );387- suffixes.optimize_for_suffix_by_preference();388- log::debug!(389- "suffixes (len={:?}, exact={:?}) extracted after optimization: {:?}",390- suffixes.len(),391- suffixes.is_exact(),392- suffixes393- );394- suffixes395-}396-397-#[cfg(test)]398-mod tests {399- use super::LiteralSets;400- use regex_syntax::Parser;401-402- fn sets(pattern: &str) -> LiteralSets {403- let hir = Parser::new().parse(pattern).unwrap();404- LiteralSets::new(&hir)405- }406-407- fn one_regex(pattern: &str) -> Option<String> {408- sets(pattern).one_regex(false)409- }410-411- // Put a pattern into the same format as the one returned by `one_regex`.412- fn pat(pattern: &str) -> Option<String> {413- Some(format!("(?-u:{})", pattern))414- }415-416- #[test]417- fn various() {418- // Obviously no literals.419- assert!(one_regex(r"\w").is_none());420- assert!(one_regex(r"\pL").is_none());421-422- // Tantalizingly close.423- assert!(one_regex(r"\w|foo").is_none());424-425- // There's a literal, but it's better if the regex engine handles it426- // internally.427- assert!(one_regex(r"abc").is_none());428-429- // Core use cases.430- assert_eq!(one_regex(r"\wabc\w"), pat("abc"));431- assert_eq!(one_regex(r"abc\w"), pat("abc"));432-433- // TODO: Make these pass. We're missing some potentially big wins434- // without these.435- // assert_eq!(one_regex(r"\w(foo|bar|baz)"), pat("foo|bar|baz"));436- // assert_eq!(one_regex(r"\w(foo|bar|baz)\w"), pat("foo|bar|baz"));437- }438-439- #[test]440- fn regression_1064() {441- // Regression from:442- // https://github.com/BurntSushi/ripgrep/issues/1064443- // assert_eq!(one_regex(r"a.*c"), pat("a"));444- assert_eq!(one_regex(r"a(.*c)"), pat("a"));445- }446-447- #[test]448- fn regression_1319() {449- // Regression from:450- // https://github.com/BurntSushi/ripgrep/issues/1319451- assert_eq!(452- one_regex(r"TTGAGTCCAGGAG[ATCG]{2}C"),453- pat("TTGAGTCCAGGAG"),454- );455- }456-457- #[test]458- fn regression_1537() {459- // Regression from:460- // https://github.com/BurntSushi/ripgrep/issues/1537461- assert_eq!(one_regex(r";(.*,)"), pat(";"));462- assert_eq!(one_regex(r";((.*,))"), pat(";"));463- assert_eq!(one_regex(r";(.*,)+"), pat(";"),);464- assert_eq!(one_regex(r";(.*,){1}"), pat(";"),);465- }466-}