prosaic-project 0.6.2

Folder-of-files project format and bundler for Prosaic templates.
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
//! `prosaic.toml` schema for the `[style_profile]` section.
//!
//! `StyleProfileConfig` is the TOML-friendly mirror of
//! [`prosaic_core::StyleProfile`]. It uses string keys for RST-relation
//! pools (TOML can't key tables by Rust enum variants directly), keeps
//! every field optional so projects can declare just the dials they care
//! about, and supports a single `extends = "path"` reference to another
//! profile TOML for file-level composition.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use prosaic_core::{
    ConnectivePreferences, HedgingCalibration, LengthDistribution, ListStyleBias, PronounDensity,
    RstRelation, SalienceBias, StyleProfile, StyleProfileError, Verbosity,
};
use serde::{Deserialize, Serialize};

use crate::error::ProjectError;

/// TOML representation of a [`StyleProfile`].
///
/// Every field is optional so an authoring file can declare just the dials
/// it cares about; missing fields fall through to the neutral default.
/// `extends = "path"` loads another `StyleProfileConfig` as the base; the
/// inline `Some(_)` fields then override per-dial.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct StyleProfileConfig {
    /// Optional path (relative to the manifest's directory) to another
    /// profile TOML to use as the base. Inline fields below override the
    /// base per-dial.
    pub extends: Option<String>,
    pub name: Option<String>,
    pub verbosity: Option<String>,
    pub list_style_bias: Option<String>,
    pub pronoun_density: Option<String>,
    pub salience: Option<String>,
    pub sentence_length: Option<LengthDistributionConfig>,
    pub connectives: Option<ConnectivePreferencesConfig>,
    pub hedging: Option<HedgingCalibrationConfig>,
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct LengthDistributionConfig {
    pub short: Option<f32>,
    pub medium: Option<f32>,
    pub long: Option<f32>,
    pub short_max_words: Option<u16>,
    pub medium_max_words: Option<u16>,
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ConnectivePreferencesConfig {
    /// Per-RST-relation allowed connective pools. Keys are lowercase
    /// `RstRelation` variant names: `elaboration`, `contrast`, `cause`,
    /// `result`, `concession`, `sequence`, `condition`, `background`,
    /// `summary`. Unknown keys are rejected at parse time so typos
    /// surface as clear errors instead of silently no-op'ing.
    pub allowed: Option<HashMap<String, Vec<String>>>,
    /// Per-RST-relation tie-breaker weights. Inner shape is array of
    /// `[connective, weight]` pairs.
    pub preferred: Option<HashMap<String, Vec<(String, f32)>>>,
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct HedgingCalibrationConfig {
    pub offset: Option<i8>,
    pub forbid: Option<Vec<String>>,
}

impl StyleProfileConfig {
    /// Convert this TOML config into a validated [`StyleProfile`].
    ///
    /// `manifest_dir` is the directory containing the project's
    /// `prosaic.toml`; relative `extends` paths resolve from there. The
    /// returned profile has been run through [`StyleProfile::validate`]
    /// — invalid configurations surface as `ProjectError::ManifestStyle`
    /// rather than silently producing a half-built profile.
    pub fn into_style_profile(self, manifest_dir: &Path) -> Result<StyleProfile, ProjectError> {
        let merged = self.resolve(manifest_dir, &mut Vec::new())?;
        merged.build_profile()
    }

    fn resolve(
        self,
        manifest_dir: &Path,
        seen: &mut Vec<PathBuf>,
    ) -> Result<StyleProfileConfig, ProjectError> {
        // Walk `extends` chain depth-first, base-first. The accumulated
        // base config gets overlaid by self's `Some(_)` fields at the end.
        let base = if let Some(ext_path) = &self.extends {
            let mut path = manifest_dir.join(ext_path);
            if !path.is_absolute() {
                path = manifest_dir.join(ext_path);
            }
            let canonical = path.canonicalize().unwrap_or(path.clone());
            if seen.iter().any(|p| p == &canonical) {
                return Err(ProjectError::ManifestStyle {
                    reason: format!(
                        "extends cycle detected: `{}` is already in the resolution chain",
                        path.display()
                    ),
                });
            }
            seen.push(canonical);
            let text = std::fs::read_to_string(&path).map_err(|e| ProjectError::Io {
                path: path.display().to_string(),
                cause: e.to_string(),
            })?;
            let parent = path
                .parent()
                .map(Path::to_path_buf)
                .unwrap_or_else(|| manifest_dir.to_path_buf());
            let parsed: StyleProfileConfig =
                toml::from_str(&text).map_err(|e| ProjectError::TomlParse {
                    file: path.display().to_string(),
                    cause: e.to_string(),
                })?;
            Some(parsed.resolve(&parent, seen)?)
        } else {
            None
        };

        Ok(merge_overlay(base.unwrap_or_default(), self))
    }

    fn build_profile(self) -> Result<StyleProfile, ProjectError> {
        let mut builder =
            StyleProfile::builder(self.name.unwrap_or_else(|| String::from("default")));
        if let Some(v) = self.verbosity {
            builder = builder.verbosity(parse_verbosity(&v)?);
        }
        if let Some(l) = self.list_style_bias {
            builder = builder.list_style_bias(parse_list_style_bias(&l)?);
        }
        if let Some(p) = self.pronoun_density {
            builder = builder.pronoun_density(parse_pronoun_density(&p)?);
        }
        if let Some(s) = self.salience {
            builder = builder.salience(parse_salience_bias(&s)?);
        }
        if let Some(sl) = self.sentence_length {
            builder = builder.sentence_length(build_length_distribution(sl));
        }
        if let Some(c) = self.connectives {
            builder = builder.connectives(build_connective_preferences(c)?);
        }
        if let Some(h) = self.hedging {
            builder = builder.hedging(build_hedging_calibration(h));
        }
        builder.build().map_err(map_style_error)
    }
}

fn merge_overlay(base: StyleProfileConfig, overlay: StyleProfileConfig) -> StyleProfileConfig {
    StyleProfileConfig {
        extends: None, // resolved already
        name: overlay.name.or(base.name),
        verbosity: overlay.verbosity.or(base.verbosity),
        list_style_bias: overlay.list_style_bias.or(base.list_style_bias),
        pronoun_density: overlay.pronoun_density.or(base.pronoun_density),
        salience: overlay.salience.or(base.salience),
        sentence_length: merge_length(base.sentence_length, overlay.sentence_length),
        connectives: merge_connectives(base.connectives, overlay.connectives),
        hedging: merge_hedging(base.hedging, overlay.hedging),
    }
}

fn merge_length(
    base: Option<LengthDistributionConfig>,
    overlay: Option<LengthDistributionConfig>,
) -> Option<LengthDistributionConfig> {
    match (base, overlay) {
        (None, o) => o,
        (b, None) => b,
        (Some(b), Some(o)) => Some(LengthDistributionConfig {
            short: o.short.or(b.short),
            medium: o.medium.or(b.medium),
            long: o.long.or(b.long),
            short_max_words: o.short_max_words.or(b.short_max_words),
            medium_max_words: o.medium_max_words.or(b.medium_max_words),
        }),
    }
}

fn merge_connectives(
    base: Option<ConnectivePreferencesConfig>,
    overlay: Option<ConnectivePreferencesConfig>,
) -> Option<ConnectivePreferencesConfig> {
    match (base, overlay) {
        (None, o) => o,
        (b, None) => b,
        (Some(b), Some(o)) => Some(ConnectivePreferencesConfig {
            allowed: o.allowed.or(b.allowed),
            preferred: o.preferred.or(b.preferred),
        }),
    }
}

fn merge_hedging(
    base: Option<HedgingCalibrationConfig>,
    overlay: Option<HedgingCalibrationConfig>,
) -> Option<HedgingCalibrationConfig> {
    match (base, overlay) {
        (None, o) => o,
        (b, None) => b,
        (Some(b), Some(o)) => Some(HedgingCalibrationConfig {
            offset: o.offset.or(b.offset),
            forbid: o.forbid.or(b.forbid),
        }),
    }
}

fn build_length_distribution(c: LengthDistributionConfig) -> LengthDistribution {
    let neutral = LengthDistribution::neutral();
    LengthDistribution {
        short: c.short.unwrap_or(neutral.short),
        medium: c.medium.unwrap_or(neutral.medium),
        long: c.long.unwrap_or(neutral.long),
        short_max_words: c.short_max_words.unwrap_or(neutral.short_max_words),
        medium_max_words: c.medium_max_words.unwrap_or(neutral.medium_max_words),
    }
}

fn build_connective_preferences(
    c: ConnectivePreferencesConfig,
) -> Result<ConnectivePreferences, ProjectError> {
    let mut prefs = ConnectivePreferences::neutral();
    if let Some(allowed) = c.allowed {
        for (k, v) in allowed {
            let rst = parse_rst_relation(&k)?;
            prefs.allowed.insert(rst, v);
        }
    }
    if let Some(preferred) = c.preferred {
        for (k, v) in preferred {
            let rst = parse_rst_relation(&k)?;
            prefs.preferred.insert(rst, v);
        }
    }
    Ok(prefs)
}

fn build_hedging_calibration(c: HedgingCalibrationConfig) -> HedgingCalibration {
    HedgingCalibration {
        offset: c.offset.unwrap_or(0),
        forbid: c.forbid.unwrap_or_default(),
    }
}

fn parse_verbosity(s: &str) -> Result<Verbosity, ProjectError> {
    match s {
        "terse" => Ok(Verbosity::Terse),
        "neutral" => Ok(Verbosity::Neutral),
        "verbose" => Ok(Verbosity::Verbose),
        other => Err(ProjectError::ManifestStyle {
            reason: format!(
                "unknown verbosity `{other}` — expected one of terse, neutral, verbose"
            ),
        }),
    }
}

fn parse_list_style_bias(s: &str) -> Result<ListStyleBias, ProjectError> {
    match s {
        "auto" => Ok(ListStyleBias::Auto),
        "including" => Ok(ListStyleBias::Including),
        "such_as" => Ok(ListStyleBias::SuchAs),
        "dash" => Ok(ListStyleBias::Dash),
        "bracketed" => Ok(ListStyleBias::Bracketed),
        other => Err(ProjectError::ManifestStyle {
            reason: format!(
                "unknown list_style_bias `{other}` — expected one of auto, including, such_as, dash, bracketed"
            ),
        }),
    }
}

fn parse_pronoun_density(s: &str) -> Result<PronounDensity, ProjectError> {
    match s {
        "low" => Ok(PronounDensity::Low),
        "default" => Ok(PronounDensity::Default),
        "high" => Ok(PronounDensity::High),
        other => Err(ProjectError::ManifestStyle {
            reason: format!(
                "unknown pronoun_density `{other}` — expected one of low, default, high"
            ),
        }),
    }
}

fn parse_salience_bias(s: &str) -> Result<SalienceBias, ProjectError> {
    match s {
        "lower" => Ok(SalienceBias::Lower),
        "auto" => Ok(SalienceBias::Auto),
        "higher" => Ok(SalienceBias::Higher),
        other => Err(ProjectError::ManifestStyle {
            reason: format!(
                "unknown salience bias `{other}` — expected one of lower, auto, higher"
            ),
        }),
    }
}

fn parse_rst_relation(s: &str) -> Result<RstRelation, ProjectError> {
    match s {
        "elaboration" => Ok(RstRelation::Elaboration),
        "contrast" => Ok(RstRelation::Contrast),
        "cause" => Ok(RstRelation::Cause),
        "result" => Ok(RstRelation::Result),
        "concession" => Ok(RstRelation::Concession),
        "sequence" => Ok(RstRelation::Sequence),
        "condition" => Ok(RstRelation::Condition),
        "background" => Ok(RstRelation::Background),
        "summary" => Ok(RstRelation::Summary),
        other => Err(ProjectError::ManifestStyle {
            reason: format!(
                "unknown RST relation key `{other}` — expected one of elaboration, contrast, cause, result, concession, sequence, condition, background, summary"
            ),
        }),
    }
}

fn map_style_error(err: StyleProfileError) -> ProjectError {
    ProjectError::ManifestStyle {
        reason: err.to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    #[test]
    fn parses_minimal_inline_profile() {
        let toml_str = r#"
            name = "concise"
            verbosity = "terse"
            list_style_bias = "bracketed"
        "#;
        let cfg: StyleProfileConfig = toml::from_str(toml_str).unwrap();
        let dir = tempdir().unwrap();
        let profile = cfg.into_style_profile(dir.path()).unwrap();
        assert_eq!(profile.name, "concise");
        assert_eq!(profile.verbosity, Verbosity::Terse);
        assert_eq!(profile.list_style_bias, ListStyleBias::Bracketed);
        assert!(profile.connectives.is_neutral());
    }

    #[test]
    fn parses_per_relation_connective_pools() {
        let toml_str = r#"
            name = "tight-contrast"
            [connectives.allowed]
            elaboration = ["Furthermore,", "Additionally,"]
            contrast = ["However,"]
            [connectives.preferred]
            elaboration = [["Furthermore,", 1.0], ["Additionally,", 0.5]]
        "#;
        let cfg: StyleProfileConfig = toml::from_str(toml_str).unwrap();
        let dir = tempdir().unwrap();
        let profile = cfg.into_style_profile(dir.path()).unwrap();
        assert_eq!(
            profile
                .connectives
                .allowed
                .get(&RstRelation::Elaboration)
                .map(Vec::len),
            Some(2)
        );
        assert_eq!(
            profile
                .connectives
                .allowed
                .get(&RstRelation::Contrast)
                .map(Vec::len),
            Some(1)
        );
        assert_eq!(
            profile
                .connectives
                .preferred
                .get(&RstRelation::Elaboration)
                .map(Vec::len),
            Some(2)
        );
    }

    #[test]
    fn unknown_rst_relation_key_is_rejected() {
        let toml_str = r#"
            name = "bad"
            [connectives.allowed]
            shrubbery = ["foo"]
        "#;
        let cfg: StyleProfileConfig = toml::from_str(toml_str).unwrap();
        let dir = tempdir().unwrap();
        let result = cfg.into_style_profile(dir.path());
        assert!(matches!(
            result,
            Err(ProjectError::ManifestStyle { reason }) if reason.contains("shrubbery")
        ));
    }

    #[test]
    fn unknown_verbosity_value_is_rejected() {
        let toml_str = r#"
            name = "bad"
            verbosity = "yelly"
        "#;
        let cfg: StyleProfileConfig = toml::from_str(toml_str).unwrap();
        let dir = tempdir().unwrap();
        let result = cfg.into_style_profile(dir.path());
        assert!(matches!(
            result,
            Err(ProjectError::ManifestStyle { reason }) if reason.contains("yelly")
        ));
    }

    #[test]
    fn extends_loads_referenced_profile_and_overlays() {
        let dir = tempdir().unwrap();
        let base_path = dir.path().join("base.toml");
        fs::write(
            &base_path,
            r#"
                name = "base"
                verbosity = "terse"
                list_style_bias = "bracketed"
            "#,
        )
        .unwrap();

        // Inline overrides only verbosity; list_style_bias stays from base.
        let overlay_toml = r#"
            extends = "base.toml"
            name = "child"
            verbosity = "verbose"
        "#;
        let cfg: StyleProfileConfig = toml::from_str(overlay_toml).unwrap();
        let profile = cfg.into_style_profile(dir.path()).unwrap();
        assert_eq!(profile.name, "child");
        assert_eq!(profile.verbosity, Verbosity::Verbose);
        assert_eq!(profile.list_style_bias, ListStyleBias::Bracketed);
    }

    #[test]
    fn extends_cycle_is_rejected() {
        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("a.toml"),
            r#"
                extends = "b.toml"
                name = "a"
            "#,
        )
        .unwrap();
        fs::write(
            dir.path().join("b.toml"),
            r#"
                extends = "a.toml"
                name = "b"
            "#,
        )
        .unwrap();
        let cfg = StyleProfileConfig {
            extends: Some("a.toml".to_string()),
            ..Default::default()
        };
        let result = cfg.into_style_profile(dir.path());
        assert!(matches!(
            result,
            Err(ProjectError::ManifestStyle { reason }) if reason.contains("cycle")
        ));
    }

    #[test]
    fn validation_errors_propagate() {
        let toml_str = r#"
            name = "bad"
            [hedging]
            offset = 75
        "#;
        let cfg: StyleProfileConfig = toml::from_str(toml_str).unwrap();
        let dir = tempdir().unwrap();
        let result = cfg.into_style_profile(dir.path());
        assert!(matches!(
            result,
            Err(ProjectError::ManifestStyle { reason }) if reason.contains("75")
        ));
    }

    #[test]
    fn empty_config_produces_neutral_profile() {
        let cfg = StyleProfileConfig::default();
        let dir = tempdir().unwrap();
        let profile = cfg.into_style_profile(dir.path()).unwrap();
        assert!(profile.is_neutral());
    }
}