regex_automata - Rust (original) (raw)

Crate regex_automata

Source

Expand description

This crate exposes a variety of regex engines used by the regex crate. It provides a vast, sprawling and “expert” level API to each regex engine. The regex engines provided by this crate focus heavily on finite automata implementations and specifically guarantee worst case O(m * n) time complexity for all searches. (Where m ~ len(regex) and n ~ len(haystack).)

The primary goal of this crate is to serve as an implementation detail for theregex crate. A secondary goal is to make its internals available for use by others.

§Table of contents

§Should I be using this crate?

If you find yourself here because you just want to use regexes, then you should first check out whether the regex crate meets your needs. It provides a streamlined and difficult-to-misuse API for regex searching.

If you’re here because there is something specific you want to do that can’t be easily done with regex crate, then you are perhaps in the right place. It’s most likely that the first stop you’ll want to make is to explore themeta regex APIs. Namely, the regex crate is just a light wrapper over a meta::Regex, so its API will probably be the easiest to transition to. In contrast to the regex crate, the meta::Regex API supports more search parameters and does multi-pattern searches. However, it isn’t quite as ergonomic.

Otherwise, the following is an inexhaustive list of reasons to use this crate:

§Examples

This section tries to identify a few interesting things you can do with this crate and demonstrates them.

§Multi-pattern searches with capture groups

One of the more frustrating limitations of RegexSet in the regex crate (at the time of writing) is that it doesn’t report match positions. With this crate, multi-pattern support was intentionally designed in from the beginning, which means it works in all regex engines and even for capture groups as well.

This example shows how to search for matches of multiple regexes, where each regex uses the same capture group names to parse different key-value formats.

use regex_automata::{meta::Regex, PatternID};

let re = Regex::new_many(&[
    r#"(?m)^(?<key>[[:word:]]+)=(?<val>[[:word:]]+)$"#,
    r#"(?m)^(?<key>[[:word:]]+)="(?<val>[^"]+)"$"#,
    r#"(?m)^(?<key>[[:word:]]+)='(?<val>[^']+)'$"#,
    r#"(?m)^(?<key>[[:word:]]+):\s*(?<val>[[:word:]]+)$"#,
])?;
let hay = r#"
best_album="Blow Your Face Out"
best_quote='"then as it was, then again it will be"'
best_year=1973
best_simpsons_episode: HOMR
"#;
let mut kvs = vec![];
for caps in re.captures_iter(hay) {
    // N.B. One could use capture indices '1' and '2' here
    // as well. Capture indices are local to each pattern.
    // (Just like names are.)
    let key = &hay[caps.get_group_by_name("key").unwrap()];
    let val = &hay[caps.get_group_by_name("val").unwrap()];
    kvs.push((key, val));
}
assert_eq!(kvs, vec![
    ("best_album", "Blow Your Face Out"),
    ("best_quote", "\"then as it was, then again it will be\""),
    ("best_year", "1973"),
    ("best_simpsons_episode", "HOMR"),
]);

§Build a full DFA and walk it manually

One of the regex engines in this crate is a fully compiled DFA. It takes worst case exponential time to build, but once built, it can be easily explored and used for searches. Here’s a simple example that uses its lower level APIs to implement a simple anchored search by hand.

use regex_automata::{dfa::{Automaton, dense}, Input};

let dfa = dense::DFA::new(r"(?-u)\b[A-Z]\w+z\b")?;
let haystack = "Quartz";

// The start state is determined by inspecting the position and the
// initial bytes of the haystack.
let mut state = dfa.start_state_forward(&Input::new(haystack))?;
// Walk all the bytes in the haystack.
for &b in haystack.as_bytes().iter() {
    state = dfa.next_state(state, b);
}
// DFAs in this crate require an explicit
// end-of-input transition if a search reaches
// the end of a haystack.
state = dfa.next_eoi_state(state);
assert!(dfa.is_match_state(state));

Or do the same with a lazy DFA that avoids exponential worst case compile time, but requires mutable scratch space to lazily build the DFA during the search.

use regex_automata::{hybrid::dfa::DFA, Input};

let dfa = DFA::new(r"(?-u)\b[A-Z]\w+z\b")?;
let mut cache = dfa.create_cache();
let hay = "Quartz";

// The start state is determined by inspecting the position and the
// initial bytes of the haystack.
let mut state = dfa.start_state_forward(&mut cache, &Input::new(hay))?;
// Walk all the bytes in the haystack.
for &b in hay.as_bytes().iter() {
    state = dfa.next_state(&mut cache, state, b)?;
}
// DFAs in this crate require an explicit
// end-of-input transition if a search reaches
// the end of a haystack.
state = dfa.next_eoi_state(&mut cache, state)?;
assert!(state.is_match());

§Find all overlapping matches

This example shows how to build a DFA and use it to find all possible matches, including overlapping matches. A similar example will work with a lazy DFA as well. This also works with multiple patterns and will report all matches at the same position where multiple patterns match.

use regex_automata::{
    dfa::{dense, Automaton, OverlappingState},
    Input, MatchKind,
};

let dfa = dense::DFA::builder()
    .configure(dense::DFA::config().match_kind(MatchKind::All))
    .build(r"(?-u)\w{3,}")?;
let input = Input::new("homer marge bart lisa maggie");
let mut state = OverlappingState::start();

let mut matches = vec![];
while let Some(hm) = {
    dfa.try_search_overlapping_fwd(&input, &mut state)?;
    state.get_match()
} {
    matches.push(hm.offset());
}
assert_eq!(matches, vec![
    3, 4, 5,        // hom, home, homer
    9, 10, 11,      // mar, marg, marge
    15, 16,         // bar, bart
    20, 21,         // lis, lisa
    25, 26, 27, 28, // mag, magg, maggi, maggie
]);

§Available regex engines

The following is a complete list of all regex engines provided by this crate, along with a very brief description of it and why you might want to use it.

§API themes

While each regex engine has its own APIs and configuration options, there are some general themes followed by all of them.

§The Input abstraction

Most search routines in this crate accept anything that implementsInto<Input>. Both &str and &[u8] haystacks satisfy this constraint, which means that things like engine.search("foo") will work as you would expect.

By virtue of accepting an Into<Input> though, callers can provide more than just a haystack. Indeed, the Input type has more details, but briefly, callers can use it to configure various aspects of the search:

Some lower level search routines accept an &Input for performance reasons. In which case, &Input::new("haystack") can be used for a simple search.

§Error reporting

Most, but not all, regex engines in this crate can fail to execute a search. When a search fails, callers cannot determine whether or not a match exists. That is, the result is indeterminate.

Search failure, in all cases in this crate, is represented by a MatchError. Routines that can fail start with the try_ prefix in their name. For example,hybrid::regex::Regex::try_search can fail for a number of reasons. Conversely, routines that either can’t fail or can panic on failure lack thetry_ prefix. For example, hybrid::regex::Regex::find will panic in cases where hybrid::regex::Regex::try_search would return an error, andmeta::Regex::find will never panic. Therefore, callers need to pay close attention to the panicking conditions in the documentation.

In most cases, the reasons that a search fails are either predictable or configurable, albeit at some additional cost.

An example of predictable failure isBoundedBacktracker::try_search. Namely, it fails whenever the multiplication of the haystack, the regex and some constant exceeds theconfigured visited capacity. Callers can predict the failure in terms of haystack length via theBoundedBacktracker::max_haystack_lenmethod. While this form of failure is technically avoidable by increasing the visited capacity, it isn’t practical to do so for all inputs because the memory usage required for larger haystacks becomes impractically large. So in practice, if one is using the bounded backtracker, you really do have to deal with the failure.

An example of configurable failure happens when one enables heuristic support for Unicode word boundaries in a DFA. Namely, since the DFAs in this crate (except for the one-pass DFA) do not support Unicode word boundaries on non-ASCII haystacks, building a DFA from an NFA that contains a Unicode word boundary will itself fail. However, one can configure DFAs to still be built in this case byconfiguring heuristic support for Unicode word boundaries. If the NFA the DFA is built from contains a Unicode word boundary, then the DFA will still be built, but special transitions will be added to every state that cause the DFA to fail if any non-ASCII byte is seen. This failure happens at search time and it requires the caller to opt into this.

There are other ways for regex engines to fail in this crate, but the above two should represent the general theme of failures one can find. Dealing with these failures is, in part, one the responsibilities of the meta regex engine. Notice, for example, that the meta regex engine exposes an API that never returns an error nor panics. It carefully manages all of the ways in which the regex engines can fail and either avoids the predictable ones entirely (e.g., the bounded backtracker) or reacts to configured failures by falling back to a different engine (e.g., the lazy DFA quitting because it saw a non-ASCII byte).

§Configuration and Builders

Most of the regex engines in this crate come with two types to facilitate building the regex engine: a Config and a Builder. A Config is usually specific to that particular regex engine, but other objects such as parsing and NFA compilation have Config types too. A Builder is the thing responsible for taking inputs (either pattern strings or already-parsed patterns or even NFAs directly) and turning them into an actual regex engine that can be used for searching.

The main reason why building a regex engine is a bit complicated is because of the desire to permit composition with de-coupled components. For example, you might want to manually construct a Thompson NFAand then build a regex engine from it without ever using a regex parser at all. On the other hand, you might also want to build a regex engine directly from the concrete syntax. This demonstrates why regex engine construction is so flexible: it needs to support not just convenient construction, but also construction from parts built elsewhere.

This is also in turn why there are many different Config structs in this crate. Let’s look more closely at an example: hybrid::regex::Builder. It accepts three different Config types for configuring construction of a lazy DFA regex:

The lazy DFA regex engine uses all three of those configuration objects for methods like hybrid::regex::Builder::build, which accepts a pattern string containing the concrete syntax of your regex. It uses the syntax configuration to parse it into an AST and translate it into an HIR. Then the NFA configuration when compiling the HIR into an NFA. And then finally the DFA configuration when lazily determinizing the NFA into a DFA.

Notice though that the builder also has ahybrid::regex::Builder::build_from_dfas constructor. This permits callers to build the underlying pair of lazy DFAs themselves (one for the forward searching to find the end of a match and one for the reverse searching to find the start of a match), and then build the regex engine from them. The lazy DFAs, in turn, have their own builder that permits construction directly from a Thompson NFA. Continuing down the rabbit hole, a Thompson NFA has its own compiler that permits construction directly from an HIR. The lazy DFA regex engine builder lets you follow this rabbit hole all the way down, but also provides convenience routines that do it for you when you don’t need precise control over every component.

The meta regex engine is a good example of something that utilizes the full flexibility of these builders. It often needs not only precise control over each component, but also shares them across multiple regex engines. (Most sharing is done by internal reference accounting. For example, anNFA is reference counted internally which makes cloning cheap.)

§Size limits

Unlike the regex crate, the regex-automata crate specifically does not enable any size limits by default. That means users of this crate need to be quite careful when using untrusted patterns. Namely, because bounded repetitions can grow exponentially by stacking them, it is possible to build a very large internal regex object from just a small pattern string. For example, the NFA built from the pattern a{10}{10}{10}{10}{10}{10}{10} is over 240MB.

There are multiple size limit options in this crate. If one or more size limits are relevant for the object you’re building, they will be configurable via methods on a corresponding Config type.

§Crate features

This crate has a dizzying number of features. The main idea is to be able to control how much stuff you pull in for your specific use case, since the full crate is quite large and can dramatically increase compile times and binary size.

The most barebones but useful configuration is to disable all default features and enable only dfa-search. This will bring in just the DFA deserialization and search routines without any dependency on std or alloc. This does require generating and serializing a DFA, and then storing it somewhere, but it permits regex searches in freestanding or embedded environments.

Because there are so many features, they are split into a few groups.

The default set of features is: std, syntax, perf, unicode, meta,nfa, dfa and hybrid. Basically, the default is to enable everything except for development related features like logging.

§Ecosystem features

§Performance features

§Unicode features

§Regex engine features

dfadfa-search or dfa-onepass

A module for building and searching with deterministic finite automata (DFAs).

hybridhybrid

A module for building and searching with lazy deterministic finite automata (DFAs).

metameta

Provides a regex matcher that composes several other regex matchers automatically.

nfanfa-thompson

Provides non-deterministic finite automata (NFA) and regex engines that use them.

util

A collection of modules that provide APIs that are useful across many regex engines.

HalfMatch

A representation of “half” of a match reported by a DFA.

Input

The parameters for a regex search including the haystack to search.

Match

A representation of a match reported by a regex engine.

MatchError

An error indicating that a search stopped before reporting whether a match exists or not.

PatternID

The identifier of a regex pattern, represented by a SmallIndex.

PatternSetalloc

A set of PatternIDs.

PatternSetInsertErroralloc

An error that occurs when a PatternID failed to insert into aPatternSet.

PatternSetIteralloc

An iterator over all pattern identifiers in a PatternSet.

Span

A representation of a span reported by a regex engine.

Anchored

The type of anchored search to perform.

MatchErrorKind

The underlying kind of a MatchError.

MatchKind

The kind of match semantics to use for a regex pattern.