use std::sync::Arc;
use techy::core::constructs::{ArgumentParser, ConstructParserResult, ParseContext, ParsedArgumentNodes};
use techy::core::node::{BuildId, ContentNodes, NodeKind, NodeRef, StagedNodeView, StagedNodes};
use techy::core::specs::ArgumentSpec;
use crate::lang::mint::opaque::wrap_argument;
use crate::lang::mint::{
ArgDef, ArgStdKind, DefinitionShape, FlmArgumentParser, IntoFlmArgumentParser, TackOnField,
field_name,
};
use crate::lang::text::{CharsSegment, is_blank, is_blank_text, is_space, read_chars};
use crate::lang::{Flm, FlmCallableType, FlmGroupType};
use crate::model::aspects::{
AcceptedRefTypes, AnchorPolicy, ApartFromText, BlockRole, BlockRoleAspect, ContentRef,
FixedBlockRole, Label, NumberSource, PointId, RefDisplayOptions, RefPoint, RefSite,
Referenceable, Referencing, Whitespace,
};
use crate::model::addr::NodeAddr;
use crate::model::element::{ElementSpec, element_of, element_value};
use crate::model::names::{Name, RefKind};
use crate::stdlib::features::refs;
use super::config::{TheoremClass, TheoremKind, TheoremsConfig};
use super::numbers::{counter_name, style_name};
pub const THEOREM: &str = "flm.theorems.theorem";
pub const TITLE_ARG: &str = "title";
pub const NOPROOFREF_FIELD: &str = "noproofref";
pub const POINT_KIND: &str = "theorem";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TheoremElement {
pub name: Name,
pub kind: TheoremKind,
pub class_name: Name,
pub class: TheoremClass,
pub counter: Option<Name>,
pub label_types: Vec<String>,
}
impl TheoremElement {
pub fn of(config: &TheoremsConfig, name: &Name) -> Option<TheoremElement> {
let (kind, class) = config.kind_and_class(name.as_str())?;
let counter = counter_name(config, name.as_str());
let label_types = if counter.is_some() { config.label_types.clone() } else { Vec::new() };
Some(TheoremElement {
name: name.clone(),
kind: kind.clone(),
class_name: kind.class.clone(),
class: class.clone(),
counter,
label_types,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TitleReading {
Absent,
Title,
Relation {
text: String,
label: Label,
shown: bool,
},
Malformed,
Unknown,
}
pub fn title_reading(node: &NodeRef<'_, Flm>) -> Option<TitleReading> {
let value = element_value::<TheoremElement>(node)?;
let Ok(Some(title)) = node.argument_content_nodes_named(TITLE_ARG) else {
return Some(TitleReading::Absent);
};
if !value.class.relation_ref {
return Some(TitleReading::Title);
}
let Ok(read) = read_chars(title.iter()) else {
let starred = title
.iter()
.find(|node| !(node.is_comment() || is_blank(node)))
.and_then(|node| node.chars())
.is_some_and(|text| text.trim_start_matches(is_space).starts_with('*'));
return Some(if starred { TitleReading::Malformed } else { TitleReading::Title });
};
let leading: String = read
.segments()
.iter()
.map_while(|segment| segment.as_text())
.collect();
let leading = leading.trim_start_matches(is_space);
let placeholder = read.segments().iter().any(|segment| matches!(segment, CharsSegment::Placeholder(_)));
if placeholder && (leading.is_empty() || leading.starts_with('*')) {
return Some(TitleReading::Unknown);
}
let Some(starred) = leading.strip_prefix('*') else {
return Some(TitleReading::Title);
};
let (rest, shown) = match starred.strip_prefix('*') {
Some(rest) => (rest, false),
None => (starred, true),
};
let text = rest.trim_matches(is_space).to_string();
Some(match Label::parse(&text) {
Some(label) => TitleReading::Relation { text, label, shown },
None => TitleReading::Malformed,
})
}
pub(super) fn relation_site(node: &NodeRef<'_, Flm>) -> Option<RefSite> {
element_of(node).aspect::<dyn Referencing>()?.sites(node).into_iter().next()
}
pub(super) fn theorem_point(addr: NodeAddr) -> PointId {
PointId { addr, index: 0 }
}
pub(super) fn relation_site_id(addr: NodeAddr) -> refs::SiteId {
refs::SiteId { addr, index: 0 }
}
pub fn has_noproofref(node: &NodeRef<'_, Flm>) -> bool {
let Ok(Some(fields)) = node.argument_content_nodes_named(refs::FIELDS_ARG) else {
return false;
};
fields.iter().any(|field| field_name(&field) == Some(NOPROOFREF_FIELD))
}
impl Referenceable for TheoremElement {
fn points(&self, node: &NodeRef<'_, Flm>) -> Vec<RefPoint> {
let (labels, malformed) = refs::point_labels(&refs::label_uses(node));
let (anchor, number) = match &self.counter {
Some(counter) => (
AnchorPolicy::FromValue { prefix: self.name.to_string() },
Some(NumberSource {
counter: counter.clone(),
instances: Vec::new(),
style: style_name(self.name.as_str()),
advance: vec![0],
number_format: None,
}),
),
None => (AnchorPolicy::FromFirstLabel, None),
};
vec![RefPoint {
kind: RefKind::from(POINT_KIND),
labels,
computed: 0,
malformed,
anchor,
number,
content: None,
accepts: AcceptedRefTypes::these(self.label_types.iter().map(String::as_str)),
}]
}
}
impl Referencing for TheoremElement {
fn sites(&self, node: &NodeRef<'_, Flm>) -> Vec<RefSite> {
match title_reading(node) {
Some(TitleReading::Relation { label, shown, .. }) => vec![RefSite {
target: label,
display: RefDisplayOptions { variant: None, with_prefix: true },
shown,
}],
_ => Vec::new(),
}
}
}
impl ApartFromText for TheoremElement {
fn apart_from_text(&self, _node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
vec![ContentRef::ArgumentNamed(refs::FIELDS_ARG.to_string())]
}
}
pub(super) fn theorem_element(value: TheoremElement) -> Arc<ElementSpec> {
let docs = format!("`{}`: a theorem-like environment of the theorem class `{}`.", value.name, value.class_name);
let value = Arc::new(value);
Arc::new(
ElementSpec::new(THEOREM)
.docs(docs)
.with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::Block)))
.with::<dyn Referenceable>(Arc::clone(&value) as Arc<dyn Referenceable>)
.with::<dyn Referencing>(Arc::clone(&value) as Arc<dyn Referencing>)
.with::<dyn ApartFromText>(Arc::clone(&value) as Arc<dyn ApartFromText>)
.with_value(value),
)
}
pub fn theorem_args(relation_ref: bool) -> Vec<ArgDef> {
let noproofref = TackOnField::new(NOPROOFREF_FIELD, Vec::new())
.docs("Says that no proof of the statement is coming.");
let fields = ArgStdKind::TackOn { fields: vec![refs::label_field(), noproofref] };
let title = if relation_ref {
ArgDef::named(TITLE_ARG, RelationTitleParser::new())
} else {
ArgDef::named(TITLE_ARG, ArgStdKind::Optional)
};
vec![
title
.docs(
"The theorem's title, or, on a proof, a back-reference `*type:label` to the \
statement it proves.",
),
ArgDef::named(refs::FIELDS_ARG, fields)
.docs(
"The `\\label{…}` and `\\noproofref` fields written after the title: they label \
the theorem and mark it as having no proof.",
),
]
}
const RELATION_TITLE_IDENTITY: &str = "flm.theorems.relation-title";
#[derive(Debug)]
struct RelationTitleParser {
optional: Arc<dyn FlmArgumentParser>,
}
impl RelationTitleParser {
fn new() -> RelationTitleParser {
RelationTitleParser { optional: ArgStdKind::Optional.into_flm_argument_parser() }
}
}
impl ArgumentParser<Flm> for RelationTitleParser {
fn parse_argument(
&self,
cx: &mut ParseContext<'_, '_, Flm>,
spec: &ArgumentSpec<Flm>,
) -> ConstructParserResult<Flm, Option<ParsedArgumentNodes<Flm>>> {
let Some(read) = self.optional.parse_argument(cx, spec)? else {
return Ok(None);
};
let staged = cx.staged_nodes();
let content = match &read.content {
ContentNodes::InRegion(range) => read.nodes.get(range.start as usize..range.end as usize),
ContentNodes::InChildrenOf(parent, range) => staged
.get(*parent)
.and_then(|view| view.children().get(range.start as usize..range.end as usize)),
};
if !begins_with_star(staged, content.unwrap_or_default()) {
return Ok(Some(read));
}
wrap_argument(cx, read).map(Some)
}
fn can_match_empty(&self) -> bool {
self.optional.can_match_empty()
}
}
impl FlmArgumentParser for RelationTitleParser {
fn identity(&self) -> Vec<u8> {
RELATION_TITLE_IDENTITY.as_bytes().to_vec()
}
fn definition_shape(&self) -> DefinitionShape {
DefinitionShape::Value
}
fn description(&self) -> String {
String::from("an optional `[…]` group, kept as written when it begins with `*`")
}
}
fn begins_with_star(staged: StagedNodes<'_, Flm>, content: &[BuildId]) -> bool {
match leading_characters(staged, content) {
Some(leading) => leading.trim_start_matches(is_space).starts_with('*'),
None => content
.iter()
.filter_map(|id| staged.get(*id))
.filter(|view| {
!matches!(view.kind(), NodeKind::Comment(_))
&& !view.ext().element.has_aspect::<dyn Whitespace>()
})
.find(|view| staged_chars(view).is_none_or(|text| !is_blank_text(text)))
.and_then(|view| staged_chars(&view))
.is_some_and(|text| text.trim_start_matches(is_space).starts_with('*')),
}
}
fn leading_characters(staged: StagedNodes<'_, Flm>, content: &[BuildId]) -> Option<String> {
let mut leading = String::new();
let mut at_placeholder = false;
let mut pending: Vec<BuildId> = content.iter().rev().copied().collect();
while let Some(id) = pending.pop() {
let view = staged.get(id)?;
match view.kind() {
NodeKind::Chars { .. } => {
if !at_placeholder {
leading.push_str(staged_chars(&view).unwrap_or_default());
}
}
NodeKind::Comment(_) => {}
NodeKind::Group(group) if matches!(group.group_type, Some(FlmGroupType::Math(_))) => {
return None;
}
NodeKind::Group(_) | NodeKind::List => pending.extend(view.children().iter().rev()),
NodeKind::Callable(callable) => {
if callable.callable_type != FlmCallableType::Placeholder {
return None;
}
at_placeholder = true;
}
}
}
Some(leading)
}
fn staged_chars<'b>(view: &StagedNodeView<'b, Flm>) -> Option<&'b str> {
match view.kind() {
NodeKind::Chars { content } => Some(content.resolve(view.span().source())),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_kind_of_a_numbered_class_counts_and_accepts_the_label_types() {
let config = TheoremsConfig::new();
let lemma = TheoremElement::of(&config, &Name::from("lemma")).expect("declared");
assert_eq!(lemma.counter.as_deref(), Some("flm.theorems.theorem"));
assert_eq!(lemma.label_types, config.label_types);
assert_eq!(lemma.class_name.as_str(), "theoremlike");
let proof = TheoremElement::of(&config, &Name::from("proof")).expect("declared");
assert_eq!(proof.counter, None);
assert!(proof.label_types.is_empty());
assert!(TheoremElement::of(&config, &Name::from("nosuch")).is_none());
}
}