use rand::distr::Distribution;
use rand::distr::weighted::WeightedIndex;
use rand::seq::IndexedRandom;
use super::error::RenderError;
use super::state::{IterationValue, LoopMetadata, RenderState};
pub trait TextGeneratorNode {
fn generate_text(&self, state: &mut RenderState) -> Result<String, RenderError>;
fn generate_unique_text(
&self,
rule_name: &str,
_state: &mut RenderState,
) -> Result<String, RenderError> {
Err(RenderError::UnsupportedUniqueChoice(rule_name.to_string()))
}
}
impl TextGeneratorNode for String {
fn generate_text(&self, _state: &mut RenderState) -> Result<String, RenderError> {
Ok(self.clone())
}
}
pub struct VariableNode {
name: String,
}
impl VariableNode {
pub fn new(name: String) -> Self {
VariableNode { name }
}
}
impl TextGeneratorNode for VariableNode {
fn generate_text(&self, state: &mut RenderState) -> Result<String, RenderError> {
state
.resolve_bound_text(&self.name)?
.ok_or_else(|| RenderError::UnknownRule(self.name.clone()))
}
}
pub struct RuleCallNode {
name: String,
unique: bool,
}
impl RuleCallNode {
pub fn new(name: String) -> Self {
RuleCallNode {
name,
unique: false,
}
}
pub fn new_unique(name: String) -> Self {
RuleCallNode { name, unique: true }
}
}
impl TextGeneratorNode for RuleCallNode {
fn generate_text(&self, state: &mut RenderState) -> Result<String, RenderError> {
if let Some(value) = state.resolve_bound_text(&self.name)? {
return Ok(value);
}
if let Some(value) = state
.ruleset
.render_context_default_with_state(&self.name, state)?
{
state.cache_context_default(&self.name, value.clone());
return Ok(value);
}
if self.unique {
return state
.ruleset
.render_unique_rule_with_state(&self.name, state);
}
state.ruleset.render_rule_with_state(&self.name, state)
}
}
pub enum BindMode {
IfMissing,
Overwrite,
}
pub struct BindNode {
name: String,
node: Box<dyn TextGeneratorNode>,
mode: BindMode,
}
impl BindNode {
pub fn new(name: String, node: Box<dyn TextGeneratorNode>, mode: BindMode) -> Self {
BindNode { name, node, mode }
}
}
impl TextGeneratorNode for BindNode {
fn generate_text(&self, state: &mut RenderState) -> Result<String, RenderError> {
if matches!(self.mode, BindMode::IfMissing) && state.contains_bound_value(&self.name)? {
return Ok(String::new());
}
if matches!(self.mode, BindMode::Overwrite) {
state.ensure_mutable_binding(&self.name)?;
}
let value = self.node.generate_text(state)?;
state.bind(&self.name, value, matches!(self.mode, BindMode::Overwrite))?;
Ok(String::new())
}
}
pub(crate) trait IterationSource {
fn elements<'a>(&self, state: &RenderState<'a>)
-> Result<Vec<IterationValue<'a>>, RenderError>;
}
pub(crate) struct ArrayIterationSource {
path: String,
}
impl ArrayIterationSource {
pub(crate) fn new(path: String) -> Self {
ArrayIterationSource { path }
}
}
impl IterationSource for ArrayIterationSource {
fn elements<'a>(
&self,
state: &RenderState<'a>,
) -> Result<Vec<IterationValue<'a>>, RenderError> {
state.iterable_elements(&self.path)
}
}
pub(crate) struct ForEachNode {
variable_name: String,
source: Box<dyn IterationSource>,
body: Box<dyn TextGeneratorNode>,
}
impl ForEachNode {
pub(crate) fn new(
variable_name: String,
source: Box<dyn IterationSource>,
body: Box<dyn TextGeneratorNode>,
) -> Self {
ForEachNode {
variable_name,
source,
body,
}
}
}
impl TextGeneratorNode for ForEachNode {
fn generate_text(&self, state: &mut RenderState) -> Result<String, RenderError> {
let elements = self.source.elements(state)?;
let length = elements.len();
let mut output = String::new();
for (index, element) in elements.into_iter().enumerate() {
state.push_iteration_scope(
&self.variable_name,
element,
LoopMetadata { index, length },
);
let rendered = self.body.generate_text(state);
state.pop_iteration_scope();
output.push_str(&rendered?);
}
Ok(output)
}
}
pub struct ProcessorPipelineNode {
node: Box<dyn TextGeneratorNode>,
processors: Vec<String>,
}
impl ProcessorPipelineNode {
pub fn new(node: Box<dyn TextGeneratorNode>, processors: Vec<String>) -> Self {
ProcessorPipelineNode { node, processors }
}
}
impl TextGeneratorNode for ProcessorPipelineNode {
fn generate_text(&self, state: &mut RenderState) -> Result<String, RenderError> {
let mut value = self.node.generate_text(state)?;
for processor_name in &self.processors {
value = state.ruleset.process(processor_name, &value)?;
}
Ok(value)
}
}
pub struct ChoiceNode {
nodes: Vec<Box<dyn TextGeneratorNode>>,
}
impl ChoiceNode {
pub fn new(nodes: Vec<Box<dyn TextGeneratorNode>>) -> Self {
ChoiceNode { nodes }
}
}
impl TextGeneratorNode for ChoiceNode {
fn generate_text(&self, state: &mut RenderState) -> Result<String, RenderError> {
let random_node = self
.nodes
.choose(&mut state.rng)
.ok_or(RenderError::EmptyChoice)?;
random_node.generate_text(state)
}
fn generate_unique_text(
&self,
rule_name: &str,
state: &mut RenderState,
) -> Result<String, RenderError> {
if self.nodes.is_empty() {
return Err(RenderError::EmptyChoice);
}
let used_indices = state.used_unique_choice_indices(rule_name);
let unused_indices = (0..self.nodes.len())
.filter(|index| used_indices.is_none_or(|used| !used.contains(index)))
.collect::<Vec<_>>();
let selected_index = *unused_indices
.choose(&mut state.rng)
.ok_or_else(|| RenderError::ExhaustedUniqueChoice(rule_name.to_string()))?;
state.mark_unique_choice_index(rule_name, selected_index);
self.nodes[selected_index].generate_text(state)
}
}
pub struct WeightedChoiceNode {
nodes: Vec<Box<dyn TextGeneratorNode>>,
weights: Vec<f64>,
distribution: WeightedIndex<f64>,
}
impl WeightedChoiceNode {
pub fn new(entries: Vec<(Box<dyn TextGeneratorNode>, f64)>) -> Result<Self, RenderError> {
let (nodes, weights): (Vec<_>, Vec<_>) = entries.into_iter().unzip();
let distribution = WeightedIndex::new(weights.clone())
.map_err(|error| RenderError::InvalidWeightedChoice(error.to_string()))?;
Ok(WeightedChoiceNode {
nodes,
weights,
distribution,
})
}
}
impl TextGeneratorNode for WeightedChoiceNode {
fn generate_text(&self, state: &mut RenderState) -> Result<String, RenderError> {
let index = self.distribution.sample(&mut state.rng);
self.nodes[index].generate_text(state)
}
fn generate_unique_text(
&self,
rule_name: &str,
state: &mut RenderState,
) -> Result<String, RenderError> {
if self.nodes.is_empty() {
return Err(RenderError::EmptyChoice);
}
let used_indices = state.used_unique_choice_indices(rule_name);
let unused_entries = self
.weights
.iter()
.enumerate()
.filter(|(index, _)| used_indices.is_none_or(|used| !used.contains(index)))
.map(|(index, weight)| (index, *weight))
.collect::<Vec<_>>();
if unused_entries.is_empty() {
return Err(RenderError::ExhaustedUniqueChoice(rule_name.to_string()));
}
let remaining_weights = unused_entries
.iter()
.map(|(_, weight)| *weight)
.collect::<Vec<_>>();
let distribution = WeightedIndex::new(remaining_weights)
.map_err(|_| RenderError::ExhaustedUniqueChoice(rule_name.to_string()))?;
let selected_entry_index = distribution.sample(&mut state.rng);
let selected_node_index = unused_entries[selected_entry_index].0;
state.mark_unique_choice_index(rule_name, selected_node_index);
self.nodes[selected_node_index].generate_text(state)
}
}
pub struct VecNode {
nodes: Vec<Box<dyn TextGeneratorNode>>,
}
impl VecNode {
pub fn new(nodes: Vec<Box<dyn TextGeneratorNode>>) -> Self {
VecNode { nodes }
}
}
impl TextGeneratorNode for VecNode {
fn generate_text(&self, state: &mut RenderState) -> Result<String, RenderError> {
let mut output = String::new();
for node in &self.nodes {
output.push_str(&node.generate_text(state)?);
}
Ok(output)
}
}
pub struct UnsupportedValueNode {
value_type: String,
}
impl UnsupportedValueNode {
pub fn new(value_type: String) -> Self {
UnsupportedValueNode { value_type }
}
}
impl TextGeneratorNode for UnsupportedValueNode {
fn generate_text(&self, _state: &mut RenderState) -> Result<String, RenderError> {
Err(RenderError::UnsupportedValue(self.value_type.clone()))
}
}