use std::fmt;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, OnceLock};
use techy::core::node::BuildId;
use crate::core::lowering::{LowerCx, LowerError, Lowerer};
use crate::core::registry::{LateInit, LateInitError};
use crate::lang::{BuiltLang, FlmDiagnostics};
use crate::stdlib::features::numbering::{CompiledJoin, JoinDecl, ListPiece, list_shape};
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Deserialize)]
#[derive(schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct RefsConfig {
pub join: JoinDecl,
}
impl RefsConfig {
pub fn new() -> RefsConfig {
RefsConfig::default()
}
pub fn join(mut self, join: JoinDecl) -> RefsConfig {
self.join = join;
self
}
pub fn digest_bytes(&self) -> Vec<u8> {
let mut out = Vec::new();
self.join.digest_into(&mut out);
out
}
}
impl Hash for RefsConfig {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write(&self.digest_bytes());
}
}
const LIST_TEXT_ORIGIN: &str = "reference list joining text";
#[derive(Default)]
pub(super) struct ListTexts {
compiled: OnceLock<CompiledJoin>,
}
impl fmt::Debug for ListTexts {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ListTexts").field("compiled", &self.compiled.get().is_some()).finish()
}
}
pub(super) struct CompileList {
pub(super) texts: Arc<ListTexts>,
pub(super) decl: JoinDecl,
}
impl LateInit for CompileList {
fn late_init(&self, lang: &BuiltLang, diags: &mut FlmDiagnostics) -> Result<(), LateInitError> {
let mut warnings = Vec::new();
let compiled = CompiledJoin::compile(&self.decl, LIST_TEXT_ORIGIN, lang, &mut warnings)
.map_err(|error| {
LateInitError::new(format!(
"a text that joins the targets of a reference to several labels (the \
configuration key `join` of the feature `refs`) is not valid: {error}"
))
})?;
for warning in warnings {
diags.push(warning);
}
let _ = self.texts.compiled.set(compiled);
Ok(())
}
}
pub(super) fn join_items(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
texts: &ListTexts,
mut items: Vec<Vec<BuildId>>,
) -> Result<Vec<BuildId>, LowerError> {
let Some(join) = texts.compiled.get() else {
return Err(LowerError::structure(
"the texts that join the targets of a reference were never compiled",
));
};
let mut out = Vec::new();
for piece in list_shape(items.len()) {
match piece {
ListPiece::Text(which) => out.extend(lw.splice(cx, join.text(which))?),
ListPiece::Item(index) => out.append(&mut items[index]),
}
}
Ok(out)
}