copperlace 0.4.2

Procedural text renderer for generative grammar configuration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
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};

/// Compiled collection of named rules from the config.
///
/// Top-level config entries become startable rules, so callers can render
/// `origin`, `story`, `name`, or any other named entry directly. A top-level
/// `context` object is treated specially: its entries become lazy defaults for
/// bound variables, so `{hero}` can generate and cache `context.hero` on first
/// use within a render.
pub struct RuleSet {
    document: StructuredNode,
    text_rules: HashMap<String, Box<dyn TextGeneratorNode>>,
    context_defaults: HashMap<String, Box<dyn TextGeneratorNode>>,
    processors: ProcessorRegistry,
}

impl RuleSet {
    /// Compiles a parsed configuration root value using the builtin processor registry.
    ///
    /// The root value must be a configuration object. Top-level entries become named
    /// rules, except a top-level object named `context`, whose entries become
    /// lazy defaults available to template references.
    pub fn from_config(config: hocon_rs::Value) -> Result<Self, RenderError> {
        Self::from_config_with_processors(config, ProcessorRegistry::new())
    }

    /// Compiles a parsed configuration root value with additional custom processors.
    ///
    /// Custom processors are merged into the builtin registry before templates
    /// are compiled, so unknown processor names fail during compilation. A
    /// custom processor with the same name as a builtin overrides the builtin.
    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,
        })
    }

    /// Renders a named rule from this ruleset.
    ///
    /// Each call starts with a fresh render context. Bindings and lazy context
    /// defaults are cached within one render, but not shared with later calls.
    pub fn render_rule(&self, rule_name: &str) -> Result<String, RenderError> {
        self.render_rule_with_context(rule_name, RenderContext::new())
    }

    /// Renders a named rule using render options.
    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)
    }

    /// Renders a named rule with initial render context values.
    ///
    /// Initial context values resolve before lazy `context` defaults and named
    /// rules. They are scoped to this render call and are not stored on the
    /// ruleset.
    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())
    }

    /// Renders a named rule with initial render context values and render options.
    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)
    }

    /// Renders a named rule as text, inferring structured JSON for object-valued rules.
    ///
    /// String-valued and list-valued rules use existing text rendering. Object-valued
    /// rules render as formatted JSON using tab indentation.
    pub fn render_rule_inferred(&self, rule_name: &str) -> Result<String, RenderError> {
        self.render_rule_inferred_with_context(rule_name, RenderContext::new())
    }

    /// Renders a named rule with render options, inferring structured JSON for object-valued rules.
    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)
    }

    /// Renders a named rule with initial context, inferring structured JSON for object-valued rules.
    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(),
        )
    }

    /// Renders a named rule with initial context and render options, inferring structured JSON for object-valued rules.
    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)
    }

    /// Renders an object-valued rule as a native structured value.
    ///
    /// Each call starts with a fresh render context. Text leaves within the
    /// structured object share one render state, so bindings and lazy context
    /// defaults are stable within the structured render.
    pub fn render_rule_structured(&self, rule_name: &str) -> Result<CopperlaceValue, RenderError> {
        self.render_rule_structured_with_context(rule_name, RenderContext::new())
    }

    /// Renders an object-valued rule as a native structured value using render options.
    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,
        )
    }

    /// Renders an object-valued rule as a native structured value with initial context.
    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(),
        )
    }

    /// Renders an object-valued rule as a native structured value with initial context and render options.
    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)
    }

    /// Returns the compiled structured document tree.
    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,
            })
    }
}

/// Compiles a parsed configuration root value and renders one rule.
///
/// This is a one-shot helper around [`RuleSet::from_config`] and
/// [`RuleSet::render_rule`]. Use [`RuleSet`] directly for repeated renders.
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())
}

/// Compiles a parsed configuration root value and renders one rule with initial context.
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(),
    )
}

/// Compiles a parsed configuration root value and renders one rule with initial context and render options.
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)
}

/// Compiles a parsed configuration root value and renders one object-valued rule.
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())
}

/// Compiles a parsed configuration root value and renders one object-valued rule with initial context.
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(),
    )
}

/// Compiles a parsed configuration root value and renders one object-valued rule with initial context and render options.
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)
}