Skip to main content

workshop_rs/output/
emitter.rs

1//! Deterministic localized Workshop emitter.
2//!
3//! Serializes validated public Workshop programs into localized Workshop text with a
4//! selectable output locale. Canonical catalog identities resolve to
5//! locale-specific spellings; missing target-locale mappings fail explicitly
6//! with a [`WorkshopError::MissingMapping`] diagnostic — never a guess, never
7//! a silent passthrough of another locale's spelling. Fallback to another
8//! declared locale is opt-in ([`EmitOptions`]) and every fell-back identity
9//! is recorded in [`EmitOutput::fallback_ids`].
10
11pub(crate) use std::fmt::Write;
12
13pub(crate) use crate::catalog::{Catalog, Kind, Locale};
14pub(crate) use crate::core::error::{Result, WorkshopError};
15pub(crate) use crate::settings::table::KeyKind;
16pub(crate) use crate::settings::{PathPart, table};
17pub(crate) use crate::settings::{Settings as SettingsTree, SettingsNode};
18pub(crate) use crate::wir;
19
20/// Emission options: opt-in fallback for missing target-locale mappings.
21#[derive(Debug, Clone, Default, PartialEq, Eq)]
22#[non_exhaustive]
23pub struct EmitOptions {
24    /// When a canonical identity has no spelling for the target locale, its
25    /// spelling in this declared locale is used instead. `None` (the default)
26    /// keeps missing mappings failing explicitly. The fallback choice is
27    /// visible in [`EmitOutput::fallback_ids`].
28    pub fallback_locale: Option<Locale>,
29}
30
31/// The result of a localized emission.
32#[derive(Debug, Clone, PartialEq, Eq)]
33#[non_exhaustive]
34pub struct EmitOutput {
35    /// The emitted localized Workshop text.
36    pub text: String,
37    /// Canonical identities (and the `settings` marker) whose spelling came
38    /// from the opt-in fallback locale instead of the target locale. Empty
39    /// when no fallback occurred.
40    pub fallback_ids: Vec<String>,
41}
42
43/// Emit a public Workshop program as localized Workshop text, failing explicitly
44/// on any missing target-locale mapping (no fallback).
45pub fn emit(program: &crate::Program, catalog: &Catalog, locale: &Locale) -> Result<String> {
46    emit_with_options(program, catalog, locale, &EmitOptions::default()).map(|out| out.text)
47}
48
49#[cfg(test)]
50pub(crate) fn emit_wir(
51    program: &wir::Program,
52    catalog: &Catalog,
53    locale: &Locale,
54) -> Result<String> {
55    emit_with_options_inner(program, catalog, locale, &EmitOptions::default()).map(|out| out.text)
56}
57
58/// Emit a public Workshop program as localized Workshop text with emission
59/// options (opt-in fallback locale).
60pub fn emit_with_options(
61    program: &crate::Program,
62    catalog: &Catalog,
63    locale: &Locale,
64    options: &EmitOptions,
65) -> Result<EmitOutput> {
66    let storage = program.to_wir()?;
67    emit_with_options_inner(&storage, catalog, locale, options)
68}
69
70#[cfg(test)]
71pub(crate) fn emit_wir_with_options(
72    program: &wir::Program,
73    catalog: &Catalog,
74    locale: &Locale,
75    options: &EmitOptions,
76) -> Result<EmitOutput> {
77    emit_with_options_inner(program, catalog, locale, options)
78}
79
80fn emit_with_options_inner(
81    program: &wir::Program,
82    catalog: &Catalog,
83    locale: &Locale,
84    options: &EmitOptions,
85) -> Result<EmitOutput> {
86    let mut emitter = EmitContext {
87        program,
88        catalog,
89        locale: locale.clone(),
90        fallback: options.fallback_locale.clone(),
91        fallback_ids: Vec::new(),
92        out: String::new(),
93        line_count: 0,
94    };
95    emitter.run()?;
96    Ok(EmitOutput {
97        text: emitter.out,
98        fallback_ids: emitter.fallback_ids,
99    })
100}
101
102pub(crate) struct EmitContext<'a> {
103    pub(crate) program: &'a wir::Program,
104    pub(crate) catalog: &'a Catalog,
105    pub(crate) locale: Locale,
106    /// The opt-in fallback locale for missing target-locale mappings.
107    pub(crate) fallback: Option<Locale>,
108    /// Canonical ids emitted with a fallback-locale spelling.
109    pub(crate) fallback_ids: Vec<String>,
110    pub(crate) out: String,
111    pub(crate) line_count: usize,
112}
113
114impl EmitContext<'_> {
115    pub(crate) fn run(&mut self) -> Result<()> {
116        // Section order: settings, variables, subroutines, rules.
117        if let Some(settings) = &self.program.settings {
118            self.emit_settings(settings)?;
119            self.out.push('\n');
120        }
121        if !self.program.global_variables.is_empty() || !self.program.player_variables.is_empty() {
122            let variables = self.structural("variables")?;
123            self.line(0, &format!("{variables} {{"))?;
124            if !self.program.global_variables.is_empty() {
125                let global = self.structural("global")?;
126                self.line(1, &format!("{global}:"))?;
127                for variable in self.program.global_variables.iter() {
128                    self.line(2, &format!("{}: {}", variable.index, variable.name))?;
129                }
130            }
131            if !self.program.player_variables.is_empty() {
132                let player = self.structural("player")?;
133                self.line(1, &format!("{player}:"))?;
134                for variable in self.program.player_variables.iter() {
135                    self.line(2, &format!("{}: {}", variable.index, variable.name))?;
136                }
137            }
138            self.line(0, "}")?;
139            self.out.push('\n');
140        }
141        if !self.program.subroutines.is_empty() {
142            let subroutines = self.structural("subroutines")?;
143            self.line(0, &format!("{subroutines} {{"))?;
144            for subroutine in self.program.subroutines.iter() {
145                self.line(1, &format!("{}: {}", subroutine.index, subroutine.name))?;
146            }
147            self.line(0, "}")?;
148            self.out.push('\n');
149        }
150        for (emitted_rules, rule) in self.program.rules.iter().enumerate() {
151            if emitted_rules > 0 {
152                self.out.push('\n');
153            }
154            self.rule(rule)?;
155        }
156        // The oracle's raw artifact ends with a trailing blank line (the
157        // committed snapshots strip it via the acquisition normalizer; the
158        // pinned oracle's own output keeps it).
159        if !self.out.is_empty() && !self.out.ends_with("\n\n") {
160            self.out.push('\n');
161        }
162        Ok(())
163    }
164
165    pub(crate) fn indent(&mut self, level: usize) {
166        for _ in 0..level {
167            self.out.push_str("    ");
168        }
169    }
170
171    pub(crate) fn line(&mut self, level: usize, text: &str) -> Result<()> {
172        self.indent(level);
173        self.out.push_str(text);
174        self.out.push('\n');
175        self.line_count += 1;
176        Ok(())
177    }
178}
179
180/// Format a float like the reference frontend: integers print without a
181/// decimal point, and non-integers print the shortest round-trip
182/// representation truncated to 16 significant digits (OverPy behavior;
183/// evidence: the pinned oracle snapshots).
184pub(crate) fn escape_string(value: &str) -> String {
185    value.replace('"', "\\\"")
186}
187
188/// Re-escape a decoded value string the way the pinned oracle does (#87):
189/// `\`, `"`, newline, and carriage return re-escape; tabs pass through raw
190/// (byte-measured oracle behavior: `a\tb` emits a real tab, `a\nb` emits the
191/// literal two-character `\n`).
192pub(crate) fn escape_value_string(value: &str) -> String {
193    let mut out = String::with_capacity(value.len());
194    for ch in value.chars() {
195        match ch {
196            '\\' => out.push_str("\\\\"),
197            '"' => out.push_str("\\\""),
198            '\n' => out.push_str("\\n"),
199            '\r' => out.push_str("\\r"),
200            other => out.push(other),
201        }
202    }
203    out
204}
205
206/// Split a decoded string per the oracle's long-string rule (#87): when the
207/// decoded length exceeds the Workshop 128-char limit, non-final segments
208/// hold exactly 125 decoded chars and are emitted with a `{0}` continuation
209/// placeholder (128 total text chars), chained as nested `Custom String`
210/// arguments; the final segment holds the remainder without a placeholder.
211/// Segment texts are re-escaped. Byte-measured basis: chunk sizes are
212/// counted on the decoded string (70 escaped newlines — 140 escaped chars,
213/// 70 decoded — emit unsplit; 129 decoded newlines split at 125 decoded).
214pub(crate) fn split_string(value: &str) -> Vec<String> {
215    if value.chars().count() <= 128 {
216        return vec![escape_value_string(value)];
217    }
218    let mut segments = Vec::new();
219    let mut rest = value;
220    while rest.chars().count() > 125 {
221        let chunk: String = rest.chars().take(125).collect();
222        let mut text = escape_value_string(&chunk);
223        text.push_str("{0}");
224        segments.push(text);
225        rest = &rest[chunk.len()..];
226    }
227    if !rest.is_empty() {
228        segments.push(escape_value_string(rest));
229    }
230    segments
231}
232
233/// Escape a settings string value the way the pinned oracle does: every
234/// decode the JSONC parser performed is re-escaped, so decoded values
235/// round-trip to the oracle's spelling. Evidence: the inputhud description
236/// (`\n` in the source block) is emitted by the oracle as the literal
237/// two-character sequence `\n` in the Workshop settings section.
238pub(crate) fn escape_settings_string(value: &str) -> String {
239    let mut out = String::with_capacity(value.len());
240    for ch in value.chars() {
241        match ch {
242            '\\' => out.push_str("\\\\"),
243            '"' => out.push_str("\\\""),
244            '\n' => out.push_str("\\n"),
245            '\t' => out.push_str("\\t"),
246            '\r' => out.push_str("\\r"),
247            other => out.push(other),
248        }
249    }
250    out
251}
252
253/// Emit the nested continuation chain
254/// `Custom String(seg0, Custom String(seg1, ...))`; segment texts are
255/// pre-escaped, non-final segments carry the `{0}` placeholder. Iterative:
256/// every segment except the first opens a `Custom String` level, then all
257/// levels close.
258pub(crate) fn emit_string_chain(spelling: &str, segments: &[String], out: &mut String) {
259    let Some((first, rest)) = segments.split_first() else {
260        return;
261    };
262    out.push_str(spelling);
263    out.push('(');
264    write!(out, "\"{first}\"").unwrap();
265    for segment in rest {
266        out.push_str(", ");
267        out.push_str(spelling);
268        out.push('(');
269        write!(out, "\"{segment}\"").unwrap();
270    }
271    for _ in 0..=rest.len() {
272        out.push(')');
273    }
274}
275
276/// Render a constant format argument the way the oracle folds it: integers
277/// without decimals, non-integers with exactly two decimals (JS `toFixed(2)`
278/// rounding: `0.5` -> `0.50`, `0.125` -> `0.13`, #87).
279pub(crate) fn fold_number(value: f64) -> String {
280    if value.fract() == 0.0 && value.abs() < 1e15 {
281        format!("{}", value as i64)
282    } else {
283        let scaled = (value * 100.0).round();
284        let sign = if scaled < 0.0 { "-" } else { "" };
285        let scaled = scaled.abs() as i64;
286        format!("{sign}{}.{:02}", scaled / 100, scaled % 100)
287    }
288}