use std::collections::BTreeMap;
use techy::core::node::{NodeRef, NodeTree};
use techy::error::Diagnostic;
use techy::serialize::SerialValue;
use crate::core::data::store::StageOut;
use crate::core::data::table::{PieceClass, ProjectCx, SingletonTable, Table, TableName};
use crate::core::plan::PlanCx;
use crate::core::run::StageCx;
use crate::core::stage::{Effect, Needs, Scope, Stage, StageDecl};
use crate::lang::rewrites::blocks::run_holds_blocks;
use crate::lang::text::plain_text;
use crate::lang::{Flm, FlmDiagnostics};
use crate::model::element::element_value;
use super::diagnostics::{EntryCites, EntryNotInline, NoProvider, ProviderFailed, ProviderWarning};
use super::elements::CitationElement;
use super::numbers::{number_works, stage_failed, CITATIONS, KEYS};
use super::providers::{
CitationAnswer, CitationEntry, CitationProvider, CitationProviderError, CitationRequest,
ProviderCx, PROVIDERS_SLOT,
};
pub const ENTRIES: TableName<CitationEntries> = TableName::new("flm.citations.entries");
pub const RETRIEVE: &str = "flm.citations.retrieve";
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum MissingEntry {
NoProviderInstalled,
UnknownProvider,
Failed(CitationProviderError),
Cites,
NotInline,
Unprocessable,
}
impl MissingEntry {
pub fn reason(&self) -> String {
match self {
MissingEntry::NoProviderInstalled => "no bibliography source set up".to_string(),
MissingEntry::UnknownProvider => "no appropriate citation provider found".to_string(),
MissingEntry::Failed(error) => format!("failed to retrieve the bibliography entry ({error})"),
MissingEntry::Cites => "the bibliography entry may not use ‘\\cite’ recursively".to_string(),
MissingEntry::NotInline => {
"the bibliography entry must hold inline content only (no paragraph breaks or blocks)".to_string()
}
MissingEntry::Unprocessable => "failed to process the bibliography entry".to_string(),
}
}
fn token(&self) -> &'static str {
match self {
MissingEntry::NoProviderInstalled => "no-provider",
MissingEntry::UnknownProvider => "unknown",
MissingEntry::Failed(_) => "failed",
MissingEntry::Cites => "cites",
MissingEntry::NotInline => "not-inline",
MissingEntry::Unprocessable => "unprocessable",
}
}
}
#[derive(Debug, Clone)]
pub enum Retrieval {
Found(CitationAnswer),
Missing(MissingEntry),
}
#[derive(Debug, Clone, Default)]
pub struct CitationEntries {
keys: Vec<String>,
retrieved: BTreeMap<String, Retrieval>,
}
impl CitationEntries {
pub fn get(&self, key: &str) -> Option<&Retrieval> {
self.retrieved.get(key)
}
pub fn entry(&self, key: &str) -> Option<&CitationEntry> {
match self.retrieved.get(key)? {
Retrieval::Found(answer) => Some(&answer.entry),
Retrieval::Missing(_) => None,
}
}
pub fn iter(&self) -> impl Iterator<Item = (&str, &Retrieval)> {
self.keys.iter().filter_map(|key| self.retrieved.get(key).map(|found| (key.as_str(), found)))
}
pub fn len(&self) -> usize {
self.keys.len()
}
pub fn is_empty(&self) -> bool {
self.keys.is_empty()
}
fn record(&mut self, key: &str, retrieval: Retrieval) {
if self.retrieved.contains_key(key) {
return;
}
self.keys.push(key.to_string());
self.retrieved.insert(key.to_string(), retrieval);
}
}
impl Table for CitationEntries {
fn absorb(&mut self, piece: CitationEntries) {
let CitationEntries { keys, mut retrieved } = piece;
for key in keys {
if let Some(found) = retrieved.remove(&key) {
self.record(&key, found);
}
}
}
fn project(&self, _cx: &dyn ProjectCx) -> SerialValue {
SerialValue::List(
self.iter()
.map(|(key, found)| {
let (field, value) = match found {
Retrieval::Found(answer) => ("entry", plain_text(&answer.entry.content)),
Retrieval::Missing(missing) => ("missing", missing.token().to_string()),
};
SerialValue::Map(vec![
("key".to_string(), SerialValue::Str(key.to_string())),
(field.to_string(), SerialValue::Str(value)),
])
})
.collect(),
)
}
fn piece_class(&self) -> PieceClass {
if self.is_empty() { PieceClass::Empty } else { PieceClass::DocumentFact }
}
}
impl SingletonTable for CitationEntries {
const NAME: &'static str = "flm.citations.entries";
}
fn cites(tree: &NodeTree<Flm>) -> bool {
tree.root().descendants().any(|node| element_value::<CitationElement>(&node).is_some())
}
fn retrieve(keys: &[&str], providers: &[&dyn CitationProvider], cx: &ProviderCx<'_>) -> Vec<Retrieval> {
if providers.is_empty() {
return keys.iter().map(|_| Retrieval::Missing(MissingEntry::NoProviderInstalled)).collect();
}
let mut decided: Vec<Option<Retrieval>> = keys.iter().map(|_| None).collect();
let mut pending: Vec<usize> = (0..keys.len()).collect();
for provider in providers {
if pending.is_empty() {
break;
}
let requests: Vec<CitationRequest> = pending.iter().map(|&at| CitationRequest::new(keys[at])).collect();
let answers = provider.answer_all(&requests, cx);
if answers.len() != requests.len() {
let error = CitationProviderError::new(format!(
"the citation provider returned {} for {}; expected one result per key",
counted(answers.len(), "result", "results"),
counted(requests.len(), "key", "keys")
));
for &at in &pending {
decided[at] = Some(Retrieval::Missing(MissingEntry::Failed(error.clone())));
}
pending.clear();
break;
}
let mut unclaimed = Vec::new();
for (&at, answer) in pending.iter().zip(answers) {
match answer {
Ok(None) => unclaimed.push(at),
Ok(Some(answer)) => decided[at] = Some(Retrieval::Found(answer)),
Err(error) => decided[at] = Some(Retrieval::Missing(MissingEntry::Failed(error))),
}
}
pending = unclaimed;
}
decided.into_iter().map(|found| found.unwrap_or(Retrieval::Missing(MissingEntry::UnknownProvider))).collect()
}
fn counted(count: usize, one: &str, many: &str) -> String {
format!("{count} {}", if count == 1 { one } else { many })
}
fn refusal(cx: &StageCx<'_>, entry: &CitationEntry, diags: &mut FlmDiagnostics) -> Option<MissingEntry> {
let caught = match cx.resolve_value(&entry.content) {
Ok(caught) => caught,
Err(error) => {
if let Some(diagnostic) = error.diagnostic() {
diags.push(diagnostic.clone());
}
return Some(MissingEntry::Unprocessable);
}
};
for diagnostic in caught.diags {
diags.push(diagnostic);
}
if cites(&caught.tree) {
return Some(MissingEntry::Cites);
}
let content: Vec<NodeRef<'_, Flm>> = caught.tree.root().children().iter().collect();
if run_holds_blocks(&content) {
return Some(MissingEntry::NotInline);
}
None
}
#[derive(Debug, Default)]
pub(super) struct Retrieve;
impl Stage for Retrieve {
fn decl(&self) -> StageDecl {
StageDecl::new(RETRIEVE, Effect::Compute, Scope::Document).writes(ENTRIES).writes(CITATIONS).docs(
"Retrieves the citation entries of the cited keys from the citation providers in \
`flm.citations.providers` and writes them to `flm.citations.entries`, then numbers \
the cited works in order of first citation and writes the numbers to `flm.citations`.",
)
}
fn needs(&self, _cx: &PlanCx<'_>) -> Needs {
Needs::new().reads(KEYS)
}
fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
let cited = match cx.get(KEYS) {
Ok(Some(cited)) => cited,
Ok(None) => return,
Err(error) => return stage_failed(out, RETRIEVE, error),
};
let providers: Vec<&dyn CitationProvider> =
cx.registry().services().services_by_precedence_named::<dyn CitationProvider>(PROVIDERS_SLOT).collect();
let provider_cx = ProviderCx::new(cx.registry().lang(), cx.progress());
if providers.is_empty() {
if let Some((key, span)) = cited.iter().next() {
out.diags.push(Diagnostic::error(NoProvider { key: key.to_string() }, span.clone()));
}
}
let keys: Vec<&str> = cited.iter().map(|(key, _)| key).collect();
let answers = retrieve(&keys, &providers, &provider_cx);
let mut entries = CitationEntries::default();
let mut identities: Vec<(&str, String)> = Vec::with_capacity(keys.len());
for ((key, span), mut found) in cited.iter().zip(answers) {
let identity = match &found {
Retrieval::Found(answer) => answer.identity_for(key).to_string(),
Retrieval::Missing(_) => key.to_string(),
};
identities.push((key, identity));
if let Retrieval::Found(answer) = &found {
for detail in &answer.warnings {
let warning = ProviderWarning { key: key.to_string(), detail: detail.clone() };
out.diags.push(Diagnostic::warning(warning, span.clone()));
}
if let Some(missing) = refusal(cx, &answer.entry, &mut out.diags) {
found = Retrieval::Missing(missing);
}
}
let (owned, span) = (key.to_string(), span.clone());
match &found {
Retrieval::Missing(MissingEntry::Failed(error)) => out.diags.push(Diagnostic::error(
ProviderFailed { key: owned, detail: error.detail.clone() },
span,
)),
Retrieval::Missing(MissingEntry::Cites) => out.diags.push(Diagnostic::error(EntryCites { key: owned }, span)),
Retrieval::Missing(MissingEntry::NotInline) => {
out.diags.push(Diagnostic::error(EntryNotInline { key: owned }, span))
}
_ => {}
}
entries.record(key, found);
}
let works = number_works(identities.iter().map(|(key, identity)| (*key, identity.as_str())));
match out.table(ENTRIES) {
Ok(table) => *table = entries,
Err(error) => stage_failed(out, RETRIEVE, error),
}
match out.table(CITATIONS) {
Ok(table) => *table = works,
Err(error) => stage_failed(out, RETRIEVE, error),
}
}
}