mod case;
#[rustfmt::skip]
#[allow(clippy::unreadable_literal, reason = "generated tables")]
mod case_data;
use crate::catalog::{AtString, Chunk, Entry, Msg, hole_ranges, is_js_space};
use crate::check::LinkError;
use crate::hash::FastMap;
use crate::i18n::LocaleData;
use crate::lazy::{Layer, LinkCtx};
use case::Lang;
use std::sync::Arc;
pub(crate) type ChunkKey = (Arc<str>, Option<Arc<str>>);
pub(crate) type Chunks = Vec<(ChunkKey, Arc<Chunk>)>;
pub(crate) struct Setup<'a> {
pub(crate) links: &'a FastMap<Arc<str>, Arc<str>>,
pub(crate) fallback: Option<&'a str>,
pub(crate) iso: &'a FastMap<Arc<str>, Arc<str>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Broken {
pub(crate) locale: Arc<str>,
pub(crate) page: Option<Arc<str>>,
pub(crate) key: Arc<str>,
pub(crate) link: Box<str>,
pub(crate) reason: LinkError,
}
#[derive(Debug, Clone)]
struct Fail {
link: Box<str>,
reason: LinkError,
}
#[derive(Debug, Clone)]
enum Outcome {
Text(Arc<str>),
Missing,
Broken(Vec<Fail>),
}
enum Got {
Text(Arc<str>),
Missing,
Cycle,
Broken,
}
struct Link<'a> {
len: usize,
modifier: Option<&'a str>,
key: &'a str,
}
fn parse_link(s: &str) -> Option<Link<'_>> {
let rest = s.strip_prefix('@')?;
let (modifier, rest) = match rest.strip_prefix('.') {
Some(r) => {
let n = r.bytes().take_while(u8::is_ascii_alphabetic).count();
let name = r.get(..n).filter(|m| !m.is_empty())?;
(Some(name), r.get(n..)?.strip_prefix(':')?)
}
None => (None, rest.strip_prefix(':')?),
};
let head = s.len() - rest.len();
let (key, used) = match rest.strip_prefix("{'") {
Some(r) => {
let end = r.find('\'')?;
r.get(end + 1..)?.strip_prefix('}')?;
(r.get(..end)?, end + 4)
}
None => {
let end = rest
.find(|c: char| {
is_js_space(c) || matches!(c, '{' | '}' | '@' | '%' | '|' | '(' | ')')
})
.unwrap_or(rest.len());
(rest.get(..end).filter(|k| !k.is_empty())?, end)
}
};
Some(Link {
len: head + used,
modifier,
key,
})
}
fn modify(text: &str, modifier: &str, lang: Lang, out: &mut String) {
let mut at = 0;
let mut first = true;
let mut part = |part: &str, out: &mut String| {
match modifier {
"upper" => case::upper(part, lang, out),
"lower" => case::lower(part, lang, out),
_ if first => {
let n = part.chars().next().map_or(0, char::len_utf8);
case::upper(part.get(..n).unwrap_or(""), lang, out);
out.push_str(part.get(n..).unwrap_or(""));
}
_ => out.push_str(part),
}
first = false;
};
for (s, e) in hole_ranges(text) {
part(text.get(at..s - 1).unwrap_or(""), out);
out.push_str(text.get(s - 1..e + 1).unwrap_or(""));
at = e + 1;
}
part(text.get(at..).unwrap_or(""), out);
}
const MODIFIERS: [&str; 3] = ["upper", "lower", "capitalize"];
struct Resolver<'a> {
layers: Vec<&'a Chunk>,
lang: Lang,
done: FastMap<Box<str>, Outcome>,
active: Vec<Box<str>>,
}
impl<'a> Resolver<'a> {
fn new(layers: Vec<&'a Chunk>, lang: Lang) -> Self {
Resolver {
layers,
lang,
done: FastMap::default(),
active: Vec::new(),
}
}
fn text_at(&self, key: &str) -> Option<Arc<str>> {
match self.layers.iter().find_map(|c| c.link_target(key))? {
Entry::Value(v) if *v == "true" || *v == "false" => None,
e => e.text().map(Arc::from),
}
}
fn target(&mut self, key: &str) -> Got {
if self.active.iter().any(|k| &**k == key) {
return Got::Cycle;
}
if !self.done.contains_key(key) {
let outcome = match self.text_at(key) {
None => Outcome::Missing,
Some(text) => match self.message(key, &text) {
Ok(s) => Outcome::Text(s),
Err(f) => Outcome::Broken(f),
},
};
self.done.insert(key.into(), outcome);
}
match self.done.get(key) {
Some(Outcome::Text(s)) => Got::Text(s.clone()),
Some(Outcome::Missing) | None => Got::Missing,
Some(Outcome::Broken(_)) => Got::Broken,
}
}
fn outcome(&mut self, key: &str) -> Outcome {
self.target(key);
self.done.get(key).cloned().unwrap_or(Outcome::Missing)
}
fn message(&mut self, key: &str, text: &Arc<str>) -> Result<Arc<str>, Vec<Fail>> {
if !text.contains('@') {
return Ok(text.clone());
}
self.active.push(key.into());
let mut out = String::with_capacity(text.len());
let mut fails = Vec::new();
let (mut copied, mut scan) = (0, 0);
while let Some(off) = text.get(scan..).and_then(|t| t.find('@')) {
let start = scan + off;
let Some(link) = text.get(start..).and_then(parse_link) else {
scan = start + 1;
continue;
};
let written = text.get(start..start + link.len).unwrap_or("");
out.push_str(text.get(copied..start).unwrap_or(""));
copied = start + link.len;
scan = copied;
let modifier = match link.modifier {
Some(m) if !MODIFIERS.contains(&m) => {
fails.push(Fail {
link: written.into(),
reason: LinkError::UnknownModifier,
});
out.push_str(written);
continue;
}
m => m,
};
let reason = match self.target(link.key) {
Got::Text(t) => {
match modifier {
Some(m) => modify(&t, m, self.lang, &mut out),
None => out.push_str(&t),
}
continue;
}
Got::Missing => LinkError::Missing,
Got::Cycle => LinkError::Cycle,
Got::Broken => LinkError::Broken,
};
fails.push(Fail {
link: written.into(),
reason,
});
out.push_str(written);
}
out.push_str(text.get(copied..).unwrap_or(""));
self.active.pop();
if fails.is_empty() {
Ok(out.into())
} else {
Err(fails)
}
}
}
fn chain<'a>(setup: &'a Setup<'_>, code: &'a str) -> Vec<&'a str> {
let mut codes: Vec<&str> = Vec::new();
let mut next = Some(code);
while let Some(c) = next {
if codes.contains(&c) {
break;
}
codes.push(c);
next = setup.links.get(c).map(|s| &**s);
}
if let Some(fb) = setup.fallback
&& !codes.contains(&fb)
{
codes.push(fb);
}
codes
}
fn lang(setup: &Setup<'_>, code: &str) -> Lang {
let tag = setup.iso.get(code).map_or(code, |t| &**t);
Lang::of(Some(if tag.is_empty() { code } else { tag }))
}
fn final_text(outcome: &Outcome, raw: &Arc<str>) -> Arc<str> {
match outcome {
Outcome::Text(s) => s.clone(),
_ => raw.clone(),
}
}
#[derive(Clone)]
enum Answer<'c> {
Text(Arc<str>),
Stored(&'c Entry),
}
impl Answer<'_> {
fn shape(&self) -> (u8, Option<&str>) {
match self {
Answer::Text(t) => (0, Some(t)),
Answer::Stored(e @ Entry::Msg(_)) => (0, e.text()),
Answer::Stored(e @ Entry::Value(_)) => (1, e.text()),
Answer::Stored(Entry::Node) => (2, None),
}
}
fn entry(&self) -> Entry {
match self {
Answer::Text(t) => Entry::Msg(Msg::new(t)),
Answer::Stored(e) => (*e).clone(),
}
}
}
fn report(out: &mut Vec<Broken>, view: &ChunkKey, key: &Arc<str>, outcome: &Outcome) {
if let Outcome::Broken(fails) = outcome {
out.extend(fails.iter().map(|f| Broken {
locale: view.0.clone(),
page: view.1.clone(),
key: key.clone(),
link: f.link.clone(),
reason: f.reason,
}));
}
}
fn links(text: &str) -> impl Iterator<Item = Link<'_>> {
let mut scan = 0;
std::iter::from_fn(move || {
while let Some(off) = text.get(scan..).and_then(|t| t.find('@')) {
let start = scan + off;
match text.get(start..).and_then(parse_link) {
Some(link) => {
scan = start + link.len;
return Some(link);
}
None => scan = start + 1,
}
}
None
})
}
type Deps = Vec<(Box<str>, Option<usize>)>;
struct OwnMsg {
s: AtString,
outcome: Outcome,
deps: Deps,
}
struct Views<'c> {
keys: Vec<ChunkKey>,
chunk: Vec<Option<&'c Chunk>>,
path: Vec<Vec<usize>>,
}
impl<'c> Views<'c> {
fn new(chunks: &'c Chunks, setup: &Setup<'_>) -> Views<'c> {
let mut locales: Vec<&Arc<str>> = chunks.iter().map(|((l, _), _)| l).collect();
locales.dedup();
let mut pages: Vec<&Arc<str>> =
chunks.iter().filter_map(|((_, p), _)| p.as_ref()).collect();
pages.sort_unstable();
pages.dedup();
let width = pages.len() + 1;
let index = |locale: &str, page: Option<&str>| -> Option<usize> {
let l = locales.binary_search_by(|x| (***x).cmp(locale)).ok()?;
let p = match page {
None => 0,
Some(p) => pages.binary_search_by(|x| (***x).cmp(p)).ok()? + 1,
};
Some(l * width + p)
};
let mut keys = Vec::with_capacity(locales.len() * width);
for l in &locales {
keys.push(((*l).clone(), None));
keys.extend(pages.iter().map(|p| ((*l).clone(), Some((*p).clone()))));
}
let mut chunk = vec![None; keys.len()];
for ((l, p), c) in chunks {
if let Some(v) = index(l, p.as_deref()) {
chunk[v] = Some(&**c);
}
}
let path = keys
.iter()
.map(|(l, p)| {
let mut out = Vec::new();
for code in chain(setup, l) {
out.extend(p.iter().filter_map(|p| index(code, Some(p))));
out.extend(index(code, None));
}
out
})
.collect();
Views { keys, chunk, path }
}
fn layers(&self, v: usize) -> Vec<(usize, &'c Chunk)> {
self.path[v]
.iter()
.filter_map(|&w| self.chunk[w].map(|c| (w, c)))
.collect()
}
}
fn reach(found: &[(usize, &Chunk)], key: &str) -> Deps {
let mut seen: Deps = Vec::new();
let mut todo: Vec<Box<str>> = vec![key.into()];
while let Some(k) = todo.pop() {
if seen.iter().any(|(s, _)| *s == k) {
continue;
}
let hit = found
.iter()
.find_map(|&(v, c)| c.link_target(&k).map(|e| (v, e)));
if let Some(text) = hit.and_then(|(_, e)| e.text()) {
todo.extend(links(text).map(|l| Box::from(l.key)));
}
seen.push((k, hit.map(|(v, _)| v)));
}
seen
}
fn own_messages(views: &Views<'_>, setup: &Setup<'_>) -> Vec<Vec<OwnMsg>> {
(0..views.keys.len())
.map(|v| {
let Some(chunk) = views.chunk[v] else {
return Vec::new();
};
let mut strings = chunk.strings_with_at();
if strings.is_empty() {
return Vec::new();
}
strings.sort_unstable_by(|a, b| (a.hidden, &a.key).cmp(&(b.hidden, &b.key)));
let found = views.layers(v);
let mut r = Resolver::new(
found.iter().map(|&(_, c)| c).collect(),
lang(setup, &views.keys[v].0),
);
strings
.into_iter()
.map(|s| {
if s.hidden {
let outcome = match r.message(&s.key, &s.raw) {
Ok(t) => Outcome::Text(t),
Err(f) => Outcome::Broken(f),
};
OwnMsg {
s,
outcome,
deps: Deps::new(),
}
} else {
let outcome = r.outcome(&s.key);
let deps = reach(&found, &s.key);
OwnMsg { s, outcome, deps }
}
})
.collect()
})
.collect()
}
fn own_at<'o>(own: &'o [Vec<OwnMsg>], v: usize, key: &str) -> Option<&'o OwnMsg> {
let list = own.get(v)?;
let visible = list.partition_point(|m| !m.s.hidden);
let at = list
.get(..visible)?
.binary_search_by(|m| (*m.s.key).cmp(key))
.ok()?;
list.get(at)
}
type Stored<'c> = Vec<(Box<str>, Answer<'c>)>;
fn stored_at<'s, 'c>(list: &'s Stored<'c>, key: &str) -> Option<&'s Answer<'c>> {
let at = list.binary_search_by(|(k, _)| (**k).cmp(key)).ok()?;
list.get(at).map(|(_, a)| a)
}
fn view_answers<'c>(
views: &Views<'c>,
setup: &Setup<'_>,
own: &[Vec<OwnMsg>],
broken: &mut Vec<Broken>,
) -> Vec<Stored<'c>> {
let after_pass1 = |w: usize, key: &str| -> Option<Answer<'c>> {
match own_at(own, w, key) {
Some(m) => Some(Answer::Text(final_text(&m.outcome, &m.s.raw))),
None => views.chunk[w]?.link_target(key).map(Answer::Stored),
}
};
let n = views.keys.len();
let mut linked: Vec<Stored<'c>> = (0..n).map(|_| Vec::new()).collect();
let mut fresh: Vec<Vec<Box<str>>> = (0..n).map(|_| Vec::new()).collect();
let mut first = true;
loop {
let mut added: Vec<(usize, Box<str>, Answer<'c>, Option<Outcome>)> = Vec::new();
for v in 0..n {
let path = &views.path[v];
let raw = views.layers(v);
let mut keys: Vec<&str> = path
.iter()
.filter(|&&w| w != v)
.flat_map(|&w| fresh[w].iter().map(|k| &**k))
.collect();
if first {
keys.extend(
raw.iter().filter(|&&(w, _)| w != v).flat_map(|&(w, _)| {
own[w].iter().filter(|m| !m.s.hidden).map(|m| &*m.s.key)
}),
);
}
keys.sort_unstable();
keys.dedup();
let mut r: Option<Resolver<'_>> = None;
for key in keys {
if stored_at(&linked[v], key).is_some() {
continue;
}
let Some(&(provider, chunk)) =
raw.iter().find(|(_, c)| c.link_target(key).is_some())
else {
continue;
};
if provider == v {
continue;
}
let (mine, outcome) = match own_at(own, provider, key) {
Some(m)
if lang(setup, &views.keys[v].0)
== lang(setup, &views.keys[provider].0)
&& m.deps.iter().all(|(d, at)| {
let here = raw.iter().find(|(_, c)| c.link_target(d).is_some());
here.map(|&(w, _)| w) == *at
}) =>
{
(
Answer::Text(final_text(&m.outcome, &m.s.raw)),
Some(m.outcome.clone()),
)
}
Some(m) => {
let r = r.get_or_insert_with(|| {
let found = raw.iter().map(|&(_, c)| c).collect();
Resolver::new(found, lang(setup, &views.keys[v].0))
});
let outcome = r.outcome(key);
(Answer::Text(final_text(&outcome, &m.s.raw)), Some(outcome))
}
None => match chunk.link_target(key) {
Some(e) => (Answer::Stored(e), None),
None => continue,
},
};
let current = path.iter().find_map(|&w| {
stored_at(&linked[w], key)
.cloned()
.or_else(|| after_pass1(w, key))
});
if current.is_none_or(|c| c.shape() != mine.shape()) {
added.push((v, Box::from(key), mine, outcome));
}
}
}
if added.is_empty() {
return linked;
}
first = false;
fresh.iter_mut().for_each(Vec::clear);
for (v, key, answer, outcome) in added {
if let Some(o) = &outcome {
report(broken, &views.keys[v], &Arc::from(&*key), o);
}
fresh[v].push(key.clone());
linked[v].push((key, answer));
}
for list in &mut linked {
list.sort_unstable_by(|a, b| a.0.cmp(&b.0));
}
}
}
pub(crate) fn resolve(chunks: &mut Chunks, setup: &Setup<'_>) -> Vec<Broken> {
let mut broken = Vec::new();
let (keys, own, linked) = {
let views = Views::new(chunks, setup);
let own = own_messages(&views, setup);
if own.iter().all(Vec::is_empty) {
return broken;
}
let linked: Vec<Vec<(Box<str>, Entry)>> = view_answers(&views, setup, &own, &mut broken)
.into_iter()
.map(|list| list.into_iter().map(|(k, a)| (k, a.entry())).collect())
.collect();
(views.keys, own, linked)
};
for (v, (done, answers)) in own.into_iter().zip(linked).enumerate() {
if done.is_empty() && answers.is_empty() {
continue;
}
let key = &keys[v];
let at = match chunks.binary_search_by(|(k, _)| k.cmp(key)) {
Ok(at) => at,
Err(at) => {
chunks.insert(at, (key.clone(), Arc::default()));
at
}
};
let Some((_, chunk)) = chunks.get_mut(at) else {
continue;
};
let chunk = Arc::make_mut(chunk);
for m in done {
match &m.outcome {
Outcome::Text(t) if *t != m.s.raw => chunk.set_message(&m.s.key, m.s.own, t),
Outcome::Broken(_) if !m.s.hidden => report(&mut broken, key, &m.s.key, &m.outcome),
_ => {}
}
}
for (k, entry) in answers {
chunk.insert_linked(&k, entry);
}
}
broken.sort_unstable_by(|a, b| {
(&a.locale, &a.page, &a.key, &a.link).cmp(&(&b.locale, &b.page, &b.key, &b.link))
});
broken
}
pub(crate) fn lazy_contexts(data: &FastMap<Arc<str>, LocaleData>, setup: &Setup<'_>) {
for (code, d) in data {
let pairs = std::iter::once((None, d.root.as_ref()))
.chain(d.pages.iter().map(|(p, l)| (Some(p), Some(l))));
for (page, layer) in pairs {
let Some(Layer::Lazy(cell)) = layer else {
continue;
};
let mut layers = Vec::new();
for c in chain(setup, code) {
let c: Arc<str> = data
.get_key_value(c)
.map_or_else(|| Arc::from(c), |(k, _)| k.clone());
for p in page.into_iter().map(|p| Some(p.clone())).chain([None]) {
if c == *code && p.as_ref() == page {
continue;
}
layers.push((c.clone(), p));
}
}
let tag = setup
.iso
.get(code)
.filter(|t| !t.is_empty())
.unwrap_or(code);
let _ = cell.linked.set(Arc::new(LinkCtx {
layers,
tag: tag.clone(),
resolve: resolve_tree,
}));
}
}
}
pub(crate) fn mark_lazy(
broken: &mut [Broken],
data: &FastMap<Arc<str>, LocaleData>,
setup: &Setup<'_>,
) {
for b in broken.iter_mut().filter(|b| b.reason == LinkError::Missing) {
let lazy = chain(setup, &b.locale).into_iter().any(|c| {
data.get(c).is_some_and(|d| {
[
b.page.as_deref().and_then(|p| d.layer(Some(p))),
d.layer(None),
]
.into_iter()
.any(|l| matches!(l, Some(Layer::Lazy(_))))
})
});
if lazy {
b.reason = LinkError::Lazy;
}
}
}
fn resolve_tree(tree: &mut Chunk, others: &[&Chunk], tag: &str) {
let mut strings = tree.strings_with_at();
if strings.is_empty() {
return;
}
strings.sort_unstable_by(|a, b| (a.hidden, &a.key).cmp(&(b.hidden, &b.key)));
let done: Vec<(AtString, Option<Arc<str>>)> = {
let layers = std::iter::once(&*tree)
.chain(others.iter().copied())
.collect();
let mut r = Resolver::new(layers, Lang::of(Some(tag)));
strings
.into_iter()
.map(|s| {
let text = if s.hidden {
r.message(&s.key, &s.raw).ok()
} else {
match r.outcome(&s.key) {
Outcome::Text(t) => Some(t),
_ => None,
}
};
(s, text)
})
.collect()
};
for (s, text) in done {
if let Some(t) = text.filter(|t| *t != s.raw) {
tree.set_message(&s.key, s.own, &t);
}
}
}