rpic-core 0.10.0

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
//! Abstract syntax tree for the pic language.
//!
//! Mirrors the structure of dpic's `grammar.txt`. The parser populates the
//! drawing core (pictures, primitives + attributes, positions, expressions,
//! blocks, assignments) plus the control constructs (`if`/`for`/`define`/
//! `print`/`exec`) used by the evaluator and macro preprocessor.

use crate::diagnostic::Span;
use crate::lexer::Spanned;
use crate::token::{
    Arrow, Color, Corner, Dir, EnvVar, Func1, Func2, LineType, Param, Prim, TextPos,
};

/// Macro definitions (name → body tokens), carried from parse to eval so that
/// `if`/`for` bodies can be expanded lazily along the executed path.
pub type Macros = std::collections::HashMap<String, Vec<Spanned>>;

/// A deferred block of statements, kept as raw tokens until the branch/iteration
/// that contains it actually runs (so dead branches and recursive macro calls
/// are never parsed). Parsed on demand by the evaluator.
pub type Body = Vec<Spanned>;

/// A complete picture: optional `.PS <w> <h>` dimensions plus a list of elements.
#[derive(Debug, Clone, PartialEq)]
pub struct Picture {
    pub width: Option<Expr>,
    pub height: Option<Expr>,
    pub stmts: Vec<Stmt>,
    pub macros: Macros,
    /// Filesystem context for `copy "file"` includes (directory + policy);
    /// carried so eval-time deferred parsing resolves includes the same way.
    pub includes: IncludeCtx,
}

/// Policy for `copy "file"` filesystem includes. The default matches the CLI:
/// full access, absolute paths allowed. Embedders compiling untrusted source
/// should pick a restrictive policy. The embedded `copy "circuits"` library
/// is always available — it never touches the filesystem.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum IncludePolicy {
    /// Resolve like the CLI: absolute paths allowed, no fence. (Default.)
    #[default]
    Unrestricted,
    /// Only files inside the base directory (canonicalized prefix check, so
    /// `..` and symlink escapes are rejected); absolute paths are errors.
    SandboxedToBase,
    /// No filesystem includes at all (the wasm behavior everywhere).
    Deny,
}

/// Where and how `copy "file"` includes resolve: the current directory (the
/// including file's own dir, which varies as includes nest) plus the fixed
/// [`IncludePolicy`] and its canonicalized fence root.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct IncludeCtx {
    /// Directory relative includes resolve against; `None` when parsing has
    /// no filesystem context (WASM/bindings without `base`).
    pub dir: Option<std::path::PathBuf>,
    /// Policy applied to every filesystem include in this compilation.
    pub policy: IncludePolicy,
    /// Canonicalized sandbox root. Set when the policy is `SandboxedToBase`
    /// and the base directory canonicalizes; `None` under that policy means
    /// every filesystem include is denied (a fence that failed to resolve
    /// must fail closed).
    pub(crate) fence: Option<std::path::PathBuf>,
}

impl IncludeCtx {
    /// The CLI behavior: resolve against `dir`, no restrictions.
    pub fn unrestricted(dir: Option<std::path::PathBuf>) -> Self {
        Self {
            dir,
            policy: IncludePolicy::Unrestricted,
            fence: None,
        }
    }

    /// Build a context for `dir` under `policy`, canonicalizing the fence
    /// root for `SandboxedToBase` (fails closed if it cannot resolve).
    pub fn with_policy(dir: Option<std::path::PathBuf>, policy: IncludePolicy) -> Self {
        let fence = match policy {
            IncludePolicy::SandboxedToBase => {
                dir.as_deref().and_then(|d| std::fs::canonicalize(d).ok())
            }
            _ => None,
        };
        Self { dir, policy, fence }
    }

    /// A nested include's context: its own directory, same policy and fence.
    pub(crate) fn child(&self, dir: Option<std::path::PathBuf>) -> Self {
        Self {
            dir,
            policy: self.policy,
            fence: self.fence.clone(),
        }
    }
}

/// A label with an optional `[subscript]` suffix.
#[derive(Debug, Clone, PartialEq)]
pub struct Label {
    pub name: String,
    pub subscript: Option<Expr>,
}

/// A top-level element.
#[derive(Debug, Clone, PartialEq)]
pub enum Stmt {
    /// A drawn object, optionally labelled (`Start: box …`).
    Object {
        label: Option<Label>,
        object: Object,
    },
    /// `Label: position` — names a point without drawing.
    Place { label: Label, pos: Position },
    /// One or more comma-separated assignments.
    Assign(Vec<Assignment>),
    /// A bare direction change (`up` / `down` / `left` / `right`).
    Direction(Dir),
    /// `{ … }` grouping block (local scope, no bounding object).
    Group(Vec<Stmt>),
    /// rpic animation directive (extension; see [`Animate`]).
    // Boxed: `Animate` carries several `Place`s and is far larger than the
    // other variants (clippy::large_enum_variant).
    Animate(Box<Animate>),
    /// rpic extension: `animate scroll` — a timeline-level hint that the host
    /// should scrub the animation on scroll instead of autoplaying.
    AnimateScroll,
    /// rpic extension: `draggable <place> [inertia] [bounds <place>] [x|y]` —
    /// mark an object grabbable in the browser (GSAP Draggable). Interaction,
    /// not a timeline effect, so it is its own directive.
    Draggable(Draggable),
    /// rpic extension: `class <place> "name"` — append a CSS class to an
    /// already-drawn object's shape group (labels and ordinals both work).
    Class { target: Place, class: StringExpr },
    /// rpic extension: `canvas from <pos> to <pos>` — fix the output page to
    /// the rectangle spanned by the two corners, independent of content, so
    /// the viewBox stays stable while objects move (visual editors).
    Canvas { from: Position, to: Position },
    /// `if <cond> then { … } [else { … }]`. Bodies are deferred raw tokens.
    If {
        cond: Expr,
        then_body: Body,
        else_body: Option<Body>,
    },
    /// `for v = from to to [by [*] step] do { … }`. Body is deferred raw tokens.
    For {
        var: String,
        subscript: Option<Expr>,
        from: Expr,
        to: Expr,
        by: Expr,
        /// `by *` multiplies instead of adds.
        mult: bool,
        body: Body,
    },
    /// `print …` (evaluated for diagnostics; no drawing effect).
    Print(PrintItem),
    /// `exec <string>` — evaluate generated pic source in the current state.
    Exec {
        command: StringExpr,
        arg_frame: Option<Vec<Vec<Spanned>>>,
    },
    /// `reset` (all) or `reset a, b, …` — restore environment variables.
    Reset(Vec<EnvVar>),
}

#[derive(Debug, Clone, PartialEq)]
pub enum PrintItem {
    Str(StringExpr),
    Expr(Expr),
}

/// A `draggable` interaction directive (rpic extension).
#[derive(Debug, Clone, PartialEq)]
pub struct Draggable {
    pub target: Place,
    /// `inertia` — throw with momentum (GSAP InertiaPlugin).
    pub inertia: bool,
    /// `bounds <place>` — constrain dragging to another object's box.
    pub bounds: Option<Place>,
    /// `x` / `y` — lock dragging to one axis (`None` = free).
    pub axis: Option<DragAxis>,
}

/// Axis lock for a `draggable` directive.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DragAxis {
    X,
    Y,
}

/// Granularity of the `type` effect's staggered reveal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TypeUnit {
    /// One tspan per character (default).
    Char,
    /// One tspan per whitespace-separated word.
    Word,
}

/// `animate <target> with "<effect>" [along <path>] [to <colour>] [for <dur>]
///   [at <t> | after <ref>] [delay <d>] [repeat <n>] [yoyo] [ease "<name>"]`.
#[derive(Debug, Clone, PartialEq)]
pub struct Animate {
    pub target: Place,
    pub effect: StringExpr,
    pub effect_span: Option<Span>,
    pub duration: Option<Expr>,
    pub timing: Timing,
    pub delay: Option<Expr>,
    /// Object whose geometry the `move` effect follows (GSAP MotionPath).
    pub along: Option<Place>,
    /// Number of repeats after the first play (GSAP `repeat`): `-1` loops
    /// forever, `0`/absent plays once.
    pub repeat: Option<Expr>,
    /// Alternate direction on each repeat (GSAP `yoyo`).
    pub yoyo: bool,
    /// GSAP easing name overriding the per-effect default (e.g. `"elastic.out"`).
    pub ease: Option<StringExpr>,
    /// Target colour for the `highlight` effect (`to <colour>`); any rpic
    /// colour form (name, `rgb()`, `0xRRGGBB`).
    pub color: Option<StringExpr>,
    /// When the target is a block, fan the effect across its children with this
    /// per-child start offset in seconds (GSAP-style `stagger`).
    pub stagger: Option<Expr>,
    /// Play the effect as an exit (reverse: `.to()` the hidden state) rather
    /// than an entrance.
    pub out: bool,
    /// Direction the `slide` effect enters from (`from left`, …).
    pub slide_from: Option<Dir>,
    /// Target object the `morph` effect morphs into (`into B`).
    pub morph_into: Option<Place>,
    /// Split granularity for the `type` effect (`by word` / `by char`); `None`
    /// defaults to `Char`.
    pub type_unit: Option<TypeUnit>,
    /// Custom scramble charset for the `scramble` effect (`by "01"`); `None`
    /// defaults to the plugin's `upperCase`.
    pub scramble_chars: Option<StringExpr>,
    /// Oscillation count for the `wiggle` effect (`wiggles <n>`); `None`
    /// defaults to a few.
    pub wiggles: Option<Expr>,
    /// Start of the revealed segment for the `draw` effect, as a fraction of the
    /// stroke (`from 40%` → `0.4`); `None` starts at the beginning.
    pub draw_from: Option<Expr>,
    /// End of the revealed segment for the `draw` effect, as a fraction of the
    /// stroke (`to 60%` → `0.6`); `None` reaches the end.
    pub draw_to: Option<Expr>,
}

/// When an animation starts.
#[derive(Debug, Clone, PartialEq)]
pub enum Timing {
    /// After the previously declared animation ends (default).
    Sequential,
    /// At an absolute time (seconds).
    At(Expr),
    /// After the named object's animation ends.
    After(Place),
}

/// A single assignment `target op value`.
#[derive(Debug, Clone, PartialEq)]
pub struct Assignment {
    pub target: AssignTarget,
    pub op: AssignOp,
    pub value: Expr,
}

#[derive(Debug, Clone, PartialEq)]
pub enum AssignTarget {
    Var(String, Option<Expr>),
    Env(EnvVar),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AssignOp {
    Set,      // =
    ColonSet, // :=
    Add,      // +=
    Sub,      // -=
    Mul,      // *=
    Div,      // /=
    Rem,      // %=
}

/// A drawable object: a base plus a chain of attributes.
#[derive(Debug, Clone, PartialEq)]
pub struct Object {
    pub kind: ObjectKind,
    pub attrs: Vec<Attr>,
    /// Span of the statement's leading token (for per-object geometry export
    /// and future diagnostics).
    pub span: Option<Span>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum ObjectKind {
    Primitive(Prim),
    Block(Vec<Stmt>),
    /// `[]` empty-block reference.
    Empty,
    /// A bare quoted string places a text-only object.
    Text,
    /// rpic extension: a curly brace annotation between two points.
    Brace,
    /// rpic extension: a junction dot — a tiny solid circle (`dotrad`).
    Dot,
    /// `continue` — extend the previous line with another segment.
    Continue,
}

/// An object attribute (applied left to right).
#[derive(Debug, Clone, PartialEq)]
pub enum Attr {
    Dim(DimKind, Expr),
    Direction(Dir, Option<Expr>),
    /// A bare distance with no direction word (e.g. `move 1`): advance by this
    /// much along the prevailing direction.
    Dist(Expr, Option<Span>),
    /// `spline <expr> …`: the expression right after `spline` is a spline
    /// tension parameter (dpic semantics), NOT a distance.
    SplineTension(Expr),
    LineStyle(LineType, Option<Expr>),
    Chop(Option<Expr>),
    Fill(Option<Expr>),
    Arrowhead(Arrow, Option<Expr>),
    Then,
    Cw,
    Ccw,
    Same,
    Continue,
    Text(StringExpr),
    /// rpic extension: size a closed object to text declared before `fit`.
    Fit,
    /// rpic extension: hatch-filled closed regions.
    Hatch(HatchKind),
    /// rpic extension: hatch line angle in degrees.
    HatchAngle(Expr),
    /// rpic extension: hatch line spacing in pic units.
    HatchSep(Expr),
    /// rpic extension: hatch line width in points.
    HatchWidth(Expr),
    /// rpic extension: hatch line color (with its source span for diagnostics).
    HatchColor(StringExpr, Option<Span>),
    /// rpic extension: fill opacity, 0 = transparent and 1 = opaque.
    Opacity(Expr),
    /// rpic extension: two-stop linear gradient fill (`from`, `to` colors,
    /// each with its source span for diagnostics).
    Gradient(StringExpr, Option<Span>, StringExpr, Option<Span>),
    /// rpic extension: gradient angle in degrees, pic coordinates.
    GradientAngle(Expr),
    /// rpic extension: close a `line` path into a polygon.
    Close,
    TextPos(TextPos),
    From(Position),
    To(Position),
    At(Position),
    By(Position),
    With {
        anchor: WithAnchor,
        at: Position,
    },
    /// A colour attribute (`outlined`/`shaded`/`color`) with its source span.
    Color(Color, StringExpr, Option<Span>),
    /// rpic extension: draw this object below another already-placed object.
    Behind(Place),
    /// rpic extension: CSS class hook attached to this object's shape group.
    Class(StringExpr),
    /// rpic extension (pikchr-flavoured): a lighter stroke — sets the object's
    /// line thickness to ⅔ of the current `linethick` (no value; the sugar for
    /// `thick (linethick*2/3)`, mirroring `thick <n>`).
    Thin,
    /// rpic extension: bold face for the preceding text string.
    Bold,
    /// rpic extension: italic face for the preceding text string.
    Italic,
    /// rpic extension: monospace family for the preceding text string.
    Mono,
    /// rpic extension: font family for the preceding text string.
    Font(StringExpr),
    /// rpic extension: font size in points for the preceding text string.
    FontSize(Expr),
    /// rpic extension: rotation in degrees (CCW) for the preceding string.
    Rotated(Expr),
    /// rpic extension: align the preceding string to the host segment's angle
    /// (pikchr `aligned`). Only linear objects have a segment; elsewhere inert.
    Aligned,
    /// rpic extension: pikchr `big`/`small` text size (sugar over `fontsize`);
    /// `true` = big (1.5×), `false` = small (0.7×) of the classic 11 pt.
    Sized(bool),
    /// rpic extension: relative cusp position for a `brace` object.
    BracePos(Expr),
    /// rpic extension: extra outward spacing between a `brace` cusp and label.
    BraceLabelOffset(Expr),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HatchKind {
    Single,
    Cross,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DimKind {
    Ht,
    Wid,
    Rad,
    Diam,
    Thick,
    Scaled,
}

/// The reference point on an object used by `with … at …`.
#[derive(Debug, Clone, PartialEq)]
pub enum WithAnchor {
    Corner(Corner),
    Pair(Expr, Expr),
    Place(Place),
    Plain,
}

/// A position (point) expression. Positions support full vector arithmetic
/// (dpic): `p + q`, `p - q`, `p * s`, `p / s` with the usual precedence.
#[derive(Debug, Clone, PartialEq)]
pub enum Position {
    /// Explicit `x , y`.
    Pair(Expr, Expr),
    /// A bare location.
    Place(Location),
    /// `frac [of the way] between A and B`.
    Between {
        frac: Box<Expr>,
        a: Box<Position>,
        b: Box<Position>,
        of_the_way: bool,
    },
    /// `p + q` / `p - q`.
    Sum(Sign, Box<Position>, Box<Position>),
    /// `p * s` (or `p / s` when `div`), scaling a position by a scalar.
    Scale(Box<Position>, Expr, bool),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Sign {
    Plus,
    Minus,
}

/// A point-valued location.
#[derive(Debug, Clone, PartialEq)]
pub enum Location {
    Place(Place),
    /// `( position )`.
    Paren(Box<Position>),
    /// `( position , position )` — x of the first, y of the second.
    ParenPair(Box<Position>, Box<Position>),
}

/// A named place in the drawing.
#[derive(Debug, Clone, PartialEq)]
pub enum Place {
    /// A label, optionally subscripted.
    Name {
        name: String,
        subscript: Option<Box<Expr>>,
        /// Span of the reference (for eval-phase diagnostics).
        span: Option<Span>,
    },
    /// `last box`, `2nd last circle`, etc.
    Nth {
        count: Nth,
        obj: PrimObj,
        /// Span of the reference (for eval-phase diagnostics).
        span: Option<Span>,
    },
    /// `place . corner` (e.g. `A.ne`).
    Corner(Box<Place>, Corner),
    /// `corner of place` / `corner place` (e.g. `top of A`).
    CornerOf(Corner, Box<Place>),
    /// `place . place` (block sub-label, e.g. `B.A`).
    Member(Box<Place>, Box<Place>),
    Here,
}

#[derive(Debug, Clone, PartialEq)]
pub enum Nth {
    Last,
    /// `count`-th object; `from_last` true for `… last`.
    Count(Box<Expr>, bool),
}

#[derive(Debug, Clone, PartialEq)]
pub enum PrimObj {
    Prim(Prim),
    Brace,
    Block,
    Str(String),
    EmptyBrack,
    /// Untyped `last` / `Nth last` — the most recent object of any kind
    /// (e.g. `last.c`, `2nd last.n`). Used when no type keyword follows.
    Any,
}

/// A string-valued expression.
#[derive(Debug, Clone, PartialEq)]
pub enum StringExpr {
    Lit(String),
    Concat(Box<StringExpr>, Box<StringExpr>),
    Sprintf(Box<StringExpr>, Vec<Expr>),
    /// rpic extension: `rgb(r,g,b)` colour literal (components 0–255);
    /// evaluates to `#rrggbb`.
    Rgb(Box<[Expr; 3]>),
    /// rpic extension: a numeric colour in colour position (`shaded
    /// 0x1b5e20`, pikchr-style); evaluates to `#rrggbb`.
    ColorNum(Box<Expr>),
    /// dpic SVG-backend helper. rpic does not emit backend preamble text, so
    /// this evaluates to a harmless empty string.
    SvgFont(Vec<Expr>),
    Arg(u32),
}

/// A scalar (numeric / boolean) expression. pic treats booleans as numbers.
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
    Num(f64),
    /// A string operand, valid only as an operand of `==`/`!=` (pic compares
    /// strings for equality, e.g. the `"$1"==""` default-argument idiom).
    Str(StringExpr),
    /// Comma-separated array subscript, valid only inside `name[...]`.
    Index(Vec<Expr>),
    Var(String, Option<Box<Expr>>),
    Env(EnvVar),
    Unary(UnOp, Box<Expr>),
    Bin(BinOp, Box<Expr>, Box<Expr>),
    Func1(Func1, Box<Expr>),
    Func2(Func2, Box<Expr>, Box<Expr>),
    Rand(Option<Box<Expr>>),
    /// `( name = expr )` — assign and yield the assigned value.
    Assign(String, Option<Box<Expr>>, Box<Expr>),
    DotX(Location),
    DotY(Location),
    PlaceAttr(Place, Param),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnOp {
    Neg,
    Pos,
    Not,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinOp {
    Add,
    Sub,
    Mul,
    Div,
    Mod,
    Pow,
    Eq,
    Ne,
    Lt,
    Le,
    Gt,
    Ge,
    And,
    Or,
}