ruff/crates/ruff_python_ast/src/str.rs
Charlie Marsh ea1c089652
Use AhoCorasick to speed up quote match (#9773)
<!--
Thank you for contributing to Ruff! To help us out with reviewing,
please consider the following:

- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title?
- Does this pull request include references to any relevant issues?
-->

## Summary

When I was looking at the v0.2.0 release, this method showed up in a
CodSpeed regression (we were calling it more), so I decided to quickly
look at speeding it up. @BurntSushi suggested using Aho-Corasick, and it
looks like it's about 7 or 8x faster:

```text
Parser/AhoCorasick      time:   [8.5646 ns 8.5914 ns 8.6191 ns]
Parser/Iterator         time:   [64.992 ns 65.124 ns 65.271 ns]
```

## Test Plan

`cargo test`
2024-02-02 09:57:39 -05:00

217 lines
5.1 KiB
Rust

use aho_corasick::{AhoCorasick, AhoCorasickKind, Anchored, Input, MatchKind, StartKind};
use once_cell::sync::Lazy;
use ruff_text_size::{TextLen, TextRange};
/// Includes all permutations of `r`, `u`, `f`, and `fr` (`ur` is invalid, as is `uf`). This
/// includes all possible orders, and all possible casings, for both single and triple quotes.
///
/// See: <https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals>
#[rustfmt::skip]
const TRIPLE_QUOTE_STR_PREFIXES: &[&str] = &[
"FR\"\"\"",
"Fr\"\"\"",
"fR\"\"\"",
"fr\"\"\"",
"RF\"\"\"",
"Rf\"\"\"",
"rF\"\"\"",
"rf\"\"\"",
"FR'''",
"Fr'''",
"fR'''",
"fr'''",
"RF'''",
"Rf'''",
"rF'''",
"rf'''",
"R\"\"\"",
"r\"\"\"",
"R'''",
"r'''",
"F\"\"\"",
"f\"\"\"",
"F'''",
"f'''",
"U\"\"\"",
"u\"\"\"",
"U'''",
"u'''",
"\"\"\"",
"'''",
];
#[rustfmt::skip]
const SINGLE_QUOTE_STR_PREFIXES: &[&str] = &[
"FR\"",
"Fr\"",
"fR\"",
"fr\"",
"RF\"",
"Rf\"",
"rF\"",
"rf\"",
"FR'",
"Fr'",
"fR'",
"fr'",
"RF'",
"Rf'",
"rF'",
"rf'",
"R\"",
"r\"",
"R'",
"r'",
"F\"",
"f\"",
"F'",
"f'",
"U\"",
"u\"",
"U'",
"u'",
"\"",
"'",
];
/// Includes all permutations of `b` and `rb`. This includes all possible orders, and all possible
/// casings, for both single and triple quotes.
///
/// See: <https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals>
#[rustfmt::skip]
pub const TRIPLE_QUOTE_BYTE_PREFIXES: &[&str] = &[
"BR\"\"\"",
"Br\"\"\"",
"bR\"\"\"",
"br\"\"\"",
"RB\"\"\"",
"Rb\"\"\"",
"rB\"\"\"",
"rb\"\"\"",
"BR'''",
"Br'''",
"bR'''",
"br'''",
"RB'''",
"Rb'''",
"rB'''",
"rb'''",
"B\"\"\"",
"b\"\"\"",
"B'''",
"b'''",
];
#[rustfmt::skip]
pub const SINGLE_QUOTE_BYTE_PREFIXES: &[&str] = &[
"BR\"",
"Br\"",
"bR\"",
"br\"",
"RB\"",
"Rb\"",
"rB\"",
"rb\"",
"BR'",
"Br'",
"bR'",
"br'",
"RB'",
"Rb'",
"rB'",
"rb'",
"B\"",
"b\"",
"B'",
"b'",
];
/// Strip the leading and trailing quotes from a string.
/// Assumes that the string is a valid string literal, but does not verify that the string
/// is a "simple" string literal (i.e., that it does not contain any implicit concatenations).
pub fn raw_contents(contents: &str) -> Option<&str> {
let range = raw_contents_range(contents)?;
Some(&contents[range])
}
pub fn raw_contents_range(contents: &str) -> Option<TextRange> {
let leading_quote_str = leading_quote(contents)?;
let trailing_quote_str = trailing_quote(contents)?;
Some(TextRange::new(
leading_quote_str.text_len(),
contents.text_len() - trailing_quote_str.text_len(),
))
}
/// An [`AhoCorasick`] matcher for string and byte literal prefixes.
static PREFIX_MATCHER: Lazy<AhoCorasick> = Lazy::new(|| {
AhoCorasick::builder()
.start_kind(StartKind::Anchored)
.match_kind(MatchKind::LeftmostLongest)
.kind(Some(AhoCorasickKind::DFA))
.build(
TRIPLE_QUOTE_STR_PREFIXES
.iter()
.chain(TRIPLE_QUOTE_BYTE_PREFIXES)
.chain(SINGLE_QUOTE_STR_PREFIXES)
.chain(SINGLE_QUOTE_BYTE_PREFIXES),
)
.unwrap()
});
/// Return the leading quote for a string or byte literal (e.g., `"""`).
pub fn leading_quote(content: &str) -> Option<&str> {
let mat = PREFIX_MATCHER.find(Input::new(content).anchored(Anchored::Yes))?;
Some(&content[mat.start()..mat.end()])
}
/// Return the trailing quote string for a string or byte literal (e.g., `"""`).
pub fn trailing_quote(content: &str) -> Option<&str> {
if content.ends_with("'''") {
Some("'''")
} else if content.ends_with("\"\"\"") {
Some("\"\"\"")
} else if content.ends_with('\'') {
Some("'")
} else if content.ends_with('\"') {
Some("\"")
} else {
None
}
}
/// Return `true` if the string is a triple-quote string or byte prefix.
pub fn is_triple_quote(content: &str) -> bool {
TRIPLE_QUOTE_STR_PREFIXES.contains(&content) || TRIPLE_QUOTE_BYTE_PREFIXES.contains(&content)
}
#[cfg(test)]
mod tests {
use super::{
SINGLE_QUOTE_BYTE_PREFIXES, SINGLE_QUOTE_STR_PREFIXES, TRIPLE_QUOTE_BYTE_PREFIXES,
TRIPLE_QUOTE_STR_PREFIXES,
};
#[test]
fn prefix_uniqueness() {
let prefixes = TRIPLE_QUOTE_STR_PREFIXES
.iter()
.chain(TRIPLE_QUOTE_BYTE_PREFIXES)
.chain(SINGLE_QUOTE_STR_PREFIXES)
.chain(SINGLE_QUOTE_BYTE_PREFIXES)
.collect::<Vec<_>>();
for (i, prefix_i) in prefixes.iter().enumerate() {
for (j, prefix_j) in prefixes.iter().enumerate() {
if i > j {
assert!(
!prefix_i.starts_with(*prefix_j),
"Prefixes are not unique: {prefix_i} starts with {prefix_j}",
);
}
}
}
}
}