use std::collections::BTreeSet;
use techy::error::Diagnostic;
use techy::core::node::NodeRef;
use crate::core::data::store::StageOut;
use crate::core::plan::PlanCx;
use crate::core::registry::FlmRegistry;
use crate::core::run::StageCx;
use crate::core::stage::{Effect, Needs, Scope, Stage, StageDecl};
use crate::lang::{Flm, FlmOrigin, FlmSpan, nowhere};
use crate::model::aspects::Referenceable;
use crate::stdlib::features::index::{ELEMENT_INDEX, walk_values_of};
use crate::stdlib::features::refs::{REF_RESOLUTIONS, Resolution};
use super::config::TheoremsConfig;
use super::diagnostics::{BadRelationRef, MissingProof, StageFailed};
use super::elements::{
TITLE_ARG, TheoremElement, TitleReading, has_noproofref, relation_site_id, theorem_point,
title_reading,
};
pub const CHECK_PROOFS: &str = "flm.theorems.check-proofs";
pub(super) struct CheckProofs {
proof_kind: Option<String>,
}
impl CheckProofs {
pub(super) fn new(config: &TheoremsConfig) -> CheckProofs {
let proof_kind = config
.kinds
.iter()
.find(|(_, kind)| config.classes.get(&kind.class).is_some_and(|class| class.relation_ref))
.map(|(name, _)| name.to_string());
CheckProofs { proof_kind }
}
}
fn resolutions_declared(registry: &FlmRegistry) -> bool {
registry.cap_id(REF_RESOLUTIONS.name()).is_some()
}
fn title_span(node: &NodeRef<'_, Flm>) -> FlmSpan {
node.argument_content_nodes_named(TITLE_ARG)
.ok()
.flatten()
.and_then(|title| title.iter().next().map(|first| first.span().clone()))
.unwrap_or_else(|| node.span().clone())
}
fn accepted_label(value: &TheoremElement, node: &NodeRef<'_, Flm>) -> Option<String> {
let point = value.points(node).into_iter().next()?;
let label = point.labels.iter().find(|label| point.accepts.accepts(&label.ref_type))?;
Some(label.to_string())
}
fn stage_failed(out: &mut StageOut<'_>, detail: impl ToString) {
out.diags.push(Diagnostic::error(
StageFailed { stage: CHECK_PROOFS.to_string(), detail: detail.to_string() },
nowhere(FlmOrigin::none()),
));
}
impl Stage for CheckProofs {
fn decl(&self) -> StageDecl {
StageDecl::new(CHECK_PROOFS, Effect::Check, Scope::Document).provides(CHECK_PROOFS).docs(
"Reports a warning for each theorem that has no proof although its kind expects \
one, unless the theorem carries `\\noproofref`. Reports an error for each title \
of a proof that begins with a star but is not a valid back-reference.",
)
}
fn needs(&self, cx: &PlanCx<'_>) -> Needs {
let needs = Needs::new().reads(ELEMENT_INDEX);
if resolutions_declared(cx.registry()) { needs.reads(REF_RESOLUTIONS) } else { needs }
}
fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
let index = match cx.get(ELEMENT_INDEX) {
Ok(Some(index)) => index,
Ok(None) => return,
Err(error) => return stage_failed(out, error),
};
let resolutions = if resolutions_declared(cx.registry()) {
match cx.get(REF_RESOLUTIONS) {
Ok(resolutions) => resolutions,
Err(error) => return stage_failed(out, error),
}
} else {
None
};
let mut theorems = Vec::new();
let mut proved = BTreeSet::new();
for (addr, node, value) in walk_values_of::<TheoremElement>(cx, index) {
let site = relation_site_id(addr);
if let Some(Resolution::Resolved { point: Some(point), .. }) =
resolutions.and_then(|resolutions| resolutions.site(site))
{
proved.insert(*point);
}
theorems.push((addr, node, value));
}
for (addr, node, value) in theorems {
if title_reading(&node) == Some(TitleReading::Malformed) {
out.diags.push(Diagnostic::error(
BadRelationRef { environment: value.name.to_string() },
title_span(&node),
));
}
let point = theorem_point(addr);
if resolutions.is_some()
&& value.kind.expects_proof
&& !proved.contains(&point)
&& !has_noproofref(&node)
{
let Some(label_type) = value.label_types.first() else { continue };
let missing = MissingProof {
kind: value.name.to_string(),
label: accepted_label(value, &node),
label_type: label_type.clone(),
proof_kind: self.proof_kind.clone(),
};
out.diags.push(Diagnostic::warning(missing, node.span().clone()));
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_stage_is_a_document_check_providing_its_capability() {
let decl = CheckProofs::new(&TheoremsConfig::new()).decl();
assert_eq!(decl.name, CHECK_PROOFS);
assert_eq!(decl.effect, Effect::Check);
assert_eq!(decl.scope, Scope::Document);
assert_eq!(decl.provides, [crate::model::names::CapName::from(CHECK_PROOFS)]);
assert!(decl.writes.is_empty());
}
#[test]
fn the_proof_kind_is_the_first_kind_of_a_class_reading_back_references() {
assert_eq!(CheckProofs::new(&TheoremsConfig::new()).proof_kind.as_deref(), Some("proof"));
assert_eq!(CheckProofs::new(&TheoremsConfig::new().without_kind("proof")).proof_kind, None);
}
}