use std::fmt;
use std::sync::Arc;
use techy::core::node::{BuildId, NodeKind, NodeRef, NodeTree};
use techy::core::Lang;
use techy::error::Diagnostic;
use techy::source::TextContent;
use techy::transform::{Restage, RestageError, RestageVisitor};
use crate::model::element::element_of;
use crate::lang::flm::Flm;
use crate::lang::BuiltLang;
use crate::lang::guard::{self, GuardPolicy, NestingTooDeep};
use crate::lang::origin::{FlmDiagnostic, FlmDiagnostics, FlmSpan};
use crate::lang::parse::WorkerThreadUnavailable;
use crate::lang::rewrites::userdefs::diagnostics::{
BadPlaceholder, ExpansionFailed, PlaceholderProblem, RecursionLimit,
};
use crate::lang::rewrites::userdefs::hook::{
Expand, ExpandCx, ExpandError, ExpandSet, Expander, Expansion, PlaceholderBindings,
};
use crate::lang::rewrites::userdefs::instantiate::{instance_nodes, instantiate};
use crate::lang::rewrites::userdefs::template::CompiledTemplate;
pub const DEFAULT_RECURSION_LIMIT: usize = 32;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExpandOptions {
pub recursion_limit: usize,
pub guard: GuardPolicy,
}
impl Default for ExpandOptions {
fn default() -> ExpandOptions {
ExpandOptions { recursion_limit: DEFAULT_RECURSION_LIMIT, guard: GuardPolicy::StackBudget }
}
}
#[derive(Debug)]
pub enum ExpandFailure {
NestingTooDeep(FlmDiagnostic),
Failed(FlmDiagnostic),
WorkerThread(FlmDiagnostic),
}
impl ExpandFailure {
pub fn diagnostic(&self) -> &FlmDiagnostic {
match self {
ExpandFailure::NestingTooDeep(diagnostic)
| ExpandFailure::Failed(diagnostic)
| ExpandFailure::WorkerThread(diagnostic) => diagnostic,
}
}
}
impl fmt::Display for ExpandFailure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.diagnostic().message())
}
}
impl std::error::Error for ExpandFailure {}
pub fn expand(
tree: &NodeTree<Flm>,
lang: &BuiltLang,
options: &ExpandOptions,
set: ExpandSet,
diags: &mut FlmDiagnostics,
) -> Result<Arc<NodeTree<Flm>>, ExpandFailure> {
let run = || run_pass(tree, lang, options, set, diags);
match guard::on_worker_thread(run) {
Ok(result) => result,
Err(error) => Err(ExpandFailure::WorkerThread(Diagnostic::error(
WorkerThreadUnavailable::new(error.to_string()),
tree.root().span().clone(),
))),
}
}
fn run_pass(
tree: &NodeTree<Flm>,
lang: &BuiltLang,
options: &ExpandOptions,
set: ExpandSet,
diags: &mut FlmDiagnostics,
) -> Result<Arc<NodeTree<Flm>>, ExpandFailure> {
let mut pass = ExpandPass::new(lang, options, set, diags);
let result = guard::restager(&mut pass, options.guard).restage(tree);
match result {
Ok(expanded) => Ok(Arc::new(expanded)),
Err(error) => Err(failure(error, tree.root().span().clone())),
}
}
fn failure(error: RestageError<ExpandError>, at: FlmSpan) -> ExpandFailure {
let refusal = match &error {
RestageError::DescentLimitExceeded { detail, .. } => Some(detail.clone()),
RestageError::Visitor(inner) => inner.descent_refusal().map(String::from),
_ => None,
};
match refusal {
Some(detail) => {
ExpandFailure::NestingTooDeep(Diagnostic::error(NestingTooDeep::new(detail), at))
}
None => {
ExpandFailure::Failed(Diagnostic::error(ExpansionFailed::new(error.to_string()), at))
}
}
}
struct ExpandPass<'d> {
lang: &'d BuiltLang,
diags: &'d mut FlmDiagnostics,
recursion_limit: usize,
guard: GuardPolicy,
set: ExpandSet,
depth: usize,
}
impl<'d> ExpandPass<'d> {
fn new(
lang: &'d BuiltLang,
options: &ExpandOptions,
set: ExpandSet,
diags: &'d mut FlmDiagnostics,
) -> ExpandPass<'d> {
ExpandPass {
lang,
diags,
recursion_limit: options.recursion_limit,
guard: options.guard,
set,
depth: 0,
}
}
}
impl RestageVisitor<Flm, (), ()> for ExpandPass<'_> {
type Error = ExpandError;
fn restage(
&mut self,
node: NodeRef<'_, Flm>,
cx: &mut ExpandCx<'_>,
) -> Result<Restage<()>, ExpandError> {
if let Some(hook) = element_of(&node).aspect::<dyn Expand>() {
if self.set.includes(hook.policy()) {
return Ok(match hook.expand(node, cx, self)? {
Expansion::Default => Restage::Descend(()),
Expansion::Emit(ids) => Restage::Emit(ids),
});
}
}
Ok(Restage::Descend(()))
}
}
impl Expander for ExpandPass<'_> {
fn depth(&self) -> usize {
self.depth
}
fn recursion_limit(&self) -> usize {
self.recursion_limit
}
fn instantiate(
&mut self,
cx: &mut ExpandCx<'_>,
site: NodeRef<'_, Flm>,
template: &CompiledTemplate,
bindings: &dyn PlaceholderBindings,
) -> Result<Vec<BuildId>, ExpandError> {
if self.depth >= self.recursion_limit {
let condition = RecursionLimit::new(template.definition(), self.recursion_limit);
let diagnostic = Diagnostic::error(condition, site.span().clone());
return self.recover(cx, site, diagnostic);
}
let instance = match instantiate(site.span(), template, bindings, self.guard) {
Ok(instance) => instance,
Err(error) => {
let Some(reference) = error.bad_placeholder().map(String::from) else {
return Err(error);
};
let condition = BadPlaceholder::new(
template.definition(),
reference,
PlaceholderProblem::Unresolvable,
);
let diagnostic = Diagnostic::error(condition, site.span().clone());
return self.recover(cx, site, diagnostic);
}
};
self.depth += 1;
let mut ids = Vec::new();
let mut outcome = Ok(());
for child in instance_nodes(&instance).iter() {
match cx.restage_subtree(child, self) {
Ok(staged) => ids.extend(staged),
Err(error) => {
outcome = Err(ExpandError::from(error));
break;
}
}
}
self.depth -= 1;
outcome?;
Ok(ids)
}
fn recover(
&mut self,
cx: &mut ExpandCx<'_>,
site: NodeRef<'_, Flm>,
diagnostic: FlmDiagnostic,
) -> Result<Vec<BuildId>, ExpandError> {
self.diags.push(diagnostic);
let span = site.span().clone();
let kind = NodeKind::<Flm>::chars(TextContent::Spanned(span.span()));
let state = Arc::clone(site.parsing_state());
let builder = cx.builder();
let ext = Flm::make_node_ext(&kind, &span, &state, builder.staged_children(&[]))?;
Ok(vec![builder.add(kind, span, state, Vec::new(), ext, ())?])
}
fn diagnose(&mut self, diagnostic: FlmDiagnostic) {
self.diags.push(diagnostic);
}
fn lang(&self) -> &BuiltLang {
self.lang
}
}