use techy::core::node::{NodeRef, NodeSlice};
use techy::extract::parse_keyval_drop_annotations;
use crate::lang::Flm;
use crate::lang::copy::{WrittenPiece, key_value_pieces, trim_pieces};
use crate::lang::text::{is_blank, is_space};
use super::{LABEL_KEY, OPTIONS_ARG, REF_KEY, TAG_KEY};
const SHORT_FORM_CHARACTERS: &str = "[]().:-+*aAiI1";
const SHORT_FORM_TRAILING: [char; 3] = ['.', ':', '-'];
const TOKENS: [(char, &str); 5] =
[('a', "alph"), ('A', "Alph"), ('i', "roman"), ('I', "Roman"), ('1', "arabic")];
#[derive(Debug, Clone)]
pub struct OwnLabel<'t> {
pub template: String,
pub ref_template: String,
pub written: String,
pub pieces: Vec<WrittenPiece<'t>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum OptionProblem {
UnknownKey(String),
MissingValue(String),
BadLabelForm { written: String, first: String, second: String },
}
#[derive(Debug, Clone, Default)]
pub struct ListOptions<'t> {
pub label: Option<OwnLabel<'t>>,
pub ref_label: Option<String>,
pub(super) problems: Vec<OptionProblem>,
}
impl ListOptions<'_> {
pub fn ref_template(&self) -> Option<&str> {
self.ref_label
.as_deref()
.or_else(|| self.label.as_ref().map(|label| label.ref_template.as_str()))
}
}
#[derive(Debug, Clone)]
pub struct ItemTag<'t> {
pub pieces: Vec<WrittenPiece<'t>>,
}
#[derive(Debug, Clone, Default)]
pub struct ItemOptions<'t> {
pub tag: Option<ItemTag<'t>>,
pub(super) problems: Vec<OptionProblem>,
}
fn bracket<'t>(node: &NodeRef<'t, Flm>) -> Option<NodeSlice<'t, Flm>> {
let content = node.argument_content_nodes_named(OPTIONS_ARG).ok()??;
let blank = content.iter().all(|child| child.is_comment() || is_blank(&child));
(!blank).then_some(content)
}
fn holds_equals(nodes: &NodeSlice<'_, Flm>) -> bool {
nodes.iter().any(|node| node.chars().is_some_and(|text| text.contains('=')))
}
fn written_text<'t>(nodes: impl IntoIterator<Item = NodeRef<'t, Flm>>) -> String {
nodes.into_iter().map(|node| node.span_content().to_string()).collect()
}
fn template_text<'t>(nodes: impl IntoIterator<Item = NodeRef<'t, Flm>>) -> String {
nodes
.into_iter()
.map(|node| match node.chars() {
Some(text) => text.to_string(),
None if node.is_comment() => String::new(),
None => node.span_content().to_string(),
})
.collect()
}
pub fn short_form(text: &str) -> Option<Result<String, (String, String)>> {
if text.is_empty() || !text.chars().all(|ch| SHORT_FORM_CHARACTERS.contains(ch)) {
return None;
}
let reading = |at: usize, ch: char| {
let name = TOKENS.iter().find(|(token, _)| *token == ch).map(|(_, name)| *name)?;
Some(format!("{}#{{{name}}}{}", &text[..at], &text[at + ch.len_utf8()..]))
};
let mut tokens = text.char_indices().filter_map(|(at, ch)| reading(at, ch));
Some(match (tokens.next(), tokens.next()) {
(None, _) => Ok(text.to_string()),
(Some(only), None) => Ok(only),
(Some(first), Some(second)) => Err((first, second)),
})
}
pub fn short_form_ref(text: &str) -> Option<String> {
let label = short_form(text)?.ok()?;
if !text.chars().any(|ch| TOKENS.iter().any(|(token, _)| *token == ch)) {
return Some(label);
}
short_form(text.trim_end_matches(SHORT_FORM_TRAILING))?.ok()
}
pub fn list_options<'t>(node: &NodeRef<'t, Flm>) -> ListOptions<'t> {
let mut options = ListOptions::default();
let Some(content) = bracket(node) else { return options };
if !holds_equals(&content) {
let unwrapped = match (content.len(), content.first()) {
(1, Some(group)) if group.is_group() => written_text(group.children().iter()),
_ => written_text(content.iter()),
};
let written = unwrapped.trim_matches(is_space).to_string();
let pieces = trim_pieces(content.iter().map(WrittenPiece::Node).collect());
match (short_form(&written), short_form_ref(&written)) {
(Some(Ok(template)), Some(ref_template)) => {
options.label = Some(OwnLabel { template, ref_template, written, pieces })
}
(Some(Err((first, second))), _) => {
options.problems.push(OptionProblem::BadLabelForm { written, first, second })
}
_ => options.problems.push(OptionProblem::UnknownKey(written)),
}
return options;
}
let Ok(keyvals) = parse_keyval_drop_annotations(content) else {
let written = written_text(content.iter()).trim_matches(is_space).to_string();
options.problems.push(OptionProblem::UnknownKey(written));
return options;
};
for entry in keyvals.iter() {
let key = entry.key();
if key.is_empty() {
continue;
}
if key != LABEL_KEY && key != REF_KEY {
options.problems.push(OptionProblem::UnknownKey(key.to_string()));
continue;
}
match (entry.value(), entry.value_content()) {
(Some(_), Some(unwrapped)) if key == REF_KEY => {
options.ref_label = Some(template_text(unwrapped.iter()).trim_matches(is_space).to_string());
}
(Some(value), Some(unwrapped)) => {
let written = template_text(unwrapped.iter()).trim_matches(is_space).to_string();
let pieces = key_value_pieces(&content, value);
options.label = Some(OwnLabel {
template: written.clone(),
ref_template: written.clone(),
written,
pieces,
});
}
_ => options.problems.push(OptionProblem::MissingValue(key.to_string())),
}
}
options
}
pub fn item_options<'t>(node: &NodeRef<'t, Flm>) -> ItemOptions<'t> {
let mut options = ItemOptions::default();
let Some(content) = bracket(node) else { return options };
if !holds_equals(&content) {
options.tag = Some(ItemTag { pieces: content.iter().map(WrittenPiece::Node).collect() });
return options;
}
let Ok(keyvals) = parse_keyval_drop_annotations(content) else {
let written = written_text(content.iter()).trim_matches(is_space).to_string();
options.problems.push(OptionProblem::UnknownKey(written));
return options;
};
for entry in keyvals.iter() {
let key = entry.key();
if key.is_empty() {
continue;
}
if key != TAG_KEY {
options.problems.push(OptionProblem::UnknownKey(key.to_string()));
continue;
}
let Some(value) = entry.value() else {
options.problems.push(OptionProblem::MissingValue(key.to_string()));
continue;
};
options.tag = Some(ItemTag { pieces: key_value_pieces(&content, value) });
}
options
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_short_form_with_one_number_character_names_its_format() {
assert_eq!(short_form("(i)"), Some(Ok("(#{roman})".to_string())));
assert_eq!(short_form("1."), Some(Ok("#{arabic}.".to_string())));
assert_eq!(short_form("a-"), Some(Ok("#{alph}-".to_string())));
assert_eq!(short_form("A)"), Some(Ok("#{Alph})".to_string())));
assert_eq!(short_form("[I]"), Some(Ok("[#{Roman}]".to_string())));
}
#[test]
fn a_short_form_with_no_number_character_is_a_fixed_label() {
for fixed in ["-", "*", "+", "--", "()", ":"] {
assert_eq!(short_form(fixed), Some(Ok(fixed.to_string())));
assert_eq!(short_form_ref(fixed), Some(fixed.to_string()));
}
}
#[test]
fn a_short_form_s_reference_template_drops_its_trailing_punctuation() {
assert_eq!(short_form("1.:"), Some(Ok("#{arabic}.:".to_string())));
assert_eq!(short_form_ref("1.:"), Some("#{arabic}".to_string()));
assert_eq!(short_form_ref("1."), Some("#{arabic}".to_string()));
assert_eq!(short_form_ref("a-"), Some("#{alph}".to_string()));
assert_eq!(short_form_ref("(i)"), Some("(#{roman})".to_string()));
assert_eq!(short_form_ref("(i)."), Some("(#{roman})".to_string()));
assert_eq!(short_form_ref("-1-"), Some("-#{arabic}".to_string()));
assert_eq!(short_form_ref("i.a"), None);
assert_eq!(short_form_ref("x"), None);
}
#[test]
fn a_short_form_with_two_number_characters_names_both_readings() {
assert_eq!(
short_form("i.a"),
Some(Err(("#{roman}.a".to_string(), "i.#{alph}".to_string())))
);
}
#[test]
fn any_other_character_makes_no_short_form() {
for other in ["\u{2022}", "(${alph})", "(b)", "x", " (i)", ""] {
assert_eq!(short_form(other), None, "{other:?}");
}
}
}