use std::collections::BTreeMap;
use std::convert::Infallible;
use std::fmt;
use std::sync::Arc;
use techy::core::node::{BuildId, NodeKind, NodeRef, NodeTree};
use techy::core::{Lang, ParsingState};
use techy::error::Severity;
use techy::source::{SourceSpan, TextContent};
use techy::transform::{Restage, RestageContext, RestageError, RestageVisitor};
use crate::model::addr::NodeAddr;
use crate::model::doc::FragmentLayout;
use crate::model::names::Name;
use crate::lang::guard::{self, GuardPolicy};
use crate::lang::{
parse_fragment, BuiltLang, Flm, FlmDiagnostic, FlmOrigin, FlmSource, FlmSpan, ParseOptions,
};
use crate::lang::rewrites::userdefs::template::TemplateLanguage;
use super::formats::{CompiledNumber, NumberFormat, NumberPart, NumberTemplate};
use super::joiner::{CompiledWithinJoiner, JoinCx, Part};
use super::template::{instantiate_template, Binding, Bindings};
use super::value::CounterValue;
use super::writer::{
default_writer, CompiledNumberWriter, JoinText, NumberOut, NumberWriter, NumberedValue,
WriteCx, WriterCx,
};
#[derive(Clone, Debug)]
pub enum StyleError {
Template {
text: String,
diagnostics: Vec<FlmDiagnostic>,
},
UnknownKey {
text: String,
key: String,
},
UnknownJoiner {
name: Name,
},
UnknownWriter {
name: Name,
},
UnknownVariable {
text: String,
name: String,
},
Parse {
text: String,
diagnostics: Vec<FlmDiagnostic>,
},
ParseFailed {
text: String,
detail: String,
},
}
impl StyleError {
pub(super) fn in_text(self, text: &str) -> StyleError {
let text = text.to_string();
match self {
StyleError::Template { diagnostics, .. } => StyleError::Template { text, diagnostics },
StyleError::UnknownKey { key, .. } => StyleError::UnknownKey { text, key },
StyleError::UnknownJoiner { name } => StyleError::UnknownJoiner { name },
StyleError::UnknownWriter { name } => StyleError::UnknownWriter { name },
StyleError::UnknownVariable { name, .. } => StyleError::UnknownVariable { text, name },
StyleError::Parse { diagnostics, .. } => StyleError::Parse { text, diagnostics },
StyleError::ParseFailed { detail, .. } => StyleError::ParseFailed { text, detail },
}
}
}
impl fmt::Display for StyleError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let messages = |diagnostics: &[FlmDiagnostic]| {
let joined: Vec<String> =
diagnostics.iter().map(|diagnostic| diagnostic.message()).collect();
if joined.is_empty() { String::new() } else { format!(": {}", joined.join("; ")) }
};
match self {
StyleError::Template { text, diagnostics } => write!(
f,
"Invalid template ‘{text}’{}",
messages(diagnostics)
),
StyleError::UnknownKey { text, key } => write!(
f,
"Invalid key ‘{key}’ in template ‘{text}’: keys in \
brackets must be ‘bare’ or the name of a number format"
),
StyleError::UnknownJoiner { name } => {
write!(f, "Unknown within-joiner ‘{name}’")
}
StyleError::UnknownWriter { name } => {
write!(f, "Unknown number writer ‘{name}’")
}
StyleError::UnknownVariable { text, name } => write!(
f,
"Unknown join key ‘{name}’ in join text ‘{text}’"
),
StyleError::Parse { text, diagnostics } => write!(
f,
"Invalid FLM text ‘{text}’{}",
messages(diagnostics)
),
StyleError::ParseFailed { text, detail } => {
write!(f, "Failed to parse ‘{text}’: {detail}")
}
}
}
}
impl std::error::Error for StyleError {}
#[derive(Clone, Debug)]
pub enum FormatError {
UndeclaredSubLevel {
style: Name,
level: usize,
number: i64,
},
UnknownAncestor {
joiner: String,
counter: Name,
},
NestingTooDeep {
detail: String,
},
Failed {
detail: String,
},
}
impl fmt::Display for FormatError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
FormatError::UndeclaredSubLevel { style, level, number } => write!(
f,
"the counter style `{style}` must declare a format for sub-level {level} \
(counting the first sub-level as 0), since the value has the sub-number \
{number} there"
),
FormatError::UnknownAncestor { joiner, counter } => write!(
f,
"the within-joiner `{joiner}` may write only counters this number is numbered \
within, but it writes the counter `{counter}`"
),
FormatError::NestingTooDeep { detail } => {
write!(f, "the content nests too deeply to write a number with: {detail}")
}
FormatError::Failed { detail } => write!(f, "writing the number failed: {detail}"),
}
}
}
impl std::error::Error for FormatError {}
#[derive(Clone, PartialEq, Eq, Debug, Default, serde::Deserialize, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct Delimiters {
pub open: String,
pub close: String,
}
impl Delimiters {
pub fn new(open: impl Into<String>, close: impl Into<String>) -> Delimiters {
Delimiters { open: open.into(), close: close.into() }
}
}
#[derive(Clone, PartialEq, Eq, Debug, Default, serde::Deserialize, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct PluralWords {
pub one: String,
pub other: String,
}
impl PluralWords {
pub fn new(one: impl Into<String>, other: impl Into<String>) -> PluralWords {
PluralWords { one: one.into(), other: other.into() }
}
pub fn same(word: impl Into<String>) -> PluralWords {
let word = word.into();
PluralWords { one: word.clone(), other: word }
}
}
#[derive(Clone, PartialEq, Eq, Debug, Default, serde::Deserialize, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct PrefixWords {
pub base: PluralWords,
pub variants: BTreeMap<String, PluralWords>,
}
impl PrefixWords {
pub fn new(one: impl Into<String>, other: impl Into<String>) -> PrefixWords {
PrefixWords { base: PluralWords::new(one, other), variants: BTreeMap::new() }
}
pub fn with_variant(mut self, name: impl Into<String>, variant: PluralWords) -> PrefixWords {
self.variants.insert(name.into(), variant);
self
}
}
#[derive(Clone, PartialEq, Eq, Debug, serde::Deserialize, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct SubLevelDecl {
pub separator: String,
pub number_format: NumberTemplate,
}
impl SubLevelDecl {
pub fn new(separator: impl Into<String>, number_format: NumberTemplate) -> SubLevelDecl {
SubLevelDecl { separator: separator.into(), number_format }
}
}
#[derive(Clone, PartialEq, Eq, Debug, Default, serde::Deserialize, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct JoinDecl {
pub one_pre: Option<String>,
pub one_post: Option<String>,
pub pair_pre: Option<String>,
pub pair_mid: Option<String>,
pub pair_post: Option<String>,
pub range_pre: Option<String>,
pub range_mid: Option<String>,
pub range_pairmid: Option<String>,
pub range_post: Option<String>,
pub list_pre: Option<String>,
pub list_mid: Option<String>,
pub list_midlast: Option<String>,
pub list_post: Option<String>,
pub and: Option<String>,
pub sep: Option<String>,
pub endash: Option<String>,
pub empty: Option<String>,
}
impl JoinDecl {
pub fn texts(&self) -> [&Option<String>; 17] {
[
&self.one_pre,
&self.one_post,
&self.pair_pre,
&self.pair_mid,
&self.pair_post,
&self.range_pre,
&self.range_mid,
&self.range_pairmid,
&self.range_post,
&self.list_pre,
&self.list_mid,
&self.list_midlast,
&self.list_post,
&self.and,
&self.sep,
&self.endash,
&self.empty,
]
}
pub(crate) fn digest_into(&self, out: &mut Vec<u8>) {
for text in self.texts() {
out.push(u8::from(text.is_some()));
super::decl::digest_text(out, text.as_deref().unwrap_or(""));
}
}
pub fn compact() -> JoinDecl {
JoinDecl {
pair_mid: Some(",".to_string()),
range_pairmid: Some(",".to_string()),
list_mid: Some(",".to_string()),
list_midlast: Some(",".to_string()),
..JoinDecl::default()
}
}
}
#[derive(Clone, PartialEq, Eq, Debug, serde::Deserialize, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(transform = style_schema)]
pub struct CounterStyleDecl {
#[schemars(skip)]
pub name: Name,
pub number_format: NumberTemplate,
pub sub_levels: Vec<SubLevelDecl>,
pub prefix_words: PrefixWords,
pub delimiters: Delimiters,
pub join: JoinDecl,
pub name_in_link: bool,
pub repeat_parents_in_range: bool,
pub ranges: bool,
pub number_writer: Option<Name>,
}
fn style_schema(schema: &mut schemars::Schema) {
crate::core::settings::named::require_only(schema, &[]);
}
impl CounterStyleDecl {
pub fn new(name: impl Into<Name>) -> CounterStyleDecl {
CounterStyleDecl {
name: name.into(),
number_format: NumberTemplate::formats("#{arabic}"),
sub_levels: Vec::new(),
prefix_words: PrefixWords::default(),
delimiters: Delimiters::default(),
join: JoinDecl::default(),
name_in_link: true,
repeat_parents_in_range: false,
ranges: true,
number_writer: None,
}
}
pub fn with_number_writer(mut self, name: impl Into<Name>) -> CounterStyleDecl {
self.number_writer = Some(name.into());
self
}
pub fn compile(&self, lang: &BuiltLang) -> Result<CounterStyle, StyleError> {
let language = TemplateLanguage::new(lang).map_err(|errors| StyleError::ParseFailed {
text: self.number_format.text().to_string(),
detail: errors.iter().map(ToString::to_string).collect::<Vec<_>>().join("; "),
})?;
self.compile_with(lang, &language, &[])
}
pub fn compile_with(
&self,
lang: &BuiltLang,
language: &TemplateLanguage,
writers: &[Arc<dyn NumberWriter>],
) -> Result<CounterStyle, StyleError> {
let mut warnings = Vec::new();
let blank = parse_text("", lang, &mut warnings)?;
let number =
CompiledNumber::compile(&self.number_format, &self.name, lang, language, &mut warnings)?;
let mut sub_levels = Vec::with_capacity(self.sub_levels.len());
for level in &self.sub_levels {
sub_levels.push(CompiledSubLevel {
separator: parse_text(&level.separator, lang, &mut warnings)?,
number: CompiledNumber::compile(
&level.number_format,
&self.name,
lang,
language,
&mut warnings,
)?,
});
}
let writer = match &self.number_writer {
None => Arc::clone(default_writer()),
Some(name) => {
let Some(declared) = writers.iter().find(|writer| writer.name() == name) else {
return Err(StyleError::UnknownWriter { name: name.clone() });
};
declared.compile(&WriterCx::new(lang, &self.name))?
}
};
let words = CompiledWords {
base: compile_words(&self.prefix_words.base, lang, &mut warnings)?,
variants: self
.prefix_words
.variants
.iter()
.map(|(name, words)| {
compile_words(words, lang, &mut warnings).map(|words| (name.clone(), words))
})
.collect::<Result<BTreeMap<_, _>, _>>()?,
};
Ok(CounterStyle {
name: self.name.clone(),
number,
sub_levels: Arc::new(sub_levels),
words: Arc::new(words),
open: parse_text(&self.delimiters.open, lang, &mut warnings)?,
close: parse_text(&self.delimiters.close, lang, &mut warnings)?,
join: Arc::new(CompiledJoin::compile(
&self.join,
STYLE_TEXT_ORIGIN,
lang,
&mut warnings,
)?),
name_in_link: self.name_in_link,
repeat_parents_in_range: self.repeat_parents_in_range,
ranges: self.ranges,
writer,
state: Arc::clone(lang.initial_state()),
blank,
warnings,
})
}
}
struct CompiledSubLevel {
separator: Arc<NodeTree<Flm>>,
number: CompiledNumber,
}
struct CompiledPlural {
one: Arc<NodeTree<Flm>>,
other: Arc<NodeTree<Flm>>,
}
struct CompiledWords {
base: CompiledPlural,
variants: BTreeMap<String, CompiledPlural>,
}
pub(crate) struct CompiledJoin {
pub(super) one_pre: Arc<NodeTree<Flm>>,
pub(super) one_post: Arc<NodeTree<Flm>>,
pub(super) pair_pre: Arc<NodeTree<Flm>>,
pub(super) pair_mid: Arc<NodeTree<Flm>>,
pub(super) pair_post: Arc<NodeTree<Flm>>,
pub(super) range_pre: Arc<NodeTree<Flm>>,
pub(super) range_mid: Arc<NodeTree<Flm>>,
pub(super) range_pairmid: Arc<NodeTree<Flm>>,
pub(super) range_post: Arc<NodeTree<Flm>>,
pub(super) list_pre: Arc<NodeTree<Flm>>,
pub(super) list_mid: Arc<NodeTree<Flm>>,
pub(super) list_midlast: Arc<NodeTree<Flm>>,
pub(super) list_post: Arc<NodeTree<Flm>>,
pub(super) empty: Arc<NodeTree<Flm>>,
}
pub struct CounterStyle {
name: Name,
number: CompiledNumber,
sub_levels: Arc<Vec<CompiledSubLevel>>,
words: Arc<CompiledWords>,
open: Arc<NodeTree<Flm>>,
close: Arc<NodeTree<Flm>>,
join: Arc<CompiledJoin>,
name_in_link: bool,
repeat_parents_in_range: bool,
ranges: bool,
writer: Arc<dyn CompiledNumberWriter>,
state: Arc<ParsingState<Flm>>,
blank: Arc<NodeTree<Flm>>,
warnings: Vec<FlmDiagnostic>,
}
impl fmt::Debug for CounterStyle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CounterStyle").field("name", &self.name.as_str()).finish_non_exhaustive()
}
}
impl CounterStyle {
pub fn name(&self) -> &Name {
&self.name
}
pub fn warnings(&self) -> &[FlmDiagnostic] {
&self.warnings
}
pub fn with_number_format(
&self,
template: &NumberTemplate,
lang: &BuiltLang,
language: &TemplateLanguage,
) -> Result<CounterStyle, StyleError> {
let mut warnings = self.warnings.clone();
let number = CompiledNumber::compile(template, &self.name, lang, language, &mut warnings)?;
Ok(CounterStyle {
name: self.name.clone(),
number,
sub_levels: Arc::clone(&self.sub_levels),
words: Arc::clone(&self.words),
open: Arc::clone(&self.open),
close: Arc::clone(&self.close),
join: Arc::clone(&self.join),
name_in_link: self.name_in_link,
repeat_parents_in_range: self.repeat_parents_in_range,
ranges: self.ranges,
writer: Arc::clone(&self.writer),
state: Arc::clone(&self.state),
blank: Arc::clone(&self.blank),
warnings,
})
}
pub fn declares_variant(&self, name: &str) -> bool {
self.words.variants.contains_key(name)
}
pub fn sub_level_count(&self) -> usize {
self.sub_levels.len()
}
pub fn literal(&self, text: &str) -> Result<Arc<NodeTree<Flm>>, FormatError> {
let pieces = [Piece::Digits(text.to_string())];
on_worker(|| assemble_pieces(self, &pieces))
}
pub(super) fn site(&self) -> FlmSpan {
let at: &FlmSpan = self.blank.root().span();
SourceSpan::new(at.source(), at.start()..at.start())
}
fn word(&self, count: usize, variant: Option<&str>) -> &Arc<NodeTree<Flm>> {
let words = variant
.and_then(|variant| self.words.variants.get(variant))
.unwrap_or(&self.words.base);
if count == 1 {
&words.one
} else {
&words.other
}
}
}
#[derive(Clone, Debug)]
pub struct Ancestor {
pub counter: Name,
pub value: CounterValue,
pub style: Arc<CounterStyle>,
pub joiner: Option<Arc<dyn CompiledWithinJoiner>>,
pub instance: Option<NodeAddr>,
}
impl Ancestor {
pub fn new(counter: impl Into<Name>, value: CounterValue, style: Arc<CounterStyle>) -> Ancestor {
Ancestor { counter: counter.into(), value, style, joiner: None, instance: None }
}
pub fn in_instance(mut self, instance: NodeAddr) -> Ancestor {
self.instance = Some(instance);
self
}
pub fn within(mut self, joiner: Arc<dyn CompiledWithinJoiner>) -> Ancestor {
self.joiner = Some(joiner);
self
}
}
#[derive(Clone, Copy, Debug)]
pub struct Parent<'a> {
pub joiner: &'a dyn CompiledWithinJoiner,
pub ancestors: &'a [Ancestor],
}
impl<'a> Parent<'a> {
pub fn new(
joiner: &'a dyn CompiledWithinJoiner,
ancestors: &'a [Ancestor],
) -> Parent<'a> {
Parent { joiner, ancestors }
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct FormatOptions {
pub variant: Option<String>,
pub with_word: bool,
pub with_delimiters: bool,
}
impl Default for FormatOptions {
fn default() -> FormatOptions {
FormatOptions { variant: None, with_word: true, with_delimiters: true }
}
}
impl FormatOptions {
pub fn new() -> FormatOptions {
FormatOptions::default()
}
pub fn variant(mut self, variant: impl Into<String>) -> FormatOptions {
self.variant = Some(variant.into());
self
}
pub fn without_word(mut self) -> FormatOptions {
self.with_word = false;
self
}
pub fn without_delimiters(mut self) -> FormatOptions {
self.with_delimiters = false;
self
}
}
pub struct Segment {
content: Arc<NodeTree<Flm>>,
link: Option<usize>,
}
impl fmt::Debug for Segment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Segment").field("link", &self.link).finish_non_exhaustive()
}
}
impl Segment {
pub fn content(&self) -> &Arc<NodeTree<Flm>> {
&self.content
}
pub fn link(&self) -> Option<usize> {
self.link
}
}
pub fn format(
value: &CounterValue,
style: &CounterStyle,
parent: Option<Parent<'_>>,
options: &FormatOptions,
) -> Result<Vec<Segment>, FormatError> {
on_worker(|| {
let mut numbered = NumberedValue::new(value);
if let Some(parent) = parent {
numbered = numbered.within(parent);
}
let cx = WriteCx::new(style);
let mut out = NumberOut::new();
style.writer().write_one(&numbered, options, &cx, &mut out)?;
segments(style, out.into_items())
})
}
pub(super) fn default_one<'a>(
value: &NumberedValue<'a>,
options: &FormatOptions,
cx: &WriteCx<'a>,
out: &mut NumberOut<'a>,
) -> Result<(), FormatError> {
let style = cx.style();
let mut pieces = Vec::new();
if options.with_word {
pieces.push(Piece::Flm(style.word(1, options.variant.as_deref())));
}
if options.with_delimiters {
pieces.push(Piece::Flm(&style.open));
}
let own = value.value();
let sub_numbers: Vec<Option<i64>> = own.sub_numbers().iter().map(|n| Some(*n)).collect();
number_pieces(style, Some(own.number()), &sub_numbers, Some((value, cx)), &mut pieces)?;
if options.with_delimiters {
pieces.push(Piece::Flm(&style.close));
}
out.item(Item { pieces, mark: Mark::Value(value.index()) });
Ok(())
}
pub fn parts(style: &CounterStyle, parent: Parent<'_>) -> Result<Vec<Part>, FormatError> {
on_worker(|| {
let cx = JoinCx::new(style);
parent.joiner.parts(parent.ancestors, &cx)
})
}
pub(super) enum Piece<'a> {
Flm(&'a Arc<NodeTree<Flm>>),
Tree(Arc<NodeTree<Flm>>),
Digits(String),
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum Mark {
Never,
Either,
Value(usize),
}
pub(super) struct Item<'a> {
pub(super) pieces: Vec<Piece<'a>>,
pub(super) mark: Mark,
}
impl<'a> Item<'a> {
pub(super) fn text(tree: &'a Arc<NodeTree<Flm>>, mark: Mark) -> Item<'a> {
Item { pieces: vec![Piece::Flm(tree)], mark }
}
}
pub(super) fn number_pieces<'a>(
style: &'a CounterStyle,
number: Option<i64>,
sub_numbers: &[Option<i64>],
within: Option<(&NumberedValue<'a>, &WriteCx<'a>)>,
out: &mut Vec<Piece<'a>>,
) -> Result<(), FormatError> {
let mut wrote_something = false;
if let Some(number) = number {
if style.number.with_parent() {
if let Some((value, cx)) = within {
for part in cx.parts(value)? {
out.push(Piece::Tree(part.content));
}
}
}
template_pieces(style, &style.number, number, out)?;
wrote_something = true;
}
sub_level_pieces(style, sub_numbers, None, &mut wrote_something, out)
}
fn sub_level_pieces<'a>(
style: &'a CounterStyle,
sub_numbers: &[Option<i64>],
format: Option<NumberFormat>,
wrote_something: &mut bool,
out: &mut Vec<Piece<'a>>,
) -> Result<(), FormatError> {
for (level, sub_number) in sub_numbers.iter().enumerate() {
let Some(sub_number) = *sub_number else { continue };
if sub_number == 0 {
continue;
}
let Some(declared) = style.sub_levels.get(level) else {
return Err(FormatError::UndeclaredSubLevel {
style: style.name.clone(),
level,
number: sub_number,
});
};
if *wrote_something {
out.push(Piece::Flm(&declared.separator));
}
match format {
Some(format) => out.push(Piece::Digits(format.text(sub_number))),
None => template_pieces(style, &declared.number, sub_number, out)?,
}
*wrote_something = true;
}
Ok(())
}
fn template_pieces<'a>(
style: &CounterStyle,
template: &'a CompiledNumber,
number: i64,
out: &mut Vec<Piece<'a>>,
) -> Result<(), FormatError> {
match template {
CompiledNumber::Initial { parts, .. } => {
for part in parts {
match part {
NumberPart::Literal(tree) => out.push(Piece::Flm(tree)),
NumberPart::Number(format) => out.push(Piece::Digits(format.text(number))),
}
}
Ok(())
}
CompiledNumber::Written { template, formats } => {
let mut entries = Vec::with_capacity(formats.len());
for format in formats {
entries.push(Binding {
name: format.written_name().to_string(),
keys: String::new(),
content: assemble_pieces(style, &[Piece::Digits(format.text(number))])?,
});
}
let bindings = Bindings::new(entries);
out.push(Piece::Tree(instantiate_template(&style.site(), template, &bindings)?));
Ok(())
}
}
}
pub(super) fn number_tree(
style: &CounterStyle,
value: &CounterValue,
format: Option<NumberFormat>,
) -> Result<Arc<NodeTree<Flm>>, FormatError> {
let sub_numbers: Vec<Option<i64>> = value.sub_numbers().iter().map(|n| Some(*n)).collect();
let mut pieces = Vec::new();
match format {
None => number_pieces(style, Some(value.number()), &sub_numbers, None, &mut pieces)?,
Some(format) => {
pieces.push(Piece::Digits(format.text(value.number())));
let mut wrote_something = true;
sub_level_pieces(style, &sub_numbers, Some(format), &mut wrote_something, &mut pieces)?;
}
}
assemble_pieces(style, &pieces)
}
pub(super) fn segments(
style: &CounterStyle,
items: Vec<Item<'_>>,
) -> Result<Vec<Segment>, FormatError> {
let mut merged: Vec<Item<'_>> = Vec::new();
for item in items {
match merged.last_mut() {
Some(last) if last.mark == Mark::Never && item.mark == Mark::Never => {
last.pieces.extend(item.pieces);
continue;
}
Some(last)
if last.mark != Mark::Never
&& item.mark != Mark::Never
&& (item.mark == Mark::Either
|| last.mark == Mark::Either
|| item.mark == last.mark) =>
{
if let (Mark::Value(_), Mark::Either) = (item.mark, last.mark) {
last.mark = item.mark;
}
last.pieces.extend(item.pieces);
continue;
}
_ => {}
}
merged.push(item);
}
let mut out = Vec::with_capacity(merged.len());
for item in merged {
let link = match item.mark {
Mark::Value(position) => Some(position),
Mark::Never | Mark::Either => None,
};
let content = assemble_pieces(style, &item.pieces)?;
if link.is_none() && content.root().child_count() == 0 {
continue;
}
out.push(Segment { content, link });
}
Ok(out)
}
pub(super) fn on_worker<T: Send>(
work: impl FnOnce() -> Result<T, FormatError> + Send,
) -> Result<T, FormatError> {
match guard::on_worker_thread(work) {
Ok(result) => result,
Err(error) => Err(FormatError::Failed { detail: error.to_string() }),
}
}
pub(super) const STYLE_TEXT_ORIGIN: &str = "counter style text";
pub(super) fn parse_text(
text: &str,
lang: &BuiltLang,
warnings: &mut Vec<FlmDiagnostic>,
) -> Result<Arc<NodeTree<Flm>>, StyleError> {
parse_text_from(text, STYLE_TEXT_ORIGIN, lang, warnings)
}
fn parse_text_from(
text: &str,
origin: &str,
lang: &BuiltLang,
warnings: &mut Vec<FlmDiagnostic>,
) -> Result<Arc<NodeTree<Flm>>, StyleError> {
let origin = FlmOrigin::synthetic(origin);
let source = Arc::new(FlmSource::new(text.to_string()).with_origin(origin));
let fragment =
parse_fragment(lang, source, FragmentLayout::default(), &ParseOptions::default())
.map_err(|error| StyleError::ParseFailed {
text: text.to_string(),
detail: error.to_string(),
})?;
let errors: Vec<FlmDiagnostic> = fragment
.diags()
.iter()
.filter(|diagnostic| diagnostic.severity() == Severity::Error)
.cloned()
.collect();
if !errors.is_empty() {
return Err(StyleError::Parse { text: text.to_string(), diagnostics: errors });
}
warnings.extend(
fragment
.diags()
.iter()
.filter(|diagnostic| diagnostic.severity() != Severity::Error)
.cloned(),
);
Ok(Arc::clone(fragment.tree()))
}
fn compile_words(
words: &PluralWords,
lang: &BuiltLang,
warnings: &mut Vec<FlmDiagnostic>,
) -> Result<CompiledPlural, StyleError> {
Ok(CompiledPlural {
one: parse_text(&words.one, lang, warnings)?,
other: parse_text(&words.other, lang, warnings)?,
})
}
struct Verbatim;
impl RestageVisitor<Flm, (), ()> for Verbatim {
type Error = Infallible;
fn restage(
&mut self,
_node: NodeRef<'_, Flm>,
_cx: &mut RestageContext<'_, Flm, (), ()>,
) -> Result<Restage<()>, Infallible> {
Ok(Restage::Descend(()))
}
}
struct Assemble<'a, 'p> {
style: &'a CounterStyle,
pieces: &'p [Piece<'a>],
}
impl RestageVisitor<Flm, (), ()> for Assemble<'_, '_> {
type Error = FormatError;
fn restage(
&mut self,
root: NodeRef<'_, Flm>,
cx: &mut RestageContext<'_, Flm, (), ()>,
) -> Result<Restage<()>, FormatError> {
let mut children: Vec<BuildId> = Vec::new();
for piece in self.pieces {
match piece {
Piece::Flm(tree) => {
for node in tree.root().children().iter() {
let copied = cx
.restage_subtree(node, &mut Verbatim)
.map_err(|error| failed(&error))?;
children.extend(copied);
}
}
Piece::Tree(tree) => {
for node in tree.root().children().iter() {
let copied = cx
.restage_subtree(node, &mut Verbatim)
.map_err(|error| failed(&error))?;
children.extend(copied);
}
}
Piece::Digits(text) if !text.is_empty() => {
children.push(self.digits(cx, text)?);
}
Piece::Digits(_) => {}
}
}
let span = SourceSpan::new(root.span().source(), root.span().start()..root.span().start());
let state = Arc::clone(&self.style.state);
let kind = NodeKind::list();
let ext = Flm::make_node_ext(&kind, &span, &state, cx.builder().staged_children(&children))
.map_err(|error| FormatError::Failed { detail: error.to_string() })?;
let list = cx
.builder()
.add(kind, span, state, children, ext, ())
.map_err(|error| FormatError::Failed { detail: error.to_string() })?;
Ok(Restage::Emit(vec![list]))
}
}
impl Assemble<'_, '_> {
fn digits(
&self,
cx: &mut RestageContext<'_, Flm, (), ()>,
text: &str,
) -> Result<BuildId, FormatError> {
let at: &FlmSpan = self.style.blank.root().span();
let span = SourceSpan::new(at.source(), at.start()..at.start());
let state = Arc::clone(&self.style.state);
let kind = NodeKind::chars(TextContent::Owned(Box::from(text)));
let ext = Flm::make_node_ext(&kind, &span, &state, cx.builder().staged_children(&[]))
.map_err(|error| FormatError::Failed { detail: error.to_string() })?;
cx.builder()
.add(kind, span, state, Vec::new(), ext, ())
.map_err(|error| FormatError::Failed { detail: error.to_string() })
}
}
fn failed<E: fmt::Display>(error: &RestageError<E>) -> FormatError {
match error {
RestageError::DescentLimitExceeded { detail, .. } => {
FormatError::NestingTooDeep { detail: detail.clone() }
}
other => FormatError::Failed { detail: other.to_string() },
}
}
pub(super) fn assemble_pieces(
style: &CounterStyle,
pieces: &[Piece<'_>],
) -> Result<Arc<NodeTree<Flm>>, FormatError> {
let mut visitor = Assemble { style, pieces };
guard::restager(&mut visitor, GuardPolicy::StackBudget)
.restage(&style.blank)
.map_err(|error| failed(&error))
.map(Arc::new)
}
const JOIN_DEFAULTS: [(&str, &str); 17] = [
("one_pre", ""),
("one_post", ""),
("pair_pre", ""),
("pair_mid", " ${and} "),
("pair_post", ""),
("range_pre", ""),
("range_mid", "${endash}"),
("range_pairmid", "${sep}"),
("range_post", ""),
("list_pre", ""),
("list_mid", "${sep} "),
("list_midlast", "${sep} ${and} "),
("list_post", ""),
("and", "and"),
("sep", ","),
("endash", "\u{2013}"),
("empty", "(empty)"),
];
impl CompiledJoin {
pub(crate) fn text(&self, which: JoinText) -> &Arc<NodeTree<Flm>> {
match which {
JoinText::OnePre => &self.one_pre,
JoinText::OnePost => &self.one_post,
JoinText::PairPre => &self.pair_pre,
JoinText::PairMid => &self.pair_mid,
JoinText::PairPost => &self.pair_post,
JoinText::RangePre => &self.range_pre,
JoinText::RangeMid => &self.range_mid,
JoinText::RangePairMid => &self.range_pairmid,
JoinText::RangePost => &self.range_post,
JoinText::ListPre => &self.list_pre,
JoinText::ListMid => &self.list_mid,
JoinText::ListMidLast => &self.list_midlast,
JoinText::ListPost => &self.list_post,
JoinText::Empty => &self.empty,
}
}
pub(crate) fn compile(
decl: &JoinDecl,
origin: &str,
lang: &BuiltLang,
warnings: &mut Vec<FlmDiagnostic>,
) -> Result<CompiledJoin, StyleError> {
let declared: [(&str, &Option<String>); 17] = [
("one_pre", &decl.one_pre),
("one_post", &decl.one_post),
("pair_pre", &decl.pair_pre),
("pair_mid", &decl.pair_mid),
("pair_post", &decl.pair_post),
("range_pre", &decl.range_pre),
("range_mid", &decl.range_mid),
("range_pairmid", &decl.range_pairmid),
("range_post", &decl.range_post),
("list_pre", &decl.list_pre),
("list_mid", &decl.list_mid),
("list_midlast", &decl.list_midlast),
("list_post", &decl.list_post),
("and", &decl.and),
("sep", &decl.sep),
("endash", &decl.endash),
("empty", &decl.empty),
];
let mut raw: BTreeMap<&str, &str> = JOIN_DEFAULTS.into_iter().collect();
for (key, value) in declared {
if let Some(value) = value {
raw.insert(key, value);
}
}
let mut parsed: BTreeMap<&str, Arc<NodeTree<Flm>>> = BTreeMap::new();
for (key, _) in JOIN_DEFAULTS {
let resolved = substitute_variables(raw[key], &raw)?;
parsed.insert(key, parse_text_from(&resolved, origin, lang, warnings)?);
}
let mut take = |key: &str| parsed.remove(key).expect("every join key was parsed");
Ok(CompiledJoin {
one_pre: take("one_pre"),
one_post: take("one_post"),
pair_pre: take("pair_pre"),
pair_mid: take("pair_mid"),
pair_post: take("pair_post"),
range_pre: take("range_pre"),
range_mid: take("range_mid"),
range_pairmid: take("range_pairmid"),
range_post: take("range_post"),
list_pre: take("list_pre"),
list_mid: take("list_mid"),
list_midlast: take("list_midlast"),
list_post: take("list_post"),
empty: take("empty"),
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ListPiece {
Text(JoinText),
Item(usize),
}
pub(crate) fn list_shape(count: usize) -> Vec<ListPiece> {
let mut pieces = Vec::new();
match count {
0 => {}
1 => {
pieces.push(ListPiece::Text(JoinText::OnePre));
pieces.push(ListPiece::Item(0));
pieces.push(ListPiece::Text(JoinText::OnePost));
}
2 => {
pieces.push(ListPiece::Text(JoinText::PairPre));
pieces.push(ListPiece::Item(0));
pieces.push(ListPiece::Text(JoinText::PairMid));
pieces.push(ListPiece::Item(1));
pieces.push(ListPiece::Text(JoinText::PairPost));
}
_ => {
pieces.push(ListPiece::Text(JoinText::ListPre));
for index in 0..count - 1 {
if index > 0 {
pieces.push(ListPiece::Text(JoinText::ListMid));
}
pieces.push(ListPiece::Item(index));
}
pieces.push(ListPiece::Text(JoinText::ListMidLast));
pieces.push(ListPiece::Item(count - 1));
pieces.push(ListPiece::Text(JoinText::ListPost));
}
}
pieces
}
fn substitution_at(text: &str) -> Option<(&str, usize)> {
let rest = text.strip_prefix("${")?;
let end = rest.find('}')?;
let name = &rest[..end];
if name.is_empty()
|| !name.chars().all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '.')
{
return None;
}
Some((name, 2 + end + 1))
}
fn substitute_variables(
text: &str,
values: &BTreeMap<&str, &str>,
) -> Result<String, StyleError> {
let mut out = String::new();
let mut rest = text;
while let Some(start) = rest.find("${") {
match substitution_at(&rest[start..]) {
Some((name, length)) => {
let Some(value) = values.get(name) else {
return Err(StyleError::UnknownVariable {
text: text.to_string(),
name: name.to_string(),
});
};
out.push_str(&rest[..start]);
out.push_str(value);
rest = &rest[start + length..];
}
None => {
out.push_str(&rest[..start + 2]);
rest = &rest[start + 2..];
}
}
}
out.push_str(rest);
Ok(out)
}
impl CounterStyle {
pub(crate) fn word_text(
&self,
count: usize,
variant: Option<&str>,
) -> Option<&Arc<NodeTree<Flm>>> {
let word = self.word(count, variant);
(word.root().child_count() > 0).then_some(word)
}
pub(crate) fn open(&self) -> &Arc<NodeTree<Flm>> {
&self.open
}
pub(crate) fn close(&self) -> &Arc<NodeTree<Flm>> {
&self.close
}
pub(super) fn name_in_link(&self) -> bool {
self.name_in_link
}
pub(super) fn repeat_parents_in_range(&self) -> bool {
self.repeat_parents_in_range
}
pub(super) fn ranges(&self) -> bool {
self.ranges
}
pub(super) fn writer(&self) -> &Arc<dyn CompiledNumberWriter> {
&self.writer
}
pub(crate) fn join(&self) -> &CompiledJoin {
&self.join
}
}