use std::any::Any;
use std::fmt;
use std::sync::Arc;
use techy::core::node::{BuildId, NodeRef, NodeSlice, NodeTree};
use techy::error::{Diagnostic, DiagnosticInfo};
use techy::transform::RestageContext;
use crate::model::addr::{NodeAddr, TreeId};
use crate::model::doc::FragmentLayout;
use crate::model::names::{BackendName, CapName, ElementName, Name, RuleName, StageName};
use crate::model::options::{DataValue, OptionError, OptionKey, OptionRef, Options};
use serde_json::Value;
use crate::core::data::store::AccessError;
use crate::core::data::table::{TableKey, TableRef};
use crate::lang::text::{NotCharacters, read_chars};
use crate::lang::{BuiltLang, Flm, FlmCallableType, FlmDiagnostic, FlmSpan, PresPayload};
pub type LowerCx<'a> = RestageContext<'a, Flm, (), ()>;
#[derive(Debug)]
pub enum Lowering {
Default,
Emit(Vec<BuildId>),
}
#[derive(Debug, Clone, Default)]
pub struct LoweringDecl {
pub requires: Vec<CapName>,
pub reads: Vec<TableRef>,
pub reads_opt: Vec<TableRef>,
pub options: Vec<OptionRef>,
pub produces: Vec<ElementName>,
pub selection_requires: Vec<Name>,
pub unchecked_output: Vec<UncheckedOutputDecl>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UncheckedOutputDecl {
pub backend: BackendName,
pub written: String,
pub reader: String,
}
impl LoweringDecl {
pub fn new() -> LoweringDecl {
LoweringDecl::default()
}
pub fn requires(mut self, capability: impl Into<CapName>) -> LoweringDecl {
self.requires.push(capability.into());
self
}
pub fn reads(mut self, table: impl TableKey) -> LoweringDecl {
self.reads.push(table.table_ref());
self
}
pub fn reads_opt(mut self, table: impl TableKey) -> LoweringDecl {
self.reads_opt.push(table.table_ref());
self
}
pub fn option<T: Options>(mut self) -> LoweringDecl {
self.options.push(OptionRef::of::<T>());
self
}
pub fn option_named(mut self, name: impl Into<Name>) -> LoweringDecl {
self.options.push(OptionRef::named(name));
self
}
pub fn produces(mut self, element: impl Into<ElementName>) -> LoweringDecl {
self.produces.push(element.into());
self
}
pub fn selection_requires(mut self, id: impl Into<Name>) -> LoweringDecl {
self.selection_requires.push(id.into());
self
}
pub fn unchecked_output(
mut self,
backend: impl Into<BackendName>,
written: impl Into<String>,
reader: impl Into<String>,
) -> LoweringDecl {
self.unchecked_output.push(UncheckedOutputDecl {
backend: backend.into(),
written: written.into(),
reader: reader.into(),
});
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DefaultMark {
Everywhere,
OnBackends(Vec<BackendName>),
Never,
}
impl DefaultMark {
pub fn is_general(&self) -> bool {
matches!(self, DefaultMark::Everywhere)
}
pub fn is_specific_to(&self, backend: &BackendName) -> bool {
match self {
DefaultMark::OnBackends(backends) => backends.contains(backend),
_ => false,
}
}
pub fn takes_part_on(&self, backend: &BackendName) -> bool {
match self {
DefaultMark::OnBackends(backends) => backends.contains(backend),
DefaultMark::Everywhere | DefaultMark::Never => true,
}
}
}
#[derive(Clone)]
pub struct LoweringRule {
pub name: RuleName,
pub element: ElementName,
pub decl: LoweringDecl,
pub rule: Arc<dyn Lower>,
pub default: DefaultMark,
pub docs: String,
}
impl LoweringRule {
pub fn new(
name: impl Into<RuleName>,
element: impl Into<ElementName>,
decl: LoweringDecl,
rule: Arc<dyn Lower>,
default: DefaultMark,
) -> LoweringRule {
LoweringRule {
name: name.into(),
element: element.into(),
decl,
rule,
default,
docs: String::new(),
}
}
pub fn docs(mut self, docs: impl Into<String>) -> LoweringRule {
self.docs = crate::kept_docs(docs);
self
}
}
impl fmt::Debug for LoweringRule {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("LoweringRule")
.field("name", &self.name)
.field("element", &self.element)
.field("decl", &self.decl)
.field("default", &self.default)
.finish()
}
}
#[derive(Debug, Clone)]
pub enum LowerError {
Access(AccessError),
Option(OptionError),
UndeclaredProduces {
rule: RuleName,
element: ElementName,
declared: Vec<ElementName>,
},
Structure {
detail: String,
},
Build {
detail: String,
},
CatchUp {
detail: String,
},
DocumentFactInValue {
stage: StageName,
table: CapName,
},
Refused(Box<FlmDiagnostic>),
RegionNotFound {
detail: String,
},
PlaceholderCharacters,
Other {
detail: String,
},
}
impl LowerError {
pub fn structure(detail: impl Into<String>) -> LowerError {
LowerError::Structure { detail: detail.into() }
}
pub fn other(detail: impl Into<String>) -> LowerError {
LowerError::Other { detail: detail.into() }
}
}
impl From<AccessError> for LowerError {
fn from(error: AccessError) -> LowerError {
LowerError::Access(error)
}
}
impl From<OptionError> for LowerError {
fn from(error: OptionError) -> LowerError {
LowerError::Option(error)
}
}
impl fmt::Display for LowerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
LowerError::Access(error) => fmt::Display::fmt(error, f),
LowerError::Option(error) => fmt::Display::fmt(error, f),
LowerError::UndeclaredProduces { rule, element, declared } => write!(
f,
"rule `{rule}` builds a node of `{element}`, so it must list `{element}` among \
the elements it produces; it lists: [{}]",
declared.iter().map(|e| e.as_str()).collect::<Vec<_>>().join(", ")
),
LowerError::Structure { detail } => {
write!(
f,
"the content does not have the structure that lowering it requires: {detail}"
)
}
LowerError::Build { detail } => write!(f, "a node could not be built: {detail}"),
LowerError::CatchUp { detail } => {
write!(f, "content generated during processing could not be prepared: {detail}")
}
LowerError::DocumentFactInValue { stage, table } => write!(
f,
"content generated during processing must not state a fact about the whole \
document, such as a label, but stage `{stage}` stated one in `{table}` when it \
ran over that content"
),
LowerError::Refused(diagnostic) => f.write_str(&diagnostic.message()),
LowerError::RegionNotFound { detail } => {
write!(f, "the argument or content slot to lower does not exist: {detail}")
}
LowerError::PlaceholderCharacters => f.write_str(
"a placeholder of a definition's template must not appear where the characters \
of the content are read (such as an address or a reference key): its \
characters are known only once the template is expanded",
),
LowerError::Other { detail } => f.write_str(detail),
}
}
}
impl std::error::Error for LowerError {}
pub fn chars_at_lowering<'t>(
nodes: impl IntoIterator<Item = NodeRef<'t, Flm>>,
) -> Result<Result<String, NotCharacters>, LowerError> {
match read_chars(nodes) {
Ok(read) => read.text().map(Ok).ok_or(LowerError::PlaceholderCharacters),
Err(not) => Ok(Err(not)),
}
}
pub fn spelling_at_lowering<'t>(
nodes: impl IntoIterator<Item = NodeRef<'t, Flm>>,
) -> Result<(), LowerError> {
let placeholder = |node: NodeRef<'t, Flm>| node.callable_type() == Some(FlmCallableType::Placeholder);
let holds = nodes
.into_iter()
.any(|node| placeholder(node) || node.descendants().any(placeholder));
if holds { Err(LowerError::PlaceholderCharacters) } else { Ok(()) }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NodeRegion {
Argument(usize),
Slot(usize),
}
impl NodeRegion {
pub fn argument_named(node: &NodeRef<'_, Flm>, name: &str) -> Option<NodeRegion> {
node.arguments()?
.iter()
.position(|argument| argument.name() == Some(name))
.map(NodeRegion::Argument)
}
pub fn content_nodes<'t>(&self, node: &NodeRef<'t, Flm>) -> Option<Vec<NodeRef<'t, Flm>>> {
match *self {
NodeRegion::Argument(index) => {
if index >= node.arguments()?.len() {
return None;
}
let content = node.argument_content_nodes(index);
Some(content.map(|nodes| nodes.iter().collect()).unwrap_or_default())
}
NodeRegion::Slot(index) => Some(node.slot_content_nodes(index)?.iter().collect()),
}
}
pub fn is_absent(&self, node: &NodeRef<'_, Flm>) -> bool {
match *self {
NodeRegion::Argument(index) => {
node.arguments().is_some_and(|arguments| index < arguments.len())
&& node.argument_content_nodes(index).is_none()
}
NodeRegion::Slot(_) => false,
}
}
}
impl fmt::Display for NodeRegion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
NodeRegion::Argument(index) => write!(f, "argument {index}"),
NodeRegion::Slot(index) => write!(f, "slot {index}"),
}
}
}
pub type RegionShape<'f> = dyn FnMut(
&mut LowerCx<'_>,
&mut dyn Lowerer,
&NodeRef<'_, Flm>,
&[NodeRef<'_, Flm>],
) -> Result<Vec<BuildId>, LowerError>
+ 'f;
pub trait Lower: Send + Sync {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError>;
}
pub trait Lowerer {
fn rule(&self) -> &RuleName;
fn backend(&self) -> &BackendName;
fn comment_start(&self) -> Option<&str>;
fn lang(&self) -> &BuiltLang;
fn tree_id(&self) -> TreeId;
fn layout(&self) -> FragmentLayout;
fn addr(&self) -> NodeAddr;
fn addr_of(&self, node: &NodeRef<'_, Flm>) -> Result<NodeAddr, LowerError>;
fn placement(&self) -> Option<TreeId>;
fn get_erased(&self, table: &TableRef)
-> Result<Option<&(dyn Any + Send + Sync)>, AccessError>;
fn producer_of(&self, table: &CapName) -> Option<StageName>;
fn option_erased(&self, key: OptionKey) -> Result<&(dyn Any + Send + Sync), OptionError>;
fn lower_children(
&mut self,
cx: &mut LowerCx<'_>,
node: &NodeRef<'_, Flm>,
) -> Result<Vec<BuildId>, LowerError>;
fn lower_body(
&mut self,
cx: &mut LowerCx<'_>,
node: &NodeRef<'_, Flm>,
) -> Result<Vec<BuildId>, LowerError>;
fn lower_arg(
&mut self,
cx: &mut LowerCx<'_>,
node: &NodeRef<'_, Flm>,
index: usize,
) -> Result<Vec<BuildId>, LowerError>;
fn lower_arg_named(
&mut self,
cx: &mut LowerCx<'_>,
node: &NodeRef<'_, Flm>,
name: &str,
) -> Result<Vec<BuildId>, LowerError>;
fn lower_nodes(
&mut self,
cx: &mut LowerCx<'_>,
nodes: NodeSlice<'_, Flm>,
) -> Result<Vec<BuildId>, LowerError>;
fn default(
&mut self,
cx: &mut LowerCx<'_>,
node: &NodeRef<'_, Flm>,
) -> Result<Vec<BuildId>, LowerError>;
fn pres(
&mut self,
cx: &mut LowerCx<'_>,
element: &ElementName,
payload: Arc<dyn PresPayload>,
body: Vec<BuildId>,
) -> Result<BuildId, LowerError>;
fn pres_slots(
&mut self,
cx: &mut LowerCx<'_>,
element: &ElementName,
payload: Arc<dyn PresPayload>,
slots: Vec<(String, Vec<BuildId>)>,
) -> Result<BuildId, LowerError> {
let _ = (cx, element, payload, slots);
Err(LowerError::other("this lowerer cannot build a presentation node with content slots"))
}
fn text(&mut self, cx: &mut LowerCx<'_>, text: &str) -> Result<BuildId, LowerError>;
fn splice(
&mut self,
cx: &mut LowerCx<'_>,
value: &Arc<NodeTree<Flm>>,
) -> Result<Vec<BuildId>, LowerError>;
fn lower_region(
&mut self,
cx: &mut LowerCx<'_>,
at: NodeAddr,
region: NodeRegion,
shape: &mut RegionShape<'_>,
) -> Result<Vec<BuildId>, LowerError>;
fn require(&mut self, id: &Name);
fn diagnose(&mut self, diagnostic: FlmDiagnostic);
}
impl dyn Lowerer + '_ {
pub fn get<K: TableKey>(&self, key: K) -> Result<Option<&K::Table>, AccessError> {
Ok(self.get_erased(&key.table_ref())?.map(|table| {
table
.downcast_ref::<K::Table>()
.expect("a table is stored under its declared type, which the key matched")
}))
}
pub fn option<T: Options>(&self) -> Result<&T, OptionError> {
Ok(self
.option_erased(OptionKey::of::<T>())?
.downcast_ref::<T>()
.expect("a resolved option is stored under its own type"))
}
pub fn option_named(&self, name: &str) -> Result<&Value, OptionError> {
Ok(&self
.option_erased(OptionKey::named(name))?
.downcast_ref::<DataValue>()
.expect("an option declared from data is stored as a `DataValue`")
.0)
}
pub fn pres_with<P: PresPayload>(
&mut self,
cx: &mut LowerCx<'_>,
element: &ElementName,
payload: P,
body: Vec<BuildId>,
) -> Result<BuildId, LowerError> {
self.pres(cx, element, Arc::new(payload), body)
}
pub fn pres_slots_with<P: PresPayload>(
&mut self,
cx: &mut LowerCx<'_>,
element: &ElementName,
payload: P,
slots: Vec<(String, Vec<BuildId>)>,
) -> Result<BuildId, LowerError> {
self.pres_slots(cx, element, Arc::new(payload), slots)
}
pub fn error(&mut self, condition: impl DiagnosticInfo, span: FlmSpan) {
self.diagnose(Diagnostic::error(condition, span));
}
pub fn warning(&mut self, condition: impl DiagnosticInfo, span: FlmSpan) {
self.diagnose(Diagnostic::warning(condition, span));
}
pub fn note(&mut self, condition: impl DiagnosticInfo, span: FlmSpan) {
self.diagnose(Diagnostic::note(condition, span));
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_default_mark_answers_per_backend() {
assert!(DefaultMark::Everywhere.is_general());
assert!(!DefaultMark::Never.is_general());
let specific = DefaultMark::OnBackends(vec!["latex-rendered".into()]);
assert!(specific.is_specific_to(&"latex-rendered".into()));
assert!(!specific.is_specific_to(&"text".into()));
assert!(!specific.is_general());
}
}