use std::any::Any;
use std::fmt;
use techy::core::node::{
CallableData, ChildRegion, NodeId, NodeRef, NodeTree, TreeViolation, validate_tree,
};
use techy::error::{Diagnostic, DiagnosticInfo};
use techy::latexlike::{Mode, ParagraphBreakSpec};
use crate::model::aspects::{BlockRole, Placement, block_role_of, is_whitespace_of};
use crate::model::element::{ElementSpec, element_of};
use crate::model::names::ElementName;
use crate::lang::ext::RestrictedInterior;
use crate::lang::flm::{Flm, FlmCallableType, FlmGroupType};
use crate::lang::mint::specs::element_of_spec;
use crate::lang::mint::{FALLBACK_PACKAGE_NAME, body_def_of, resolve_element};
use crate::lang::origin::FlmDiagnostic;
use crate::lang::rewrites::userdefs::Expand;
use crate::lang::text::is_space_byte;
use super::predicates::{Region, argument_holds_blocks, is_content, is_opaque_group, slot_layout};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ContractViolationKind {
Tree(TreeViolation),
ElementMismatch {
expected: ElementName,
found: ElementName,
},
SpecNotMinted {
name: String,
},
UnknownCallableShape {
element: ElementName,
},
FallbackShape {
name: String,
},
VerbatimInteriorRulesOn,
OpaqueWrapperDelimiters {
open: String,
close: String,
},
PlaceholderSurvived,
UseSiteSurvived {
element: ElementName,
},
ParbreakSurvived,
ParagraphDelimiters {
open: String,
close: String,
},
EmptyParagraph,
BlockInParagraph {
element: ElementName,
},
InlineInBlocksRegion {
element: ElementName,
},
ParagraphInInlineContainer {
element: ElementName,
},
LeadsNotFirst {
element: ElementName,
},
TrailsNotLast {
element: ElementName,
},
WhitespaceNotCollapsed,
ParagraphEdgeNotTrimmed,
WhitespaceBesideDisplayed {
element: ElementName,
},
AdjacentText,
SourceMapDoesNotTile {
mapped: u32,
text_len: usize,
},
SourceMapOnNonText,
}
impl ContractViolationKind {
pub const fn as_str(&self) -> &'static str {
match self {
ContractViolationKind::Tree(_) => "Tree",
ContractViolationKind::ElementMismatch { .. } => "ElementMismatch",
ContractViolationKind::SpecNotMinted { .. } => "SpecNotMinted",
ContractViolationKind::UnknownCallableShape { .. } => "UnknownCallableShape",
ContractViolationKind::FallbackShape { .. } => "FallbackShape",
ContractViolationKind::VerbatimInteriorRulesOn => "VerbatimInteriorRulesOn",
ContractViolationKind::OpaqueWrapperDelimiters { .. } => "OpaqueWrapperDelimiters",
ContractViolationKind::PlaceholderSurvived => "PlaceholderSurvived",
ContractViolationKind::UseSiteSurvived { .. } => "UseSiteSurvived",
ContractViolationKind::ParbreakSurvived => "ParbreakSurvived",
ContractViolationKind::ParagraphDelimiters { .. } => "ParagraphDelimiters",
ContractViolationKind::EmptyParagraph => "EmptyParagraph",
ContractViolationKind::BlockInParagraph { .. } => "BlockInParagraph",
ContractViolationKind::InlineInBlocksRegion { .. } => "InlineInBlocksRegion",
ContractViolationKind::ParagraphInInlineContainer { .. } => {
"ParagraphInInlineContainer"
}
ContractViolationKind::LeadsNotFirst { .. } => "LeadsNotFirst",
ContractViolationKind::TrailsNotLast { .. } => "TrailsNotLast",
ContractViolationKind::WhitespaceNotCollapsed => "WhitespaceNotCollapsed",
ContractViolationKind::ParagraphEdgeNotTrimmed => "ParagraphEdgeNotTrimmed",
ContractViolationKind::WhitespaceBesideDisplayed { .. } => "WhitespaceBesideDisplayed",
ContractViolationKind::AdjacentText => "AdjacentText",
ContractViolationKind::SourceMapDoesNotTile { .. } => "SourceMapDoesNotTile",
ContractViolationKind::SourceMapOnNonText => "SourceMapOnNonText",
}
}
}
impl fmt::Display for ContractViolationKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ContractViolationKind::Tree(violation) => write!(f, "{violation}"),
ContractViolationKind::ElementMismatch { expected, found } if expected == found => {
write!(
f,
"the node carries an element named ‘{found}’ that is not the element its \
parser settings give to a node of this form (text, group, macro, environment, ...)"
)
}
ContractViolationKind::ElementMismatch { expected, found } => {
write!(
f,
"the node carries the element ‘{found}’, but the parser settings it was read with \
give the element ‘{expected}’ to a node of this form"
)
}
ContractViolationKind::SpecNotMinted { name } => {
write!(f, "the command ‘{name}’ has a specification that FLM did not build")
}
ContractViolationKind::UnknownCallableShape { element } => {
write!(
f,
"a node carries ‘{element}’ but is not written as the command form \
that this element requires"
)
}
ContractViolationKind::FallbackShape { name } => {
write!(
f,
"the macro ‘{name}’, which no declaration defines, must have no arguments and no content"
)
}
ContractViolationKind::VerbatimInteriorRulesOn => {
write!(
f,
"the text of a verbatim group was not read with the markup rules switched off"
)
}
ContractViolationKind::OpaqueWrapperDelimiters { open, close } => {
write!(
f,
"a group that keeps its content as written has the delimiters {open:?} and \
{close:?}, and must have none"
)
}
ContractViolationKind::PlaceholderSurvived => {
write!(f, "a template placeholder remains after expansion")
}
ContractViolationKind::UseSiteSurvived { element } => {
write!(
f,
"a use of the user definition ‘{element}’ remains after expansion"
)
}
ContractViolationKind::ParbreakSurvived => {
write!(
f,
"a paragraph break remains outside mathematics, verbatim content and content \
kept as written"
)
}
ContractViolationKind::ParagraphDelimiters { open, close } => {
write!(
f,
"a paragraph has the delimiters {open:?} and {close:?}, and must have none"
)
}
ContractViolationKind::EmptyParagraph => write!(f, "a paragraph holds nothing but comments and whitespace"),
ContractViolationKind::BlockInParagraph { element } => {
write!(f, "the block-level node ‘{element}’ is inside a paragraph")
}
ContractViolationKind::InlineInBlocksRegion { element } => {
write!(f, "the inline node ‘{element}’ is placed between blocks, outside any paragraph")
}
ContractViolationKind::ParagraphInInlineContainer { element } => {
write!(
f,
"a paragraph is inside ‘{element}’, whose content is laid out inline"
)
}
ContractViolationKind::LeadsNotFirst { element } => {
write!(
f,
"the decorator ‘{element}’ must come first in its paragraph"
)
}
ContractViolationKind::TrailsNotLast { element } => {
write!(
f,
"the decorator ‘{element}’ must come last in its paragraph"
)
}
ContractViolationKind::WhitespaceNotCollapsed => {
write!(f, "a text node holds a tab, a line break or two consecutive spaces")
}
ContractViolationKind::ParagraphEdgeNotTrimmed => {
write!(f, "a paragraph begins or ends with whitespace")
}
ContractViolationKind::WhitespaceBesideDisplayed { element } => {
write!(
f,
"the displayed item ‘{element}’ must have no whitespace beside it"
)
}
ContractViolationKind::AdjacentText => write!(f, "two text nodes follow each other without a node between them"),
ContractViolationKind::SourceMapDoesNotTile { mapped, text_len } => {
write!(
f,
"the source map of a text node covers {mapped} bytes, and its text has {text_len} bytes"
)
}
ContractViolationKind::SourceMapOnNonText => {
write!(f, "a source map is attached to a node that is not text")
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContractViolation {
pub node: Option<NodeId>,
pub kind: ContractViolationKind,
}
impl ContractViolation {
fn at(node: &NodeRef<'_, Flm>, kind: ContractViolationKind) -> ContractViolation {
ContractViolation {
node: Some(node.id()),
kind,
}
}
pub fn diagnostic(&self, tree: &NodeTree<Flm>) -> FlmDiagnostic {
let span = self
.node
.and_then(|id| tree.get(id))
.map_or_else(|| tree.root().span().clone(), |node| node.span().clone());
let condition = ContractViolated::new(self.kind.as_str(), self.kind.to_string());
Diagnostic::error(condition, span)
}
}
impl fmt::Display for ContractViolation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.node {
Some(node) => write!(f, "node {node:?}: {}", self.kind),
None => write!(f, "{}", self.kind),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.blocks.contract-violated",
message = "the document tree breaks the structural rule {rule}: {detail}"
)]
pub struct ContractViolated {
pub rule: String,
pub detail: String,
}
struct Facts {
opaque: Vec<bool>,
content_parent: Vec<bool>,
}
impl Facts {
fn of(tree: &NodeTree<Flm>) -> Facts {
let count = tree.node_count();
let mut facts = Facts {
opaque: vec![false; count],
content_parent: vec![false; count],
};
let mut under_opaque_group = vec![false; count];
for node in tree.iter_storage_order() {
let i = node.id().index();
let math_mode = node.parsing_state().mode() == Mode::Math;
if let Some(parent) = node.parent() {
let p = parent.id().index();
under_opaque_group[i] = under_opaque_group[p] || is_opaque_group(&parent);
}
facts.opaque[i] = under_opaque_group[i] || math_mode;
if let Some(callable) = node.callable() {
for region in regions(callable) {
let parent = region.content_parent().index();
if let Some(flag) = facts.content_parent.get_mut(parent) {
*flag = true;
}
}
}
}
facts
}
fn index(node: &NodeRef<'_, Flm>) -> usize {
node.id().index()
}
fn opaque(&self, node: &NodeRef<'_, Flm>) -> bool {
self.opaque[Facts::index(node)]
}
fn is_content_parent(&self, node: &NodeRef<'_, Flm>) -> bool {
self.content_parent[Facts::index(node)]
}
}
pub fn check_parse_contract(tree: &NodeTree<Flm>) -> Vec<ContractViolation> {
let mut out = Vec::new();
if let Err(violation) = validate_tree(tree) {
out.push(ContractViolation {
node: violation.node,
kind: ContractViolationKind::Tree(violation),
});
return out;
}
for node in tree.iter_storage_order() {
let ext = node.parsing_state().ext();
let element = element_of(&node);
if let Ok(expected) = resolve_element(node.kind(), ext) {
if !ElementSpec::same_value(&expected, element) {
let kind = ContractViolationKind::ElementMismatch {
expected: expected.name.clone(),
found: element.name.clone(),
};
out.push(ContractViolation::at(&node, kind));
}
}
if let Some(spec) = node.spec() {
let minted = node.callable_type() == Some(FlmCallableType::Placeholder)
|| element_of_spec(&**spec).is_some()
|| (&**spec as &dyn Any)
.downcast_ref::<ParagraphBreakSpec>()
.is_some();
if !minted {
let name = node.name().unwrap_or_default().to_string();
out.push(ContractViolation::at(
&node,
ContractViolationKind::SpecNotMinted { name },
));
}
let from_fallback = spec
.provenance()
.and_then(|provenance| provenance.provider())
.is_some_and(|provider| provider.name() == FALLBACK_PACKAGE_NAME);
if from_fallback && node.callable_type() == Some(FlmCallableType::Macro) {
let has_arguments = node
.arguments()
.is_some_and(|arguments| !arguments.is_empty());
if has_arguments || node.child_count() > 0 {
let name = node.name().unwrap_or_default().to_string();
out.push(ContractViolation::at(
&node,
ContractViolationKind::FallbackShape { name },
));
}
}
}
if ElementSpec::same_value(element, &ext.structural.unknown_macro)
&& node.callable_type() != Some(FlmCallableType::Macro)
{
out.push(ContractViolation::at(
&node,
ContractViolationKind::UnknownCallableShape {
element: element.name.clone(),
},
));
}
if ElementSpec::same_value(element, &ext.structural.unknown_environment) {
let recovery = node.callable_type() == Some(FlmCallableType::Environment)
&& body_def_of(&node).is_some();
if !recovery {
out.push(ContractViolation::at(
&node,
ContractViolationKind::UnknownCallableShape {
element: element.name.clone(),
},
));
}
}
if node.group_type() == Some(FlmGroupType::Verbatim) {
for child in node.children().iter() {
let own = child.is_chars() && child.span().same_source(node.span());
if own && !interior_rules_off(&child) {
out.push(ContractViolation::at(
&child,
ContractViolationKind::VerbatimInteriorRulesOn,
));
}
}
}
if node.group_type() == Some(FlmGroupType::OpaqueWrapper) {
if let Some((open, close)) = node.group_delimiters() {
if !open.is_empty() || !close.is_empty() {
let kind = ContractViolationKind::OpaqueWrapperDelimiters {
open: open.to_string(),
close: close.to_string(),
};
out.push(ContractViolation::at(&node, kind));
}
}
}
}
out
}
fn interior_rules_off(node: &NodeRef<'_, Flm>) -> bool {
let state = node.parsing_state();
let rules = state.rules();
let (commands_listed, specials_listed) = match &state.ext().restricted_interior {
RestrictedInterior::Template(template) => (!template.commands.is_empty(), template.specials),
RestrictedInterior::Document => (false, false),
};
!rules.comments.enabled
&& !rules.paragraphs.enabled
&& (commands_listed || !rules.commands.enabled)
&& (specials_listed || !rules.specials.enabled)
}
fn regions(callable: &CallableData<Flm>) -> impl Iterator<Item = &ChildRegion> {
callable
.arguments
.iter()
.filter_map(|argument| argument.region.as_ref())
.chain(callable.slots.iter().map(|slot| &slot.region))
}
fn is_region_noise(node: &NodeRef<'_, Flm>) -> bool {
let Some(parent) = node.parent() else {
return false;
};
let Ok(index) = u32::try_from(node.id().index()) else {
return false;
};
if let Some(callable) = parent.callable() {
return !regions(callable).any(|region| {
region.content_parent() == parent.id() && region.content_range().contains(&index)
});
}
let Some(callable) = parent.parent().and_then(|grand| grand.callable()) else {
return false;
};
regions(callable)
.find(|region| region.content_parent() == parent.id())
.is_some_and(|region| !region.content_range().contains(&index))
}
pub fn check_block_contract(tree: &NodeTree<Flm>) -> Vec<ContractViolation> {
let mut out = Vec::new();
if let Err(violation) = validate_tree(tree) {
out.push(ContractViolation {
node: violation.node,
kind: ContractViolationKind::Tree(violation),
});
return out;
}
let facts = Facts::of(tree);
for node in tree.iter_storage_order() {
let ext = node.parsing_state().ext();
let element = element_of(&node);
if node.callable_type() == Some(FlmCallableType::Placeholder)
|| ElementSpec::same_value(element, &ext.structural.placeholder)
{
out.push(ContractViolation::at(
&node,
ContractViolationKind::PlaceholderSurvived,
));
}
if element.has_aspect::<dyn Expand>() {
out.push(ContractViolation::at(
&node,
ContractViolationKind::UseSiteSurvived { element: element.name.clone() },
));
}
if !facts.opaque(&node) && ElementSpec::same_value(element, &ext.structural.parbreak) {
out.push(ContractViolation::at(
&node,
ContractViolationKind::ParbreakSurvived,
));
}
if node.is_callable() {
check_callable_regions(&node, &facts, &mut out);
} else if node.group_type() == Some(FlmGroupType::Paragraph) {
check_paragraph(&node, &facts, &mut out);
} else if node.group_type() == Some(FlmGroupType::Content) {
if !facts.is_content_parent(&node) {
check_inline_container(&node, element, &facts, &mut out);
}
} else if node.is_list() && !facts.is_content_parent(&node) {
check_list(&node, &facts, &mut out);
}
if is_resolved_text(&node, &facts) {
let text = node.chars().unwrap_or("");
let raw = text
.bytes()
.any(|byte| matches!(byte, b'\t' | b'\r' | b'\n'))
|| text.contains(" ");
if raw {
out.push(ContractViolation::at(
&node,
ContractViolationKind::WhitespaceNotCollapsed,
));
}
let next = node
.parent()
.zip(node.index_in_parent())
.and_then(|(parent, index)| parent.child(index + 1));
if next.is_some_and(|next| is_resolved_text(&next, &facts)) {
out.push(ContractViolation::at(
&node,
ContractViolationKind::AdjacentText,
));
}
}
if let Some(map) = node.ext().source_map.as_ref() {
match node.chars() {
None => out.push(ContractViolation::at(
&node,
ContractViolationKind::SourceMapOnNonText,
)),
Some(text) if map.total_len() as usize != text.len() => {
let kind = ContractViolationKind::SourceMapDoesNotTile {
mapped: map.total_len(),
text_len: text.len(),
};
out.push(ContractViolation::at(&node, kind));
}
Some(_) => {}
}
}
}
out
}
fn check_paragraph(
paragraph: &NodeRef<'_, Flm>,
facts: &Facts,
out: &mut Vec<ContractViolation>,
) {
if let Some((open, close)) = paragraph.group_delimiters() {
if !open.is_empty() || !close.is_empty() {
let kind = ContractViolationKind::ParagraphDelimiters {
open: open.to_string(),
close: close.to_string(),
};
out.push(ContractViolation::at(paragraph, kind));
}
}
let children: Vec<NodeRef<'_, Flm>> = paragraph.children().iter().collect();
if !children.iter().any(is_content) {
out.push(ContractViolation::at(
paragraph,
ContractViolationKind::EmptyParagraph,
));
}
for (index, child) in children.iter().enumerate() {
match block_role_of(child) {
BlockRole::Block => {
let kind = ContractViolationKind::BlockInParagraph {
element: element_of(child).name.clone(),
};
out.push(ContractViolation::at(child, kind));
}
BlockRole::BlockDecorator(Placement::Leads) => {
if children[..index].iter().any(|before| !before.is_comment()) {
let kind = ContractViolationKind::LeadsNotFirst {
element: element_of(child).name.clone(),
};
out.push(ContractViolation::at(child, kind));
}
}
BlockRole::BlockDecorator(Placement::Trails) => {
if children[index + 1..]
.iter()
.any(|after| !after.is_comment())
{
let kind = ContractViolationKind::TrailsNotLast {
element: element_of(child).name.clone(),
};
out.push(ContractViolation::at(child, kind));
}
}
BlockRole::Displayed => check_beside_displayed(&children, index, facts, out),
BlockRole::BlockDecorator(Placement::Free) | BlockRole::Inline(_) => {}
}
}
let leads = |node: &NodeRef<'_, Flm>| {
node.is_comment()
|| matches!(
block_role_of(node),
BlockRole::BlockDecorator(Placement::Leads)
)
};
let trails = |node: &NodeRef<'_, Flm>| {
node.is_comment()
|| matches!(
block_role_of(node),
BlockRole::BlockDecorator(Placement::Trails)
)
};
if let Some(head) = children.iter().find(|child| !leads(child)) {
let blank = head
.chars()
.is_some_and(|text| text.bytes().next().is_some_and(is_space_byte));
if blank || is_whitespace_of(head) {
out.push(ContractViolation::at(
head,
ContractViolationKind::ParagraphEdgeNotTrimmed,
));
}
}
if let Some(tail) = children.iter().rev().find(|child| !trails(child)) {
let blank = tail
.chars()
.is_some_and(|text| text.bytes().next_back().is_some_and(is_space_byte));
if blank || is_whitespace_of(tail) {
out.push(ContractViolation::at(
tail,
ContractViolationKind::ParagraphEdgeNotTrimmed,
));
}
}
}
fn check_callable_regions(
node: &NodeRef<'_, Flm>,
facts: &Facts,
out: &mut Vec<ContractViolation>,
) {
let Some(callable) = node.callable() else {
return;
};
for i in 0..callable.arguments.len() {
let Some(content) = node.argument_content_nodes(i) else {
continue;
};
let layout = if argument_holds_blocks(node, i) { Region::Blocks } else { Region::Inline };
check_region(node, content.iter(), layout, facts, out);
}
for i in 0..callable.slots.len() {
let Some(content) = node.slot_content_nodes(i) else {
continue;
};
check_region(node, content.iter(), slot_layout(node, i), facts, out);
}
}
fn check_region<'t>(
node: &NodeRef<'t, Flm>,
content: impl Iterator<Item = NodeRef<'t, Flm>>,
layout: Region,
facts: &Facts,
out: &mut Vec<ContractViolation>,
) {
let content: Vec<NodeRef<'t, Flm>> = content.collect();
for (index, child) in content.iter().enumerate() {
if facts.opaque(child) {
continue;
}
match layout {
Region::Blocks if !is_block_child(child) => {
let kind = ContractViolationKind::InlineInBlocksRegion {
element: element_of(child).name.clone(),
};
out.push(ContractViolation::at(child, kind));
}
Region::Inline if is_paragraph(child) => {
let kind = ContractViolationKind::ParagraphInInlineContainer {
element: element_of(node).name.clone(),
};
out.push(ContractViolation::at(child, kind));
}
Region::Inline if is_displayed(child) => {
check_beside_displayed(&content, index, facts, out);
}
Region::Blocks | Region::Inline | Region::Raw(_) => {}
}
}
}
fn check_inline_container(
group: &NodeRef<'_, Flm>,
element: &ElementSpec,
facts: &Facts,
out: &mut Vec<ContractViolation>,
) {
let children: Vec<NodeRef<'_, Flm>> = group.children().iter().collect();
for (index, child) in children.iter().enumerate() {
if is_paragraph(child) {
let kind = ContractViolationKind::ParagraphInInlineContainer {
element: element.name.clone(),
};
out.push(ContractViolation::at(child, kind));
} else if is_displayed(child) {
check_beside_displayed(&children, index, facts, out);
}
}
}
fn check_list(list: &NodeRef<'_, Flm>, facts: &Facts, out: &mut Vec<ContractViolation>) {
let children: Vec<NodeRef<'_, Flm>> = list.children().iter().collect();
let blocks = children.iter().any(is_paragraph);
for (index, child) in children.iter().enumerate() {
if blocks && !is_block_child(child) {
let kind = ContractViolationKind::InlineInBlocksRegion {
element: element_of(child).name.clone(),
};
out.push(ContractViolation::at(child, kind));
} else if !blocks && is_displayed(child) {
check_beside_displayed(&children, index, facts, out);
}
}
}
fn check_beside_displayed(
run: &[NodeRef<'_, Flm>],
index: usize,
facts: &Facts,
out: &mut Vec<ContractViolation>,
) {
let before = run[..index]
.iter()
.rev()
.find(|node| !node.is_comment())
.filter(|node| {
is_whitespace_of(node)
|| node
.chars()
.is_some_and(|text| text.bytes().next_back().is_some_and(is_space_byte))
});
let after = run[index + 1..]
.iter()
.find(|node| !node.is_comment())
.filter(|node| {
is_whitespace_of(node)
|| node
.chars()
.is_some_and(|text| text.bytes().next().is_some_and(is_space_byte))
});
for neighbor in before.into_iter().chain(after) {
if !facts.opaque(neighbor) {
let kind = ContractViolationKind::WhitespaceBesideDisplayed {
element: element_of(&run[index]).name.clone(),
};
out.push(ContractViolation::at(neighbor, kind));
}
}
}
fn is_paragraph(node: &NodeRef<'_, Flm>) -> bool {
node.group_type() == Some(FlmGroupType::Paragraph)
}
fn is_displayed(node: &NodeRef<'_, Flm>) -> bool {
block_role_of(node) == BlockRole::Displayed
}
fn is_block_child(node: &NodeRef<'_, Flm>) -> bool {
is_paragraph(node) || node.is_comment() || matches!(block_role_of(node), BlockRole::Block)
}
fn is_resolved_text(node: &NodeRef<'_, Flm>, facts: &Facts) -> bool {
node.is_chars() && !facts.opaque(node) && !is_region_noise(node)
}