Skip to main content

drawland_core/
grammar.rs

1//! The graph a profile script builds (`drawland-script`), and its JSON form:
2//! named nodes in four typed sections, the draws, and the composition.
3//!
4//! ```json
5//! { "output": { "width": "6in", "height": "4in", "scale": "1:10000" },
6//!   "$features": { "bldg_1": { "tiles_select": "buildings", "at": [3, 14] } },
7//!   "$areas": { "polygons_2": { "tools_polygons": "$features.bldg_1", "at": [4, 19] } },
8//!   "$lines": { "rings_3": { "tools_rings": "$areas.polygons_2", "at": [5, 15] } },
9//!   "draw": [{ "id": "bldg_ring", "from": "$lines.rings_3", "stroke": "solid", "at": [6, 1] }],
10//!   "compose": { "order": ["bldg_ring"] } }
11//! ```
12//!
13//! A node refers to another by `$section.name`; the section is its type.
14//! Operations are namespaced: `tools_*` (this module), `osm_*` / `tiles_*` /
15//! `engine_*` (sources: Overpass, vector tiles, the output, the ocean) and
16//! `module_*` (compiled recipes such as roads, whose outputs are drawn as
17//! `roads.outlines`). `at` is where the script made the node; errors about it
18//! carry that line and column.
19//!
20//! Loading is strict: unknown sections, operations and names are errors at
21//! load, never halfway through a render.
22
23use crate::profile::{FillSpec, StrokeSpec};
24use crate::select::{Selector, TagMatch, TagTest};
25use crate::units::Mm;
26use serde::de::{self, Deserializer, MapAccess, Visitor};
27use serde::{Deserialize, Serialize};
28use serde_json::Value;
29use std::collections::{BTreeMap, BTreeSet};
30use std::fmt;
31
32// ---------------------------------------------------------------------------
33// Names
34// ---------------------------------------------------------------------------
35
36/// Which section a name lives in. The section is the type.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
38pub enum Section {
39    Features,
40    Areas,
41    Lines,
42    Fills,
43}
44
45impl Section {
46    pub const ALL: [Section; 4] = [Section::Features, Section::Areas, Section::Lines, Section::Fills];
47
48    pub fn key(self) -> &'static str {
49        match self {
50            Section::Features => "features",
51            Section::Areas => "areas",
52            Section::Lines => "lines",
53            Section::Fills => "fills",
54        }
55    }
56}
57
58impl fmt::Display for Section {
59    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
60        f.write_str(self.key())
61    }
62}
63
64/// A reference such as `$areas.river` or `$fills.hatch`.
65#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
66pub struct Name {
67    pub section: Section,
68    pub name: String,
69}
70
71impl Name {
72    /// Parse `$<section>.<name>`. Anything else (a bare word)
73    /// is not a reference the grammar resolver understands.
74    pub fn parse(text: &str) -> Result<Name, String> {
75        let rest = text.strip_prefix('$').ok_or_else(|| format!("{text:?} is not a $section.name reference"))?;
76        let (section, name) = rest
77            .split_once('.')
78            .ok_or_else(|| format!("{text:?} has no section (expected $section.name)"))?;
79        let section = Section::ALL
80            .into_iter()
81            .find(|s| s.key() == section)
82            .ok_or_else(|| format!("unknown section {section:?} in {text:?}"))?;
83        if name.is_empty() {
84            return Err(format!("{text:?} has an empty name"));
85        }
86        Ok(Name { section, name: name.to_string() })
87    }
88}
89
90impl fmt::Display for Name {
91    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
92        write!(f, "${}.{}", self.section.key(), self.name)
93    }
94}
95
96/// An SVG group id: a label, not a variable, so it carries no marker.
97#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
98pub struct Id(pub String);
99
100// ---------------------------------------------------------------------------
101// Operations
102// ---------------------------------------------------------------------------
103
104/// A tag filter, as `osm_select: { building: true, highway: [primary] }`.
105pub type Select = Vec<(String, TagMatch)>;
106
107/// A vector tile selection, as `tiles_select: [buildings, landcover:park]`:
108/// terramask presets and `layer:class` rules, a class or a subclass by name.
109#[derive(Debug, Clone, PartialEq)]
110pub struct TileSelect {
111    /// As written.
112    pub items: Vec<String>,
113    pub filter: terramask::Filter,
114}
115
116/// Where a `data_select` reads its features.
117#[derive(Debug, Clone, PartialEq)]
118pub enum DataSource {
119    /// A GeoJSON URL or file path, for the host to read.
120    Url(String),
121    /// GeoJSON the profile wrote out itself.
122    Inline(Value),
123    /// Plain JSON with positions in it (a transit API, a feed), read by the
124    /// host like a GeoJSON URL and turned into points by [`JsonSource`].
125    Json(JsonSource),
126}
127
128impl DataSource {
129    /// The URL or path the host reads, when there is one.
130    pub fn url(&self) -> Option<&str> {
131        match self {
132            DataSource::Url(u) => Some(u),
133            DataSource::Json(j) => Some(&j.url),
134            DataSource::Inline(_) => None,
135        }
136    }
137}
138
139/// `features.json(url, { items, lat, lng })`: dot-paths into the reply — the
140/// array of items (empty: the reply is the array), and each item's latitude
141/// and longitude (numbers, or numbers written as text).
142#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
143#[serde(deny_unknown_fields)]
144pub struct JsonSource {
145    pub url: String,
146    #[serde(default)]
147    pub items: String,
148    pub lat: String,
149    pub lng: String,
150}
151
152/// `tools_where`: the features of `of` whose tags pass every test, as
153/// `{ of: $features.b, tags: { render_height: { min: 20, max: 40 } } }`.
154#[derive(Debug, Clone, PartialEq)]
155pub struct Where {
156    pub of: Name,
157    pub tags: Vec<(String, TagTest)>,
158}
159
160/// A compiled module, reading `from` when given, else every OSM feature.
161#[derive(Debug, Clone, PartialEq)]
162pub struct Module {
163    pub name: String,
164    pub from: Option<Name>,
165    pub roads: crate::themes::RoadOptions,
166}
167
168/// Buffer a shape by a distance, positive or negative.
169#[derive(Debug, Clone, PartialEq)]
170pub struct Grow {
171    pub of: Name,
172    pub by: Mm,
173}
174
175/// An area moved across the page by `by` mm (x right, y down): a shadow
176/// cast off what casts it.
177#[derive(Debug, Clone, PartialEq)]
178pub struct Move {
179    pub of: Name,
180    pub by: [Mm; 2],
181}
182
183/// A disc of radius `by` around every point of a feature set (mapped trees),
184/// merged into one area. Lines and polygons in the set are ignored.
185#[derive(Debug, Clone, PartialEq)]
186pub struct Around {
187    pub of: Name,
188    pub by: Mm,
189}
190
191/// Geometry written by the profile: `points` are mm offsets from `at`, in
192/// page axes (x right, y down), turned clockwise by `rotate` degrees. `at` is
193/// a place on the ground or a point on the page.
194#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
195#[serde(deny_unknown_fields)]
196pub struct Shape {
197    pub at: ShapeAt,
198    pub points: Vec<[f64; 2]>,
199    #[serde(default)]
200    pub rotate: f64,
201    /// Lines only: join the last point back to the first.
202    #[serde(default)]
203    pub closed: bool,
204}
205
206#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
207#[serde(untagged)]
208pub enum ShapeAt {
209    Geo { lat: f64, lng: f64 },
210    Page([PagePos; 2]),
211}
212
213/// A page coordinate: a length, or `"50%"` of the page's width (x) or height (y).
214#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
215#[serde(untagged)]
216pub enum PagePos {
217    Mm(Mm),
218    Percent(String),
219}
220
221/// A line of text written by the profile, centred on `at`; `size` is the
222/// capital height.
223#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
224#[serde(deny_unknown_fields)]
225pub struct Text {
226    pub at: ShapeAt,
227    pub text: String,
228    pub size: Mm,
229    #[serde(default)]
230    pub font: crate::text::LabelFont,
231    #[serde(default)]
232    pub rotate: f64,
233    /// `areas.text` with an outline font: keep the letters' counters (the
234    /// holes in A, B, O) open, for a fill inside the letters; closed by
235    /// default, for a mask.
236    #[serde(default, rename = "openCounters", skip_serializing_if = "std::ops::Not::not")]
237    pub open_counters: bool,
238}
239
240/// `"50%"` as a fraction, 0.5.
241pub fn percent(s: &str) -> Option<f64> {
242    s.trim().strip_suffix('%')?.trim().parse::<f64>().ok().map(|p| p / 100.0)
243}
244
245/// How `tools_buffer_lines` ends each stroke.
246#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
247#[serde(rename_all = "lowercase")]
248pub enum LineBufferCap {
249    #[default]
250    Round,
251    Flat,
252}
253
254/// Buffer lines by a half-width, merged into one area. Caps and joins are round
255/// unless `cap` is `flat` (butt caps; joins stay round).
256#[derive(Debug, Clone, PartialEq)]
257pub struct BufferLines {
258    pub lines: Name,
259    pub by: Mm,
260    pub cap: LineBufferCap,
261}
262
263/// Close the thin gaps between `of` and the edges of `within` (tile polygons
264/// that stop just short of the card border); `gap_mm` is the widest closed.
265#[derive(Debug, Clone, PartialEq)]
266pub struct ExtendToFrame {
267    pub of: Name,
268    pub within: Name,
269    pub gap_mm: Option<Mm>,
270}
271
272/// `tools_terrain`: pen-and-ink terrain in an area, drawn by burin from the
273/// elevation under the output.
274#[derive(Debug, Clone, PartialEq)]
275pub struct Terrain {
276    /// The area to draw in, or `None` for the whole output.
277    pub in_area: Option<Name>,
278    /// The colour at each dash, as burin writes one: a hex colour, or a tree.
279    pub color: Option<serde_json::Value>,
280    /// The line width at each dash, as a multiple of the pen.
281    pub width: Option<serde_json::Value>,
282    /// The field the streamlines run along, degrees.
283    pub angle: f64,
284    /// What to call the layer; `terrain` without one.
285    pub layer: Option<String>,
286    /// Style parameters, as burin names them.
287    pub style: serde_json::Map<String, serde_json::Value>,
288    /// Draw the shore (the zero contour) as well.
289    pub shore: bool,
290    /// The heights a fill keeps to, as burin writes them: `elevMin`, `elevMax`
291    /// and the depths. Empty for streamlines, which cover the ground they can.
292    pub band: serde_json::Map<String, serde_json::Value>,
293    /// What to draw: streamlines along the slope, or a fill of the band.
294    pub draw: TerrainDraw,
295}
296
297/// What a `tools_terrain` def draws.
298#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
299pub enum TerrainDraw {
300    /// Pen-and-ink hatching along the slope; the default.
301    #[default]
302    Lines,
303    /// A flat fill of the band: what a contour belt between two heights is.
304    Fill,
305    /// Stippling, denser where the shading is darker.
306    Dots,
307}
308
309/// `tools_burin`: a whole burin document, built by burin's own language inside
310/// a draw.land profile, drawn by the engine from the elevation under the
311/// output. The atlas is burin's own JSON — the same thing `burin.draw()`
312/// yields at burin's front ends — so no vocabulary is repeated here.
313#[derive(Debug, Clone, PartialEq, Default)]
314pub struct Burin {
315    /// The burin atlas, as `burin.json()` writes it: batches and water passes.
316    pub atlas: serde_json::Value,
317    /// The area the drawing is kept to, or `None` for the whole output.
318    pub in_area: Option<Name>,
319    /// Regions batches name in `within` / `outside`, by name, in output mm.
320    pub regions: std::collections::BTreeMap<String, Name>,
321    /// Where the water is, in output mm: burin's water mask. `None` lets burin
322    /// guess it from the elevation (at or below 0.5 m).
323    pub water: Option<Name>,
324    /// What to call the layer; `burin` without one.
325    pub layer: Option<String>,
326}
327
328#[derive(Debug, Clone, PartialEq)]
329pub struct Difference {
330    pub base: Name,
331    /// Named defs to subtract (empty when `cut_rule` is used).
332    pub cut: Vec<Name>,
333    /// `cut: { tools_rings: $areas.a }` — a rule written on the line.
334    pub cut_rule: Option<Box<Op>>,
335}
336
337/// What `tools_union` / `tools_join` read.
338#[derive(Debug, Clone, PartialEq)]
339pub enum UnionRules {
340    /// `tools_union: [$areas.a, $areas.b]`
341    Refs(Vec<Name>),
342    /// `tools_union: $areas.a` — one reference, `list: false`
343    Ref(Name),
344}
345
346#[derive(Debug, Clone, PartialEq)]
347pub struct Intersect {
348    pub base: Name,
349    /// A named def (empty when `keep_rule` is used).
350    pub keep: Option<Name>,
351    pub keep_rule: Option<Box<Op>>,
352}
353
354#[derive(Debug, Clone, PartialEq)]
355pub struct Rings {
356    pub of: Name,
357    pub exterior_only: bool,
358}
359
360#[derive(Debug, Clone, PartialEq)]
361pub struct ClipLines {
362    pub lines: Name,
363    pub within: Name,
364    pub invert: bool,
365}
366
367/// Read strokes or the covered area from a `$lines` labels def, optionally
368/// one rule bucket (`rule: "park"` matches `modules.labels` `rules[].id`).
369#[derive(Debug, Clone, PartialEq)]
370pub struct LabelPick {
371    pub of: Name,
372    pub rule: Option<String>,
373    /// Only the places' dots (`marker`), not the letters.
374    pub dots: bool,
375}
376
377/// `tools_labels`: the names of `from`, placed so that none covers another,
378/// as the pen strokes of their letters. What the letters cover is read from
379/// it by `tools_label_area` / `tools_label_lines`.
380#[derive(Debug, Clone, PartialEq)]
381pub struct Labels {
382    /// Placed together, so no set's labels cover another's.
383    pub from: Vec<Name>,
384    pub in_area: Option<Name>,
385    /// An area the letters keep off (the lines of a transit map); a place's
386    /// point and dot may still sit on it.
387    pub avoid: Option<Name>,
388    pub style: crate::labels::Style,
389}
390
391/// `tools_graticule` (lines) / `tools_graticule_area` (an area): an atlas
392/// plate's meridians and parallels round the page rectangle `in` (its
393/// bounds), through the output's projection. `part` picks what comes out.
394#[derive(Debug, Clone, PartialEq)]
395pub struct Graticule {
396    pub in_area: Name,
397    pub look: GraticuleLook,
398}
399
400#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
401#[serde(rename_all = "lowercase")]
402pub enum GraticulePart {
403    /// Lines: the meridians and parallels, cut to `in`.
404    Grid,
405    /// Lines: the degree labels round the border; as an area, what they cover.
406    Labels,
407    /// An area: the border's inked keys.
408    Keys,
409}
410
411#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
412#[serde(deny_unknown_fields)]
413pub struct GraticuleLook {
414    pub part: GraticulePart,
415    /// Minutes of arc between lines, and between labels.
416    pub step: f64,
417    /// Minutes of arc per key of the border; 0, none.
418    #[serde(default)]
419    pub ticks: f64,
420    /// The key band's width, just outside `in`.
421    #[serde(default)]
422    pub band: Mm,
423    /// Paper between the band and the labels.
424    #[serde(default)]
425    pub gap: Mm,
426    /// The labels' capital height.
427    #[serde(default = "graticule_size")]
428    pub size: Mm,
429    #[serde(default)]
430    pub font: crate::text::LabelFont,
431}
432
433fn graticule_size() -> Mm {
434    Mm(1.8)
435}
436
437/// A penfill run. `per: feature` runs one pattern per polygon instead of one
438/// on the union. `content` fills the area with lines made elsewhere (burin's,
439/// or any `$lines`), cut to it, instead of a pattern. `motif` is lines drawn
440/// elsewhere (`lines.text`, `lines.shape`) used as the pattern's motif: the
441/// runner centres them on the origin and hands them to penfill as polylines.
442#[derive(Debug, Clone, PartialEq)]
443pub struct Fill {
444    pub in_area: Name,
445    pub per_feature: bool,
446    pub content: Option<Name>,
447    pub motif: Option<Name>,
448    pub spec: FillSpec,
449}
450
451/// One operation. Every variant names the section it produces.
452#[derive(Debug, Clone, PartialEq)]
453pub enum Op {
454    // ---- feature sets ----------------------------------------------------
455    Select(Selector),
456    TileSelect(TileSelect),
457    /// `data_select: "<url or path>"`, or `data_select: { geojson: {…} }`:
458    /// every feature of a GeoJSON dataset, read by the host (see
459    /// [`Grammar::datasets`]) or written in the profile.
460    DataSelect(DataSource),
461    /// `terrain_select: { contours: {…} }` or `{ soundings: {…} }`: features
462    /// made from the elevation, their heights as tags (see [`crate::contours`]).
463    TerrainSelect(crate::contours::TerrainSelect),
464    Where(Where),
465
466    // ---- areas -----------------------------------------------------------
467    Polygons(Name),
468    Union(UnionRules),
469    Difference(Difference),
470    Intersect(Intersect),
471    FillHoles(Name),
472    Grow(Grow),
473    Move(Move),
474    Around(Around),
475    /// A closed shape written by the profile.
476    Shape(Shape),
477    /// What a profile's text covers.
478    TextArea(Text),
479    /// An atlas graticule's keys, or its labels' cover.
480    GraticuleArea(Graticule),
481    BufferLines(BufferLines),
482    /// What the letters of a `$lines` labels def cover.
483    LabelArea(LabelPick),
484    /// What a fill covers on paper (its clearings left out, its overflow
485    /// in), to mask other layers with.
486    FillCover(Fill),
487    /// The output rectangle.
488    Frame,
489    ExtendToFrame(ExtendToFrame),
490
491    // ---- lines -----------------------------------------------------------
492    Rings(Rings),
493    Lines(Name),
494    Segments(Name),
495    Dedupe(Name),
496    Merge(Name),
497    Join(UnionRules),
498    ClipLines(ClipLines),
499    /// A line written by the profile.
500    Path(Shape),
501    /// Text written by the profile, as pen strokes.
502    Text(Text),
503    /// An atlas graticule: its lines, or its degree labels.
504    Graticule(Graticule),
505    /// Pen-and-ink terrain, drawn by burin from the elevation.
506    Terrain(Terrain),
507    /// A height or depth band of the elevation, as an area (`areas.band`): the
508    /// fill burin would draw for `draw: "fill"`, closed into polygons.
509    TerrainBand(Terrain),
510    /// A whole burin document, drawn from the elevation.
511    Burin(Burin),
512    /// Names on the map, as pen strokes.
513    Labels(Labels),
514    /// Strokes from a labels def, or one of its rule buckets.
515    LabelLines(LabelPick),
516
517    // ---- fills (lines, produced by penfill) -------------------------------
518    Fill(Fill),
519
520    // ---- compiled modules (roads) ----------------------------------------
521    /// Publishes named outputs (`roads.area`, `roads.outlines`, …).
522    Module(Module),
523}
524
525impl Clip {
526    pub fn auto() -> Clip {
527        Clip::Auto
528    }
529}
530
531impl Op {
532    /// What a def holding this operation defines.
533    pub fn section(&self) -> Section {
534        match self {
535            Op::Select(_) | Op::TileSelect(_) | Op::DataSelect(_) | Op::TerrainSelect(_) | Op::Where(_) => Section::Features,
536            Op::Polygons(_)
537            | Op::Union(_)
538            | Op::Difference(_)
539            | Op::Intersect(_)
540            | Op::FillHoles(_)
541            | Op::Grow(_)
542            | Op::Move(_)
543            | Op::Around(_)
544            | Op::Shape(_)
545            | Op::TextArea(_)
546            | Op::GraticuleArea(_)
547            | Op::BufferLines(_)
548            | Op::LabelArea(_)
549            | Op::FillCover(_)
550            | Op::Frame
551            | Op::ExtendToFrame(_)
552            | Op::TerrainBand(_) => Section::Areas,
553            Op::Path(_)
554            | Op::Text(_)
555            | Op::Graticule(_)
556            | Op::Rings(_)
557            | Op::Lines(_)
558            | Op::Segments(_)
559            | Op::Dedupe(_)
560            | Op::Merge(_)
561            | Op::Join(_)
562            | Op::ClipLines(_)
563            | Op::Terrain(_)
564            | Op::Burin(_)
565            | Op::Labels(_)
566            | Op::LabelLines(_) => Section::Lines,
567            Op::Fill(_) => Section::Fills,
568            // A module is called from $areas: its headline output is an area,
569            // and the rest are reached by output name (`roads.outlines`).
570            Op::Module(_) => Section::Areas,
571        }
572    }
573
574    /// The names this operation reads.
575    pub fn refs(&self) -> Vec<Name> {
576        match self {
577            Op::Select(_) | Op::TileSelect(_) | Op::DataSelect(_) | Op::TerrainSelect(_) | Op::Frame | Op::Shape(_) | Op::Path(_) | Op::Text(_) | Op::TextArea(_) => vec![],
578            Op::Module(m) => m.from.iter().cloned().collect(),
579            Op::Polygons(n) | Op::FillHoles(n) | Op::Dedupe(n) | Op::Merge(n) | Op::Lines(n) | Op::Segments(n) => {
580                vec![n.clone()]
581            }
582            Op::Union(UnionRules::Refs(ns)) | Op::Join(UnionRules::Refs(ns)) => ns.clone(),
583            Op::Union(UnionRules::Ref(n)) | Op::Join(UnionRules::Ref(n)) => vec![n.clone()],
584            Op::Difference(d) => std::iter::once(d.base.clone())
585                .chain(d.cut.iter().cloned())
586                .chain(d.cut_rule.as_deref().map(Op::refs).unwrap_or_default())
587                .collect(),
588            Op::Intersect(i) => std::iter::once(i.base.clone())
589                .chain(i.keep.iter().cloned())
590                .chain(i.keep_rule.as_deref().map(Op::refs).unwrap_or_default())
591                .collect(),
592            Op::Grow(g) => vec![g.of.clone()],
593            Op::Move(m) => vec![m.of.clone()],
594            Op::Around(a) => vec![a.of.clone()],
595            Op::BufferLines(b) => vec![b.lines.clone()],
596            Op::ExtendToFrame(e) => vec![e.of.clone(), e.within.clone()],
597            Op::Where(w) => vec![w.of.clone()],
598            Op::Rings(r) => vec![r.of.clone()],
599            Op::ClipLines(c) => vec![c.lines.clone(), c.within.clone()],
600            Op::Terrain(t) | Op::TerrainBand(t) => t.in_area.iter().cloned().collect(),
601            Op::Burin(b) => b
602                .in_area
603                .iter()
604                .cloned()
605                .chain(b.regions.values().cloned())
606                .chain(b.water.iter().cloned())
607                .collect(),
608            Op::Labels(l) => l.from.iter().chain(l.in_area.iter()).chain(l.avoid.iter()).cloned().collect(),
609            Op::Graticule(g) | Op::GraticuleArea(g) => vec![g.in_area.clone()],
610            Op::LabelLines(p) | Op::LabelArea(p) => vec![p.of.clone()],
611            Op::Fill(f) | Op::FillCover(f) => {
612                std::iter::once(f.in_area.clone()).chain(f.content.iter().cloned()).chain(f.motif.iter().cloned()).collect()
613            }
614        }
615    }
616
617    /// Same rule shape and the same inputs: the only difference is where the
618    /// inputs live (a named def vs. on the line).
619    pub fn same_semantics(&self, other: &Op) -> bool {
620        match (self, other) {
621            (Op::Polygons(a), Op::Polygons(b)) => a == b,
622            (Op::Union(a), Op::Union(b)) => a == b,
623            (Op::Difference(a), Op::Difference(b)) => a.base == b.base && a.cut.len() == b.cut.len(),
624            (Op::Intersect(a), Op::Intersect(b)) => a.base == b.base && a.keep == b.keep,
625            (Op::FillHoles(a), Op::FillHoles(b)) => a == b,
626            (Op::LabelArea(a), Op::LabelArea(b)) => a == b,
627            (Op::LabelLines(a), Op::LabelLines(b)) => a == b,
628            (Op::Grow(a), Op::Grow(b)) => a.of == b.of,
629            (Op::Around(a), Op::Around(b)) => a == b,
630            (Op::BufferLines(a), Op::BufferLines(b)) => a.lines == b.lines && a.by == b.by && a.cap == b.cap,
631            (Op::Rings(a), Op::Rings(b)) => a.of == b.of,
632            (Op::Lines(a), Op::Lines(b)) => a == b,
633            (Op::Segments(a), Op::Segments(b)) => a == b,
634            (Op::Dedupe(a), Op::Dedupe(b)) => a == b,
635            (Op::Merge(a), Op::Merge(b)) => a == b,
636            (Op::Join(a), Op::Join(b)) => a == b,
637            (Op::ClipLines(a), Op::ClipLines(b)) => a.lines == b.lines,
638            // A selection, an engine source or a module cannot be inlined in v3.
639            _ => false,
640        }
641    }
642}
643
644/// Where a script wrote something: line and column, from 1. Written as
645/// `line 12 column 5`, the form the web editor's markers read.
646#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
647pub struct At(pub u32, pub u32);
648
649impl fmt::Display for At {
650    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
651        write!(f, "line {} column {}", self.0, self.1)
652    }
653}
654
655/// `what`, followed by ` (line 12 column 5)` when the script position is known.
656pub fn located(what: &str, at: Option<At>) -> String {
657    match at {
658        Some(at) => format!("{what} ({at})"),
659        None => what.to_string(),
660    }
661}
662
663/// A def: the name you chose, and the one operation it runs.
664#[derive(Debug, Clone, PartialEq)]
665pub struct Def {
666    pub name: String,
667    pub op: Op,
668    pub at: Option<At>,
669}
670
671impl Def {
672    /// The reference other defs use to reach this one.
673    pub fn reference(&self) -> Name {
674        Name { section: self.op.section(), name: self.name.clone() }
675    }
676
677    /// The reference, with the script line that made it.
678    pub fn label(&self) -> String {
679        located(&self.reference().to_string(), self.at)
680    }
681}
682
683// ---------------------------------------------------------------------------
684// draw: and compose:
685// ---------------------------------------------------------------------------
686
687#[derive(Debug, Clone, PartialEq)]
688pub struct Draw {
689    /// SVG group id. `None` falls back to the def name (`fills_hatch`).
690    pub id: Option<String>,
691    pub from: Target,
692    pub stroke: Option<StrokeSpec>,
693    pub at: Option<At>,
694}
695
696impl Draw {
697    /// The group name this entry writes: explicit `id`, else the def reference
698    /// with `$` dropped and the dot turned into an underscore.
699    pub fn group(&self) -> String {
700        match &self.id {
701            Some(id) => id.clone(),
702            None => match &self.from.module {
703                Some(m) => format!("{m}_{}", self.from.name.name),
704                None => format!("{}_{}", self.from.name.section.key(), self.from.name.name),
705            },
706        }
707    }
708}
709
710#[derive(Debug, Clone, PartialEq)]
711pub struct Mask {
712    pub from: Target,
713    pub occludes: Vec<Id>,
714    pub at: Option<At>,
715}
716
717#[derive(Debug, Clone, Default, PartialEq)]
718pub enum Clip {
719    #[default]
720    Auto,
721    None,
722    /// Subtract exactly these areas.
723    Areas(Vec<Name>),
724}
725
726#[derive(Debug, Clone, PartialEq, Default)]
727pub struct Compose {
728    /// Bottom-most first. Empty means the order of `draw`.
729    pub order: Vec<Id>,
730    pub masks: Vec<(String, Mask)>,
731    pub clip: BTreeMap<Id, Clip>,
732    pub clip_default: Clip,
733    pub optimize: Vec<crate::optimize::OptimizeStep>,
734}
735
736// ---------------------------------------------------------------------------
737// The profile
738// ---------------------------------------------------------------------------
739
740#[derive(Debug, Clone, PartialEq)]
741pub struct Grammar {
742    /// A name for the profile, carried with it when shared; nothing draws it.
743    pub title: Option<String>,
744    pub output: crate::profile::OutputSpec,
745    /// Sections in the order they were written, each with its defs.
746    pub sections: Vec<(Section, Vec<Def>)>,
747    pub draw: Vec<Draw>,
748    pub compose: Compose,
749    /// Other places drawn into rectangles of this page (`view(...)`), under
750    /// the page's own groups. Each is a whole graph with its own output.
751    pub views: Vec<View>,
752}
753
754/// A view: another place, at its own scale, drawn into a rectangle of the
755/// page. Its graph's `output` is the place and the rectangle's size; `at` is
756/// the rectangle's top-left corner on the page, in mm. A page mask whose
757/// `occludes` names the view's `id` cuts every stroke of it.
758#[derive(Debug, Clone, PartialEq)]
759pub struct View {
760    pub id: String,
761    pub at: (f64, f64),
762    pub grammar: Box<Grammar>,
763    /// One colour for every stroke of the view, whatever its style asks: the
764    /// view is then one group of its own, named `id` — one pen.
765    pub ink: Option<String>,
766}
767
768impl View {
769    /// The place the view shows, as `(lng, lat)`.
770    pub fn center(&self) -> (f64, f64) {
771        (self.grammar.output.lng.unwrap_or(0.0), self.grammar.output.lat.unwrap_or(0.0))
772    }
773}
774
775impl Grammar {
776    /// The `tools_terrain` defs, in file order: what the host reads the
777    /// elevation for.
778    pub fn terrains(&self) -> Vec<&Terrain> {
779        self.all_defs()
780            .filter_map(|d| match &d.op {
781                Op::Terrain(t) | Op::TerrainBand(t) => Some(t),
782                _ => None,
783            })
784            .collect()
785    }
786
787    /// The `tools_burin` defs: whole burin documents the engine draws.
788    pub fn burins(&self) -> Vec<&Burin> {
789        self.all_defs()
790            .filter_map(|d| match &d.op {
791                Op::Burin(b) => Some(b),
792                _ => None,
793            })
794            .collect()
795    }
796
797    /// Whether any def draws the elevation — terrain, or a burin document.
798    /// What turns the terrain fetch on.
799    pub fn draws_terrain(&self) -> bool {
800        !self.terrains().is_empty()
801            || !self.burins().is_empty()
802            || self.all_defs().any(|d| matches!(d.op, Op::TerrainSelect(_)))
803    }
804
805    pub fn defs(&self, section: Section) -> &[Def] {
806        self.sections
807            .iter()
808            .find(|(s, _)| *s == section)
809            .map(|(_, d)| d.as_slice())
810            .unwrap_or(&[])
811    }
812
813    /// Every def, in section order.
814    pub fn all_defs(&self) -> impl Iterator<Item = &Def> {
815        self.sections.iter().flat_map(|(_, defs)| defs.iter())
816    }
817
818    pub fn find(&self, name: &Name) -> Option<&Def> {
819        self.defs(name.section).iter().find(|d| d.name == name.name)
820    }
821
822    /// The def holding `module_<module>`, if the profile calls one.
823    pub fn module(&self, module: &str) -> Option<&Def> {
824        self.all_defs().find(|d| matches!(&d.op, Op::Module(m) if m.name == module))
825    }
826
827    /// The SVG group each draw entry writes.
828    pub fn groups(&self) -> Vec<String> {
829        self.draw.iter().map(Draw::group).collect()
830    }
831
832    /// Every OSM key the profile can select on: what Overpass must fetch.
833    ///
834    /// Modules read tags the profile never names (`module_roads` needs
835    /// `highway`), so they contribute their keys too, unless they read a
836    /// feature set of their own (`from`). Empty: the profile needs no
837    /// Overpass at all.
838    pub fn osm_keys(&self) -> Vec<String> {
839        let mut keys: Vec<String> = Vec::new();
840        fn add(keys: &mut Vec<String>, k: &str) {
841            if !keys.iter().any(|x| x == k) {
842                keys.push(k.to_string());
843            }
844        }
845        let defs: Vec<&Def> = self.all_defs().collect();
846        for def in defs {
847            match &def.op {
848                Op::Select(sel) => sel.keys().for_each(|k| add(&mut keys, k)),
849                Op::Module(Module { name, from: None, .. }) => {
850                    crate::themes::osm_keys(name).iter().for_each(|k| add(&mut keys, k))
851                }
852                _ => {}
853            }
854        }
855        keys
856    }
857
858    /// Every `tiles_select` item: what to read from the vector tiles.
859    pub fn tile_selectors(&self) -> Vec<String> {
860        let mut out: Vec<String> = Vec::new();
861        for def in self.all_defs() {
862            if let Op::TileSelect(t) = &def.op {
863                out.extend(t.items.iter().filter(|i| !out.contains(i)).cloned().collect::<Vec<_>>());
864            }
865        }
866        out
867    }
868
869    /// Whether the profile reads open-sea polygons from the vector tiles.
870    pub fn draws_ocean(&self) -> bool {
871        self.tile_selectors().iter().any(|s| s == "ocean")
872    }
873
874    /// Every `data_select` source, a URL or a file path, in order: the
875    /// GeoJSON the host must read and pass as `Inputs::data`.
876    pub fn datasets(&self) -> Vec<String> {
877        let mut out: Vec<String> = Vec::new();
878        for def in self.all_defs() {
879            if let Some(src) = match &def.op {
880                Op::DataSelect(d) => d.url(),
881                _ => None,
882            } {
883                if !out.iter().any(|o| o == src) {
884                    out.push(src.to_string());
885                }
886            }
887        }
888        out
889    }
890
891    /// SVG files named by a fill `source`, for the host to read.
892    pub fn source_files(&self) -> Vec<String> {
893        let mut out = Vec::new();
894        for def in self.defs(Section::Fills) {
895            if let Op::Fill(f) = &def.op {
896                if let Some(src) = &f.spec.source {
897                    if !out.contains(&src.file) {
898                        out.push(src.file.clone());
899                    }
900                }
901            }
902        }
903        out
904    }
905}
906
907// ---------------------------------------------------------------------------
908// Deserialization
909// ---------------------------------------------------------------------------
910
911#[derive(Debug, thiserror::Error)]
912pub enum GrammarError {
913    #[error("graph JSON: {0}")]
914    Json(String),
915    #[error("profile: {0}")]
916    Invalid(String),
917}
918
919/// Raw shape: sections as written, before validation.
920#[derive(Debug, Deserialize)]
921#[serde(deny_unknown_fields)]
922struct Raw {
923    #[serde(default)]
924    title: Option<String>,
925    output: crate::profile::OutputSpec,
926    #[serde(default, rename = "$features", deserialize_with = "ordered_defs")]
927    features: Vec<(String, RawOp)>,
928    #[serde(default, rename = "$areas", deserialize_with = "ordered_defs")]
929    areas: Vec<(String, RawOp)>,
930    #[serde(default, rename = "$lines", deserialize_with = "ordered_defs")]
931    lines: Vec<(String, RawOp)>,
932    #[serde(default, rename = "$fills", deserialize_with = "ordered_defs")]
933    fills: Vec<(String, RawOp)>,
934    /// Recognised so the error is clear, not "unknown field".
935    #[serde(default)]
936    draw: Vec<RawDraw>,
937    #[serde(default)]
938    compose: RawCompose,
939    #[serde(default)]
940    views: Vec<RawView>,
941}
942
943#[derive(Debug, Deserialize)]
944#[serde(deny_unknown_fields)]
945struct RawView {
946    id: String,
947    at: [f64; 2],
948    graph: Value,
949    #[serde(default)]
950    ink: Option<String>,
951}
952
953
954/// `Vec<(String, T)>` from a YAML/JSON **mapping**, keeping the written order.
955/// Used for the `$sections` (def name → operation) and for `compose.masks`.
956fn ordered_defs<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<(String, RawOp)>, D::Error> {
957    ordered_map(d)
958}
959
960fn ordered_masks<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<(String, RawMask)>, D::Error> {
961    ordered_map(d)
962}
963
964fn ordered_map<'de, D, T>(d: D) -> Result<Vec<(String, T)>, D::Error>
965where
966    D: Deserializer<'de>,
967    T: serde::de::DeserializeOwned,
968{
969    struct V<T>(std::marker::PhantomData<T>);
970    impl<'de, T: serde::de::DeserializeOwned> Visitor<'de> for V<T> {
971        type Value = Vec<(String, T)>;
972        fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
973            f.write_str("a mapping of name to value")
974        }
975        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
976            let mut out = Vec::new();
977            while let Some((k, v)) = map.next_entry::<String, T>()? {
978                out.push((k, v));
979            }
980            Ok(out)
981        }
982        /// `$features:` with nothing under it is an empty section, not an error.
983        fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
984            Ok(Vec::new())
985        }
986    }
987    d.deserialize_any(V(std::marker::PhantomData))
988}
989
990#[derive(Debug, Deserialize)]
991#[serde(deny_unknown_fields)]
992struct RawDraw {
993    #[serde(default)]
994    id: Option<String>,
995    from: String,
996    #[serde(default)]
997    stroke: Option<StrokeSpec>,
998    #[serde(default)]
999    at: Option<At>,
1000}
1001
1002#[derive(Debug, Default, Deserialize)]
1003#[serde(deny_unknown_fields)]
1004struct RawCompose {
1005    #[serde(default)]
1006    order: Vec<String>,
1007    #[serde(default, deserialize_with = "ordered_masks")]
1008    masks: Vec<(String, RawMask)>,
1009    #[serde(default)]
1010    clip: ClipBlock,
1011    #[serde(default)]
1012    optimize: Vec<RawOptimizeStep>,
1013}
1014
1015#[derive(Debug, Clone, Serialize, Deserialize)]
1016pub struct RawOptimizeStep {
1017    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1018    pub layers: Vec<String>,
1019    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1020    pub except: Vec<String>,
1021    #[serde(flatten)]
1022    pub op: crate::optimize::OptimizeOp,
1023    #[serde(default, skip_serializing_if = "Option::is_none")]
1024    pub at: Option<At>,
1025}
1026
1027#[derive(Debug, Default, Deserialize)]
1028#[serde(deny_unknown_fields)]
1029struct ClipBlock {
1030    #[serde(default)]
1031    default: Option<ClipValue>,
1032}
1033
1034#[derive(Debug, Clone, Deserialize)]
1035#[serde(untagged)]
1036enum ClipValue {
1037    Keyword(String),
1038    List(Vec<String>),
1039}
1040
1041#[derive(Debug, Deserialize)]
1042#[serde(deny_unknown_fields)]
1043struct RawMask {
1044    from: String,
1045    #[serde(default)]
1046    occludes: Vec<String>,
1047    #[serde(default)]
1048    at: Option<At>,
1049}
1050
1051/// One operation, as a single-key mapping. The key picks the variant; a def
1052/// with several keys is an error (one operation per def).
1053/// `at: [line, column]` may sit next to the operation key: where the script
1054/// made the def.
1055#[derive(Debug)]
1056struct RawOp(BTreeMap<String, Value>, Option<At>);
1057
1058impl<'de> Deserialize<'de> for RawOp {
1059    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1060        struct V;
1061        impl<'de> Visitor<'de> for V {
1062            type Value = RawOp;
1063            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
1064                f.write_str("a mapping with exactly one operation key")
1065            }
1066            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<RawOp, A::Error> {
1067                let mut entries = BTreeMap::new();
1068                let mut at = None;
1069                while let Some((k, v)) = map.next_entry::<String, Value>()? {
1070                    if k == "at" {
1071                        at = Some(serde_json::from_value(v).map_err(de::Error::custom)?);
1072                    } else {
1073                        entries.insert(k, v);
1074                    }
1075                }
1076                if entries.len() != 1 {
1077                    let keys: Vec<&str> = entries.keys().map(String::as_str).collect();
1078                    return Err(de::Error::custom(format!(
1079                        "a def takes exactly one operation, found {}: {}",
1080                        entries.len(),
1081                        keys.join(", ")
1082                    )));
1083                }
1084                Ok(RawOp(entries, at))
1085            }
1086            /// `def: name` with no body (an alias style) is not supported here.
1087            fn visit_str<E: de::Error>(self, v: &str) -> Result<RawOp, E> {
1088                Err(de::Error::custom(format!(
1089                    "expected an operation, found the bare name {v:?}; write `tools_union: [{v}]` or a real op"
1090                )))
1091            }
1092        }
1093        d.deserialize_any(V)
1094    }
1095}
1096
1097/// Peak at the operation key without consuming the rest.
1098fn only_op(raw: RawOp) -> Result<(String, Value), String> {
1099    let (k, v) = raw.0.into_iter().next().ok_or("empty operation")?;
1100    Ok((k, v))
1101}
1102
1103fn json<T: serde::de::DeserializeOwned>(value: &Value, what: &str) -> Result<T, GrammarError> {
1104    serde_json::from_value(value.clone()).map_err(|e| GrammarError::Invalid(format!("{what}: {e}")))
1105}
1106
1107/// Tests write graphs as YAML, the op form's shortest spelling; the engine
1108/// itself reads only JSON.
1109#[cfg(test)]
1110pub(crate) fn from_yaml(text: &str) -> Result<Grammar, GrammarError> {
1111    let value: Value = serde_saphyr::from_str(text).map_err(|e| GrammarError::Json(e.to_string()))?;
1112    Grammar::from_json(&value.to_string())
1113}
1114
1115fn build(raw: Raw) -> Result<Grammar, GrammarError> {
1116    let mut sections: Vec<(Section, Vec<Def>)> = Vec::new();
1117    for (section, entries) in [
1118        (Section::Features, raw.features),
1119        (Section::Areas, raw.areas),
1120        (Section::Lines, raw.lines),
1121        (Section::Fills, raw.fills),
1122    ] {
1123        if entries.is_empty() {
1124            continue;
1125        }
1126        let mut seen = BTreeSet::new();
1127        let mut defs = Vec::new();
1128        for (name, raw_op) in entries {
1129            if !seen.insert(name.clone()) {
1130                return Err(GrammarError::Invalid(format!("${}.{} is defined twice", section, name)));
1131            }
1132            let at = raw_op.1;
1133            let op = parse_op(raw_op, section).map_err(|e| match e {
1134                GrammarError::Invalid(m) => GrammarError::Invalid(located(&format!("${section}.{name}: {m}"), at)),
1135                other => other,
1136            })?;
1137            defs.push(Def { name, op, at });
1138        }
1139        sections.push((section, defs));
1140    }
1141
1142    let draw = raw
1143        .draw
1144        .into_iter()
1145        .map(|d| {
1146            Ok(Draw {
1147                from: parse_output(&d.from)?,
1148                id: d.id,
1149                stroke: d.stroke,
1150                at: d.at,
1151            })
1152        })
1153        .collect::<Result<Vec<_>, GrammarError>>()?;
1154
1155    let mut masks = Vec::new();
1156    for (name, m) in raw.compose.masks {
1157        masks.push((
1158            name,
1159            Mask {
1160                from: parse_output(&m.from)?,
1161                occludes: m.occludes.into_iter().map(Id).collect(),
1162                at: m.at,
1163            },
1164        ));
1165    }
1166
1167    let clip_default = match &raw.compose.clip.default {
1168        None => Clip::Auto,
1169        Some(ClipValue::Keyword(k)) => match k.as_str() {
1170            "auto" => Clip::Auto,
1171            "none" => Clip::None,
1172            other => {
1173                return Err(GrammarError::Invalid(format!(
1174                    "clip default {other:?} is unknown: write auto, none, or a list of $areas.*"
1175                )))
1176            }
1177        },
1178        Some(ClipValue::List(names)) => Clip::Areas(
1179            names
1180                .iter()
1181                .map(|n| refname(n))
1182                .collect::<Result<Vec<_>, _>>()?,
1183        ),
1184    };
1185
1186    let optimize = raw
1187        .compose
1188        .optimize
1189        .into_iter()
1190        .map(|s| crate::optimize::OptimizeStep {
1191            layers: s.layers.into_iter().map(Id).collect(),
1192            except: s.except.into_iter().map(Id).collect(),
1193            op: s.op,
1194            at: s.at,
1195        })
1196        .collect();
1197
1198    let compose = Compose {
1199        order: raw.compose.order.into_iter().map(Id).collect(),
1200        masks,
1201        clip: BTreeMap::new(),
1202        clip_default,
1203        optimize,
1204    };
1205
1206    let views = raw
1207        .views
1208        .into_iter()
1209        .map(|v| {
1210            let inner: Raw = serde_json::from_value(v.graph).map_err(|e| GrammarError::Json(format!("views.{}: {e}", v.id)))?;
1211            let grammar = build(inner).map_err(|e| GrammarError::Invalid(format!("view {}: {e}", v.id)))?;
1212            Ok(View { id: v.id, at: (v.at[0], v.at[1]), grammar: Box::new(grammar), ink: v.ink })
1213        })
1214        .collect::<Result<Vec<_>, GrammarError>>()?;
1215    let grammar = Grammar { title: raw.title, output: raw.output, sections, draw, compose, views };
1216    validate(&grammar)?;
1217    Ok(grammar)
1218}
1219
1220fn not_a_reference(text: String) -> GrammarError {
1221    GrammarError::Invalid(format!("{text:?} is not a $section.name reference"))
1222}
1223
1224/// `$lines.x`, `$fills.x`, or `roads.outlines` (a module output).
1225fn parse_output(text: &str) -> Result<Target, GrammarError> {
1226    if let Some(rest) = text.strip_prefix('$') {
1227        return Ok(Target { module: None, name: refname(&format!("${rest}"))? });
1228    }
1229    match text.split_once('.') {
1230        Some((module, name)) if !name.is_empty() => {
1231            Ok(Target { module: Some(module.to_string()), name: Name { section: Section::Lines, name: name.to_string() } })
1232        }
1233        _ => Err(GrammarError::Invalid(format!(
1234            "{text:?} is not a reference: write $lines.x, $fills.x or <module>.<output>"
1235        ))),
1236    }
1237}
1238
1239fn refname(text: &str) -> Result<Name, GrammarError> {
1240    Name::parse(text).map_err(|_| not_a_reference(text.to_string()))
1241}
1242
1243/// A draw/`from` target: `$lines.x` / `$fills.x`, or `roads.outlines` (a module
1244/// output, which has no `$` because the engine produced it).
1245#[derive(Debug, Clone, PartialEq, Eq)]
1246pub struct Target {
1247    /// `None` = a `$section.name` def; `Some(module)` = a module output.
1248    pub module: Option<String>,
1249    pub name: Name,
1250}
1251
1252fn parse_op(raw: RawOp, section: Section) -> Result<Op, GrammarError> {
1253    let (key, value) = only_op(raw).map_err(GrammarError::Invalid)?;
1254    let target = match key.as_str() {
1255        "osm_select" | "tiles_select" | "data_select" | "terrain_select" | "tools_where" => Section::Features,
1256        "tools_polygons" | "tools_union" | "tools_difference" | "tools_intersect" | "tools_fill_holes"
1257        | "tools_fill_cover" | "tools_grow" | "tools_move" | "tools_around" | "tools_shape" | "tools_text_area" | "tools_buffer_lines" | "tools_label_area" | "tools_graticule_area" | "tools_extend_to_frame" | "tools_terrain_band" | "engine_frame" => {
1258            Section::Areas
1259        }
1260        "tools_rings" | "tools_lines" | "tools_segments" | "tools_dedupe" | "tools_merge" | "tools_join"
1261        | "tools_clip" | "tools_path" | "tools_text" | "tools_terrain" | "tools_burin" | "tools_labels" | "tools_label_lines" | "tools_graticule" => Section::Lines,
1262        "tools_fill" => Section::Fills,
1263        other => {
1264            if let Some(rest) = other.strip_prefix("module_") {
1265                let mut obj = value.as_object().cloned().ok_or_else(|| {
1266                    GrammarError::Json(format!("{key}: expected an object"))
1267                })?;
1268                let from_val = obj.remove("from");
1269                let from = match from_val {
1270                    Some(Value::String(s)) => Some(refname(&s)?),
1271                    Some(v) => return Err(GrammarError::Json(format!("{key}.from: expected a string, got {v}"))),
1272                    None => None,
1273                };
1274                if let Some(f) = &from {
1275                    if f.section != Section::Features {
1276                        return Err(GrammarError::Invalid(format!("{key}.from is {f}, but it must be a $features set")));
1277                    }
1278                }
1279                let roads: crate::themes::RoadOptions = json(&Value::Object(obj), &key)?;
1280                roads.validate().map_err(GrammarError::Invalid)?;
1281                return Ok(Op::Module(Module { name: rest.to_string(), from, roads }));
1282            }
1283            if let Some(rest) = other.strip_prefix("primitives_") {
1284                return Err(GrammarError::Invalid(format!(
1285                    "primitives_{rest} is not defined in this build"
1286                )));
1287            }
1288            return Err(GrammarError::Invalid(format!("unknown operation {other:?}")));
1289        }
1290    };
1291    if target != section {
1292        return Err(GrammarError::Invalid(format!(
1293            "{key} produces {target}, but it is written under ${section}"
1294        )));
1295    }
1296    let _ = target;
1297    let op = match key.as_str() {
1298        "osm_select" => Op::Select(parse_selector(&value)?),
1299        "tiles_select" => Op::TileSelect(parse_tile_select(&value)?),
1300        "terrain_select" => {
1301            let t: crate::contours::TerrainSelect = json(&value, "terrain_select")?;
1302            t.validate().map_err(GrammarError::Invalid)?;
1303            Op::TerrainSelect(t)
1304        }
1305        "data_select" => match &value {
1306            Value::String(s) if !s.trim().is_empty() => Op::DataSelect(DataSource::Url(s.trim().to_string())),
1307            Value::Object(o) if o.len() == 1 && o.get("geojson").is_some_and(Value::is_object) => {
1308                let gj = o["geojson"].clone();
1309                crate::geojson::features_of(&gj).map_err(|e| GrammarError::Invalid(format!("data_select: {e}")))?;
1310                Op::DataSelect(DataSource::Inline(gj))
1311            }
1312            Value::Object(o) if o.len() == 1 && o.get("json").is_some_and(Value::is_object) => {
1313                let js: JsonSource = serde_json::from_value(o["json"].clone())
1314                    .map_err(|e| GrammarError::Invalid(format!("data_select.json: {e}")))?;
1315                if js.url.trim().is_empty() || js.lat.is_empty() || js.lng.is_empty() {
1316                    return Err(GrammarError::Invalid("data_select.json needs a url, and the lat and lng paths".into()));
1317                }
1318                Op::DataSelect(DataSource::Json(js))
1319            }
1320            _ => return Err(GrammarError::Invalid("data_select is a URL, a file path, { geojson: {…} } or { json: { url, items, lat, lng } }".into())),
1321        },
1322        "tools_where" => Op::Where(parse_where(&value)?),
1323        "engine_frame" => Op::Frame,
1324        "tools_polygons" => Op::Polygons(name_ref(&value, "tools_polygons")?),
1325        "tools_union" => Op::Union(union_rules(&value, "tools_union")?),
1326        "tools_difference" => {
1327            #[derive(Deserialize)]
1328            struct Raw {
1329                base: String,
1330                cut: OneOrMany,
1331            }
1332            let raw: Raw = json(&value, "tools_difference")?;
1333            let (cut, cut_rule) = cut_rules(&raw.cut.into_vec(), "tools_difference.cut")?;
1334            Op::Difference(Difference { base: refname(&raw.base)?, cut, cut_rule })
1335        }
1336        "tools_intersect" => {
1337            #[derive(Deserialize)]
1338            struct Raw {
1339                base: String,
1340                #[serde(default)]
1341                keep: Option<String>,
1342                #[serde(default)]
1343                keep_rule: Option<RawOp>,
1344            }
1345            let raw: Raw = json(&value, "tools_intersect")?;
1346            if raw.keep.is_some() == raw.keep_rule.is_some() {
1347                return Err(GrammarError::Invalid(
1348                    "tools_intersect needs exactly one of `keep: $areas.x` or `keep_rule: { ... }`".into(),
1349                ));
1350            }
1351            let keep_rule = match raw.keep_rule {
1352                Some(op) => Some(Box::new(parse_op(op, Section::Areas)?)),
1353                None => None,
1354            };
1355            Op::Intersect(Intersect {
1356                base: refname(&raw.base)?,
1357                keep: raw.keep.as_deref().map(refname).transpose()?,
1358                keep_rule,
1359            })
1360        }
1361        "tools_fill_holes" => Op::FillHoles(name_ref(&value, "tools_fill_holes")?),
1362        "tools_label_area" => Op::LabelArea(parse_label_pick(&value, "tools_label_area")?),
1363        "tools_label_lines" => Op::LabelLines(parse_label_pick(&value, "tools_label_lines")?),
1364        "tools_move" => {
1365            #[derive(Deserialize)]
1366            #[serde(deny_unknown_fields)]
1367            struct Raw {
1368                of: String,
1369                by: [Mm; 2],
1370            }
1371            let raw: Raw = json(&value, "tools_move")?;
1372            Op::Move(Move { of: refname(&raw.of)?, by: raw.by })
1373        }
1374        "tools_grow" => {
1375            #[derive(Deserialize)]
1376            #[serde(deny_unknown_fields)]
1377            struct Raw {
1378                of: String,
1379                by: Mm,
1380            }
1381            let raw: Raw = json(&value, "tools_grow")?;
1382            Op::Grow(Grow { of: refname(&raw.of)?, by: raw.by })
1383        }
1384        "tools_around" => {
1385            #[derive(Deserialize)]
1386            #[serde(deny_unknown_fields)]
1387            struct Raw {
1388                of: String,
1389                by: Mm,
1390            }
1391            let raw: Raw = json(&value, "tools_around")?;
1392            let of = refname(&raw.of)?;
1393            if of.section != Section::Features {
1394                return Err(GrammarError::Invalid("tools_around: of must be $features".into()));
1395            }
1396            Op::Around(Around { of, by: raw.by })
1397        }
1398        "tools_shape" | "tools_path" => {
1399            let shape: Shape = json(&value, &key)?;
1400            if let ShapeAt::Page(xy) = &shape.at {
1401                for p in xy {
1402                    if let PagePos::Percent(s) = p {
1403                        if percent(s).is_none() {
1404                            return Err(GrammarError::Invalid(format!("{key}.at: {s:?} is not a length or a percentage")));
1405                        }
1406                    }
1407                }
1408            }
1409            if shape.points.len() < if key == "tools_shape" { 3 } else { 2 } {
1410                return Err(GrammarError::Invalid(format!("{key}: too few points")));
1411            }
1412            if key == "tools_shape" { Op::Shape(shape) } else { Op::Path(shape) }
1413        }
1414        "tools_text" | "tools_text_area" => {
1415            let text: Text = json(&value, &key)?;
1416            crate::text::validate_label_font(&text.font).map_err(GrammarError::Invalid)?;
1417            if key == "tools_text" { Op::Text(text) } else { Op::TextArea(text) }
1418        }
1419        "tools_buffer_lines" => {
1420            #[derive(Deserialize)]
1421            #[serde(deny_unknown_fields)]
1422            struct Raw {
1423                lines: String,
1424                by: Mm,
1425                #[serde(default)]
1426                cap: LineBufferCap,
1427            }
1428            let raw: Raw = json(&value, "tools_buffer_lines")?;
1429            Op::BufferLines(BufferLines { lines: refname(&raw.lines)?, by: raw.by, cap: raw.cap })
1430        }
1431        "tools_extend_to_frame" => {
1432            #[derive(Deserialize)]
1433            #[serde(deny_unknown_fields)]
1434            struct Raw {
1435                of: String,
1436                within: String,
1437                // Read and ignored: saved graphs still carry it.
1438                #[serde(rename = "min_height_frac")]
1439                _min_height_frac: Option<f64>,
1440                gap_mm: Option<Mm>,
1441            }
1442            let raw: Raw = json(&value, "tools_extend_to_frame")?;
1443            Op::ExtendToFrame(ExtendToFrame {
1444                of: refname(&raw.of)?,
1445                within: refname(&raw.within)?,
1446                gap_mm: raw.gap_mm,
1447            })
1448        }
1449        "tools_terrain" | "tools_terrain_band" => {
1450            #[derive(Deserialize)]
1451            #[serde(deny_unknown_fields)]
1452            struct Raw {
1453                #[serde(default)]
1454                in_area: Option<String>,
1455                #[serde(default)]
1456                color: Option<serde_json::Value>,
1457                #[serde(default)]
1458                width: Option<serde_json::Value>,
1459                #[serde(default)]
1460                angle: Option<f64>,
1461                #[serde(default)]
1462                layer: Option<String>,
1463                #[serde(default)]
1464                shore: Option<bool>,
1465                #[serde(default)]
1466                style: Option<serde_json::Map<String, serde_json::Value>>,
1467                #[serde(default)]
1468                r#where: Option<serde_json::Map<String, serde_json::Value>>,
1469                #[serde(default)]
1470                draw: Option<String>,
1471            }
1472            let raw: Raw = json(&value, "tools_terrain")?;
1473            let band = key.as_str() == "tools_terrain_band";
1474            let t = Terrain {
1475                in_area: raw.in_area.as_deref().map(refname).transpose()?,
1476                color: raw.color,
1477                width: raw.width,
1478                angle: raw.angle.unwrap_or(0.0),
1479                layer: raw.layer,
1480                style: raw.style.unwrap_or_default(),
1481                shore: raw.shore.unwrap_or(false),
1482                band: raw.r#where.unwrap_or_default(),
1483                draw: match raw.draw.as_deref() {
1484                    None | Some("lines") => TerrainDraw::Lines,
1485                    Some("fill") => TerrainDraw::Fill,
1486                    Some("dots") => TerrainDraw::Dots,
1487                    Some(other) => {
1488                        return Err(GrammarError::Invalid(format!(
1489                            "tools_terrain draws lines, a fill or dots, not {other:?}"
1490                        )))
1491                    }
1492                },
1493            };
1494            if band {
1495                Op::TerrainBand(Terrain { draw: TerrainDraw::Fill, ..t })
1496            } else {
1497                Op::Terrain(t)
1498            }
1499        }
1500        "tools_burin" => {
1501            #[derive(Deserialize)]
1502            #[serde(deny_unknown_fields)]
1503            struct Raw {
1504                /// The atlas, as `burin.json()` writes it: a list, or the JSON
1505                /// string of one (the library hands a string).
1506                atlas: Value,
1507                #[serde(default)]
1508                in_area: Option<String>,
1509                #[serde(default)]
1510                regions: std::collections::BTreeMap<String, String>,
1511                #[serde(default)]
1512                water: Option<String>,
1513                #[serde(default)]
1514                layer: Option<String>,
1515            }
1516            let raw: Raw = json(&value, "tools_burin")?;
1517            let regions = raw
1518                .regions
1519                .into_iter()
1520                .map(|(name, r)| {
1521                    let n = refname(&r)?;
1522                    if n.section != Section::Areas {
1523                        return Err(GrammarError::Invalid(format!(
1524                            "tools_burin.regions.{name} must be an area, not {n}"
1525                        )));
1526                    }
1527                    Ok((name, n))
1528                })
1529                .collect::<Result<_, _>>()?;
1530            let atlas = match raw.atlas {
1531                Value::String(text) => {
1532                    serde_json::from_str(&text).map_err(|e| GrammarError::Invalid(format!("tools_burin atlas: {e}")))?
1533                }
1534                other => other,
1535            };
1536            if !atlas.is_array() {
1537                return Err(GrammarError::Invalid("tools_burin atlas is a list of batches and water passes".into()));
1538            }
1539            Op::Burin(Burin {
1540                atlas,
1541                in_area: raw.in_area.as_deref().map(refname).transpose()?,
1542                regions,
1543                water: raw.water.as_deref().map(refname).transpose()?,
1544                layer: raw.layer,
1545            })
1546        }
1547        "tools_graticule" | "tools_graticule_area" => {
1548            let mut body = match value {
1549                Value::Object(m) => m,
1550                _ => return Err(GrammarError::Invalid(format!("{key} takes {{ in, part, step, ... }}"))),
1551            };
1552            let in_area = match body.remove("in") {
1553                Some(Value::String(s)) => refname(&s)?,
1554                _ => return Err(GrammarError::Invalid(format!("{key} needs in: an $areas reference"))),
1555            };
1556            if in_area.section != Section::Areas {
1557                return Err(GrammarError::Invalid(format!("{key}.in is {in_area}, but it reads an $areas def")));
1558            }
1559            let look: GraticuleLook = json(&Value::Object(body), &key)?;
1560            crate::text::validate_label_font(&look.font).map_err(GrammarError::Invalid)?;
1561            if !(look.step > 0.0) {
1562                return Err(GrammarError::Invalid(format!("{key}.step is minutes of arc, more than 0")));
1563            }
1564            let fits = match look.part {
1565                GraticulePart::Grid => key == "tools_graticule",
1566                GraticulePart::Keys => key == "tools_graticule_area",
1567                GraticulePart::Labels => true,
1568            };
1569            if !fits {
1570                return Err(GrammarError::Invalid(format!("{key}: part {:?} is not drawn by it", look.part)));
1571            }
1572            let g = Graticule { in_area, look };
1573            if key == "tools_graticule" { Op::Graticule(g) } else { Op::GraticuleArea(g) }
1574        }
1575        "tools_labels" => {
1576            let mut body = match value {
1577                Value::Object(m) => m,
1578                _ => return Err(GrammarError::Invalid("tools_labels takes { from, ...style }".into())),
1579            };
1580            let from: Vec<Name> = match body.remove("from") {
1581                Some(Value::String(s)) => vec![refname(&s)?],
1582                Some(Value::Array(items)) if !items.is_empty() => items
1583                    .iter()
1584                    .map(|v| v.as_str().ok_or_else(|| not_a_reference(v.to_string())).and_then(refname))
1585                    .collect::<Result<_, _>>()?,
1586                _ => return Err(GrammarError::Invalid("tools_labels needs from: $features.x or a list of them".into())),
1587            };
1588            if let Some(f) = from.iter().find(|f| f.section != Section::Features) {
1589                return Err(GrammarError::Invalid(format!("tools_labels.from has {f}, but it reads $features sets")));
1590            }
1591            let mut area_ref = |key: &str| -> Result<Option<Name>, GrammarError> {
1592                match body.remove(key) {
1593                    None => Ok(None),
1594                    Some(Value::String(s)) => {
1595                        let n = refname(&s)?;
1596                        if n.section != Section::Areas {
1597                            return Err(GrammarError::Invalid(format!("tools_labels.{key} is {n}, but it reads an $areas def")));
1598                        }
1599                        Ok(Some(n))
1600                    }
1601                    Some(_) => Err(GrammarError::Invalid(format!("tools_labels.{key} expects an $areas reference"))),
1602                }
1603            };
1604            let in_area = area_ref("in")?;
1605            let avoid = area_ref("avoid")?;
1606            let style: crate::labels::Style = json(&Value::Object(body), "tools_labels")?;
1607            crate::labels::validate_style(&style).map_err(GrammarError::Invalid)?;
1608            Op::Labels(Labels { from, in_area, avoid, style })
1609        }
1610        "tools_rings" => match &value {
1611            Value::String(s) => Op::Rings(Rings { of: refname(s)?, exterior_only: false }),
1612            _ => {
1613                #[derive(Deserialize)]
1614                #[serde(deny_unknown_fields)]
1615                struct Raw {
1616                    of: String,
1617                    #[serde(default)]
1618                    exterior_only: bool,
1619                }
1620                let raw: Raw = json(&value, "tools_rings")?;
1621                Op::Rings(Rings { of: refname(&raw.of)?, exterior_only: raw.exterior_only })
1622            }
1623        },
1624        "tools_lines" => Op::Lines(name_ref(&value, "tools_lines")?),
1625        "tools_segments" => Op::Segments(name_ref(&value, "tools_segments")?),
1626        "tools_dedupe" => Op::Dedupe(name_ref(&value, "tools_dedupe")?),
1627        "tools_merge" => Op::Merge(name_ref(&value, "tools_merge")?),
1628        "tools_join" => Op::Join(union_rules(&value, "tools_join")?),
1629        "tools_clip" => {
1630            #[derive(Deserialize)]
1631            #[serde(deny_unknown_fields)]
1632            struct Raw {
1633                lines: String,
1634                within: String,
1635                #[serde(default)]
1636                invert: bool,
1637            }
1638            let raw: Raw = json(&value, "tools_clip")?;
1639            Op::ClipLines(ClipLines { lines: refname(&raw.lines)?, within: refname(&raw.within)?, invert: raw.invert })
1640        }
1641        "tools_fill" | "tools_fill_cover" => {
1642            // The v3 toolkit writes `pattern:` (dots, waves, zigzag…), the spec
1643            // calls it `generator:`; one rename and the rest is FillSpec.
1644            #[derive(Deserialize)]
1645            struct Raw {
1646                #[serde(rename = "in")]
1647                in_area: String,
1648                #[serde(default)]
1649                per: Option<String>,
1650                #[serde(default)]
1651                pattern: Option<String>,
1652                #[serde(default)]
1653                content: Option<String>,
1654                #[serde(flatten)]
1655                spec: FillSpec,
1656            }
1657            let mut raw: Raw = json(&value, &key)?;
1658            if let Some(pattern) = raw.pattern.take() {
1659                if raw.spec.generator.is_none() {
1660                    raw.spec.generator = Some(pattern);
1661                }
1662            }
1663            let per_feature = match raw.per.as_deref() {
1664                None => false,
1665                Some("feature") => true,
1666                Some(other) => {
1667                    return Err(GrammarError::Invalid(format!(
1668                        "tools_fill: per: {other:?} is unknown (only `per: feature`)"
1669                    )))
1670                }
1671            };
1672            let content = raw.content.as_deref().map(refname).transpose()?;
1673            if content.as_ref().is_some_and(|c| c.section != Section::Lines) {
1674                return Err(GrammarError::Invalid("tools_fill: content must be $lines".into()));
1675            }
1676            // A motif given as `$lines.…` is a reference, resolved when the fill
1677            // runs; polylines or a symbol name stay in the spec as they are.
1678            let motif = match raw.spec.options.get("motif") {
1679                Some(Value::String(s)) if s.starts_with('$') => {
1680                    let name = refname(s)?;
1681                    if name.section != Section::Lines {
1682                        return Err(GrammarError::Invalid("tools_fill: motif must be $lines, polylines or a symbol name".into()));
1683                    }
1684                    raw.spec.options.remove("motif");
1685                    Some(name)
1686                }
1687                _ => None,
1688            };
1689            let fill = Fill { in_area: refname(&raw.in_area)?, per_feature, content, motif, spec: raw.spec };
1690            if key == "tools_fill" {
1691                Op::Fill(fill)
1692            } else if fill.per_feature || fill.content.is_some() {
1693                return Err(GrammarError::Invalid("tools_fill_cover takes a pattern, not per or content".into()));
1694            } else {
1695                Op::FillCover(fill)
1696            }
1697        }
1698        _ => unreachable!("keys are matched above"),
1699    };
1700    Ok(op)
1701}
1702
1703/// `tools_difference.cut`: a list of references, or one inline rule.
1704fn cut_rules(items: &[String], what: &str) -> Result<(Vec<Name>, Option<Box<Op>>), GrammarError> {
1705    if items.is_empty() {
1706        return Err(GrammarError::Invalid(format!("{what} needs at least one input")));
1707    }
1708    if items.len() == 1 {
1709        if let Ok(op) = serde_json::from_str::<RawOp>(&items[0]) {
1710            return Err(GrammarError::Invalid(format!(
1711                "{what}: inline rules are not supported yet; define it under $areas and use $areas.name ({op:?})"
1712            )));
1713        }
1714    }
1715    Ok((items.iter().map(|s| refname(s)).collect::<Result<_, _>>()?, None))
1716}
1717
1718fn name_ref(value: &Value, op: &str) -> Result<Name, GrammarError> {
1719    let s: String = json(value, op)?;
1720    refname(&s)
1721}
1722
1723fn parse_label_pick(value: &Value, op: &str) -> Result<LabelPick, GrammarError> {
1724    match value {
1725        Value::String(s) => {
1726            let of = refname(s)?;
1727            if of.section != Section::Lines {
1728                return Err(GrammarError::Invalid(format!("{op} reads {of}, but labels live under $lines")));
1729            }
1730            Ok(LabelPick { of, rule: None, dots: false })
1731        }
1732        _ => {
1733            #[derive(Deserialize)]
1734            #[serde(deny_unknown_fields)]
1735            struct Raw {
1736                of: String,
1737                #[serde(default)]
1738                rule: Option<String>,
1739                #[serde(default)]
1740                dots: bool,
1741            }
1742            let raw: Raw = json(value, op)?;
1743            let of = refname(&raw.of)?;
1744            if of.section != Section::Lines {
1745                return Err(GrammarError::Invalid(format!("{op}.of is {of}, but labels live under $lines")));
1746            }
1747            Ok(LabelPick { of, rule: raw.rule, dots: raw.dots })
1748        }
1749    }
1750}
1751
1752fn label_pick_json(pick: &LabelPick) -> Value {
1753    use serde_json::json;
1754    match (&pick.rule, pick.dots) {
1755        (None, false) => Value::String(pick.of.to_string()),
1756        (rule, false) => json!({ "of": pick.of.to_string(), "rule": rule }),
1757        (None, true) => json!({ "of": pick.of.to_string(), "dots": true }),
1758        (rule, true) => json!({ "of": pick.of.to_string(), "rule": rule, "dots": true }),
1759    }
1760}
1761
1762/// `tools_union`: a list of references, or one reference with `list: false`.
1763fn union_rules(value: &Value, op: &str) -> Result<UnionRules, GrammarError> {
1764    #[derive(Deserialize)]
1765    #[serde(deny_unknown_fields)]
1766    struct Raw {
1767        #[serde(default)]
1768        refs: Vec<String>,
1769        #[serde(default, rename = "ref")]
1770        single: Option<String>,
1771        #[serde(default)]
1772        list: Option<bool>,
1773        #[serde(default)]
1774        rule: Option<RawOp>,
1775    }
1776    match value {
1777        // The plain form: `tools_union: [{ tools_polygons: ... }, ...]`
1778        Value::Array(items) => {
1779            if items.is_empty() {
1780                return Err(GrammarError::Invalid(format!("{op} needs at least one input")));
1781            }
1782            Ok(UnionRules::Refs(inline_list(items, op)?))
1783        }
1784        Value::String(s) => Ok(UnionRules::Ref(refname(s)?)),
1785        Value::Object(_) => {
1786            let raw: Raw = json(value, op)?;
1787            if let Some(rule) = raw.rule {
1788                let parsed = parse_op(rule, Section::Areas)?;
1789                if parsed.section() != Section::Areas {
1790                    return Err(GrammarError::Invalid(format!(
1791                        "{op}: `rule` must produce an area"
1792                    )));
1793                }
1794                return Ok(UnionRules::Refs(parsed.refs()));
1795            }
1796            match (raw.single, raw.list, raw.refs.is_empty()) {
1797                (Some(s), Some(false), true) => Ok(UnionRules::Ref(refname(&s)?)),
1798                (Some(s), _, true) => Ok(UnionRules::Ref(refname(&s)?)),
1799                (None, _, false) => Ok(UnionRules::Refs(
1800                    raw.refs.iter().map(|s| refname(s)).collect::<Result<_, _>>()?,
1801                )),
1802                _ => Err(GrammarError::Invalid(format!(
1803                    "{op} needs a list of references (or `list: false` with one)"
1804                ))),
1805            }
1806        }
1807        other => Err(GrammarError::Invalid(format!("{op}: unexpected {other}"))),
1808    }
1809}
1810
1811/// A list that may contain `$refs` and/or one inline rule.
1812/// v3 allows exactly one form: if a rule is present it must be the only item.
1813fn inline_list(items: &[Value], op: &str) -> Result<Vec<Name>, GrammarError> {
1814    let mut refs = Vec::new();
1815    let mut rules = 0usize;
1816    for item in items {
1817        match item {
1818            Value::String(s) => refs.push(refname(s)?),
1819            Value::Object(_) => rules += 1,
1820            other => return Err(GrammarError::Invalid(format!("{op}: unexpected item {other}"))),
1821        }
1822    }
1823    if rules > 1 || (rules == 1 && !refs.is_empty()) {
1824        return Err(GrammarError::Invalid(format!(
1825            "{op}: write one inline rule, or a list of $refs, not both"
1826        )));
1827    }
1828    Ok(refs)
1829}
1830
1831#[derive(Debug, Deserialize)]
1832#[serde(untagged)]
1833enum OneOrMany {
1834    One(String),
1835    Many(Vec<String>),
1836}
1837
1838impl OneOrMany {
1839    fn into_vec(self) -> Vec<String> {
1840        match self {
1841            OneOrMany::One(s) => vec![s],
1842            OneOrMany::Many(v) => v,
1843        }
1844    }
1845}
1846
1847fn parse_tile_select(value: &Value) -> Result<TileSelect, GrammarError> {
1848    let items: Vec<String> = json::<OneOrMany>(value, "tiles_select")?
1849        .into_vec()
1850        .iter()
1851        .flat_map(|s| s.split(|c: char| c.is_whitespace()).map(str::to_string).collect::<Vec<_>>())
1852        .filter(|s| !s.is_empty())
1853        .collect();
1854    if items.is_empty() {
1855        return Err(GrammarError::Invalid("tiles_select needs a preset or a layer:class rule".into()));
1856    }
1857    let filter = terramask::Filter::parse(&items).map_err(|e| GrammarError::Invalid(format!("tiles_select: {e}")))?;
1858    Ok(TileSelect { items, filter })
1859}
1860
1861fn parse_where(value: &Value) -> Result<Where, GrammarError> {
1862    #[derive(Deserialize)]
1863    #[serde(deny_unknown_fields)]
1864    struct Raw {
1865        of: String,
1866        tags: serde_json::Map<String, Value>,
1867    }
1868    let raw: Raw = json(value, "tools_where")?;
1869    let of = refname(&raw.of)?;
1870    if of.section != Section::Features {
1871        return Err(GrammarError::Invalid(format!("tools_where.of is {of}, but it must be a $features set")));
1872    }
1873    if raw.tags.is_empty() {
1874        return Err(GrammarError::Invalid("tools_where needs at least one tag".into()));
1875    }
1876    let tags = crate::select::parse_tag_tests(raw.tags).map_err(|e| GrammarError::Invalid(format!("tools_where: {e}")))?;
1877    Ok(Where { of, tags })
1878}
1879
1880fn parse_selector(value: &Value) -> Result<Selector, GrammarError> {
1881    #[derive(Deserialize)]
1882    struct Raw {
1883        #[serde(flatten)]
1884        any: BTreeMap<String, OneOrManyOrBool>,
1885        #[serde(default)]
1886        except: BTreeMap<String, OneOrManyOrBool>,
1887        #[serde(default)]
1888        underground: bool,
1889    }
1890    #[derive(Deserialize)]
1891    #[serde(untagged)]
1892    enum OneOrManyOrBool {
1893        Bool(bool),
1894        One(String),
1895        Many(Vec<String>),
1896    }
1897    impl OneOrManyOrBool {
1898        fn to_match(&self) -> TagMatch {
1899            match self {
1900                OneOrManyOrBool::Bool(p) => TagMatch::Present(*p),
1901                OneOrManyOrBool::One(v) => TagMatch::Values(vec![v.clone()]),
1902                OneOrManyOrBool::Many(vs) => TagMatch::Values(vs.clone()),
1903            }
1904        }
1905    }
1906    let raw: Raw = json(value, "osm_select")?;
1907    if raw.any.is_empty() {
1908        return Err(GrammarError::Invalid("osm_select needs at least one tag".into()));
1909    }
1910    Ok(Selector {
1911        any: raw.any.iter().map(|(k, v)| (k.clone(), v.to_match())).collect(),
1912        except: raw.except.iter().map(|(k, v)| (k.clone(), v.to_match())).collect(),
1913        underground: raw.underground,
1914    })
1915}
1916
1917// ---------------------------------------------------------------------------
1918// JSON: the graph saved and loaded
1919// ---------------------------------------------------------------------------
1920
1921/// One operation from its JSON form, `{ "tools_union": ["$areas.a"] }`, as
1922/// the def it will be in `section`.
1923pub fn op_from_json(section: Section, op: Value) -> Result<Op, GrammarError> {
1924    let Value::Object(map) = op else {
1925        return Err(GrammarError::Invalid(format!("an operation is an object, not {op}")));
1926    };
1927    let raw = RawOp(map.into_iter().collect(), None);
1928    if raw.0.len() != 1 {
1929        return Err(GrammarError::Invalid("an operation has exactly one key".into()));
1930    }
1931    parse_op(raw, section)
1932}
1933
1934fn tag_json(m: &TagMatch) -> Value {
1935    match m {
1936        TagMatch::Present(p) => Value::Bool(*p),
1937        TagMatch::Values(vs) if vs.len() == 1 => Value::String(vs[0].clone()),
1938        TagMatch::Values(vs) => vs.iter().cloned().map(Value::String).collect(),
1939    }
1940}
1941
1942fn refs_json(names: &[Name]) -> Value {
1943    names.iter().map(|n| Value::String(n.to_string())).collect()
1944}
1945
1946/// The JSON form [`op_from_json`] reads back.
1947pub fn op_to_json(op: &Op) -> Value {
1948    use serde_json::json;
1949    let union = |u: &UnionRules| match u {
1950        UnionRules::Refs(ns) => refs_json(ns),
1951        UnionRules::Ref(n) => Value::String(n.to_string()),
1952    };
1953    let (key, value) = match op {
1954        Op::Select(sel) => {
1955            let mut body: serde_json::Map<String, Value> =
1956                sel.any.iter().map(|(k, m)| (k.clone(), tag_json(m))).collect();
1957            if !sel.except.is_empty() {
1958                body.insert("except".into(), sel.except.iter().map(|(k, m)| (k.clone(), tag_json(m))).collect());
1959            }
1960            if sel.underground {
1961                body.insert("underground".into(), Value::Bool(true));
1962            }
1963            ("osm_select", Value::Object(body))
1964        }
1965        Op::TileSelect(t) => ("tiles_select", t.items.iter().cloned().map(Value::String).collect()),
1966        Op::DataSelect(DataSource::Url(src)) => ("data_select", Value::String(src.clone())),
1967        Op::TerrainSelect(t) => ("terrain_select", serde_json::to_value(t).unwrap_or(Value::Null)),
1968        Op::DataSelect(DataSource::Inline(gj)) => ("data_select", json!({ "geojson": gj })),
1969        Op::DataSelect(DataSource::Json(js)) => ("data_select", json!({ "json": js })),
1970        Op::Where(w) => {
1971            let tags: serde_json::Map<String, Value> = w
1972                .tags
1973                .iter()
1974                .map(|(k, t)| {
1975                    let v = match t {
1976                        TagTest::Match(m) => tag_json(m),
1977                        TagTest::Range { min, max } => {
1978                            let mut r = serde_json::Map::new();
1979                            if let Some(lo) = min {
1980                                r.insert("min".into(), json!(lo));
1981                            }
1982                            if let Some(hi) = max {
1983                                r.insert("max".into(), json!(hi));
1984                            }
1985                            Value::Object(r)
1986                        }
1987                    };
1988                    (k.clone(), v)
1989                })
1990                .collect();
1991            ("tools_where", json!({ "of": w.of.to_string(), "tags": tags }))
1992        }
1993        Op::Polygons(n) => ("tools_polygons", Value::String(n.to_string())),
1994        Op::Union(u) => ("tools_union", union(u)),
1995        Op::Difference(d) => ("tools_difference", json!({ "base": d.base.to_string(), "cut": refs_json(&d.cut) })),
1996        Op::Intersect(i) => (
1997            "tools_intersect",
1998            json!({ "base": i.base.to_string(), "keep": i.keep.as_ref().map(Name::to_string) }),
1999        ),
2000        Op::FillHoles(n) => ("tools_fill_holes", Value::String(n.to_string())),
2001        Op::LabelArea(p) => ("tools_label_area", label_pick_json(p)),
2002        Op::LabelLines(p) => ("tools_label_lines", label_pick_json(p)),
2003        Op::Terrain(t) | Op::TerrainBand(t) => {
2004            let mut body = serde_json::Map::new();
2005            if let Some(a) = &t.in_area {
2006                body.insert("in_area".into(), Value::String(a.to_string()));
2007            }
2008            if let Some(c) = &t.color {
2009                body.insert("color".into(), c.clone());
2010            }
2011            if let Some(w) = &t.width {
2012                body.insert("width".into(), w.clone());
2013            }
2014            if t.angle != 0.0 {
2015                body.insert("angle".into(), json!(t.angle));
2016            }
2017            if let Some(l) = &t.layer {
2018                body.insert("layer".into(), Value::String(l.clone()));
2019            }
2020            if t.shore {
2021                body.insert("shore".into(), Value::Bool(true));
2022            }
2023            if !t.style.is_empty() {
2024                body.insert("style".into(), Value::Object(t.style.clone()));
2025            }
2026            if !t.band.is_empty() {
2027                body.insert("where".into(), Value::Object(t.band.clone()));
2028            }
2029            match t.draw {
2030                TerrainDraw::Lines => {}
2031                TerrainDraw::Fill => {
2032                    body.insert("draw".into(), Value::String("fill".into()));
2033                }
2034                TerrainDraw::Dots => {
2035                    body.insert("draw".into(), Value::String("dots".into()));
2036                }
2037            }
2038            (if matches!(op, Op::TerrainBand(_)) { "tools_terrain_band" } else { "tools_terrain" }, Value::Object(body))
2039        }
2040        Op::Burin(b) => {
2041            let mut body = serde_json::Map::new();
2042            body.insert("atlas".into(), b.atlas.clone());
2043            if let Some(a) = &b.in_area {
2044                body.insert("in_area".into(), Value::String(a.to_string()));
2045            }
2046            if !b.regions.is_empty() {
2047                body.insert(
2048                    "regions".into(),
2049                    Value::Object(
2050                        b.regions
2051                            .iter()
2052                            .map(|(k, v)| (k.clone(), Value::String(v.to_string())))
2053                            .collect(),
2054                    ),
2055                );
2056            }
2057            if let Some(w) = &b.water {
2058                body.insert("water".into(), Value::String(w.to_string()));
2059            }
2060            if let Some(l) = &b.layer {
2061                body.insert("layer".into(), Value::String(l.clone()));
2062            }
2063            ("tools_burin", Value::Object(body))
2064        }
2065        Op::Graticule(g) | Op::GraticuleArea(g) => {
2066            let mut body = serde_json::to_value(&g.look).unwrap_or_else(|_| json!({}));
2067            body["in"] = Value::String(g.in_area.to_string());
2068            (if matches!(op, Op::Graticule(_)) { "tools_graticule" } else { "tools_graticule_area" }, body)
2069        }
2070        Op::Labels(l) => {
2071            let mut body = serde_json::to_value(&l.style).unwrap_or_else(|_| json!({}));
2072            body["from"] = refs_json(&l.from);
2073            if let Some(a) = &l.in_area {
2074                body["in"] = Value::String(a.to_string());
2075            }
2076            if let Some(a) = &l.avoid {
2077                body["avoid"] = Value::String(a.to_string());
2078            }
2079            ("tools_labels", body)
2080        }
2081        Op::Grow(g) => ("tools_grow", json!({ "of": g.of.to_string(), "by": g.by })),
2082        Op::Move(m) => ("tools_move", json!({ "of": m.of.to_string(), "by": [m.by[0], m.by[1]] })),
2083        Op::Around(a) => ("tools_around", json!({ "of": a.of.to_string(), "by": a.by })),
2084        Op::Shape(s) => ("tools_shape", serde_json::to_value(s).unwrap_or_default()),
2085        Op::Path(s) => ("tools_path", serde_json::to_value(s).unwrap_or_default()),
2086        Op::Text(t) => ("tools_text", serde_json::to_value(t).unwrap_or_default()),
2087        Op::TextArea(t) => ("tools_text_area", serde_json::to_value(t).unwrap_or_default()),
2088        Op::BufferLines(b) => {
2089            let mut body = serde_json::Map::from_iter([
2090                ("lines".into(), Value::String(b.lines.to_string())),
2091                ("by".into(), json!(b.by)),
2092            ]);
2093            if b.cap == LineBufferCap::Flat {
2094                body.insert("cap".into(), json!("flat"));
2095            }
2096            ("tools_buffer_lines", Value::Object(body))
2097        }
2098        Op::Frame => ("engine_frame", json!({})),
2099        Op::ExtendToFrame(e) => (
2100            "tools_extend_to_frame",
2101            json!({
2102                "of": e.of.to_string(),
2103                "within": e.within.to_string(),
2104                "gap_mm": e.gap_mm,
2105            }),
2106        ),
2107        Op::Rings(r) => ("tools_rings", json!({ "of": r.of.to_string(), "exterior_only": r.exterior_only })),
2108        Op::Lines(n) => ("tools_lines", Value::String(n.to_string())),
2109        Op::Segments(n) => ("tools_segments", Value::String(n.to_string())),
2110        Op::Dedupe(n) => ("tools_dedupe", Value::String(n.to_string())),
2111        Op::Merge(n) => ("tools_merge", Value::String(n.to_string())),
2112        Op::Join(u) => ("tools_join", union(u)),
2113        Op::ClipLines(c) => (
2114            "tools_clip",
2115            json!({ "lines": c.lines.to_string(), "within": c.within.to_string(), "invert": c.invert }),
2116        ),
2117        Op::Fill(f) => {
2118            let mut body = serde_json::to_value(&f.spec).unwrap_or_else(|_| json!({}));
2119            body["in"] = Value::String(f.in_area.to_string());
2120            if f.per_feature {
2121                body["per"] = Value::String("feature".into());
2122            }
2123            if let Some(c) = &f.content {
2124                body["content"] = Value::String(c.to_string());
2125            }
2126            if let Some(m) = &f.motif {
2127                body["motif"] = Value::String(m.to_string());
2128            }
2129            ("tools_fill", body)
2130        }
2131        Op::FillCover(f) => {
2132            let mut body = serde_json::to_value(&f.spec).unwrap_or_else(|_| json!({}));
2133            body["in"] = Value::String(f.in_area.to_string());
2134            if let Some(m) = &f.motif {
2135                body["motif"] = Value::String(m.to_string());
2136            }
2137            ("tools_fill_cover", body)
2138        }
2139        Op::Module(m) => {
2140            let key = format!("module_{}", m.name);
2141            let mut body = serde_json::to_value(&m.roads).unwrap_or_else(|_| json!({}));
2142            if let Some(from) = &m.from {
2143                if let Some(obj) = body.as_object_mut() {
2144                    obj.insert("from".into(), Value::String(from.to_string()));
2145                }
2146            }
2147            return json!({ key: body });
2148        }
2149    };
2150    json!({ key: value })
2151}
2152
2153impl Target {
2154    fn to_json(&self) -> Value {
2155        match &self.module {
2156            Some(m) => Value::String(format!("{m}.{}", self.name.name)),
2157            None => Value::String(self.name.to_string()),
2158        }
2159    }
2160}
2161
2162impl Grammar {
2163    /// The graph as JSON: what a script built, for presets, `--dump-graph`
2164    /// and the page's worker. [`Grammar::from_json`] reads it back.
2165    pub fn to_json(&self) -> Value {
2166        use serde_json::json;
2167        let mut out = serde_json::Map::new();
2168        if let Some(t) = &self.title {
2169            out.insert("title".into(), Value::String(t.clone()));
2170        }
2171        out.insert("output".into(), serde_json::to_value(&self.output).unwrap_or(Value::Null));
2172        for (section, defs) in &self.sections {
2173            let body: serde_json::Map<String, Value> = defs
2174                .iter()
2175                .map(|d| {
2176                    let mut op = op_to_json(&d.op);
2177                    if let Some(at) = d.at {
2178                        op["at"] = json!(at);
2179                    }
2180                    (d.name.clone(), op)
2181                })
2182                .collect();
2183            out.insert(format!("${}", section.key()), Value::Object(body));
2184        }
2185        let draw: Vec<Value> = self
2186            .draw
2187            .iter()
2188            .map(|d| {
2189                let mut v = json!({ "from": d.from.to_json() });
2190                if let Some(id) = &d.id {
2191                    v["id"] = json!(id);
2192                }
2193                if let Some(s) = &d.stroke {
2194                    v["stroke"] = json!(s);
2195                }
2196                if let Some(at) = d.at {
2197                    v["at"] = json!(at);
2198                }
2199                v
2200            })
2201            .collect();
2202        out.insert("draw".into(), Value::Array(draw));
2203        let masks: serde_json::Map<String, Value> = self
2204            .compose
2205            .masks
2206            .iter()
2207            .map(|(name, m)| {
2208                let mut v = json!({
2209                    "from": m.from.to_json(),
2210                    "occludes": m.occludes.iter().map(|i| i.0.clone()).collect::<Vec<_>>(),
2211                });
2212                if let Some(at) = m.at {
2213                    v["at"] = json!(at);
2214                }
2215                (name.clone(), v)
2216            })
2217            .collect();
2218        let clip = match &self.compose.clip_default {
2219            Clip::Auto => json!("auto"),
2220            Clip::None => json!("none"),
2221            Clip::Areas(ns) => refs_json(ns),
2222        };
2223        let mut compose_obj = json!({
2224            "order": self.compose.order.iter().map(|i| i.0.clone()).collect::<Vec<_>>(),
2225            "masks": masks,
2226            "clip": { "default": clip },
2227        });
2228        if !self.compose.optimize.is_empty() {
2229            let opt: Vec<Value> = self
2230                .compose
2231                .optimize
2232                .iter()
2233                .map(|s| {
2234                    let raw = RawOptimizeStep {
2235                        layers: s.layers.iter().map(|i| i.0.clone()).collect(),
2236                        except: s.except.iter().map(|i| i.0.clone()).collect(),
2237                        op: s.op.clone(),
2238                        at: s.at,
2239                    };
2240                    serde_json::to_value(raw).unwrap()
2241                })
2242                .collect();
2243            compose_obj["optimize"] = Value::Array(opt);
2244        }
2245        out.insert("compose".into(), compose_obj);
2246        if !self.views.is_empty() {
2247            let views: Vec<Value> =
2248                self.views
2249                    .iter()
2250                    .map(|v| {
2251                        let mut o = json!({ "id": v.id, "at": [v.at.0, v.at.1], "graph": v.grammar.to_json() });
2252                        if let Some(ink) = &v.ink {
2253                            o["ink"] = json!(ink);
2254                        }
2255                        o
2256                    })
2257                    .collect();
2258            out.insert("views".into(), Value::Array(views));
2259        }
2260        Value::Object(out)
2261    }
2262
2263    pub fn from_json(text: &str) -> Result<Grammar, GrammarError> {
2264        let raw: Raw = serde_json::from_str(text).map_err(|e| GrammarError::Json(e.to_string()))?;
2265        build(raw)
2266    }
2267}
2268
2269// ---------------------------------------------------------------------------
2270// Validation
2271// ---------------------------------------------------------------------------
2272
2273fn validate_label_pick(g: &Grammar, def: &Def, pick: &LabelPick) -> Result<(), GrammarError> {
2274    let labels = g.find(&pick.of).ok_or_else(|| {
2275        GrammarError::Invalid(format!("{} reads {}, which is not defined", def.label(), pick.of))
2276    })?;
2277    if !matches!(&labels.op, Op::Labels(_)) {
2278        return Err(GrammarError::Invalid(format!("{} reads {}, which is not a labels def", def.label(), pick.of)));
2279    }
2280    if let Some(rule) = &pick.rule {
2281        let Op::Labels(l) = &labels.op else { unreachable!() };
2282        if !l.style.rule_ids().iter().any(|id| id == rule) {
2283            return Err(GrammarError::Invalid(format!(
2284                "{}: rule {:?} is not a labels.rules[].id on {}",
2285                def.label(),
2286                rule,
2287                pick.of
2288            )));
2289        }
2290    }
2291    Ok(())
2292}
2293
2294/// Every reference defined in the right section, draw ids unique, order and
2295/// masks naming draw ids, no loops.
2296pub fn validate(g: &Grammar) -> Result<(), GrammarError> {
2297    // Every reference must exist, in the right section.
2298    for def in g.all_defs() {
2299        for r in def.op.refs() {
2300            if g.find(&r).is_none() {
2301                return Err(GrammarError::Invalid(format!(
2302                    "{} refers to {r}, which is not defined under ${}",
2303                    def.label(),
2304                    r.section
2305                )));
2306            }
2307        }
2308        if let Op::LabelArea(pick) | Op::LabelLines(pick) = &def.op {
2309            validate_label_pick(g, def, pick)?;
2310        }
2311    }
2312    // A draw must point at line output: $lines, $fills, or a module output.
2313    for d in &g.draw {
2314        if d.from.module.is_some() {
2315            continue; // e.g. roads.outlines: the module owns the name
2316        }
2317        if !matches!(d.from.name.section, Section::Lines | Section::Fills) {
2318            return Err(GrammarError::Invalid(located(
2319                &format!("draw from {} needs $lines or $fills, not ${}", d.from.name, d.from.name.section),
2320                d.at,
2321            )));
2322        }
2323        if g.find(&d.from.name).is_none() {
2324            return Err(GrammarError::Invalid(format!("draw from {}: no such def", d.from.name)));
2325        }
2326    }
2327    let mut groups: BTreeSet<String> = BTreeSet::new();
2328    for d in &g.draw {
2329        if !groups.insert(d.group()) {
2330            return Err(GrammarError::Invalid(located(
2331                &format!("two draw entries write the same SVG group id {:?}", d.group()),
2332                d.at,
2333            )));
2334        }
2335    }
2336    // Order and occludes must name draw groups.
2337    for id in &g.compose.order {
2338        if !groups.contains(&id.0) {
2339            return Err(GrammarError::Invalid(format!("compose.order names {:?}, which is not a draw id", id.0)));
2340        }
2341    }
2342    for (name, mask) in &g.compose.masks {
2343        if mask.from.module.is_some() {
2344            // e.g. roads.area: an area published by a module.
2345        } else if mask.from.name.section != Section::Areas {
2346            return Err(GrammarError::Invalid(located(
2347                &format!("masks.{name}.from is {}, but a mask must be an area", mask.from.name),
2348                mask.at,
2349            )));
2350        } else if g.find(&mask.from.name).is_none() {
2351            return Err(GrammarError::Invalid(located(
2352                &format!("masks.{name}.from: no such def {}", mask.from.name),
2353                mask.at,
2354            )));
2355        }
2356        for id in &mask.occludes {
2357            if !groups.contains(&id.0) && !g.views.iter().any(|v| v.id == id.0) {
2358                return Err(GrammarError::Invalid(located(
2359                    &format!("masks.{name}.occludes names {:?}, which is not a draw id", id.0),
2360                    mask.at,
2361                )));
2362            }
2363        }
2364    }
2365    for (id, clip) in &g.compose.clip {
2366        if !groups.contains(&id.0) {
2367            return Err(GrammarError::Invalid(format!("compose.clip names {:?}, which is not a draw id", id.0)));
2368        }
2369        if let Clip::Areas(names) = clip {
2370            for n in names {
2371                if n.section != Section::Areas || g.find(n).is_none() {
2372                    return Err(GrammarError::Invalid(format!("compose.clip[{:?}]: {n} is not an area def", id.0)));
2373                }
2374            }
2375        }
2376    }
2377    for step in &g.compose.optimize {
2378        for id in &step.layers {
2379            if !groups.contains(&id.0) {
2380                return Err(GrammarError::Invalid(located(
2381                    &format!("compose.{} names {:?}, which is not a draw id", step.op.name(), id.0),
2382                    step.at,
2383                )));
2384            }
2385        }
2386        for id in &step.except {
2387            if !groups.contains(&id.0) {
2388                return Err(GrammarError::Invalid(located(
2389                    &format!("compose.{} except names {:?}, which is not a draw id", step.op.name(), id.0),
2390                    step.at,
2391                )));
2392            }
2393        }
2394    }
2395    // No loops across defs.
2396    if let Some(cycle) = find_cycle(g) {
2397        return Err(GrammarError::Invalid(format!("loop between defs: {}", cycle.join(" → "))));
2398    }
2399    Ok(())
2400}
2401
2402fn find_cycle(g: &Grammar) -> Option<Vec<String>> {
2403    #[derive(Clone, Copy, PartialEq)]
2404    enum Mark {
2405        Open,
2406        Done,
2407    }
2408    fn visit(
2409        g: &Grammar,
2410        name: &Name,
2411        marks: &mut BTreeMap<Name, Mark>,
2412        path: &mut Vec<Name>,
2413    ) -> Option<Vec<String>> {
2414        match marks.get(name) {
2415            Some(Mark::Done) => return None,
2416            Some(Mark::Open) => {
2417                let at = path.iter().position(|p| p == name).unwrap_or(0);
2418                let mut loop_names: Vec<String> = path[at..].iter().map(Name::to_string).collect();
2419                loop_names.push(name.to_string());
2420                return Some(loop_names);
2421            }
2422            None => {}
2423        }
2424        marks.insert(name.clone(), Mark::Open);
2425        path.push(name.clone());
2426        if let Some(def) = g.find(name) {
2427            for r in def.op.refs() {
2428                if let Some(cycle) = visit(g, &r, marks, path) {
2429                    return Some(cycle);
2430                }
2431            }
2432        }
2433        path.pop();
2434        marks.insert(name.clone(), Mark::Done);
2435        None
2436    }
2437
2438    let mut marks = BTreeMap::new();
2439    let mut path = Vec::new();
2440    for def in g.all_defs() {
2441        if !marks.contains_key(&def.reference()) {
2442            if let Some(cycle) = visit(g, &def.reference(), &mut marks, &mut path) {
2443                return Some(cycle);
2444            }
2445        }
2446    }
2447    None
2448}
2449
2450#[cfg(test)]
2451mod tests {
2452    use super::*;
2453
2454    /// The example profile, trimmed to the parts the grammar must accept.
2455    const YAML: &str = r#"
2456output: { width: 6in, height: 4in, scale: "1:10000" }
2457
2458$features:
2459  garden: { osm_select: { leisure: garden } }
2460  bldg:   { osm_select: { building: true } }
2461
2462$areas:
2463  garden:     { tools_polygons: $features.garden }
2464  parks:      { tools_union: [$areas.garden] }
2465  parks_ext:  { tools_fill_holes: $areas.parks }
2466  footprints: { tools_polygons: $features.bldg }
2467  dissolved:  { tools_union: [$areas.footprints] }
2468  inner_band: { tools_grow: { of: $areas.dissolved, by: -0.1mm } }
2469  wet:        { tools_union: [$areas.garden] }
2470
2471$lines:
2472  parks_edge: { tools_rings: { of: $areas.parks_ext, exterior_only: true } }
2473  bldg_lines: { tools_segments: $features.bldg }
2474  bldg_dedupe: { tools_dedupe: $lines.bldg_lines }
2475  walls:      { tools_clip: { lines: $lines.bldg_dedupe, within: $areas.inner_band } }
2476
2477$fills:
2478  hatch: { tools_fill: { in: $areas.footprints, per: feature, pattern: zigzag, spacing: 0.5mm, angle: 45 } }
2479
2480draw:
2481  - { id: parks_ring, from: $lines.parks_edge, stroke: { style: dash, dash: 0.45mm, gap: 0.40mm } }
2482  - { from: $fills.hatch }
2483  - { id: bldg_wall, from: $lines.walls, stroke: solid }
2484
2485compose:
2486  order: [parks_ring, fills_hatch, bldg_wall]
2487  masks:
2488    bldg_cover: { from: $areas.dissolved, occludes: [parks_ring] }
2489  clip:
2490    default: auto
2491"#;
2492
2493    /// The tests below write only the part under test; the output is boilerplate.
2494    fn parse(text: &str) -> Result<Grammar, GrammarError> {
2495        let body = if text.contains("output:") {
2496            text.to_string()
2497        } else {
2498            format!("output: {{ width: 100mm, height: 50mm }}\n{text}")
2499        };
2500        from_yaml(&body)
2501    }
2502
2503    #[test]
2504    fn parses_the_example_and_types_its_sections() {
2505        let g = parse(YAML).unwrap();
2506        assert_eq!(g.defs(Section::Features).len(), 2);
2507        assert_eq!(g.defs(Section::Areas).len(), 7);
2508        assert_eq!(g.defs(Section::Lines).len(), 4);
2509        assert_eq!(g.defs(Section::Fills).len(), 1);
2510        let dissolved = Name::parse("$areas.dissolved").unwrap();
2511        assert_eq!(g.find(&dissolved).unwrap().op.section(), Section::Areas);
2512    }
2513
2514    #[test]
2515    fn a_title_is_optional_and_kept_as_written() {
2516        assert_eq!(parse(YAML).unwrap().title, None);
2517        let g = parse(&format!("title: \"Parks: and buildings\"\n{YAML}")).unwrap();
2518        assert_eq!(g.title.as_deref(), Some("Parks: and buildings"));
2519    }
2520
2521    #[test]
2522    fn ids_fall_back_to_the_def_name() {
2523        let g = parse(YAML).unwrap();
2524        assert_eq!(g.groups(), vec!["parks_ring", "fills_hatch", "bldg_wall"]);
2525    }
2526
2527    #[test]
2528    fn a_reference_must_exist_and_carry_its_section() {
2529        let bad = "$areas:\n  a: { tools_polygons: $features.nope }\n";
2530        assert!(matches!(parse(bad), Err(GrammarError::Invalid(m)) if m.contains("$features.nope")));
2531        let bad = "$areas:\n  a: { tools_polygons: $lines.nope }\n";
2532        assert!(matches!(parse(bad), Err(GrammarError::Invalid(m)) if m.contains("$lines.nope")));
2533    }
2534
2535    #[test]
2536    fn an_operation_must_match_its_section() {
2537        // tools_rings makes lines; under $areas it is an error.
2538        let bad = "$areas:\n  a: { tools_rings: $areas.b }\n";
2539        assert!(matches!(
2540            parse(bad),
2541            Err(GrammarError::Invalid(m)) if m.contains("lines") && m.contains("areas")
2542        ));
2543    }
2544
2545    #[test]
2546    fn draw_needs_line_output_and_masks_need_areas() {
2547        let base = "$features:\n  f: { osm_select: { building: true } }\n\
2548                    $areas:\n  a: { tools_polygons: $features.f }\n\
2549                    $lines:\n  l: { tools_rings: $areas.a }\n";
2550        // draw from an area: refused
2551        assert!(parse(&format!("{base}draw:\n  - {{ from: $areas.a }}\n")).is_err());
2552        // mask from a line set: refused
2553        let text = format!("{base}draw:\n  - {{ from: $lines.l }}\ncompose:\n  masks:\n    m: {{ from: $lines.l }}\n");
2554        assert!(matches!(parse(&text), Err(GrammarError::Invalid(m)) if m.contains("must be an area")));
2555    }
2556
2557    #[test]
2558    fn loops_and_unknown_operations_are_load_errors() {
2559        let looped = "$areas:\n  a: { tools_union: [$areas.b] }\n  b: { tools_grow: { of: $areas.a, by: 1mm } }\n";
2560        assert!(matches!(parse(looped), Err(GrammarError::Invalid(m)) if m.contains("loop")));
2561        let unknown = "$areas:\n  a: { tools_bogus: 1 }\n";
2562        assert!(matches!(parse(unknown), Err(GrammarError::Invalid(m)) if m.contains("unknown operation")));
2563    }
2564
2565    #[test]
2566    fn one_operation_per_def() {
2567        let two = "$areas:\n  a: { tools_polygons: $areas.b, engine_frame: {} }\n  b: { engine_frame: {} }\n";
2568        assert!(matches!(parse(two), Err(GrammarError::Json(m)) if m.contains("exactly one operation")));
2569    }
2570
2571    #[test]
2572    fn modules_are_recorded_and_bad_references_named() {
2573        let module = "$lines:\n  roads: { module_roads: {} }\n";
2574        let g = parse(module).unwrap();
2575        assert_eq!(
2576            g.defs(Section::Lines)[0].op,
2577            Op::Module(Module { name: "roads".into(), from: None, roads: Default::default() })
2578        );
2579        let bad_ref = "$areas:\n  a: { tools_union: [dense] }\n";
2580        assert!(matches!(parse(bad_ref), Err(GrammarError::Invalid(m)) if m.contains("\"dense\" is not a $section.name reference")));
2581        let bad_len = "$fills:\n  f: { tools_fill: { in: $areas.a, spacing: dense } }\n$areas:\n  a: { engine_frame: {} }\n";
2582        assert!(parse(bad_len).is_err());
2583    }
2584
2585    #[test]
2586    fn tile_selections_and_modules_reading_them() {
2587        let text = "$features:\n  bldg: { tiles_select: buildings }\n  ways: { tiles_select: [roads, \"paths\"] }\n  sea: { tiles_select: ocean }\n\
2588                    $areas:\n  roads: { module_roads: { from: $features.ways } }\n";
2589        let g = parse(text).unwrap();
2590        assert_eq!(g.tile_selectors(), ["buildings", "roads", "paths", "ocean"]);
2591        assert!(g.osm_keys().is_empty(), "nothing reads Overpass");
2592        assert!(g.draws_ocean());
2593        assert_eq!(g.find(&Name::parse("$areas.roads").unwrap()).unwrap().op.refs(), [Name::parse("$features.ways").unwrap()]);
2594        let osm = parse("$areas:\n  roads: { module_roads: {} }\n").unwrap();
2595        assert!(osm.osm_keys().contains(&"highway".to_string()) && osm.tile_selectors().is_empty());
2596        assert!(matches!(parse("$features:\n  a: { tiles_select: forrest }\n"), Err(GrammarError::Invalid(m)) if m.contains("preset")));
2597        assert!(parse("$areas:\n  r: { module_roads: { from: $areas.r } }\n").is_err());
2598        assert!(parse("$areas:\n  r: { module_roads: { form: $features.x } }\n").is_err());
2599    }
2600
2601    #[test]
2602    fn duplicate_names_and_extra_keys_are_refused() {
2603        let dup = r#"{ "output": {}, "$areas": { "a": { "engine_frame": {} }, "a": { "engine_frame": {} } } }"#;
2604        assert!(matches!(Grammar::from_json(dup), Err(GrammarError::Invalid(m)) if m.contains("defined twice")));
2605        let extra = "$areas:\n  a: { engine_frame: {}, note: hi }\n";
2606        assert!(parse(extra).is_err());
2607    }
2608
2609    #[test]
2610    fn the_graph_round_trips_through_json() {
2611        let g = parse(YAML).unwrap();
2612        let json = g.to_json().to_string();
2613        let back = Grammar::from_json(&json).unwrap();
2614        assert_eq!(back, g);
2615        assert_eq!(back.to_json().to_string(), json);
2616    }
2617
2618    #[test]
2619    fn script_positions_ride_along_and_label_errors() {
2620        let mut g = parse(YAML).unwrap();
2621        g.sections[1].1[0].at = Some(At(12, 5));
2622        let back = Grammar::from_json(&g.to_json().to_string()).unwrap();
2623        assert_eq!(back.sections[1].1[0].at, Some(At(12, 5)));
2624        assert_eq!(back.sections[1].1[0].label(), "$areas.garden (line 12 column 5)");
2625        let mut bad = g.to_json();
2626        bad["$areas"]["garden"]["tools_polygons"] = Value::String("$features.nope".into());
2627        let err = Grammar::from_json(&bad.to_string()).unwrap_err().to_string();
2628        assert!(err.contains("line 12 column 5"), "{err}");
2629    }
2630
2631    #[test]
2632    fn label_area_accepts_a_rule_bucket_object() {
2633        let text = r#"{
2634          "output": { "width": "100mm", "height": "50mm" },
2635          "$features": { "p": { "tiles_select": ["parks"] } },
2636          "$lines": { "names": { "tools_labels": { "from": ["$features.p"], "rules": [{ "id": "park", "tags": { "class": "park" } }] } } },
2637          "$areas": { "park": { "tools_label_area": { "of": "$lines.names", "rule": "park" } } }
2638        }"#;
2639        let g = Grammar::from_json(text).unwrap();
2640        let def = g.defs(Section::Areas).iter().find(|d| d.name == "park").unwrap();
2641        let Op::LabelArea(pick) = &def.op else { panic!("label area") };
2642        assert_eq!(pick.rule.as_deref(), Some("park"));
2643    }
2644}