use std::{
borrow::Cow,
collections::{HashMap, VecDeque},
};
use laravel_rust_format_core::str;
use super::check_bytes;
use crate::error::{Error, ErrorKind, Result};
pub(crate) const MIN_MATCHER_STATES: usize = 64;
const MAX_MATCHER_STATES: usize = 32_768;
fn matcher_limit() -> Error {
Error::new(
ErrorKind::Limit,
"translation matcher state limit exceeded",
None,
)
}
pub(super) fn make<'l>(
line: &'l str,
replace: &[(&str, &str)],
max_bytes: Option<usize>,
) -> Result<Cow<'l, str>> {
replace_all(line, replace.iter().copied(), max_bytes)
}
pub(super) fn make_with_count<'l>(
line: &'l str,
replace: &[(&str, &str)],
count: &str,
max_bytes: Option<usize>,
) -> Result<Cow<'l, str>> {
let count = (!replace.iter().any(|&(key, _)| key == "count")).then_some(("count", count));
replace_all(line, replace.iter().copied().chain(count), max_bytes)
}
fn replace_all<'l, 'r>(
line: &'l str,
replace: impl Iterator<Item = (&'r str, &'r str)>,
max_bytes: Option<usize>,
) -> Result<Cow<'l, str>> {
let max_states = max_bytes.map_or(usize::MAX, |bytes| {
bytes.clamp(MIN_MATCHER_STATES, MAX_MATCHER_STATES)
});
let max_bytes = max_bytes.unwrap_or(usize::MAX);
if !line.contains(':') {
check_bytes(line.len(), max_bytes)?;
return Ok(Cow::Borrowed(line));
}
let mut entries = indexmap::IndexMap::new();
for (key, value) in replace {
if entries.len() == max_states && !entries.contains_key(key) {
return Err(matcher_limit());
}
entries.insert(key, value);
}
let mut matcher = Matcher::default();
for (key, value) in entries {
for (spelling, replacement) in [
(ucfirst(key), Replacement::First(value)),
(upper(key), Replacement::Upper(value)),
(Cow::Borrowed(key), Replacement::Plain(value)),
] {
if spelling.len() < line.len() {
matcher.insert(&spelling, replacement, max_states)?;
}
}
}
matcher.replace(line, max_bytes)
}
#[derive(Clone, Copy)]
enum Replacement<'a> {
Plain(&'a str),
First(&'a str),
Upper(&'a str),
}
impl<'a> Replacement<'a> {
fn text(self) -> Cow<'a, str> {
match self {
Self::Plain(text) => Cow::Borrowed(text),
Self::First(text) => ucfirst(text),
Self::Upper(text) => upper(text),
}
}
}
#[derive(Default)]
struct State<'a> {
next: HashMap<u8, usize>,
fail: usize,
longest: Option<usize>,
replacement: Option<Replacement<'a>>,
length: usize,
}
struct Matcher<'a> {
states: Vec<State<'a>>,
}
impl Default for Matcher<'_> {
fn default() -> Self {
Self {
states: vec![State::default()],
}
}
}
impl<'a> Matcher<'a> {
fn insert(&mut self, key: &str, replacement: Replacement<'a>, max_states: usize) -> Result<()> {
let mut state = 0;
for byte in key.bytes().rev().chain(std::iter::once(b':')) {
let next = if let Some(&next) = self.states[state].next.get(&byte) {
next
} else {
let next = self.states.len();
if next == max_states {
return Err(matcher_limit());
}
self.states[state].next.insert(byte, next);
self.states.push(State::default());
next
};
state = next;
}
let terminal = &mut self.states[state];
terminal.length = key.len() + 1;
terminal.replacement = Some(replacement);
terminal.longest = Some(state);
Ok(())
}
fn step(&self, mut state: usize, byte: u8) -> usize {
loop {
if let Some(&next) = self.states[state].next.get(&byte) {
return next;
}
if state == 0 {
return 0;
}
state = self.states[state].fail;
}
}
fn link_fallbacks(&mut self) {
let mut queue: VecDeque<_> = self.states[0].next.values().copied().collect();
while let Some(parent) = queue.pop_front() {
let fallback = self.states[parent].fail;
let children: Vec<_> = self.states[parent]
.next
.iter()
.map(|(&byte, &child)| (byte, child))
.collect();
for (byte, child) in children {
let fail = self.step(fallback, byte);
let longest = self.states[fail].longest;
let state = &mut self.states[child];
state.fail = fail;
state.longest = state.longest.or(longest);
queue.push_back(child);
}
}
}
fn replace<'l>(mut self, line: &'l str, max_bytes: usize) -> Result<Cow<'l, str>> {
self.link_fallbacks();
let mut state = 0;
let mut matches = Vec::new();
for (start, byte) in line.bytes().enumerate().rev() {
state = self.step(state, byte);
if let Some(terminal) = self.states[state].longest {
matches.push((start, terminal));
}
}
if matches.is_empty() {
check_bytes(line.len(), max_bytes)?;
return Ok(Cow::Borrowed(line));
}
let mut output = String::new();
let mut copied = 0;
let mut transformed = HashMap::new();
for (start, terminal) in matches.into_iter().rev() {
if start < copied {
continue;
}
let state = &self.states[terminal];
if let Some(replacement) = state.replacement {
let value = transformed
.entry(terminal)
.or_insert_with(|| replacement.text());
check_bytes(
output
.len()
.saturating_add(start - copied)
.saturating_add(value.len()),
max_bytes,
)?;
output.push_str(&line[copied..start]);
output.push_str(value);
copied = start + state.length;
}
}
check_bytes(output.len().saturating_add(line.len() - copied), max_bytes)?;
output.push_str(&line[copied..]);
Ok(Cow::Owned(output))
}
}
fn ucfirst(text: &str) -> Cow<'_, str> {
match text.chars().next() {
Some(first) if first.is_ascii_lowercase() || !first.is_ascii() => {
Cow::Owned(str::ucfirst(text))
}
_ => Cow::Borrowed(text),
}
}
fn upper(text: &str) -> Cow<'_, str> {
if !text.is_ascii() {
return Cow::Owned(str::upper(text));
}
if text.bytes().any(|byte| byte.is_ascii_lowercase()) {
Cow::Owned(text.to_ascii_uppercase())
} else {
Cow::Borrowed(text)
}
}
#[cfg(test)]
mod tests {
use std::borrow::Cow;
use super::*;
fn make<'l>(line: &'l str, replace: &[(&str, &str)]) -> Cow<'l, str> {
super::make(line, replace, None).unwrap()
}
fn make_with_count<'l>(line: &'l str, replace: &[(&str, &str)], count: &str) -> Cow<'l, str> {
super::make_with_count(line, replace, count, None).unwrap()
}
fn made(line: &str, replace: &[(&str, &str)]) -> String {
make(line, replace).into_owned()
}
#[test]
fn the_three_forms_of_a_name() {
assert_eq!(made("x :name", &[("name", "ana")]), "x ana");
assert_eq!(made("x :Name", &[("name", "ana")]), "x Ana");
assert_eq!(made("x :NAME", &[("name", "ana")]), "x ANA");
assert_eq!(made(":name :Name :NAME", &[("name", "ana")]), "ana Ana ANA");
assert_eq!(made("x :namey", &[("name", "ana")]), "x anay");
assert_eq!(made("a: :name", &[("name", "n")]), "a: n");
assert_eq!(made("x :name", &[]), "x :name");
}
#[test]
fn the_longest_name_wins_and_replaced_text_is_not_searched_again() {
assert_eq!(made(":name", &[("na", "X"), ("name", "Y")]), "Y");
assert_eq!(made(":nax", &[("name", "Y"), ("na", "X")]), "Xx");
assert_eq!(made(":name", &[("name", ":na"), ("na", "X")]), ":na");
assert_eq!(made(":name:name", &[("name", "n"), ("e", "E")]), "nn");
assert_eq!(made(":name :n", &[("n", "a"), ("name", "b")]), "b a");
assert_eq!(made(":abc", &[("abc", "C"), ("ab", "AB"), ("a", "A")]), "C");
assert_eq!(made(":a", &[("a", "A"), ("ab", "AB")]), "A");
}
#[test]
fn overlapping_colons_use_longest_leftmost_matches_with_many_other_keys() {
let other: Vec<_> = (0..4096).map(|i| format!("name{i}")).collect();
let mut replacements: Vec<_> = other.iter().map(|name| (name.as_str(), "unused")).collect();
replacements.extend([("a:a", "L"), ("a", "s")]);
let line = ":a:a:a | ".repeat(4096);
assert_eq!(make(&line, &replacements), "Ls | ".repeat(4096));
}
#[test]
fn matcher_rejects_before_allocating_another_state_or_transition() {
let mut matcher = Matcher::default();
matcher.insert("x", Replacement::Plain("first"), 3).unwrap();
matcher
.insert("x", Replacement::Plain("second"), 3)
.unwrap();
let error = matcher
.insert("y", Replacement::Plain("unused"), 3)
.unwrap_err();
assert_eq!(error.kind, ErrorKind::Limit);
assert_eq!(matcher.states.len(), 3);
assert!(!matcher.states[0].next.contains_key(&b'y'));
assert_eq!(matcher.replace(":x", 6).unwrap(), "second");
}
#[test]
fn names_that_spell_the_same_after_casing() {
assert_eq!(
made("x :Name :name", &[("name", "ana"), ("Name", "Bob")]),
"x Bob ana"
);
assert_eq!(
made("x :Name :name", &[("Name", "Bob"), ("name", "ana")]),
"x Ana ana"
);
assert_eq!(
made("x :Name :name", &[("name", "bob"), ("NAME", "x")]),
"x Bob bob"
);
assert_eq!(made("x :Count", &[("count", "x")]), "x X");
assert_eq!(made("x :NAME", &[("Name", "Bob")]), "x BOB");
}
#[test]
fn a_repeated_key_keeps_its_first_position_and_takes_its_last_value() {
assert_eq!(made("x :name", &[("name", "a"), ("name", "b")]), "x b");
assert_eq!(made("x :A", &[("a", "1"), ("A", "2"), ("a", "3")]), "x 2");
}
#[test]
fn count_is_appended_after_the_other_names() {
assert_eq!(make_with_count("x :count", &[], "5").as_ref(), "x 5");
assert_eq!(
make_with_count("x :Count", &[("Count", "X")], "5").as_ref(),
"x 5"
);
assert_eq!(
make_with_count("x :count", &[("count", "X")], "5").as_ref(),
"x X"
);
assert_eq!(
make_with_count("x :count", &[("other", "X")], "2.5").as_ref(),
"x 2.5"
);
assert_eq!(make_with_count("x", &[("other", "X")], "2.5").as_ref(), "x");
}
#[test]
fn empty_names_and_values() {
assert_eq!(made(":x", &[("x", "")]), "");
assert_eq!(made(":x", &[("x", "0")]), "0");
assert_eq!(made("a:b", &[("", "N")]), "aNb");
assert_eq!(made("::", &[("", "")]), "");
assert_eq!(made("a\0:b", &[("b", "c\0d")]), "a\0c\0d");
}
#[test]
fn unicode_follows_php() {
assert_eq!(made("é :Name", &[("name", "élan")]), "é Élan");
assert_eq!(made("x :Name", &[("name", "ßabc")]), "x Ssabc");
assert_eq!(
made("x :NAME", &[("name", "Straße fi ʼnđ dže")]),
"x STRASSE FI ʼNĐ DŽE"
);
assert_eq!(made("x :Name", &[("name", "dže")]), "x Dže");
assert_eq!(made(":NAME", &[("name", "nja ʼn ǰ")]), "NJA ʼN J̌");
assert_eq!(
made("x :NAME", &[("name", "ünïcödé ıi ᾈ")]),
"x ÜNÏCÖDÉ II ἈΙ"
);
assert_eq!(made("x :Ssname", &[("ßname", "x")]), "x X");
assert_eq!(made("x :SSNAME", &[("ßname", "x")]), "x X");
assert_eq!(made("x :ßname", &[("ßname", "x")]), "x x");
assert_eq!(made("x :SS", &[("ß", "x")]), "x X");
}
#[test]
fn an_untouched_line_is_borrowed() {
assert!(matches!(
make("x :name", &[("other", "y")]),
Cow::Borrowed("x :name")
));
assert!(matches!(
make("no colons", &[("name", "y")]),
Cow::Borrowed(_)
));
assert!(matches!(make("x :name", &[]), Cow::Borrowed(_)));
}
#[test]
fn casing_helpers_borrow_what_does_not_change() {
assert!(matches!(ucfirst("Ana 1-"), Cow::Borrowed(_)));
assert!(matches!(ucfirst("ana"), Cow::Owned(_)));
assert!(matches!(ucfirst("élan"), Cow::Owned(_)));
assert!(matches!(ucfirst(""), Cow::Borrowed(_)));
assert!(matches!(upper("ANA 1-"), Cow::Borrowed(_)));
assert!(matches!(upper("ANA 1- é"), Cow::Owned(_)));
assert!(matches!(upper("ana"), Cow::Owned(_)));
assert!(matches!(upper("é"), Cow::Owned(_)));
}
}