wcl 0.6.1-alpha

WCL (Wil's Configuration Language) — a typed, block-structured configuration language
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
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::Path;

use crate::schema::type_name;
use crate::{ResolvedField, ResolvedSchema, ResolvedVariant, ValidateConstraints};

pub fn run(
    files: &[std::path::PathBuf],
    output: &Path,
    title: &str,
    lib_args: &crate::cli::LibraryArgs,
) -> Result<(), String> {
    // Parse all files and collect schemas (flattened from per-name vecs)
    let mut all_schemas: HashMap<String, ResolvedSchema> = HashMap::new();

    for file in files {
        let source = fs::read_to_string(file)
            .map_err(|e| format!("failed to read {}: {}", file.display(), e))?;
        let mut opts = crate::ParseOptions {
            root_dir: file.parent().unwrap_or(Path::new(".")).to_path_buf(),
            ..Default::default()
        };
        lib_args.apply(&mut opts);
        let doc = crate::parse(&source, opts);
        for (name, schema_vec) in doc.schemas.schemas {
            let has_scoped = schema_vec.len() > 1;
            for schema in schema_vec {
                let key = match &schema.allowed_parents {
                    Some(parents) if has_scoped => {
                        format!("{} (in {})", name, parents.join(", "))
                    }
                    _ => name.clone(),
                };
                all_schemas.insert(key, schema);
            }
        }
    }

    if all_schemas.is_empty() {
        return Err("no schemas found in input files".to_string());
    }

    // Build hierarchy
    let tree = SchemaTree::build(&all_schemas);

    // Create output directories
    let src_dir = output.join("src");
    let schemas_dir = src_dir.join("schemas");
    fs::create_dir_all(&schemas_dir)
        .map_err(|e| format!("failed to create output directory: {}", e))?;

    // Write book.toml
    fs::write(
        output.join("book.toml"),
        format!(
            "[book]\ntitle = \"{}\"\nsrc = \"src\"\n\n[output.html]\ndefault-theme = \"light\"\n",
            title
        ),
    )
    .map_err(|e| format!("failed to write book.toml: {}", e))?;

    // Build ordered list for SUMMARY
    let ordered = tree.ordered_schemas();

    // Write SUMMARY.md
    let mut summary = String::from("# Summary\n\n");
    summary.push_str("[Overview](overview.md)\n\n");
    summary.push_str("# Schemas\n\n");
    for (name, depth) in &ordered {
        let indent = "  ".repeat(*depth);
        summary.push_str(&format!("{}- [{}](schemas/{}.md)\n", indent, name, name));
    }
    fs::write(src_dir.join("SUMMARY.md"), summary)
        .map_err(|e| format!("failed to write SUMMARY.md: {}", e))?;

    // Write overview.md
    let mut overview = format!("# {}\n\n", title);
    overview.push_str(&format!(
        "This reference documents **{}** schemas.\n\n",
        all_schemas.len()
    ));

    // Hierarchy diagram
    if !tree.roots.is_empty() {
        overview.push_str("## Hierarchy\n\n```\n");
        let mut diagram_visited = HashSet::new();
        for root in &tree.roots {
            write_tree_diagram(
                &mut overview,
                root,
                &tree.children_map,
                0,
                &mut diagram_visited,
            );
        }
        overview.push_str("```\n\n");
    }

    overview.push_str("## All Schemas\n\n");
    overview.push_str("| Schema | Description |\n|--------|-------------|\n");
    let mut sorted_names: Vec<_> = all_schemas.keys().collect();
    sorted_names.sort();
    for name in &sorted_names {
        let schema = &all_schemas[*name];
        let desc = schema.doc.as_deref().unwrap_or("");
        overview.push_str(&format!("| [{}](schemas/{}.md) | {} |\n", name, name, desc));
    }
    fs::write(src_dir.join("overview.md"), overview)
        .map_err(|e| format!("failed to write overview.md: {}", e))?;

    // Write per-schema pages
    for (name, schema) in &all_schemas {
        let page = render_schema_page(name, schema, &all_schemas);
        fs::write(schemas_dir.join(format!("{}.md", name)), page)
            .map_err(|e| format!("failed to write {}.md: {}", name, e))?;
    }

    eprintln!(
        "Generated mdBook with {} schemas in {}",
        all_schemas.len(),
        output.display()
    );
    Ok(())
}

// ── Schema tree for hierarchy ───────────────────────────────────────────────

struct SchemaTree {
    roots: Vec<String>,
    children_map: HashMap<String, Vec<String>>,
}

impl SchemaTree {
    fn build(schemas: &HashMap<String, ResolvedSchema>) -> Self {
        let mut children_map: HashMap<String, Vec<String>> = HashMap::new();
        let mut has_parent: HashSet<String> = HashSet::new();

        for (name, schema) in schemas {
            if name == "_root" {
                continue;
            }
            if let Some(ref parents) = schema.allowed_parents {
                for parent in parents {
                    children_map
                        .entry(parent.clone())
                        .or_default()
                        .push(name.clone());
                    has_parent.insert(name.clone());
                }
            }
        }

        // Sort children for deterministic output
        for children in children_map.values_mut() {
            children.sort();
        }

        // Roots: schemas listed as children of _root, or schemas without @parent
        let mut roots: Vec<String> = Vec::new();
        if let Some(root_children) = children_map.get("_root") {
            roots.extend(root_children.iter().cloned());
        }
        // Add schemas with no @parent that aren't already roots
        let mut parentless: Vec<String> = schemas
            .keys()
            .filter(|n| *n != "_root" && !has_parent.contains(*n))
            .cloned()
            .collect();
        parentless.sort();
        for name in parentless {
            if !roots.contains(&name) {
                roots.push(name);
            }
        }
        roots.sort();

        SchemaTree {
            roots,
            children_map,
        }
    }

    fn ordered_schemas(&self) -> Vec<(String, usize)> {
        let mut result = Vec::new();
        let mut visited = HashSet::new();
        for root in &self.roots {
            self.dfs(root, 0, &mut visited, &mut result);
        }
        result
    }

    fn dfs(
        &self,
        name: &str,
        depth: usize,
        visited: &mut HashSet<String>,
        result: &mut Vec<(String, usize)>,
    ) {
        if !visited.insert(name.to_string()) {
            return;
        }
        result.push((name.to_string(), depth));
        if let Some(children) = self.children_map.get(name) {
            for child in children {
                self.dfs(child, depth + 1, visited, result);
            }
        }
    }
}

fn write_tree_diagram(
    out: &mut String,
    name: &str,
    children_map: &HashMap<String, Vec<String>>,
    depth: usize,
    visited: &mut HashSet<String>,
) {
    let indent = "  ".repeat(depth);
    if !visited.insert(name.to_string()) {
        out.push_str(&format!("{}{} (...)\n", indent, name));
        return;
    }
    out.push_str(&format!("{}{}\n", indent, name));
    if let Some(children) = children_map.get(name) {
        for child in children {
            write_tree_diagram(out, child, children_map, depth + 1, visited);
        }
    }
}

// ── Page rendering ──────────────────────────────────────────────────────────

fn render_schema_page(
    name: &str,
    schema: &ResolvedSchema,
    all_schemas: &HashMap<String, ResolvedSchema>,
) -> String {
    let mut page = format!("# {}\n\n", name);

    // Doc text
    if let Some(ref doc) = schema.doc {
        page.push_str(doc);
        page.push_str("\n\n");
    }

    // Badges
    let mut badges = Vec::new();
    if schema.open {
        badges.push("`open`".to_string());
    }
    if let Some(ref tag) = schema.tag_field {
        badges.push(format!("`tagged({})`", tag));
    }
    if schema
        .allowed_children
        .as_ref()
        .is_some_and(|c| c.is_empty())
    {
        badges.push("`leaf`".to_string());
    }
    if !badges.is_empty() {
        page.push_str(&badges.join(" "));
        page.push_str("\n\n");
    }

    // Fields table
    if !schema.fields.is_empty() {
        page.push_str("## Fields\n\n");
        page.push_str(
            "| Field | Type | Required | Default | Constraints | Description |\n\
             |-------|------|----------|---------|-------------|-------------|\n",
        );
        for field in &schema.fields {
            page.push_str(&render_field_row(field));
        }
        page.push('\n');
    }

    // Variants
    if !schema.variants.is_empty() {
        page.push_str("## Variants\n\n");
        for variant in &schema.variants {
            render_variant(&mut page, variant);
        }
    }

    // Relationships
    page.push_str("## Relationships\n\n");
    render_relationships(&mut page, name, schema, all_schemas);

    page
}

fn render_field_row(field: &ResolvedField) -> String {
    let type_str = type_name(&field.type_expr);
    let required = if field.required { "yes" } else { "no" };
    let default = field
        .default
        .as_ref()
        .map(|v| format!("`{}`", v))
        .unwrap_or_default();
    let constraints = render_constraints(&field.validate, &field.ref_target, &field.id_pattern);
    let desc = field.doc.as_deref().unwrap_or("");

    format!(
        "| {} | `{}` | {} | {} | {} | {} |\n",
        field.name, type_str, required, default, constraints, desc
    )
}

fn render_constraints(
    validate: &Option<ValidateConstraints>,
    ref_target: &Option<String>,
    id_pattern: &Option<String>,
) -> String {
    let mut parts = Vec::new();

    if let Some(ref v) = validate {
        if let Some(min) = v.min {
            parts.push(format!("min={}", min));
        }
        if let Some(max) = v.max {
            parts.push(format!("max={}", max));
        }
        if let Some(ref pat) = v.pattern {
            parts.push(format!("pattern=`{}`", pat));
        }
        if let Some(ref vals) = v.one_of {
            let items: Vec<String> = vals.iter().map(|v| format!("{}", v)).collect();
            parts.push(format!("one\\_of=[{}]", items.join(", ")));
        }
    }

    if let Some(ref target) = ref_target {
        parts.push(format!("@ref({})", target));
    }
    if let Some(ref pat) = id_pattern {
        parts.push(format!("@id\\_pattern(`{}`)", pat));
    }

    parts.join(", ")
}

fn render_variant(page: &mut String, variant: &ResolvedVariant) {
    page.push_str(&format!("### Variant: `{}`\n\n", variant.tag_value));
    if let Some(ref doc) = variant.doc {
        page.push_str(doc);
        page.push_str("\n\n");
    }
    if !variant.fields.is_empty() {
        page.push_str(
            "| Field | Type | Required | Default | Constraints | Description |\n\
             |-------|------|----------|---------|-------------|-------------|\n",
        );
        for field in &variant.fields {
            page.push_str(&render_field_row(field));
        }
        page.push('\n');
    }
}

fn render_relationships(
    page: &mut String,
    name: &str,
    schema: &ResolvedSchema,
    all_schemas: &HashMap<String, ResolvedSchema>,
) {
    // Parents
    match &schema.allowed_parents {
        Some(parents) => {
            let links: Vec<String> = parents
                .iter()
                .map(|p| {
                    if p == "_root" {
                        "*(root)*".to_string()
                    } else {
                        format!("[{}](schemas/{}.md)", p, p)
                    }
                })
                .collect();
            page.push_str(&format!("- **Parent**: {}\n", links.join(", ")));
        }
        None => page.push_str("- **Parent**: any\n"),
    }

    // Children
    match &schema.allowed_children {
        Some(children) if children.is_empty() => {
            page.push_str("- **Children**: none (leaf)\n");
        }
        Some(children) => {
            let links: Vec<String> = children
                .iter()
                .map(|c| format!("[{}](schemas/{}.md)", c, c))
                .collect();
            page.push_str(&format!("- **Children**: {}\n", links.join(", ")));
        }
        None => page.push_str("- **Children**: any\n"),
    }

    // Child constraints
    if !schema.child_constraints.is_empty() {
        page.push_str("- **Child constraints**:\n");
        for cc in &schema.child_constraints {
            let mut parts = vec![format!("`{}`", cc.kind)];
            if let Some(min) = cc.min {
                parts.push(format!("min={}", min));
            }
            if let Some(max) = cc.max {
                parts.push(format!("max={}", max));
            }
            if let Some(md) = cc.max_depth {
                parts.push(format!("max\\_depth={}", md));
            }
            page.push_str(&format!("  - {}\n", parts.join(", ")));
        }
    }

    // Reverse: who lists this schema as a child?
    let mut referenced_by: Vec<&str> = all_schemas
        .iter()
        .filter(|(_, s)| {
            s.allowed_children
                .as_ref()
                .is_some_and(|c| c.iter().any(|ch| ch == name))
        })
        .map(|(n, _)| n.as_str())
        .collect();
    referenced_by.sort();
    if !referenced_by.is_empty() {
        let links: Vec<String> = referenced_by
            .iter()
            .map(|r| {
                if *r == "_root" {
                    "*(root)*".to_string()
                } else {
                    format!("[{}](schemas/{}.md)", r, r)
                }
            })
            .collect();
        page.push_str(&format!("- **Referenced by**: {}\n", links.join(", ")));
    }
}