Skip to main content

rpic_core/
parser.rs

1//! Recursive-descent parser for the pic drawing core.
2//!
3//! Follows dpic's `grammar.txt`. Implemented: pictures (`.PS … .PE`), primitives
4//! with the full attribute set, positions (pairs, places, corners, ordinals,
5//! `between`, `± shifts`), expressions with proper precedence, `[ … ]` blocks,
6//! `{ … }` groups, labels, assignments, macros, includes, conditionals, loops,
7//! `print` and `exec`.
8
9use crate::ast::*;
10use crate::diagnostic::{Diagnostic, Span};
11use crate::lexer::{LexError, Spanned, lex, lex_named};
12use crate::token::*;
13
14/// A parse error with source location. `file` (via [`ParseError::span`]) is
15/// `None` for the user's own input, or the `copy` include / library name the
16/// position is relative to.
17#[derive(Debug, Clone, PartialEq)]
18pub struct ParseError {
19    pub msg: String,
20    pub line: u32,
21    pub col: u32,
22    pub end_col: u32,
23    file: Option<std::sync::Arc<str>>,
24    detail: Box<ParseErrorDetail>,
25}
26
27#[derive(Debug, Clone, PartialEq)]
28struct ParseErrorDetail {
29    kind: String,
30    found: Option<String>,
31    expected: Option<String>,
32    hint: Option<String>,
33}
34
35impl std::fmt::Display for ParseError {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        match &self.file {
38            Some(file) => write!(f, "{}:{}:{}: {}", file, self.line, self.col, self.msg),
39            None => write!(f, "{}:{}: {}", self.line, self.col, self.msg),
40        }
41    }
42}
43
44impl ParseError {
45    fn new(msg: impl Into<String>, span: Span) -> Self {
46        Self {
47            msg: msg.into(),
48            line: span.line,
49            col: span.col,
50            end_col: span.end_col,
51            file: span.file,
52            detail: Box::new(ParseErrorDetail {
53                kind: "parse".into(),
54                found: None,
55                expected: None,
56                hint: None,
57            }),
58        }
59    }
60
61    fn expected(expected: impl Into<String>, found: impl Into<String>, span: Span) -> Self {
62        let expected = expected.into();
63        let found = found.into();
64        Self {
65            msg: format!("expected {expected}, found {found}"),
66            line: span.line,
67            col: span.col,
68            end_col: span.end_col,
69            file: span.file,
70            detail: Box::new(ParseErrorDetail {
71                kind: "expected_token".into(),
72                found: Some(found),
73                expected: Some(expected),
74                hint: None,
75            }),
76        }
77    }
78
79    /// Override the diagnostic kind (crate-internal builder).
80    pub(crate) fn with_kind(mut self, kind: impl Into<String>) -> Self {
81        self.detail.kind = kind.into();
82        self
83    }
84
85    /// The error's source span, including which source it refers to.
86    pub fn span(&self) -> Span {
87        Span::new(self.line, self.col, self.end_col).in_file(self.file.clone())
88    }
89
90    pub fn diagnostic(&self) -> Diagnostic {
91        let mut d = Diagnostic::new(self.detail.kind.clone(), self.msg.clone()).at(self.span());
92        d.found = self.detail.found.clone();
93        d.expected = self.detail.expected.clone();
94        d.hint = self.detail.hint.clone();
95        d
96    }
97}
98
99impl From<LexError> for ParseError {
100    fn from(e: LexError) -> Self {
101        ParseError {
102            msg: e.msg,
103            line: e.line,
104            col: e.col,
105            end_col: e.end_col,
106            file: e.file,
107            detail: Box::new(ParseErrorDetail {
108                kind: e.kind,
109                found: None,
110                expected: None,
111                hint: None,
112            }),
113        }
114    }
115}
116
117/// Parse a full source string into a [`Picture`] with no filesystem context.
118/// `copy "file"` includes are unavailable (they require a base directory).
119pub fn parse(src: &str) -> Result<Picture, ParseError> {
120    parse_in_dir(src, None)
121}
122
123/// Parse pic source, resolving `copy "file"` includes relative to `base`
124/// with the default (unrestricted) include policy.
125pub fn parse_in_dir(src: &str, base: Option<&Path>) -> Result<Picture, ParseError> {
126    parse_with_prelude(
127        src,
128        IncludeCtx::unrestricted(base.map(|p| p.to_path_buf())),
129        false,
130        false,
131    )
132}
133
134/// Parse pic source with optional preludes: `circuits` loads the embedded
135/// circuit-element library and `texlabels` injects `texlabels = 1` — the
136/// library equivalents of the CLI `-c` / `-t` flags. Each prelude is lexed
137/// as its own named source unit (not text glued in front of `src`), so every
138/// diagnostic position stays relative to the source it belongs to: the user's
139/// own input reports user lines, and library problems name the library.
140pub fn parse_with_prelude(
141    src: &str,
142    includes: IncludeCtx,
143    circuits: bool,
144    texlabels: bool,
145) -> Result<Picture, ParseError> {
146    let mut toks: Vec<Spanned> = Vec::new();
147    if circuits {
148        splice_unit(&mut toks, lex_named(crate::CIRCUITS, "circuits")?);
149    }
150    if texlabels {
151        // Initializer only — the source stays sovereign (`texlabels = 0` wins).
152        splice_unit(&mut toks, lex_named("texlabels = 1\n", "<texlabels>")?);
153    }
154    let src = strip_backend_preamble(src);
155    toks.extend(lex(&src)?);
156    let (toks, macros) = preprocess(toks, &includes)?;
157    let mut pic = Parser::new(toks).parse_picture()?;
158    pic.macros = macros;
159    pic.includes = includes;
160    Ok(pic)
161}
162
163/// Append a lexed prelude unit ahead of the tokens that follow: drop its
164/// `Eof` and guarantee a trailing `Newline` so the units stay statement-
165/// separated (equivalent to the `\n` the old string-prepending inserted).
166fn splice_unit(out: &mut Vec<Spanned>, mut unit: Vec<Spanned>) {
167    if matches!(unit.last().map(|s| &s.tok), Some(Token::Eof)) {
168        unit.pop();
169    }
170    if !matches!(unit.last().map(|s| &s.tok), Some(Token::Newline)) {
171        let (line, file) = unit
172            .last()
173            .map(|s| (s.line, s.file.clone()))
174            .unwrap_or((1, None));
175        unit.push(Spanned::new(Token::Newline, line, 1).with_file(file));
176    }
177    out.extend(unit);
178}
179
180/// Parse a deferred body (the raw tokens of an `if`/`for` block) with the macro
181/// table in scope, expanding macro calls (and `copy` includes) along this
182/// executed path. Used by the evaluator so dead branches and recursive macros
183/// are never parsed.
184pub fn parse_body_tokens(
185    toks: &[Spanned],
186    macros: &mut Macros,
187    includes: &IncludeCtx,
188) -> Result<Vec<Stmt>, ParseError> {
189    let before = body_macro_frame(toks).unwrap_or_else(|| macros.clone());
190    let mut m = before.clone();
191    let mut input = toks.to_vec();
192    input.push(Spanned::new(Token::Eof, 0, 0));
193    let expanded = expand(&input, &mut m, 0, includes)?;
194    propagate_macro_changes(macros, &before, &m);
195    let mut p = Parser::new(expanded);
196    p.parse_elementlist(&[])
197}
198
199fn body_macro_frame(toks: &[Spanned]) -> Option<Macros> {
200    toks.iter()
201        .find_map(|s| s.macro_frame.as_ref().map(|m| m.as_ref().clone()))
202}
203
204fn propagate_macro_changes(macros: &mut Macros, before: &Macros, after: &Macros) {
205    for name in before.keys() {
206        if !after.contains_key(name) {
207            macros.remove(name);
208        }
209    }
210    for (name, body) in after {
211        if before.get(name) != Some(body) {
212            macros.insert(name.clone(), body.clone());
213        }
214    }
215}
216
217/// Parse pic source produced by `exec`, applying the caller's macro argument
218/// frame before normal macro expansion.
219pub(crate) fn parse_exec_source(
220    src: &str,
221    macros: &Macros,
222    includes: &IncludeCtx,
223    arg_frame: Option<&[Vec<Spanned>]>,
224) -> Result<Vec<Stmt>, ParseError> {
225    let mut toks = lex(src)?;
226    if let Some(args) = arg_frame {
227        toks = substitute(&toks, args);
228    }
229    let mut m = macros.clone();
230    let expanded = expand(&toks, &mut m, 0, includes)?;
231    let mut p = Parser::new(expanded);
232    p.parse_elementlist(&[])
233}
234
235pub(crate) fn parse_stringexpr_tokens(
236    toks: &[Spanned],
237    macros: &mut Macros,
238    includes: &IncludeCtx,
239) -> Result<StringExpr, ParseError> {
240    let mut input = toks.to_vec();
241    input.push(Spanned::new(Token::Eof, 0, 0));
242    let expanded = expand(&input, macros, 0, includes)?;
243    let mut p = Parser::new(expanded);
244    p.skip_newlines();
245    let expr = p.parse_stringexpr()?;
246    p.skip_newlines();
247    if !p.at(&Token::Eof) {
248        return p.err(format!("unexpected {:?} after string expression", p.cur()));
249    }
250    Ok(expr)
251}
252
253// ---- backend preamble filter ----------------------------------------------
254
255/// Drop non-SVG backend snippets commonly embedded in dpic examples.
256///
257/// These TeX/PSTricks preambles are meaningful to other backends, but for rpic's
258/// SVG output they should be tolerated as no-ops. Replacing ignored lines with
259/// empty lines keeps subsequent diagnostics on the original line numbers.
260fn strip_backend_preamble(src: &str) -> String {
261    let mut out = String::with_capacity(src.len());
262    let mut in_verbatimtex = false;
263    let mut in_string = false;
264    let mut in_raw_sh = false;
265
266    for line in src.lines() {
267        let trimmed = line.trim_start();
268        if in_verbatimtex {
269            out.push('\n');
270            if starts_word(trimmed, "etex") {
271                in_verbatimtex = false;
272            }
273            continue;
274        }
275
276        if in_raw_sh {
277            out.push_str(line);
278            out.push('\n');
279            in_raw_sh = line_continues(line);
280            continue;
281        }
282
283        if !in_string && starts_word(trimmed, "verbatimtex") {
284            in_verbatimtex = true;
285            out.push('\n');
286        } else if !in_string && is_ignored_backend_line(trimmed) {
287            out.push('\n');
288        } else {
289            out.push_str(line);
290            out.push('\n');
291            if starts_word(trimmed, "sh") {
292                in_raw_sh = line_continues(line);
293            } else {
294                in_string = update_string_state(line, in_string);
295            }
296        }
297    }
298    out
299}
300
301fn line_continues(line: &str) -> bool {
302    line.trim_end_matches([' ', '\t', '\r']).ends_with('\\')
303}
304
305fn update_string_state(line: &str, mut in_string: bool) -> bool {
306    let mut slashes = 0usize;
307    for c in line.chars() {
308        if c == '\\' {
309            slashes += 1;
310            continue;
311        }
312        if c == '"' && slashes.is_multiple_of(2) {
313            in_string = !in_string;
314        }
315        slashes = 0;
316    }
317    in_string
318}
319
320fn is_ignored_backend_line(trimmed: &str) -> bool {
321    trimmed.starts_with("\\global") || trimmed.starts_with("\\psset")
322}
323
324fn starts_word(s: &str, word: &str) -> bool {
325    let Some(rest) = s.strip_prefix(word) else {
326        return false;
327    };
328    !rest
329        .chars()
330        .next()
331        .is_some_and(|c| c.is_alphanumeric() || c == '_')
332}
333
334// ---- macro preprocessor ----------------------------------------------------
335//
336// Handles `define name { body }` (brace-delimited) with `$1..$9` argument
337// substitution at the token level, before parsing. Invocations `name(a, b)` (or
338// bare `name`) are replaced by the body with arguments spliced in; the result is
339// re-expanded so macros may call macros. `undef name` removes a definition.
340
341use std::collections::HashMap;
342use std::path::Path;
343
344fn preprocess(
345    input: Vec<Spanned>,
346    includes: &IncludeCtx,
347) -> Result<(Vec<Spanned>, Macros), ParseError> {
348    let mut macros: Macros = builtin_unit_macros();
349    let out = expand(&input, &mut macros, 0, includes)?;
350    Ok((out, macros))
351}
352
353/// dpic's absolute-unit suffix macros (`11bp__` → `11*(scale/72)`), predefined so
354/// examples that use them without `copy`ing dpictools still work. A user
355/// `define` of the same name overrides these.
356fn builtin_unit_macros() -> Macros {
357    let defs = [
358        ("bp__", "*(scale/72)"),       // Adobe big point
359        ("pt__", "*(scale/72.27)"),    // TeX point
360        ("pc__", "*(12*scale/72.27)"), // pica
361        ("in__", "*scale"),            // inch
362        ("cm__", "*(scale/2.54)"),     // centimetre
363        ("mm__", "*(scale/25.4)"),     // millimetre
364        ("px__", "*(scale/96)"),       // pixel (96 dpi)
365    ];
366    let mut m = Macros::new();
367    for (name, body) in defs {
368        if let Ok(toks) = lex(body) {
369            let body_toks: Vec<Spanned> =
370                toks.into_iter().filter(|s| s.tok != Token::Eof).collect();
371            m.insert(name.to_string(), body_toks);
372        }
373    }
374    m
375}
376
377fn loc(toks: &[Spanned], i: usize) -> Span {
378    toks.get(i)
379        .map(|s| s.span())
380        .unwrap_or_else(|| Span::new(0, 0, 0))
381}
382
383fn expand(
384    toks: &[Spanned],
385    macros: &mut HashMap<String, Vec<Spanned>>,
386    depth: usize,
387    includes: &IncludeCtx,
388) -> Result<Vec<Spanned>, ParseError> {
389    if depth > 64 {
390        return Err(ParseError::new(
391            "macro expansion too deep (recursive define?)",
392            Span::new(0, 0, 0),
393        ));
394    }
395    let mut out = Vec::new();
396    let mut i = 0;
397    while i < toks.len() {
398        match &toks[i].tok {
399            Token::Kw(Kw::Define) => {
400                let span = loc(toks, i);
401                i += 1;
402                let name = match toks.get(i).map(|s| &s.tok) {
403                    Some(Token::Name(n)) | Some(Token::Label(n)) => n.clone(),
404                    _ => {
405                        return Err(ParseError::new(
406                            "define: expected a macro name",
407                            span.clone(),
408                        ));
409                    }
410                };
411                i += 1;
412                // the macro body delimiter may begin on a following line
413                while toks.get(i).map(|s| &s.tok) == Some(&Token::Newline) {
414                    i += 1;
415                }
416                let Some(delim) = toks.get(i).map(|s| s.tok.clone()) else {
417                    return Err(ParseError::new(
418                        "define: expected a body delimiter",
419                        span.clone(),
420                    ));
421                };
422                let body = if delim == Token::LeftBrace {
423                    i += 1; // past `{`
424                    let start = i;
425                    let mut bd = 1;
426                    while i < toks.len() && bd > 0 {
427                        match &toks[i].tok {
428                            Token::LeftBrace => bd += 1,
429                            Token::RightBrace => {
430                                bd -= 1;
431                                if bd == 0 {
432                                    break;
433                                }
434                            }
435                            _ => {}
436                        }
437                        i += 1;
438                    }
439                    if bd != 0 {
440                        return Err(ParseError::new(
441                            "define: unterminated `{` body",
442                            span.clone(),
443                        ));
444                    }
445                    let body = trim_edge_newlines(&toks[start..i]);
446                    i += 1; // past `}`
447                    body
448                } else {
449                    if matches!(delim, Token::Eof | Token::Newline) {
450                        let span = loc(toks, i);
451                        return Err(ParseError::new(
452                            "define: expected a body delimiter",
453                            span.clone(),
454                        ));
455                    }
456                    i += 1; // past delimiter
457                    let start = i;
458                    while i < toks.len() && toks[i].tok != delim {
459                        i += 1;
460                    }
461                    if i >= toks.len() {
462                        return Err(ParseError::new(
463                            "define: unterminated delimited body",
464                            span.clone(),
465                        ));
466                    }
467                    let body = trim_edge_newlines(&toks[start..i]);
468                    i += 1; // past closing delimiter
469                    body
470                };
471                macros.insert(name, body);
472            }
473            Token::Kw(Kw::Undef) => {
474                i += 1;
475                if let Some(Token::Name(n)) | Some(Token::Label(n)) = toks.get(i).map(|s| &s.tok) {
476                    macros.remove(n);
477                }
478                i += 1;
479            }
480            // `if`/`for` bodies are copied verbatim (macro calls inside are not
481            // expanded here): they are expanded lazily, by the evaluator, only
482            // along the branch/iteration that actually runs. The condition/range
483            // is still expanded so macros there work.
484            Token::Kw(Kw::If) => {
485                let if_tok = toks[i].clone();
486                out.push(toks[i].clone());
487                i += 1;
488                let Some(te) = find_kw_depth0(toks, i, Kw::Then) else {
489                    continue; // malformed; let the parser report it
490                };
491                let cond = expand(&toks[i..te], macros, depth + 1, includes)?;
492                if let Some((then_body, after_then)) = read_braced_body(toks, te + 1)? {
493                    let mut j = after_then;
494                    while matches!(toks.get(j).map(|s| &s.tok), Some(Token::Newline)) {
495                        j += 1;
496                    }
497                    let else_body =
498                        if matches!(toks.get(j).map(|s| &s.tok), Some(Token::Kw(Kw::Else))) {
499                            read_braced_body(toks, j + 1)?
500                        } else {
501                            None
502                        };
503                    if let Some(take_then) = static_truth(&cond) {
504                        let after_static = else_body
505                            .as_ref()
506                            .map(|(_, after)| *after)
507                            .unwrap_or(after_then);
508                        out.pop(); // discard the speculative `if`
509                        if take_then {
510                            out.extend(expand(&then_body, macros, depth + 1, includes)?);
511                            i = after_static;
512                        } else if let Some((body, after)) = else_body {
513                            out.extend(expand(&body, macros, depth + 1, includes)?);
514                            i = after;
515                        } else {
516                            i = after_then;
517                        }
518                        continue;
519                    }
520                }
521                *out.last_mut().unwrap() = if_tok;
522                out.extend(cond);
523                out.push(toks[te].clone()); // `then`
524                i = copy_braced(toks, te + 1, &mut out, macros)?;
525                // optional `else { … }` (possibly across newlines)
526                let mut j = i;
527                while matches!(toks.get(j).map(|s| &s.tok), Some(Token::Newline)) {
528                    j += 1;
529                }
530                if matches!(toks.get(j).map(|s| &s.tok), Some(Token::Kw(Kw::Else))) {
531                    out.push(toks[j].clone());
532                    i = copy_braced(toks, j + 1, &mut out, macros)?;
533                }
534            }
535            Token::Kw(Kw::For) => {
536                out.push(toks[i].clone());
537                i += 1;
538                let Some(de) = find_kw_depth0(toks, i, Kw::Do) else {
539                    continue;
540                };
541                out.extend(expand(&toks[i..de], macros, depth + 1, includes)?);
542                out.push(toks[de].clone()); // `do`
543                i = copy_braced(toks, de + 1, &mut out, macros)?;
544            }
545            Token::Name(n) | Token::Label(n) if macros.contains_key(n) => {
546                let body = macros.get(n).unwrap().clone();
547                i += 1;
548                let args = if toks.get(i).map(|s| &s.tok) == Some(&Token::Lparen) {
549                    i += 1;
550                    let (a, ni) = read_args(toks, i)?;
551                    i = ni;
552                    a
553                } else {
554                    Vec::new()
555                };
556                let sub = substitute(&body, &args);
557                let expanded = expand(&sub, macros, depth + 1, includes)?;
558                out.extend(expanded);
559            }
560            // `copy "file"` splices another pic file's (expanded) tokens inline.
561            Token::Kw(Kw::Copy) => {
562                let span = loc(toks, i);
563                i += 1;
564                let Some(Token::Str(fname)) = toks.get(i).map(|s| &s.tok) else {
565                    return Err(ParseError::new(
566                        "copy: expected a quoted file name (only `copy \"file\"` is supported)",
567                        span.clone(),
568                    ));
569                };
570                let fname = fname.clone();
571                i += 1;
572                let inc = include_file(includes, &fname, macros, depth, span)?;
573                out.extend(inc);
574            }
575            _ => {
576                out.push(toks[i].clone());
577                i += 1;
578            }
579        }
580    }
581    Ok(out)
582}
583
584/// Read comma-separated argument token-lists after a `(` (index `i` is just past
585/// it), returning the args and the index after the matching `)`.
586fn read_args(toks: &[Spanned], mut i: usize) -> Result<(Vec<Vec<Spanned>>, usize), ParseError> {
587    let mut args: Vec<Vec<Spanned>> = Vec::new();
588    let mut cur: Vec<Spanned> = Vec::new();
589    let mut depth = 0i32;
590    loop {
591        let Some(s) = toks.get(i) else {
592            return Err(ParseError::new(
593                "unterminated macro arguments",
594                Span::new(0, 0, 0),
595            ));
596        };
597        match &s.tok {
598            Token::Lparen | Token::LeftBrack | Token::LeftBrace => {
599                depth += 1;
600                cur.push(s.clone());
601                i += 1;
602            }
603            Token::Rparen if depth == 0 => {
604                i += 1;
605                trim_trailing_newlines(&mut cur);
606                if !cur.is_empty() || !args.is_empty() {
607                    args.push(cur);
608                }
609                break;
610            }
611            Token::Rparen | Token::RightBrack | Token::RightBrace => {
612                depth -= 1;
613                cur.push(s.clone());
614                i += 1;
615            }
616            Token::Comma if depth == 0 => {
617                trim_trailing_newlines(&mut cur);
618                args.push(std::mem::take(&mut cur));
619                i += 1;
620            }
621            Token::Newline if depth == 0 && cur.is_empty() => {
622                i += 1;
623            }
624            _ => {
625                cur.push(s.clone());
626                i += 1;
627            }
628        }
629    }
630    Ok((args, i))
631}
632
633fn trim_trailing_newlines(toks: &mut Vec<Spanned>) {
634    while matches!(toks.last().map(|s| &s.tok), Some(Token::Newline)) {
635        toks.pop();
636    }
637}
638
639/// Drop leading and trailing `Newline` tokens (used for macro bodies, where the
640/// newlines around a multi-line `{ … }` are formatting, not structure).
641fn trim_edge_newlines(toks: &[Spanned]) -> Vec<Spanned> {
642    let mut start = 0;
643    let mut end = toks.len();
644    while start < end && toks[start].tok == Token::Newline {
645        start += 1;
646    }
647    while end > start && toks[end - 1].tok == Token::Newline {
648        end -= 1;
649    }
650    toks[start..end].to_vec()
651}
652
653/// Replace `$k` argument tokens in a macro body with the k-th argument's tokens.
654fn substitute(body: &[Spanned], args: &[Vec<Spanned>]) -> Vec<Spanned> {
655    let mut out = Vec::new();
656    let mut i = 0;
657    while i < body.len() {
658        if matches!(body[i].tok, Token::Kw(Kw::Define))
659            && let Some((define, next)) = copy_define_verbatim(body, i)
660        {
661            out.extend(define);
662            i = next;
663            continue;
664        }
665
666        if let Some((pasted, next)) = paste_adjacent_args(body, args, i) {
667            out.push(pasted.with_arg_frame(args));
668            i = next;
669            continue;
670        }
671
672        let s = &body[i];
673        match &s.tok {
674            Token::Arg(k) => {
675                if let Some(a) = args.get((*k as usize).wrapping_sub(1)) {
676                    out.extend(a.iter().cloned().map(|s| s.with_arg_frame(args)));
677                }
678            }
679            // `$+` is the number of arguments passed to this macro
680            Token::ArgCount => out.push(
681                Spanned::new(Token::Float(args.len() as f64), s.line, s.col).with_arg_frame(args),
682            ),
683            // `$n` is also substituted inside string literals (the `"$1"==""`
684            // default-argument idiom, sprintf templates like `"$2%g"`, …).
685            Token::Str(text) if text.contains('$') => {
686                out.push(
687                    Spanned::new(Token::Str(subst_in_string(text, args)), s.line, s.col)
688                        .with_arg_frame(args),
689                );
690            }
691            _ => out.push(s.clone().with_arg_frame(args)),
692        }
693        i += 1;
694    }
695    out
696}
697
698fn copy_define_verbatim(body: &[Spanned], start: usize) -> Option<(Vec<Spanned>, usize)> {
699    let mut name_idx = start + 1;
700    while matches!(body.get(name_idx).map(|s| &s.tok), Some(Token::Newline)) {
701        name_idx += 1;
702    }
703    if !matches!(
704        body.get(name_idx).map(|s| &s.tok),
705        Some(Token::Name(_)) | Some(Token::Label(_))
706    ) {
707        return None;
708    }
709
710    let mut out = Vec::new();
711    let mut i = start;
712    while let Some(s) = body.get(i) {
713        out.push(s.clone());
714        i += 1;
715        if matches!(s.tok, Token::LeftBrace) {
716            break;
717        }
718    }
719
720    if !matches!(out.last().map(|s| &s.tok), Some(Token::LeftBrace)) {
721        return None;
722    }
723
724    let mut depth = 1i32;
725    while let Some(s) = body.get(i) {
726        match &s.tok {
727            Token::LeftBrace => depth += 1,
728            Token::RightBrace => depth -= 1,
729            _ => {}
730        }
731        out.push(s.clone());
732        i += 1;
733        if depth == 0 {
734            return Some((out, i));
735        }
736    }
737    None
738}
739
740fn paste_adjacent_args(
741    body: &[Spanned],
742    args: &[Vec<Spanned>],
743    start: usize,
744) -> Option<(Spanned, usize)> {
745    let first = body.get(start)?;
746    let Token::Arg(k) = &first.tok else {
747        return None;
748    };
749
750    let mut text = arg_text(*k, args);
751    let mut count = 1usize;
752    let mut end = start + 1;
753    let mut prev = first;
754    while let Some(next) = body.get(end) {
755        let Token::Arg(k) = &next.tok else {
756            break;
757        };
758        if !adjacent_arg_tokens(prev, next) {
759            break;
760        }
761        text.push_str(&arg_text(*k, args));
762        count += 1;
763        prev = next;
764        end += 1;
765    }
766
767    if count < 2 || text.is_empty() {
768        return None;
769    }
770
771    Some((tokenize_pasted_arg_text(&text, first.line, first.col), end))
772}
773
774fn arg_text(k: u32, args: &[Vec<Spanned>]) -> String {
775    args.get((k as usize).wrapping_sub(1))
776        .map(|a| tokens_to_text(a))
777        .unwrap_or_default()
778}
779
780fn adjacent_arg_tokens(left: &Spanned, right: &Spanned) -> bool {
781    left.line == right.line && arg_end_col(left) == Some(right.col)
782}
783
784fn arg_end_col(s: &Spanned) -> Option<u32> {
785    let Token::Arg(k) = &s.tok else {
786        return None;
787    };
788    Some(s.col + 1 + k.to_string().len() as u32)
789}
790
791fn tokenize_pasted_arg_text(text: &str, line: u32, col: u32) -> Spanned {
792    if let Ok(toks) = lex(text)
793        && toks.len() == 2
794        && matches!(toks[1].tok, Token::Eof)
795    {
796        return Spanned::new(toks[0].tok.clone(), line, col);
797    }
798
799    let tok = if text.chars().next().is_some_and(|c| c.is_ascii_uppercase()) {
800        Token::Label(text.to_string())
801    } else {
802        Token::Name(text.to_string())
803    };
804    Spanned::new(tok, line, col)
805}
806
807/// Replace `$n` references inside a string literal with the textual form of the
808/// n-th macro argument (empty if missing).
809fn subst_in_string(text: &str, args: &[Vec<Spanned>]) -> String {
810    let chars: Vec<char> = text.chars().collect();
811    let mut out = String::new();
812    let mut i = 0;
813    while i < chars.len() {
814        if chars[i] == '$' && chars.get(i + 1) == Some(&'+') {
815            out.push_str(&args.len().to_string());
816            i += 2;
817        } else if chars[i] == '$' && chars.get(i + 1).is_some_and(|c| c.is_ascii_digit()) {
818            let mut j = i + 1;
819            let mut num = String::new();
820            while j < chars.len() && chars[j].is_ascii_digit() {
821                num.push(chars[j]);
822                j += 1;
823            }
824            if let Ok(k) = num.parse::<usize>()
825                && k >= 1
826                && let Some(a) = args.get(k - 1)
827            {
828                out.push_str(&tokens_to_text(a));
829            }
830            i = j;
831        } else {
832            out.push(chars[i]);
833            i += 1;
834        }
835    }
836    out
837}
838
839/// Best-effort textual rendering of an argument token list, for `$n` splicing
840/// inside string literals.
841fn tokens_to_text(toks: &[Spanned]) -> String {
842    let mut s = String::new();
843    for t in toks {
844        match &t.tok {
845            Token::Float(v) => s.push_str(&format!("{v}")),
846            Token::Str(t) => s.push_str(t),
847            Token::Name(n) | Token::Label(n) => s.push_str(n),
848            Token::Lparen => s.push('('),
849            Token::Rparen => s.push(')'),
850            Token::LeftBrack => s.push('['),
851            Token::RightBrack => s.push(']'),
852            Token::LeftBrace => s.push('{'),
853            Token::RightBrace => s.push('}'),
854            Token::Comma => s.push(','),
855            Token::Colon => s.push(':'),
856            Token::Dot => s.push('.'),
857            Token::Plus => s.push('+'),
858            Token::Minus => s.push('-'),
859            Token::Mult => s.push('*'),
860            Token::Div => s.push('/'),
861            Token::Percent => s.push('%'),
862            Token::Dollar => s.push('$'),
863            Token::Backslash => s.push('\\'),
864            Token::DotX => s.push_str(".x"),
865            Token::DotY => s.push_str(".y"),
866            Token::DotPS => s.push_str(".PS"),
867            Token::DotPE => s.push_str(".PE"),
868            Token::Corner(c) => s.push_str(corner_text(*c)),
869            Token::Param(p) => s.push_str(param_text(*p)),
870            Token::LineType(l) => s.push_str(line_type_text(*l)),
871            Token::TextPos(p) => s.push_str(text_pos_text(*p)),
872            Token::Arrow(a) => s.push_str(arrow_text(*a)),
873            Token::Dir(d) => s.push_str(dir_text(*d)),
874            Token::Prim(p) => s.push_str(prim_text(*p)),
875            Token::Color(c) => s.push_str(color_text(*c)),
876            _ => {}
877        }
878    }
879    s
880}
881
882fn corner_text(c: Corner) -> &'static str {
883    match c {
884        Corner::N => ".n",
885        Corner::S => ".s",
886        Corner::E => ".e",
887        Corner::W => ".w",
888        Corner::Ne => ".ne",
889        Corner::Se => ".se",
890        Corner::Nw => ".nw",
891        Corner::Sw => ".sw",
892        Corner::Start => ".start",
893        Corner::End => ".end",
894        Corner::Center => ".c",
895    }
896}
897
898fn param_text(p: Param) -> &'static str {
899    match p {
900        Param::Height => ".ht",
901        Param::Width => ".wid",
902        Param::Radius => ".rad",
903        Param::Diameter => ".diam",
904        Param::Thickness => ".thick",
905        Param::Length => ".len",
906    }
907}
908
909fn line_type_text(l: LineType) -> &'static str {
910    match l {
911        LineType::Solid => "solid",
912        LineType::Dotted => "dotted",
913        LineType::Dashed => "dashed",
914        LineType::Invis => "invis",
915    }
916}
917
918fn text_pos_text(p: TextPos) -> &'static str {
919    match p {
920        TextPos::Center => "center",
921        TextPos::Ljust => "ljust",
922        TextPos::Rjust => "rjust",
923        TextPos::Above => "above",
924        TextPos::Below => "below",
925    }
926}
927
928fn arrow_text(a: Arrow) -> &'static str {
929    match a {
930        Arrow::Left => "<-",
931        Arrow::Right => "->",
932        Arrow::Double => "<->",
933    }
934}
935
936fn dir_text(d: Dir) -> &'static str {
937    match d {
938        Dir::Up => "up",
939        Dir::Down => "down",
940        Dir::Right => "right",
941        Dir::Left => "left",
942    }
943}
944
945fn prim_text(p: Prim) -> &'static str {
946    match p {
947        Prim::Box => "box",
948        Prim::Circle => "circle",
949        Prim::Ellipse => "ellipse",
950        Prim::Arc => "arc",
951        Prim::Line => "line",
952        Prim::Arrow => "arrow",
953        Prim::Move => "move",
954        Prim::Spline => "spline",
955    }
956}
957
958fn color_text(c: Color) -> &'static str {
959    match c {
960        Color::Colored => "color",
961        Color::Outlined => "outlined",
962        Color::Shaded => "shaded",
963    }
964}
965
966fn kw_text(k: Kw) -> &'static str {
967    match k {
968        Kw::Ht => "ht",
969        Kw::Wid => "wid",
970        Kw::Rad => "rad",
971        Kw::Diam => "diam",
972        Kw::Thick => "thick",
973        Kw::Scaled => "scaled",
974        Kw::From => "from",
975        Kw::To => "to",
976        Kw::At => "at",
977        Kw::With => "with",
978        Kw::By => "by",
979        Kw::Then => "then",
980        Kw::Continue => "continue",
981        Kw::Chop => "chop",
982        Kw::Same => "same",
983        Kw::Cw => "cw",
984        Kw::Ccw => "ccw",
985        Kw::Of => "of",
986        Kw::The => "the",
987        Kw::Way => "way",
988        Kw::Between => "between",
989        Kw::And => "and",
990        Kw::Here => "Here",
991        Kw::Last => "last",
992        Kw::Fill => "fill",
993        Kw::Nth => "ordinal suffix",
994        Kw::Print => "print",
995        Kw::Copy => "copy",
996        Kw::Reset => "reset",
997        Kw::Exec => "exec",
998        Kw::Sh => "sh",
999        Kw::Command => "command",
1000        Kw::Define => "define",
1001        Kw::Undef => "undef",
1002        Kw::Rand => "rand",
1003        Kw::If => "if",
1004        Kw::Else => "else",
1005        Kw::For => "for",
1006        Kw::Do => "do",
1007        Kw::Sprintf => "sprintf",
1008        Kw::Animate => "animate",
1009        Kw::After => "after",
1010        Kw::Delay => "delay",
1011    }
1012}
1013
1014fn token_text(t: &Token) -> String {
1015    match t {
1016        Token::Float(v) => fmt_float(*v),
1017        Token::Str(s) => format!("\"{s}\""),
1018        Token::Name(s) | Token::Label(s) => format!("`{s}`"),
1019        Token::Arg(n) => format!("${n}"),
1020        Token::ArgCount => "$+".into(),
1021        Token::Dollar => "$".into(),
1022        Token::Backslash => "\\".into(),
1023        Token::Newline => "end of line".into(),
1024        Token::DotPS => ".PS".into(),
1025        Token::DotPE => ".PE".into(),
1026        Token::Eof => "end of input".into(),
1027        Token::Lt => "<".into(),
1028        Token::Lparen => "(".into(),
1029        Token::Rparen => ")".into(),
1030        Token::Mult => "*".into(),
1031        Token::Plus => "+".into(),
1032        Token::Minus => "-".into(),
1033        Token::Div => "/".into(),
1034        Token::Percent => "%".into(),
1035        Token::Caret => "^".into(),
1036        Token::Not => "!".into(),
1037        Token::AndAnd => "&&".into(),
1038        Token::OrOr => "||".into(),
1039        Token::Ampersand => "&".into(),
1040        Token::Comma => ",".into(),
1041        Token::Colon => ":".into(),
1042        Token::LeftBrack => "[".into(),
1043        Token::RightBrack => "]".into(),
1044        Token::LeftBrace => "{".into(),
1045        Token::RightBrace => "}".into(),
1046        Token::Dot => ".".into(),
1047        Token::Block => "[]".into(),
1048        Token::LeftQuote => "`".into(),
1049        Token::RightQuote => "'".into(),
1050        Token::Eq => "=".into(),
1051        Token::ColonEq => ":=".into(),
1052        Token::PlusEq => "+=".into(),
1053        Token::MinusEq => "-=".into(),
1054        Token::MultEq => "*=".into(),
1055        Token::DivEq => "/=".into(),
1056        Token::RemEq => "%=".into(),
1057        Token::EqEq => "==".into(),
1058        Token::Neq => "!=".into(),
1059        Token::Ge => ">=".into(),
1060        Token::Le => "<=".into(),
1061        Token::Gt => ">".into(),
1062        Token::DotX => ".x".into(),
1063        Token::DotY => ".y".into(),
1064        Token::Kw(k) => kw_text(*k).into(),
1065        Token::Corner(c) => corner_text(*c).into(),
1066        Token::Param(p) => format!(".{}", param_text(*p)),
1067        Token::Func1(f) => format!("{f:?}").to_ascii_lowercase(),
1068        Token::Func2(f) => format!("{f:?}").to_ascii_lowercase(),
1069        Token::LineType(l) => line_type_text(*l).into(),
1070        Token::TextPos(p) => text_pos_text(*p).into(),
1071        Token::Arrow(a) => arrow_text(*a).into(),
1072        Token::Dir(d) => dir_text(*d).into(),
1073        Token::Prim(p) => prim_text(*p).into(),
1074        Token::Color(c) => color_text(*c).into(),
1075        Token::EnvVar(e) => format!("{e:?}").to_ascii_lowercase(),
1076    }
1077}
1078
1079fn fmt_float(v: f64) -> String {
1080    let mut s = v.to_string();
1081    if s.ends_with(".0") {
1082        s.truncate(s.len() - 2);
1083    }
1084    s
1085}
1086
1087fn suggest_object(word: &str) -> Option<&'static str> {
1088    const WORDS: &[&str] = &[
1089        "arc", "arrow", "box", "brace", "circle", "dot", "ellipse", "line", "move", "spline",
1090    ];
1091    crate::diagnostic::closest(word, WORDS)
1092}
1093
1094/// Read and tokenize a `copy "file"` include, returning its expanded tokens
1095/// (with the trailing `Eof` removed so it splices cleanly mid-stream). The
1096/// included file resolves nested `copy`s relative to its own directory.
1097fn include_file(
1098    includes: &IncludeCtx,
1099    fname: &str,
1100    macros: &mut HashMap<String, Vec<Spanned>>,
1101    depth: usize,
1102    span: Span,
1103) -> Result<Vec<Spanned>, ParseError> {
1104    let mkerr = |msg: String| ParseError::new(msg, span.clone());
1105    let denied = |why: &str| {
1106        ParseError::new(format!("copy \"{fname}\": {why}"), span.clone())
1107            .with_kind("include_denied")
1108    };
1109    // `copy "circuits"` is a reserved target: it loads the embedded native
1110    // circuit-element library — the in-source spelling of `-c`, usable even
1111    // where file includes are not (wasm, compile_json with no base dir). It
1112    // shadows any real file literally named `circuits`. Skipped when the
1113    // library is already loaded (`-c` plus an explicit copy): `__resistor`
1114    // is one of its own defines.
1115    if fname == "circuits" {
1116        if macros.contains_key("__resistor") {
1117            return Ok(Vec::new());
1118        }
1119        let toks = lex_named(crate::CIRCUITS, "circuits")?;
1120        let mut expanded = expand(&toks, macros, depth + 1, includes)?;
1121        if matches!(expanded.last().map(|s| &s.tok), Some(Token::Eof)) {
1122            expanded.pop();
1123        }
1124        return Ok(expanded);
1125    }
1126    if includes.policy == IncludePolicy::Deny {
1127        return Err(denied(
1128            "filesystem includes are disabled by the include policy",
1129        ));
1130    }
1131    let p = Path::new(fname);
1132    if p.is_absolute() && includes.policy == IncludePolicy::SandboxedToBase {
1133        return Err(denied(
1134            "absolute paths are not allowed by the include policy",
1135        ));
1136    }
1137    let path = if p.is_absolute() {
1138        p.to_path_buf()
1139    } else {
1140        match includes.dir.as_deref() {
1141            Some(b) => b.join(p),
1142            None => {
1143                return Err(mkerr(format!(
1144                    "copy \"{fname}\": file includes require a file path (unavailable here)"
1145                )));
1146            }
1147        }
1148    };
1149    if includes.policy == IncludePolicy::SandboxedToBase {
1150        // Canonicalize (resolving `..` and symlinks) and require the result
1151        // to stay inside the fence root. A fence that failed to resolve at
1152        // setup fails closed. The error names the path as written, never the
1153        // resolved location.
1154        let inside = includes
1155            .fence
1156            .as_deref()
1157            .is_some_and(|fence| std::fs::canonicalize(&path).is_ok_and(|c| c.starts_with(fence)));
1158        if !inside {
1159            return Err(denied("path resolves outside the include base directory"));
1160        }
1161    }
1162    let content =
1163        std::fs::read_to_string(&path).map_err(|e| mkerr(format!("copy \"{fname}\": {e}")))?;
1164    let toks = lex_named(&content, fname)?;
1165    let inc_base = path.parent().map(|d| d.to_path_buf());
1166    let inc_ctx = includes.child(inc_base);
1167    let mut expanded = expand(&toks, macros, depth + 1, &inc_ctx)?;
1168    if matches!(expanded.last().map(|s| &s.tok), Some(Token::Eof)) {
1169        expanded.pop();
1170    }
1171    Ok(expanded)
1172}
1173
1174/// Find the next occurrence of keyword `kw` at bracket-depth 0 from `start`.
1175fn find_kw_depth0(toks: &[Spanned], start: usize, kw: Kw) -> Option<usize> {
1176    let mut depth = 0i32;
1177    for (off, s) in toks[start..].iter().enumerate() {
1178        match &s.tok {
1179            Token::Lparen | Token::LeftBrace | Token::LeftBrack => depth += 1,
1180            Token::Rparen | Token::RightBrace | Token::RightBrack => {
1181                depth -= 1;
1182                if depth < 0 {
1183                    return None;
1184                }
1185            }
1186            Token::Kw(k) if *k == kw && depth == 0 => return Some(start + off),
1187            _ => {}
1188        }
1189    }
1190    None
1191}
1192
1193/// Copy a brace-delimited block verbatim into `out` (including any nested
1194/// braces), skipping/copying leading newlines. Returns the index past the `}`.
1195fn copy_braced(
1196    toks: &[Spanned],
1197    mut i: usize,
1198    out: &mut Vec<Spanned>,
1199    macros: &HashMap<String, Vec<Spanned>>,
1200) -> Result<usize, ParseError> {
1201    while matches!(toks.get(i).map(|s| &s.tok), Some(Token::Newline)) {
1202        out.push(toks[i].clone());
1203        i += 1;
1204    }
1205    if !matches!(toks.get(i).map(|s| &s.tok), Some(Token::LeftBrace)) {
1206        return Ok(i); // no body; the parser will report the problem
1207    }
1208    let mut depth = 0i32;
1209    let mut tagged_body = false;
1210    while let Some(s) = toks.get(i) {
1211        let mut s = s.clone();
1212        let outer_left_brace = depth == 0 && matches!(s.tok, Token::LeftBrace);
1213        match &s.tok {
1214            Token::LeftBrace => depth += 1,
1215            Token::RightBrace => {
1216                out.push(s);
1217                i += 1;
1218                depth -= 1;
1219                if depth == 0 {
1220                    return Ok(i);
1221                }
1222                continue;
1223            }
1224            _ => {}
1225        }
1226        if depth == 1 && !outer_left_brace && !tagged_body {
1227            s = s.with_macro_frame(macros);
1228            tagged_body = true;
1229        }
1230        out.push(s);
1231        i += 1;
1232    }
1233    Err(ParseError::new("unterminated `{` body", Span::new(0, 0, 0)))
1234}
1235
1236fn read_braced_body(
1237    toks: &[Spanned],
1238    mut i: usize,
1239) -> Result<Option<(Vec<Spanned>, usize)>, ParseError> {
1240    while matches!(toks.get(i).map(|s| &s.tok), Some(Token::Newline)) {
1241        i += 1;
1242    }
1243    if !matches!(toks.get(i).map(|s| &s.tok), Some(Token::LeftBrace)) {
1244        return Ok(None);
1245    }
1246    i += 1;
1247    let start = i;
1248    let mut depth = 1i32;
1249    while let Some(s) = toks.get(i) {
1250        match &s.tok {
1251            Token::LeftBrace => depth += 1,
1252            Token::RightBrace => {
1253                depth -= 1;
1254                if depth == 0 {
1255                    return Ok(Some((toks[start..i].to_vec(), i + 1)));
1256                }
1257            }
1258            _ => {}
1259        }
1260        i += 1;
1261    }
1262    Err(ParseError::new("unterminated `{` body", Span::new(0, 0, 0)))
1263}
1264
1265fn static_truth(toks: &[Spanned]) -> Option<bool> {
1266    let toks = trim_trailing_eof(toks);
1267    match toks {
1268        [
1269            Spanned {
1270                tok: Token::Float(v),
1271                ..
1272            },
1273        ] => Some(*v != 0.0),
1274        [
1275            Spanned {
1276                tok: Token::Not, ..
1277            },
1278            Spanned {
1279                tok: Token::Float(v),
1280                ..
1281            },
1282        ] => Some(*v == 0.0),
1283        [a, op, b] => match op.tok {
1284            Token::EqEq | Token::Neq => {
1285                if let (Some(lhs), Some(rhs)) = (static_string(a), static_string(b)) {
1286                    return Some(if matches!(op.tok, Token::EqEq) {
1287                        lhs == rhs
1288                    } else {
1289                        lhs != rhs
1290                    });
1291                }
1292                if let (Some(lhs), Some(rhs)) = (static_number(a), static_number(b)) {
1293                    return Some(if matches!(op.tok, Token::EqEq) {
1294                        (lhs - rhs).abs() < f64::EPSILON
1295                    } else {
1296                        (lhs - rhs).abs() >= f64::EPSILON
1297                    });
1298                }
1299                None
1300            }
1301            _ => None,
1302        },
1303        [a, op, b, op2, c] if matches!(op2.tok, Token::Plus) => {
1304            let lhs = static_string(a)?;
1305            let mut rhs = static_string(b)?;
1306            rhs.push_str(&static_string(c)?);
1307            match op.tok {
1308                Token::EqEq => Some(lhs == rhs),
1309                Token::Neq => Some(lhs != rhs),
1310                _ => None,
1311            }
1312        }
1313        _ => None,
1314    }
1315}
1316
1317fn trim_trailing_eof(toks: &[Spanned]) -> &[Spanned] {
1318    if matches!(toks.last().map(|s| &s.tok), Some(Token::Eof)) {
1319        &toks[..toks.len() - 1]
1320    } else {
1321        toks
1322    }
1323}
1324
1325fn static_string(s: &Spanned) -> Option<String> {
1326    match &s.tok {
1327        Token::Str(v) => Some(v.clone()),
1328        _ => None,
1329    }
1330}
1331
1332fn static_number(s: &Spanned) -> Option<f64> {
1333    match &s.tok {
1334        Token::Float(v) => Some(*v),
1335        Token::Name(n) | Token::Label(n) => dpic_backend_constant(n),
1336        _ => None,
1337    }
1338}
1339
1340fn dpic_backend_constant(name: &str) -> Option<f64> {
1341    match name {
1342        "optMFpic" => Some(0.0),
1343        "optMpost" => Some(1.0),
1344        "optPDF" => Some(2.0),
1345        "optPGF" => Some(3.0),
1346        "optPict2e" => Some(4.0),
1347        "optPS" => Some(5.0),
1348        "optPSfrag" => Some(6.0),
1349        "optPSTricks" => Some(7.0),
1350        "optSVG" | "dpicopt" => Some(8.0),
1351        "optTeX" => Some(9.0),
1352        "opttTeX" => Some(10.0),
1353        "optxfig" => Some(11.0),
1354        _ => None,
1355    }
1356}
1357
1358type PResult<T> = Result<T, ParseError>;
1359
1360fn is_assign_op(t: &Token) -> bool {
1361    matches!(
1362        t,
1363        Token::Eq
1364            | Token::ColonEq
1365            | Token::PlusEq
1366            | Token::MinusEq
1367            | Token::MultEq
1368            | Token::DivEq
1369            | Token::RemEq
1370    )
1371}
1372
1373struct Parser {
1374    toks: Vec<Spanned>,
1375    idx: usize,
1376}
1377
1378impl Parser {
1379    fn new(toks: Vec<Spanned>) -> Self {
1380        Parser { toks, idx: 0 }
1381    }
1382
1383    // ---- cursor helpers ----------------------------------------------------
1384
1385    fn cur(&self) -> &Token {
1386        &self.toks[self.idx].tok
1387    }
1388    fn cur_span(&self) -> Span {
1389        self.toks[self.idx].span()
1390    }
1391    fn peek(&self, n: usize) -> &Token {
1392        self.toks
1393            .get(self.idx + n)
1394            .map(|s| &s.tok)
1395            .unwrap_or(&Token::Eof)
1396    }
1397    fn at(&self, t: &Token) -> bool {
1398        self.cur() == t
1399    }
1400    fn bump(&mut self) -> Token {
1401        let t = self.toks[self.idx].tok.clone();
1402        if self.idx + 1 < self.toks.len() {
1403            self.idx += 1;
1404        }
1405        t
1406    }
1407    fn eat(&mut self, t: &Token) -> bool {
1408        if self.at(t) {
1409            self.bump();
1410            true
1411        } else {
1412            false
1413        }
1414    }
1415    fn expect(&mut self, t: &Token) -> PResult<()> {
1416        if self.eat(t) {
1417            Ok(())
1418        } else {
1419            self.expected_here(token_text(t))
1420        }
1421    }
1422    fn err<T>(&self, msg: impl Into<String>) -> PResult<T> {
1423        let s = &self.toks[self.idx];
1424        Err(ParseError::new(msg, s.span()))
1425    }
1426    fn expected_here<T>(&self, expected: impl Into<String>) -> PResult<T> {
1427        let s = &self.toks[self.idx];
1428        Err(ParseError::expected(expected, token_text(&s.tok), s.span()))
1429    }
1430    fn expected_object<T>(&self) -> PResult<T> {
1431        let s = &self.toks[self.idx];
1432        let mut e = ParseError::expected("an object", token_text(&s.tok), s.span());
1433        if let Token::Name(name) | Token::Label(name) = &s.tok
1434            && let Some(hint) = suggest_object(name)
1435        {
1436            e.detail.hint = Some(format!("did you mean `{hint}`?"));
1437        }
1438        Err(e)
1439    }
1440    fn at_kw(&self, k: Kw) -> bool {
1441        matches!(self.cur(), Token::Kw(x) if *x == k)
1442    }
1443    fn eat_kw(&mut self, k: Kw) -> bool {
1444        if self.at_kw(k) {
1445            self.bump();
1446            true
1447        } else {
1448            false
1449        }
1450    }
1451    fn skip_newlines(&mut self) {
1452        while self.at(&Token::Newline) {
1453            self.bump();
1454        }
1455    }
1456
1457    // ---- top level ---------------------------------------------------------
1458
1459    fn parse_picture(&mut self) -> PResult<Picture> {
1460        // `.PS`/`.PE` are treated as markers that may appear anywhere; statements
1461        // (including `animate`) are collected across them up to EOF. The first
1462        // `.PS` may carry optional width/height.
1463        let (mut width, mut height) = (None, None);
1464        let mut seen_ps = false;
1465        let mut stmts = Vec::new();
1466        loop {
1467            self.skip_newlines();
1468            match self.cur() {
1469                Token::Eof => break,
1470                Token::DotPS => {
1471                    self.bump();
1472                    if !seen_ps && self.starts_scalar() {
1473                        width = Some(self.parse_expr()?);
1474                        if self.starts_scalar() {
1475                            height = Some(self.parse_expr()?);
1476                        }
1477                    }
1478                    seen_ps = true;
1479                    while !self.at(&Token::Newline) && !self.at(&Token::Eof) {
1480                        self.bump();
1481                    }
1482                    continue;
1483                }
1484                Token::DotPE => {
1485                    self.bump();
1486                    continue;
1487                }
1488                _ => {}
1489            }
1490            stmts.push(self.parse_element()?);
1491            if !self.at(&Token::Newline)
1492                && !self.at(&Token::Eof)
1493                && !self.at(&Token::DotPE)
1494                && !self.at(&Token::DotPS)
1495            {
1496                return self.err(format!("unexpected {:?} after statement", self.cur()));
1497            }
1498        }
1499        Ok(Picture {
1500            width,
1501            height,
1502            stmts,
1503            macros: HashMap::new(),
1504            includes: IncludeCtx::default(),
1505        })
1506    }
1507
1508    /// Parse elements until one of `terminators` (or EOF) is the current token.
1509    fn parse_elementlist(&mut self, terminators: &[Token]) -> PResult<Vec<Stmt>> {
1510        let mut stmts = Vec::new();
1511        loop {
1512            self.skip_newlines();
1513            if self.at(&Token::Eof) || terminators.iter().any(|t| self.at(t)) {
1514                break;
1515            }
1516            let s = self.parse_element()?;
1517            stmts.push(s);
1518            // a statement must end at a newline, a terminator, or EOF
1519            if !self.at(&Token::Newline)
1520                && !self.at(&Token::Eof)
1521                && !terminators.iter().any(|t| self.at(t))
1522            {
1523                return self.err(format!("unexpected {:?} after statement", self.cur()));
1524            }
1525        }
1526        Ok(stmts)
1527    }
1528
1529    // ---- statements --------------------------------------------------------
1530
1531    fn parse_element(&mut self) -> PResult<Stmt> {
1532        // A `%`-led line is a comment convention in some source documents (pic
1533        // proper uses `#`). `%` is never valid at statement start, so skip the
1534        // line as a no-op.
1535        if self.at(&Token::Percent) {
1536            while !self.at(&Token::Newline) && !self.at(&Token::Eof) {
1537                self.bump();
1538            }
1539            return Ok(Stmt::Print(PrintItem::Str(StringExpr::Lit(String::new()))));
1540        }
1541
1542        // rpic animation directive.
1543        if self.at_kw(Kw::Animate) {
1544            return Ok(Stmt::Animate(self.parse_animate()?));
1545        }
1546
1547        // rpic `class <place> "name"` statement (extension). Contextual:
1548        // `class = 2` stays an assignment and `class` remains usable as a
1549        // variable, mirroring how `animate` targets are referenced.
1550        if matches!(self.cur(), Token::Name(n) if n == "class")
1551            && !is_assign_op(self.peek(1))
1552            && !matches!(self.peek(1), Token::LeftBrack)
1553        {
1554            self.bump();
1555            let target = self.parse_place()?;
1556            let class = self.parse_stringexpr()?;
1557            return Ok(Stmt::Class { target, class });
1558        }
1559
1560        // control constructs
1561        match self.cur() {
1562            Token::Kw(Kw::If) => return self.parse_if(),
1563            Token::Kw(Kw::For) => return self.parse_for(),
1564            Token::Kw(Kw::Print) => return self.parse_print(),
1565            Token::Kw(Kw::Exec) => return self.parse_exec(),
1566            Token::Kw(Kw::Reset) => return self.parse_reset(),
1567            _ => {}
1568        }
1569
1570        // `define`/`undef` are handled by the macro preprocessor before parsing;
1571        // reaching here means a non-brace form we don't support.
1572        if let Token::Kw(k) = self.cur() {
1573            match k {
1574                Kw::Define | Kw::Undef => {
1575                    return self.err("only the `define name { body }` macro form is supported");
1576                }
1577                // Policy (docs/raw-backend-policy in dpic-compat-audit.md):
1578                // `command` raw backend text is never injected into the SVG
1579                // output, and `sh` is never executed — both are tolerated as
1580                // true no-ops so dpic sources keep compiling. The lexer already
1581                // skipped their raw argument text.
1582                Kw::Command | Kw::Sh => {
1583                    self.bump();
1584                    return Ok(Stmt::Group(Vec::new()));
1585                }
1586                Kw::Copy => {
1587                    return self.err("`copy` is not supported yet (planned milestone)");
1588                }
1589                _ => {}
1590            }
1591        }
1592
1593        // `{ … }` grouping
1594        if self.eat(&Token::LeftBrace) {
1595            let stmts = self.parse_elementlist(&[Token::RightBrace])?;
1596            self.expect(&Token::RightBrace)?;
1597            return Ok(Stmt::Group(stmts));
1598        }
1599
1600        // Labelled element: `Label [suffix] : (object | position)`
1601        if matches!(self.cur(), Token::Label(_)) && self.label_colon_ahead() {
1602            let label = self.parse_label()?;
1603            self.expect(&Token::Colon)?;
1604            if self.at_object_start() {
1605                let object = self.parse_object()?;
1606                return Ok(Stmt::Object {
1607                    label: Some(label),
1608                    object,
1609                });
1610            } else {
1611                let pos = self.parse_label_position()?;
1612                return Ok(Stmt::Place { label, pos });
1613            }
1614        }
1615
1616        // Assignment: `name [suffix] op …` or `envvar op …`
1617        if self.at_assignment_start() {
1618            return Ok(Stmt::Assign(self.parse_assignlist()?));
1619        }
1620
1621        // Bare direction change.
1622        if let Token::Dir(d) = self.cur() {
1623            let d = *d;
1624            // Only a standalone direction (next token ends the statement).
1625            if matches!(self.peek(1), Token::Newline | Token::Eof) {
1626                self.bump();
1627                return Ok(Stmt::Direction(d));
1628            }
1629        }
1630
1631        // Otherwise: an unlabelled object.
1632        let object = self.parse_object()?;
1633        Ok(Stmt::Object {
1634            label: None,
1635            object,
1636        })
1637    }
1638
1639    fn parse_if(&mut self) -> PResult<Stmt> {
1640        self.expect_kw(Kw::If)?;
1641        let cond = self.parse_expr()?;
1642        self.expect_kw(Kw::Then)?;
1643        let then_body = self.capture_braced()?;
1644        // optional `else { … }`, possibly across newlines (which otherwise end
1645        // the statement)
1646        let save = self.idx;
1647        self.skip_newlines();
1648        let else_body = if self.eat_kw(Kw::Else) {
1649            Some(self.capture_braced()?)
1650        } else {
1651            self.idx = save;
1652            None
1653        };
1654        Ok(Stmt::If {
1655            cond,
1656            then_body,
1657            else_body,
1658        })
1659    }
1660
1661    fn parse_for(&mut self) -> PResult<Stmt> {
1662        self.expect_kw(Kw::For)?;
1663        let var = match self.bump() {
1664            Token::Name(s) | Token::Label(s) => s,
1665            other => return self.err(format!("expected loop variable, found {other:?}")),
1666        };
1667        let subscript = if self.eat(&Token::LeftBrack) {
1668            let e = self.parse_subscript()?;
1669            self.expect(&Token::RightBrack)?;
1670            Some(e)
1671        } else {
1672            None
1673        };
1674        match self.bump() {
1675            Token::Eq | Token::ColonEq => {}
1676            other => return self.err(format!("expected `=` in for, found {other:?}")),
1677        }
1678        let from = self.parse_expr()?;
1679        self.expect_kw(Kw::To)?;
1680        let to = self.parse_expr()?;
1681        let mut by = Expr::Num(1.0);
1682        let mut mult = false;
1683        if self.eat_kw(Kw::By) {
1684            mult = self.eat(&Token::Mult);
1685            by = self.parse_expr()?;
1686        }
1687        self.expect_kw(Kw::Do)?;
1688        let body = self.capture_braced()?;
1689        Ok(Stmt::For {
1690            var,
1691            subscript,
1692            from,
1693            to,
1694            by,
1695            mult,
1696            body,
1697        })
1698    }
1699
1700    /// Capture a brace-delimited block as raw tokens (excluding the braces),
1701    /// for deferred parsing by the evaluator. Assumes the body follows.
1702    fn capture_braced(&mut self) -> PResult<Body> {
1703        self.skip_newlines();
1704        self.expect(&Token::LeftBrace)?;
1705        let start = self.idx;
1706        let mut depth = 1i32;
1707        loop {
1708            match self.cur() {
1709                Token::LeftBrace => depth += 1,
1710                Token::RightBrace => {
1711                    depth -= 1;
1712                    if depth == 0 {
1713                        break;
1714                    }
1715                }
1716                Token::Eof => return self.err("unterminated `{` body"),
1717                _ => {}
1718            }
1719            self.bump();
1720        }
1721        let body = self.toks[start..self.idx].to_vec();
1722        self.expect(&Token::RightBrace)?;
1723        Ok(body)
1724    }
1725
1726    fn parse_print(&mut self) -> PResult<Stmt> {
1727        self.expect_kw(Kw::Print)?;
1728        let item = if self.at_string_start() {
1729            PrintItem::Str(self.parse_stringexpr()?)
1730        } else {
1731            PrintItem::Expr(self.parse_expr()?)
1732        };
1733        Ok(Stmt::Print(item))
1734    }
1735
1736    fn parse_exec(&mut self) -> PResult<Stmt> {
1737        let arg_frame = self.toks[self.idx].arg_frame.clone();
1738        self.expect_kw(Kw::Exec)?;
1739        let command = self.parse_stringexpr()?;
1740        Ok(Stmt::Exec { command, arg_frame })
1741    }
1742
1743    fn parse_reset(&mut self) -> PResult<Stmt> {
1744        self.expect_kw(Kw::Reset)?;
1745        let mut list = Vec::new();
1746        if let Token::EnvVar(v) = self.cur() {
1747            list.push(*v);
1748            self.bump();
1749            while self.eat(&Token::Comma) {
1750                match self.cur() {
1751                    Token::EnvVar(v) => {
1752                        list.push(*v);
1753                        self.bump();
1754                    }
1755                    other => {
1756                        return self.err(format!("expected environment variable, found {other:?}"));
1757                    }
1758                }
1759            }
1760        }
1761        Ok(Stmt::Reset(list))
1762    }
1763
1764    fn at_string_start(&self) -> bool {
1765        self.token_starts_string_at(0)
1766    }
1767
1768    fn parse_animate(&mut self) -> PResult<Animate> {
1769        self.expect_kw(Kw::Animate)?;
1770        let target = self.parse_place()?;
1771        self.expect_kw(Kw::With)?;
1772        let effect_span = Some(self.cur_span());
1773        let effect = self.parse_stringexpr()?;
1774        let mut duration = None;
1775        let mut timing = Timing::Sequential;
1776        let mut delay = None;
1777        loop {
1778            if self.eat_kw(Kw::For) {
1779                duration = Some(self.parse_expr()?);
1780            } else if self.eat_kw(Kw::At) {
1781                timing = Timing::At(self.parse_expr()?);
1782            } else if self.eat_kw(Kw::After) {
1783                timing = Timing::After(self.parse_place()?);
1784            } else if self.eat_kw(Kw::Delay) {
1785                delay = Some(self.parse_expr()?);
1786            } else {
1787                break;
1788            }
1789        }
1790        Ok(Animate {
1791            target,
1792            effect,
1793            effect_span,
1794            duration,
1795            timing,
1796            delay,
1797        })
1798    }
1799
1800    /// True if the current `Label` is followed by `:` (allowing a `[suffix]`).
1801    fn label_colon_ahead(&self) -> bool {
1802        match self.peek(1) {
1803            Token::Colon => true,
1804            Token::LeftBrack => {
1805                // scan past a balanced [ … ] suffix to find ':'
1806                let mut depth = 0;
1807                let mut i = self.idx + 1;
1808                while i < self.toks.len() {
1809                    match &self.toks[i].tok {
1810                        Token::LeftBrack => depth += 1,
1811                        Token::RightBrack => {
1812                            depth -= 1;
1813                            if depth == 0 {
1814                                return matches!(
1815                                    self.toks.get(i + 1).map(|s| &s.tok),
1816                                    Some(Token::Colon)
1817                                );
1818                            }
1819                        }
1820                        Token::Newline | Token::Eof => return false,
1821                        _ => {}
1822                    }
1823                    i += 1;
1824                }
1825                false
1826            }
1827            _ => false,
1828        }
1829    }
1830
1831    fn at_object_start(&self) -> bool {
1832        matches!(
1833            self.cur(),
1834            Token::Prim(_)
1835                | Token::LeftBrack
1836                | Token::Block
1837                | Token::Str(_)
1838                | Token::Arg(_)
1839                | Token::Kw(Kw::Sprintf)
1840        ) || matches!(self.cur(), Token::Name(n) if n == "brace" || n == "dot")
1841    }
1842
1843    fn at_assignment_start(&self) -> bool {
1844        match self.cur() {
1845            Token::Name(_) | Token::Label(_) => self.assignment_op_after_var_ref(),
1846            Token::EnvVar(_) => is_assign_op(self.peek(1)),
1847            _ => false,
1848        }
1849    }
1850
1851    fn assignment_op_after_var_ref(&self) -> bool {
1852        let mut i = self.idx + 1;
1853        if matches!(self.toks.get(i).map(|s| &s.tok), Some(Token::LeftBrack)) {
1854            i += 1;
1855            let mut depth = 1i32;
1856            while let Some(tok) = self.toks.get(i).map(|s| &s.tok) {
1857                match tok {
1858                    Token::LeftBrack => depth += 1,
1859                    Token::RightBrack => {
1860                        depth -= 1;
1861                        if depth == 0 {
1862                            i += 1;
1863                            break;
1864                        }
1865                    }
1866                    Token::Eof | Token::Newline if depth > 0 => return false,
1867                    _ => {}
1868                }
1869                i += 1;
1870            }
1871            if depth != 0 {
1872                return false;
1873            }
1874        }
1875        self.toks.get(i).is_some_and(|s| is_assign_op(&s.tok))
1876    }
1877
1878    fn parse_label(&mut self) -> PResult<Label> {
1879        let name = match self.bump() {
1880            Token::Label(s) => s,
1881            other => return self.err(format!("expected label, found {other:?}")),
1882        };
1883        let subscript = if self.eat(&Token::LeftBrack) {
1884            let e = self.parse_subscript()?;
1885            self.expect(&Token::RightBrack)?;
1886            Some(e)
1887        } else {
1888            None
1889        };
1890        Ok(Label { name, subscript })
1891    }
1892
1893    fn parse_assignlist(&mut self) -> PResult<Vec<Assignment>> {
1894        let mut list = vec![self.parse_assignment()?];
1895        while self.eat(&Token::Comma) {
1896            list.push(self.parse_assignment()?);
1897        }
1898        Ok(list)
1899    }
1900
1901    fn parse_assignment(&mut self) -> PResult<Assignment> {
1902        let target = match self.cur().clone() {
1903            Token::Name(name) | Token::Label(name) => {
1904                self.bump();
1905                let sub = if self.eat(&Token::LeftBrack) {
1906                    let e = self.parse_subscript()?;
1907                    self.expect(&Token::RightBrack)?;
1908                    Some(e)
1909                } else {
1910                    None
1911                };
1912                AssignTarget::Var(name, sub)
1913            }
1914            Token::EnvVar(v) => {
1915                self.bump();
1916                AssignTarget::Env(v)
1917            }
1918            other => return self.err(format!("expected assignment target, found {other:?}")),
1919        };
1920        let op = match self.bump() {
1921            Token::Eq => AssignOp::Set,
1922            Token::ColonEq => AssignOp::ColonSet,
1923            Token::PlusEq => AssignOp::Add,
1924            Token::MinusEq => AssignOp::Sub,
1925            Token::MultEq => AssignOp::Mul,
1926            Token::DivEq => AssignOp::Div,
1927            Token::RemEq => AssignOp::Rem,
1928            other => return self.err(format!("expected assignment operator, found {other:?}")),
1929        };
1930        let value = self.parse_expr()?;
1931        Ok(Assignment { target, op, value })
1932    }
1933
1934    fn parse_subscript(&mut self) -> PResult<Expr> {
1935        let mut items = vec![self.parse_expr()?];
1936        while self.eat(&Token::Comma) {
1937            items.push(self.parse_expr()?);
1938        }
1939        if items.len() == 1 {
1940            Ok(items.pop().unwrap())
1941        } else {
1942            Ok(Expr::Index(items))
1943        }
1944    }
1945
1946    // ---- objects & attributes ---------------------------------------------
1947
1948    fn parse_object(&mut self) -> PResult<Object> {
1949        let mut attrs = Vec::new();
1950        // a bare string expression (literal, `$arg`, sprintf, concatenation)
1951        // places a text-only object.
1952        if self.at_string_start() {
1953            attrs.push(Attr::Text(self.parse_stringexpr()?));
1954            while let Some(a) = self.parse_attr(false, false, false, false)? {
1955                attrs.push(a);
1956            }
1957            return Ok(Object {
1958                kind: ObjectKind::Text,
1959                attrs,
1960            });
1961        }
1962        let kind = match self.cur().clone() {
1963            Token::Prim(p) => {
1964                self.bump();
1965                ObjectKind::Primitive(p)
1966            }
1967            Token::Block => {
1968                self.bump();
1969                ObjectKind::Empty
1970            }
1971            Token::Name(n) if n == "brace" => {
1972                self.bump();
1973                ObjectKind::Brace
1974            }
1975            Token::Name(n) if n == "dot" => {
1976                self.bump();
1977                ObjectKind::Dot
1978            }
1979            Token::LeftBrack => {
1980                self.bump();
1981                let stmts = self.parse_elementlist(&[Token::RightBrack])?;
1982                self.expect(&Token::RightBrack)?;
1983                ObjectKind::Block(stmts)
1984            }
1985            Token::Str(s) => {
1986                self.bump();
1987                attrs.push(Attr::Text(self.continue_string(StringExpr::Lit(s))?));
1988                ObjectKind::Text
1989            }
1990            Token::Kw(Kw::Continue) => {
1991                self.bump();
1992                ObjectKind::Continue
1993            }
1994            Token::Name(_) | Token::Label(_) => return self.expected_object(),
1995            _ => return self.expected_here("an object"),
1996        };
1997        // `spline <expr> <linespec>`: dpic's documented exception to the bare
1998        // distance rule — the expression right after `spline` is a tension
1999        // parameter, not a length. Parse it here so the attribute loop below
2000        // doesn't read it as `Attr::Dist`.
2001        if matches!(kind, ObjectKind::Primitive(Prim::Spline)) && self.spline_tension_ahead() {
2002            attrs.push(Attr::SplineTension(self.parse_expr()?));
2003        }
2004        let allow_fit = matches!(
2005            kind,
2006            ObjectKind::Primitive(Prim::Box | Prim::Circle | Prim::Ellipse)
2007        );
2008        let allow_brace = matches!(kind, ObjectKind::Brace);
2009        let allow_dot_fill = matches!(kind, ObjectKind::Dot);
2010        let allow_hatch = matches!(
2011            kind,
2012            ObjectKind::Primitive(
2013                Prim::Box
2014                    | Prim::Circle
2015                    | Prim::Ellipse
2016                    | Prim::Line
2017                    | Prim::Arrow
2018                    | Prim::Spline
2019                    | Prim::Arc
2020            )
2021        );
2022        let allow_close = matches!(kind, ObjectKind::Primitive(Prim::Line));
2023        while let Some(a) = self.parse_attr(
2024            allow_fit,
2025            allow_brace,
2026            allow_hatch || allow_dot_fill,
2027            allow_close,
2028        )? {
2029            attrs.push(a);
2030        }
2031        Ok(Object { kind, attrs })
2032    }
2033
2034    /// True if the next token begins a bare scalar expression — the leading
2035    /// tension argument of `spline <expr>` — rather than a linespec keyword
2036    /// (`from`/`to`/`up`/`then`/…) or another attribute.
2037    fn spline_tension_ahead(&self) -> bool {
2038        matches!(
2039            self.cur(),
2040            Token::Float(_)
2041                | Token::Lparen
2042                | Token::EnvVar(_)
2043                | Token::Func1(_)
2044                | Token::Func2(_)
2045                | Token::Name(_)
2046                | Token::Minus
2047                | Token::Plus
2048                | Token::Kw(Kw::Rand)
2049        )
2050    }
2051
2052    fn parse_attr(
2053        &mut self,
2054        allow_fit: bool,
2055        allow_brace: bool,
2056        allow_hatch: bool,
2057        allow_close: bool,
2058    ) -> PResult<Option<Attr>> {
2059        // any string expression (literal, sprintf, $arg, concatenation) is text
2060        if self.at_string_start() {
2061            return Ok(Some(Attr::Text(self.parse_stringexpr()?)));
2062        }
2063        let attr = match self.cur().clone() {
2064            Token::Kw(Kw::Ht) => {
2065                self.bump();
2066                Attr::Dim(DimKind::Ht, self.parse_expr()?)
2067            }
2068            Token::Kw(Kw::Wid) => {
2069                self.bump();
2070                Attr::Dim(DimKind::Wid, self.parse_expr()?)
2071            }
2072            Token::Kw(Kw::Rad) => {
2073                self.bump();
2074                Attr::Dim(DimKind::Rad, self.parse_expr()?)
2075            }
2076            Token::Kw(Kw::Diam) => {
2077                self.bump();
2078                Attr::Dim(DimKind::Diam, self.parse_expr()?)
2079            }
2080            Token::Kw(Kw::Thick) => {
2081                self.bump();
2082                Attr::Dim(DimKind::Thick, self.parse_expr()?)
2083            }
2084            Token::Kw(Kw::Scaled) => {
2085                self.bump();
2086                Attr::Dim(DimKind::Scaled, self.parse_expr()?)
2087            }
2088            Token::Dir(d) => {
2089                self.bump();
2090                Attr::Direction(
2091                    d,
2092                    self.opt_attr_expr(allow_fit, allow_brace, allow_hatch, allow_close)?,
2093                )
2094            }
2095            Token::LineType(lt) => {
2096                self.bump();
2097                Attr::LineStyle(
2098                    lt,
2099                    self.opt_attr_expr(allow_fit, allow_brace, allow_hatch, allow_close)?,
2100                )
2101            }
2102            Token::Kw(Kw::Chop) => {
2103                self.bump();
2104                Attr::Chop(self.opt_attr_expr(allow_fit, allow_brace, allow_hatch, allow_close)?)
2105            }
2106            Token::Kw(Kw::Fill) => {
2107                self.bump();
2108                Attr::Fill(self.opt_attr_expr(allow_fit, allow_brace, allow_hatch, allow_close)?)
2109            }
2110            Token::Arrow(a) => {
2111                self.bump();
2112                Attr::Arrowhead(
2113                    a,
2114                    self.opt_attr_expr(allow_fit, allow_brace, allow_hatch, allow_close)?,
2115                )
2116            }
2117            Token::Kw(Kw::Then) => {
2118                self.bump();
2119                Attr::Then
2120            }
2121            Token::Kw(Kw::Cw) => {
2122                self.bump();
2123                Attr::Cw
2124            }
2125            Token::Kw(Kw::Ccw) => {
2126                self.bump();
2127                Attr::Ccw
2128            }
2129            Token::Kw(Kw::Same) => {
2130                self.bump();
2131                Attr::Same
2132            }
2133            Token::Kw(Kw::Continue) => {
2134                self.bump();
2135                Attr::Continue
2136            }
2137            Token::Kw(Kw::From) => {
2138                self.bump();
2139                Attr::From(self.parse_position()?)
2140            }
2141            Token::Kw(Kw::To) => {
2142                self.bump();
2143                Attr::To(self.parse_position()?)
2144            }
2145            Token::Kw(Kw::At) => {
2146                self.bump();
2147                Attr::At(self.parse_position()?)
2148            }
2149            Token::Kw(Kw::By) => {
2150                self.bump();
2151                Attr::By(self.parse_position()?)
2152            }
2153            Token::Kw(Kw::With) => {
2154                self.bump();
2155                let anchor = if self.eat(&Token::Dot) {
2156                    WithAnchor::Place(self.parse_place()?)
2157                } else if let Token::Corner(c) = self.cur() {
2158                    let c = *c;
2159                    self.bump();
2160                    WithAnchor::Corner(c)
2161                } else if self.at(&Token::Lparen) {
2162                    self.bump();
2163                    let x = self.parse_expr()?;
2164                    self.expect(&Token::Comma)?;
2165                    let y = self.parse_expr()?;
2166                    self.expect(&Token::Rparen)?;
2167                    WithAnchor::Pair(x, y)
2168                } else {
2169                    WithAnchor::Plain
2170                };
2171                self.expect_kw(Kw::At)?;
2172                Attr::With {
2173                    anchor,
2174                    at: self.parse_position()?,
2175                }
2176            }
2177            Token::TextPos(tp) => {
2178                self.bump();
2179                Attr::TextPos(tp)
2180            }
2181            Token::Color(c) => {
2182                self.bump();
2183                // a colour may be a quoted string or a bareword name (e.g.
2184                // `shaded Custom`, `outlined red`).
2185                let s = match self.cur().clone() {
2186                    Token::Name(n) | Token::Label(n) => {
2187                        self.bump();
2188                        StringExpr::Lit(n)
2189                    }
2190                    _ => self.parse_stringexpr()?,
2191                };
2192                Attr::Color(c, s)
2193            }
2194            Token::Name(n) if allow_fit && n == "fit" => {
2195                self.bump();
2196                Attr::Fit
2197            }
2198            Token::Name(n) if allow_hatch && n == "hatch" => {
2199                self.bump();
2200                Attr::Hatch(HatchKind::Single)
2201            }
2202            Token::Name(n) if allow_hatch && n == "crosshatch" => {
2203                self.bump();
2204                Attr::Hatch(HatchKind::Cross)
2205            }
2206            Token::Name(n) if allow_hatch && n == "hatchangle" => {
2207                self.bump();
2208                Attr::HatchAngle(self.parse_expr()?)
2209            }
2210            Token::Name(n) if allow_hatch && n == "hatchsep" => {
2211                self.bump();
2212                Attr::HatchSep(self.parse_expr()?)
2213            }
2214            Token::Name(n) if allow_hatch && (n == "hatchwid" || n == "hatchwidth") => {
2215                self.bump();
2216                Attr::HatchWidth(self.parse_expr()?)
2217            }
2218            Token::Name(n) if allow_hatch && n == "hatchcolor" => {
2219                self.bump();
2220                let s = match self.cur().clone() {
2221                    Token::Name(n) | Token::Label(n) => {
2222                        self.bump();
2223                        StringExpr::Lit(n)
2224                    }
2225                    _ => self.parse_stringexpr()?,
2226                };
2227                Attr::HatchColor(s)
2228            }
2229            Token::Name(n) if allow_hatch && n == "gradient" => {
2230                self.bump();
2231                let from = self.parse_color_like()?;
2232                let to = self.parse_color_like()?;
2233                Attr::Gradient(from, to)
2234            }
2235            Token::Name(n) if allow_hatch && n == "gradientangle" => {
2236                self.bump();
2237                Attr::GradientAngle(self.parse_expr()?)
2238            }
2239            Token::Name(n) if n == "opacity" => {
2240                self.bump();
2241                Attr::Opacity(self.parse_expr()?)
2242            }
2243            Token::Name(n) if allow_close && n == "close" => {
2244                self.bump();
2245                Attr::Close
2246            }
2247            Token::Name(n) if allow_brace && n == "bracepos" => {
2248                self.bump();
2249                Attr::BracePos(self.parse_expr()?)
2250            }
2251            Token::Name(n) if allow_brace && n == "labeloffset" => {
2252                self.bump();
2253                Attr::BraceLabelOffset(self.parse_expr()?)
2254            }
2255            Token::Name(n) if n == "behind" => {
2256                self.bump();
2257                Attr::Behind(self.parse_place()?)
2258            }
2259            Token::Name(n) if n == "class" => {
2260                self.bump();
2261                Attr::Class(self.parse_stringexpr()?)
2262            }
2263            // a bare expression distance with no direction word, e.g. `move 1`,
2264            // `move -0.1`, `spline x` (length in the prevailing direction)
2265            Token::Float(_)
2266            | Token::Lparen
2267            | Token::EnvVar(_)
2268            | Token::Func1(_)
2269            | Token::Func2(_)
2270            | Token::Name(_)
2271            | Token::Minus
2272            | Token::Plus
2273            | Token::Kw(Kw::Rand) => {
2274                let span = self.cur_span();
2275                Attr::Dist(self.parse_expr()?, Some(span))
2276            }
2277            _ if self.place_is_scalar_ahead() => {
2278                let span = self.cur_span();
2279                Attr::Dist(self.parse_expr()?, Some(span))
2280            }
2281            _ => return Ok(None),
2282        };
2283        Ok(Some(attr))
2284    }
2285
2286    fn expect_kw(&mut self, k: Kw) -> PResult<()> {
2287        if self.eat_kw(k) {
2288            Ok(())
2289        } else {
2290            self.expected_here(kw_text(k))
2291        }
2292    }
2293
2294    // ---- string expressions ------------------------------------------------
2295
2296    fn parse_stringexpr(&mut self) -> PResult<StringExpr> {
2297        let first = self.parse_string_atom()?;
2298        self.continue_string(first)
2299    }
2300
2301    /// Continue a string expression with trailing `+ string` parts.
2302    fn continue_string(&mut self, first: StringExpr) -> PResult<StringExpr> {
2303        let mut e = first;
2304        while self.at(&Token::Plus) && self.string_after_plus() {
2305            self.bump();
2306            let rhs = self.parse_string_atom()?;
2307            e = StringExpr::Concat(Box::new(e), Box::new(rhs));
2308        }
2309        Ok(e)
2310    }
2311
2312    fn string_after_plus(&self) -> bool {
2313        self.token_starts_string_at(1)
2314    }
2315
2316    fn token_starts_string_at(&self, offset: usize) -> bool {
2317        match self.toks.get(self.idx + offset).map(|s| &s.tok) {
2318            Some(Token::Str(_) | Token::Arg(_) | Token::Kw(Kw::Sprintf)) => true,
2319            Some(Token::Name(n)) if n == "svg_font" => {
2320                matches!(
2321                    self.toks.get(self.idx + offset + 1).map(|s| &s.tok),
2322                    Some(Token::Lparen)
2323                )
2324            }
2325            _ => false,
2326        }
2327    }
2328
2329    fn parse_string_atom(&mut self) -> PResult<StringExpr> {
2330        match self.cur().clone() {
2331            Token::Str(s) => {
2332                self.bump();
2333                Ok(StringExpr::Lit(s))
2334            }
2335            Token::Arg(n) => {
2336                self.bump();
2337                Ok(StringExpr::Arg(n))
2338            }
2339            Token::Kw(Kw::Sprintf) => {
2340                self.bump();
2341                self.expect(&Token::Lparen)?;
2342                let fmt = self.parse_stringexpr()?;
2343                let mut args = Vec::new();
2344                while self.eat(&Token::Comma) {
2345                    args.push(self.parse_expr()?);
2346                }
2347                self.expect(&Token::Rparen)?;
2348                Ok(StringExpr::Sprintf(Box::new(fmt), args))
2349            }
2350            Token::Name(n) if n == "svg_font" && matches!(self.peek(1), Token::Lparen) => {
2351                self.bump();
2352                self.expect(&Token::Lparen)?;
2353                let mut args = Vec::new();
2354                if !self.at(&Token::Rparen) {
2355                    args.push(self.parse_expr()?);
2356                    while self.eat(&Token::Comma) {
2357                        args.push(self.parse_expr()?);
2358                    }
2359                }
2360                self.expect(&Token::Rparen)?;
2361                Ok(StringExpr::SvgFont(args))
2362            }
2363            other => self.err(format!("expected a string, found {other:?}")),
2364        }
2365    }
2366
2367    // ---- positions ---------------------------------------------------------
2368
2369    fn parse_label_position(&mut self) -> PResult<Position> {
2370        let save = self.idx;
2371        if let Ok(x) = self.parse_expr()
2372            && self.eat(&Token::Comma)
2373        {
2374            let y = self.parse_expr()?;
2375            return Ok(Position::Pair(x, y));
2376        }
2377        self.idx = save;
2378        self.parse_position()
2379    }
2380
2381    /// Positions support vector arithmetic; `+`/`-` are the lowest precedence.
2382    fn parse_position(&mut self) -> PResult<Position> {
2383        let mut left = self.parse_pos_mul()?;
2384        loop {
2385            let sign = if self.at(&Token::Plus) {
2386                Sign::Plus
2387            } else if self.at(&Token::Minus) {
2388                Sign::Minus
2389            } else {
2390                break;
2391            };
2392            self.bump();
2393            let right = self.parse_pos_mul()?;
2394            left = Position::Sum(sign, Box::new(left), Box::new(right));
2395        }
2396        Ok(left)
2397    }
2398
2399    /// Scaling a position by a scalar: `p * s`, `p / s` (binds tighter than ±).
2400    fn parse_pos_mul(&mut self) -> PResult<Position> {
2401        let mut left = self.parse_pos_primary()?;
2402        loop {
2403            if self.eat(&Token::Mult) {
2404                left = Position::Scale(Box::new(left), self.parse_unary()?, false);
2405            } else if self.eat(&Token::Div) {
2406                left = Position::Scale(Box::new(left), self.parse_unary()?, true);
2407            } else {
2408                break;
2409            }
2410        }
2411        Ok(left)
2412    }
2413
2414    fn parse_pos_primary(&mut self) -> PResult<Position> {
2415        // A fraction-led interpolation — `frac between A and B`, `frac <p,p>`, or
2416        // `frac of the way between A and B`. The fraction can be parenthesised
2417        // (e.g. `(X/Y) between A and B`), so try it before the `(`/place branches.
2418        if let Some(p) = self.try_fraction()? {
2419            return Ok(p);
2420        }
2421        // `( … )`: coordinate pair `(x,y)` of scalar expressions, a
2422        // parenthesised position, or `(pos, pos)` — x of the first, y of the
2423        // second. Try a scalar pair first so components that are themselves
2424        // parenthesised scalars (e.g. `((a*g)*cos(t), …)`) parse correctly.
2425        if self.eat(&Token::Lparen) {
2426            let save = self.idx;
2427            // Prefer parsing the contents as position(s) — handles `(A, B.c)`,
2428            // `(pos, pos)`, `(2,3)`, `(0.5 between A and B)`. If that fails, the
2429            // contents are scalar coordinate expressions that the position
2430            // grammar can't represent alone (e.g. `((a*g)*cos t, (a*g)*sin t)`).
2431            if let Ok(p1) = self.parse_position() {
2432                let p = if self.eat(&Token::Comma) {
2433                    let p2 = self.parse_position()?;
2434                    Position::Place(Location::ParenPair(Box::new(p1), Box::new(p2)))
2435                } else {
2436                    p1 // drop the redundant parentheses
2437                };
2438                self.expect(&Token::Rparen)?;
2439                return Ok(p);
2440            }
2441            self.idx = save;
2442            let e1 = self.parse_add()?;
2443            self.expect(&Token::Comma)?;
2444            let e2 = self.parse_add()?;
2445            self.expect(&Token::Rparen)?;
2446            return Ok(Position::Pair(e1, e2));
2447        }
2448        // A leading place is point-valued UNLESS it is a scalar accessor
2449        // (`place.x` / `.y` / `.attr`), which begins an `(expr, expr)` pair.
2450        if self.at_place_start() && !self.place_is_scalar_ahead() {
2451            return Ok(Position::Place(Location::Place(self.parse_place()?)));
2452        }
2453        // expression-led coordinate pair `x, y` (interpolation handled above)
2454        let e1 = self.parse_add()?;
2455        if self.eat(&Token::Comma) {
2456            let e2 = self.parse_add()?;
2457            return Ok(Position::Pair(e1, e2));
2458        }
2459        self.err("expected `,`, `between`, or `of the way between` in position")
2460    }
2461
2462    /// Try to parse `frac (between | <p,p> | of the way between)`; if the leading
2463    /// expression isn't followed by an interpolation, backtrack and return `None`
2464    /// so the caller can parse a plain place / pair / parenthesised position.
2465    fn try_fraction(&mut self) -> PResult<Option<Position>> {
2466        let save = self.idx;
2467        let Ok(frac) = self.parse_add() else {
2468            self.idx = save;
2469            return Ok(None);
2470        };
2471        let mk = |frac, a, b, of_the_way| {
2472            Ok(Some(Position::Between {
2473                frac: Box::new(frac),
2474                a: Box::new(a),
2475                b: Box::new(b),
2476                of_the_way,
2477            }))
2478        };
2479        if self.eat(&Token::Lt) {
2480            let a = self.parse_position()?;
2481            self.expect(&Token::Comma)?;
2482            let b = self.parse_position()?;
2483            self.expect(&Token::Gt)?;
2484            return mk(frac, a, b, false);
2485        }
2486        let of_the_way = if self.at_kw(Kw::Of) {
2487            self.eat_kw(Kw::Of);
2488            if !(self.eat_kw(Kw::The) && self.eat_kw(Kw::Way) && self.eat_kw(Kw::Between)) {
2489                self.idx = save;
2490                return Ok(None);
2491            }
2492            true
2493        } else if self.eat_kw(Kw::Between) {
2494            false
2495        } else {
2496            self.idx = save;
2497            return Ok(None);
2498        };
2499        let a = self.parse_position()?;
2500        self.expect_kw(Kw::And)?;
2501        let b = self.parse_position()?;
2502        mk(frac, a, b, of_the_way)
2503    }
2504
2505    /// Lookahead: does the upcoming place end in a scalar accessor
2506    /// (`.x` / `.y` / `.attr`)? If so it is a number, not a point. Non-consuming.
2507    fn place_is_scalar_ahead(&mut self) -> bool {
2508        let save = self.idx;
2509        let parsed = self.parse_place().is_ok();
2510        let scalar = parsed && matches!(self.cur(), Token::DotX | Token::DotY | Token::Param(_));
2511        self.idx = save;
2512        scalar
2513    }
2514
2515    fn at_place_start(&self) -> bool {
2516        match self.cur() {
2517            Token::Label(_) | Token::Block | Token::Corner(_) => true,
2518            Token::Kw(Kw::Last) | Token::Kw(Kw::Here) => true,
2519            Token::Float(_) => matches!(self.peek(1), Token::Kw(Kw::Nth)),
2520            // `{expr}th …` / `` `expr`th … `` ordinal counts (only valid as a
2521            // place in position/expression context, never a group here)
2522            Token::LeftBrace | Token::LeftQuote => true,
2523            _ => false,
2524        }
2525    }
2526
2527    fn parse_place(&mut self) -> PResult<Place> {
2528        // `corner [of] placename`
2529        if let Token::Corner(c) = self.cur() {
2530            let c = *c;
2531            self.bump();
2532            self.eat_kw(Kw::Of);
2533            let inner = self.parse_place()?;
2534            return Ok(Place::CornerOf(c, Box::new(inner)));
2535        }
2536
2537        let mut place = self.parse_place_base()?;
2538
2539        // trailing `.corner`, `.label`, `.nth primobj`
2540        loop {
2541            if let Token::Corner(c) = self.cur() {
2542                let c = *c;
2543                self.bump();
2544                place = Place::Corner(Box::new(place), c);
2545            } else if self.at(&Token::Dot) {
2546                self.bump();
2547                let rhs = self.parse_place_base()?;
2548                place = Place::Member(Box::new(place), Box::new(rhs));
2549            } else {
2550                break;
2551            }
2552        }
2553        Ok(place)
2554    }
2555
2556    fn parse_place_base(&mut self) -> PResult<Place> {
2557        match self.cur().clone() {
2558            Token::Kw(Kw::Here) => {
2559                self.bump();
2560                Ok(Place::Here)
2561            }
2562            Token::Label(name) => {
2563                let span = Some(self.cur_span());
2564                self.bump();
2565                let subscript = if self.eat(&Token::LeftBrack) {
2566                    let e = self.parse_subscript()?;
2567                    self.expect(&Token::RightBrack)?;
2568                    Some(Box::new(e))
2569                } else {
2570                    None
2571                };
2572                Ok(Place::Name {
2573                    name,
2574                    subscript,
2575                    span,
2576                })
2577            }
2578            Token::Kw(Kw::Last) | Token::Float(_) | Token::LeftBrace | Token::LeftQuote => {
2579                let span = Some(self.cur_span());
2580                let count = self.parse_nth()?;
2581                // A type keyword may follow (`last box`); without one, this is an
2582                // untyped reference to the most recent object of any kind
2583                // (`last`, `last.c`, `2nd last.n`).
2584                let obj = if self.at_primobj() {
2585                    self.parse_primobj()?
2586                } else {
2587                    PrimObj::Any
2588                };
2589                Ok(Place::Nth { count, obj, span })
2590            }
2591            other => self.err(format!("expected a place, found {other:?}")),
2592        }
2593    }
2594
2595    fn parse_nth(&mut self) -> PResult<Nth> {
2596        if self.eat_kw(Kw::Last) {
2597            return Ok(Nth::Last);
2598        }
2599        // ncount ordinal [last]
2600        let e = self.parse_ncount()?;
2601        self.expect_kw(Kw::Nth)?;
2602        let from_last = self.eat_kw(Kw::Last);
2603        Ok(Nth::Count(Box::new(e), from_last))
2604    }
2605
2606    /// An ordinal count: a number, `` `expr' ``, or `{ expr }` (grammar:
2607    /// `ncount`). Must NOT recurse into the general expression grammar on a
2608    /// bare number, or `2nd` would re-enter place parsing.
2609    fn parse_ncount(&mut self) -> PResult<Expr> {
2610        match self.cur().clone() {
2611            Token::Float(v) => {
2612                self.bump();
2613                Ok(Expr::Num(v))
2614            }
2615            Token::LeftBrace => {
2616                self.bump();
2617                let e = self.parse_expr()?;
2618                self.expect(&Token::RightBrace)?;
2619                Ok(e)
2620            }
2621            Token::LeftQuote => {
2622                self.bump();
2623                let e = self.parse_expr()?;
2624                self.expect(&Token::RightQuote)?;
2625                Ok(e)
2626            }
2627            other => self.err(format!("expected an ordinal count, found {other:?}")),
2628        }
2629    }
2630
2631    /// Whether the current token can begin a primitive-object type keyword
2632    /// (`box`, `[`, a string, …) — i.e. an explicit type after `last`/ordinal.
2633    fn at_primobj(&self) -> bool {
2634        matches!(
2635            self.cur(),
2636            Token::Prim(_) | Token::Block | Token::Str(_) | Token::LeftBrack
2637        ) || matches!(self.cur(), Token::Name(n) if n == "brace")
2638    }
2639
2640    fn parse_primobj(&mut self) -> PResult<PrimObj> {
2641        match self.cur().clone() {
2642            Token::Prim(p) => {
2643                self.bump();
2644                Ok(PrimObj::Prim(p))
2645            }
2646            Token::Name(n) if n == "brace" => {
2647                self.bump();
2648                Ok(PrimObj::Brace)
2649            }
2650            Token::Block => {
2651                self.bump();
2652                Ok(PrimObj::Block)
2653            }
2654            Token::Str(s) => {
2655                self.bump();
2656                Ok(PrimObj::Str(s))
2657            }
2658            Token::LeftBrack => {
2659                self.bump();
2660                self.expect(&Token::RightBrack)?;
2661                Ok(PrimObj::EmptyBrack)
2662            }
2663            other => self.err(format!("expected a primitive object, found {other:?}")),
2664        }
2665    }
2666
2667    // ---- expressions -------------------------------------------------------
2668
2669    fn opt_expr(&mut self) -> PResult<Option<Expr>> {
2670        if self.starts_scalar() || self.place_is_scalar_ahead() {
2671            Ok(Some(self.parse_expr()?))
2672        } else {
2673            Ok(None)
2674        }
2675    }
2676
2677    /// A color argument: a bare name (`red`), a label-cased name, or any
2678    /// string expression — the same grammar `hatchcolor` accepts.
2679    fn parse_color_like(&mut self) -> PResult<StringExpr> {
2680        match self.cur().clone() {
2681            Token::Name(n) | Token::Label(n) => {
2682                self.bump();
2683                Ok(StringExpr::Lit(n))
2684            }
2685            _ => self.parse_stringexpr(),
2686        }
2687    }
2688
2689    fn opt_attr_expr(
2690        &mut self,
2691        allow_fit: bool,
2692        allow_brace: bool,
2693        allow_hatch: bool,
2694        allow_close: bool,
2695    ) -> PResult<Option<Expr>> {
2696        if self.contextual_attr_ahead(allow_fit, allow_brace, allow_hatch, allow_close) {
2697            Ok(None)
2698        } else {
2699            self.opt_expr()
2700        }
2701    }
2702
2703    fn contextual_attr_ahead(
2704        &self,
2705        allow_fit: bool,
2706        allow_brace: bool,
2707        allow_hatch: bool,
2708        allow_close: bool,
2709    ) -> bool {
2710        matches!(
2711            self.cur(),
2712            Token::Name(n)
2713                if (allow_fit && n == "fit")
2714                    || (allow_hatch
2715                        && matches!(
2716                            n.as_str(),
2717                            "hatch"
2718                                | "crosshatch"
2719                                | "hatchangle"
2720                                | "hatchsep"
2721                                | "hatchwid"
2722                                | "hatchwidth"
2723                                | "hatchcolor"
2724                                | "gradient"
2725                                | "gradientangle"
2726                        ))
2727                    || n == "opacity"
2728                    || (allow_brace && matches!(n.as_str(), "bracepos" | "labeloffset"))
2729                    || n == "behind"
2730                    || n == "class"
2731                    || (allow_close && n == "close")
2732        )
2733    }
2734
2735    fn starts_scalar(&self) -> bool {
2736        matches!(
2737            self.cur(),
2738            Token::Float(_)
2739                | Token::Name(_)
2740                | Token::EnvVar(_)
2741                | Token::Lparen
2742                | Token::Minus
2743                | Token::Plus
2744                | Token::Not
2745                | Token::Func1(_)
2746                | Token::Func2(_)
2747                | Token::Kw(Kw::Rand)
2748                | Token::ArgCount
2749        )
2750    }
2751
2752    fn parse_expr(&mut self) -> PResult<Expr> {
2753        self.parse_or()
2754    }
2755
2756    fn parse_or(&mut self) -> PResult<Expr> {
2757        let mut e = self.parse_and()?;
2758        while self.eat(&Token::OrOr) {
2759            let r = self.parse_and()?;
2760            e = Expr::Bin(BinOp::Or, Box::new(e), Box::new(r));
2761        }
2762        Ok(e)
2763    }
2764
2765    fn parse_and(&mut self) -> PResult<Expr> {
2766        let mut e = self.parse_cmp()?;
2767        while self.eat(&Token::AndAnd) {
2768            let r = self.parse_cmp()?;
2769            e = Expr::Bin(BinOp::And, Box::new(e), Box::new(r));
2770        }
2771        Ok(e)
2772    }
2773
2774    fn parse_cmp(&mut self) -> PResult<Expr> {
2775        let mut e = self.parse_add()?;
2776        loop {
2777            let op = match self.cur() {
2778                Token::EqEq => BinOp::Eq,
2779                Token::Neq => BinOp::Ne,
2780                Token::Lt => BinOp::Lt,
2781                Token::Le => BinOp::Le,
2782                Token::Gt => BinOp::Gt,
2783                Token::Ge => BinOp::Ge,
2784                _ => break,
2785            };
2786            self.bump();
2787            let r = self.parse_add()?;
2788            e = Expr::Bin(op, Box::new(e), Box::new(r));
2789        }
2790        Ok(e)
2791    }
2792
2793    fn parse_add(&mut self) -> PResult<Expr> {
2794        let mut e = self.parse_mul()?;
2795        loop {
2796            let op = match self.cur() {
2797                Token::Plus => BinOp::Add,
2798                Token::Minus => BinOp::Sub,
2799                _ => break,
2800            };
2801            self.bump();
2802            let r = self.parse_mul()?;
2803            e = Expr::Bin(op, Box::new(e), Box::new(r));
2804        }
2805        Ok(e)
2806    }
2807
2808    fn parse_mul(&mut self) -> PResult<Expr> {
2809        let mut e = self.parse_unary()?;
2810        loop {
2811            let op = match self.cur() {
2812                Token::Mult => BinOp::Mul,
2813                Token::Div => BinOp::Div,
2814                Token::Percent => BinOp::Mod,
2815                _ => break,
2816            };
2817            self.bump();
2818            let r = self.parse_unary()?;
2819            e = Expr::Bin(op, Box::new(e), Box::new(r));
2820        }
2821        Ok(e)
2822    }
2823
2824    fn parse_unary(&mut self) -> PResult<Expr> {
2825        let op = match self.cur() {
2826            Token::Minus => Some(UnOp::Neg),
2827            Token::Plus => Some(UnOp::Pos),
2828            Token::Not => Some(UnOp::Not),
2829            _ => None,
2830        };
2831        if let Some(op) = op {
2832            self.bump();
2833            let e = self.parse_unary()?;
2834            Ok(Expr::Unary(op, Box::new(e)))
2835        } else {
2836            self.parse_pow()
2837        }
2838    }
2839
2840    fn parse_pow(&mut self) -> PResult<Expr> {
2841        let base = self.parse_primary()?;
2842        if self.eat(&Token::Caret) {
2843            let exp = self.parse_unary()?; // right-associative
2844            Ok(Expr::Bin(BinOp::Pow, Box::new(base), Box::new(exp)))
2845        } else {
2846            Ok(base)
2847        }
2848    }
2849
2850    /// Lookahead from just inside a `(`: is the matching `)` immediately followed
2851    /// by `.x` or `.y`? (Used to read `( position ).x` as a coordinate.)
2852    fn paren_followed_by_dot_xy(&self) -> bool {
2853        let mut depth = 1i32;
2854        let mut i = self.idx;
2855        while let Some(s) = self.toks.get(i) {
2856            match &s.tok {
2857                Token::Lparen => depth += 1,
2858                Token::Rparen => {
2859                    depth -= 1;
2860                    if depth == 0 {
2861                        return matches!(
2862                            self.toks.get(i + 1).map(|t| &t.tok),
2863                            Some(Token::DotX | Token::DotY)
2864                        );
2865                    }
2866                }
2867                Token::Eof => return false,
2868                _ => {}
2869            }
2870            i += 1;
2871        }
2872        false
2873    }
2874
2875    fn parse_primary(&mut self) -> PResult<Expr> {
2876        // place-derived scalars: location.x / location.y / place.attr
2877        if self.at_place_start() && self.place_is_scalar_ahead() {
2878            return self.parse_place_scalar();
2879        }
2880        // a string operand (only meaningful as an `==`/`!=` operand)
2881        if self.at_string_start() {
2882            return Ok(Expr::Str(self.parse_stringexpr()?));
2883        }
2884        match self.cur().clone() {
2885            Token::Float(v) => {
2886                self.bump();
2887                Ok(Expr::Num(v))
2888            }
2889            Token::Name(name) | Token::Label(name) => {
2890                self.bump();
2891                let subscript = if self.eat(&Token::LeftBrack) {
2892                    let e = self.parse_subscript()?;
2893                    self.expect(&Token::RightBrack)?;
2894                    Some(Box::new(e))
2895                } else {
2896                    None
2897                };
2898                Ok(Expr::Var(name, subscript))
2899            }
2900            Token::EnvVar(v) => {
2901                self.bump();
2902                Ok(Expr::Env(v))
2903            }
2904            Token::Lparen => {
2905                self.bump();
2906                // embedded assignment `( name = expr )` yields the assigned value
2907                if matches!(self.cur(), Token::Name(_) | Token::Label(_))
2908                    && self.assignment_op_after_var_ref()
2909                {
2910                    let name = match self.bump() {
2911                        Token::Name(n) | Token::Label(n) => n,
2912                        _ => unreachable!(),
2913                    };
2914                    let subscript = if self.eat(&Token::LeftBrack) {
2915                        let e = self.parse_subscript()?;
2916                        self.expect(&Token::RightBrack)?;
2917                        Some(Box::new(e))
2918                    } else {
2919                        None
2920                    };
2921                    self.bump(); // `=`
2922                    let v = self.parse_expr()?;
2923                    self.expect(&Token::Rparen)?;
2924                    return Ok(Expr::Assign(name, subscript, Box::new(v)));
2925                }
2926                // `( position ).x` / `.y` — a coordinate of a parenthesised
2927                // position (e.g. `(A - B).x`, `($1-($2)).y`). Chosen by lookahead
2928                // for a trailing `.x`/`.y`, since `(A - B)` alone parses as scalar
2929                // (labels read as variables).
2930                if self.paren_followed_by_dot_xy() {
2931                    let pos = self.parse_position()?;
2932                    self.expect(&Token::Rparen)?;
2933                    let loc = Location::Paren(Box::new(pos));
2934                    return Ok(if self.eat(&Token::DotX) {
2935                        Expr::DotX(loc)
2936                    } else {
2937                        self.expect(&Token::DotY)?;
2938                        Expr::DotY(loc)
2939                    });
2940                }
2941                // a plain scalar group `( expr )`
2942                let e = self.parse_expr()?;
2943                self.expect(&Token::Rparen)?;
2944                Ok(e)
2945            }
2946            // `$+` outside any macro invocation: zero arguments
2947            Token::ArgCount => {
2948                self.bump();
2949                Ok(Expr::Num(0.0))
2950            }
2951            Token::Func1(f) => {
2952                self.bump();
2953                self.expect(&Token::Lparen)?;
2954                let e = self.parse_expr()?;
2955                self.expect(&Token::Rparen)?;
2956                Ok(Expr::Func1(f, Box::new(e)))
2957            }
2958            Token::Func2(f) => {
2959                self.bump();
2960                self.expect(&Token::Lparen)?;
2961                let a = self.parse_expr()?;
2962                self.expect(&Token::Comma)?;
2963                let b = self.parse_expr()?;
2964                self.expect(&Token::Rparen)?;
2965                Ok(Expr::Func2(f, Box::new(a), Box::new(b)))
2966            }
2967            Token::Kw(Kw::Rand) => {
2968                self.bump();
2969                self.expect(&Token::Lparen)?;
2970                let arg = if self.at(&Token::Rparen) {
2971                    None
2972                } else {
2973                    Some(Box::new(self.parse_expr()?))
2974                };
2975                self.expect(&Token::Rparen)?;
2976                Ok(Expr::Rand(arg))
2977            }
2978            other => self.err(format!("expected an expression, found {other:?}")),
2979        }
2980    }
2981
2982    /// Parse a place followed by `.x` / `.y` / `.attr` to yield a scalar.
2983    fn parse_place_scalar(&mut self) -> PResult<Expr> {
2984        let place = self.parse_place()?;
2985        match self.cur().clone() {
2986            Token::DotX => {
2987                self.bump();
2988                Ok(Expr::DotX(Location::Place(place)))
2989            }
2990            Token::DotY => {
2991                self.bump();
2992                Ok(Expr::DotY(Location::Place(place)))
2993            }
2994            Token::Param(p) => {
2995                self.bump();
2996                Ok(Expr::PlaceAttr(place, p))
2997            }
2998            other => self.err(format!(
2999                "a place is not a number here; expected `.x`, `.y`, or an attribute, found {other:?}"
3000            )),
3001        }
3002    }
3003}
3004
3005#[cfg(test)]
3006mod tests {
3007    use super::*;
3008
3009    fn pic(src: &str) -> Picture {
3010        parse(src).unwrap_or_else(|e| panic!("parse error: {e}"))
3011    }
3012
3013    #[test]
3014    fn kernighan_pipeline() {
3015        let p = pic(r#".PS
3016ellipse "document"
3017arrow
3018box "PIC"
3019arrow
3020box "TBL/EQN" "(optional)" dashed
3021arrow
3022box "TROFF"
3023arrow
3024ellipse "typesetter"
3025.PE
3026"#);
3027        assert_eq!(p.stmts.len(), 9);
3028        // the dashed box with two strings
3029        if let Stmt::Object { object, .. } = &p.stmts[4] {
3030            assert_eq!(object.kind, ObjectKind::Primitive(Prim::Box));
3031            let texts = object
3032                .attrs
3033                .iter()
3034                .filter(|a| matches!(a, Attr::Text(_)))
3035                .count();
3036            assert_eq!(texts, 2);
3037            assert!(
3038                object
3039                    .attrs
3040                    .iter()
3041                    .any(|a| matches!(a, Attr::LineStyle(LineType::Dashed, _)))
3042            );
3043        } else {
3044            panic!("expected object");
3045        }
3046    }
3047
3048    #[test]
3049    fn box_with_dims_and_at() {
3050        let p = pic("box ht 0.3 wid 0.5 at 0.25,0.15");
3051        let Stmt::Object { object, .. } = &p.stmts[0] else {
3052            panic!()
3053        };
3054        assert!(matches!(object.attrs[0], Attr::Dim(DimKind::Ht, _)));
3055        assert!(matches!(object.attrs[1], Attr::Dim(DimKind::Wid, _)));
3056        assert!(matches!(object.attrs[2], Attr::At(Position::Pair(_, _))));
3057    }
3058
3059    #[test]
3060    fn behind_parses_as_contextual_extension_attribute() {
3061        let p = pic("A: box\nbox behind A");
3062        let Stmt::Object { object, .. } = &p.stmts[1] else {
3063            panic!()
3064        };
3065        let Some(Attr::Behind(Place::Name {
3066            name, subscript, ..
3067        })) = object.attrs.last()
3068        else {
3069            panic!("expected behind attribute");
3070        };
3071        assert_eq!(name, "A");
3072        assert!(subscript.is_none());
3073
3074        let p = pic("behind = 2\nbox wid behind");
3075        assert_eq!(p.stmts.len(), 2);
3076        assert!(matches!(p.stmts[0], Stmt::Assign(_)));
3077    }
3078
3079    #[test]
3080    fn fit_parses_as_contextual_extension_attribute() {
3081        let p = pic("box \"long label\" fit");
3082        let Stmt::Object { object, .. } = &p.stmts[0] else {
3083            panic!()
3084        };
3085        assert!(object.attrs.iter().any(|a| matches!(a, Attr::Fit)));
3086
3087        let p = pic("fit = 2\nbox wid fit");
3088        assert_eq!(p.stmts.len(), 2);
3089        assert!(matches!(p.stmts[0], Stmt::Assign(_)));
3090
3091        let p = pic("fit = 2\nline fit");
3092        let Stmt::Object { object, .. } = &p.stmts[1] else {
3093            panic!()
3094        };
3095        assert!(matches!(object.attrs[0], Attr::Dist(_, _)));
3096    }
3097
3098    #[test]
3099    fn hatch_parses_as_contextual_extension_attribute() {
3100        let p = pic("box hatch hatchangle 30 hatchsep .05 hatchwid 1.2 hatchcolor red");
3101        let Stmt::Object { object, .. } = &p.stmts[0] else {
3102            panic!()
3103        };
3104        assert!(
3105            object
3106                .attrs
3107                .iter()
3108                .any(|a| matches!(a, Attr::Hatch(HatchKind::Single)))
3109        );
3110        assert!(
3111            object
3112                .attrs
3113                .iter()
3114                .any(|a| matches!(a, Attr::HatchAngle(_)))
3115        );
3116        assert!(object.attrs.iter().any(|a| matches!(a, Attr::HatchSep(_))));
3117        assert!(
3118            object
3119                .attrs
3120                .iter()
3121                .any(|a| matches!(a, Attr::HatchWidth(_)))
3122        );
3123        assert!(
3124            object
3125                .attrs
3126                .iter()
3127                .any(|a| matches!(a, Attr::HatchColor(_)))
3128        );
3129
3130        let p = pic("hatch = 2\nbox wid hatch");
3131        assert_eq!(p.stmts.len(), 2);
3132        assert!(matches!(p.stmts[0], Stmt::Assign(_)));
3133        let Stmt::Object { object, .. } = &p.stmts[1] else {
3134            panic!()
3135        };
3136        assert!(matches!(object.attrs[0], Attr::Dim(DimKind::Wid, _)));
3137    }
3138
3139    #[test]
3140    fn opacity_parses_as_contextual_extension_attribute() {
3141        let p = pic("box opacity 0.5");
3142        let Stmt::Object { object, .. } = &p.stmts[0] else {
3143            panic!()
3144        };
3145        assert!(object.attrs.iter().any(|a| matches!(a, Attr::Opacity(_))));
3146
3147        let p = pic("opacity = 2\nbox wid opacity");
3148        assert_eq!(p.stmts.len(), 2);
3149        assert!(matches!(p.stmts[0], Stmt::Assign(_)));
3150        let Stmt::Object { object, .. } = &p.stmts[1] else {
3151            panic!()
3152        };
3153        assert!(matches!(object.attrs[0], Attr::Dim(DimKind::Wid, _)));
3154    }
3155
3156    #[test]
3157    fn close_parses_as_contextual_line_extension_attribute() {
3158        let p = pic("line right then up close");
3159        let Stmt::Object { object, .. } = &p.stmts[0] else {
3160            panic!()
3161        };
3162        assert!(object.attrs.iter().any(|a| matches!(a, Attr::Close)));
3163
3164        let p = pic("close = 2\nbox wid close");
3165        assert_eq!(p.stmts.len(), 2);
3166        assert!(matches!(p.stmts[0], Stmt::Assign(_)));
3167        let Stmt::Object { object, .. } = &p.stmts[1] else {
3168            panic!()
3169        };
3170        assert!(matches!(object.attrs[0], Attr::Dim(DimKind::Wid, _)));
3171    }
3172
3173    #[test]
3174    fn gradient_parses_as_contextual_extension_attribute() {
3175        let p = pic("box gradient \"steelblue\" white gradientangle 45");
3176        let Stmt::Object { object, .. } = &p.stmts[0] else {
3177            panic!()
3178        };
3179        assert!(object.attrs.iter().any(|a| matches!(a, Attr::Gradient(..))));
3180        assert!(
3181            object
3182                .attrs
3183                .iter()
3184                .any(|a| matches!(a, Attr::GradientAngle(_)))
3185        );
3186
3187        // contextual fallback: `gradient` stays usable as a variable
3188        let p = pic("gradient = 2\nbox wid gradient");
3189        assert!(matches!(p.stmts[0], Stmt::Assign(_)));
3190        let Stmt::Object { object, .. } = &p.stmts[1] else {
3191            panic!()
3192        };
3193        assert!(matches!(object.attrs[0], Attr::Dim(DimKind::Wid, _)));
3194    }
3195
3196    #[test]
3197    fn class_parses_inline_and_statement_forms() {
3198        let p = pic("box class \"critical\"");
3199        let Stmt::Object { object, .. } = &p.stmts[0] else {
3200            panic!()
3201        };
3202        assert!(object.attrs.iter().any(|a| matches!(a, Attr::Class(_))));
3203
3204        let p = pic("A: box\nclass A \"hot\"\nclass last box \"cold\"");
3205        assert!(matches!(p.stmts[1], Stmt::Class { .. }));
3206        assert!(matches!(p.stmts[2], Stmt::Class { .. }));
3207
3208        // contextual fallbacks: assignment and expression use survive
3209        let p = pic("class = 2\nbox wid class");
3210        assert!(matches!(p.stmts[0], Stmt::Assign(_)));
3211        let Stmt::Object { object, .. } = &p.stmts[1] else {
3212            panic!()
3213        };
3214        assert!(matches!(object.attrs[0], Attr::Dim(DimKind::Wid, _)));
3215    }
3216
3217    #[test]
3218    fn brace_parses_as_contextual_extension_object() {
3219        let p = pic(
3220            "A: box\nB: box\nbrace from A.e to B.w down \"group\" wid .2 bracepos .4 labeloffset .1",
3221        );
3222        let Stmt::Object { object, .. } = &p.stmts[2] else {
3223            panic!()
3224        };
3225        assert_eq!(object.kind, ObjectKind::Brace);
3226        assert!(object.attrs.iter().any(|a| matches!(a, Attr::From(_))));
3227        assert!(object.attrs.iter().any(|a| matches!(a, Attr::To(_))));
3228        assert!(
3229            object
3230                .attrs
3231                .iter()
3232                .any(|a| matches!(a, Attr::Direction(Dir::Down, None)))
3233        );
3234        assert!(object.attrs.iter().any(|a| matches!(a, Attr::Text(_))));
3235        assert!(object.attrs.iter().any(|a| matches!(a, Attr::BracePos(_))));
3236        assert!(
3237            object
3238                .attrs
3239                .iter()
3240                .any(|a| matches!(a, Attr::BraceLabelOffset(_)))
3241        );
3242
3243        let p = pic("brace = 2\nline right brace");
3244        assert!(matches!(p.stmts[0], Stmt::Assign(_)));
3245        let Stmt::Object { object, .. } = &p.stmts[1] else {
3246            panic!()
3247        };
3248        assert_eq!(object.kind, ObjectKind::Primitive(Prim::Line));
3249
3250        let p = pic("brace from 0,0 to 1,0\nline from last brace.start to last brace.end");
3251        assert_eq!(p.stmts.len(), 2);
3252    }
3253
3254    #[test]
3255    fn labeled_and_corners() {
3256        let p = pic("B1: box\narc -> from top of B1 to last box.ne");
3257        assert!(matches!(p.stmts[0], Stmt::Object { label: Some(_), .. }));
3258        let Stmt::Object { object, .. } = &p.stmts[1] else {
3259            panic!()
3260        };
3261        assert_eq!(object.kind, ObjectKind::Primitive(Prim::Arc));
3262        assert!(
3263            object
3264                .attrs
3265                .iter()
3266                .any(|a| matches!(a, Attr::Arrowhead(Arrow::Right, _)))
3267        );
3268        // from top of B1
3269        assert!(object.attrs.iter().any(|a| matches!(
3270            a,
3271            Attr::From(Position::Place(Location::Place(Place::CornerOf(
3272                Corner::N,
3273                _
3274            ))))
3275        )));
3276    }
3277
3278    #[test]
3279    fn with_at_and_shift() {
3280        let p = pic("ellipse \"2\" with .nw at last ellipse.se + (0.1,0)");
3281        let Stmt::Object { object, .. } = &p.stmts[0] else {
3282            panic!()
3283        };
3284        let with = object
3285            .attrs
3286            .iter()
3287            .find(|a| matches!(a, Attr::With { .. }))
3288            .unwrap();
3289        let Attr::With { anchor, at } = with else {
3290            panic!()
3291        };
3292        assert_eq!(*anchor, WithAnchor::Corner(Corner::Nw));
3293        // `last ellipse.se + (0.1,0)` is a position sum
3294        assert!(matches!(at, Position::Sum(Sign::Plus, _, _)));
3295    }
3296
3297    #[test]
3298    fn with_member_anchor_parses() {
3299        let p = pic("[ A: box ] with .A.c at Here");
3300        let Stmt::Object { object, .. } = &p.stmts[0] else {
3301            panic!()
3302        };
3303        let with = object
3304            .attrs
3305            .iter()
3306            .find(|a| matches!(a, Attr::With { .. }))
3307            .unwrap();
3308        let Attr::With { anchor, .. } = with else {
3309            panic!()
3310        };
3311        assert!(matches!(
3312            anchor,
3313            WithAnchor::Place(Place::Corner(inner, Corner::Center))
3314                if matches!(inner.as_ref(), Place::Name { name, .. } if name == "A")
3315        ));
3316    }
3317
3318    #[test]
3319    fn expression_precedence() {
3320        // 2 + 3 * 4 ^ 2  ==  2 + (3 * (4^2)) = 50
3321        let p = pic("x = 2 + 3 * 4 ^ 2");
3322        let Stmt::Assign(list) = &p.stmts[0] else {
3323            panic!()
3324        };
3325        // structure: Add(2, Mul(3, Pow(4,2)))
3326        let Expr::Bin(BinOp::Add, _, rhs) = &list[0].value else {
3327            panic!("expected top-level add")
3328        };
3329        assert!(matches!(**rhs, Expr::Bin(BinOp::Mul, _, _)));
3330    }
3331
3332    #[test]
3333    fn between_position() {
3334        let p = pic("arrow from 1/3 of the way between A.ne and A.se");
3335        let Stmt::Object { object, .. } = &p.stmts[0] else {
3336            panic!()
3337        };
3338        assert!(object.attrs.iter().any(|a| matches!(
3339            a,
3340            Attr::From(Position::Between {
3341                of_the_way: true,
3342                ..
3343            })
3344        )));
3345    }
3346
3347    #[test]
3348    fn assignment_list_and_envvar() {
3349        let p = pic("boxht = 0.3; boxwid = 2 * boxht");
3350        assert_eq!(p.stmts.len(), 2);
3351        let Stmt::Assign(a0) = &p.stmts[0] else {
3352            panic!()
3353        };
3354        assert_eq!(a0[0].target, AssignTarget::Env(EnvVar::Boxht));
3355    }
3356
3357    #[test]
3358    fn dpic_svg_font_stub_parses_as_string() {
3359        let p = pic("print svg_font(\"Times\", 12)");
3360        let Stmt::Print(PrintItem::Str(StringExpr::SvgFont(args))) = &p.stmts[0] else {
3361            panic!()
3362        };
3363        assert_eq!(args.len(), 2);
3364    }
3365
3366    #[test]
3367    fn subscripted_variable_refs_parse() {
3368        let p = pic("P[1] = 2\nx = P[1]");
3369        let Stmt::Assign(a0) = &p.stmts[0] else {
3370            panic!()
3371        };
3372        assert!(matches!(&a0[0].target, AssignTarget::Var(name, Some(_)) if name == "P"));
3373
3374        let Stmt::Assign(a1) = &p.stmts[1] else {
3375            panic!()
3376        };
3377        assert!(matches!(&a1[0].value, Expr::Var(name, Some(_)) if name == "P"));
3378    }
3379
3380    #[test]
3381    fn block_object() {
3382        let p = pic("[ box; circle ] with .nw at Here");
3383        let Stmt::Object { object, .. } = &p.stmts[0] else {
3384            panic!()
3385        };
3386        let ObjectKind::Block(inner) = &object.kind else {
3387            panic!()
3388        };
3389        assert_eq!(inner.len(), 2);
3390    }
3391
3392    #[test]
3393    fn diamond_line_with_then() {
3394        let p = pic("line up right then down right then down left then up left");
3395        let Stmt::Object { object, .. } = &p.stmts[0] else {
3396            panic!()
3397        };
3398        let thens = object
3399            .attrs
3400            .iter()
3401            .filter(|a| matches!(a, Attr::Then))
3402            .count();
3403        assert_eq!(thens, 3);
3404    }
3405
3406    #[test]
3407    fn place_scalar_in_coord_pair() {
3408        // issue #3: (A.x, expr) must parse as an (expr,expr) pair, not a place
3409        let p = pic("A: box\n\"t\" at (A.x, A.y - 0.5)");
3410        let Stmt::Object { object, .. } = &p.stmts[1] else {
3411            panic!()
3412        };
3413        assert!(
3414            object
3415                .attrs
3416                .iter()
3417                .any(|a| matches!(a, Attr::At(Position::Pair(_, _))))
3418        );
3419        // a plain point place still parses as a place position
3420        let q = pic("A: box\nbox at A.ne");
3421        let Stmt::Object { object, .. } = &q.stmts[1] else {
3422            panic!()
3423        };
3424        assert!(object.attrs.iter().any(|a| matches!(
3425            a,
3426            Attr::At(Position::Place(Location::Place(Place::Corner(_, _))))
3427        )));
3428    }
3429
3430    #[test]
3431    fn ignores_non_svg_backend_preambles() {
3432        let p = pic(r#".PS
3433verbatimtex
3434\global\def\foo#1{#1}
3435etex
3436\global\def\bar#1{#1}
3437\psset{arrowsize=4pt}
3438box
3439.PE
3440"#);
3441        assert_eq!(p.stmts.len(), 1);
3442        let Stmt::Object { object, .. } = &p.stmts[0] else {
3443            panic!()
3444        };
3445        assert_eq!(object.kind, ObjectKind::Primitive(Prim::Box));
3446    }
3447
3448    #[test]
3449    fn backend_filter_keeps_global_lines_inside_strings() {
3450        let p = pic(
3451            "sh \"echo -n \\\"print \\\\\"\\\" > x\"\nif dpicopt==optPGF then { command \"cycle; \\\n\\global\\let\\dpicdraw=x\" } else { box }",
3452        );
3453        assert_eq!(p.stmts.len(), 2);
3454        let Stmt::Object { object, .. } = &p.stmts[1] else {
3455            panic!()
3456        };
3457        assert_eq!(object.kind, ObjectKind::Primitive(Prim::Box));
3458    }
3459
3460    #[test]
3461    fn static_if_copy_defines_macros_before_following_statements() {
3462        let dir = std::env::temp_dir().join(format!("rpic_static_if_{}", std::process::id()));
3463        std::fs::create_dir_all(&dir).unwrap();
3464        std::fs::write(dir.join("macros.pic"), "define makebox { box wid $1 }\n").unwrap();
3465        std::fs::write(
3466            dir.join("inc.pic"),
3467            "define makecircle { circle rad 0.1 }\n",
3468        )
3469        .unwrap();
3470        let p = parse_in_dir(
3471            "if \"plotlib\" != \"1\" then { copy \"macros.pic\" }\ndefine choose { if \"$1\"==\"\" then { box } else { copy \"$1/inc.pic\" } }\nchoose(.)\nmakecircle()\nmakebox(0.4)",
3472            Some(dir.as_path()),
3473        )
3474        .unwrap_or_else(|e| panic!("parse error: {e}"));
3475        let _ = std::fs::remove_dir_all(&dir);
3476        assert_eq!(p.stmts.len(), 2);
3477        let Stmt::Object { object, .. } = &p.stmts[0] else {
3478            panic!()
3479        };
3480        assert_eq!(object.kind, ObjectKind::Primitive(Prim::Circle));
3481        let Stmt::Object { object, .. } = &p.stmts[1] else {
3482            panic!()
3483        };
3484        assert_eq!(object.kind, ObjectKind::Primitive(Prim::Box));
3485    }
3486
3487    #[test]
3488    fn unsupported_control_is_clear() {
3489        // `copy "file"` with no filesystem context reports a clear file error
3490        let e = parse("copy \"x\"").unwrap_err();
3491        assert!(e.msg.contains("copy") && e.msg.contains("file"));
3492    }
3493
3494    #[test]
3495    fn control_constructs_parse() {
3496        assert!(parse("for i = 1 to 3 do { box }").is_ok());
3497        assert!(parse("if 1 > 0 then { box } else { circle }").is_ok());
3498        assert!(parse("reset boxht, boxwid").is_ok());
3499        // define is consumed by the preprocessor and expanded
3500        let p = parse("define e { box }\ne\ne").unwrap();
3501        assert_eq!(p.stmts.len(), 2);
3502    }
3503}