use std::collections::{BTreeMap, HashMap};
use crate::processors::builtin_processors;
use super::compile::{
contains_template_loop, insert_context_text_nodes, insert_named_text_nodes,
value_to_structured_template_node,
};
use super::error::RenderError;
use super::nodes::TextGeneratorNode;
use super::processor::ProcessorRegistry;
use super::state::{RenderContext, RenderOptions, RenderState};
use super::structured_template::ParsedTemplateConfig;
use super::value::{CopperlaceValue, StructuredNode};
pub struct RuleSet {
document: StructuredNode,
text_rules: HashMap<String, Box<dyn TextGeneratorNode>>,
context_defaults: HashMap<String, Box<dyn TextGeneratorNode>>,
processors: ProcessorRegistry,
}
impl RuleSet {
pub fn from_config(config: hocon_rs::Value) -> Result<Self, RenderError> {
Self::from_config_with_processors(config, ProcessorRegistry::new())
}
pub fn from_config_with_processors(
config: hocon_rs::Value,
custom_processors: ProcessorRegistry,
) -> Result<Self, RenderError> {
Self::from_template_config(
ParsedTemplateConfig {
value: config,
loops: HashMap::new(),
},
custom_processors,
)
}
pub(crate) fn from_template_config(
config: ParsedTemplateConfig,
custom_processors: ProcessorRegistry,
) -> Result<Self, RenderError> {
let ParsedTemplateConfig { value, loops } = config;
let hocon_rs::Value::Object(values) = value else {
return Err(RenderError::InvalidConfigRoot);
};
let mut processors = builtin_processors();
processors.extend(custom_processors);
let mut document_values = BTreeMap::new();
let mut text_rules = HashMap::new();
let mut context_defaults = HashMap::new();
for (name, value) in values {
if contains_template_loop(&value, &loops)
&& (name == "context" || !matches!(&value, hocon_rs::Value::Object(_)))
{
return Err(RenderError::InvalidExpression(
"structured loop blocks must be inside arrays in object-valued rules"
.to_string(),
));
}
document_values.insert(
name.clone(),
value_to_structured_template_node(value.clone(), &processors, &loops)?,
);
if name == "context" {
if let hocon_rs::Value::Object(context_values) = value {
for (context_name, context_value) in context_values {
insert_context_text_nodes(
&mut context_defaults,
context_name,
context_value,
&processors,
)?;
}
} else {
insert_named_text_nodes(&mut text_rules, name, value, &processors, &loops)?;
}
} else {
insert_named_text_nodes(&mut text_rules, name, value, &processors, &loops)?;
}
}
Ok(RuleSet {
document: StructuredNode::Object(document_values),
text_rules,
context_defaults,
processors,
})
}
pub fn render_rule(&self, rule_name: &str) -> Result<String, RenderError> {
self.render_rule_with_context(rule_name, RenderContext::new())
}
pub fn render_rule_with_options(
&self,
rule_name: &str,
options: RenderOptions,
) -> Result<String, RenderError> {
self.render_rule_with_context_and_options(rule_name, RenderContext::new(), options)
}
pub fn render_rule_with_context(
&self,
rule_name: &str,
context: RenderContext,
) -> Result<String, RenderError> {
self.render_rule_with_context_and_options(rule_name, context, RenderOptions::default())
}
pub fn render_rule_with_context_and_options(
&self,
rule_name: &str,
context: RenderContext,
options: RenderOptions,
) -> Result<String, RenderError> {
let mut state = RenderState::with_context_and_options(self, context, options);
self.render_rule_with_state(rule_name, &mut state)
}
pub fn render_rule_inferred(&self, rule_name: &str) -> Result<String, RenderError> {
self.render_rule_inferred_with_context(rule_name, RenderContext::new())
}
pub fn render_rule_inferred_with_options(
&self,
rule_name: &str,
options: RenderOptions,
) -> Result<String, RenderError> {
self.render_rule_inferred_with_context_and_options(rule_name, RenderContext::new(), options)
}
pub fn render_rule_inferred_with_context(
&self,
rule_name: &str,
context: RenderContext,
) -> Result<String, RenderError> {
self.render_rule_inferred_with_context_and_options(
rule_name,
context,
RenderOptions::default(),
)
}
pub fn render_rule_inferred_with_context_and_options(
&self,
rule_name: &str,
context: RenderContext,
options: RenderOptions,
) -> Result<String, RenderError> {
if matches!(
self.structured_node(rule_name),
Ok(StructuredNode::Object(_))
) {
return self
.render_rule_structured_with_context_and_options(rule_name, context, options)
.and_then(|value| value.to_formatted_json());
}
self.render_rule_with_context_and_options(rule_name, context, options)
}
pub fn render_rule_structured(&self, rule_name: &str) -> Result<CopperlaceValue, RenderError> {
self.render_rule_structured_with_context(rule_name, RenderContext::new())
}
pub fn render_rule_structured_with_options(
&self,
rule_name: &str,
options: RenderOptions,
) -> Result<CopperlaceValue, RenderError> {
self.render_rule_structured_with_context_and_options(
rule_name,
RenderContext::new(),
options,
)
}
pub fn render_rule_structured_with_context(
&self,
rule_name: &str,
context: RenderContext,
) -> Result<CopperlaceValue, RenderError> {
self.render_rule_structured_with_context_and_options(
rule_name,
context,
RenderOptions::default(),
)
}
pub fn render_rule_structured_with_context_and_options(
&self,
rule_name: &str,
context: RenderContext,
options: RenderOptions,
) -> Result<CopperlaceValue, RenderError> {
let node = self.structured_node(rule_name)?;
if !matches!(node, StructuredNode::Object(_)) {
return Err(RenderError::UnsupportedStructuredTarget(
rule_name.to_string(),
));
}
let mut state = RenderState::with_context_and_options(self, context, options);
node.generate_value(&mut state)
}
pub fn structured_document(&self) -> &StructuredNode {
&self.document
}
pub(crate) fn structured_node(&self, rule_name: &str) -> Result<&StructuredNode, RenderError> {
let mut node = &self.document;
for segment in rule_name.split('.') {
if segment.is_empty() {
return Err(RenderError::UnknownRule(rule_name.to_string()));
}
let StructuredNode::Object(values) = node else {
return Err(RenderError::UnknownRule(rule_name.to_string()));
};
let Some(next_node) = values.get(segment) else {
return Err(RenderError::UnknownRule(rule_name.to_string()));
};
node = next_node;
}
Ok(node)
}
pub(crate) fn structured_context_node(&self, name: &str) -> Option<&StructuredNode> {
let StructuredNode::Object(document) = &self.document else {
return None;
};
let StructuredNode::Object(context) = document.get("context")? else {
return None;
};
let mut node = context.get(name.split('.').next()?)?;
for segment in name.split('.').skip(1) {
let StructuredNode::Object(values) = node else {
return None;
};
node = values.get(segment)?;
}
Some(node)
}
pub(crate) fn render_rule_with_state(
&self,
rule_name: &str,
state: &mut RenderState,
) -> Result<String, RenderError> {
let Some(rule) = self
.text_rules
.get(rule_name)
.or_else(|| self.context_defaults.get(rule_name))
else {
return Err(RenderError::UnknownRule(rule_name.to_string()));
};
self.render_node_with_state(rule_name, rule.as_ref(), state, false)
}
pub(crate) fn render_unique_rule_with_state(
&self,
rule_name: &str,
state: &mut RenderState,
) -> Result<String, RenderError> {
let Some(rule) = self.text_rules.get(rule_name) else {
return Err(RenderError::UnknownRule(rule_name.to_string()));
};
self.render_node_with_state(rule_name, rule.as_ref(), state, true)
}
fn render_node_with_state(
&self,
rule_name: &str,
rule: &dyn TextGeneratorNode,
state: &mut RenderState,
unique: bool,
) -> Result<String, RenderError> {
let existing_calls = state
.call_stack
.iter()
.filter(|name| name.as_str() == rule_name)
.count();
if state.options.max_recursion_depth == 0 && existing_calls > 0 {
let mut cycle = state.call_stack.clone();
cycle.push(rule_name.to_string());
return Err(RenderError::CircularRuleReference(cycle));
}
if existing_calls > state.options.max_recursion_depth {
return Ok(String::new());
}
state.call_stack.push(rule_name.to_string());
let result = if unique {
rule.generate_unique_text(rule_name, state)
} else {
rule.generate_text(state)
};
state.call_stack.pop();
result
}
pub(crate) fn render_context_default_with_state(
&self,
name: &str,
state: &mut RenderState,
) -> Result<Option<String>, RenderError> {
let Some(rule) = self.context_defaults.get(name) else {
return Ok(None);
};
let existing_calls = state
.call_stack
.iter()
.filter(|rule_name| rule_name.as_str() == name)
.count();
if state.options.max_recursion_depth == 0 && existing_calls > 0 {
let mut cycle = state.call_stack.clone();
cycle.push(name.to_string());
return Err(RenderError::CircularRuleReference(cycle));
}
if existing_calls > state.options.max_recursion_depth {
return Ok(Some(String::new()));
}
state.call_stack.push(name.to_string());
let result = rule.generate_text(state);
state.call_stack.pop();
result.map(Some)
}
pub(crate) fn process(&self, processor_name: &str, value: &str) -> Result<String, RenderError> {
let Some(processor) = self.processors.get(processor_name) else {
return Err(RenderError::UnknownProcessor(processor_name.to_string()));
};
processor
.process(value)
.map_err(|message| RenderError::ProcessorError {
processor: processor_name.to_string(),
message,
})
}
}
pub fn render_config_rule(config: hocon_rs::Value, rule_name: &str) -> Result<String, RenderError> {
render_config_rule_with_context(config, rule_name, RenderContext::new())
}
pub fn render_config_rule_with_context(
config: hocon_rs::Value,
rule_name: &str,
context: RenderContext,
) -> Result<String, RenderError> {
render_config_rule_with_context_and_options(
config,
rule_name,
context,
RenderOptions::default(),
)
}
pub fn render_config_rule_with_context_and_options(
config: hocon_rs::Value,
rule_name: &str,
context: RenderContext,
options: RenderOptions,
) -> Result<String, RenderError> {
let ruleset = RuleSet::from_config(config)?;
ruleset.render_rule_with_context_and_options(rule_name, context, options)
}
pub fn render_config_rule_structured(
config: hocon_rs::Value,
rule_name: &str,
) -> Result<CopperlaceValue, RenderError> {
render_config_rule_structured_with_context(config, rule_name, RenderContext::new())
}
pub fn render_config_rule_structured_with_context(
config: hocon_rs::Value,
rule_name: &str,
context: RenderContext,
) -> Result<CopperlaceValue, RenderError> {
render_config_rule_structured_with_context_and_options(
config,
rule_name,
context,
RenderOptions::default(),
)
}
pub fn render_config_rule_structured_with_context_and_options(
config: hocon_rs::Value,
rule_name: &str,
context: RenderContext,
options: RenderOptions,
) -> Result<CopperlaceValue, RenderError> {
let ruleset = RuleSet::from_config(config)?;
ruleset.render_rule_structured_with_context_and_options(rule_name, context, options)
}