use techy::core::node::NodeRef;
use techy::extract::parse_keyval_drop_annotations;
use crate::core::lowering::{LowerError, Lowerer};
use crate::lang::copy::{
ValueContent, ValuePiece, WrittenPiece, copy_pieces_into_value, key_value_pieces,
};
use crate::lang::guard::{GuardPolicy, on_worker_thread};
use crate::lang::mint::field_name;
use crate::lang::{Flm, FlmGroupType};
use crate::model::aspects::ContentRef;
use crate::lang::structural::PARBREAK;
use crate::lang::text::{is_blank, is_space};
use crate::model::element::{element_of, element_value};
use crate::stdlib::features::numbering::COUNTERS;
use crate::stdlib::features::refs::{self, ANCHORS, LABEL_FIELD};
use super::config::{FloatNumbering, FloatType};
use super::content::{Handlers, Verdict};
use super::diagnostics::{
CaptionMissingValue, CaptionRepeated, CaptionRepeatedKey, CaptionUnknownKey, ContentRefused,
LabelWithoutRefs, NoNumbering, NonumberWithoutEffect,
};
use super::elements::FloatElement;
use super::{ALT_KEY, CAPTION_FIELD, CAPTION_OPTIONS_ARG, CAPTION_TEXT_ARG, NONUMBER_FIELD};
#[derive(Debug, Clone, Default)]
pub struct FloatBody<'t> {
pub content: Vec<NodeRef<'t, Flm>>,
pub captions: Vec<NodeRef<'t, Flm>>,
pub nonumbers: Vec<NodeRef<'t, Flm>>,
pub labels: Vec<NodeRef<'t, Flm>>,
}
pub(super) fn is_float_field(node: &NodeRef<'_, Flm>) -> bool {
field_name(node).is_some_and(|name| {
name == CAPTION_FIELD || name == NONUMBER_FIELD || name == LABEL_FIELD
})
}
pub(super) fn is_aside(node: &NodeRef<'_, Flm>) -> bool {
node.is_comment() || is_blank(node) || element_of(node).name.as_str() == PARBREAK
}
pub(super) fn is_paragraph(node: &NodeRef<'_, Flm>) -> bool {
node.group_type() == Some(FlmGroupType::Paragraph)
}
pub fn float_body<'t>(node: &NodeRef<'t, Flm>) -> FloatBody<'t> {
let mut body = FloatBody::default();
let Some(children) = node.body() else { return body };
let file = |field: NodeRef<'t, Flm>, body: &mut FloatBody<'t>| {
match field_name(&field) {
Some(CAPTION_FIELD) => body.captions.push(field),
Some(NONUMBER_FIELD) => body.nonumbers.push(field),
_ => body.labels.push(field),
}
};
for child in children.iter() {
if is_aside(&child) {
continue;
}
if is_float_field(&child) {
file(child, &mut body);
continue;
}
if is_paragraph(&child) {
let mut holds_content = false;
for inner in child.children().iter() {
if is_float_field(&inner) {
file(inner, &mut body);
} else if !is_aside(&inner) {
holds_content = true;
}
}
if !holds_content {
continue;
}
}
body.content.push(child);
}
body
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum CaptionProblem {
UnknownKey(String),
MissingValue,
RepeatedKey,
}
#[derive(Debug, Clone)]
pub struct Caption<'t> {
pub node: NodeRef<'t, Flm>,
pub alt: Option<Vec<WrittenPiece<'t>>>,
problems: Vec<CaptionProblem>,
}
impl<'t> Caption<'t> {
pub fn content(&self) -> Vec<NodeRef<'t, Flm>> {
self.node
.argument_content_nodes_named(CAPTION_TEXT_ARG)
.ok()
.flatten()
.map(|nodes| nodes.iter().collect())
.unwrap_or_default()
}
pub fn shown_content(&self, float: &NodeRef<'t, Flm>) -> Option<ContentRef> {
if let Some(alt) = &self.alt {
let pieces: Vec<ValuePiece<'_, '_>> = alt.iter().map(WrittenPiece::as_value_piece).collect();
return on_worker_thread(|| {
copy_pieces_into_value(&pieces, float, ValueContent::Shown, GuardPolicy::StackBudget)
})
.ok()?
.ok()
.map(ContentRef::Synthesized);
}
let region: Vec<NodeRef<'t, Flm>> = self
.node
.argument_nodes_named(CAPTION_TEXT_ARG)
.ok()
.flatten()
.map(|nodes| nodes.iter().filter(|node| !(node.is_comment() || is_blank(node))).collect())
.unwrap_or_default();
match region.as_slice() {
[one] => Some(ContentRef::Node(one.id())),
_ => None,
}
}
}
pub fn read_caption<'t>(node: NodeRef<'t, Flm>) -> Caption<'t> {
let mut caption = Caption { node, alt: None, problems: Vec::new() };
let Some(content) = node.argument_content_nodes_named(CAPTION_OPTIONS_ARG).ok().flatten() else {
return caption;
};
if content.iter().all(|child| child.is_comment() || is_blank(&child)) {
return caption;
}
let Ok(keyvals) = parse_keyval_drop_annotations(content) else {
let written: String = content.iter().map(|node| node.span_content().to_string()).collect();
caption.problems.push(CaptionProblem::UnknownKey(written.trim_matches(is_space).to_string()));
return caption;
};
for entry in keyvals.iter() {
let key = entry.key();
if key.is_empty() {
continue;
}
if key != ALT_KEY {
caption.problems.push(CaptionProblem::UnknownKey(key.to_string()));
continue;
}
let Some(value) = entry.value() else {
caption.problems.push(CaptionProblem::MissingValue);
continue;
};
if caption.alt.is_some() {
caption.problems.push(CaptionProblem::RepeatedKey);
continue;
}
caption.alt = Some(key_value_pieces(&content, value));
}
caption
}
#[derive(Debug, Clone)]
pub struct FloatFields<'t> {
pub float_type: &'t FloatType,
pub body: FloatBody<'t>,
pub caption: Option<Caption<'t>>,
pub numbered: bool,
}
pub fn float_fields<'t>(node: &NodeRef<'t, Flm>) -> Option<FloatFields<'t>> {
let value = element_value::<FloatElement>(node)?;
let body = float_body(node);
let caption = body.captions.first().map(|first| read_caption(*first));
let numbered = value.float_type.numbering.numbers(!body.labels.is_empty(), !body.nonumbers.is_empty());
Some(FloatFields { float_type: &value.float_type, body, caption, numbered })
}
#[derive(Debug, Clone)]
pub struct FloatReading<'t> {
pub fields: FloatFields<'t>,
pub verdict: Verdict,
}
pub fn read_float<'t>(
node: &NodeRef<'t, Flm>,
handlers: &Handlers,
lw: &mut dyn Lowerer,
) -> Result<FloatReading<'t>, LowerError> {
let fields = float_fields(node)
.ok_or_else(|| LowerError::structure("a float without its element's data"))?;
let float_type = fields.float_type;
let type_name = float_type.name.to_string();
for extra in fields.body.captions.iter().skip(1) {
lw.error(CaptionRepeated { float_type: type_name.clone() }, extra.span().clone());
}
if let Some(caption) = &fields.caption {
let span = caption.node.span().clone();
for problem in &caption.problems {
match problem {
CaptionProblem::UnknownKey(key) => {
lw.error(CaptionUnknownKey { key: key.clone() }, span.clone())
}
CaptionProblem::MissingValue => lw.error(CaptionMissingValue, span.clone()),
CaptionProblem::RepeatedKey => lw.error(CaptionRepeatedKey, span.clone()),
}
}
}
let labeled = !fields.body.labels.is_empty();
for (at, nonumber) in fields.body.nonumbers.iter().enumerate() {
let reason = match float_type.numbering {
FloatNumbering::Unnumbered => format!("a ‘{type_name}’ is never numbered"),
FloatNumbering::AutoNumbered if !labeled => {
format!("a ‘{type_name}’ without a ‘\\label’ is not numbered")
}
_ if at > 0 => String::from("it is already written in this float"),
_ => continue,
};
lw.note(NonumberWithoutEffect { reason }, nonumber.span().clone());
}
if let Some(first) = fields.body.labels.first() {
if lw.get(ANCHORS)?.is_none() {
lw.note(LabelWithoutRefs { float_type: type_name.clone() }, first.span().clone());
}
}
if fields.numbered && lw.get(COUNTERS)?.is_none() {
lw.error(NoNumbering { float_type: type_name.clone() }, node.span().clone());
}
let verdict = handlers.verdict(&float_type.handlers, &fields.body.content);
if let Verdict::Refused(refusals) = &verdict {
let admitted = if refusals.is_empty() {
let kinds: Vec<String> = float_type.handlers.iter().map(|kind| format!("‘{kind}’")).collect();
match kinds.as_slice() {
[one] => format!("content accepted by the missing content handler {one}"),
_ => format!(
"content accepted by one of the missing content handlers {}",
english_or(&kinds)
),
}
} else {
english_or(refusals)
};
lw.error(ContentRefused { float_type: type_name, admitted }, node.span().clone());
}
Ok(FloatReading { fields, verdict })
}
fn english_or(items: &[String]) -> String {
match items.split_last() {
None => String::new(),
Some((last, [])) => last.clone(),
Some((last, rest)) => format!("{} or {last}", rest.join(", ")),
}
}
pub(super) fn label_uses(fields: &FloatFields<'_>) -> Vec<refs::LabelUse> {
refs::label_uses_in(fields.body.labels.iter().copied())
}
#[cfg(test)]
mod tests {
use super::english_or;
#[test]
fn the_admitted_contents_join_with_or() {
let items = |list: &[&str]| list.iter().map(|item| item.to_string()).collect::<Vec<_>>();
assert_eq!(english_or(&items(&["one image"])), "one image");
assert_eq!(english_or(&items(&["a", "b"])), "a or b");
assert_eq!(english_or(&items(&["a", "b", "c"])), "a, b or c");
}
}