drawlang 0.1.2

Precision diagrams as code — a DSL and renderer built for AI-agent authors
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
mod explain;

use clap::{Parser, Subcommand};
use drawlang_syntax::diag::{self, Styles};
use drawlang_syntax::{Severity, SourceFile};
use std::io::IsTerminal;
use std::path::PathBuf;
use std::process::ExitCode;

/// Exit codes: 0 clean, 1 lints denied, 2 errors, 101 internal bug.
const EXIT_CLEAN: u8 = 0;
const EXIT_ERRORS: u8 = 2;

/// Shown under error output so an agent that has only the binary can find
/// the language reference on its own.
const GUIDE_HINT: &str = "hint: `drawlang cheatsheet` prints the full syntax reference; `drawlang explain <CODE>` details any code above";

#[derive(Parser)]
#[command(
    name = "drawlang",
    version,
    about = "Precision diagrams as code, built for AI-agent authors",
    after_help = "Learning the language:\n  \
drawlang cheatsheet      full syntax cheat sheet, sized for an LLM context window\n  \
drawlang explain <CODE>  what any error/lint code means and how to fix it\n\n\
Typical loop: edit -> `check` -> `render --report` -> fix lints -> repeat.",
    propagate_version = true
)]
struct Cli {
    #[command(subcommand)]
    command: Command,
    /// Emit machine-readable JSON instead of human output.
    #[arg(long, global = true)]
    json: bool,
    /// Disable colored output (also respects NO_COLOR).
    #[arg(long, global = true)]
    no_color: bool,
}

#[derive(Subcommand)]
enum Command {
    /// Parse and lint a file without rendering.
    Check {
        /// The .drawl file to check.
        file: PathBuf,
    },
    /// Render a diagram to SVG or PNG.
    Render {
        /// The .drawl file to render.
        file: PathBuf,
        /// Output path; format inferred from extension (.svg, .png).
        #[arg(short, long)]
        out: Option<PathBuf>,
        /// Also emit the geometry report (JSON) next to the output.
        #[arg(long)]
        report: bool,
        /// Raster scale factor for PNG output.
        #[arg(long, default_value_t = 2.0)]
        scale: f32,
        /// Override the canvas theme (paper or dark).
        #[arg(long)]
        theme: Option<String>,
    },
    /// Print resolved geometry and styles for one element.
    Query {
        file: PathBuf,
        /// Element path, e.g. `host.cpu` or `gpus[2].pcie`.
        path: String,
    },
    /// Canonically format a file in place (or check with --check).
    Fmt {
        file: PathBuf,
        /// Exit non-zero if the file is not already formatted.
        #[arg(long)]
        check: bool,
    },
    /// Solve layout and write a `.lock` sidecar pinning today's positions.
    /// Subsequent renders reuse them, so edits don't reshuffle the diagram.
    Freeze { file: PathBuf },
    /// Explain an error or lint code, e.g. `drawlang explain E0214`.
    Explain { code: String },
    /// Print the syntax cheat sheet, sized for an LLM context window.
    Cheatsheet,
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    let code = run(cli);
    ExitCode::from(code)
}

fn styles(cli_no_color: bool) -> Styles {
    let want_color =
        !cli_no_color && std::env::var_os("NO_COLOR").is_none() && std::io::stderr().is_terminal();
    if want_color {
        Styles::colored()
    } else {
        Styles::plain()
    }
}

fn read_source(path: &PathBuf) -> Result<SourceFile, String> {
    let text = std::fs::read_to_string(path)
        .map_err(|e| format!("cannot read `{}`: {e}", path.display()))?;
    Ok(SourceFile::new(path.display().to_string(), text))
}

fn run(cli: Cli) -> u8 {
    match &cli.command {
        Command::Check { file } => cmd_check(file, &cli),
        Command::Render {
            file,
            out,
            report,
            scale,
            theme,
        } => cmd_render(file, out.as_ref(), *report, *scale, theme.as_deref(), &cli),
        Command::Query { file, path } => cmd_query(file, path, &cli),
        Command::Fmt { file, check } => cmd_fmt(file, *check, &cli),
        Command::Freeze { file } => cmd_freeze(file, &cli),
        Command::Explain { code } => explain::cmd_explain(code),
        Command::Cheatsheet => {
            print!("{}", include_str!("cheatsheet.md"));
            EXIT_CLEAN
        }
    }
}

fn cmd_render(
    file: &PathBuf,
    out: Option<&PathBuf>,
    report: bool,
    scale: f32,
    theme: Option<&str>,
    cli: &Cli,
) -> u8 {
    let src = match read_source(file) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("error: {e}");
            return EXIT_ERRORS;
        }
    };
    let compiled = drawlang_core::compile(&src.text);
    let mut doc = compiled.doc;
    let mut diagnostics = compiled.diagnostics;
    let has_compile_errors = diagnostics.iter().any(|d| d.severity == Severity::Error);
    if !has_compile_errors {
        apply_lock(file, &mut doc);
    }
    match theme {
        Some("paper") => doc.canvas.theme = drawlang_core::model::Theme::Paper,
        Some("dark") => doc.canvas.theme = drawlang_core::model::Theme::Dark,
        Some(other) => {
            eprintln!("error: unknown theme `{other}` (expected `paper` or `dark`)");
            return EXIT_ERRORS;
        }
        None => {}
    }

    let layout = if has_compile_errors {
        None
    } else {
        Some(drawlang_core::layout(&doc))
    };
    if let Some(l) = &layout {
        diagnostics.extend(l.diagnostics.clone());
    }

    if cli.json {
        let resolved: Vec<_> = diagnostics.iter().map(|d| diag::resolve(d, &src)).collect();
        println!("{}", serde_json::to_string_pretty(&resolved).unwrap());
    } else if !diagnostics.is_empty() {
        eprint!(
            "{}",
            diag::render_all(&diagnostics, &src, &styles(cli.no_color))
        );
    }
    if diagnostics.iter().any(|d| d.severity == Severity::Error) {
        if !cli.json {
            eprintln!("{}", GUIDE_HINT);
        }
        return EXIT_ERRORS;
    }
    let layout = layout.expect("no errors, layout ran");

    let svg = drawlang_render::render_svg(&doc, &layout.geometry);

    // Output path: default <input>.svg next to the source.
    let out_path = out.cloned().unwrap_or_else(|| file.with_extension("svg"));
    let is_png = out_path.extension().and_then(|e| e.to_str()) == Some("png");
    let bytes = if is_png {
        match drawlang_render::render_png(&svg, scale) {
            Ok(b) => b,
            Err(e) => {
                eprintln!("error: PNG rasterization failed: {e}");
                return EXIT_ERRORS;
            }
        }
    } else {
        svg.clone().into_bytes()
    };
    if let Err(e) = std::fs::write(&out_path, &bytes) {
        eprintln!("error: cannot write `{}`: {e}", out_path.display());
        return EXIT_ERRORS;
    }
    if !cli.json {
        eprintln!("wrote {}", out_path.display());
    }

    if report {
        let rep = drawlang_core::report::report(&doc, &layout.geometry);
        println!("{}", serde_json::to_string_pretty(&rep).unwrap());
    }
    EXIT_CLEAN
}

fn cmd_query(file: &PathBuf, path: &str, cli: &Cli) -> u8 {
    let src = match read_source(file) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("error: {e}");
            return EXIT_ERRORS;
        }
    };
    let compiled = drawlang_core::compile(&src.text);
    if compiled
        .diagnostics
        .iter()
        .any(|d| d.severity == Severity::Error)
    {
        eprint!(
            "{}",
            diag::render_all(&compiled.diagnostics, &src, &styles(cli.no_color))
        );
        return EXIT_ERRORS;
    }
    let layout = drawlang_core::layout(&compiled.doc);
    let rep = drawlang_core::report::report(&compiled.doc, &layout.geometry);

    // Accept both element paths and `element.port` references.
    if let Some(entry) = rep.elements.iter().find(|e| e.path == path) {
        println!("{}", serde_json::to_string_pretty(entry).unwrap());
        return EXIT_CLEAN;
    }
    if let Some((parent, port)) = path.rsplit_once('.') {
        if let Some(entry) = rep.elements.iter().find(|e| e.path == parent) {
            if let Some(pos) = entry.ports.get(port) {
                println!(
                    "{}",
                    serde_json::json!({ "path": path, "port": port, "position": pos })
                );
                return EXIT_CLEAN;
            }
        }
    }
    let known: Vec<&str> = rep.elements.iter().map(|e| e.path.as_str()).collect();
    let suggestion = drawlang_syntax::diag::suggest(path, known.iter().copied())
        .map(|s| format!(" — did you mean `{s}`?"))
        .unwrap_or_default();
    eprintln!("error: no element `{path}` in `{}`{suggestion}", src.name);
    eprintln!(
        "hint: `drawlang render {} --report` lists every element path",
        src.name
    );
    EXIT_ERRORS
}

fn cmd_fmt(file: &PathBuf, check_only: bool, cli: &Cli) -> u8 {
    let src = match read_source(file) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("error: {e}");
            return EXIT_ERRORS;
        }
    };
    let parsed = drawlang_syntax::parse_source(&src.text);
    if parsed.has_errors() {
        eprintln!(
            "error: cannot format `{}` — fix syntax errors first:",
            src.name
        );
        eprint!(
            "{}",
            diag::render_all(&parsed.diagnostics, &src, &styles(cli.no_color))
        );
        return EXIT_ERRORS;
    }
    let formatted = drawlang_syntax::fmt::format(&parsed.file, &src.text);
    if check_only {
        if formatted == src.text {
            eprintln!("{}: already formatted", src.name);
            EXIT_CLEAN
        } else {
            eprintln!("{}: would be reformatted", src.name);
            1
        }
    } else if formatted == src.text {
        eprintln!("{}: unchanged", src.name);
        EXIT_CLEAN
    } else if let Err(e) = std::fs::write(file, &formatted) {
        eprintln!("error: cannot write `{}`: {e}", file.display());
        EXIT_ERRORS
    } else {
        eprintln!("formatted {}", src.name);
        EXIT_CLEAN
    }
}

fn lock_path(file: &std::path::Path) -> PathBuf {
    let mut p = file.to_path_buf();
    let ext = p.extension().and_then(|e| e.to_str()).unwrap_or("drawl");
    p.set_extension(format!("{ext}.lock"));
    p
}

fn cmd_freeze(file: &PathBuf, cli: &Cli) -> u8 {
    let src = match read_source(file) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("error: {e}");
            return EXIT_ERRORS;
        }
    };
    let compiled = drawlang_core::compile(&src.text);
    if compiled
        .diagnostics
        .iter()
        .any(|d| d.severity == Severity::Error)
    {
        eprint!(
            "{}",
            diag::render_all(&compiled.diagnostics, &src, &styles(cli.no_color))
        );
        return EXIT_ERRORS;
    }
    let layout = drawlang_core::layout(&compiled.doc);
    let geo = &layout.geometry;
    // Content-local positions of every top-level element, so they survive
    // padding/title changes.
    let doc = &compiled.doc;
    let mut min_x = f64::INFINITY;
    let mut min_y = f64::INFINITY;
    for &c in doc.children(doc.root) {
        let r = geo.rect(c);
        min_x = min_x.min(r.x);
        min_y = min_y.min(r.y);
    }
    let mut pins = serde_json::Map::new();
    for &c in doc.children(doc.root) {
        let r = geo.rect(c);
        pins.insert(
            doc.el(c).path.clone(),
            serde_json::json!([
                ((r.x - min_x) * 100.0).round() / 100.0,
                ((r.y - min_y) * 100.0).round() / 100.0
            ]),
        );
    }
    let lock = serde_json::json!({ "version": 1, "pins": pins });
    let out = lock_path(file);
    if let Err(e) = std::fs::write(&out, serde_json::to_string_pretty(&lock).unwrap()) {
        eprintln!("error: cannot write `{}`: {e}", out.display());
        return EXIT_ERRORS;
    }
    eprintln!(
        "froze {} top-level positions to {} (renders now reuse them; delete the file to re-layout)",
        pins.len(),
        out.display()
    );
    EXIT_CLEAN
}

/// Apply a `.lock` sidecar (if present) as pins on the document.
fn apply_lock(file: &std::path::Path, doc: &mut drawlang_core::model::Document) {
    let path = lock_path(file);
    let Ok(text) = std::fs::read_to_string(&path) else {
        return;
    };
    let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) else {
        eprintln!("warning: ignoring malformed lock file `{}`", path.display());
        return;
    };
    let Some(pins) = value.get("pins").and_then(|p| p.as_object()) else {
        return;
    };
    let mut applied = 0;
    for (path_str, pos) in pins {
        let (Some(x), Some(y)) = (
            pos.get(0).and_then(|v| v.as_f64()),
            pos.get(1).and_then(|v| v.as_f64()),
        ) else {
            continue;
        };
        if let Some(id) = doc.lookup_path(path_str) {
            if doc.el(id).parent == Some(doc.root) {
                doc.pins.push(drawlang_core::model::PinDecl {
                    target: id,
                    x,
                    y,
                    span: drawlang_syntax::Span::DUMMY,
                });
                applied += 1;
            }
        }
    }
    if applied > 0 {
        eprintln!(
            "note: applied {applied} pinned positions from `{}`",
            path.display()
        );
    }
}

fn cmd_check(file: &PathBuf, cli: &Cli) -> u8 {
    let src = match read_source(file) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("error: {e}");
            return EXIT_ERRORS;
        }
    };
    let compiled = drawlang_core::compile(&src.text);
    let mut diagnostics = compiled.diagnostics;
    // Layout also lints (constraint conflicts, ineffective constraints).
    if !diagnostics.iter().any(|d| d.severity == Severity::Error) {
        diagnostics.extend(drawlang_core::layout(&compiled.doc).diagnostics);
    }

    if cli.json {
        let resolved: Vec<_> = diagnostics.iter().map(|d| diag::resolve(d, &src)).collect();
        println!("{}", serde_json::to_string_pretty(&resolved).unwrap());
    } else if !diagnostics.is_empty() {
        eprint!(
            "{}",
            diag::render_all(&diagnostics, &src, &styles(cli.no_color))
        );
    }

    let has_errors = diagnostics.iter().any(|d| d.severity == Severity::Error);
    if has_errors {
        if !cli.json {
            eprintln!("{}", GUIDE_HINT);
        }
        EXIT_ERRORS
    } else {
        if !cli.json && diagnostics.is_empty() {
            eprintln!("{}: no problems found", src.name);
        }
        EXIT_CLEAN
    }
}