Skip to main content

rpic_core/
lib.rs

1//! rpic-core — engine for the `pic` picture-drawing language.
2//!
3//! Pipeline: source → [`lexer`] → [`parser`] → [`ast`] → [`eval`] → placed
4//! primitives ([`ir`]) → render backends ([`svg`], later PNG/PDF). This crate
5//! is pure (no file I/O); the CLI and WASM wrappers drive it.
6//!
7//! Note: [`eval`] is the pic-language *interpreter* — a safe walker over a typed
8//! expression/geometry tree. It executes no arbitrary code.
9
10pub mod ast;
11pub mod eval;
12pub mod geom;
13pub mod ir;
14pub mod lexer;
15pub mod parser;
16pub mod svg;
17pub mod token;
18
19pub use eval::{EvalError, eval};
20pub use ir::Drawing;
21pub use lexer::{LexError, lex};
22pub use parser::{ParseError, parse, parse_in_dir};
23pub use svg::to_svg;
24pub use token::Token;
25
26/// Bundled native circuit-element library (the `define` dialect). Prepend it to
27/// source to use `resistor`, `capacitor`, … See `std/circuits.pic`.
28pub const CIRCUITS: &str = include_str!("std/circuits.pic");
29
30/// Compile pic source into a placed-primitive [`Drawing`].
31pub fn compile(src: &str) -> Result<Drawing, String> {
32    compile_in_dir(src, None)
33}
34
35/// Compile pic source, resolving `copy "file"` includes relative to `base`.
36pub fn compile_in_dir(src: &str, base: Option<&std::path::Path>) -> Result<Drawing, String> {
37    let picture = parser::parse_in_dir(src, base).map_err(|e| e.to_string())?;
38    eval(&picture).map_err(|e| e.to_string())
39}
40
41/// Compile pic source directly to an SVG string.
42pub fn render_svg(src: &str) -> Result<String, String> {
43    Ok(to_svg(&compile(src)?))
44}
45
46/// Render pic source to SVG, resolving `copy "file"` includes relative to `base`.
47pub fn render_svg_in_dir(src: &str, base: Option<&std::path::Path>) -> Result<String, String> {
48    Ok(to_svg(&compile_in_dir(src, base)?))
49}
50
51/// Build the JSON animation manifest array (`[{id,effect,start,duration},…]`)
52/// for an already-compiled drawing.
53pub fn animations_json(d: &Drawing) -> String {
54    let mut s = String::from("[");
55    for (i, a) in d.anims.iter().enumerate() {
56        if i > 0 {
57            s.push(',');
58        }
59        s.push_str(&format!(
60            "{{\"id\":\"s{}\",\"effect\":\"{}\",\"start\":{},\"duration\":{}}}",
61            a.shape,
62            json_str(&a.effect),
63            a.start,
64            a.duration
65        ));
66    }
67    s.push(']');
68    s
69}
70
71/// Build the JSON diagnostic array emitted by pic `print` statements.
72pub fn diagnostics_json(d: &Drawing) -> String {
73    let mut s = String::from("[");
74    for (i, line) in d.diagnostics.iter().enumerate() {
75        if i > 0 {
76            s.push(',');
77        }
78        s.push('"');
79        s.push_str(&json_str(line));
80        s.push('"');
81    }
82    s.push(']');
83    s
84}
85
86/// Compile to a single JSON object `{ "svg": "...", "animations": [...],
87/// "diagnostics": [...] }`, or `{ "error": "..." }` on failure. This is the
88/// entry point the WASM wrapper and browser playground consume.
89pub fn compile_json(src: &str) -> String {
90    match compile(src) {
91        Ok(d) => format!(
92            "{{\"svg\":\"{}\",\"animations\":{},\"diagnostics\":{}}}",
93            json_str(&to_svg(&d)),
94            animations_json(&d),
95            diagnostics_json(&d)
96        ),
97        Err(e) => format!("{{\"error\":\"{}\"}}", json_str(&e)),
98    }
99}
100
101/// Escape a string for embedding inside a JSON string literal.
102fn json_str(s: &str) -> String {
103    let mut o = String::with_capacity(s.len() + 8);
104    for c in s.chars() {
105        match c {
106            '"' => o.push_str("\\\""),
107            '\\' => o.push_str("\\\\"),
108            '\n' => o.push_str("\\n"),
109            '\r' => o.push_str("\\r"),
110            '\t' => o.push_str("\\t"),
111            c if (c as u32) < 0x20 => o.push_str(&format!("\\u{:04x}", c as u32)),
112            c => o.push(c),
113        }
114    }
115    o
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    #[test]
123    fn json_bundles_svg_and_animations() {
124        let j = compile_json("box\nanimate last box with \"fade\"");
125        assert!(j.starts_with("{\"svg\":\"<svg"));
126        assert!(j.contains("<g id=\\\"s0\\\">")); // stable id, JSON-escaped
127        assert!(j.contains("\"animations\":[{\"id\":\"s0\",\"effect\":\"fade\""));
128        assert!(j.contains("\"diagnostics\":[]"));
129    }
130
131    #[test]
132    fn json_reports_errors() {
133        let j = compile_json("copy \"oops\"");
134        assert!(j.contains("\"error\""));
135    }
136
137    #[test]
138    fn json_reports_print_diagnostics() {
139        let j = compile_json("print \"hi\"\nprint 2+3");
140        assert!(j.contains("\"diagnostics\":[\"hi\",\"5\"]"));
141    }
142
143    #[test]
144    fn circuits_library_compiles_and_draws() {
145        let src = format!(
146            "{}\nA:(0,0); B:(1.6,0); C:(3,0)\nresistor(A,B)\ncapacitor(A,B)\ninductor(A,B)\n\
147             diode(A,B)\nbattery(A,B)\nground(A)\ndot(A)\nwire(A,B)\n\
148             and_gate(C)\nor_gate(C)\nnand_gate(C)\nnor_gate(C)\nxor_gate(C)\n\
149             xnor_gate(C)\nbuffer(C)\nnot_gate(C)\n\
150             opamp(C)\nnpn(C)\npnp(C)\nac_source(A,B)\nswitch(A,B)\n\
151             potentiometer(A,B)\ntransformer(C)\n\
152             nmos(C)\npmos(C)\ncurrent_source(A,B)\nvsource_ctrl(A,B)\n\
153             isource_ctrl(A,B)\nled(A,B)\nphotodiode(A,B)\nzener(A,B)\n\
154             clabel(A,\"x\")\nterminal(A)\nvdd(A)\nantenna(A)\ncurrent(A,B)\n\
155             voltage(A,B)\nlamp(A,B)\nfuse(A,B)\n\
156             voltmeter(A,B)\nammeter(A,B)\nohmmeter(A,B)\nmeter(A,B,\"X\")\n\
157             crystal(A,B)\nspeaker(A,B)\nhop(A,B)\nspdt(A,B,C)\n\
158             iec_resistor(A,B)\nvoltage_source(A,B)\npushbutton(A,B)\nrelay(A,B)\n\
159             thermistor(A,B)\nmotor(A,B)\ngenerator(A,B)\nbell(A,B)\n\
160             ieee_and(C)\nieee_or(C)\nieee_xor(C)\nieee_buf(C)\niecgate(C,\"x\")\n\
161             varistor(A,B)\ntline(A,B)\nbus(A,B)\n\
162             polcap(A,B)\nvarcap(A,B)\nvarind(A,B)\nschottky(A,B)\nldr(A,B)\n\
163             spark_gap(A,B)\nchassis_ground(A)\nsignal_ground(A)\n\
164             njfet(C)\npjfet(C)\nphototransistor(C)\nic_block(C,\"x\")\nmux(C)\n\
165             solar_cell(A,B)\nmicrophone(A,B)\nthermocouple(A,B)",
166            CIRCUITS
167        );
168        let d = compile(&src).expect("circuit library should compile");
169        assert!(!d.shapes.is_empty());
170    }
171}