use std::fmt;
use std::sync::Arc;
use techy::core::node::{NodeRef, NodeTree};
use techy::error::Severity;
use crate::lang::copy::{copy_pieces_into_value, CommandPiece, ValueContent, ValuePiece};
use crate::lang::{parse_fragment, BuiltLang, Flm, FlmOrigin, FlmSource, ParseOptions};
use crate::model::doc::{Fragment, FragmentLayout};
use crate::progress::Scope;
use crate::stdlib::features::href::HrefCommand;
use crate::stdlib::features::textstyles::TextStyle;
pub const PROVIDERS_SLOT: &str = "flm.citations.providers";
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct CitationRequest {
pub key: String,
}
impl CitationRequest {
pub(super) fn new(key: impl Into<String>) -> CitationRequest {
CitationRequest { key: key.into() }
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CitationEntry {
pub content: Arc<NodeTree<Flm>>,
}
impl CitationEntry {
pub fn new(content: Arc<NodeTree<Flm>>) -> CitationEntry {
CitationEntry { content }
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CitationAnswer {
pub entry: CitationEntry,
pub identity: Option<String>,
pub warnings: Vec<String>,
}
impl CitationAnswer {
pub fn new(entry: CitationEntry) -> CitationAnswer {
CitationAnswer { entry, identity: None, warnings: Vec::new() }
}
pub fn with_identity(mut self, identity: impl Into<String>) -> CitationAnswer {
self.identity = Some(identity.into());
self
}
pub fn with_warning(mut self, text: impl Into<String>) -> CitationAnswer {
self.warnings.push(text.into());
self
}
pub fn identity_for<'a>(&'a self, key: &'a str) -> &'a str {
self.identity.as_deref().unwrap_or(key)
}
}
pub type CitationResult = Result<Option<CitationAnswer>, CitationProviderError>;
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum EntryPiece {
Text(String),
Source(Arc<FlmSource>),
Emphasized(Vec<EntryPiece>),
Strong(Vec<EntryPiece>),
Link {
address: String,
content: Vec<EntryPiece>,
},
}
impl EntryPiece {
pub fn text(text: impl Into<String>) -> EntryPiece {
EntryPiece::Text(text.into())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CitationProviderError {
pub detail: String,
}
impl CitationProviderError {
pub fn new(detail: impl Into<String>) -> CitationProviderError {
CitationProviderError { detail: detail.into() }
}
}
impl fmt::Display for CitationProviderError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.detail)
}
}
impl std::error::Error for CitationProviderError {}
#[derive(Debug, Clone, Copy)]
pub struct ProviderCx<'a> {
lang: &'a BuiltLang,
progress: &'a Scope,
}
impl<'a> ProviderCx<'a> {
pub(super) fn new(lang: &'a BuiltLang, progress: &'a Scope) -> ProviderCx<'a> {
ProviderCx { lang, progress }
}
pub fn progress(&self) -> &'a Scope {
self.progress
}
pub fn lang(&self) -> &'a BuiltLang {
self.lang
}
pub fn parse_entry(&self, source: Arc<FlmSource>) -> Result<CitationEntry, CitationProviderError> {
let fragment = self.parse_inline(source)?;
let root = fragment.tree().root();
let nodes: Vec<ValuePiece<'_, '_>> = root.children().iter().map(ValuePiece::Node).collect();
self.copy(&nodes, &root).map(CitationEntry::new)
}
pub fn build_entry(&self, pieces: &[EntryPiece]) -> Result<CitationEntry, CitationProviderError> {
let anchor = self.parse_inline(Arc::new(FlmSource::new("").with_origin(FlmOrigin::none())))?;
self.build(pieces, &anchor.tree().root()).map(CitationEntry::new)
}
fn parse_inline(&self, source: Arc<FlmSource>) -> Result<Fragment, CitationProviderError> {
let fragment =
parse_fragment(self.lang, source, FragmentLayout::Inline, &ParseOptions::default())
.map_err(|error| CitationProviderError::new(error.to_string()))?;
if let Some(error) = fragment.diags().iter().find(|d| d.severity() == Severity::Error) {
return Err(CitationProviderError::new(error.message()));
}
Ok(fragment)
}
fn copy(&self, pieces: &[ValuePiece<'_, '_>], anchor: &NodeRef<'_, Flm>) -> Result<Arc<NodeTree<Flm>>, CitationProviderError> {
copy_pieces_into_value(pieces, anchor, ValueContent::Own, self.lang.guard())
.map_err(|error| CitationProviderError::new(error.to_string()))
}
fn build(&self, pieces: &[EntryPiece], anchor: &NodeRef<'_, Flm>) -> Result<Arc<NodeTree<Flm>>, CitationProviderError> {
enum Part<'p> {
Text(&'p str),
Tree(Arc<NodeTree<Flm>>),
}
let mut parts = Vec::with_capacity(pieces.len());
for piece in pieces {
let part = match piece {
EntryPiece::Text(text) => Part::Text(text),
EntryPiece::Source(source) => Part::Tree(Arc::clone(self.parse_inline(Arc::clone(source))?.tree())),
EntryPiece::Emphasized(content) => {
Part::Tree(self.group(TextStyle::Emphasis.command(), None, content, anchor)?)
}
EntryPiece::Strong(content) => Part::Tree(self.group(TextStyle::Bold.command(), None, content, anchor)?),
EntryPiece::Link { address, content } => {
Part::Tree(self.group(HrefCommand::Href.name(), Some(address), content, anchor)?)
}
};
parts.push(part);
}
let values: Vec<ValuePiece<'_, '_>> = parts
.iter()
.flat_map(|part| match part {
Part::Text(text) => vec![ValuePiece::Text(text)],
Part::Tree(tree) => tree.root().children().iter().map(ValuePiece::Node).collect(),
})
.collect();
self.copy(&values, anchor)
}
fn group(
&self,
name: &str,
first: Option<&str>,
content: &[EntryPiece],
anchor: &NodeRef<'_, Flm>,
) -> Result<Arc<NodeTree<Flm>>, CitationProviderError> {
let inner = self.build(content, anchor)?;
let command = CommandPiece::new(name, anchor.span().clone(), Arc::clone(anchor.parsing_state()))
.map_err(|error| CitationProviderError::new(error.to_string()))?;
let Some(mut command) = command else {
return Ok(inner);
};
let root = inner.root();
let nodes: Vec<ValuePiece<'_, '_>> = root.children().iter().map(ValuePiece::Node).collect();
if let Some(first) = first {
command.arguments.push(Some(vec![ValuePiece::Text(first)]));
}
command.arguments.push(Some(nodes));
self.copy(&[ValuePiece::Command(&command)], anchor)
}
}
pub trait CitationProvider: Send + Sync {
fn answer(&self, request: &CitationRequest, cx: &ProviderCx<'_>) -> CitationResult;
fn answer_all(&self, requests: &[CitationRequest], cx: &ProviderCx<'_>) -> Vec<CitationResult> {
requests.iter().map(|request| self.answer(request, cx)).collect()
}
}