use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use techy::core::node::{
BuildId, CallableData, ChildRegion, NodeBuildError, NodeKind, NodeRef, NodeSlice, NodeTree,
ParsedArgument, ParsedArguments, ParsedSlot, ParsedSlots,
};
use techy::source::{Source, SourceSpan};
use techy::transform::{Restage, RestageContext, RestageVisitor};
use crate::model::element::element_value;
use crate::lang::flm::{Flm, FlmCallableType};
use crate::lang::origin::{FlmOrigin, FlmSource, FlmSpan};
use crate::lang::guard::{self, GuardPolicy};
use crate::lang::text::is_blank;
use crate::lang::rewrites::userdefs::hook::{ExpandError, PlaceholderBindings, PlaceholderValue};
use crate::lang::rewrites::userdefs::template::{
substitution_of, substitution_text_of, CompiledTemplate, Conditional, ConditionalTest,
PlaceholderRef, PlaceholderTarget,
};
type Cx<'t> = RestageContext<'t, Flm, (), ()>;
const BLANK_TEST_DEPTH: usize = 32;
pub(crate) struct Verbatim;
impl RestageVisitor<Flm, (), ()> for Verbatim {
type Error = ExpandError;
fn restage(
&mut self,
_node: NodeRef<'_, Flm>,
_cx: &mut Cx<'_>,
) -> Result<Restage<()>, ExpandError> {
Ok(Restage::Descend(()))
}
}
fn copy_slice(cx: &mut Cx<'_>, slice: NodeSlice<'_, Flm>) -> Result<Vec<BuildId>, ExpandError> {
let mut ids = Vec::new();
for node in slice.iter() {
ids.extend(cx.restage_subtree(node, &mut Verbatim)?);
}
Ok(ids)
}
pub(crate) fn is_noise(node: &NodeRef<'_, Flm>) -> bool {
node.is_comment() || is_blank(node)
}
pub(crate) fn is_blank_node(node: &NodeRef<'_, Flm>) -> bool {
node.is_comment()
}
pub(crate) struct Substitute<'a> {
bindings: &'a dyn PlaceholderBindings,
templates: Vec<&'a CompiledTemplate>,
}
impl<'a> Substitute<'a> {
pub(crate) fn new(
template: &'a CompiledTemplate,
bindings: &'a dyn PlaceholderBindings,
) -> Substitute<'a> {
Substitute { bindings, templates: vec![template] }
}
pub(crate) fn templates(&self) -> &[&'a CompiledTemplate] {
&self.templates
}
fn remember(&mut self, template: &'a CompiledTemplate) {
if !self.templates.iter().any(|known| std::ptr::eq(*known, template)) {
self.templates.push(template);
}
}
fn placeholder_of(&self, node: &NodeRef<'_, Flm>) -> Option<&'a PlaceholderRef> {
self.templates.iter().find_map(|template| template.placeholder(node.id()))
}
fn value_of(&self, node: &NodeRef<'_, Flm>) -> Result<PlaceholderValue<'a>, ExpandError> {
let Some(reference) = self.placeholder_of(node) else {
return Err(ExpandError::BadPlaceholder {
reference: node.name().unwrap_or("").to_string(),
});
};
match self.bindings.value(&reference.target, substitution_of(node)) {
PlaceholderValue::Unresolvable => {
Err(ExpandError::BadPlaceholder { reference: reference.written.clone() })
}
value => Ok(value),
}
}
fn substitute(
&mut self,
node: NodeRef<'_, Flm>,
cx: &mut Cx<'_>,
) -> Result<Vec<BuildId>, ExpandError> {
match self.value_of(&node)? {
PlaceholderValue::NoValue | PlaceholderValue::Unresolvable => Ok(Vec::new()),
PlaceholderValue::Provided(content) => copy_slice(cx, content),
PlaceholderValue::Substitution => match substitution_of(&node) {
Some(content) => copy_slice(cx, content),
None => Ok(Vec::new()),
},
PlaceholderValue::Tree(tree) => {
let mut ids = Vec::new();
for child in tree.root().children() {
ids.extend(cx.restage_subtree(child, self)?);
}
Ok(ids)
}
PlaceholderValue::Default(template) => {
self.remember(template);
let mut ids = Vec::new();
for child in template.tree().root().children() {
ids.extend(cx.restage_subtree(child, self)?);
}
Ok(ids)
}
}
}
fn single_value(
&self,
argument: NodeSlice<'_, Flm>,
) -> Result<Option<PlaceholderValue<'a>>, ExpandError> {
let mut significant = argument.iter().filter(|node| !is_noise(node));
let Some(first) = significant.next() else {
return Ok(None);
};
let placeholder = first.callable_type() == Some(FlmCallableType::Placeholder);
if significant.next().is_some() || !placeholder {
return Ok(None);
}
self.value_of(&first).map(Some)
}
fn is_blank<'n>(
&self,
nodes: impl Iterator<Item = NodeRef<'n, Flm>>,
depth: usize,
) -> Result<bool, ExpandError> {
if depth > BLANK_TEST_DEPTH {
return Ok(false);
}
for node in nodes {
if is_blank_node(&node) {
continue;
}
if node.callable_type() != Some(FlmCallableType::Placeholder) {
return Ok(false);
}
let blank = match self.value_of(&node)? {
PlaceholderValue::NoValue | PlaceholderValue::Unresolvable => true,
PlaceholderValue::Provided(content) => self.is_blank(content.iter(), depth + 1)?,
PlaceholderValue::Default(template) => {
self.is_blank(template.tree().root().children().iter(), depth + 1)?
}
PlaceholderValue::Tree(tree) => {
self.is_blank(tree.root().children().iter(), depth + 1)?
}
PlaceholderValue::Substitution => match substitution_of(&node) {
Some(content) => self.is_blank(content.iter(), depth + 1)?,
None => true,
},
};
if !blank {
return Ok(false);
}
}
Ok(true)
}
fn test_holds(
&self,
node: &NodeRef<'_, Flm>,
test: ConditionalTest,
) -> Result<bool, ExpandError> {
let Some(argument) = node.argument_content_nodes(0) else {
return Ok(false);
};
Ok(match test {
ConditionalTest::NoValue => {
matches!(self.single_value(argument)?, Some(PlaceholderValue::NoValue))
}
ConditionalTest::Value => {
!matches!(self.single_value(argument)?, Some(PlaceholderValue::NoValue))
}
ConditionalTest::Boolean => matches!(
self.single_value(argument)?,
Some(
PlaceholderValue::Provided(_)
| PlaceholderValue::Tree(_)
| PlaceholderValue::Substitution
)
),
ConditionalTest::Blank => self.is_blank(argument.iter(), 0)?,
ConditionalTest::NotBlank => !self.is_blank(argument.iter(), 0)?,
})
}
fn select(
&mut self,
node: NodeRef<'_, Flm>,
conditional: Conditional,
cx: &mut Cx<'_>,
) -> Result<Vec<BuildId>, ExpandError> {
let holds = self.test_holds(&node, conditional.test)?;
let branch = conditional
.branch_index(holds)
.and_then(|index| node.argument_content_nodes(index));
let mut ids = Vec::new();
if let Some(branch) = branch {
for child in branch.iter() {
ids.extend(cx.restage_subtree(child, self)?);
}
}
Ok(ids)
}
}
impl RestageVisitor<Flm, (), ()> for Substitute<'_> {
type Error = ExpandError;
fn restage(
&mut self,
node: NodeRef<'_, Flm>,
cx: &mut Cx<'_>,
) -> Result<Restage<()>, ExpandError> {
if node.callable_type() == Some(FlmCallableType::Placeholder) {
return Ok(Restage::Emit(self.substitute(node, cx)?));
}
if let Some(conditional) = element_value::<Conditional>(&node) {
return Ok(Restage::Emit(self.select(node, *conditional, cx)?));
}
Ok(Restage::Descend(()))
}
}
fn append(
children: &mut Vec<BuildId>,
added: &[BuildId],
) -> Result<std::ops::Range<u32>, ExpandError> {
let too_many = || ExpandError::Build(NodeBuildError::TooManyNodes);
let start = u32::try_from(children.len()).map_err(|_| too_many())?;
children.extend_from_slice(added);
let end = u32::try_from(children.len()).map_err(|_| too_many())?;
Ok(start..end)
}
pub(crate) struct Resource<'a> {
site: FlmSpan,
templates: &'a [&'a CompiledTemplate],
minted: Vec<(Arc<FlmSource>, Arc<FlmSource>)>,
}
impl<'a> Resource<'a> {
pub(crate) fn new(site: FlmSpan, templates: &'a [&'a CompiledTemplate]) -> Resource<'a> {
Resource { site, templates, minted: Vec::new() }
}
fn resourced(&mut self, source: &Arc<FlmSource>) -> Option<Arc<FlmSource>> {
if let Some((_, minted)) = self.minted.iter().find(|(old, _)| Arc::ptr_eq(old, source)) {
return Some(Arc::clone(minted));
}
let template =
self.templates.iter().find(|template| Arc::ptr_eq(template.source(), source))?;
let minted = Arc::new(
Source::synthesized(template.text(), template.label(), self.site.clone())
.with_origin(FlmOrigin::synthetic(template.label())),
);
self.minted.push((Arc::clone(source), Arc::clone(&minted)));
Some(minted)
}
fn span_of(&mut self, node: &NodeRef<'_, Flm>) -> FlmSpan {
match self.resourced(node.span().source()) {
Some(source) => SourceSpan::new(&source, node.span().range()),
None => node.span().clone(),
}
}
fn copy_callable(
&mut self,
node: NodeRef<'_, Flm>,
data: &CallableData<Flm>,
span: FlmSpan,
cx: &mut Cx<'_>,
) -> Result<BuildId, ExpandError> {
let mut children: Vec<BuildId> = Vec::new();
let mut arguments = Vec::with_capacity(data.arguments.len());
for index in 0..data.arguments.len() {
let bundle = cx.restage_argument(node, index, self)?;
let region = match bundle.content() {
Some(content) if bundle.is_provided() => {
let range = append(&mut children, bundle.nodes())?;
Some(ChildRegion::new(range, content.clone()))
}
_ => None,
};
arguments.push(ParsedArgument {
spec: Arc::clone(bundle.spec()),
region,
ext: bundle.ext().cloned(),
});
}
let mut slots = Vec::with_capacity(data.slots.len());
for index in 0..data.slots.len() {
let bundle = cx.restage_slot(node, index, self)?;
let range = append(&mut children, bundle.nodes())?;
slots.push(ParsedSlot {
name: bundle.name().map(Box::from),
region: ChildRegion::new(range, bundle.content().clone()),
role: bundle.role(),
ext: *bundle.ext(),
});
}
let kind = NodeKind::callable(CallableData {
callable_type: data.callable_type,
name: data.name.clone(),
spec: Arc::clone(&data.spec),
arguments: ParsedArguments::new(arguments),
slots: ParsedSlots::new(slots),
invocation_syntax: data.invocation_syntax.clone(),
});
let id = cx.builder().add(
kind,
span,
Arc::clone(node.parsing_state()),
children,
node.ext().clone(),
(),
)?;
Ok(id)
}
}
impl RestageVisitor<Flm, (), ()> for Resource<'_> {
type Error = ExpandError;
fn restage(
&mut self,
node: NodeRef<'_, Flm>,
cx: &mut Cx<'_>,
) -> Result<Restage<()>, ExpandError> {
let span = self.span_of(&node);
let id = match node.callable() {
Some(data) => self.copy_callable(node, data, span, cx)?,
None => {
let children = cx.restage_children(node, self)?;
cx.builder().add(
node.kind().clone(),
span,
Arc::clone(node.parsing_state()),
children,
node.ext().clone(),
(),
)?
}
};
Ok(Restage::Emit(vec![id]))
}
}
pub(crate) fn instance_nodes(instance: &NodeTree<Flm>) -> NodeSlice<'_, Flm> {
instance.root().children()
}
pub fn instantiate(
site: &FlmSpan,
template: &CompiledTemplate,
bindings: &dyn PlaceholderBindings,
guard: GuardPolicy,
) -> Result<NodeTree<Flm>, ExpandError> {
let mut substitute = Substitute::new(template, bindings);
let substituted =
guard::restager(&mut substitute, guard).restage(template.tree()).map_err(ExpandError::from)?;
let templates = substitute.templates().to_vec();
let mut resource = Resource::new(site.clone(), &templates);
guard::restager(&mut resource, guard).restage(&substituted).map_err(ExpandError::from)
}
#[derive(Debug, Clone, Default)]
pub struct ValueBindings {
values: BTreeMap<String, Arc<NodeTree<Flm>>>,
}
impl ValueBindings {
pub fn new() -> ValueBindings {
ValueBindings::default()
}
pub fn with(mut self, name: impl Into<String>, tree: Arc<NodeTree<Flm>>) -> ValueBindings {
self.values.insert(name.into(), tree);
self
}
}
impl PlaceholderBindings for ValueBindings {
fn value<'a>(
&'a self,
target: &PlaceholderTarget,
_substitution: Option<NodeSlice<'_, Flm>>,
) -> PlaceholderValue<'a> {
match target {
PlaceholderTarget::Extra(name) => match self.values.get(name) {
Some(tree) => PlaceholderValue::Tree(tree),
None => PlaceholderValue::NoValue,
},
PlaceholderTarget::Argument(_) | PlaceholderTarget::Body => PlaceholderValue::Unresolvable,
}
}
}
#[derive(Debug, Clone)]
enum ExtraValue {
Template(Arc<CompiledTemplate>),
Tree(Arc<NodeTree<Flm>>),
NoValue,
}
#[derive(Debug, Clone, Default)]
pub struct ExtraValues {
values: BTreeMap<String, BTreeMap<Option<String>, ExtraValue>>,
}
impl ExtraValues {
pub fn new() -> ExtraValues {
ExtraValues::default()
}
pub fn template(
self,
name: impl Into<String>,
substitution: Option<&str>,
template: Arc<CompiledTemplate>,
) -> ExtraValues {
self.insert(name.into(), substitution, ExtraValue::Template(template))
}
pub fn tree(
self,
name: impl Into<String>,
substitution: Option<&str>,
tree: Arc<NodeTree<Flm>>,
) -> ExtraValues {
self.insert(name.into(), substitution, ExtraValue::Tree(tree))
}
pub fn no_value(self, name: impl Into<String>, substitution: Option<&str>) -> ExtraValues {
self.insert(name.into(), substitution, ExtraValue::NoValue)
}
pub fn over<'v>(&'v self, base: &'v dyn PlaceholderBindings) -> LayeredBindings<'v> {
LayeredBindings { values: self, base }
}
fn insert(mut self, name: String, substitution: Option<&str>, value: ExtraValue) -> ExtraValues {
self.values.entry(name).or_default().insert(substitution.map(str::to_string), value);
self
}
}
#[derive(Clone, Copy)]
pub struct LayeredBindings<'v> {
values: &'v ExtraValues,
base: &'v dyn PlaceholderBindings,
}
impl fmt::Debug for LayeredBindings<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("LayeredBindings").field("values", self.values).finish_non_exhaustive()
}
}
impl PlaceholderBindings for LayeredBindings<'_> {
fn value<'a>(
&'a self,
target: &PlaceholderTarget,
substitution: Option<NodeSlice<'_, Flm>>,
) -> PlaceholderValue<'a> {
let PlaceholderTarget::Extra(name) = target else {
return self.base.value(target, substitution);
};
let key = substitution.map(|nodes| substitution_text_of(&nodes));
match self.values.values.get(name).and_then(|values| values.get(&key)) {
Some(ExtraValue::Template(template)) => PlaceholderValue::Default(template),
Some(ExtraValue::Tree(tree)) => PlaceholderValue::Tree(tree),
Some(ExtraValue::NoValue) => PlaceholderValue::NoValue,
None => PlaceholderValue::Unresolvable,
}
}
}