use crate::fix::emoji::{Extent, Pairing};
use crate::fix::map::{Map, Match, violates};
use crate::fix::words::Gap;
use crate::fix::{Error, Hazard, Marks, Restore, Rewrite};
use crate::scan::{Hit, Position};
#[derive(Debug, Default)]
pub(super) struct Pass {
pub(super) output: String,
pub(super) spans: Vec<Span>,
pub(super) unmapped: Vec<Hit>,
}
#[derive(Debug)]
pub(super) struct Span {
pub(super) hit: Hit,
pub(super) len: usize,
pub(super) to: String,
}
impl Span {
pub(super) fn extent(&self) -> Extent {
Extent {
byte: self.hit.position.byte,
len: self.len,
to: self.to.len(),
}
}
pub(super) fn into_rewrite(self) -> Rewrite {
Rewrite {
hit: self.hit,
to: self.to,
}
}
}
#[derive(Clone, Copy)]
pub(super) struct Ground<'a> {
pub(super) map: &'a Map,
pub(super) allowed: &'a dyn Fn(char) -> bool,
pub(super) budget: usize,
}
pub(super) fn run(
text: &str,
ground: Ground<'_>,
marks: Marks,
) -> Result<Pass, Error> {
let mut walk = Run::new(text, ground, marks);
walk.walk()?;
Ok(walk.pass)
}
type Found<'a> = Result<Option<(&'a str, Match)>, Error>;
struct Run<'a> {
text: &'a str,
map: &'a Map,
allowed: &'a dyn Fn(char) -> bool,
budget: usize,
hazards: Vec<Hazard>,
kept: Vec<usize>,
restores: Vec<Restore>,
next: usize,
at: Cursor,
pass: Pass,
gap: Gap,
pairing: Pairing,
}
impl<'a> Run<'a> {
fn new(text: &'a str, ground: Ground<'a>, marks: Marks) -> Self {
Self {
text,
map: ground.map,
allowed: ground.allowed,
budget: ground.budget,
hazards: marks.hazards,
kept: marks.kept,
restores: marks.restores,
next: 0,
at: Cursor::start(),
pass: Pass::default(),
gap: Gap::default(),
pairing: Pairing::default(),
}
}
}
impl Run<'_> {
fn walk(&mut self) -> Result<(), Error> {
while let Some(rest) = self.text.get(self.at.byte..) {
let Some(ch) = rest.chars().next() else { break };
let hazard = self.hazard_here();
let found = self.matched(rest, hazard)?;
self.pairing.step(found.is_none(), ch);
match found {
Some((source, found)) => self.rewrite(source, ch, found)?,
None => self.keep(ch),
}
}
Ok(())
}
fn hazard_here(&mut self) -> Option<Hazard> {
let byte = self.at.byte;
while self.hazards.get(self.next).is_some_and(|h| h.byte < byte) {
self.next = self.next.saturating_add(1);
}
self.hazards
.get(self.next)
.filter(|h| h.byte == byte)
.copied()
}
fn matched<'b>(&self, rest: &'b str, hazard: Option<Hazard>) -> Found<'b> {
if self.pairing.closes(rest) {
return Ok(None);
}
if let Some(found) = self.restored(rest) {
return Ok(Some(found));
}
if let Some(found) = self.mapped(rest, hazard)? {
return Ok(Some(found));
}
Ok(hazard.filter(|h| h.delete).and_then(|_| deleted(rest)))
}
fn restored<'b>(&self, rest: &'b str) -> Option<(&'b str, Match)> {
let at = self
.restores
.binary_search_by_key(&self.at.byte, |r| r.byte)
.ok()?;
let run = self.restores.get(at)?;
let found = Match {
len: run.len,
to: run.to.to_string(),
word: false,
};
Some((rest.get(..run.len)?, found))
}
fn mapped<'b>(&self, rest: &'b str, hazard: Option<Hazard>) -> Found<'b> {
let here = rest.chars().next().filter(|_| hazard.is_some());
let allowed = |c: char| Some(c) != here && (self.allowed)(c);
let Some(found) = self.map.resolve_at(rest, &allowed)? else {
return Ok(None);
};
let spans = |s: &&str| !s.is_empty() && !self.covers_kept(s.len());
let Some(source) = rest.get(..found.len).filter(spans) else {
return Ok(None);
};
let to = self.expand(&found.to)?;
if violates(&to, self.allowed) {
return Ok(None);
}
Ok(Some((source, Match { to, ..found })))
}
fn covers_kept(&self, len: usize) -> bool {
let from = self.at.byte;
let first = self.kept.partition_point(|k| *k < from);
let end = from.saturating_add(len);
self.kept.get(first).is_some_and(|k| *k < end)
}
fn rewrite(
&mut self,
source: &str,
ch: char,
found: Match,
) -> Result<(), Error> {
let to = Gap::spaced(&self.pass.output, found.to, found.word);
let hit = Hit {
position: self.at.position(),
character: ch,
};
self.emit(&to);
if found.word {
self.gap.written(&to);
}
for c in source.chars() {
self.at.advance(c);
}
let len = source.len();
self.pass.spans.push(Span { hit, len, to });
Ok(())
}
fn emit(&mut self, text: &str) {
if self.gap.close(text) {
self.pass.output.push(' ');
if let Some(last) = self.pass.spans.last_mut() {
last.to.push(' ');
}
}
self.pass.output.push_str(text);
}
fn expand(&self, to: &str) -> Result<String, Error> {
let Some(budget) = self.budget.checked_sub(1) else {
return Err(Error::MapCycle);
};
let ground = Ground {
map: self.map,
allowed: self.allowed,
budget,
};
Ok(run(to, ground, Marks::default())?.output)
}
fn keep(&mut self, ch: char) {
if !(self.allowed)(ch) && !self.covers_kept(ch.len_utf8()) {
self.pass.unmapped.push(Hit {
position: self.at.position(),
character: ch,
});
}
self.emit(ch.encode_utf8(&mut [0; 4]));
self.at.advance(ch);
}
}
fn deleted(rest: &str) -> Option<(&str, Match)> {
let ch = rest.chars().next()?;
let source = rest.get(..ch.len_utf8())?;
let found = Match {
len: source.len(),
to: String::new(),
word: false,
};
Some((source, found))
}
#[derive(Debug)]
struct Cursor {
line: usize,
column: usize,
byte: usize,
}
impl Cursor {
fn start() -> Self {
Self {
line: 1,
column: 1,
byte: 0,
}
}
fn position(&self) -> Position {
Position {
line: self.line,
column: self.column,
byte: self.byte,
}
}
fn advance(&mut self, ch: char) {
self.byte = self.byte.saturating_add(ch.len_utf8());
if ch == '\n' {
self.line = self.line.saturating_add(1);
self.column = 1;
} else {
self.column = self.column.saturating_add(1);
}
}
}