use std::cell::RefCell;
use std::collections::BTreeMap;
use std::fmt;
use std::sync::{Arc, OnceLock};
use techy::core::node::NodeTree;
use crate::lang::{BuiltLang, Flm};
use crate::model::addr::NodeAddr;
use crate::model::names::Name;
use super::formats::NumberFormat;
use super::joiner::{JoinCx, Part};
use super::many::default_many;
use super::style::{
default_one, number_tree, parse_text, Ancestor, CounterStyle, FormatError, FormatOptions,
Item, Mark, Parent, Piece, StyleError,
};
use super::value::CounterValue;
#[derive(Clone, Copy, Debug)]
pub struct NumberedValue<'a> {
value: &'a CounterValue,
parent: Option<Parent<'a>>,
instance: Option<NodeAddr>,
index: usize,
}
impl<'a> NumberedValue<'a> {
pub fn new(value: &'a CounterValue) -> NumberedValue<'a> {
NumberedValue { value, parent: None, instance: None, index: 0 }
}
pub fn within(mut self, parent: Parent<'a>) -> NumberedValue<'a> {
self.parent = Some(parent);
self
}
pub fn in_instance(mut self, instance: NodeAddr) -> NumberedValue<'a> {
self.instance = Some(instance);
self
}
pub fn instance(&self) -> Option<NodeAddr> {
self.instance
}
pub fn value(&self) -> &'a CounterValue {
self.value
}
pub fn ancestors(&self) -> &'a [Ancestor] {
match &self.parent {
Some(parent) => parent.ancestors,
None => &[],
}
}
pub fn index(&self) -> usize {
self.index
}
pub(super) fn parent(&self) -> Option<Parent<'a>> {
self.parent
}
pub(super) fn at(mut self, index: usize) -> NumberedValue<'a> {
self.index = index;
self
}
}
pub struct NumberOut<'a> {
items: Vec<Item<'a>>,
}
impl<'a> NumberOut<'a> {
pub(super) fn new() -> NumberOut<'a> {
NumberOut { items: Vec::new() }
}
pub fn content(&mut self, content: Arc<NodeTree<Flm>>, link: Option<usize>) {
self.items.push(Item { pieces: vec![Piece::Tree(content)], mark: mark_of(link) });
}
pub fn text(&mut self, text: &str, link: Option<usize>) {
self.items.push(Item { pieces: vec![Piece::Digits(text.to_string())], mark: mark_of(link) });
}
pub(super) fn item(&mut self, item: Item<'a>) {
self.items.push(item);
}
pub(super) fn items(&mut self, items: impl IntoIterator<Item = Item<'a>>) {
self.items.extend(items);
}
pub(super) fn into_items(self) -> Vec<Item<'a>> {
self.items
}
}
impl fmt::Debug for NumberOut<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NumberOut").field("pieces", &self.items.len()).finish()
}
}
fn mark_of(link: Option<usize>) -> Mark {
match link {
Some(index) => Mark::Value(index),
None => Mark::Never,
}
}
pub trait NumberWriter: Send + Sync {
fn name(&self) -> &Name;
fn compile(&self, cx: &WriterCx<'_>) -> Result<Arc<dyn CompiledNumberWriter>, StyleError>;
}
#[derive(Clone)]
pub struct NumberWriterDecl {
writer: Arc<dyn NumberWriter>,
}
impl NumberWriterDecl {
pub fn new(writer: Arc<dyn NumberWriter>) -> NumberWriterDecl {
NumberWriterDecl { writer }
}
pub fn writer(&self) -> &Arc<dyn NumberWriter> {
&self.writer
}
}
impl fmt::Debug for NumberWriterDecl {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NumberWriterDecl").field("name", &self.writer.name().as_str()).finish()
}
}
pub trait CompiledNumberWriter: Send + Sync + fmt::Debug {
fn write_one<'a>(
&self,
value: &NumberedValue<'a>,
options: &FormatOptions,
cx: &WriteCx<'a>,
out: &mut NumberOut<'a>,
) -> Result<(), FormatError>;
fn write_many<'a>(
&self,
values: &[NumberedValue<'a>],
options: &FormatOptions,
cx: &WriteCx<'a>,
out: &mut NumberOut<'a>,
) -> Result<(), FormatError>;
}
pub struct WriterCx<'a> {
lang: &'a BuiltLang,
style: &'a Name,
}
impl<'a> WriterCx<'a> {
pub(super) fn new(lang: &'a BuiltLang, style: &'a Name) -> WriterCx<'a> {
WriterCx { lang, style }
}
pub fn lang(&self) -> &BuiltLang {
self.lang
}
pub fn style(&self) -> &Name {
self.style
}
pub fn parse(&self, text: &str) -> Result<Arc<NodeTree<Flm>>, StyleError> {
let mut warnings = Vec::new();
parse_text(text, self.lang, &mut warnings)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum JoinText {
OnePre,
OnePost,
PairPre,
PairMid,
PairPost,
RangePre,
RangeMid,
RangePairMid,
RangePost,
ListPre,
ListMid,
ListMidLast,
ListPost,
Empty,
}
pub struct WriteCx<'a> {
style: &'a CounterStyle,
parts: RefCell<BTreeMap<PartsKey, Arc<Vec<Part>>>>,
}
type PartsKey = (usize, usize, usize);
impl<'a> WriteCx<'a> {
pub(super) fn new(style: &'a CounterStyle) -> WriteCx<'a> {
WriteCx { style, parts: RefCell::new(BTreeMap::new()) }
}
pub fn style(&self) -> &'a CounterStyle {
self.style
}
pub fn word(&self, count: usize, variant: Option<&str>) -> Option<&'a Arc<NodeTree<Flm>>> {
self.style.word_text(count, variant)
}
pub fn open(&self) -> &'a Arc<NodeTree<Flm>> {
self.style.open()
}
pub fn close(&self) -> &'a Arc<NodeTree<Flm>> {
self.style.close()
}
pub fn name_in_link(&self) -> bool {
self.style.name_in_link()
}
pub fn repeat_parents_in_range(&self) -> bool {
self.style.repeat_parents_in_range()
}
pub fn ranges(&self) -> bool {
self.style.ranges()
}
pub fn join_text(&self, which: JoinText) -> &'a Arc<NodeTree<Flm>> {
self.style.join().text(which)
}
pub fn number(&self, value: &CounterValue) -> Result<Arc<NodeTree<Flm>>, FormatError> {
number_tree(self.style, value, None)
}
pub fn number_in(
&self,
value: &CounterValue,
format: NumberFormat,
) -> Result<Arc<NodeTree<Flm>>, FormatError> {
number_tree(self.style, value, Some(format))
}
pub fn number_of(&self, ancestor: &Ancestor) -> Result<Arc<NodeTree<Flm>>, FormatError> {
number_tree(&ancestor.style, &ancestor.value, None)
}
pub fn number_of_in(
&self,
ancestor: &Ancestor,
format: NumberFormat,
) -> Result<Arc<NodeTree<Flm>>, FormatError> {
number_tree(&ancestor.style, &ancestor.value, Some(format))
}
pub fn literal(&self, text: &str) -> Result<Arc<NodeTree<Flm>>, FormatError> {
self.style.literal(text)
}
pub fn parts(&self, value: &NumberedValue<'_>) -> Result<Vec<Part>, FormatError> {
let Some(parent) = value.parent() else { return Ok(Vec::new()) };
let key: PartsKey = (
std::ptr::from_ref(parent.joiner).cast::<()>() as usize,
parent.ancestors.as_ptr() as usize,
parent.ancestors.len(),
);
if let Some(written) = self.parts.borrow().get(&key) {
return Ok(written.as_ref().clone());
}
let cx = JoinCx::new(self.style);
let written = Arc::new(parent.joiner.parts(parent.ancestors, &cx)?);
self.parts.borrow_mut().insert(key, Arc::clone(&written));
Ok(written.as_ref().clone())
}
pub fn default_one(
&self,
value: &NumberedValue<'a>,
options: &FormatOptions,
out: &mut NumberOut<'a>,
) -> Result<(), FormatError> {
default_one(value, options, self, out)
}
pub fn default_many(
&self,
values: &[NumberedValue<'a>],
options: &FormatOptions,
out: &mut NumberOut<'a>,
) -> Result<(), FormatError> {
default_many(values, options, self, out)
}
}
impl fmt::Debug for WriteCx<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WriteCx").field("style", &self.style.name().as_str()).finish_non_exhaustive()
}
}
#[derive(Debug)]
pub(super) struct DefaultWriter;
impl CompiledNumberWriter for DefaultWriter {
fn write_one<'a>(
&self,
value: &NumberedValue<'a>,
options: &FormatOptions,
cx: &WriteCx<'a>,
out: &mut NumberOut<'a>,
) -> Result<(), FormatError> {
default_one(value, options, cx, out)
}
fn write_many<'a>(
&self,
values: &[NumberedValue<'a>],
options: &FormatOptions,
cx: &WriteCx<'a>,
out: &mut NumberOut<'a>,
) -> Result<(), FormatError> {
default_many(values, options, cx, out)
}
}
pub(super) fn default_writer() -> &'static Arc<dyn CompiledNumberWriter> {
static WRITER: OnceLock<Arc<dyn CompiledNumberWriter>> = OnceLock::new();
WRITER.get_or_init(|| Arc::new(DefaultWriter))
}