use std::cell::RefCell;
use std::collections::HashMap;
use std::path::PathBuf;
use proc_macro2::{Span, TokenStream as Tokens};
use quote::quote;
const SOURCE: &str = "en-US";
pub(crate) const LOCALES: &str = "locales";
pub(crate) struct Catalogue {
dir: String,
messages: HashMap<String, String>,
locales: Vec<String>,
missing: RefCell<Option<syn::Error>>,
}
impl Catalogue {
pub(crate) fn read(dir: &str) -> Self {
let root = std::env::var_os("CARGO_MANIFEST_DIR").map_or_else(PathBuf::new, PathBuf::from);
let path = root.join(dir);
let text = std::fs::read_to_string(path.join(format!("{SOURCE}.ftl"))).unwrap_or_default();
let mut locales: Vec<String> = std::fs::read_dir(&path)
.into_iter()
.flatten()
.flatten()
.filter_map(|entry| {
entry
.file_name()
.to_str()?
.strip_suffix(".ftl")
.map(str::to_owned)
})
.collect();
locales.sort();
Self {
dir: dir.to_owned(),
messages: messages(&text),
locales,
missing: RefCell::new(None),
}
}
pub(crate) fn text(&self, key: &str) -> Option<&str> {
self.messages.get(key).map(String::as_str)
}
pub(crate) fn word(&self, krate: &Tokens, key: &str, text: &str) -> Tokens {
self.word_with(krate, key, text, &[])
}
pub(crate) fn word_with(
&self,
krate: &Tokens,
key: &str,
text: &str,
arguments: &[(syn::Ident, syn::Expr)],
) -> Tokens {
let catalogue = self.reference(krate);
let names = arguments.iter().map(|(name, _)| name.to_string());
let values = arguments.iter().map(|(_, value)| value);
quote! {
#krate::label::Word {
key: #key,
source: #text,
catalogue: ::core::option::Option::Some(#catalogue),
arguments: ::std::vec![ #((#names, #krate::label::Argument::from(#values))),* ],
}
}
}
pub(crate) fn named(
&self,
krate: &Tokens,
span: Span,
key: &str,
arguments: &[(syn::Ident, syn::Expr)],
) -> syn::Result<Tokens> {
let Some(text) = self.text(key) else {
return Err(syn::Error::new(
span,
format!("`{key}` is no message of {}/{SOURCE}.ftl", self.dir),
));
};
let placeables = placeables(text);
for placeable in &placeables {
if !arguments.iter().any(|(name, _)| name == placeable) {
return Err(syn::Error::new(
span,
format!("`{key}` takes `{placeable}`: `word!(\"{key}\", {placeable} = …)`"),
));
}
}
for (name, _) in arguments {
if !placeables
.iter()
.any(|placeable| placeable == &name.to_string())
{
return Err(syn::Error::new(
name.span(),
format!("`{key}` says no `{name}`: its message has no `{{ ${name} }}`"),
));
}
}
Ok(self.word_with(krate, key, text, arguments))
}
pub(crate) fn reference(&self, krate: &Tokens) -> Tokens {
let dir = format!("/{}", self.dir);
let source = format!("{dir}/{SOURCE}.ftl");
let locales = &self.locales;
quote! {
&#krate::label::Catalogue {
id: ::core::env!("CARGO_PKG_NAME"),
source: ::core::include_str!(::core::concat!(::core::env!("CARGO_MANIFEST_DIR"), #source)),
dir: ::core::concat!(::core::env!("CARGO_MANIFEST_DIR"), #dir),
locales: &[#(#locales),*],
}
}
}
pub(crate) fn declared(
&self,
krate: &Tokens,
span: Span,
named: Option<&str>,
derived: &str,
written: &str,
) -> syn::Result<(Tokens, String)> {
let key = named.unwrap_or(derived);
let Some(text) = self.text(key) else {
let file = format!("{}/{SOURCE}.ftl", self.dir);
let error = syn::Error::new(
span,
match named {
Some(words) if !is_key(words) => format!(
"a label is a key of {file}, not words: add `{derived} = {words}` there \
and leave `label` out"
),
Some(_) => format!("`{key}` is no message of {file}"),
None => format!("`{key}` is no message of {file}: add `{key} = {written}`"),
},
);
match &mut *self.missing.borrow_mut() {
Some(all) => all.combine(error),
none => *none = Some(error),
}
return Ok((self.word(krate, key, written), written.to_owned()));
};
if text.contains('{') {
return Err(syn::Error::new(
span,
"a label is plain words: it takes no `{ $argument }`",
));
}
Ok((self.word(krate, key, text), text.to_owned()))
}
}
impl Catalogue {
pub(crate) fn missing(&self) -> syn::Result<()> {
self.missing.take().map_or(Ok(()), Err)
}
}
fn is_key(text: &str) -> bool {
text.contains('-')
&& text
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
}
fn placeables(text: &str) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
if c != '$' || !chars.peek().is_some_and(|c| c.is_alphabetic()) {
continue;
}
let mut name = String::new();
while let Some(&c) = chars.peek() {
if !c.is_alphanumeric() && c != '_' {
break;
}
name.push(c);
chars.next();
}
if !name.is_empty() && !out.contains(&name) {
out.push(name);
}
}
out
}
pub(crate) fn key(scope: &str, id: &str) -> String {
let scope = scope.replace(['.', '_', ':'], "-");
if id.is_empty() {
scope
} else {
format!("{scope}-{id}")
}
}
fn messages(text: &str) -> HashMap<String, String> {
let mut out = HashMap::new();
let mut current: Option<String> = None;
for line in text.lines() {
if line.starts_with(' ') && !line.trim().is_empty() {
let trimmed = line.trim();
if trimmed.starts_with('.') {
current = None;
} else if let Some(key) = ¤t
&& let Some(value) = out.get_mut(key)
{
let value: &mut String = value;
if !value.is_empty() {
value.push(' ');
}
value.push_str(trimmed);
}
continue;
}
current = None;
if line.starts_with('#') || line.starts_with('-') {
continue;
}
let Some((key, value)) = line.split_once('=') else {
continue;
};
let key = key.trim();
if key.is_empty()
|| !key
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
{
continue;
}
out.insert(key.to_owned(), value.trim().to_owned());
current = Some(key.to_owned());
}
out
}