use std::any::Any;
use std::cell::{Cell, RefCell};
use std::collections::BTreeMap;
use std::fmt;
use std::rc::Rc;
use std::sync::Arc;
use techy::core::node::{NodeRef, NodeTree};
use techy::error::{Diagnostic, DiagnosticInfo};
use crate::model::addr::{NodeAddr, TreeId};
use crate::model::doc::{Doc, Fragment, FragmentLayout};
use crate::model::names::{CapName, ElementName, StageName};
use crate::model::options::{OptionError, Options, ResolvedOptions};
use serde_json::Value;
use crate::core::plan::Plan;
use crate::core::plan::build::{request_subject, unchecked_output_message};
use crate::core::registry::StageKind;
use crate::core::registry::frozen::{FlmRegistry, StageIdx};
use crate::core::services::Services;
use crate::core::stage::{RewriteError, Scope};
use crate::core::data::store::{
AccessError, Computed, ComputedView, FoldTarget, StageOut, StoreError, fold_outs,
};
use crate::core::data::table::{SingletonTable, TableKey};
use crate::core::run::order::{DocPosition, RunOrder};
use crate::lang::structural::StructuralElements;
use crate::lang::{Flm, FlmDiagnostic, FlmDiagnostics, FlmSpan};
use crate::progress;
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.run.missing-entry",
message = "this `{element}` element has no entry in table `{table}` (written by \
`{producer}`), because it is inside content generated during processing, for \
which no such data is recorded"
)]
pub struct MissingEntry {
pub table: String,
pub producer: String,
pub element: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.synth.nesting-too-deep",
message = "in content generated during processing, {detail}"
)]
pub struct SynthNestingTooDeep {
pub detail: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(id = "flm.run.ignored-preference")]
pub struct IgnoredPreference {
pub stage: String,
pub excluded_by: String,
pub over: String,
pub workflow: Option<String>,
}
impl fmt::Display for IgnoredPreference {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} prefers the stage `{}`, but that stage cannot be scheduled: the scheduled \
stage `{}` also provides `{}`, and only one scheduled stage may provide each \
capability",
request_subject(self.workflow.as_deref()),
self.stage,
self.excluded_by,
self.over
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(id = "flm.run.preferred-rule-set-aside")]
pub struct PreferredRuleSetAside {
pub rule: String,
pub backend: String,
pub unresolved: Vec<String>,
pub workflow: Option<String>,
}
impl fmt::Display for PreferredRuleSetAside {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} prefers the lowering rule `{}` on backend `{}`, but that rule cannot be used: \
it depends on {}, which no registered feature declares",
request_subject(self.workflow.as_deref()),
self.rule,
self.backend,
self.unresolved.join(", ")
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(id = "flm.run.preferred-rule-not-candidate")]
pub struct PreferredRuleNotCandidate {
pub rule: String,
pub backend: String,
pub workflow: Option<String>,
}
impl fmt::Display for PreferredRuleNotCandidate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} prefers the lowering rule `{}` on backend `{}`, but that rule is marked as the \
default on other backends only, which restricts it to those backends",
request_subject(self.workflow.as_deref()),
self.rule,
self.backend
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(id = "flm.run.unchecked-output")]
pub struct UncheckedOutput {
pub feature: String,
pub backend: String,
pub written: String,
pub reader: String,
pub workflow: Option<String>,
}
impl fmt::Display for UncheckedOutput {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&unchecked_output_message(
&self.feature,
&self.backend,
&self.written,
&self.reader,
))
}
}
#[derive(Debug)]
pub enum CatchUpError {
NestingTooDeep(FlmDiagnostic),
Rewrite {
stage: StageName,
diagnostic: FlmDiagnostic,
},
Store(StoreError),
}
impl CatchUpError {
pub fn diagnostic(&self) -> Option<&FlmDiagnostic> {
match self {
CatchUpError::NestingTooDeep(d) => Some(d),
CatchUpError::Rewrite { diagnostic, .. } => Some(diagnostic),
CatchUpError::Store(_) => None,
}
}
}
impl fmt::Display for CatchUpError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CatchUpError::NestingTooDeep(d) => write!(f, "{}", d.message()),
CatchUpError::Rewrite { stage, diagnostic } => {
write!(
f,
"rewrite stage `{stage}` failed on content generated during processing: {}",
diagnostic.message()
)
}
CatchUpError::Store(error) => fmt::Display::fmt(error, f),
}
}
}
impl std::error::Error for CatchUpError {}
impl From<StoreError> for CatchUpError {
fn from(error: StoreError) -> CatchUpError {
CatchUpError::Store(error)
}
}
pub(crate) struct RunView<'r> {
pub doc: &'r Doc,
pub registry: &'r FlmRegistry,
pub plan: &'r Plan,
pub frozen: &'r BTreeMap<TreeId, Arc<NodeTree<Flm>>>,
pub order: &'r RunOrder,
pub tree_index: &'r BTreeMap<usize, TreeId>,
pub computed: &'r Computed,
pub options: &'r BTreeMap<StageIdx, Arc<ResolvedOptions>>,
}
type ValueTrees = Vec<(usize, TreeId, Arc<NodeTree<Flm>>)>;
struct ValueSpace {
next: Cell<u32>,
trees: RefCell<ValueTrees>,
}
pub struct CaughtUp {
pub id: TreeId,
pub tree: Arc<NodeTree<Flm>>,
pub scratch: Computed,
pub diags: FlmDiagnostics,
}
impl CaughtUp {
pub fn view<'a>(&'a self, cx: &StageCx<'a>) -> ComputedView<'a> {
cx.view.with_overlay(&self.scratch)
}
}
impl fmt::Debug for CaughtUp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CaughtUp").field("id", &self.id).field("scratch", &self.scratch).finish()
}
}
pub struct StageCx<'a> {
run: &'a RunView<'a>,
stage: StageIdx,
tree: Option<TreeId>,
value_tree: Option<Arc<NodeTree<Flm>>>,
view: ComputedView<'a>,
values: Rc<ValueSpace>,
progress: progress::Scope,
}
impl<'a> StageCx<'a> {
pub(crate) fn new(
run: &'a RunView<'a>,
stage: StageIdx,
tree: Option<TreeId>,
view: ComputedView<'a>,
progress: progress::Scope,
) -> StageCx<'a> {
StageCx {
run,
stage,
tree,
value_tree: None,
view,
values: Rc::new(ValueSpace { next: Cell::new(0), trees: RefCell::new(Vec::new()) }),
progress,
}
}
pub fn doc(&self) -> &'a Doc {
self.run.doc
}
pub fn registry(&self) -> &'a FlmRegistry {
self.run.registry
}
pub fn plan(&self) -> &'a Plan {
self.run.plan
}
pub fn stage_name(&self) -> &'a StageName {
&self.run.registry.stage(self.stage).name
}
pub fn scope(&self) -> Scope {
self.run.registry.stage(self.stage).decl.scope
}
pub fn progress(&self) -> &progress::Scope {
&self.progress
}
pub fn tree_id(&self) -> Option<TreeId> {
self.tree
}
pub fn tree(&self, id: TreeId) -> Option<Arc<NodeTree<Flm>>> {
if id.is_value() {
if self.tree == Some(id) {
return self.value_tree.clone();
}
return self
.values
.trees
.borrow()
.iter()
.find(|(_, tree_id, _)| *tree_id == id)
.map(|(_, _, tree)| Arc::clone(tree));
}
self.run.frozen.get(&id).cloned()
}
pub fn frozen_tree(&self, id: TreeId) -> Option<&'a Arc<NodeTree<Flm>>> {
self.run.frozen.get(&id)
}
pub fn my_tree(&self) -> Option<Arc<NodeTree<Flm>>> {
self.tree.and_then(|id| self.tree(id))
}
pub fn fragment(&self, id: TreeId) -> Option<&'a Arc<Fragment>> {
self.run.doc.content().fragment(id)
}
pub fn layout(&self, id: TreeId) -> Option<FragmentLayout> {
self.fragment(id).map(|fragment| fragment.layout())
}
pub fn trees(&self) -> impl Iterator<Item = (TreeId, &'a Arc<NodeTree<Flm>>)> + 'a {
let run = self.run;
run.order.trees().iter().filter_map(move |id| run.frozen.get(id).map(|tree| (*id, tree)))
}
pub fn walk(&self) -> FrozenWalk<'a> {
FrozenWalk::new(self.run)
}
pub fn position(&self, addr: NodeAddr) -> Option<DocPosition> {
self.run.order.position(addr)
}
pub fn placement_of(&self, addr: NodeAddr) -> Option<TreeId> {
self.run.order.placement_of(addr)
}
pub fn view(&self) -> &ComputedView<'a> {
&self.view
}
pub fn get<K: TableKey>(&self, key: K) -> Result<Option<&'a K::Table>, AccessError> {
self.view.get(key)
}
pub fn get_singleton<T: SingletonTable>(&self) -> Result<Option<&'a T>, AccessError> {
self.view.get_singleton::<T>()
}
pub fn option<T: Options>(&self) -> Result<&'a T, OptionError> {
self.run.options[&self.stage].get::<T>()
}
pub fn option_named(&self, name: &str) -> Result<&'a Value, OptionError> {
self.run.options[&self.stage].get_named(name)
}
pub fn options(&self) -> &'a ResolvedOptions {
&self.run.options[&self.stage]
}
pub fn services_all(&self) -> &'a Services {
self.run.registry.services()
}
pub fn service<S: ?Sized + Any + Send + Sync>(&self) -> Option<&'a S> {
self.run.registry.services().service::<S>()
}
pub fn services<S: ?Sized + Any + Send + Sync>(&self) -> impl Iterator<Item = &'a S> + 'a {
self.run.registry.services().services::<S>()
}
pub fn addr(&self, node: &NodeRef<'_, Flm>) -> Option<NodeAddr> {
let key = node.tree() as *const NodeTree<Flm> as usize;
if let Some(id) = self.run.tree_index.get(&key) {
return Some(NodeAddr::new(*id, node.id()));
}
if let (Some(id), Some(tree)) = (self.tree, &self.value_tree) {
if Arc::as_ptr(tree) as usize == key {
return Some(NodeAddr::new(id, node.id()));
}
}
self.values
.trees
.borrow()
.iter()
.find(|(ptr, _, _)| *ptr == key)
.map(|(_, id, _)| NodeAddr::new(*id, node.id()))
}
pub fn missing_entry(
&self,
table: &CapName,
element: &ElementName,
span: FlmSpan,
) -> FlmDiagnostic {
let producer = self
.view
.producer_of(table)
.map(|s| s.to_string())
.unwrap_or_else(|| "nobody".to_string());
Diagnostic::error(
MissingEntry { table: table.to_string(), producer, element: element.to_string() },
span,
)
}
pub fn resolve_value(&self, value: &Arc<NodeTree<Flm>>) -> Result<CaughtUp, CatchUpError> {
self.resolve_value_with(value, FragmentLayout::default())
}
pub fn resolve_value_with(
&self,
value: &Arc<NodeTree<Flm>>,
layout: FragmentLayout,
) -> Result<CaughtUp, CatchUpError> {
let run = self.run;
let index = self.values.next.get();
self.values.next.set(index + 1);
let id = TreeId::value(index);
let mut diags = FlmDiagnostics::new();
let mut current = Arc::clone(value);
for rewrite in run.plan.rewrites() {
let entry = run.registry.stage(*rewrite);
let StageKind::Rewrite(stage) = &entry.kind else { continue };
let cx = RewriteCx::new(run.registry, id, layout, &run.options[rewrite]);
match stage.rewrite(id, ¤t, &cx, &mut diags) {
Ok(next) => current = next,
Err(RewriteError::NestingTooDeep(diagnostic)) => {
let detail = diagnostic.message();
return Err(CatchUpError::NestingTooDeep(Diagnostic::error(
SynthNestingTooDeep { detail },
diagnostic.span().clone(),
)));
}
Err(error) => {
return Err(CatchUpError::Rewrite {
stage: entry.name.clone(),
diagnostic: error.diagnostic().clone(),
});
}
}
}
self.values.trees.borrow_mut().push((
Arc::as_ptr(¤t) as usize,
id,
Arc::clone(¤t),
));
let mut scratch = Computed::new();
let progress = self.progress.with_depth_limit(0);
for idx in run.plan.per_tree_closure(self.stage) {
let entry = run.registry.stage(idx);
let StageKind::Pipeline(stage) = &entry.kind else { continue };
let plan = run.plan.manifest(idx).expect("a scheduled stage has a manifest");
let mut out = StageOut::new(&entry.name, &plan.writes);
{
let view = ComputedView::new(&entry.name, &plan.reads, run.computed)
.with_overlay(&scratch);
let cx = StageCx {
run,
stage: idx,
tree: Some(id),
value_tree: Some(Arc::clone(¤t)),
view,
values: Rc::clone(&self.values),
progress: progress.clone(),
};
stage.run(&cx, &mut out);
}
fold_outs(
&entry.name,
&plan.writes,
vec![out],
FoldTarget::Scratch,
&mut scratch,
&mut diags,
)?;
}
Ok(CaughtUp { id, tree: current, scratch, diags })
}
}
impl fmt::Debug for StageCx<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StageCx")
.field("stage", self.stage_name())
.field("tree", &self.tree)
.finish()
}
}
pub struct FrozenWalk<'a> {
run: &'a RunView<'a>,
position: usize,
}
impl<'a> FrozenWalk<'a> {
fn new(run: &'a RunView<'a>) -> FrozenWalk<'a> {
FrozenWalk { run, position: 0 }
}
}
impl<'a> Iterator for FrozenWalk<'a> {
type Item = (NodeAddr, NodeRef<'a, Flm>);
fn next(&mut self) -> Option<(NodeAddr, NodeRef<'a, Flm>)> {
let run = self.run;
loop {
let addr = *run.order.walk().get(self.position)?;
self.position += 1;
if let Some(node) = run.frozen.get(&addr.tree).and_then(|tree| tree.get(addr.node)) {
return Some((addr, node));
}
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(0, Some(self.run.order.walk().len().saturating_sub(self.position)))
}
}
pub struct RewriteCx<'a> {
registry: &'a FlmRegistry,
tree: TreeId,
layout: FragmentLayout,
options: &'a ResolvedOptions,
}
impl<'a> RewriteCx<'a> {
pub(crate) fn new(
registry: &'a FlmRegistry,
tree: TreeId,
layout: FragmentLayout,
options: &'a ResolvedOptions,
) -> RewriteCx<'a> {
RewriteCx { registry, tree, layout, options }
}
pub fn registry(&self) -> &'a FlmRegistry {
self.registry
}
pub fn structural(&self) -> &'a Arc<StructuralElements> {
self.registry.structural()
}
pub fn tree_id(&self) -> TreeId {
self.tree
}
pub fn layout(&self) -> FragmentLayout {
self.layout
}
pub fn option<T: Options>(&self) -> Result<&'a T, OptionError> {
self.options.get::<T>()
}
pub fn option_named(&self, name: &str) -> Result<&'a Value, OptionError> {
self.options.get_named(name)
}
}
impl fmt::Debug for RewriteCx<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RewriteCx").field("tree", &self.tree).field("layout", &self.layout).finish()
}
}