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    /// A screen's layers, bottom first (`paint(...)`): what covers the grid
750    /// when the output is a screen (`output.screen`).
751    pub paint: Vec<crate::paint::Paint>,
752    /// Other places drawn into rectangles of this page (`view(...)`), under
753    /// the page's own groups. Each is a whole graph with its own output.
754    pub views: Vec<View>,
755}
756
757/// A view: another place, at its own scale, drawn into a rectangle of the
758/// page. Its graph's `output` is the place and the rectangle's size; `at` is
759/// the rectangle's top-left corner on the page, in mm. A page mask whose
760/// `occludes` names the view's `id` cuts every stroke of it.
761#[derive(Debug, Clone, PartialEq)]
762pub struct View {
763    pub id: String,
764    pub at: (f64, f64),
765    pub grammar: Box<Grammar>,
766    /// One colour for every stroke of the view, whatever its style asks: the
767    /// view is then one group of its own, named `id` — one pen.
768    pub ink: Option<String>,
769}
770
771impl View {
772    /// The place the view shows, as `(lng, lat)`.
773    pub fn center(&self) -> (f64, f64) {
774        (self.grammar.output.lng.unwrap_or(0.0), self.grammar.output.lat.unwrap_or(0.0))
775    }
776}
777
778impl Grammar {
779    /// The `tools_terrain` defs, in file order: what the host reads the
780    /// elevation for.
781    pub fn terrains(&self) -> Vec<&Terrain> {
782        self.all_defs()
783            .filter_map(|d| match &d.op {
784                Op::Terrain(t) | Op::TerrainBand(t) => Some(t),
785                _ => None,
786            })
787            .collect()
788    }
789
790    /// The `tools_burin` defs: whole burin documents the engine draws.
791    pub fn burins(&self) -> Vec<&Burin> {
792        self.all_defs()
793            .filter_map(|d| match &d.op {
794                Op::Burin(b) => Some(b),
795                _ => None,
796            })
797            .collect()
798    }
799
800    /// Whether any def draws the elevation — terrain, or a burin document.
801    /// What turns the terrain fetch on.
802    pub fn draws_terrain(&self) -> bool {
803        !self.terrains().is_empty()
804            || !self.burins().is_empty()
805            || self.all_defs().any(|d| matches!(d.op, Op::TerrainSelect(_)))
806    }
807
808    pub fn defs(&self, section: Section) -> &[Def] {
809        self.sections
810            .iter()
811            .find(|(s, _)| *s == section)
812            .map(|(_, d)| d.as_slice())
813            .unwrap_or(&[])
814    }
815
816    /// Every def, in section order.
817    pub fn all_defs(&self) -> impl Iterator<Item = &Def> {
818        self.sections.iter().flat_map(|(_, defs)| defs.iter())
819    }
820
821    /// This graph with only what it shows: the defs that no `draw`, `paint`,
822    /// mask or clip reads, directly or through other defs, left out, so
823    /// nothing is fetched or computed for them (terrain no layer reads asks
824    /// for no elevation, a tile layer none reads for no tiles). Views keep
825    /// their own graphs whole.
826    pub fn reached(mut self) -> Grammar {
827        let target = |t: &Target| match &t.module {
828            Some(m) => self.module(m).map(Def::reference),
829            None => Some(t.name.clone()),
830        };
831        let mut todo: Vec<Name> = self
832            .draw
833            .iter()
834            .map(|d| &d.from)
835            .chain(self.paint.iter().map(|p| &p.from))
836            .chain(self.compose.masks.iter().map(|(_, m)| &m.from))
837            .filter_map(target)
838            .collect();
839        for clip in self.compose.clip.values().chain([&self.compose.clip_default]) {
840            if let Clip::Areas(names) = clip {
841                todo.extend(names.iter().cloned());
842            }
843        }
844        let mut reached = BTreeSet::new();
845        while let Some(name) = todo.pop() {
846            if let Some(def) = self.find(&name) {
847                if reached.insert(name) {
848                    todo.extend(def.op.refs());
849                }
850            }
851        }
852        for (_, defs) in &mut self.sections {
853            defs.retain(|d| reached.contains(&d.reference()));
854        }
855        self
856    }
857
858    pub fn find(&self, name: &Name) -> Option<&Def> {
859        self.defs(name.section).iter().find(|d| d.name == name.name)
860    }
861
862    /// The def holding `module_<module>`, if the profile calls one.
863    pub fn module(&self, module: &str) -> Option<&Def> {
864        self.all_defs().find(|d| matches!(&d.op, Op::Module(m) if m.name == module))
865    }
866
867    /// The SVG group each draw entry writes.
868    pub fn groups(&self) -> Vec<String> {
869        self.draw.iter().map(Draw::group).collect()
870    }
871
872    /// Every OSM key the profile can select on: what Overpass must fetch.
873    ///
874    /// Modules read tags the profile never names (`module_roads` needs
875    /// `highway`), so they contribute their keys too, unless they read a
876    /// feature set of their own (`from`). Empty: the profile needs no
877    /// Overpass at all.
878    pub fn osm_keys(&self) -> Vec<String> {
879        let mut keys: Vec<String> = Vec::new();
880        fn add(keys: &mut Vec<String>, k: &str) {
881            if !keys.iter().any(|x| x == k) {
882                keys.push(k.to_string());
883            }
884        }
885        let defs: Vec<&Def> = self.all_defs().collect();
886        for def in defs {
887            match &def.op {
888                Op::Select(sel) => sel.keys().for_each(|k| add(&mut keys, k)),
889                Op::Module(Module { name, from: None, .. }) => {
890                    crate::themes::osm_keys(name).iter().for_each(|k| add(&mut keys, k))
891                }
892                _ => {}
893            }
894        }
895        keys
896    }
897
898    /// Every `tiles_select` item: what to read from the vector tiles.
899    pub fn tile_selectors(&self) -> Vec<String> {
900        let mut out: Vec<String> = Vec::new();
901        for def in self.all_defs() {
902            if let Op::TileSelect(t) = &def.op {
903                out.extend(t.items.iter().filter(|i| !out.contains(i)).cloned().collect::<Vec<_>>());
904            }
905        }
906        out
907    }
908
909    /// Whether the profile reads open-sea polygons from the vector tiles.
910    pub fn draws_ocean(&self) -> bool {
911        self.tile_selectors().iter().any(|s| s == "ocean")
912    }
913
914    /// Every `data_select` source, a URL or a file path, in order: the
915    /// GeoJSON the host must read and pass as `Inputs::data`.
916    pub fn datasets(&self) -> Vec<String> {
917        let mut out: Vec<String> = Vec::new();
918        for def in self.all_defs() {
919            if let Some(src) = match &def.op {
920                Op::DataSelect(d) => d.url(),
921                _ => None,
922            } {
923                if !out.iter().any(|o| o == src) {
924                    out.push(src.to_string());
925                }
926            }
927        }
928        out
929    }
930
931    /// SVG files named by a fill `source`, for the host to read.
932    pub fn source_files(&self) -> Vec<String> {
933        let mut out = Vec::new();
934        for def in self.defs(Section::Fills) {
935            if let Op::Fill(f) = &def.op {
936                if let Some(src) = &f.spec.source {
937                    if !out.contains(&src.file) {
938                        out.push(src.file.clone());
939                    }
940                }
941            }
942        }
943        out
944    }
945}
946
947// ---------------------------------------------------------------------------
948// Deserialization
949// ---------------------------------------------------------------------------
950
951#[derive(Debug, thiserror::Error)]
952pub enum GrammarError {
953    #[error("graph JSON: {0}")]
954    Json(String),
955    #[error("profile: {0}")]
956    Invalid(String),
957}
958
959/// Raw shape: sections as written, before validation.
960#[derive(Debug, Deserialize)]
961#[serde(deny_unknown_fields)]
962struct Raw {
963    #[serde(default)]
964    title: Option<String>,
965    output: crate::profile::OutputSpec,
966    #[serde(default, rename = "$features", deserialize_with = "ordered_defs")]
967    features: Vec<(String, RawOp)>,
968    #[serde(default, rename = "$areas", deserialize_with = "ordered_defs")]
969    areas: Vec<(String, RawOp)>,
970    #[serde(default, rename = "$lines", deserialize_with = "ordered_defs")]
971    lines: Vec<(String, RawOp)>,
972    #[serde(default, rename = "$fills", deserialize_with = "ordered_defs")]
973    fills: Vec<(String, RawOp)>,
974    /// Recognised so the error is clear, not "unknown field".
975    #[serde(default)]
976    draw: Vec<RawDraw>,
977    #[serde(default)]
978    compose: RawCompose,
979    #[serde(default)]
980    paint: Vec<RawPaint>,
981    #[serde(default)]
982    views: Vec<RawView>,
983}
984
985#[derive(Debug, Deserialize)]
986#[serde(deny_unknown_fields)]
987struct RawPaint {
988    id: String,
989    from: String,
990    #[serde(default)]
991    fill: Option<Value>,
992    #[serde(default)]
993    line: Option<Value>,
994    #[serde(default)]
995    text: Option<Value>,
996    #[serde(default)]
997    halo: crate::paint::Halo,
998    #[serde(default)]
999    minzoom: Option<f64>,
1000    #[serde(default)]
1001    maxzoom: Option<f64>,
1002    #[serde(default)]
1003    filter: Option<Value>,
1004    #[serde(default)]
1005    at: Option<At>,
1006}
1007
1008#[derive(Debug, Deserialize)]
1009#[serde(deny_unknown_fields)]
1010struct RawView {
1011    id: String,
1012    at: [f64; 2],
1013    graph: Value,
1014    #[serde(default)]
1015    ink: Option<String>,
1016}
1017
1018
1019/// `Vec<(String, T)>` from a YAML/JSON **mapping**, keeping the written order.
1020/// Used for the `$sections` (def name → operation) and for `compose.masks`.
1021fn ordered_defs<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<(String, RawOp)>, D::Error> {
1022    ordered_map(d)
1023}
1024
1025fn ordered_masks<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<(String, RawMask)>, D::Error> {
1026    ordered_map(d)
1027}
1028
1029fn ordered_map<'de, D, T>(d: D) -> Result<Vec<(String, T)>, D::Error>
1030where
1031    D: Deserializer<'de>,
1032    T: serde::de::DeserializeOwned,
1033{
1034    struct V<T>(std::marker::PhantomData<T>);
1035    impl<'de, T: serde::de::DeserializeOwned> Visitor<'de> for V<T> {
1036        type Value = Vec<(String, T)>;
1037        fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
1038            f.write_str("a mapping of name to value")
1039        }
1040        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
1041            let mut out = Vec::new();
1042            while let Some((k, v)) = map.next_entry::<String, T>()? {
1043                out.push((k, v));
1044            }
1045            Ok(out)
1046        }
1047        /// `$features:` with nothing under it is an empty section, not an error.
1048        fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
1049            Ok(Vec::new())
1050        }
1051    }
1052    d.deserialize_any(V(std::marker::PhantomData))
1053}
1054
1055#[derive(Debug, Deserialize)]
1056#[serde(deny_unknown_fields)]
1057struct RawDraw {
1058    #[serde(default)]
1059    id: Option<String>,
1060    from: String,
1061    #[serde(default)]
1062    stroke: Option<StrokeSpec>,
1063    #[serde(default)]
1064    at: Option<At>,
1065}
1066
1067#[derive(Debug, Default, Deserialize)]
1068#[serde(deny_unknown_fields)]
1069struct RawCompose {
1070    #[serde(default)]
1071    order: Vec<String>,
1072    #[serde(default, deserialize_with = "ordered_masks")]
1073    masks: Vec<(String, RawMask)>,
1074    #[serde(default)]
1075    clip: ClipBlock,
1076    #[serde(default)]
1077    optimize: Vec<RawOptimizeStep>,
1078}
1079
1080#[derive(Debug, Clone, Serialize, Deserialize)]
1081pub struct RawOptimizeStep {
1082    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1083    pub layers: Vec<String>,
1084    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1085    pub except: Vec<String>,
1086    #[serde(flatten)]
1087    pub op: crate::optimize::OptimizeOp,
1088    #[serde(default, skip_serializing_if = "Option::is_none")]
1089    pub at: Option<At>,
1090}
1091
1092#[derive(Debug, Default, Deserialize)]
1093#[serde(deny_unknown_fields)]
1094struct ClipBlock {
1095    #[serde(default)]
1096    default: Option<ClipValue>,
1097}
1098
1099#[derive(Debug, Clone, Deserialize)]
1100#[serde(untagged)]
1101enum ClipValue {
1102    Keyword(String),
1103    List(Vec<String>),
1104}
1105
1106#[derive(Debug, Deserialize)]
1107#[serde(deny_unknown_fields)]
1108struct RawMask {
1109    from: String,
1110    #[serde(default)]
1111    occludes: Vec<String>,
1112    #[serde(default)]
1113    at: Option<At>,
1114}
1115
1116/// One operation, as a single-key mapping. The key picks the variant; a def
1117/// with several keys is an error (one operation per def).
1118/// `at: [line, column]` may sit next to the operation key: where the script
1119/// made the def.
1120#[derive(Debug)]
1121struct RawOp(BTreeMap<String, Value>, Option<At>);
1122
1123impl<'de> Deserialize<'de> for RawOp {
1124    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1125        struct V;
1126        impl<'de> Visitor<'de> for V {
1127            type Value = RawOp;
1128            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
1129                f.write_str("a mapping with exactly one operation key")
1130            }
1131            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<RawOp, A::Error> {
1132                let mut entries = BTreeMap::new();
1133                let mut at = None;
1134                while let Some((k, v)) = map.next_entry::<String, Value>()? {
1135                    if k == "at" {
1136                        at = Some(serde_json::from_value(v).map_err(de::Error::custom)?);
1137                    } else {
1138                        entries.insert(k, v);
1139                    }
1140                }
1141                if entries.len() != 1 {
1142                    let keys: Vec<&str> = entries.keys().map(String::as_str).collect();
1143                    return Err(de::Error::custom(format!(
1144                        "a def takes exactly one operation, found {}: {}",
1145                        entries.len(),
1146                        keys.join(", ")
1147                    )));
1148                }
1149                Ok(RawOp(entries, at))
1150            }
1151            /// `def: name` with no body (an alias style) is not supported here.
1152            fn visit_str<E: de::Error>(self, v: &str) -> Result<RawOp, E> {
1153                Err(de::Error::custom(format!(
1154                    "expected an operation, found the bare name {v:?}; write `tools_union: [{v}]` or a real op"
1155                )))
1156            }
1157        }
1158        d.deserialize_any(V)
1159    }
1160}
1161
1162/// Peak at the operation key without consuming the rest.
1163fn only_op(raw: RawOp) -> Result<(String, Value), String> {
1164    let (k, v) = raw.0.into_iter().next().ok_or("empty operation")?;
1165    Ok((k, v))
1166}
1167
1168fn json<T: serde::de::DeserializeOwned>(value: &Value, what: &str) -> Result<T, GrammarError> {
1169    serde_json::from_value(value.clone()).map_err(|e| GrammarError::Invalid(format!("{what}: {e}")))
1170}
1171
1172/// Tests write graphs as YAML, the op form's shortest spelling; the engine
1173/// itself reads only JSON.
1174#[cfg(test)]
1175pub(crate) fn from_yaml(text: &str) -> Result<Grammar, GrammarError> {
1176    let value: Value = serde_saphyr::from_str(text).map_err(|e| GrammarError::Json(e.to_string()))?;
1177    Grammar::from_json(&value.to_string())
1178}
1179
1180fn build(raw: Raw) -> Result<Grammar, GrammarError> {
1181    let mut sections: Vec<(Section, Vec<Def>)> = Vec::new();
1182    for (section, entries) in [
1183        (Section::Features, raw.features),
1184        (Section::Areas, raw.areas),
1185        (Section::Lines, raw.lines),
1186        (Section::Fills, raw.fills),
1187    ] {
1188        if entries.is_empty() {
1189            continue;
1190        }
1191        let mut seen = BTreeSet::new();
1192        let mut defs = Vec::new();
1193        for (name, raw_op) in entries {
1194            if !seen.insert(name.clone()) {
1195                return Err(GrammarError::Invalid(format!("${}.{} is defined twice", section, name)));
1196            }
1197            let at = raw_op.1;
1198            let op = parse_op(raw_op, section).map_err(|e| match e {
1199                GrammarError::Invalid(m) => GrammarError::Invalid(located(&format!("${section}.{name}: {m}"), at)),
1200                other => other,
1201            })?;
1202            defs.push(Def { name, op, at });
1203        }
1204        sections.push((section, defs));
1205    }
1206
1207    let draw = raw
1208        .draw
1209        .into_iter()
1210        .map(|d| {
1211            Ok(Draw {
1212                from: parse_output(&d.from)?,
1213                id: d.id,
1214                stroke: d.stroke,
1215                at: d.at,
1216            })
1217        })
1218        .collect::<Result<Vec<_>, GrammarError>>()?;
1219
1220    let mut masks = Vec::new();
1221    for (name, m) in raw.compose.masks {
1222        masks.push((
1223            name,
1224            Mask {
1225                from: parse_output(&m.from)?,
1226                occludes: m.occludes.into_iter().map(Id).collect(),
1227                at: m.at,
1228            },
1229        ));
1230    }
1231
1232    let clip_default = match &raw.compose.clip.default {
1233        None => Clip::Auto,
1234        Some(ClipValue::Keyword(k)) => match k.as_str() {
1235            "auto" => Clip::Auto,
1236            "none" => Clip::None,
1237            other => {
1238                return Err(GrammarError::Invalid(format!(
1239                    "clip default {other:?} is unknown: write auto, none, or a list of $areas.*"
1240                )))
1241            }
1242        },
1243        Some(ClipValue::List(names)) => Clip::Areas(
1244            names
1245                .iter()
1246                .map(|n| refname(n))
1247                .collect::<Result<Vec<_>, _>>()?,
1248        ),
1249    };
1250
1251    let optimize = raw
1252        .compose
1253        .optimize
1254        .into_iter()
1255        .map(|s| crate::optimize::OptimizeStep {
1256            layers: s.layers.into_iter().map(Id).collect(),
1257            except: s.except.into_iter().map(Id).collect(),
1258            op: s.op,
1259            at: s.at,
1260        })
1261        .collect();
1262
1263    let compose = Compose {
1264        order: raw.compose.order.into_iter().map(Id).collect(),
1265        masks,
1266        clip: BTreeMap::new(),
1267        clip_default,
1268        optimize,
1269    };
1270
1271    let views = raw
1272        .views
1273        .into_iter()
1274        .map(|v| {
1275            let inner: Raw = serde_json::from_value(v.graph).map_err(|e| GrammarError::Json(format!("views.{}: {e}", v.id)))?;
1276            let grammar = build(inner).map_err(|e| GrammarError::Invalid(format!("view {}: {e}", v.id)))?;
1277            Ok(View { id: v.id, at: (v.at[0], v.at[1]), grammar: Box::new(grammar), ink: v.ink })
1278        })
1279        .collect::<Result<Vec<_>, GrammarError>>()?;
1280    let paint = raw
1281        .paint
1282        .into_iter()
1283        .map(|p| {
1284            let from = parse_output(&p.from)?;
1285            // Lines and features have a look by default; an area says its fill.
1286            let kind = if from.module.is_some() { Section::Lines } else { from.name.section };
1287            let (key, body) = match (p.fill, p.line, p.text) {
1288                (Some(f), None, None) => ("fill", f),
1289                (None, Some(l), None) => ("line", l),
1290                (None, None, Some(t)) => ("text", t),
1291                (None, None, None) if kind == Section::Lines => ("line", serde_json::json!({})),
1292                (None, None, None) if kind == Section::Features => ("text", serde_json::json!({})),
1293                _ => {
1294                    return Err(GrammarError::Invalid(located(
1295                        &format!("paint {:?}: one of fill, line or text", p.id),
1296                        p.at,
1297                    )))
1298                }
1299            };
1300            let fail = |m: String| GrammarError::Invalid(located(&format!("paint {:?}: {m}", p.id), p.at));
1301            let look = crate::paint::Style::new(key, body).map_err(fail)?;
1302            let shown = crate::paint::Shown::new(p.minzoom, p.maxzoom, p.filter).map_err(fail)?;
1303            Ok(crate::paint::Paint { id: p.id, from, look, shown, halo: p.halo, at: p.at })
1304        })
1305        .collect::<Result<Vec<_>, GrammarError>>()?;
1306    let mut output = raw.output;
1307    output.fit_screen().map_err(GrammarError::Invalid)?;
1308    let grammar = Grammar { title: raw.title, output, sections, draw, compose, paint, views };
1309    validate(&grammar)?;
1310    Ok(grammar)
1311}
1312
1313fn not_a_reference(text: String) -> GrammarError {
1314    GrammarError::Invalid(format!("{text:?} is not a $section.name reference"))
1315}
1316
1317/// `$lines.x`, `$fills.x`, or `roads.outlines` (a module output).
1318fn parse_output(text: &str) -> Result<Target, GrammarError> {
1319    if let Some(rest) = text.strip_prefix('$') {
1320        return Ok(Target { module: None, name: refname(&format!("${rest}"))? });
1321    }
1322    match text.split_once('.') {
1323        Some((module, name)) if !name.is_empty() => {
1324            Ok(Target { module: Some(module.to_string()), name: Name { section: Section::Lines, name: name.to_string() } })
1325        }
1326        _ => Err(GrammarError::Invalid(format!(
1327            "{text:?} is not a reference: write $lines.x, $fills.x or <module>.<output>"
1328        ))),
1329    }
1330}
1331
1332fn refname(text: &str) -> Result<Name, GrammarError> {
1333    Name::parse(text).map_err(|_| not_a_reference(text.to_string()))
1334}
1335
1336/// A draw/`from` target: `$lines.x` / `$fills.x`, or `roads.outlines` (a module
1337/// output, which has no `$` because the engine produced it).
1338#[derive(Debug, Clone, PartialEq, Eq)]
1339pub struct Target {
1340    /// `None` = a `$section.name` def; `Some(module)` = a module output.
1341    pub module: Option<String>,
1342    pub name: Name,
1343}
1344
1345fn parse_op(raw: RawOp, section: Section) -> Result<Op, GrammarError> {
1346    let (key, value) = only_op(raw).map_err(GrammarError::Invalid)?;
1347    let target = match key.as_str() {
1348        "osm_select" | "tiles_select" | "data_select" | "terrain_select" | "tools_where" => Section::Features,
1349        "tools_polygons" | "tools_union" | "tools_difference" | "tools_intersect" | "tools_fill_holes"
1350        | "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" => {
1351            Section::Areas
1352        }
1353        "tools_rings" | "tools_lines" | "tools_segments" | "tools_dedupe" | "tools_merge" | "tools_join"
1354        | "tools_clip" | "tools_path" | "tools_text" | "tools_terrain" | "tools_burin" | "tools_labels" | "tools_label_lines" | "tools_graticule" => Section::Lines,
1355        "tools_fill" => Section::Fills,
1356        other => {
1357            if let Some(rest) = other.strip_prefix("module_") {
1358                let mut obj = value.as_object().cloned().ok_or_else(|| {
1359                    GrammarError::Json(format!("{key}: expected an object"))
1360                })?;
1361                let from_val = obj.remove("from");
1362                let from = match from_val {
1363                    Some(Value::String(s)) => Some(refname(&s)?),
1364                    Some(v) => return Err(GrammarError::Json(format!("{key}.from: expected a string, got {v}"))),
1365                    None => None,
1366                };
1367                if let Some(f) = &from {
1368                    if f.section != Section::Features {
1369                        return Err(GrammarError::Invalid(format!("{key}.from is {f}, but it must be a $features set")));
1370                    }
1371                }
1372                let roads: crate::themes::RoadOptions = json(&Value::Object(obj), &key)?;
1373                roads.validate().map_err(GrammarError::Invalid)?;
1374                return Ok(Op::Module(Module { name: rest.to_string(), from, roads }));
1375            }
1376            if let Some(rest) = other.strip_prefix("primitives_") {
1377                return Err(GrammarError::Invalid(format!(
1378                    "primitives_{rest} is not defined in this build"
1379                )));
1380            }
1381            return Err(GrammarError::Invalid(format!("unknown operation {other:?}")));
1382        }
1383    };
1384    if target != section {
1385        return Err(GrammarError::Invalid(format!(
1386            "{key} produces {target}, but it is written under ${section}"
1387        )));
1388    }
1389    let _ = target;
1390    let op = match key.as_str() {
1391        "osm_select" => Op::Select(parse_selector(&value)?),
1392        "tiles_select" => Op::TileSelect(parse_tile_select(&value)?),
1393        "terrain_select" => {
1394            let t: crate::contours::TerrainSelect = json(&value, "terrain_select")?;
1395            t.validate().map_err(GrammarError::Invalid)?;
1396            Op::TerrainSelect(t)
1397        }
1398        "data_select" => match &value {
1399            Value::String(s) if !s.trim().is_empty() => Op::DataSelect(DataSource::Url(s.trim().to_string())),
1400            Value::Object(o) if o.len() == 1 && o.get("geojson").is_some_and(Value::is_object) => {
1401                let gj = o["geojson"].clone();
1402                crate::geojson::features_of(&gj).map_err(|e| GrammarError::Invalid(format!("data_select: {e}")))?;
1403                Op::DataSelect(DataSource::Inline(gj))
1404            }
1405            Value::Object(o) if o.len() == 1 && o.get("json").is_some_and(Value::is_object) => {
1406                let js: JsonSource = serde_json::from_value(o["json"].clone())
1407                    .map_err(|e| GrammarError::Invalid(format!("data_select.json: {e}")))?;
1408                if js.url.trim().is_empty() || js.lat.is_empty() || js.lng.is_empty() {
1409                    return Err(GrammarError::Invalid("data_select.json needs a url, and the lat and lng paths".into()));
1410                }
1411                Op::DataSelect(DataSource::Json(js))
1412            }
1413            _ => return Err(GrammarError::Invalid("data_select is a URL, a file path, { geojson: {…} } or { json: { url, items, lat, lng } }".into())),
1414        },
1415        "tools_where" => Op::Where(parse_where(&value)?),
1416        "engine_frame" => Op::Frame,
1417        "tools_polygons" => Op::Polygons(name_ref(&value, "tools_polygons")?),
1418        "tools_union" => Op::Union(union_rules(&value, "tools_union")?),
1419        "tools_difference" => {
1420            #[derive(Deserialize)]
1421            struct Raw {
1422                base: String,
1423                cut: OneOrMany,
1424            }
1425            let raw: Raw = json(&value, "tools_difference")?;
1426            let (cut, cut_rule) = cut_rules(&raw.cut.into_vec(), "tools_difference.cut")?;
1427            Op::Difference(Difference { base: refname(&raw.base)?, cut, cut_rule })
1428        }
1429        "tools_intersect" => {
1430            #[derive(Deserialize)]
1431            struct Raw {
1432                base: String,
1433                #[serde(default)]
1434                keep: Option<String>,
1435                #[serde(default)]
1436                keep_rule: Option<RawOp>,
1437            }
1438            let raw: Raw = json(&value, "tools_intersect")?;
1439            if raw.keep.is_some() == raw.keep_rule.is_some() {
1440                return Err(GrammarError::Invalid(
1441                    "tools_intersect needs exactly one of `keep: $areas.x` or `keep_rule: { ... }`".into(),
1442                ));
1443            }
1444            let keep_rule = match raw.keep_rule {
1445                Some(op) => Some(Box::new(parse_op(op, Section::Areas)?)),
1446                None => None,
1447            };
1448            Op::Intersect(Intersect {
1449                base: refname(&raw.base)?,
1450                keep: raw.keep.as_deref().map(refname).transpose()?,
1451                keep_rule,
1452            })
1453        }
1454        "tools_fill_holes" => Op::FillHoles(name_ref(&value, "tools_fill_holes")?),
1455        "tools_label_area" => Op::LabelArea(parse_label_pick(&value, "tools_label_area")?),
1456        "tools_label_lines" => Op::LabelLines(parse_label_pick(&value, "tools_label_lines")?),
1457        "tools_move" => {
1458            #[derive(Deserialize)]
1459            #[serde(deny_unknown_fields)]
1460            struct Raw {
1461                of: String,
1462                by: [Mm; 2],
1463            }
1464            let raw: Raw = json(&value, "tools_move")?;
1465            Op::Move(Move { of: refname(&raw.of)?, by: raw.by })
1466        }
1467        "tools_grow" => {
1468            #[derive(Deserialize)]
1469            #[serde(deny_unknown_fields)]
1470            struct Raw {
1471                of: String,
1472                by: Mm,
1473            }
1474            let raw: Raw = json(&value, "tools_grow")?;
1475            Op::Grow(Grow { of: refname(&raw.of)?, by: raw.by })
1476        }
1477        "tools_around" => {
1478            #[derive(Deserialize)]
1479            #[serde(deny_unknown_fields)]
1480            struct Raw {
1481                of: String,
1482                by: Mm,
1483            }
1484            let raw: Raw = json(&value, "tools_around")?;
1485            let of = refname(&raw.of)?;
1486            if of.section != Section::Features {
1487                return Err(GrammarError::Invalid("tools_around: of must be $features".into()));
1488            }
1489            Op::Around(Around { of, by: raw.by })
1490        }
1491        "tools_shape" | "tools_path" => {
1492            let shape: Shape = json(&value, &key)?;
1493            if let ShapeAt::Page(xy) = &shape.at {
1494                for p in xy {
1495                    if let PagePos::Percent(s) = p {
1496                        if percent(s).is_none() {
1497                            return Err(GrammarError::Invalid(format!("{key}.at: {s:?} is not a length or a percentage")));
1498                        }
1499                    }
1500                }
1501            }
1502            if shape.points.len() < if key == "tools_shape" { 3 } else { 2 } {
1503                return Err(GrammarError::Invalid(format!("{key}: too few points")));
1504            }
1505            if key == "tools_shape" { Op::Shape(shape) } else { Op::Path(shape) }
1506        }
1507        "tools_text" | "tools_text_area" => {
1508            let text: Text = json(&value, &key)?;
1509            crate::text::validate_label_font(&text.font).map_err(GrammarError::Invalid)?;
1510            if key == "tools_text" { Op::Text(text) } else { Op::TextArea(text) }
1511        }
1512        "tools_buffer_lines" => {
1513            #[derive(Deserialize)]
1514            #[serde(deny_unknown_fields)]
1515            struct Raw {
1516                lines: String,
1517                by: Mm,
1518                #[serde(default)]
1519                cap: LineBufferCap,
1520            }
1521            let raw: Raw = json(&value, "tools_buffer_lines")?;
1522            Op::BufferLines(BufferLines { lines: refname(&raw.lines)?, by: raw.by, cap: raw.cap })
1523        }
1524        "tools_extend_to_frame" => {
1525            #[derive(Deserialize)]
1526            #[serde(deny_unknown_fields)]
1527            struct Raw {
1528                of: String,
1529                within: String,
1530                // Read and ignored: saved graphs still carry it.
1531                #[serde(rename = "min_height_frac")]
1532                _min_height_frac: Option<f64>,
1533                gap_mm: Option<Mm>,
1534            }
1535            let raw: Raw = json(&value, "tools_extend_to_frame")?;
1536            Op::ExtendToFrame(ExtendToFrame {
1537                of: refname(&raw.of)?,
1538                within: refname(&raw.within)?,
1539                gap_mm: raw.gap_mm,
1540            })
1541        }
1542        "tools_terrain" | "tools_terrain_band" => {
1543            #[derive(Deserialize)]
1544            #[serde(deny_unknown_fields)]
1545            struct Raw {
1546                #[serde(default)]
1547                in_area: Option<String>,
1548                #[serde(default)]
1549                color: Option<serde_json::Value>,
1550                #[serde(default)]
1551                width: Option<serde_json::Value>,
1552                #[serde(default)]
1553                angle: Option<f64>,
1554                #[serde(default)]
1555                layer: Option<String>,
1556                #[serde(default)]
1557                shore: Option<bool>,
1558                #[serde(default)]
1559                style: Option<serde_json::Map<String, serde_json::Value>>,
1560                #[serde(default)]
1561                r#where: Option<serde_json::Map<String, serde_json::Value>>,
1562                #[serde(default)]
1563                draw: Option<String>,
1564            }
1565            let raw: Raw = json(&value, "tools_terrain")?;
1566            let band = key.as_str() == "tools_terrain_band";
1567            let t = Terrain {
1568                in_area: raw.in_area.as_deref().map(refname).transpose()?,
1569                color: raw.color,
1570                width: raw.width,
1571                angle: raw.angle.unwrap_or(0.0),
1572                layer: raw.layer,
1573                style: raw.style.unwrap_or_default(),
1574                shore: raw.shore.unwrap_or(false),
1575                band: raw.r#where.unwrap_or_default(),
1576                draw: match raw.draw.as_deref() {
1577                    None | Some("lines") => TerrainDraw::Lines,
1578                    Some("fill") => TerrainDraw::Fill,
1579                    Some("dots") => TerrainDraw::Dots,
1580                    Some(other) => {
1581                        return Err(GrammarError::Invalid(format!(
1582                            "tools_terrain draws lines, a fill or dots, not {other:?}"
1583                        )))
1584                    }
1585                },
1586            };
1587            if band {
1588                Op::TerrainBand(Terrain { draw: TerrainDraw::Fill, ..t })
1589            } else {
1590                Op::Terrain(t)
1591            }
1592        }
1593        "tools_burin" => {
1594            #[derive(Deserialize)]
1595            #[serde(deny_unknown_fields)]
1596            struct Raw {
1597                /// The atlas, as `burin.json()` writes it: a list, or the JSON
1598                /// string of one (the library hands a string).
1599                atlas: Value,
1600                #[serde(default)]
1601                in_area: Option<String>,
1602                #[serde(default)]
1603                regions: std::collections::BTreeMap<String, String>,
1604                #[serde(default)]
1605                water: Option<String>,
1606                #[serde(default)]
1607                layer: Option<String>,
1608            }
1609            let raw: Raw = json(&value, "tools_burin")?;
1610            let regions = raw
1611                .regions
1612                .into_iter()
1613                .map(|(name, r)| {
1614                    let n = refname(&r)?;
1615                    if n.section != Section::Areas {
1616                        return Err(GrammarError::Invalid(format!(
1617                            "tools_burin.regions.{name} must be an area, not {n}"
1618                        )));
1619                    }
1620                    Ok((name, n))
1621                })
1622                .collect::<Result<_, _>>()?;
1623            let atlas = match raw.atlas {
1624                Value::String(text) => {
1625                    serde_json::from_str(&text).map_err(|e| GrammarError::Invalid(format!("tools_burin atlas: {e}")))?
1626                }
1627                other => other,
1628            };
1629            if !atlas.is_array() {
1630                return Err(GrammarError::Invalid("tools_burin atlas is a list of batches and water passes".into()));
1631            }
1632            Op::Burin(Burin {
1633                atlas,
1634                in_area: raw.in_area.as_deref().map(refname).transpose()?,
1635                regions,
1636                water: raw.water.as_deref().map(refname).transpose()?,
1637                layer: raw.layer,
1638            })
1639        }
1640        "tools_graticule" | "tools_graticule_area" => {
1641            let mut body = match value {
1642                Value::Object(m) => m,
1643                _ => return Err(GrammarError::Invalid(format!("{key} takes {{ in, part, step, ... }}"))),
1644            };
1645            let in_area = match body.remove("in") {
1646                Some(Value::String(s)) => refname(&s)?,
1647                _ => return Err(GrammarError::Invalid(format!("{key} needs in: an $areas reference"))),
1648            };
1649            if in_area.section != Section::Areas {
1650                return Err(GrammarError::Invalid(format!("{key}.in is {in_area}, but it reads an $areas def")));
1651            }
1652            let look: GraticuleLook = json(&Value::Object(body), &key)?;
1653            crate::text::validate_label_font(&look.font).map_err(GrammarError::Invalid)?;
1654            if !(look.step > 0.0) {
1655                return Err(GrammarError::Invalid(format!("{key}.step is minutes of arc, more than 0")));
1656            }
1657            let fits = match look.part {
1658                GraticulePart::Grid => key == "tools_graticule",
1659                GraticulePart::Keys => key == "tools_graticule_area",
1660                GraticulePart::Labels => true,
1661            };
1662            if !fits {
1663                return Err(GrammarError::Invalid(format!("{key}: part {:?} is not drawn by it", look.part)));
1664            }
1665            let g = Graticule { in_area, look };
1666            if key == "tools_graticule" { Op::Graticule(g) } else { Op::GraticuleArea(g) }
1667        }
1668        "tools_labels" => {
1669            let mut body = match value {
1670                Value::Object(m) => m,
1671                _ => return Err(GrammarError::Invalid("tools_labels takes { from, ...style }".into())),
1672            };
1673            let from: Vec<Name> = match body.remove("from") {
1674                Some(Value::String(s)) => vec![refname(&s)?],
1675                Some(Value::Array(items)) if !items.is_empty() => items
1676                    .iter()
1677                    .map(|v| v.as_str().ok_or_else(|| not_a_reference(v.to_string())).and_then(refname))
1678                    .collect::<Result<_, _>>()?,
1679                _ => return Err(GrammarError::Invalid("tools_labels needs from: $features.x or a list of them".into())),
1680            };
1681            if let Some(f) = from.iter().find(|f| f.section != Section::Features) {
1682                return Err(GrammarError::Invalid(format!("tools_labels.from has {f}, but it reads $features sets")));
1683            }
1684            let mut area_ref = |key: &str| -> Result<Option<Name>, GrammarError> {
1685                match body.remove(key) {
1686                    None => Ok(None),
1687                    Some(Value::String(s)) => {
1688                        let n = refname(&s)?;
1689                        if n.section != Section::Areas {
1690                            return Err(GrammarError::Invalid(format!("tools_labels.{key} is {n}, but it reads an $areas def")));
1691                        }
1692                        Ok(Some(n))
1693                    }
1694                    Some(_) => Err(GrammarError::Invalid(format!("tools_labels.{key} expects an $areas reference"))),
1695                }
1696            };
1697            let in_area = area_ref("in")?;
1698            let avoid = area_ref("avoid")?;
1699            let style: crate::labels::Style = json(&Value::Object(body), "tools_labels")?;
1700            crate::labels::validate_style(&style).map_err(GrammarError::Invalid)?;
1701            Op::Labels(Labels { from, in_area, avoid, style })
1702        }
1703        "tools_rings" => match &value {
1704            Value::String(s) => Op::Rings(Rings { of: refname(s)?, exterior_only: false }),
1705            _ => {
1706                #[derive(Deserialize)]
1707                #[serde(deny_unknown_fields)]
1708                struct Raw {
1709                    of: String,
1710                    #[serde(default)]
1711                    exterior_only: bool,
1712                }
1713                let raw: Raw = json(&value, "tools_rings")?;
1714                Op::Rings(Rings { of: refname(&raw.of)?, exterior_only: raw.exterior_only })
1715            }
1716        },
1717        "tools_lines" => Op::Lines(name_ref(&value, "tools_lines")?),
1718        "tools_segments" => Op::Segments(name_ref(&value, "tools_segments")?),
1719        "tools_dedupe" => Op::Dedupe(name_ref(&value, "tools_dedupe")?),
1720        "tools_merge" => Op::Merge(name_ref(&value, "tools_merge")?),
1721        "tools_join" => Op::Join(union_rules(&value, "tools_join")?),
1722        "tools_clip" => {
1723            #[derive(Deserialize)]
1724            #[serde(deny_unknown_fields)]
1725            struct Raw {
1726                lines: String,
1727                within: String,
1728                #[serde(default)]
1729                invert: bool,
1730            }
1731            let raw: Raw = json(&value, "tools_clip")?;
1732            Op::ClipLines(ClipLines { lines: refname(&raw.lines)?, within: refname(&raw.within)?, invert: raw.invert })
1733        }
1734        "tools_fill" | "tools_fill_cover" => {
1735            // The v3 toolkit writes `pattern:` (dots, waves, zigzag…), the spec
1736            // calls it `generator:`; one rename and the rest is FillSpec.
1737            #[derive(Deserialize)]
1738            struct Raw {
1739                #[serde(rename = "in")]
1740                in_area: String,
1741                #[serde(default)]
1742                per: Option<String>,
1743                #[serde(default)]
1744                pattern: Option<String>,
1745                #[serde(default)]
1746                content: Option<String>,
1747                #[serde(flatten)]
1748                spec: FillSpec,
1749            }
1750            let mut raw: Raw = json(&value, &key)?;
1751            if let Some(pattern) = raw.pattern.take() {
1752                if raw.spec.generator.is_none() {
1753                    raw.spec.generator = Some(pattern);
1754                }
1755            }
1756            let per_feature = match raw.per.as_deref() {
1757                None => false,
1758                Some("feature") => true,
1759                Some(other) => {
1760                    return Err(GrammarError::Invalid(format!(
1761                        "tools_fill: per: {other:?} is unknown (only `per: feature`)"
1762                    )))
1763                }
1764            };
1765            let content = raw.content.as_deref().map(refname).transpose()?;
1766            if content.as_ref().is_some_and(|c| c.section != Section::Lines) {
1767                return Err(GrammarError::Invalid("tools_fill: content must be $lines".into()));
1768            }
1769            // A motif given as `$lines.…` is a reference, resolved when the fill
1770            // runs; polylines or a symbol name stay in the spec as they are.
1771            let motif = match raw.spec.options.get("motif") {
1772                Some(Value::String(s)) if s.starts_with('$') => {
1773                    let name = refname(s)?;
1774                    if name.section != Section::Lines {
1775                        return Err(GrammarError::Invalid("tools_fill: motif must be $lines, polylines or a symbol name".into()));
1776                    }
1777                    raw.spec.options.remove("motif");
1778                    Some(name)
1779                }
1780                _ => None,
1781            };
1782            let fill = Fill { in_area: refname(&raw.in_area)?, per_feature, content, motif, spec: raw.spec };
1783            if key == "tools_fill" {
1784                Op::Fill(fill)
1785            } else if fill.per_feature || fill.content.is_some() {
1786                return Err(GrammarError::Invalid("tools_fill_cover takes a pattern, not per or content".into()));
1787            } else {
1788                Op::FillCover(fill)
1789            }
1790        }
1791        _ => unreachable!("keys are matched above"),
1792    };
1793    Ok(op)
1794}
1795
1796/// `tools_difference.cut`: a list of references, or one inline rule.
1797fn cut_rules(items: &[String], what: &str) -> Result<(Vec<Name>, Option<Box<Op>>), GrammarError> {
1798    if items.is_empty() {
1799        return Err(GrammarError::Invalid(format!("{what} needs at least one input")));
1800    }
1801    if items.len() == 1 {
1802        if let Ok(op) = serde_json::from_str::<RawOp>(&items[0]) {
1803            return Err(GrammarError::Invalid(format!(
1804                "{what}: inline rules are not supported yet; define it under $areas and use $areas.name ({op:?})"
1805            )));
1806        }
1807    }
1808    Ok((items.iter().map(|s| refname(s)).collect::<Result<_, _>>()?, None))
1809}
1810
1811fn name_ref(value: &Value, op: &str) -> Result<Name, GrammarError> {
1812    let s: String = json(value, op)?;
1813    refname(&s)
1814}
1815
1816fn parse_label_pick(value: &Value, op: &str) -> Result<LabelPick, GrammarError> {
1817    match value {
1818        Value::String(s) => {
1819            let of = refname(s)?;
1820            if of.section != Section::Lines {
1821                return Err(GrammarError::Invalid(format!("{op} reads {of}, but labels live under $lines")));
1822            }
1823            Ok(LabelPick { of, rule: None, dots: false })
1824        }
1825        _ => {
1826            #[derive(Deserialize)]
1827            #[serde(deny_unknown_fields)]
1828            struct Raw {
1829                of: String,
1830                #[serde(default)]
1831                rule: Option<String>,
1832                #[serde(default)]
1833                dots: bool,
1834            }
1835            let raw: Raw = json(value, op)?;
1836            let of = refname(&raw.of)?;
1837            if of.section != Section::Lines {
1838                return Err(GrammarError::Invalid(format!("{op}.of is {of}, but labels live under $lines")));
1839            }
1840            Ok(LabelPick { of, rule: raw.rule, dots: raw.dots })
1841        }
1842    }
1843}
1844
1845fn label_pick_json(pick: &LabelPick) -> Value {
1846    use serde_json::json;
1847    match (&pick.rule, pick.dots) {
1848        (None, false) => Value::String(pick.of.to_string()),
1849        (rule, false) => json!({ "of": pick.of.to_string(), "rule": rule }),
1850        (None, true) => json!({ "of": pick.of.to_string(), "dots": true }),
1851        (rule, true) => json!({ "of": pick.of.to_string(), "rule": rule, "dots": true }),
1852    }
1853}
1854
1855/// `tools_union`: a list of references, or one reference with `list: false`.
1856fn union_rules(value: &Value, op: &str) -> Result<UnionRules, GrammarError> {
1857    #[derive(Deserialize)]
1858    #[serde(deny_unknown_fields)]
1859    struct Raw {
1860        #[serde(default)]
1861        refs: Vec<String>,
1862        #[serde(default, rename = "ref")]
1863        single: Option<String>,
1864        #[serde(default)]
1865        list: Option<bool>,
1866        #[serde(default)]
1867        rule: Option<RawOp>,
1868    }
1869    match value {
1870        // The plain form: `tools_union: [{ tools_polygons: ... }, ...]`
1871        Value::Array(items) => {
1872            if items.is_empty() {
1873                return Err(GrammarError::Invalid(format!("{op} needs at least one input")));
1874            }
1875            Ok(UnionRules::Refs(inline_list(items, op)?))
1876        }
1877        Value::String(s) => Ok(UnionRules::Ref(refname(s)?)),
1878        Value::Object(_) => {
1879            let raw: Raw = json(value, op)?;
1880            if let Some(rule) = raw.rule {
1881                let parsed = parse_op(rule, Section::Areas)?;
1882                if parsed.section() != Section::Areas {
1883                    return Err(GrammarError::Invalid(format!(
1884                        "{op}: `rule` must produce an area"
1885                    )));
1886                }
1887                return Ok(UnionRules::Refs(parsed.refs()));
1888            }
1889            match (raw.single, raw.list, raw.refs.is_empty()) {
1890                (Some(s), Some(false), true) => Ok(UnionRules::Ref(refname(&s)?)),
1891                (Some(s), _, true) => Ok(UnionRules::Ref(refname(&s)?)),
1892                (None, _, false) => Ok(UnionRules::Refs(
1893                    raw.refs.iter().map(|s| refname(s)).collect::<Result<_, _>>()?,
1894                )),
1895                _ => Err(GrammarError::Invalid(format!(
1896                    "{op} needs a list of references (or `list: false` with one)"
1897                ))),
1898            }
1899        }
1900        other => Err(GrammarError::Invalid(format!("{op}: unexpected {other}"))),
1901    }
1902}
1903
1904/// A list that may contain `$refs` and/or one inline rule.
1905/// v3 allows exactly one form: if a rule is present it must be the only item.
1906fn inline_list(items: &[Value], op: &str) -> Result<Vec<Name>, GrammarError> {
1907    let mut refs = Vec::new();
1908    let mut rules = 0usize;
1909    for item in items {
1910        match item {
1911            Value::String(s) => refs.push(refname(s)?),
1912            Value::Object(_) => rules += 1,
1913            other => return Err(GrammarError::Invalid(format!("{op}: unexpected item {other}"))),
1914        }
1915    }
1916    if rules > 1 || (rules == 1 && !refs.is_empty()) {
1917        return Err(GrammarError::Invalid(format!(
1918            "{op}: write one inline rule, or a list of $refs, not both"
1919        )));
1920    }
1921    Ok(refs)
1922}
1923
1924#[derive(Debug, Deserialize)]
1925#[serde(untagged)]
1926enum OneOrMany {
1927    One(String),
1928    Many(Vec<String>),
1929}
1930
1931impl OneOrMany {
1932    fn into_vec(self) -> Vec<String> {
1933        match self {
1934            OneOrMany::One(s) => vec![s],
1935            OneOrMany::Many(v) => v,
1936        }
1937    }
1938}
1939
1940fn parse_tile_select(value: &Value) -> Result<TileSelect, GrammarError> {
1941    let items: Vec<String> = json::<OneOrMany>(value, "tiles_select")?
1942        .into_vec()
1943        .iter()
1944        .flat_map(|s| s.split(|c: char| c.is_whitespace()).map(str::to_string).collect::<Vec<_>>())
1945        .filter(|s| !s.is_empty())
1946        .collect();
1947    if items.is_empty() {
1948        return Err(GrammarError::Invalid("tiles_select needs a preset or a layer:class rule".into()));
1949    }
1950    let filter = terramask::Filter::parse(&items).map_err(|e| GrammarError::Invalid(format!("tiles_select: {e}")))?;
1951    Ok(TileSelect { items, filter })
1952}
1953
1954fn parse_where(value: &Value) -> Result<Where, GrammarError> {
1955    #[derive(Deserialize)]
1956    #[serde(deny_unknown_fields)]
1957    struct Raw {
1958        of: String,
1959        tags: serde_json::Map<String, Value>,
1960    }
1961    let raw: Raw = json(value, "tools_where")?;
1962    let of = refname(&raw.of)?;
1963    if of.section != Section::Features {
1964        return Err(GrammarError::Invalid(format!("tools_where.of is {of}, but it must be a $features set")));
1965    }
1966    if raw.tags.is_empty() {
1967        return Err(GrammarError::Invalid("tools_where needs at least one tag".into()));
1968    }
1969    let tags = crate::select::parse_tag_tests(raw.tags).map_err(|e| GrammarError::Invalid(format!("tools_where: {e}")))?;
1970    Ok(Where { of, tags })
1971}
1972
1973fn parse_selector(value: &Value) -> Result<Selector, GrammarError> {
1974    #[derive(Deserialize)]
1975    struct Raw {
1976        #[serde(flatten)]
1977        any: BTreeMap<String, OneOrManyOrBool>,
1978        #[serde(default)]
1979        except: BTreeMap<String, OneOrManyOrBool>,
1980        #[serde(default)]
1981        underground: bool,
1982    }
1983    #[derive(Deserialize)]
1984    #[serde(untagged)]
1985    enum OneOrManyOrBool {
1986        Bool(bool),
1987        One(String),
1988        Many(Vec<String>),
1989    }
1990    impl OneOrManyOrBool {
1991        fn to_match(&self) -> TagMatch {
1992            match self {
1993                OneOrManyOrBool::Bool(p) => TagMatch::Present(*p),
1994                OneOrManyOrBool::One(v) => TagMatch::Values(vec![v.clone()]),
1995                OneOrManyOrBool::Many(vs) => TagMatch::Values(vs.clone()),
1996            }
1997        }
1998    }
1999    let raw: Raw = json(value, "osm_select")?;
2000    if raw.any.is_empty() {
2001        return Err(GrammarError::Invalid("osm_select needs at least one tag".into()));
2002    }
2003    Ok(Selector {
2004        any: raw.any.iter().map(|(k, v)| (k.clone(), v.to_match())).collect(),
2005        except: raw.except.iter().map(|(k, v)| (k.clone(), v.to_match())).collect(),
2006        underground: raw.underground,
2007    })
2008}
2009
2010// ---------------------------------------------------------------------------
2011// JSON: the graph saved and loaded
2012// ---------------------------------------------------------------------------
2013
2014/// One operation from its JSON form, `{ "tools_union": ["$areas.a"] }`, as
2015/// the def it will be in `section`.
2016pub fn op_from_json(section: Section, op: Value) -> Result<Op, GrammarError> {
2017    let Value::Object(map) = op else {
2018        return Err(GrammarError::Invalid(format!("an operation is an object, not {op}")));
2019    };
2020    let raw = RawOp(map.into_iter().collect(), None);
2021    if raw.0.len() != 1 {
2022        return Err(GrammarError::Invalid("an operation has exactly one key".into()));
2023    }
2024    parse_op(raw, section)
2025}
2026
2027fn tag_json(m: &TagMatch) -> Value {
2028    match m {
2029        TagMatch::Present(p) => Value::Bool(*p),
2030        TagMatch::Values(vs) if vs.len() == 1 => Value::String(vs[0].clone()),
2031        TagMatch::Values(vs) => vs.iter().cloned().map(Value::String).collect(),
2032    }
2033}
2034
2035fn refs_json(names: &[Name]) -> Value {
2036    names.iter().map(|n| Value::String(n.to_string())).collect()
2037}
2038
2039/// The JSON form [`op_from_json`] reads back.
2040pub fn op_to_json(op: &Op) -> Value {
2041    use serde_json::json;
2042    let union = |u: &UnionRules| match u {
2043        UnionRules::Refs(ns) => refs_json(ns),
2044        UnionRules::Ref(n) => Value::String(n.to_string()),
2045    };
2046    let (key, value) = match op {
2047        Op::Select(sel) => {
2048            let mut body: serde_json::Map<String, Value> =
2049                sel.any.iter().map(|(k, m)| (k.clone(), tag_json(m))).collect();
2050            if !sel.except.is_empty() {
2051                body.insert("except".into(), sel.except.iter().map(|(k, m)| (k.clone(), tag_json(m))).collect());
2052            }
2053            if sel.underground {
2054                body.insert("underground".into(), Value::Bool(true));
2055            }
2056            ("osm_select", Value::Object(body))
2057        }
2058        Op::TileSelect(t) => ("tiles_select", t.items.iter().cloned().map(Value::String).collect()),
2059        Op::DataSelect(DataSource::Url(src)) => ("data_select", Value::String(src.clone())),
2060        Op::TerrainSelect(t) => ("terrain_select", serde_json::to_value(t).unwrap_or(Value::Null)),
2061        Op::DataSelect(DataSource::Inline(gj)) => ("data_select", json!({ "geojson": gj })),
2062        Op::DataSelect(DataSource::Json(js)) => ("data_select", json!({ "json": js })),
2063        Op::Where(w) => {
2064            let tags: serde_json::Map<String, Value> = w
2065                .tags
2066                .iter()
2067                .map(|(k, t)| {
2068                    let v = match t {
2069                        TagTest::Match(m) => tag_json(m),
2070                        TagTest::Range { min, max } => {
2071                            let mut r = serde_json::Map::new();
2072                            if let Some(lo) = min {
2073                                r.insert("min".into(), json!(lo));
2074                            }
2075                            if let Some(hi) = max {
2076                                r.insert("max".into(), json!(hi));
2077                            }
2078                            Value::Object(r)
2079                        }
2080                    };
2081                    (k.clone(), v)
2082                })
2083                .collect();
2084            ("tools_where", json!({ "of": w.of.to_string(), "tags": tags }))
2085        }
2086        Op::Polygons(n) => ("tools_polygons", Value::String(n.to_string())),
2087        Op::Union(u) => ("tools_union", union(u)),
2088        Op::Difference(d) => ("tools_difference", json!({ "base": d.base.to_string(), "cut": refs_json(&d.cut) })),
2089        Op::Intersect(i) => (
2090            "tools_intersect",
2091            json!({ "base": i.base.to_string(), "keep": i.keep.as_ref().map(Name::to_string) }),
2092        ),
2093        Op::FillHoles(n) => ("tools_fill_holes", Value::String(n.to_string())),
2094        Op::LabelArea(p) => ("tools_label_area", label_pick_json(p)),
2095        Op::LabelLines(p) => ("tools_label_lines", label_pick_json(p)),
2096        Op::Terrain(t) | Op::TerrainBand(t) => {
2097            let mut body = serde_json::Map::new();
2098            if let Some(a) = &t.in_area {
2099                body.insert("in_area".into(), Value::String(a.to_string()));
2100            }
2101            if let Some(c) = &t.color {
2102                body.insert("color".into(), c.clone());
2103            }
2104            if let Some(w) = &t.width {
2105                body.insert("width".into(), w.clone());
2106            }
2107            if t.angle != 0.0 {
2108                body.insert("angle".into(), json!(t.angle));
2109            }
2110            if let Some(l) = &t.layer {
2111                body.insert("layer".into(), Value::String(l.clone()));
2112            }
2113            if t.shore {
2114                body.insert("shore".into(), Value::Bool(true));
2115            }
2116            if !t.style.is_empty() {
2117                body.insert("style".into(), Value::Object(t.style.clone()));
2118            }
2119            if !t.band.is_empty() {
2120                body.insert("where".into(), Value::Object(t.band.clone()));
2121            }
2122            match t.draw {
2123                TerrainDraw::Lines => {}
2124                TerrainDraw::Fill => {
2125                    body.insert("draw".into(), Value::String("fill".into()));
2126                }
2127                TerrainDraw::Dots => {
2128                    body.insert("draw".into(), Value::String("dots".into()));
2129                }
2130            }
2131            (if matches!(op, Op::TerrainBand(_)) { "tools_terrain_band" } else { "tools_terrain" }, Value::Object(body))
2132        }
2133        Op::Burin(b) => {
2134            let mut body = serde_json::Map::new();
2135            body.insert("atlas".into(), b.atlas.clone());
2136            if let Some(a) = &b.in_area {
2137                body.insert("in_area".into(), Value::String(a.to_string()));
2138            }
2139            if !b.regions.is_empty() {
2140                body.insert(
2141                    "regions".into(),
2142                    Value::Object(
2143                        b.regions
2144                            .iter()
2145                            .map(|(k, v)| (k.clone(), Value::String(v.to_string())))
2146                            .collect(),
2147                    ),
2148                );
2149            }
2150            if let Some(w) = &b.water {
2151                body.insert("water".into(), Value::String(w.to_string()));
2152            }
2153            if let Some(l) = &b.layer {
2154                body.insert("layer".into(), Value::String(l.clone()));
2155            }
2156            ("tools_burin", Value::Object(body))
2157        }
2158        Op::Graticule(g) | Op::GraticuleArea(g) => {
2159            let mut body = serde_json::to_value(&g.look).unwrap_or_else(|_| json!({}));
2160            body["in"] = Value::String(g.in_area.to_string());
2161            (if matches!(op, Op::Graticule(_)) { "tools_graticule" } else { "tools_graticule_area" }, body)
2162        }
2163        Op::Labels(l) => {
2164            let mut body = serde_json::to_value(&l.style).unwrap_or_else(|_| json!({}));
2165            body["from"] = refs_json(&l.from);
2166            if let Some(a) = &l.in_area {
2167                body["in"] = Value::String(a.to_string());
2168            }
2169            if let Some(a) = &l.avoid {
2170                body["avoid"] = Value::String(a.to_string());
2171            }
2172            ("tools_labels", body)
2173        }
2174        Op::Grow(g) => ("tools_grow", json!({ "of": g.of.to_string(), "by": g.by })),
2175        Op::Move(m) => ("tools_move", json!({ "of": m.of.to_string(), "by": [m.by[0], m.by[1]] })),
2176        Op::Around(a) => ("tools_around", json!({ "of": a.of.to_string(), "by": a.by })),
2177        Op::Shape(s) => ("tools_shape", serde_json::to_value(s).unwrap_or_default()),
2178        Op::Path(s) => ("tools_path", serde_json::to_value(s).unwrap_or_default()),
2179        Op::Text(t) => ("tools_text", serde_json::to_value(t).unwrap_or_default()),
2180        Op::TextArea(t) => ("tools_text_area", serde_json::to_value(t).unwrap_or_default()),
2181        Op::BufferLines(b) => {
2182            let mut body = serde_json::Map::from_iter([
2183                ("lines".into(), Value::String(b.lines.to_string())),
2184                ("by".into(), json!(b.by)),
2185            ]);
2186            if b.cap == LineBufferCap::Flat {
2187                body.insert("cap".into(), json!("flat"));
2188            }
2189            ("tools_buffer_lines", Value::Object(body))
2190        }
2191        Op::Frame => ("engine_frame", json!({})),
2192        Op::ExtendToFrame(e) => (
2193            "tools_extend_to_frame",
2194            json!({
2195                "of": e.of.to_string(),
2196                "within": e.within.to_string(),
2197                "gap_mm": e.gap_mm,
2198            }),
2199        ),
2200        Op::Rings(r) => ("tools_rings", json!({ "of": r.of.to_string(), "exterior_only": r.exterior_only })),
2201        Op::Lines(n) => ("tools_lines", Value::String(n.to_string())),
2202        Op::Segments(n) => ("tools_segments", Value::String(n.to_string())),
2203        Op::Dedupe(n) => ("tools_dedupe", Value::String(n.to_string())),
2204        Op::Merge(n) => ("tools_merge", Value::String(n.to_string())),
2205        Op::Join(u) => ("tools_join", union(u)),
2206        Op::ClipLines(c) => (
2207            "tools_clip",
2208            json!({ "lines": c.lines.to_string(), "within": c.within.to_string(), "invert": c.invert }),
2209        ),
2210        Op::Fill(f) => {
2211            let mut body = serde_json::to_value(&f.spec).unwrap_or_else(|_| json!({}));
2212            body["in"] = Value::String(f.in_area.to_string());
2213            if f.per_feature {
2214                body["per"] = Value::String("feature".into());
2215            }
2216            if let Some(c) = &f.content {
2217                body["content"] = Value::String(c.to_string());
2218            }
2219            if let Some(m) = &f.motif {
2220                body["motif"] = Value::String(m.to_string());
2221            }
2222            ("tools_fill", body)
2223        }
2224        Op::FillCover(f) => {
2225            let mut body = serde_json::to_value(&f.spec).unwrap_or_else(|_| json!({}));
2226            body["in"] = Value::String(f.in_area.to_string());
2227            if let Some(m) = &f.motif {
2228                body["motif"] = Value::String(m.to_string());
2229            }
2230            ("tools_fill_cover", body)
2231        }
2232        Op::Module(m) => {
2233            let key = format!("module_{}", m.name);
2234            let mut body = serde_json::to_value(&m.roads).unwrap_or_else(|_| json!({}));
2235            if let Some(from) = &m.from {
2236                if let Some(obj) = body.as_object_mut() {
2237                    obj.insert("from".into(), Value::String(from.to_string()));
2238                }
2239            }
2240            return json!({ key: body });
2241        }
2242    };
2243    json!({ key: value })
2244}
2245
2246impl Target {
2247    fn to_json(&self) -> Value {
2248        match &self.module {
2249            Some(m) => Value::String(format!("{m}.{}", self.name.name)),
2250            None => Value::String(self.name.to_string()),
2251        }
2252    }
2253}
2254
2255impl Grammar {
2256    /// The graph as JSON: what a script built, for presets, `--dump-graph`
2257    /// and the page's worker. [`Grammar::from_json`] reads it back.
2258    pub fn to_json(&self) -> Value {
2259        use serde_json::json;
2260        let mut out = serde_json::Map::new();
2261        if let Some(t) = &self.title {
2262            out.insert("title".into(), Value::String(t.clone()));
2263        }
2264        out.insert("output".into(), serde_json::to_value(&self.output).unwrap_or(Value::Null));
2265        for (section, defs) in &self.sections {
2266            let body: serde_json::Map<String, Value> = defs
2267                .iter()
2268                .map(|d| {
2269                    let mut op = op_to_json(&d.op);
2270                    if let Some(at) = d.at {
2271                        op["at"] = json!(at);
2272                    }
2273                    (d.name.clone(), op)
2274                })
2275                .collect();
2276            out.insert(format!("${}", section.key()), Value::Object(body));
2277        }
2278        let draw: Vec<Value> = self
2279            .draw
2280            .iter()
2281            .map(|d| {
2282                let mut v = json!({ "from": d.from.to_json() });
2283                if let Some(id) = &d.id {
2284                    v["id"] = json!(id);
2285                }
2286                if let Some(s) = &d.stroke {
2287                    v["stroke"] = json!(s);
2288                }
2289                if let Some(at) = d.at {
2290                    v["at"] = json!(at);
2291                }
2292                v
2293            })
2294            .collect();
2295        out.insert("draw".into(), Value::Array(draw));
2296        if !self.paint.is_empty() {
2297            let paint: Vec<Value> = self
2298                .paint
2299                .iter()
2300                .map(|p| {
2301                    let mut v = json!({ "id": p.id, "from": p.from.to_json() });
2302                    v[p.look.key()] = p.look.to_json();
2303                    if !p.halo.is_none() {
2304                        v["halo"] = json!(p.halo);
2305                    }
2306                    if let Some(z) = p.shown.minzoom {
2307                        v["minzoom"] = json!(z);
2308                    }
2309                    if let Some(z) = p.shown.maxzoom {
2310                        v["maxzoom"] = json!(z);
2311                    }
2312                    if let Some((f, _)) = &p.shown.filter {
2313                        v["filter"] = f.clone();
2314                    }
2315                    if let Some(at) = p.at {
2316                        v["at"] = json!(at);
2317                    }
2318                    v
2319                })
2320                .collect();
2321            out.insert("paint".into(), Value::Array(paint));
2322        }
2323        let masks: serde_json::Map<String, Value> = self
2324            .compose
2325            .masks
2326            .iter()
2327            .map(|(name, m)| {
2328                let mut v = json!({
2329                    "from": m.from.to_json(),
2330                    "occludes": m.occludes.iter().map(|i| i.0.clone()).collect::<Vec<_>>(),
2331                });
2332                if let Some(at) = m.at {
2333                    v["at"] = json!(at);
2334                }
2335                (name.clone(), v)
2336            })
2337            .collect();
2338        let clip = match &self.compose.clip_default {
2339            Clip::Auto => json!("auto"),
2340            Clip::None => json!("none"),
2341            Clip::Areas(ns) => refs_json(ns),
2342        };
2343        let mut compose_obj = json!({
2344            "order": self.compose.order.iter().map(|i| i.0.clone()).collect::<Vec<_>>(),
2345            "masks": masks,
2346            "clip": { "default": clip },
2347        });
2348        if !self.compose.optimize.is_empty() {
2349            let opt: Vec<Value> = self
2350                .compose
2351                .optimize
2352                .iter()
2353                .map(|s| {
2354                    let raw = RawOptimizeStep {
2355                        layers: s.layers.iter().map(|i| i.0.clone()).collect(),
2356                        except: s.except.iter().map(|i| i.0.clone()).collect(),
2357                        op: s.op.clone(),
2358                        at: s.at,
2359                    };
2360                    serde_json::to_value(raw).unwrap()
2361                })
2362                .collect();
2363            compose_obj["optimize"] = Value::Array(opt);
2364        }
2365        out.insert("compose".into(), compose_obj);
2366        if !self.views.is_empty() {
2367            let views: Vec<Value> =
2368                self.views
2369                    .iter()
2370                    .map(|v| {
2371                        let mut o = json!({ "id": v.id, "at": [v.at.0, v.at.1], "graph": v.grammar.to_json() });
2372                        if let Some(ink) = &v.ink {
2373                            o["ink"] = json!(ink);
2374                        }
2375                        o
2376                    })
2377                    .collect();
2378            out.insert("views".into(), Value::Array(views));
2379        }
2380        Value::Object(out)
2381    }
2382
2383    pub fn from_json(text: &str) -> Result<Grammar, GrammarError> {
2384        let raw: Raw = serde_json::from_str(text).map_err(|e| GrammarError::Json(e.to_string()))?;
2385        build(raw)
2386    }
2387}
2388
2389// ---------------------------------------------------------------------------
2390// Validation
2391// ---------------------------------------------------------------------------
2392
2393fn validate_label_pick(g: &Grammar, def: &Def, pick: &LabelPick) -> Result<(), GrammarError> {
2394    let labels = g.find(&pick.of).ok_or_else(|| {
2395        GrammarError::Invalid(format!("{} reads {}, which is not defined", def.label(), pick.of))
2396    })?;
2397    if !matches!(&labels.op, Op::Labels(_)) {
2398        return Err(GrammarError::Invalid(format!("{} reads {}, which is not a labels def", def.label(), pick.of)));
2399    }
2400    if let Some(rule) = &pick.rule {
2401        let Op::Labels(l) = &labels.op else { unreachable!() };
2402        if !l.style.rule_ids().iter().any(|id| id == rule) {
2403            return Err(GrammarError::Invalid(format!(
2404                "{}: rule {:?} is not a labels.rules[].id on {}",
2405                def.label(),
2406                rule,
2407                pick.of
2408            )));
2409        }
2410    }
2411    Ok(())
2412}
2413
2414/// What each paint entry paints is defined and fits its look: an area is
2415/// filled, lines are lined, features are named. Ids are unique.
2416fn validate_paint(g: &Grammar) -> Result<(), GrammarError> {
2417    let mut ids = BTreeSet::new();
2418    for p in &g.paint {
2419        let fail = |m: String| GrammarError::Invalid(located(&format!("paint {:?}: {m}", p.id), p.at));
2420        if !ids.insert(p.id.as_str()) {
2421            return Err(fail("the id is painted twice".into()));
2422        }
2423        let kind = match &p.from.module {
2424            Some(m) => {
2425                if g.module(m).is_none() {
2426                    return Err(fail(format!("nothing calls module {m}")));
2427                }
2428                Section::Lines
2429            }
2430            None => {
2431                if g.find(&p.from.name).is_none() {
2432                    return Err(fail(format!("from {}: no such def", p.from.name)));
2433                }
2434                p.from.name.section
2435            }
2436        };
2437        let wants = match (p.look.key(), kind) {
2438            ("fill", Section::Areas) | ("line", Section::Lines) | ("text", Section::Features) => None,
2439            (_, Section::Fills) => Some("a fill's strokes are for paper: paint its area with a fill pattern instead".to_string()),
2440            ("fill", _) => Some(format!("fill paints an area, not ${kind}")),
2441            ("line", _) => Some(format!("line paints lines, not ${kind}")),
2442            _ => Some(format!("text names features, not ${kind}")),
2443        };
2444        // An area or lines are geometry made from features, their tags gone:
2445        // only names read them.
2446        if p.look.key() != "text" && p.look.reads().or(p.shown.reads()).feature {
2447            return Err(fail(format!(
2448                "{} reads a feature's tags ([\"get\", …]), which only names keep: split the features with features.where before they become {}",
2449                p.look.key(),
2450                if p.look.key() == "fill" { "an area" } else { "lines" }
2451            )));
2452        }
2453        if let Some(m) = wants {
2454            return Err(fail(m));
2455        }
2456    }
2457    if let Some(screen) = g.output.screen {
2458        let (own, other, medium) = match screen.kind {
2459            crate::paint::ScreenKind::Bitmap => ("px", "ch", "a bitmap counts pixels"),
2460            crate::paint::ScreenKind::Text => ("ch", "px", "a text screen counts characters"),
2461        };
2462        for p in &g.paint {
2463            if let Some(u) = p.look.units().iter().find(|u| **u != own) {
2464                let why = if *u == other { format!("{u} is the other screen's unit") } else { format!("{u} measures paper") };
2465                return Err(GrammarError::Invalid(located(&format!("paint {:?}: {why}; {medium}: write {own}, or a bare number", p.id), p.at)));
2466            }
2467        }
2468    }
2469    if !g.paint.is_empty() && g.output.screen.is_none() {
2470        return Err(GrammarError::Invalid("paint covers a screen: give the output one, output({ screen: { kind, width, height } })".into()));
2471    }
2472    Ok(())
2473}
2474
2475/// Every reference defined in the right section, draw ids unique, order and
2476/// masks naming draw ids, no loops.
2477pub fn validate(g: &Grammar) -> Result<(), GrammarError> {
2478    // Every reference must exist, in the right section.
2479    for def in g.all_defs() {
2480        for r in def.op.refs() {
2481            if g.find(&r).is_none() {
2482                return Err(GrammarError::Invalid(format!(
2483                    "{} refers to {r}, which is not defined under ${}",
2484                    def.label(),
2485                    r.section
2486                )));
2487            }
2488        }
2489        if let Op::LabelArea(pick) | Op::LabelLines(pick) = &def.op {
2490            validate_label_pick(g, def, pick)?;
2491        }
2492    }
2493    // A draw must point at line output: $lines, $fills, or a module output.
2494    for d in &g.draw {
2495        if d.from.module.is_some() {
2496            continue; // e.g. roads.outlines: the module owns the name
2497        }
2498        if !matches!(d.from.name.section, Section::Lines | Section::Fills) {
2499            return Err(GrammarError::Invalid(located(
2500                &format!("draw from {} needs $lines or $fills, not ${}", d.from.name, d.from.name.section),
2501                d.at,
2502            )));
2503        }
2504        if g.find(&d.from.name).is_none() {
2505            return Err(GrammarError::Invalid(format!("draw from {}: no such def", d.from.name)));
2506        }
2507    }
2508    validate_paint(g)?;
2509    let mut groups: BTreeSet<String> = BTreeSet::new();
2510    for d in &g.draw {
2511        if !groups.insert(d.group()) {
2512            return Err(GrammarError::Invalid(located(
2513                &format!("two draw entries write the same SVG group id {:?}", d.group()),
2514                d.at,
2515            )));
2516        }
2517    }
2518    // Order and occludes must name draw groups.
2519    for id in &g.compose.order {
2520        if !groups.contains(&id.0) {
2521            return Err(GrammarError::Invalid(format!("compose.order names {:?}, which is not a draw id", id.0)));
2522        }
2523    }
2524    for (name, mask) in &g.compose.masks {
2525        if mask.from.module.is_some() {
2526            // e.g. roads.area: an area published by a module.
2527        } else if mask.from.name.section != Section::Areas {
2528            return Err(GrammarError::Invalid(located(
2529                &format!("masks.{name}.from is {}, but a mask must be an area", mask.from.name),
2530                mask.at,
2531            )));
2532        } else if g.find(&mask.from.name).is_none() {
2533            return Err(GrammarError::Invalid(located(
2534                &format!("masks.{name}.from: no such def {}", mask.from.name),
2535                mask.at,
2536            )));
2537        }
2538        for id in &mask.occludes {
2539            if !groups.contains(&id.0) && !g.views.iter().any(|v| v.id == id.0) {
2540                return Err(GrammarError::Invalid(located(
2541                    &format!("masks.{name}.occludes names {:?}, which is not a draw id", id.0),
2542                    mask.at,
2543                )));
2544            }
2545        }
2546    }
2547    for (id, clip) in &g.compose.clip {
2548        if !groups.contains(&id.0) {
2549            return Err(GrammarError::Invalid(format!("compose.clip names {:?}, which is not a draw id", id.0)));
2550        }
2551        if let Clip::Areas(names) = clip {
2552            for n in names {
2553                if n.section != Section::Areas || g.find(n).is_none() {
2554                    return Err(GrammarError::Invalid(format!("compose.clip[{:?}]: {n} is not an area def", id.0)));
2555                }
2556            }
2557        }
2558    }
2559    for step in &g.compose.optimize {
2560        for id in &step.layers {
2561            if !groups.contains(&id.0) {
2562                return Err(GrammarError::Invalid(located(
2563                    &format!("compose.{} names {:?}, which is not a draw id", step.op.name(), id.0),
2564                    step.at,
2565                )));
2566            }
2567        }
2568        for id in &step.except {
2569            if !groups.contains(&id.0) {
2570                return Err(GrammarError::Invalid(located(
2571                    &format!("compose.{} except names {:?}, which is not a draw id", step.op.name(), id.0),
2572                    step.at,
2573                )));
2574            }
2575        }
2576    }
2577    // No loops across defs.
2578    if let Some(cycle) = find_cycle(g) {
2579        return Err(GrammarError::Invalid(format!("loop between defs: {}", cycle.join(" → "))));
2580    }
2581    Ok(())
2582}
2583
2584fn find_cycle(g: &Grammar) -> Option<Vec<String>> {
2585    #[derive(Clone, Copy, PartialEq)]
2586    enum Mark {
2587        Open,
2588        Done,
2589    }
2590    fn visit(
2591        g: &Grammar,
2592        name: &Name,
2593        marks: &mut BTreeMap<Name, Mark>,
2594        path: &mut Vec<Name>,
2595    ) -> Option<Vec<String>> {
2596        match marks.get(name) {
2597            Some(Mark::Done) => return None,
2598            Some(Mark::Open) => {
2599                let at = path.iter().position(|p| p == name).unwrap_or(0);
2600                let mut loop_names: Vec<String> = path[at..].iter().map(Name::to_string).collect();
2601                loop_names.push(name.to_string());
2602                return Some(loop_names);
2603            }
2604            None => {}
2605        }
2606        marks.insert(name.clone(), Mark::Open);
2607        path.push(name.clone());
2608        if let Some(def) = g.find(name) {
2609            for r in def.op.refs() {
2610                if let Some(cycle) = visit(g, &r, marks, path) {
2611                    return Some(cycle);
2612                }
2613            }
2614        }
2615        path.pop();
2616        marks.insert(name.clone(), Mark::Done);
2617        None
2618    }
2619
2620    let mut marks = BTreeMap::new();
2621    let mut path = Vec::new();
2622    for def in g.all_defs() {
2623        if !marks.contains_key(&def.reference()) {
2624            if let Some(cycle) = visit(g, &def.reference(), &mut marks, &mut path) {
2625                return Some(cycle);
2626            }
2627        }
2628    }
2629    None
2630}
2631
2632#[cfg(test)]
2633mod tests {
2634    use super::*;
2635
2636    /// The example profile, trimmed to the parts the grammar must accept.
2637    const YAML: &str = r#"
2638output: { width: 6in, height: 4in, scale: "1:10000" }
2639
2640$features:
2641  garden: { osm_select: { leisure: garden } }
2642  bldg:   { osm_select: { building: true } }
2643
2644$areas:
2645  garden:     { tools_polygons: $features.garden }
2646  parks:      { tools_union: [$areas.garden] }
2647  parks_ext:  { tools_fill_holes: $areas.parks }
2648  footprints: { tools_polygons: $features.bldg }
2649  dissolved:  { tools_union: [$areas.footprints] }
2650  inner_band: { tools_grow: { of: $areas.dissolved, by: -0.1mm } }
2651  wet:        { tools_union: [$areas.garden] }
2652
2653$lines:
2654  parks_edge: { tools_rings: { of: $areas.parks_ext, exterior_only: true } }
2655  bldg_lines: { tools_segments: $features.bldg }
2656  bldg_dedupe: { tools_dedupe: $lines.bldg_lines }
2657  walls:      { tools_clip: { lines: $lines.bldg_dedupe, within: $areas.inner_band } }
2658
2659$fills:
2660  hatch: { tools_fill: { in: $areas.footprints, per: feature, pattern: zigzag, spacing: 0.5mm, angle: 45 } }
2661
2662draw:
2663  - { id: parks_ring, from: $lines.parks_edge, stroke: { style: dash, dash: 0.45mm, gap: 0.40mm } }
2664  - { from: $fills.hatch }
2665  - { id: bldg_wall, from: $lines.walls, stroke: solid }
2666
2667compose:
2668  order: [parks_ring, fills_hatch, bldg_wall]
2669  masks:
2670    bldg_cover: { from: $areas.dissolved, occludes: [parks_ring] }
2671  clip:
2672    default: auto
2673"#;
2674
2675    /// The tests below write only the part under test; the output is boilerplate.
2676    fn parse(text: &str) -> Result<Grammar, GrammarError> {
2677        let body = if text.contains("output:") {
2678            text.to_string()
2679        } else {
2680            format!("output: {{ width: 100mm, height: 50mm }}\n{text}")
2681        };
2682        from_yaml(&body)
2683    }
2684
2685    #[test]
2686    fn parses_the_example_and_types_its_sections() {
2687        let g = parse(YAML).unwrap();
2688        assert_eq!(g.defs(Section::Features).len(), 2);
2689        assert_eq!(g.defs(Section::Areas).len(), 7);
2690        assert_eq!(g.defs(Section::Lines).len(), 4);
2691        assert_eq!(g.defs(Section::Fills).len(), 1);
2692        let dissolved = Name::parse("$areas.dissolved").unwrap();
2693        assert_eq!(g.find(&dissolved).unwrap().op.section(), Section::Areas);
2694    }
2695
2696    #[test]
2697    fn a_title_is_optional_and_kept_as_written() {
2698        assert_eq!(parse(YAML).unwrap().title, None);
2699        let g = parse(&format!("title: \"Parks: and buildings\"\n{YAML}")).unwrap();
2700        assert_eq!(g.title.as_deref(), Some("Parks: and buildings"));
2701    }
2702
2703    #[test]
2704    fn ids_fall_back_to_the_def_name() {
2705        let g = parse(YAML).unwrap();
2706        assert_eq!(g.groups(), vec!["parks_ring", "fills_hatch", "bldg_wall"]);
2707    }
2708
2709    #[test]
2710    fn a_reference_must_exist_and_carry_its_section() {
2711        let bad = "$areas:\n  a: { tools_polygons: $features.nope }\n";
2712        assert!(matches!(parse(bad), Err(GrammarError::Invalid(m)) if m.contains("$features.nope")));
2713        let bad = "$areas:\n  a: { tools_polygons: $lines.nope }\n";
2714        assert!(matches!(parse(bad), Err(GrammarError::Invalid(m)) if m.contains("$lines.nope")));
2715    }
2716
2717    #[test]
2718    fn an_operation_must_match_its_section() {
2719        // tools_rings makes lines; under $areas it is an error.
2720        let bad = "$areas:\n  a: { tools_rings: $areas.b }\n";
2721        assert!(matches!(
2722            parse(bad),
2723            Err(GrammarError::Invalid(m)) if m.contains("lines") && m.contains("areas")
2724        ));
2725    }
2726
2727    #[test]
2728    fn draw_needs_line_output_and_masks_need_areas() {
2729        let base = "$features:\n  f: { osm_select: { building: true } }\n\
2730                    $areas:\n  a: { tools_polygons: $features.f }\n\
2731                    $lines:\n  l: { tools_rings: $areas.a }\n";
2732        // draw from an area: refused
2733        assert!(parse(&format!("{base}draw:\n  - {{ from: $areas.a }}\n")).is_err());
2734        // mask from a line set: refused
2735        let text = format!("{base}draw:\n  - {{ from: $lines.l }}\ncompose:\n  masks:\n    m: {{ from: $lines.l }}\n");
2736        assert!(matches!(parse(&text), Err(GrammarError::Invalid(m)) if m.contains("must be an area")));
2737    }
2738
2739    #[test]
2740    fn a_screen_is_painted_by_what_each_entry_paints() {
2741        let screen = "output: { screen: { kind: text, width: 80, height: 24 } }\n";
2742        let base = format!(
2743            "{screen}$features:\n  f: {{ osm_select: {{ building: true }} }}\n\
2744             $areas:\n  a: {{ tools_polygons: $features.f }}\n\
2745             $lines:\n  l: {{ tools_rings: $areas.a }}\n"
2746        );
2747        let g = parse(&format!(
2748            "{base}paint:\n  - {{ id: blocks, from: $areas.a, fill: {{ chars: [\"~ \", \" ~\"], color: \"#36c\" }} }}\n\
2749             \x20 - {{ id: walls, from: $lines.l, line: {{ style: box }}, halo: [1, 0] }}\n\
2750             \x20 - {{ id: names, from: $features.f, text: {{ marker: \"*\" }} }}\n"
2751        ))
2752        .unwrap();
2753        // The screen's size is counted in characters, a row two of them tall.
2754        assert_eq!((g.output.width.0, g.output.height.0), (80.0, 48.0));
2755        assert_eq!(g.paint.len(), 3);
2756        assert_eq!(g.paint[1].halo, crate::paint::Halo(1, 0));
2757        // Back through JSON, the same graph.
2758        let again = Grammar::from_json(&g.to_json().to_string()).unwrap();
2759        assert_eq!(again.paint, g.paint);
2760        assert_eq!(again.output, g.output);
2761        // An area is filled, not lined; a pattern must be one there is.
2762        let wrong = parse(&format!("{base}paint:\n  - {{ id: x, from: $areas.a, line: {{}} }}\n"));
2763        assert!(matches!(&wrong, Err(GrammarError::Invalid(m)) if m.contains("line paints lines")), "{wrong:?}");
2764        let unknown = parse(&format!("{base}paint:\n  - {{ id: x, from: $areas.a, fill: {{ pattern: plaid }} }}\n"));
2765        assert!(matches!(unknown, Err(GrammarError::Invalid(m)) if m.contains("plaid")));
2766        // Paper has no paint.
2767        let paper = parse("$areas:\n  a: { engine_frame: {} }\npaint:\n  - { id: x, from: $areas.a, fill: { pattern: solid } }\n");
2768        assert!(matches!(paper, Err(GrammarError::Invalid(m)) if m.contains("give the output one")));
2769    }
2770
2771    #[test]
2772    fn loops_and_unknown_operations_are_load_errors() {
2773        let looped = "$areas:\n  a: { tools_union: [$areas.b] }\n  b: { tools_grow: { of: $areas.a, by: 1mm } }\n";
2774        assert!(matches!(parse(looped), Err(GrammarError::Invalid(m)) if m.contains("loop")));
2775        let unknown = "$areas:\n  a: { tools_bogus: 1 }\n";
2776        assert!(matches!(parse(unknown), Err(GrammarError::Invalid(m)) if m.contains("unknown operation")));
2777    }
2778
2779    #[test]
2780    fn one_operation_per_def() {
2781        let two = "$areas:\n  a: { tools_polygons: $areas.b, engine_frame: {} }\n  b: { engine_frame: {} }\n";
2782        assert!(matches!(parse(two), Err(GrammarError::Json(m)) if m.contains("exactly one operation")));
2783    }
2784
2785    #[test]
2786    fn modules_are_recorded_and_bad_references_named() {
2787        let module = "$lines:\n  roads: { module_roads: {} }\n";
2788        let g = parse(module).unwrap();
2789        assert_eq!(
2790            g.defs(Section::Lines)[0].op,
2791            Op::Module(Module { name: "roads".into(), from: None, roads: Default::default() })
2792        );
2793        let bad_ref = "$areas:\n  a: { tools_union: [dense] }\n";
2794        assert!(matches!(parse(bad_ref), Err(GrammarError::Invalid(m)) if m.contains("\"dense\" is not a $section.name reference")));
2795        let bad_len = "$fills:\n  f: { tools_fill: { in: $areas.a, spacing: dense } }\n$areas:\n  a: { engine_frame: {} }\n";
2796        assert!(parse(bad_len).is_err());
2797    }
2798
2799    #[test]
2800    fn tile_selections_and_modules_reading_them() {
2801        let text = "$features:\n  bldg: { tiles_select: buildings }\n  ways: { tiles_select: [roads, \"paths\"] }\n  sea: { tiles_select: ocean }\n\
2802                    $areas:\n  roads: { module_roads: { from: $features.ways } }\n";
2803        let g = parse(text).unwrap();
2804        assert_eq!(g.tile_selectors(), ["buildings", "roads", "paths", "ocean"]);
2805        assert!(g.osm_keys().is_empty(), "nothing reads Overpass");
2806        assert!(g.draws_ocean());
2807        assert_eq!(g.find(&Name::parse("$areas.roads").unwrap()).unwrap().op.refs(), [Name::parse("$features.ways").unwrap()]);
2808        let osm = parse("$areas:\n  roads: { module_roads: {} }\n").unwrap();
2809        assert!(osm.osm_keys().contains(&"highway".to_string()) && osm.tile_selectors().is_empty());
2810        assert!(matches!(parse("$features:\n  a: { tiles_select: forrest }\n"), Err(GrammarError::Invalid(m)) if m.contains("preset")));
2811        assert!(parse("$areas:\n  r: { module_roads: { from: $areas.r } }\n").is_err());
2812        assert!(parse("$areas:\n  r: { module_roads: { form: $features.x } }\n").is_err());
2813    }
2814
2815    #[test]
2816    fn duplicate_names_and_extra_keys_are_refused() {
2817        let dup = r#"{ "output": {}, "$areas": { "a": { "engine_frame": {} }, "a": { "engine_frame": {} } } }"#;
2818        assert!(matches!(Grammar::from_json(dup), Err(GrammarError::Invalid(m)) if m.contains("defined twice")));
2819        let extra = "$areas:\n  a: { engine_frame: {}, note: hi }\n";
2820        assert!(parse(extra).is_err());
2821    }
2822
2823    #[test]
2824    fn the_graph_round_trips_through_json() {
2825        let g = parse(YAML).unwrap();
2826        let json = g.to_json().to_string();
2827        let back = Grammar::from_json(&json).unwrap();
2828        assert_eq!(back, g);
2829        assert_eq!(back.to_json().to_string(), json);
2830    }
2831
2832    #[test]
2833    fn script_positions_ride_along_and_label_errors() {
2834        let mut g = parse(YAML).unwrap();
2835        g.sections[1].1[0].at = Some(At(12, 5));
2836        let back = Grammar::from_json(&g.to_json().to_string()).unwrap();
2837        assert_eq!(back.sections[1].1[0].at, Some(At(12, 5)));
2838        assert_eq!(back.sections[1].1[0].label(), "$areas.garden (line 12 column 5)");
2839        let mut bad = g.to_json();
2840        bad["$areas"]["garden"]["tools_polygons"] = Value::String("$features.nope".into());
2841        let err = Grammar::from_json(&bad.to_string()).unwrap_err().to_string();
2842        assert!(err.contains("line 12 column 5"), "{err}");
2843    }
2844
2845    #[test]
2846    fn label_area_accepts_a_rule_bucket_object() {
2847        let text = r#"{
2848          "output": { "width": "100mm", "height": "50mm" },
2849          "$features": { "p": { "tiles_select": ["parks"] } },
2850          "$lines": { "names": { "tools_labels": { "from": ["$features.p"], "rules": [{ "id": "park", "tags": { "class": "park" } }] } } },
2851          "$areas": { "park": { "tools_label_area": { "of": "$lines.names", "rule": "park" } } }
2852        }"#;
2853        let g = Grammar::from_json(text).unwrap();
2854        let def = g.defs(Section::Areas).iter().find(|d| d.name == "park").unwrap();
2855        let Op::LabelArea(pick) = &def.op else { panic!("label area") };
2856        assert_eq!(pick.rule.as_deref(), Some("park"));
2857    }
2858}