rpic-core 0.6.2

Core engine for rpic: lexer, parser, geometry, and SVG/PNG/PDF backends for the pic graphics language.
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
//! rpic-core — engine for the `pic` picture-drawing language.
//!
//! Pipeline: source → [`lexer`] → [`parser`] → [`ast`] → [`eval`] → placed
//! primitives ([`ir`]) → render backends ([`svg`], later PNG/PDF). This crate
//! is pure (no file I/O); the CLI and WASM wrappers drive it.
//!
//! Note: [`eval`] is the pic-language *interpreter* — a safe walker over a typed
//! expression/geometry tree. It executes no arbitrary code.

pub mod ast;
pub mod diagnostic;
pub mod eval;
pub mod geom;
pub mod ir;
pub mod lexer;
mod math;
pub mod parser;
pub mod svg;
pub mod token;

pub use ast::{IncludeCtx, IncludePolicy};
pub use diagnostic::{CompileError, Diagnostic, Span};
pub use eval::{EvalError, eval};
pub use ir::Drawing;
pub use lexer::{LexError, lex};
pub use math::{MathSpan, set_math_renderer};
pub use parser::{ParseError, parse, parse_in_dir, parse_with_prelude};
pub use svg::to_svg;
pub use token::Token;

/// Bundled native circuit-element library (the `define` dialect). Prepend it to
/// source to use `resistor`, `capacitor`, … See `std/circuits.pic`.
pub const CIRCUITS: &str = include_str!("std/circuits.pic");

/// Compile pic source into a placed-primitive [`Drawing`].
pub fn compile(src: &str) -> Result<Drawing, String> {
    compile_in_dir(src, None)
}

/// Compile pic source, resolving `copy "file"` includes relative to `base`.
pub fn compile_in_dir(src: &str, base: Option<&std::path::Path>) -> Result<Drawing, String> {
    let picture = parser::parse_in_dir(src, base).map_err(|e| e.to_string())?;
    eval(&picture).map_err(|e| e.to_string())
}

/// Compile pic source directly to an SVG string.
pub fn render_svg(src: &str) -> Result<String, String> {
    Ok(to_svg(&compile(src)?))
}

/// Render pic source to SVG, resolving `copy "file"` includes relative to `base`.
pub fn render_svg_in_dir(src: &str, base: Option<&std::path::Path>) -> Result<String, String> {
    Ok(to_svg(&compile_in_dir(src, base)?))
}

/// Build the JSON animation manifest array (`[{id,effect,start,duration},…]`)
/// for an already-compiled drawing.
pub fn animations_json(d: &Drawing) -> String {
    let mut s = String::from("[");
    for (i, a) in d.anims.iter().enumerate() {
        if i > 0 {
            s.push(',');
        }
        s.push_str(&format!(
            "{{\"id\":\"s{}\",\"effect\":\"{}\",\"start\":{},\"duration\":{}}}",
            a.shape,
            json_str(&a.effect),
            a.start,
            a.duration
        ));
    }
    s.push(']');
    s
}

/// Build the JSON diagnostic array emitted by pic `print` statements.
pub fn diagnostics_json(d: &Drawing) -> String {
    let mut s = String::from("[");
    for (i, line) in d.diagnostics.iter().enumerate() {
        if i > 0 {
            s.push(',');
        }
        s.push('"');
        s.push_str(&json_str(line));
        s.push('"');
    }
    s.push(']');
    s
}

/// Compile options for the `*_with_options` entry points — the library
/// equivalents of the CLI flags. Preludes (`circuits`, `texlabels`) are lexed
/// as their own named source units, NOT glued in front of the user's source,
/// so diagnostic positions always stay relative to the source they belong to
/// (`Diagnostic::file` names an include/library; `None` is the user's input).
#[derive(Debug, Clone, Default)]
pub struct CompileOptions {
    /// Load the embedded circuit-element library (the `-c` flag).
    pub circuits: bool,
    /// Inject `texlabels = 1` as an initializer (the `-t` flag); the source
    /// can still override it.
    pub texlabels: bool,
    /// Resolve `copy "file"` includes relative to this directory.
    pub base: Option<std::path::PathBuf>,
    /// Policy for `copy "file"` filesystem includes — leave the default
    /// (`Unrestricted`, the CLI behavior) for local use; embedders compiling
    /// untrusted source should pick `SandboxedToBase` or `Deny`.
    pub includes: IncludePolicy,
}

/// Compile pic source with [`CompileOptions`] into a [`Drawing`].
pub fn compile_with_options(src: &str, opts: &CompileOptions) -> Result<Drawing, String> {
    compile_with_diagnostics(src, opts).map_err(|e| e.message)
}

/// Like [`compile_with_options`], but failures return the structured
/// [`CompileError`] (flat message + [`Diagnostic`]) instead of a bare string —
/// for bindings that attach position data to exceptions/conditions.
pub fn compile_with_diagnostics(src: &str, opts: &CompileOptions) -> Result<Drawing, CompileError> {
    let picture = parse_options(src, opts).map_err(|e| CompileError {
        message: e.to_string(),
        info: Box::new(e.diagnostic()),
    })?;
    eval(&picture).map_err(|e| {
        // Eval errors carry their own diagnostic when the failure site had
        // one (deferred-parse errors, unknown labels, ordinals — with spans
        // straight from the failing reference's tokens, includes included).
        let info = e
            .info
            .clone()
            .unwrap_or_else(|| Box::new(Diagnostic::new("eval", e.msg.clone())));
        CompileError {
            message: e.msg,
            info,
        }
    })
}

/// Render pic source to SVG with [`CompileOptions`].
pub fn render_svg_with_options(src: &str, opts: &CompileOptions) -> Result<String, String> {
    Ok(to_svg(&compile_with_options(src, opts)?))
}

fn parse_options(src: &str, opts: &CompileOptions) -> Result<ast::Picture, ParseError> {
    parser::parse_with_prelude(
        src,
        ast::IncludeCtx::with_policy(opts.base.clone(), opts.includes),
        opts.circuits,
        opts.texlabels,
    )
}

/// Compile to a single JSON object `{ "svg": "...", "animations": [...],
/// "diagnostics": [...], "warnings": [...] }`, or `{ "error": "...",
/// "error_info": { ... } }` on failure. The flat `error` string is kept for
/// backward compatibility with older bindings.
pub fn compile_json(src: &str) -> String {
    compile_json_with_options(src, &CompileOptions::default())
}

/// Compile to a JSON bundle, resolving `copy "file"` includes relative to
/// `base`.
pub fn compile_json_in_dir(src: &str, base: Option<&std::path::Path>) -> String {
    compile_json_with_options(
        src,
        &CompileOptions {
            base: base.map(|p| p.to_path_buf()),
            ..Default::default()
        },
    )
}

/// Compile to a JSON bundle with [`CompileOptions`]. Diagnostic positions are
/// relative to the user's `src` (or carry a `file` naming the include/library
/// they are in) — never to a concatenated stream.
pub fn compile_json_with_options(src: &str, opts: &CompileOptions) -> String {
    match compile_with_diagnostics(src, opts) {
        Ok(d) => drawing_json(&d),
        Err(e) => error_json(&e.message, &e.info),
    }
}

fn drawing_json(d: &Drawing) -> String {
    format!(
        "{{\"svg\":\"{}\",\"animations\":{},\"diagnostics\":{},\"warnings\":{}}}",
        json_str(&to_svg(d)),
        animations_json(d),
        diagnostics_json(d),
        diagnostics_json_structured(&d.warnings)
    )
}

fn error_json(message: &str, diagnostic: &Diagnostic) -> String {
    format!(
        "{{\"error\":\"{}\",\"error_info\":{},\"warnings\":[]}}",
        json_str(message),
        diagnostic_json(diagnostic)
    )
}

fn diagnostics_json_structured(items: &[Diagnostic]) -> String {
    let mut s = String::from("[");
    for (i, d) in items.iter().enumerate() {
        if i > 0 {
            s.push(',');
        }
        s.push_str(&diagnostic_json(d));
    }
    s.push(']');
    s
}

fn diagnostic_json(d: &Diagnostic) -> String {
    let mut s = String::from("{");
    s.push_str(&format!("\"message\":\"{}\"", json_str(&d.message)));
    s.push_str(&format!(",\"line\":{}", json_opt_u32(d.line)));
    s.push_str(&format!(",\"col\":{}", json_opt_u32(d.col)));
    s.push_str(&format!(",\"end_col\":{}", json_opt_u32(d.end_col)));
    s.push_str(&format!(",\"file\":{}", json_opt_str(d.file.as_deref())));
    s.push_str(&format!(",\"kind\":\"{}\"", json_str(&d.kind)));
    s.push_str(&format!(",\"found\":{}", json_opt_str(d.found.as_deref())));
    s.push_str(&format!(
        ",\"expected\":{}",
        json_opt_str(d.expected.as_deref())
    ));
    s.push_str(&format!(",\"hint\":{}", json_opt_str(d.hint.as_deref())));
    s.push('}');
    s
}

fn json_opt_u32(v: Option<u32>) -> String {
    v.map(|n| n.to_string()).unwrap_or_else(|| "null".into())
}

fn json_opt_str(v: Option<&str>) -> String {
    v.map(|s| format!("\"{}\"", json_str(s)))
        .unwrap_or_else(|| "null".into())
}

/// Escape a string for embedding inside a JSON string literal.
fn json_str(s: &str) -> String {
    let mut o = String::with_capacity(s.len() + 8);
    for c in s.chars() {
        match c {
            '"' => o.push_str("\\\""),
            '\\' => o.push_str("\\\\"),
            '\n' => o.push_str("\\n"),
            '\r' => o.push_str("\\r"),
            '\t' => o.push_str("\\t"),
            c if (c as u32) < 0x20 => o.push_str(&format!("\\u{:04x}", c as u32)),
            c => o.push(c),
        }
    }
    o
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn json_bundles_svg_and_animations() {
        let j = compile_json("box\nanimate last box with \"fade\"");
        assert!(j.starts_with("{\"svg\":\"<svg"));
        assert!(j.contains("<g id=\\\"s0\\\">")); // stable id, JSON-escaped
        assert!(j.contains("\"animations\":[{\"id\":\"s0\",\"effect\":\"fade\""));
        assert!(j.contains("\"diagnostics\":[]"));
    }

    #[test]
    fn json_reports_errors() {
        let j = compile_json("copy \"oops\"");
        assert!(j.contains("\"error\""));
        assert!(j.contains("\"error_info\""));
    }

    #[test]
    fn json_reports_print_diagnostics() {
        let j = compile_json("print \"hi\"\nprint 2+3");
        assert!(j.contains("\"diagnostics\":[\"hi\",\"5\"]"));
    }

    #[test]
    fn copy_circuits_loads_the_embedded_library() {
        // `copy "circuits"` is the in-source spelling of `-c`: byte-identical
        // output, and it works with no base dir (the wasm/compile_json case,
        // where file includes are unavailable).
        let body = "A:(0,0); B:(2,0)\nresistor(A,B)";
        let via_copy = compile(&format!("copy \"circuits\"\n{body}")).unwrap();
        let via_flag = compile(&format!("{CIRCUITS}\n{body}")).unwrap();
        assert_eq!(to_svg(&via_copy), to_svg(&via_flag));
    }

    #[test]
    fn copy_circuits_is_idempotent_with_the_flag() {
        // `-c` plus an explicit `copy "circuits"` must not double-load (the
        // second load is skipped) — same bytes as the flag alone.
        let body = "A:(0,0); B:(2,0)\nresistor(A,B)";
        let both = compile(&format!("{CIRCUITS}\ncopy \"circuits\"\n{body}")).unwrap();
        let flag = compile(&format!("{CIRCUITS}\n{body}")).unwrap();
        assert_eq!(to_svg(&both), to_svg(&flag));
    }

    #[test]
    fn options_preludes_do_not_shift_user_positions() {
        // #181 acceptance: with the circuits/texlabels preludes on, an error
        // on the user's line 1 reports line 1 (not ~1093), file null.
        let opts = CompileOptions {
            circuits: true,
            texlabels: true,
            ..Default::default()
        };
        let j = compile_json_with_options("bxo\n", &opts);
        assert!(j.contains("\"line\":1"), "{j}");
        assert!(j.contains("\"col\":1"), "{j}");
        assert!(j.contains("\"file\":null"), "{j}");
        assert!(j.contains("\"error\":\"1:1: expected an object"), "{j}");
    }

    #[test]
    fn options_output_matches_the_prepending_it_replaces() {
        // The prelude splice must be behaviorally identical to the old
        // string-prepending: byte-identical SVG.
        let body = "A:(0,0); B:(2,0)\nresistor(A,B)";
        let opts = CompileOptions {
            circuits: true,
            ..Default::default()
        };
        let via_opts = compile_with_options(body, &opts).unwrap();
        let via_prepend = compile(&format!("{CIRCUITS}\n{body}")).unwrap();
        assert_eq!(to_svg(&via_opts), to_svg(&via_prepend));
    }

    #[test]
    fn options_texlabels_is_an_initializer_only() {
        // the source stays sovereign: `texlabels = 0` overrides the prelude
        let opts = CompileOptions {
            texlabels: true,
            ..Default::default()
        };
        let j = compile_json_with_options("texlabels = 0\nbox \"$x$\"\n", &opts);
        assert!(!j.contains("no math renderer"), "{j}");
    }

    #[test]
    fn diagnostics_inside_an_include_name_the_file() {
        // #181 acceptance: a warning (or error) inside a `copy`'d file carries
        // the include's name and include-relative position.
        let dir = std::env::temp_dir().join(format!("rpic_incl_diag_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("warn.pic"), "# comment\nbox \"a\" dashd\n").unwrap();
        let j = compile_json_in_dir("circle\ncopy \"warn.pic\"", Some(dir.as_path()));
        assert!(j.contains("\"kind\":\"ignored_attribute\""), "{j}");
        assert!(j.contains("\"file\":\"warn.pic\""), "{j}");
        assert!(j.contains("\"line\":2"), "{j}"); // include-relative, not stream

        std::fs::write(dir.join("bad.pic"), "bxo\n").unwrap();
        let e = compile_json_in_dir("circle\ncopy \"bad.pic\"", Some(dir.as_path()));
        let _ = std::fs::remove_dir_all(&dir);
        assert!(
            e.contains("\"error\":\"bad.pic:1:1: expected an object"),
            "{e}"
        );
        assert!(e.contains("\"file\":\"bad.pic\""), "{e}");
        assert!(e.contains("\"line\":1"), "{e}");
    }

    #[test]
    fn include_policy_sandboxes_and_denies() {
        // layout: root/outside.pic (outside the fence), root/base/inc.pic (in)
        let root = std::env::temp_dir().join(format!("rpic_inc_policy_{}", std::process::id()));
        let base = root.join("base");
        std::fs::create_dir_all(&base).unwrap();
        std::fs::write(root.join("outside.pic"), "circle\n").unwrap();
        std::fs::write(base.join("inc.pic"), "box wid 0.5 ht 0.5\n").unwrap();

        let sandboxed = CompileOptions {
            base: Some(base.clone()),
            includes: IncludePolicy::SandboxedToBase,
            ..Default::default()
        };
        // in-base include works
        assert!(compile_with_options("copy \"inc.pic\"\nbox", &sandboxed).is_ok());
        // `..` escape is denied, with the structured kind and the copy's span
        let esc = compile_json_with_options("copy \"../outside.pic\"\nbox", &sandboxed);
        assert!(esc.contains("\"kind\":\"include_denied\""), "{esc}");
        assert!(esc.contains("outside the include base directory"), "{esc}");
        assert!(esc.contains("\"line\":1"), "{esc}");
        // absolute paths are denied outright
        let abs_src = format!("copy \"{}\"\nbox", root.join("outside.pic").display());
        let abs = compile_json_with_options(&abs_src, &sandboxed);
        assert!(abs.contains("\"kind\":\"include_denied\""), "{abs}");
        assert!(abs.contains("absolute paths are not allowed"), "{abs}");
        // symlink pointing out of the fence is caught by canonicalization
        #[cfg(unix)]
        {
            let link = base.join("link.pic");
            let _ = std::fs::remove_file(&link);
            std::os::unix::fs::symlink(root.join("outside.pic"), &link).unwrap();
            let sym = compile_json_with_options("copy \"link.pic\"\nbox", &sandboxed);
            assert!(sym.contains("\"kind\":\"include_denied\""), "{sym}");
        }
        // the embedded library is not a filesystem include — always available
        assert!(
            compile_with_options(
                "copy \"circuits\"\nA:(0,0); B:(1,0)\nresistor(A,B)",
                &sandboxed
            )
            .is_ok()
        );

        let deny = CompileOptions {
            base: Some(base.clone()),
            includes: IncludePolicy::Deny,
            ..Default::default()
        };
        let d = compile_json_with_options("copy \"inc.pic\"\nbox", &deny);
        assert!(d.contains("\"kind\":\"include_denied\""), "{d}");
        assert!(d.contains("disabled by the include policy"), "{d}");
        assert!(compile_with_options("copy \"circuits\"\nbox", &deny).is_ok());

        // default stays the CLI behavior: `..` resolution is allowed
        let open = CompileOptions {
            base: Some(base.clone()),
            ..Default::default()
        };
        assert!(compile_with_options("copy \"../outside.pic\"\nbox", &open).is_ok());

        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn json_in_dir_resolves_copy_includes() {
        let dir = std::env::temp_dir().join(format!("rpic_json_copy_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("inc.pic"), "box wid 0.5 ht 0.5\n").unwrap();

        let j = compile_json_in_dir("copy \"inc.pic\"\ncircle", Some(dir.as_path()));
        let _ = std::fs::remove_dir_all(&dir);

        assert!(j.starts_with("{\"svg\":\"<svg"), "{j}");
        assert!(j.contains("<rect"), "{j}");
        assert!(j.contains("<circle"), "{j}");
        assert!(j.contains("\"diagnostics\":[]"), "{j}");
        assert!(!j.contains("\"error\""), "{j}");
    }

    #[test]
    fn json_error_info_uses_user_facing_tokens_and_spans() {
        let j = compile_json("bxo\n");

        assert!(
            j.contains("\"error\":\"1:1: expected an object, found `bxo`\""),
            "{j}"
        );
        assert!(j.contains("\"kind\":\"expected_token\""), "{j}");
        assert!(j.contains("\"line\":1"), "{j}");
        assert!(j.contains("\"col\":1"), "{j}");
        assert!(j.contains("\"end_col\":4"), "{j}");
        assert!(j.contains("\"found\":\"`bxo`\""), "{j}");
        assert!(j.contains("\"expected\":\"an object\""), "{j}");
        assert!(j.contains("\"hint\":\"did you mean `box`?\""), "{j}");
    }

    #[test]
    fn json_unterminated_string_points_at_opening_quote() {
        let j = compile_json("box wid 1\n  \"oops\n");

        assert!(j.contains("\"kind\":\"unterminated_string\""), "{j}");
        assert!(j.contains("\"line\":2"), "{j}");
        assert!(j.contains("\"col\":3"), "{j}");
    }

    #[test]
    fn json_eval_errors_get_structured_locations_when_possible() {
        let label = compile_json("box at A\n");
        assert!(label.contains("\"kind\":\"unknown_label\""), "{label}");
        assert!(label.contains("\"line\":1"), "{label}");
        assert!(label.contains("\"col\":8"), "{label}");
        assert!(label.contains("\"found\":\"A\""), "{label}");

        let ordinal = compile_json("box\nbox at 3rd box\n");
        assert!(
            ordinal.contains("\"kind\":\"ordinal_out_of_range\""),
            "{ordinal}"
        );
        assert!(ordinal.contains("\"line\":2"), "{ordinal}");
        assert!(ordinal.contains("\"col\":8"), "{ordinal}");
        assert!(ordinal.contains("\"found\":\"3\""), "{ordinal}");
        assert!(ordinal.contains("\"expected\":\"1..1\""), "{ordinal}");
    }

    #[test]
    fn json_eval_error_inside_include_names_the_file() {
        // #197: the failing reference's own tokens carry the span (and its
        // include provenance) — no re-lexing of the user source involved.
        let dir = std::env::temp_dir().join(format!("rpic_eval_incl_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("inc-eval.pic"), "# comment\nbox at Missing\n").unwrap();
        let j = compile_json_in_dir("circle\ncopy \"inc-eval.pic\"", Some(dir.as_path()));
        let _ = std::fs::remove_dir_all(&dir);
        assert!(j.contains("\"error\":\"unknown label `Missing`\""), "{j}");
        assert!(j.contains("\"kind\":\"unknown_label\""), "{j}");
        assert!(j.contains("\"file\":\"inc-eval.pic\""), "{j}");
        assert!(j.contains("\"line\":2"), "{j}"); // include-relative
        assert!(j.contains("\"col\":8"), "{j}");
    }

    #[test]
    fn json_deferred_parse_errors_keep_their_structure() {
        // #197: a parse error inside a dynamically-executed body used to be
        // flattened to kind "eval" with null position/found/hint.
        let j = compile_json("x = 1\nif x then { bxo }\n");
        assert!(j.contains("\"kind\":\"expected_token\""), "{j}");
        assert!(j.contains("\"line\":2"), "{j}");
        assert!(j.contains("\"col\":13"), "{j}");
        assert!(j.contains("\"found\":\"`bxo`\""), "{j}");
        assert!(j.contains("\"hint\":\"did you mean `box`?\""), "{j}");

        let f = compile_json("for i = 1 to 2 do { bxo }\n");
        assert!(f.contains("\"kind\":\"expected_token\""), "{f}");
        assert!(f.contains("\"hint\":\"did you mean `box`?\""), "{f}");
    }

    #[test]
    fn json_success_bundle_reports_warnings() {
        let attr = compile_json("box \"a\" dashd\n");
        assert!(attr.contains("\"warnings\":[{"), "{attr}");
        assert!(attr.contains("\"kind\":\"ignored_attribute\""), "{attr}");
        assert!(attr.contains("\"found\":\"dashd\""), "{attr}");
        assert!(
            attr.contains("\"hint\":\"did you mean `dashed`?\""),
            "{attr}"
        );

        let anim = compile_json("box\nanimate 1st box with \"zoom\"\n");
        assert!(
            anim.contains("\"kind\":\"unknown_animation_effect\""),
            "{anim}"
        );
        assert!(anim.contains("\"found\":\"zoom\""), "{anim}");
        assert!(anim.contains("\"line\":2"), "{anim}");
    }

    #[test]
    fn circuits_library_compiles_and_draws() {
        let src = format!(
            "{}\nA:(0,0); B:(1.6,0); C:(3,0)\nresistor(A,B)\ncapacitor(A,B)\ninductor(A,B)\n\
             diode(A,B)\nbattery(A,B)\nground(A)\ndot(A)\nwire(A,B)\n\
             and_gate(C)\nor_gate(C)\nnand_gate(C)\nnor_gate(C)\nxor_gate(C)\n\
             xnor_gate(C)\nbuffer(C)\nnot_gate(C)\n\
             opamp(C)\nnpn(C)\npnp(C)\nac_source(A,B)\nswitch(A,B)\n\
             potentiometer(A,B)\ntransformer(C)\n\
             nmos(C)\npmos(C)\ncurrent_source(A,B)\nvsource_ctrl(A,B)\n\
             isource_ctrl(A,B)\nled(A,B)\nphotodiode(A,B)\nzener(A,B)\n\
             clabel(A,\"x\")\nterminal(A)\nvdd(A)\nantenna(A)\ncurrent(A,B)\n\
             voltage(A,B)\nlamp(A,B)\nfuse(A,B)\n\
             voltmeter(A,B)\nammeter(A,B)\nohmmeter(A,B)\nmeter(A,B,\"X\")\n\
             crystal(A,B)\nspeaker(A,B)\nhop(A,B)\nspdt(A,B,C)\n\
             iec_resistor(A,B)\nvoltage_source(A,B)\npushbutton(A,B)\nrelay(A,B)\n\
             thermistor(A,B)\nmotor(A,B)\ngenerator(A,B)\nbell(A,B)\n\
             ieee_and(C)\nieee_or(C)\nieee_xor(C)\nieee_buf(C)\niecgate(C,\"x\")\n\
             varistor(A,B)\ntline(A,B)\nbus(A,B)\n\
             polcap(A,B)\nvarcap(A,B)\nvarind(A,B)\nschottky(A,B)\nldr(A,B)\n\
             spark_gap(A,B)\nchassis_ground(A)\nsignal_ground(A)\n\
             njfet(C)\npjfet(C)\nphototransistor(C)\nic_block(C,\"x\")\nmux(C)\n\
             solar_cell(A,B)\nmicrophone(A,B)\nthermocouple(A,B)",
            CIRCUITS
        );
        let d = compile(&src).expect("circuit library should compile");
        assert!(!d.shapes.is_empty());
    }
}